text
stringlengths
437
491k
meta
dict
with OpenGL.Thin; package body OpenGL.View is -- -- Viewport specification. -- procedure Depth_Range (Near : in OpenGL.Types.Clamped_Double_t; Far : in OpenGL.Types.Clamped_Double_t) is begin Thin.Depth_Range (Near_Value => Thin.Double_t (Near), Far_Value => Thin.Double_t (Far)); end Depth_Range; procedure Viewport (Left : in Natural; Bottom : in Natural; Width : in Positive; Height : in Positive) is begin Thin.Viewport (X => Thin.Integer_t (Left), Y => Thin.Integer_t (Bottom), Width => Thin.Size_t (Width), Height => Thin.Size_t (Height)); end Viewport; end OpenGL.View;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This file provides definitions for the STM32F4 (ARM Cortex M4F -- from ST Microelectronics) Serial Peripheral Interface (SPI) facility. package STM32F4.SPI is type SPI_Port is limited private; type SPI_Data_Direction is (D2Lines_FullDuplex, D2Lines_RxOnly, D1Line_Rx, D1Line_Tx); type SPI_Data_Size is (Data_16, Data_8); type SPI_Mode is (Master, Slave); type SPI_CLock_Polarity is (High, Low); type SPI_CLock_Phase is (P1Edge, P2Edge); type SPI_Slave_Management is (Soft, Hard); type SPI_Baud_Rate_Prescaler is (BRP_2, BRP_4, BRP_8, BRP_16, BRP_32, BRP_64, BRP_128, BRP_256); type SPI_First_Bit is (MSB, LSB); type SPI_Configuration is record Direction : SPI_Data_Direction; Mode : SPI_Mode; Data_Size : SPI_Data_Size; Clock_Polarity : SPI_Clock_Polarity; Clock_Phase : SPI_Clock_Phase; Slave_Management : SPI_Slave_Management; Baud_Rate_Prescaler : SPI_Baud_Rate_Prescaler; First_Bit : SPI_First_Bit; CRC_Poly : Half_Word; end record; procedure Configure (Port : in out SPI_Port; Conf : SPI_Configuration); procedure Enable (Port : in out SPI_Port); procedure Disable (Port : in out SPI_Port); function Enabled (Port : SPI_Port) return Boolean; procedure Send (Port : in out SPI_Port; Data : Half_Word); function Data (Port : SPI_Port) return Half_Word with Inline; procedure Send (Port : in out SPI_Port; Data : Byte); function Data (Port : SPI_Port) return Byte with Inline; function Rx_Is_Empty (Port : SPI_Port) return Boolean with Inline; function Tx_Is_Empty (Port : SPI_Port) return Boolean with Inline; function Busy (Port : SPI_Port) return Boolean with Inline; function Channel_Side_Indicated (Port : SPI_Port) return Boolean with Inline; function Underrun_Indicated (Port : SPI_Port) return Boolean with Inline; function CRC_Error_Indicated (Port : SPI_Port) return Boolean with Inline; function Mode_Fault_Indicated (Port : SPI_Port) return Boolean with Inline; function Overrun_Indicated (Port : SPI_Port) return Boolean with Inline; function Frame_Fmt_Error_Indicated (Port : SPI_Port) return Boolean with Inline; private type SPI_Control_Register is record Clock_Phase : Bits_1; Clock_Polarity : Bits_1; Master_Select : Bits_1; Baud_Rate_Ctrl : Bits_3; SPI_Enable : Bits_1; LSB_First : Bits_1; -- Frame Format Slave_Select : Bits_1; Soft_Slave_Mgt : Bits_1; -- Software Slave Management RXOnly : Bits_1; Data_Frame_Fmt : Bits_1; -- 1=16-bit 0=8-bit CRC_Next : Bits_1; -- 1=CRC Phase 0=No CRC Phase CRC_Enable : Bits_1; Output_BiDir : Bits_1; -- Output enable in bidirectional mode BiDir_Mode : Bits_1; -- Bidirectional data mode enable end record with Pack, Volatile, Size => 16; type SPI_Control_Register2 is record RX_DMA_Enable : Bits_1; TX_DMA_Enable : Bits_1; SS_Out_Enable : Bits_1; Reserved_1 : Bits_1; Frame_Fmt : Bits_1; -- 0=Motorola Mode 1=TI Mode Err_Int_Enable : Bits_1; RX_Not_Empty_Int_Enable : Bits_1; TX_Empty_Int_Enable : Bits_1; Reserved_2 : Bits_8; end record with Pack, Volatile, Size => 16; type SPI_I2S_Config_Register is record Channel_Length : Bits_1; Data_Length : Bits_2; Clock_Polarity : Bits_1; I2S_Standard : Bits_2; -- 00==Philips 01=MSB (L) 10=LSB (R) 11=PCM Reserved_1 : Bits_1; PCM_Frame_Sync : Bits_1; -- 0=Short 1=Long Config_Mode : Bits_2; -- 00=SlaveTX 01=SlaveRX 10=MasterTX11=MasterRX Enable : Bits_1; Mode_Select : Bits_1; -- 0=SPI Mode 1=I2S Mode Reserved_2 : Bits_4; end record with Pack, Volatile, Size => 16; type SPI_I2S_Prescale_Register is record Linear_Prescler : Bits_8; Odd_Factor : Bits_1; Master_CLK_Out_Enable : Bits_1; Reserved : Bits_6; end record with Pack, Volatile, Size => 16; type SPI_Status_Register is record RX_Buffer_Not_Empty : Boolean; TX_Buffer_Empty : Boolean; Channel_Side : Boolean; Underrun_Flag : Boolean; CRC_Error_Flag : Boolean; Mode_Fault : Boolean; Overrun_Flag : Boolean; Busy_Flag : Boolean; Frame_Fmt_Error : Boolean; Reserved : Bits_7; end record with Pack, Volatile, Size => 16; type SPI_Port is record CTRL1 : SPI_Control_Register; Reserved_1 : Half_Word; CTRL2 : SPI_Control_Register2; Reserved_2 : Half_Word; Status : SPI_Status_Register; Reserved_3 : Half_Word; Data : Half_Word; Reserved_4 : Half_Word; CRC_Poly : Half_Word; -- Default = 16#0007# Reserved_5 : Half_Word; RX_CRC : Half_Word; Reserved_6 : Half_Word; TX_CRC : Half_Word; Reserved_7 : Half_Word; I2S_Conf : SPI_I2S_Config_Register; Reserved_8 : Half_Word; I2S_PreScal : SPI_I2S_Prescale_Register; Reserved_9 : Half_Word; end record with Pack, Volatile, Size => 9 * 32; end STM32F4.SPI;
{ "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.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Maps.Constants; -- NIGET TOM PEIP2-B2 -- IMPORTANT ! -- Si vous utilisez GNAT ou une vieille version d'Ada pas aux normes, -- décommentez la ligne ci-dessous et commentez celle juste après --with Ada.Strings.Unbounded_Text_IO; use Ada.Strings.Unbounded_Text_IO; with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; procedure tp3_niget is type T_Couleur_Vin is (Rouge, Blanc, Rose); -- pour l'affichage Couleur_Vin_Aff : array (T_Couleur_Vin) of Unbounded_String := ( To_Unbounded_String("rouge"), To_Unbounded_String("blanc"), To_Unbounded_String("rosé") ); type T_Région is ( Alsace, Beaujolais, Bordeaux, Bourgogne, Chablis, Champagne, Corse, Jura, Languedoc_Roussillon, Loire, Provence, Rhone, Savoie, Sud_Ouest ); -- pour l'affichage Région_Aff : array (T_Région) of Unbounded_String := ( To_Unbounded_String("Alsace"), To_Unbounded_String("Beaujolais"), To_Unbounded_String("Bordeaux"), To_Unbounded_String("Bourgogne"), To_Unbounded_String("Chablis"), To_Unbounded_String("Champagne"), To_Unbounded_String("Corse"), To_Unbounded_String("Jura"), To_Unbounded_String("Languedoc-Roussillon"), To_Unbounded_String("Loire"), To_Unbounded_String("Provence"), To_Unbounded_String("Rhône"), To_Unbounded_String("Savoie"), To_Unbounded_String("Sud-Ouest") ); type T_Vin is record Nom : Unbounded_String; Région : T_Région; Couleur : T_Couleur_Vin; Millésime : Integer; Quantité : Natural; end record; TAILLE_CAVE : constant Positive := 40; Cave : array (1..TAILLE_CAVE) of T_Vin; subtype Pos_Vin is Integer range Cave'Range; -- nombre de cases occupées de Cave Cave_NB : Natural range 0..TAILLE_CAVE := 0; -- pose une question fermée function Choix(Msg : Unbounded_String) return Boolean is Rep : Character; begin Put(Msg & " [O/N] "); Get(Rep); return Rep = 'O' or Rep = 'o'; end Choix; -- a < b : -1 -- a = b : 0 -- a > b : 1 subtype Comparaison is Integer range -1..1; -- compare deux chaînes sans se préoccuper de la casse function Compare_Chaines(A, B : Unbounded_String) return Comparaison is X : Unbounded_String := A; Y : Unbounded_String := B; begin -- passage en minuscule pour mettre X et Y sur un pied d'égalité -- pour éviter les 'z' > 'A' et autres loufoqueries des comparateurs d'Ada Ada.Strings.Unbounded.Translate(X, Ada.Strings.Maps.Constants.Lower_Case_Map); Ada.Strings.Unbounded.Translate(Y, Ada.Strings.Maps.Constants.Lower_Case_Map); if X > Y then return 1; elsif X < Y then return -1; else return 0; end if; end Compare_Chaines; -- détermine l'emplacement où insérer un nouveau vin -- par recherche dichotomique function Indice_Correct(Q : Unbounded_String) return Pos_Vin is -- bornes A : Pos_Vin := 1; B : Pos_Vin; -- milieu de l'intervalle Mid : Pos_Vin; -- valeur à comparer Val : Unbounded_String; -- résultat de comparaison Comp : Comparaison; begin -- si la cave est vide, on insère au début if Cave_NB = 0 then return 1; else B := Cave_NB; end if; while A < B loop Mid := (A + B) / 2; Val := Cave(Mid).Nom; Comp := Compare_Chaines(Q, Val); if Comp = 0 then return Mid + 1; -- +1 pour ajouter à la fin d'une suite d'éléments équivalents et non au début elsif Comp = -1 then B := Mid; elsif Comp = 1 then if A = Mid then return B + 1; end if; A := Mid; end if; end loop; return B; end Indice_Correct; -- vérifie si la cave est vide, affiche une erreur le cas échéant function Verif_Vide return Boolean is begin if Cave_NB = 0 then Put_Line("*** La cave est vide ! ***"); return True; end if; return False; end Verif_Vide; -- affiche les caractéristiques d'un vin procedure Aff_Vin(Vin : T_Vin) is begin Put_Line(Vin.Nom & " - vin " & Couleur_Vin_Aff(Vin.Couleur) & " d'origine " & Région_Aff(Vin.Région) & ", millésime" & Integer'Image(Vin.Millésime) & ", stock :" & Integer'Image(Vin.Quantité)); end Aff_Vin; -- liste les vins procedure A_Liste_Vins is begin if Verif_Vide then return; end if; Put_Line("Il y a" & Integer'Image(Cave_NB) & " vins :"); for i in 1..Cave_NB loop Put(Integer'Image(i) & "- "); Aff_Vin(Cave(i)); end loop; end A_Liste_Vins; -- demande à l'utilisateur de choisir un vin function Choisir_Vin return Pos_Vin is N_Vin : Integer; begin A_Liste_Vins; loop Put_Line("Veuillez saisir le numéro du vin."); Put("> "); Get(N_Vin); exit when N_Vin in 1..Cave_NB; Put_Line("*** Numéro de vin incorrect ! ***"); end loop; return N_Vin; end Choisir_Vin; -- insère un vin à la position spécifiée -- pour cela, décale vers la droite celles qui sont dans le chemin procedure Insérer_Vin(Vin : T_Vin; Pos : Pos_Vin) is begin for i in reverse Pos..Cave_NB loop Cave(i + 1) := Cave(i); end loop; Cave(Pos) := Vin; Cave_NB := Cave_NB + 1; end Insérer_Vin; -- supprime le vin à la position spécifiée procedure A_Suppr_Vin(N : Integer := -1) is N_Vin : Pos_Vin; begin if N not in Pos_Vin'Range then N_Vin := Choisir_Vin; else N_Vin := N; end if; if not Choix(To_Unbounded_String("*** Cette action est irréversible ! Êtes-vous sûr(e) ? ***")) then return; end if; Put_Line("*** Suppression de " & Cave(N_Vin).Nom & " ***"); for i in N_Vin..Cave_NB loop Cave(i) := Cave(i + 1); end loop; Cave_NB := Cave_NB - 1; end A_Suppr_Vin; procedure A_Ajout_Bouteille(N : Integer := -1) is N_Vin : Pos_Vin; Quant : Positive; begin if Verif_Vide then return; end if; if N not in Pos_Vin'Range then N_Vin := Choisir_Vin; else N_Vin := N; end if; Put("Nombre de bouteilles à ajouter au stock : "); Get(Quant); Cave(N_Vin).Quantité := Cave(N_Vin).Quantité + Quant; end A_Ajout_Bouteille; -- lit et ajoute un ou plusieurs vins procedure A_Ajout_Vin is Vin : T_Vin; Ent : Integer; Existe : Boolean := False; begin loop if Cave_NB = TAILLE_CAVE then Put_Line("*** La cave est pleine ! ***"); exit; end if; -- efface le buffer d'entrée pour éviter de -- relire le retour chariot précédemment entré -- lors du choix de l'opération Skip_Line; Put_Line("Veuillez saisir les informations du vin."); Put("Nom : "); Vin.Nom := Get_Line; Existe := False; for i in Cave'Range loop if Compare_Chaines(Cave(i).Nom, Vin.Nom) = 0 then Put_Line("*** Le vin est déjà présent dans la base, entrée en mode ajout de bouteille ***"); A_Ajout_Bouteille(i); Existe := True; end if; end loop; if not Existe then for r in T_Région'Range loop Put_Line(Integer'Image(T_Région'Pos(r) + 1) & "- " & Région_Aff(r)); end loop; loop Put("Région : "); Get(Ent); exit when Ent in 1..(T_Région'Pos(T_Région'Last) + 1); Put_Line("*** Numéro de région incorrect ! ***"); end loop; Vin.Région := T_Région'Val(Ent - 1); for r in T_Couleur_Vin'Range loop Put_Line(Integer'Image(T_Couleur_Vin'Pos(r) + 1) & "- " & Couleur_Vin_Aff(r)); end loop; loop Put("Couleur : "); Get(Ent); exit when Ent in 1..(T_Couleur_Vin'Pos(T_Couleur_Vin'Last) + 1); Put_Line("*** Numéro de couleur incorrect ! ***"); end loop; Vin.Couleur := T_Couleur_Vin'Val(Ent - 1); Put("Millésime : "); Get(Vin.Millésime); Put("Quantité : "); Get(Vin.Quantité); Insérer_Vin(Vin, Indice_Correct(Vin.Nom)); end if; exit when not Choix(To_Unbounded_String("Voulez-vous ajouter un autre vin ?")); end loop; end A_Ajout_Vin; -- lit et sort une ou plusieures bouteilles procedure A_Sortir_Bouteille is N_Vin : Integer; N_Quant : Integer; begin loop if Verif_Vide then return; end if; N_Vin := Choisir_Vin; loop Put_Line("Combien de bouteilles voulez-vous sortir ?"); Put("> "); Get(N_Quant); exit when N_Quant in 1..Cave(N_Vin).Quantité; Put_Line("*** La quantité doit être entre 1 et " & Integer'Image(Cave(N_Vin).Quantité) & " ! ***"); end loop; Cave(N_Vin).Quantité := Cave(N_Vin).Quantité - N_Quant; if Cave(N_Vin).Quantité = 0 then Put_Line("*** Le vin est en rupture de stock ***"); if Choix(To_Unbounded_String("*** Voulez-vous le supprimer de la base ? ***")) then A_Suppr_Vin(N_Vin); end if; end if; A_Liste_Vins; exit when not Choix(To_Unbounded_String("Voulez-vous sortir une autre bouteille ?")); end loop; end A_Sortir_Bouteille; Action : Character; begin -- mettre à True pour charger des données d'exemple -- pour ne pas avoir à tout saisir à la main if True then Cave := ( (To_Unbounded_String("Beaujolais AOC"),Beaujolais,Rouge,2000,7), (To_Unbounded_String("Chablis AOC"),Bourgogne,Blanc,2017,11), (To_Unbounded_String("Côtes de Provence"),Provence,Rose,1999,11), (To_Unbounded_String("Saint-Emilion"),Bordeaux,Rouge,2003,3), others => <> ); Cave_NB := 4; end if; loop -- affichage du menu Put_Line("Choisissez une opération à effectuer :"); Put_Line(" 1- Ajouter un vin"); Put_Line(" 2- Supprimer un vin"); Put_Line(" 3- Ajouter une bouteille"); Put_Line(" 4- Sortir une bouteille"); Put_Line(" 5- Afficher la liste des vins"); Put_Line(" 6- Quitter"); Put("> "); Get(Action); New_Line; case Action is when '1' => A_Ajout_Vin; when '2' => A_Suppr_Vin; when '3' => A_Ajout_Bouteille; when '4' => A_Sortir_Bouteille; when '5' => A_Liste_Vins; when '6' => exit; when others => Put_Line("*** Numéro d'opération incorrect ! ***"); end case; New_Line; end loop; end tp3_niget;
{ "source": "starcoderdata", "programming_language": "ada" }
with Interfaces; use Interfaces; with HIL; -- @summary -- read/write from/to a non-volatile location. Every "variable" -- has one byte. When the compilation date/time changed, all -- variables are reset to their respective defaults. Otherwise -- NVRAM keeps values across reboot/loss of power. package NVRAM with SPARK_Mode, Abstract_State => Memory_State is procedure Init; -- initialize this module and possibly underlying hardware procedure Self_Check (Status : out Boolean); -- check whether initialization was successful -- List of all variables stored in NVRAM. Add new ones when needed. type Variable_Name is (VAR_MISSIONSTATE, VAR_BOOTCOUNTER, VAR_EXCEPTION_LINE_L, VAR_EXCEPTION_LINE_H, VAR_START_TIME_A, VAR_START_TIME_B, VAR_START_TIME_C, VAR_START_TIME_D, VAR_HOME_HEIGHT_L, VAR_HOME_HEIGHT_H, VAR_GPS_TARGET_LONG_A, VAR_GPS_TARGET_LONG_B, VAR_GPS_TARGET_LONG_C, VAR_GPS_TARGET_LONG_D, VAR_GPS_TARGET_LAT_A, VAR_GPS_TARGET_LAT_B, VAR_GPS_TARGET_LAT_C, VAR_GPS_TARGET_LAT_D, VAR_GPS_TARGET_ALT_A, VAR_GPS_TARGET_ALT_B, VAR_GPS_TARGET_ALT_C, VAR_GPS_TARGET_ALT_D, VAR_GPS_LAST_LONG_A, VAR_GPS_LAST_LONG_B, VAR_GPS_LAST_LONG_C, VAR_GPS_LAST_LONG_D, VAR_GPS_LAST_LAT_A, VAR_GPS_LAST_LAT_B, VAR_GPS_LAST_LAT_C, VAR_GPS_LAST_LAT_D, VAR_GPS_LAST_ALT_A, VAR_GPS_LAST_ALT_B, VAR_GPS_LAST_ALT_C, VAR_GPS_LAST_ALT_D, VAR_GYRO_BIAS_X, VAR_GYRO_BIAS_Y, VAR_GYRO_BIAS_Z ); -- Default values for all variables (obligatory) type Defaults_Table is array (Variable_Name'Range) of HIL.Byte; Variable_Defaults : constant Defaults_Table := (VAR_MISSIONSTATE => 0, VAR_BOOTCOUNTER => 0, VAR_EXCEPTION_LINE_L => 0, VAR_EXCEPTION_LINE_H => 0, VAR_START_TIME_A => 0, VAR_START_TIME_B => 0, VAR_START_TIME_C => 0, VAR_START_TIME_D => 0, VAR_HOME_HEIGHT_L => 0, VAR_HOME_HEIGHT_H => 0, VAR_GPS_TARGET_LONG_A => 0, VAR_GPS_TARGET_LONG_B => 0, VAR_GPS_TARGET_LONG_C => 0, VAR_GPS_TARGET_LONG_D => 0, VAR_GPS_TARGET_LAT_A => 0, VAR_GPS_TARGET_LAT_B => 0, VAR_GPS_TARGET_LAT_C => 0, VAR_GPS_TARGET_LAT_D => 0, VAR_GPS_TARGET_ALT_A => 0, VAR_GPS_TARGET_ALT_B => 0, VAR_GPS_TARGET_ALT_C => 0, VAR_GPS_TARGET_ALT_D => 0, VAR_GPS_LAST_LONG_A => 0, VAR_GPS_LAST_LONG_B => 0, VAR_GPS_LAST_LONG_C => 0, VAR_GPS_LAST_LONG_D => 0, VAR_GPS_LAST_LAT_A => 0, VAR_GPS_LAST_LAT_B => 0, VAR_GPS_LAST_LAT_C => 0, VAR_GPS_LAST_LAT_D => 0, VAR_GPS_LAST_ALT_A => 0, VAR_GPS_LAST_ALT_B => 0, VAR_GPS_LAST_ALT_C => 0, VAR_GPS_LAST_ALT_D => 0, VAR_GYRO_BIAS_X => 20, -- Bias in deci degree VAR_GYRO_BIAS_Y => 26, VAR_GYRO_BIAS_Z => 128-3+128 -- most evil hack ever ); procedure Load (variable : in Variable_Name; data : out HIL.Byte); -- read variable with given name from NVRAM and return value procedure Load (variable : in Variable_Name; data : out Float) with Pre => Variable_Name'Pos (variable) < Variable_Name'Pos (Variable_Name'Last) - 3; -- same, but with Float convenience conversion. Point to first variable of the quadrupel. procedure Store (variable : in Variable_Name; data : in HIL.Byte); -- write variable with given name to NVRAM. procedure Store (variable : in Variable_Name; data : in Float) with Pre => Variable_Name'Pos (variable) < Variable_Name'Pos (Variable_Name'Last) - 3; -- same, but with Float convenience conversion. Point to first variable of the quadrupel. procedure Reset; -- explicit reset of NVRAM to defaults; same effect as re-compiling. end NVRAM;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Exceptions; with Ada.Strings.Equal_Case_Insensitive; with Ada.Text_IO; with Extraction.Bodies_For_Decls; with Extraction.Bodies_For_Entries; with Extraction.Decls; with Extraction.Deferred_Constants; with Extraction.Derived_Type_Defs; with Extraction.Direct_Calls; with Extraction.File_System; with Extraction.Generic_Instantiations; with Extraction.Graph_Operations; with Extraction.Node_Edge_Types; with Extraction.Primitive_Subps; with Extraction.Project_Files; with Extraction.References_Of_Decls; with Extraction.Renamings; with Extraction.Source_Files_From_Projects; with Extraction.Subp_Overrides; with Extraction.Decl_Types; with Extraction.Utilities; with Extraction.With_Clauses; package body Extraction is -- TODO: Improve node naming such that line numbers are not needed -- TODO: Relate arguments in generic instantiations with formal parameters -- of generics use type VFS.Filesystem_String; use type VFS.Virtual_File; function Node_Attributes return GW.Attribute_Definition_Sets.Map renames Node_Edge_Types.Node_Attributes; function Edge_Attributes return GW.Attribute_Definition_Sets.Map renames Node_Edge_Types.Edge_Attributes; procedure Extract_Dependency_Graph (Project_Filename : String; Recurse_Projects : Boolean; Directory_Prefix : VFS.Virtual_File; Graph_File : in out GW.GraphML_File) is Context : constant Utilities.Project_Context := Utilities.Open_Project (Project_Filename); Projects : constant Utilities.Project_Vectors.Vector := Utilities.Get_Projects (Context, Recurse_Projects); Units : constant Utilities.Analysis_Unit_Vectors.Vector := Utilities.Open_Analysis_Units (Context, Recurse_Projects); Graph : constant Graph_Operations.Graph_Context := Graph_Operations.Create_Graph_Context (Graph_File'Unchecked_Access, Directory_Prefix, Context); procedure Handle_Exception (E : Ada.Exceptions.Exception_Occurrence; Node : LAL.Ada_Node'Class); procedure Handle_Exception (E : Ada.Exceptions.Exception_Occurrence; Node : LAL.Ada_Node'Class) is Message : constant String := Ada.Exceptions.Exception_Message (E); begin if not Ada.Strings.Equal_Case_Insensitive (Message, "memoized error") then Ada.Text_IO.Put_Line ("Encountered Libadalang problem: " & Message); Node.Print; end if; end Handle_Exception; function Node_Visitor (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status; function Node_Visitor (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status is begin -- TODO: Remove exception block once all libadalang problems -- have been fixed. begin Decls.Extract_Nodes (Node, Graph); Subp_Overrides.Extract_Nodes (Node, Graph); Primitive_Subps.Extract_Nodes (Node, Graph); References_Of_Decls.Extract_Nodes (Node, Graph); exception when E : LALCO.Property_Error => Handle_Exception (E, Node); end; return LALCO.Into; end Node_Visitor; function Edge_Visitor (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status; function Edge_Visitor (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status is begin -- TODO: Remove exception block once all libadalang problems -- have been fixed. begin Decls.Extract_Edges (Node, Graph); Subp_Overrides.Extract_Edges (Node, Graph); Primitive_Subps.Extract_Edges (Node, Graph); Generic_Instantiations.Extract_Edges (Node, Graph); References_Of_Decls.Extract_Edges (Node, Graph); Bodies_For_Decls.Extract_Edges (Node, Graph); Bodies_For_Entries.Extract_Edges (Node, Graph); Renamings.Extract_Edges (Node, Graph); Direct_Calls.Extract_Edges (Node, Graph); With_Clauses.Extract_Edges (Node, Graph); Derived_Type_Defs.Extract_Edges (Node, Graph); Decl_Types.Extract_Edges (Node, Graph); Deferred_Constants.Extract_Edges (Node, Graph); exception when E : LALCO.Property_Error => Handle_Exception (E, Node); end; return LALCO.Into; end Edge_Visitor; begin -- Node extraction -- File_System.Extract_Nodes should occur before the extraction of any -- other kind of node (see also the implementation of -- Get_Node_Attributes in Extraction.Node_Edge_Types). if Directory_Prefix /= VFS.No_File then File_System.Extract_Nodes (Directory_Prefix, Graph); end if; for Project of Projects loop Ada.Text_IO.Put_Line ("-- " & (+Project.Project_Path.Full_Name) & " --"); Project_Files.Extract_Nodes (Project, Graph); Source_Files_From_Projects.Extract_Nodes (Project, Graph); end loop; for Unit of Units loop Ada.Text_IO.Put_Line ("-- " & Unit.Get_Filename & " --"); Unit.Root.Traverse (Node_Visitor'Access); end loop; -- Edge extraction. if Directory_Prefix /= VFS.No_File then File_System.Extract_Edges (Directory_Prefix, Graph); end if; for Project of Projects loop Ada.Text_IO.Put_Line ("== " & (+Project.Project_Path.Full_Name) & " =="); Project_Files.Extract_Edges (Project, Recurse_Projects, Graph); Source_Files_From_Projects.Extract_Edges (Project, Context, Recurse_Projects, Graph); end loop; for Unit of Units loop Ada.Text_IO.Put_Line ("== " & Unit.Get_Filename & " =="); Unit.Root.Traverse (Edge_Visitor'Access); end loop; end Extract_Dependency_Graph; end Extraction;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Aspects; use Aspects; with Atree; use Atree; with Einfo; use Einfo; with Errout; use Errout; with Exp_Util; use Exp_Util; with Lib; use Lib; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Table; with Tbuild; use Tbuild; with Uintp; use Uintp; with Urealp; use Urealp; with GNAT.HTable; package body Sem_Dim is ------------------------- -- Rational Arithmetic -- ------------------------- type Whole is new Int; subtype Positive_Whole is Whole range 1 .. Whole'Last; type Rational is record Numerator : Whole; Denominator : Positive_Whole; end record; Zero : constant Rational := Rational'(Numerator => 0, Denominator => 1); No_Rational : constant Rational := Rational'(Numerator => 0, Denominator => 2); -- Used to indicate an expression that cannot be interpreted as a rational -- Returned value of the Create_Rational_From routine when parameter Expr -- is not a static representation of a rational. -- Rational constructors function "+" (Right : Whole) return Rational; function GCD (Left, Right : Whole) return Int; function Reduce (X : Rational) return Rational; -- Unary operator for Rational function "-" (Right : Rational) return Rational; function "abs" (Right : Rational) return Rational; -- Rational operations for Rationals function "+" (Left, Right : Rational) return Rational; function "-" (Left, Right : Rational) return Rational; function "*" (Left, Right : Rational) return Rational; function "/" (Left, Right : Rational) return Rational; ------------------ -- System Types -- ------------------ Max_Number_Of_Dimensions : constant := 7; -- Maximum number of dimensions in a dimension system High_Position_Bound : constant := Max_Number_Of_Dimensions; Invalid_Position : constant := 0; Low_Position_Bound : constant := 1; subtype Dimension_Position is Nat range Invalid_Position .. High_Position_Bound; type Name_Array is array (Dimension_Position range Low_Position_Bound .. High_Position_Bound) of Name_Id; -- Store the names of all units within a system No_Names : constant Name_Array := (others => No_Name); type Symbol_Array is array (Dimension_Position range Low_Position_Bound .. High_Position_Bound) of String_Id; -- Store the symbols of all units within a system No_Symbols : constant Symbol_Array := (others => No_String); -- The following record should be documented field by field type System_Type is record Type_Decl : Node_Id; Unit_Names : Name_Array; Unit_Symbols : Symbol_Array; Dim_Symbols : Symbol_Array; Count : Dimension_Position; end record; Null_System : constant System_Type := (Empty, No_Names, No_Symbols, No_Symbols, Invalid_Position); subtype System_Id is Nat; -- The following table maps types to systems package System_Table is new Table.Table ( Table_Component_Type => System_Type, Table_Index_Type => System_Id, Table_Low_Bound => 1, Table_Initial => 5, Table_Increment => 5, Table_Name => "System_Table"); -------------------- -- Dimension Type -- -------------------- type Dimension_Type is array (Dimension_Position range Low_Position_Bound .. High_Position_Bound) of Rational; Null_Dimension : constant Dimension_Type := (others => Zero); type Dimension_Table_Range is range 0 .. 510; function Dimension_Table_Hash (Key : Node_Id) return Dimension_Table_Range; -- The following table associates nodes with dimensions package Dimension_Table is new GNAT.HTable.Simple_HTable (Header_Num => Dimension_Table_Range, Element => Dimension_Type, No_Element => Null_Dimension, Key => Node_Id, Hash => Dimension_Table_Hash, Equal => "="); ------------------ -- Symbol Types -- ------------------ type Symbol_Table_Range is range 0 .. 510; function Symbol_Table_Hash (Key : Entity_Id) return Symbol_Table_Range; -- Each subtype with a dimension has a symbolic representation of the -- related unit. This table establishes a relation between the subtype -- and the symbol. package Symbol_Table is new GNAT.HTable.Simple_HTable (Header_Num => Symbol_Table_Range, Element => String_Id, No_Element => No_String, Key => Entity_Id, Hash => Symbol_Table_Hash, Equal => "="); -- The following array enumerates all contexts which may contain or -- produce a dimension. OK_For_Dimension : constant array (Node_Kind) of Boolean := (N_Attribute_Reference => True, N_Case_Expression => True, N_Expanded_Name => True, N_Explicit_Dereference => True, N_Defining_Identifier => True, N_Function_Call => True, N_Identifier => True, N_If_Expression => True, N_Indexed_Component => True, N_Integer_Literal => True, N_Op_Abs => True, N_Op_Add => True, N_Op_Divide => True, N_Op_Expon => True, N_Op_Minus => True, N_Op_Mod => True, N_Op_Multiply => True, N_Op_Plus => True, N_Op_Rem => True, N_Op_Subtract => True, N_Qualified_Expression => True, N_Real_Literal => True, N_Selected_Component => True, N_Slice => True, N_Type_Conversion => True, N_Unchecked_Type_Conversion => True, others => False); ----------------------- -- Local Subprograms -- ----------------------- procedure Analyze_Dimension_Assignment_Statement (N : Node_Id); -- Subroutine of Analyze_Dimension for assignment statement. Check that the -- dimensions of the left-hand side and the right-hand side of N match. procedure Analyze_Dimension_Binary_Op (N : Node_Id); -- Subroutine of Analyze_Dimension for binary operators. Check the -- dimensions of the right and the left operand permit the operation. -- Then, evaluate the resulting dimensions for each binary operator. procedure Analyze_Dimension_Component_Declaration (N : Node_Id); -- Subroutine of Analyze_Dimension for component declaration. Check that -- the dimensions of the type of N and of the expression match. procedure Analyze_Dimension_Extended_Return_Statement (N : Node_Id); -- Subroutine of Analyze_Dimension for extended return statement. Check -- that the dimensions of the returned type and of the returned object -- match. procedure Analyze_Dimension_Has_Etype (N : Node_Id); -- Subroutine of Analyze_Dimension for a subset of N_Has_Etype denoted by -- the list below: -- N_Attribute_Reference -- N_Identifier -- N_Indexed_Component -- N_Qualified_Expression -- N_Selected_Component -- N_Slice -- N_Type_Conversion -- N_Unchecked_Type_Conversion procedure Analyze_Dimension_Case_Expression (N : Node_Id); -- Verify that all alternatives have the same dimension procedure Analyze_Dimension_If_Expression (N : Node_Id); -- Verify that all alternatives have the same dimension procedure Analyze_Dimension_Number_Declaration (N : Node_Id); -- Procedure to analyze dimension of expression in a number declaration. -- This allows a named number to have nontrivial dimensions, while by -- default a named number is dimensionless. procedure Analyze_Dimension_Object_Declaration (N : Node_Id); -- Subroutine of Analyze_Dimension for object declaration. Check that -- the dimensions of the object type and the dimensions of the expression -- (if expression is present) match. Note that when the expression is -- a literal, no error is returned. This special case allows object -- declaration such as: m : constant Length := 1.0; procedure Analyze_Dimension_Object_Renaming_Declaration (N : Node_Id); -- Subroutine of Analyze_Dimension for object renaming declaration. Check -- the dimensions of the type and of the renamed object name of N match. procedure Analyze_Dimension_Simple_Return_Statement (N : Node_Id); -- Subroutine of Analyze_Dimension for simple return statement -- Check that the dimensions of the returned type and of the returned -- expression match. procedure Analyze_Dimension_Subtype_Declaration (N : Node_Id); -- Subroutine of Analyze_Dimension for subtype declaration. Propagate the -- dimensions from the parent type to the identifier of N. Note that if -- both the identifier and the parent type of N are not dimensionless, -- return an error. procedure Analyze_Dimension_Type_Conversion (N : Node_Id); -- Type conversions handle conversions between literals and dimensioned -- types, from dimensioned types to their base type, and between different -- dimensioned systems. Dimensions of the conversion are obtained either -- from those of the expression, or from the target type, and dimensional -- consistency must be checked when converting between values belonging -- to different dimensioned systems. procedure Analyze_Dimension_Unary_Op (N : Node_Id); -- Subroutine of Analyze_Dimension for unary operators. For Plus, Minus and -- Abs operators, propagate the dimensions from the operand to N. function Create_Rational_From (Expr : Node_Id; Complain : Boolean) return Rational; -- Given an arbitrary expression Expr, return a valid rational if Expr can -- be interpreted as a rational. Otherwise return No_Rational and also an -- error message if Complain is set to True. function Dimensions_Of (N : Node_Id) return Dimension_Type; -- Return the dimension vector of node N function Dimensions_Msg_Of (N : Node_Id; Description_Needed : Boolean := False) return String; -- Given a node N, return the dimension symbols of N, preceded by "has -- dimension" if Description_Needed. if N is dimensionless, return "'[']", -- or "is dimensionless" if Description_Needed. function Dimension_System_Root (T : Entity_Id) return Entity_Id; -- Given a type that has dimension information, return the type that is the -- root of its dimension system, e.g. Mks_Type. If T is not a dimensioned -- type, i.e. a standard numeric type, return Empty. procedure Dim_Warning_For_Numeric_Literal (N : Node_Id; Typ : Entity_Id); -- Issue a warning on the given numeric literal N to indicate that the -- compiler made the assumption that the literal is not dimensionless -- but has the dimension of Typ. procedure Eval_Op_Expon_With_Rational_Exponent (N : Node_Id; Exponent_Value : Rational); -- Evaluate the exponent it is a rational and the operand has a dimension function Exists (Dim : Dimension_Type) return Boolean; -- Returns True iff Dim does not denote the null dimension function Exists (Str : String_Id) return Boolean; -- Returns True iff Str does not denote No_String function Exists (Sys : System_Type) return Boolean; -- Returns True iff Sys does not denote the null system function From_Dim_To_Str_Of_Dim_Symbols (Dims : Dimension_Type; System : System_Type; In_Error_Msg : Boolean := False) return String_Id; -- Given a dimension vector and a dimension system, return the proper -- string of dimension symbols. If In_Error_Msg is True (i.e. the String_Id -- will be used to issue an error message) then this routine has a special -- handling for the insertion characters * or [ which must be preceded by -- a quote ' to be placed literally into the message. function From_Dim_To_Str_Of_Unit_Symbols (Dims : Dimension_Type; System : System_Type) return String_Id; -- Given a dimension vector and a dimension system, return the proper -- string of unit symbols. function Is_Dim_IO_Package_Entity (E : Entity_Id) return Boolean; -- Return True if E is the package entity of System.Dim.Float_IO or -- System.Dim.Integer_IO. function Is_Invalid (Position : Dimension_Position) return Boolean; -- Return True if Pos denotes the invalid position procedure Move_Dimensions (From : Node_Id; To : Node_Id); -- Copy dimension vector of From to To and delete dimension vector of From procedure Remove_Dimensions (N : Node_Id); -- Remove the dimension vector of node N procedure Set_Dimensions (N : Node_Id; Val : Dimension_Type); -- Associate a dimension vector with a node procedure Set_Symbol (E : Entity_Id; Val : String_Id); -- Associate a symbol representation of a dimension vector with a subtype function Symbol_Of (E : Entity_Id) return String_Id; -- E denotes a subtype with a dimension. Return the symbol representation -- of the dimension vector. function System_Of (E : Entity_Id) return System_Type; -- E denotes a type, return associated system of the type if it has one --------- -- "+" -- --------- function "+" (Right : Whole) return Rational is begin return Rational'(Numerator => Right, Denominator => 1); end "+"; function "+" (Left, Right : Rational) return Rational is R : constant Rational := Rational'(Numerator => Left.Numerator * Right.Denominator + Left.Denominator * Right.Numerator, Denominator => Left.Denominator * Right.Denominator); begin return Reduce (R); end "+"; --------- -- "-" -- --------- function "-" (Right : Rational) return Rational is begin return Rational'(Numerator => -Right.Numerator, Denominator => Right.Denominator); end "-"; function "-" (Left, Right : Rational) return Rational is R : constant Rational := Rational'(Numerator => Left.Numerator * Right.Denominator - Left.Denominator * Right.Numerator, Denominator => Left.Denominator * Right.Denominator); begin return Reduce (R); end "-"; --------- -- "*" -- --------- function "*" (Left, Right : Rational) return Rational is R : constant Rational := Rational'(Numerator => Left.Numerator * Right.Numerator, Denominator => Left.Denominator * Right.Denominator); begin return Reduce (R); end "*"; --------- -- "/" -- --------- function "/" (Left, Right : Rational) return Rational is R : constant Rational := abs Right; L : Rational := Left; begin if Right.Numerator < 0 then L.Numerator := Whole (-Integer (L.Numerator)); end if; return Reduce (Rational'(Numerator => L.Numerator * R.Denominator, Denominator => L.Denominator * R.Numerator)); end "/"; ----------- -- "abs" -- ----------- function "abs" (Right : Rational) return Rational is begin return Rational'(Numerator => abs Right.Numerator, Denominator => Right.Denominator); end "abs"; ------------------------------ -- Analyze_Aspect_Dimension -- ------------------------------ -- with Dimension => -- ([Symbol =>] SYMBOL, DIMENSION_VALUE {, DIMENSION_Value}) -- -- SYMBOL ::= STRING_LITERAL | CHARACTER_LITERAL -- DIMENSION_VALUE ::= -- RATIONAL -- | others => RATIONAL -- | DISCRETE_CHOICE_LIST => RATIONAL -- RATIONAL ::= [-] NUMERIC_LITERAL [/ NUMERIC_LITERAL] -- Note that when the dimensioned type is an integer type, then any -- dimension value must be an integer literal. procedure Analyze_Aspect_Dimension (N : Node_Id; Id : Entity_Id; Aggr : Node_Id) is Def_Id : constant Entity_Id := Defining_Identifier (N); Processed : array (Dimension_Type'Range) of Boolean := (others => False); -- This array is used when processing ranges or Others_Choice as part of -- the dimension aggregate. Dimensions : Dimension_Type := Null_Dimension; procedure Extract_Power (Expr : Node_Id; Position : Dimension_Position); -- Given an expression with denotes a rational number, read the number -- and associate it with Position in Dimensions. function Position_In_System (Id : Node_Id; System : System_Type) return Dimension_Position; -- Given an identifier which denotes a dimension, return the position of -- that dimension within System. ------------------- -- Extract_Power -- ------------------- procedure Extract_Power (Expr : Node_Id; Position : Dimension_Position) is begin Dimensions (Position) := Create_Rational_From (Expr, True); Processed (Position) := True; -- If the dimensioned root type is an integer type, it is not -- particularly useful, and fractional dimensions do not make -- much sense for such types, so previously we used to reject -- dimensions of integer types that were not integer literals. -- However, the manipulation of dimensions does not depend on -- the kind of root type, so we can accept this usage for rare -- cases where dimensions are specified for integer values. end Extract_Power; ------------------------ -- Position_In_System -- ------------------------ function Position_In_System (Id : Node_Id; System : System_Type) return Dimension_Position is Dimension_Name : constant Name_Id := Chars (Id); begin for Position in System.Unit_Names'Range loop if Dimension_Name = System.Unit_Names (Position) then return Position; end if; end loop; return Invalid_Position; end Position_In_System; -- Local variables Assoc : Node_Id; Choice : Node_Id; Expr : Node_Id; Num_Choices : Nat := 0; Num_Dimensions : Nat := 0; Others_Seen : Boolean := False; Position : Nat := 0; Sub_Ind : Node_Id; Symbol : String_Id := No_String; Symbol_Expr : Node_Id; System : System_Type; Typ : Entity_Id; Errors_Count : Nat; -- Errors_Count is a count of errors detected by the compiler so far -- just before the extraction of symbol, names and values in the -- aggregate (Step 2). -- -- At the end of the analysis, there is a check to verify that this -- count equals to Serious_Errors_Detected i.e. no erros have been -- encountered during the process. Otherwise the Dimension_Table is -- not filled. -- Start of processing for Analyze_Aspect_Dimension begin -- STEP 1: Legality of aspect if Nkind (N) /= N_Subtype_Declaration then Error_Msg_NE ("aspect& must apply to subtype declaration", N, Id); return; end if; Sub_Ind := Subtype_Indication (N); Typ := Etype (Sub_Ind); System := System_Of (Typ); if Nkind (Sub_Ind) = N_Subtype_Indication then Error_Msg_NE ("constraint not allowed with aspect&", Constraint (Sub_Ind), Id); return; end if; -- The dimension declarations are useless if the parent type does not -- declare a valid system. if not Exists (System) then Error_Msg_NE ("parent type of& lacks dimension system", Sub_Ind, Def_Id); return; end if; if Nkind (Aggr) /= N_Aggregate then Error_Msg_N ("aggregate expected", Aggr); return; end if; -- STEP 2: Symbol, Names and values extraction -- Get the number of errors detected by the compiler so far Errors_Count := Serious_Errors_Detected; -- STEP 2a: Symbol extraction -- The first entry in the aggregate may be the symbolic representation -- of the quantity. -- Positional symbol argument Symbol_Expr := First (Expressions (Aggr)); -- Named symbol argument if No (Symbol_Expr) or else Nkind (Symbol_Expr) not in N_Character_Literal | N_String_Literal then Symbol_Expr := Empty; -- Component associations present if Present (Component_Associations (Aggr)) then Assoc := First (Component_Associations (Aggr)); Choice := First (Choices (Assoc)); if No (Next (Choice)) and then Nkind (Choice) = N_Identifier then -- Symbol component association is present if Chars (Choice) = Name_Symbol then Num_Choices := Num_Choices + 1; Symbol_Expr := Expression (Assoc); -- Verify symbol expression is a string or a character if Nkind (Symbol_Expr) not in N_Character_Literal | N_String_Literal then Symbol_Expr := Empty; Error_Msg_N ("symbol expression must be character or string", Symbol_Expr); end if; -- Special error if no Symbol choice but expression is string -- or character. elsif Nkind (Expression (Assoc)) in N_Character_Literal | N_String_Literal then Num_Choices := Num_Choices + 1; Error_Msg_N ("optional component Symbol expected, found&", Choice); end if; end if; end if; end if; -- STEP 2b: Names and values extraction -- Positional elements Expr := First (Expressions (Aggr)); -- Skip the symbol expression when present if Present (Symbol_Expr) and then Num_Choices = 0 then Next (Expr); end if; Position := Low_Position_Bound; while Present (Expr) loop if Position > High_Position_Bound then Error_Msg_N ("type& has more dimensions than system allows", Def_Id); exit; end if; Extract_Power (Expr, Position); Position := Position + 1; Num_Dimensions := Num_Dimensions + 1; Next (Expr); end loop; -- Named elements Assoc := First (Component_Associations (Aggr)); -- Skip the symbol association when present if Num_Choices = 1 then Next (Assoc); end if; while Present (Assoc) loop Expr := Expression (Assoc); Choice := First (Choices (Assoc)); while Present (Choice) loop -- Identifier case: NAME => EXPRESSION if Nkind (Choice) = N_Identifier then Position := Position_In_System (Choice, System); if Is_Invalid (Position) then Error_Msg_N ("dimension name& not part of system", Choice); else Extract_Power (Expr, Position); end if; -- Range case: NAME .. NAME => EXPRESSION elsif Nkind (Choice) = N_Range then declare Low : constant Node_Id := Low_Bound (Choice); High : constant Node_Id := High_Bound (Choice); Low_Pos : Dimension_Position; High_Pos : Dimension_Position; begin if Nkind (Low) /= N_Identifier then Error_Msg_N ("bound must denote a dimension name", Low); elsif Nkind (High) /= N_Identifier then Error_Msg_N ("bound must denote a dimension name", High); else Low_Pos := Position_In_System (Low, System); High_Pos := Position_In_System (High, System); if Is_Invalid (Low_Pos) then Error_Msg_N ("dimension name& not part of system", Low); elsif Is_Invalid (High_Pos) then Error_Msg_N ("dimension name& not part of system", High); elsif Low_Pos > High_Pos then Error_Msg_N ("expected low to high range", Choice); else for Position in Low_Pos .. High_Pos loop Extract_Power (Expr, Position); end loop; end if; end if; end; -- Others case: OTHERS => EXPRESSION elsif Nkind (Choice) = N_Others_Choice then if Present (Next (Choice)) or else Present (Prev (Choice)) then Error_Msg_N ("OTHERS must appear alone in a choice list", Choice); elsif Present (Next (Assoc)) then Error_Msg_N ("OTHERS must appear last in an aggregate", Choice); elsif Others_Seen then Error_Msg_N ("multiple OTHERS not allowed", Choice); else -- Fill the non-processed dimensions with the default value -- supplied by others. for Position in Processed'Range loop if not Processed (Position) then Extract_Power (Expr, Position); end if; end loop; end if; Others_Seen := True; -- All other cases are illegal declarations of dimension names else Error_Msg_NE ("wrong syntax for aspect&", Choice, Id); end if; Num_Choices := Num_Choices + 1; Next (Choice); end loop; Num_Dimensions := Num_Dimensions + 1; Next (Assoc); end loop; -- STEP 3: Consistency of system and dimensions if Present (First (Expressions (Aggr))) and then (First (Expressions (Aggr)) /= Symbol_Expr or else Present (Next (Symbol_Expr))) and then (Num_Choices > 1 or else (Num_Choices = 1 and then not Others_Seen)) then Error_Msg_N ("named associations cannot follow positional associations", Aggr); end if; if Num_Dimensions > System.Count then Error_Msg_N ("type& has more dimensions than system allows", Def_Id); elsif Num_Dimensions < System.Count and then not Others_Seen then Error_Msg_N ("type& has less dimensions than system allows", Def_Id); end if; -- STEP 4: Dimension symbol extraction if Present (Symbol_Expr) then if Nkind (Symbol_Expr) = N_Character_Literal then Start_String; Store_String_Char (UI_To_CC (Char_Literal_Value (Symbol_Expr))); Symbol := End_String; else Symbol := Strval (Symbol_Expr); end if; if String_Length (Symbol) = 0 then Error_Msg_N ("empty string not allowed here", Symbol_Expr); end if; end if; -- STEP 5: Storage of extracted values -- Check that no errors have been detected during the analysis if Errors_Count = Serious_Errors_Detected then -- Check for useless declaration if Symbol = No_String and then not Exists (Dimensions) then Error_Msg_N ("useless dimension declaration", Aggr); end if; if Symbol /= No_String then Set_Symbol (Def_Id, Symbol); end if; if Exists (Dimensions) then Set_Dimensions (Def_Id, Dimensions); end if; end if; end Analyze_Aspect_Dimension; ------------------------------------- -- Analyze_Aspect_Dimension_System -- ------------------------------------- -- with Dimension_System => (DIMENSION {, DIMENSION}); -- DIMENSION ::= ( -- [Unit_Name =>] IDENTIFIER, -- [Unit_Symbol =>] SYMBOL, -- [Dim_Symbol =>] SYMBOL) procedure Analyze_Aspect_Dimension_System (N : Node_Id; Id : Entity_Id; Aggr : Node_Id) is function Is_Derived_Numeric_Type (N : Node_Id) return Boolean; -- Determine whether type declaration N denotes a numeric derived type ------------------------------- -- Is_Derived_Numeric_Type -- ------------------------------- function Is_Derived_Numeric_Type (N : Node_Id) return Boolean is begin return Nkind (N) = N_Full_Type_Declaration and then Nkind (Type_Definition (N)) = N_Derived_Type_Definition and then Is_Numeric_Type (Entity (Subtype_Indication (Type_Definition (N)))); end Is_Derived_Numeric_Type; -- Local variables Assoc : Node_Id; Choice : Node_Id; Dim_Aggr : Node_Id; Dim_Symbol : Node_Id; Dim_Symbols : Symbol_Array := No_Symbols; Dim_System : System_Type := Null_System; Position : Dimension_Position := Invalid_Position; Unit_Name : Node_Id; Unit_Names : Name_Array := No_Names; Unit_Symbol : Node_Id; Unit_Symbols : Symbol_Array := No_Symbols; Errors_Count : Nat; -- Errors_Count is a count of errors detected by the compiler so far -- just before the extraction of names and symbols in the aggregate -- (Step 3). -- -- At the end of the analysis, there is a check to verify that this -- count equals Serious_Errors_Detected i.e. no errors have been -- encountered during the process. Otherwise the System_Table is -- not filled. -- Start of processing for Analyze_Aspect_Dimension_System begin -- STEP 1: Legality of aspect if not Is_Derived_Numeric_Type (N) then Error_Msg_NE ("aspect& must apply to numeric derived type declaration", N, Id); return; end if; if Nkind (Aggr) /= N_Aggregate then Error_Msg_N ("aggregate expected", Aggr); return; end if; -- STEP 2: Structural verification of the dimension aggregate if Present (Component_Associations (Aggr)) then Error_Msg_N ("expected positional aggregate", Aggr); return; end if; -- STEP 3: Name and Symbol extraction Dim_Aggr := First (Expressions (Aggr)); Errors_Count := Serious_Errors_Detected; while Present (Dim_Aggr) loop if Position = High_Position_Bound then Error_Msg_N ("too many dimensions in system", Aggr); exit; end if; Position := Position + 1; if Nkind (Dim_Aggr) /= N_Aggregate then Error_Msg_N ("aggregate expected", Dim_Aggr); else if Present (Component_Associations (Dim_Aggr)) and then Present (Expressions (Dim_Aggr)) then Error_Msg_N ("mixed positional/named aggregate not allowed here", Dim_Aggr); -- Verify each dimension aggregate has three arguments elsif List_Length (Component_Associations (Dim_Aggr)) /= 3 and then List_Length (Expressions (Dim_Aggr)) /= 3 then Error_Msg_N ("three components expected in aggregate", Dim_Aggr); else -- Named dimension aggregate if Present (Component_Associations (Dim_Aggr)) then -- Check first argument denotes the unit name Assoc := First (Component_Associations (Dim_Aggr)); Choice := First (Choices (Assoc)); Unit_Name := Expression (Assoc); if Present (Next (Choice)) or else Nkind (Choice) /= N_Identifier then Error_Msg_NE ("wrong syntax for aspect&", Choice, Id); elsif Chars (Choice) /= Name_Unit_Name then Error_Msg_N ("expected Unit_Name, found&", Choice); end if; -- Check the second argument denotes the unit symbol Next (Assoc); Choice := First (Choices (Assoc)); Unit_Symbol := Expression (Assoc); if Present (Next (Choice)) or else Nkind (Choice) /= N_Identifier then Error_Msg_NE ("wrong syntax for aspect&", Choice, Id); elsif Chars (Choice) /= Name_Unit_Symbol then Error_Msg_N ("expected Unit_Symbol, found&", Choice); end if; -- Check the third argument denotes the dimension symbol Next (Assoc); Choice := First (Choices (Assoc)); Dim_Symbol := Expression (Assoc); if Present (Next (Choice)) or else Nkind (Choice) /= N_Identifier then Error_Msg_NE ("wrong syntax for aspect&", Choice, Id); elsif Chars (Choice) /= Name_Dim_Symbol then Error_Msg_N ("expected Dim_Symbol, found&", Choice); end if; -- Positional dimension aggregate else Unit_Name := First (Expressions (Dim_Aggr)); Unit_Symbol := Next (Unit_Name); Dim_Symbol := Next (Unit_Symbol); end if; -- Check the first argument for each dimension aggregate is -- a name. if Nkind (Unit_Name) = N_Identifier then Unit_Names (Position) := Chars (Unit_Name); else Error_Msg_N ("expected unit name", Unit_Name); end if; -- Check the second argument for each dimension aggregate is -- a string or a character. if Nkind (Unit_Symbol) not in N_String_Literal | N_Character_Literal then Error_Msg_N ("expected unit symbol (string or character)", Unit_Symbol); else -- String case if Nkind (Unit_Symbol) = N_String_Literal then Unit_Symbols (Position) := Strval (Unit_Symbol); -- Character case else Start_String; Store_String_Char (UI_To_CC (Char_Literal_Value (Unit_Symbol))); Unit_Symbols (Position) := End_String; end if; -- Verify that the string is not empty if String_Length (Unit_Symbols (Position)) = 0 then Error_Msg_N ("empty string not allowed here", Unit_Symbol); end if; end if; -- Check the third argument for each dimension aggregate is -- a string or a character. if Nkind (Dim_Symbol) not in N_String_Literal | N_Character_Literal then Error_Msg_N ("expected dimension symbol (string or character)", Dim_Symbol); else -- String case if Nkind (Dim_Symbol) = N_String_Literal then Dim_Symbols (Position) := Strval (Dim_Symbol); -- Character case else Start_String; Store_String_Char (UI_To_CC (Char_Literal_Value (Dim_Symbol))); Dim_Symbols (Position) := End_String; end if; -- Verify that the string is not empty if String_Length (Dim_Symbols (Position)) = 0 then Error_Msg_N ("empty string not allowed here", Dim_Symbol); end if; end if; end if; end if; Next (Dim_Aggr); end loop; -- STEP 4: Storage of extracted values -- Check that no errors have been detected during the analysis if Errors_Count = Serious_Errors_Detected then Dim_System.Type_Decl := N; Dim_System.Unit_Names := Unit_Names; Dim_System.Unit_Symbols := Unit_Symbols; Dim_System.Dim_Symbols := Dim_Symbols; Dim_System.Count := Position; System_Table.Append (Dim_System); end if; end Analyze_Aspect_Dimension_System; ----------------------- -- Analyze_Dimension -- ----------------------- -- This dispatch routine propagates dimensions for each node procedure Analyze_Dimension (N : Node_Id) is begin -- Aspect is an Ada 2012 feature. Note that there is no need to check -- dimensions for nodes that don't come from source, except for subtype -- declarations where the dimensions are inherited from the base type, -- for explicit dereferences generated when expanding iterators, and -- for object declarations generated for inlining. if Ada_Version < Ada_2012 then return; -- Inlined bodies have already been checked for dimensionality elsif In_Inlined_Body then return; elsif not Comes_From_Source (N) then if Nkind (N) not in N_Explicit_Dereference | N_Identifier | N_Object_Declaration | N_Subtype_Declaration then return; end if; end if; case Nkind (N) is when N_Assignment_Statement => Analyze_Dimension_Assignment_Statement (N); when N_Binary_Op => Analyze_Dimension_Binary_Op (N); when N_Case_Expression => Analyze_Dimension_Case_Expression (N); when N_Component_Declaration => Analyze_Dimension_Component_Declaration (N); when N_Extended_Return_Statement => Analyze_Dimension_Extended_Return_Statement (N); when N_Attribute_Reference | N_Expanded_Name | N_Explicit_Dereference | N_Function_Call | N_Indexed_Component | N_Qualified_Expression | N_Selected_Component | N_Slice | N_Unchecked_Type_Conversion => Analyze_Dimension_Has_Etype (N); -- In the presence of a repaired syntax error, an identifier may be -- introduced without a usable type. when N_Identifier => if Present (Etype (N)) then Analyze_Dimension_Has_Etype (N); end if; when N_If_Expression => Analyze_Dimension_If_Expression (N); when N_Number_Declaration => Analyze_Dimension_Number_Declaration (N); when N_Object_Declaration => Analyze_Dimension_Object_Declaration (N); when N_Object_Renaming_Declaration => Analyze_Dimension_Object_Renaming_Declaration (N); when N_Simple_Return_Statement => if not Comes_From_Extended_Return_Statement (N) then Analyze_Dimension_Simple_Return_Statement (N); end if; when N_Subtype_Declaration => Analyze_Dimension_Subtype_Declaration (N); when N_Type_Conversion => Analyze_Dimension_Type_Conversion (N); when N_Unary_Op => Analyze_Dimension_Unary_Op (N); when others => null; end case; end Analyze_Dimension; --------------------------------------- -- Analyze_Dimension_Array_Aggregate -- --------------------------------------- procedure Analyze_Dimension_Array_Aggregate (N : Node_Id; Comp_Typ : Entity_Id) is Comp_Ass : constant List_Id := Component_Associations (N); Dims_Of_Comp_Typ : constant Dimension_Type := Dimensions_Of (Comp_Typ); Exps : constant List_Id := Expressions (N); Comp : Node_Id; Dims_Of_Expr : Dimension_Type; Expr : Node_Id; Error_Detected : Boolean := False; -- This flag is used in order to indicate if an error has been detected -- so far by the compiler in this routine. begin -- Aspect is an Ada 2012 feature. Nothing to do here if the component -- base type is not a dimensioned type. -- Inlined bodies have already been checked for dimensionality. -- Note that here the original node must come from source since the -- original array aggregate may not have been entirely decorated. if Ada_Version < Ada_2012 or else In_Inlined_Body or else not Comes_From_Source (Original_Node (N)) or else not Has_Dimension_System (Base_Type (Comp_Typ)) then return; end if; -- Check whether there is any positional component association if Is_Empty_List (Exps) then Comp := First (Comp_Ass); else Comp := First (Exps); end if; while Present (Comp) loop -- Get the expression from the component if Nkind (Comp) = N_Component_Association then Expr := Expression (Comp); else Expr := Comp; end if; -- Issue an error if the dimensions of the component type and the -- dimensions of the component mismatch. -- Note that we must ensure the expression has been fully analyzed -- since it may not be decorated at this point. We also don't want to -- issue the same error message multiple times on the same expression -- (may happen when an aggregate is converted into a positional -- aggregate). We also must verify that this is a scalar component, -- and not a subaggregate of a multidimensional aggregate. -- The expression may be an identifier that has been copied several -- times during expansion, its dimensions are those of its type. if Is_Entity_Name (Expr) then Dims_Of_Expr := Dimensions_Of (Etype (Expr)); else Dims_Of_Expr := Dimensions_Of (Expr); end if; if Comes_From_Source (Original_Node (Expr)) and then Present (Etype (Expr)) and then Is_Numeric_Type (Etype (Expr)) and then Dims_Of_Expr /= Dims_Of_Comp_Typ and then Sloc (Comp) /= Sloc (Prev (Comp)) then -- Check if an error has already been encountered so far if not Error_Detected then Error_Msg_N ("dimensions mismatch in array aggregate", N); Error_Detected := True; end if; Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Comp_Typ) & ", found " & Dimensions_Msg_Of (Expr), Expr); end if; -- Look at the named components right after the positional components if not Present (Next (Comp)) and then List_Containing (Comp) = Exps then Comp := First (Comp_Ass); else Next (Comp); end if; end loop; end Analyze_Dimension_Array_Aggregate; -------------------------------------------- -- Analyze_Dimension_Assignment_Statement -- -------------------------------------------- procedure Analyze_Dimension_Assignment_Statement (N : Node_Id) is Lhs : constant Node_Id := Name (N); Dims_Of_Lhs : constant Dimension_Type := Dimensions_Of (Lhs); Rhs : constant Node_Id := Expression (N); Dims_Of_Rhs : constant Dimension_Type := Dimensions_Of (Rhs); procedure Error_Dim_Msg_For_Assignment_Statement (N : Node_Id; Lhs : Node_Id; Rhs : Node_Id); -- Error using Error_Msg_N at node N. Output the dimensions of left -- and right hand sides. -------------------------------------------- -- Error_Dim_Msg_For_Assignment_Statement -- -------------------------------------------- procedure Error_Dim_Msg_For_Assignment_Statement (N : Node_Id; Lhs : Node_Id; Rhs : Node_Id) is begin Error_Msg_N ("dimensions mismatch in assignment", N); Error_Msg_N ("\left-hand side " & Dimensions_Msg_Of (Lhs, True), N); Error_Msg_N ("\right-hand side " & Dimensions_Msg_Of (Rhs, True), N); end Error_Dim_Msg_For_Assignment_Statement; -- Start of processing for Analyze_Dimension_Assignment begin if Dims_Of_Lhs /= Dims_Of_Rhs then Error_Dim_Msg_For_Assignment_Statement (N, Lhs, Rhs); end if; end Analyze_Dimension_Assignment_Statement; --------------------------------- -- Analyze_Dimension_Binary_Op -- --------------------------------- -- Check and propagate the dimensions for binary operators -- Note that when the dimensions mismatch, no dimension is propagated to N. procedure Analyze_Dimension_Binary_Op (N : Node_Id) is N_Kind : constant Node_Kind := Nkind (N); function Dimensions_Of_Operand (N : Node_Id) return Dimension_Type; -- If the operand is a numeric literal that comes from a declared -- constant, use the dimensions of the constant which were computed -- from the expression of the constant declaration. Otherwise the -- dimensions are those of the operand, or the type of the operand. -- This takes care of node rewritings from validity checks, where the -- dimensions of the operand itself may not be preserved, while the -- type comes from context and must have dimension information. procedure Error_Dim_Msg_For_Binary_Op (N, L, R : Node_Id); -- Error using Error_Msg_NE and Error_Msg_N at node N. Output the -- dimensions of both operands. --------------------------- -- Dimensions_Of_Operand -- --------------------------- function Dimensions_Of_Operand (N : Node_Id) return Dimension_Type is Dims : constant Dimension_Type := Dimensions_Of (N); begin if Exists (Dims) then return Dims; elsif Is_Entity_Name (N) then return Dimensions_Of (Etype (Entity (N))); elsif Nkind (N) = N_Real_Literal then if Present (Original_Entity (N)) then return Dimensions_Of (Original_Entity (N)); else return Dimensions_Of (Etype (N)); end if; -- Otherwise return the default dimensions else return Dims; end if; end Dimensions_Of_Operand; --------------------------------- -- Error_Dim_Msg_For_Binary_Op -- --------------------------------- procedure Error_Dim_Msg_For_Binary_Op (N, L, R : Node_Id) is begin Error_Msg_NE ("both operands for operation& must have same dimensions", N, Entity (N)); Error_Msg_N ("\left operand " & Dimensions_Msg_Of (L, True), N); Error_Msg_N ("\right operand " & Dimensions_Msg_Of (R, True), N); end Error_Dim_Msg_For_Binary_Op; -- Start of processing for Analyze_Dimension_Binary_Op begin -- If the node is already analyzed, do not examine the operands. At the -- end of the analysis their dimensions have been removed, and the node -- itself may have been rewritten. if Analyzed (N) then return; end if; if N_Kind in N_Op_Add | N_Op_Expon | N_Op_Subtract | N_Multiplying_Operator | N_Op_Compare then declare L : constant Node_Id := Left_Opnd (N); Dims_Of_L : constant Dimension_Type := Dimensions_Of_Operand (L); L_Has_Dimensions : constant Boolean := Exists (Dims_Of_L); R : constant Node_Id := Right_Opnd (N); Dims_Of_R : constant Dimension_Type := Dimensions_Of_Operand (R); R_Has_Dimensions : constant Boolean := Exists (Dims_Of_R); Dims_Of_N : Dimension_Type := Null_Dimension; begin -- N_Op_Add, N_Op_Mod, N_Op_Rem or N_Op_Subtract case if N_Kind in N_Op_Add | N_Op_Mod | N_Op_Rem | N_Op_Subtract then -- Check both operands have same dimension if Dims_Of_L /= Dims_Of_R then Error_Dim_Msg_For_Binary_Op (N, L, R); else -- Check both operands are not dimensionless if Exists (Dims_Of_L) then Set_Dimensions (N, Dims_Of_L); end if; end if; -- N_Op_Multiply or N_Op_Divide case elsif N_Kind in N_Op_Multiply | N_Op_Divide then -- Check at least one operand is not dimensionless if L_Has_Dimensions or R_Has_Dimensions then -- Multiplication case -- Get both operands dimensions and add them if N_Kind = N_Op_Multiply then for Position in Dimension_Type'Range loop Dims_Of_N (Position) := Dims_Of_L (Position) + Dims_Of_R (Position); end loop; -- Division case -- Get both operands dimensions and subtract them else for Position in Dimension_Type'Range loop Dims_Of_N (Position) := Dims_Of_L (Position) - Dims_Of_R (Position); end loop; end if; if Exists (Dims_Of_N) then Set_Dimensions (N, Dims_Of_N); end if; end if; -- Exponentiation case -- Note: a rational exponent is allowed for dimensioned operand elsif N_Kind = N_Op_Expon then -- Check the left operand is not dimensionless. Note that the -- value of the exponent must be known compile time. Otherwise, -- the exponentiation evaluation will return an error message. if L_Has_Dimensions then if not Compile_Time_Known_Value (R) then Error_Msg_N ("exponent of dimensioned operand must be " & "known at compile time", N); end if; declare Exponent_Value : Rational := Zero; begin -- Real operand case if Is_Real_Type (Etype (L)) then -- Define the exponent as a Rational number Exponent_Value := Create_Rational_From (R, False); -- Verify that the exponent cannot be interpreted -- as a rational, otherwise interpret the exponent -- as an integer. if Exponent_Value = No_Rational then Exponent_Value := +Whole (UI_To_Int (Expr_Value (R))); end if; -- Integer operand case. -- For integer operand, the exponent cannot be -- interpreted as a rational. else Exponent_Value := +Whole (UI_To_Int (Expr_Value (R))); end if; for Position in Dimension_Type'Range loop Dims_Of_N (Position) := Dims_Of_L (Position) * Exponent_Value; end loop; if Exists (Dims_Of_N) then Set_Dimensions (N, Dims_Of_N); end if; end; end if; -- Comparison cases -- For relational operations, only dimension checking is -- performed (no propagation). If one operand is the result -- of constant folding the dimensions may have been lost -- in a tree copy, so assume that preanalysis has verified -- that dimensions are correct. elsif N_Kind in N_Op_Compare then if (L_Has_Dimensions or R_Has_Dimensions) and then Dims_Of_L /= Dims_Of_R then if Nkind (L) = N_Real_Literal and then not (Comes_From_Source (L)) and then Expander_Active then null; elsif Nkind (R) = N_Real_Literal and then not (Comes_From_Source (R)) and then Expander_Active then null; -- Numeric literal case. Issue a warning to indicate the -- literal is treated as if its dimension matches the type -- dimension. elsif Nkind (Original_Node (L)) in N_Integer_Literal | N_Real_Literal then Dim_Warning_For_Numeric_Literal (L, Etype (R)); elsif Nkind (Original_Node (R)) in N_Integer_Literal | N_Real_Literal then Dim_Warning_For_Numeric_Literal (R, Etype (L)); else Error_Dim_Msg_For_Binary_Op (N, L, R); end if; end if; end if; -- If expander is active, remove dimension information from each -- operand, as only dimensions of result are relevant. if Expander_Active then Remove_Dimensions (L); Remove_Dimensions (R); end if; end; end if; end Analyze_Dimension_Binary_Op; ---------------------------- -- Analyze_Dimension_Call -- ---------------------------- procedure Analyze_Dimension_Call (N : Node_Id; Nam : Entity_Id) is Actuals : constant List_Id := Parameter_Associations (N); Actual : Node_Id; Dims_Of_Formal : Dimension_Type; Formal : Node_Id; Formal_Typ : Entity_Id; Error_Detected : Boolean := False; -- This flag is used in order to indicate if an error has been detected -- so far by the compiler in this routine. begin -- Aspect is an Ada 2012 feature. Note that there is no need to check -- dimensions for calls in inlined bodies, or calls that don't come -- from source, or those that may have semantic errors. if Ada_Version < Ada_2012 or else In_Inlined_Body or else not Comes_From_Source (N) or else Error_Posted (N) then return; end if; -- Check the dimensions of the actuals, if any if not Is_Empty_List (Actuals) then -- Special processing for elementary functions -- For Sqrt call, the resulting dimensions equal to half the -- dimensions of the actual. For all other elementary calls, this -- routine check that every actual is dimensionless. if Nkind (N) = N_Function_Call then Elementary_Function_Calls : declare Dims_Of_Call : Dimension_Type; Ent : Entity_Id := Nam; function Is_Elementary_Function_Entity (Sub_Id : Entity_Id) return Boolean; -- Given Sub_Id, the original subprogram entity, return True -- if call is to an elementary function (see Ada.Numerics. -- Generic_Elementary_Functions). ----------------------------------- -- Is_Elementary_Function_Entity -- ----------------------------------- function Is_Elementary_Function_Entity (Sub_Id : Entity_Id) return Boolean is Loc : constant Source_Ptr := Sloc (Sub_Id); begin -- Is entity in Ada.Numerics.Generic_Elementary_Functions? return Loc > No_Location and then Is_RTU (Cunit_Entity (Get_Source_Unit (Loc)), Ada_Numerics_Generic_Elementary_Functions); end Is_Elementary_Function_Entity; -- Start of processing for Elementary_Function_Calls begin -- Get original subprogram entity following the renaming chain if Present (Alias (Ent)) then Ent := Alias (Ent); end if; -- Check the call is an Elementary function call if Is_Elementary_Function_Entity (Ent) then -- Sqrt function call case if Chars (Ent) = Name_Sqrt then Dims_Of_Call := Dimensions_Of (First_Actual (N)); -- Evaluates the resulting dimensions (i.e. half the -- dimensions of the actual). if Exists (Dims_Of_Call) then for Position in Dims_Of_Call'Range loop Dims_Of_Call (Position) := Dims_Of_Call (Position) * Rational'(Numerator => 1, Denominator => 2); end loop; Set_Dimensions (N, Dims_Of_Call); end if; -- All other elementary functions case. Note that every -- actual here should be dimensionless. else Actual := First_Actual (N); while Present (Actual) loop if Exists (Dimensions_Of (Actual)) then -- Check if error has already been encountered if not Error_Detected then Error_Msg_NE ("dimensions mismatch in call of&", N, Name (N)); Error_Detected := True; end if; Error_Msg_N ("\expected dimension '['], found " & Dimensions_Msg_Of (Actual), Actual); end if; Next_Actual (Actual); end loop; end if; -- Nothing more to do for elementary functions return; end if; end Elementary_Function_Calls; end if; -- General case. Check, for each parameter, the dimensions of the -- actual and its corresponding formal match. Otherwise, complain. Actual := First_Actual (N); Formal := First_Formal (Nam); while Present (Formal) loop -- A missing corresponding actual indicates that the analysis of -- the call was aborted due to a previous error. if No (Actual) then Check_Error_Detected; return; end if; Formal_Typ := Etype (Formal); Dims_Of_Formal := Dimensions_Of (Formal_Typ); -- If the formal is not dimensionless, check dimensions of formal -- and actual match. Otherwise, complain. if Exists (Dims_Of_Formal) and then Dimensions_Of (Actual) /= Dims_Of_Formal then -- Check if an error has already been encountered so far if not Error_Detected then Error_Msg_NE ("dimensions mismatch in& call", N, Name (N)); Error_Detected := True; end if; Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Formal_Typ) & ", found " & Dimensions_Msg_Of (Actual), Actual); end if; Next_Actual (Actual); Next_Formal (Formal); end loop; end if; -- For function calls, propagate the dimensions from the returned type if Nkind (N) = N_Function_Call then Analyze_Dimension_Has_Etype (N); end if; end Analyze_Dimension_Call; --------------------------------------- -- Analyze_Dimension_Case_Expression -- --------------------------------------- procedure Analyze_Dimension_Case_Expression (N : Node_Id) is Frst : constant Node_Id := First (Alternatives (N)); Frst_Expr : constant Node_Id := Expression (Frst); Dims : constant Dimension_Type := Dimensions_Of (Frst_Expr); Alt : Node_Id; begin Alt := Next (Frst); while Present (Alt) loop if Dimensions_Of (Expression (Alt)) /= Dims then Error_Msg_N ("dimension mismatch in case expression", Alt); exit; end if; Next (Alt); end loop; Copy_Dimensions (Frst_Expr, N); end Analyze_Dimension_Case_Expression; --------------------------------------------- -- Analyze_Dimension_Component_Declaration -- --------------------------------------------- procedure Analyze_Dimension_Component_Declaration (N : Node_Id) is Expr : constant Node_Id := Expression (N); Id : constant Entity_Id := Defining_Identifier (N); Etyp : constant Entity_Id := Etype (Id); Dims_Of_Etyp : constant Dimension_Type := Dimensions_Of (Etyp); Dims_Of_Expr : Dimension_Type; procedure Error_Dim_Msg_For_Component_Declaration (N : Node_Id; Etyp : Entity_Id; Expr : Node_Id); -- Error using Error_Msg_N at node N. Output the dimensions of the -- type Etyp and the expression Expr of N. --------------------------------------------- -- Error_Dim_Msg_For_Component_Declaration -- --------------------------------------------- procedure Error_Dim_Msg_For_Component_Declaration (N : Node_Id; Etyp : Entity_Id; Expr : Node_Id) is begin Error_Msg_N ("dimensions mismatch in component declaration", N); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Etyp) & ", found " & Dimensions_Msg_Of (Expr), Expr); end Error_Dim_Msg_For_Component_Declaration; -- Start of processing for Analyze_Dimension_Component_Declaration begin -- Expression is present if Present (Expr) then Dims_Of_Expr := Dimensions_Of (Expr); -- Check dimensions match if Dims_Of_Etyp /= Dims_Of_Expr then -- Numeric literal case. Issue a warning if the object type is not -- dimensionless to indicate the literal is treated as if its -- dimension matches the type dimension. if Nkind (Original_Node (Expr)) in N_Real_Literal | N_Integer_Literal then Dim_Warning_For_Numeric_Literal (Expr, Etyp); -- Issue a dimension mismatch error for all other cases else Error_Dim_Msg_For_Component_Declaration (N, Etyp, Expr); end if; end if; end if; end Analyze_Dimension_Component_Declaration; ------------------------------------------------- -- Analyze_Dimension_Extended_Return_Statement -- ------------------------------------------------- procedure Analyze_Dimension_Extended_Return_Statement (N : Node_Id) is Return_Ent : constant Entity_Id := Return_Statement_Entity (N); Return_Etyp : constant Entity_Id := Etype (Return_Applies_To (Return_Ent)); Return_Obj_Decls : constant List_Id := Return_Object_Declarations (N); Return_Obj_Decl : Node_Id; Return_Obj_Id : Entity_Id; Return_Obj_Typ : Entity_Id; procedure Error_Dim_Msg_For_Extended_Return_Statement (N : Node_Id; Return_Etyp : Entity_Id; Return_Obj_Typ : Entity_Id); -- Error using Error_Msg_N at node N. Output dimensions of the returned -- type Return_Etyp and the returned object type Return_Obj_Typ of N. ------------------------------------------------- -- Error_Dim_Msg_For_Extended_Return_Statement -- ------------------------------------------------- procedure Error_Dim_Msg_For_Extended_Return_Statement (N : Node_Id; Return_Etyp : Entity_Id; Return_Obj_Typ : Entity_Id) is begin Error_Msg_N ("dimensions mismatch in extended return statement", N); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Return_Etyp) & ", found " & Dimensions_Msg_Of (Return_Obj_Typ), N); end Error_Dim_Msg_For_Extended_Return_Statement; -- Start of processing for Analyze_Dimension_Extended_Return_Statement begin if Present (Return_Obj_Decls) then Return_Obj_Decl := First (Return_Obj_Decls); while Present (Return_Obj_Decl) loop if Nkind (Return_Obj_Decl) = N_Object_Declaration then Return_Obj_Id := Defining_Identifier (Return_Obj_Decl); if Is_Return_Object (Return_Obj_Id) then Return_Obj_Typ := Etype (Return_Obj_Id); -- Issue an error message if dimensions mismatch if Dimensions_Of (Return_Etyp) /= Dimensions_Of (Return_Obj_Typ) then Error_Dim_Msg_For_Extended_Return_Statement (N, Return_Etyp, Return_Obj_Typ); return; end if; end if; end if; Next (Return_Obj_Decl); end loop; end if; end Analyze_Dimension_Extended_Return_Statement; ----------------------------------------------------- -- Analyze_Dimension_Extension_Or_Record_Aggregate -- ----------------------------------------------------- procedure Analyze_Dimension_Extension_Or_Record_Aggregate (N : Node_Id) is Comp : Node_Id; Comp_Id : Entity_Id; Comp_Typ : Entity_Id; Expr : Node_Id; Error_Detected : Boolean := False; -- This flag is used in order to indicate if an error has been detected -- so far by the compiler in this routine. begin -- Aspect is an Ada 2012 feature. Note that there is no need to check -- dimensions in inlined bodies, or for aggregates that don't come -- from source, or if we are within an initialization procedure, whose -- expressions have been checked at the point of record declaration. if Ada_Version < Ada_2012 or else In_Inlined_Body or else not Comes_From_Source (N) or else Inside_Init_Proc then return; end if; Comp := First (Component_Associations (N)); while Present (Comp) loop Comp_Id := Entity (First (Choices (Comp))); Comp_Typ := Etype (Comp_Id); -- Check the component type is either a dimensioned type or a -- dimensioned subtype. if Has_Dimension_System (Base_Type (Comp_Typ)) then Expr := Expression (Comp); -- A box-initialized component needs no checking. if No (Expr) and then Box_Present (Comp) then null; -- Issue an error if the dimensions of the component type and the -- dimensions of the component mismatch. elsif Dimensions_Of (Expr) /= Dimensions_Of (Comp_Typ) then -- Check if an error has already been encountered so far if not Error_Detected then -- Extension aggregate case if Nkind (N) = N_Extension_Aggregate then Error_Msg_N ("dimensions mismatch in extension aggregate", N); -- Record aggregate case else Error_Msg_N ("dimensions mismatch in record aggregate", N); end if; Error_Detected := True; end if; Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Comp_Typ) & ", found " & Dimensions_Msg_Of (Expr), Comp); end if; end if; Next (Comp); end loop; end Analyze_Dimension_Extension_Or_Record_Aggregate; ------------------------------- -- Analyze_Dimension_Formals -- ------------------------------- procedure Analyze_Dimension_Formals (N : Node_Id; Formals : List_Id) is Dims_Of_Typ : Dimension_Type; Formal : Node_Id; Typ : Entity_Id; begin -- Aspect is an Ada 2012 feature. Note that there is no need to check -- dimensions for sub specs that don't come from source. if Ada_Version < Ada_2012 or else not Comes_From_Source (N) then return; end if; Formal := First (Formals); while Present (Formal) loop Typ := Parameter_Type (Formal); Dims_Of_Typ := Dimensions_Of (Typ); if Exists (Dims_Of_Typ) then declare Expr : constant Node_Id := Expression (Formal); begin -- Issue a warning if Expr is a numeric literal and if its -- dimensions differ with the dimensions of the formal type. if Present (Expr) and then Dims_Of_Typ /= Dimensions_Of (Expr) and then Nkind (Original_Node (Expr)) in N_Real_Literal | N_Integer_Literal then Dim_Warning_For_Numeric_Literal (Expr, Etype (Typ)); end if; end; end if; Next (Formal); end loop; end Analyze_Dimension_Formals; --------------------------------- -- Analyze_Dimension_Has_Etype -- --------------------------------- procedure Analyze_Dimension_Has_Etype (N : Node_Id) is Etyp : constant Entity_Id := Etype (N); Dims_Of_Etyp : Dimension_Type := Dimensions_Of (Etyp); begin -- General case. Propagation of the dimensions from the type if Exists (Dims_Of_Etyp) then Set_Dimensions (N, Dims_Of_Etyp); -- Identifier case. Propagate the dimensions from the entity for -- identifier whose entity is a non-dimensionless constant. elsif Nkind (N) = N_Identifier then Analyze_Dimension_Identifier : declare Id : constant Entity_Id := Entity (N); begin -- If Id is missing, abnormal tree, assume previous error if No (Id) then Check_Error_Detected; return; elsif Ekind (Id) in E_Constant | E_Named_Real and then Exists (Dimensions_Of (Id)) then Set_Dimensions (N, Dimensions_Of (Id)); end if; end Analyze_Dimension_Identifier; -- Attribute reference case. Propagate the dimensions from the prefix. elsif Nkind (N) = N_Attribute_Reference and then Has_Dimension_System (Base_Type (Etyp)) then Dims_Of_Etyp := Dimensions_Of (Prefix (N)); -- Check the prefix is not dimensionless if Exists (Dims_Of_Etyp) then Set_Dimensions (N, Dims_Of_Etyp); end if; end if; -- Remove dimensions from inner expressions, to prevent dimensions -- table from growing uselessly. case Nkind (N) is when N_Attribute_Reference | N_Indexed_Component => declare Exprs : constant List_Id := Expressions (N); Expr : Node_Id; begin if Present (Exprs) then Expr := First (Exprs); while Present (Expr) loop Remove_Dimensions (Expr); Next (Expr); end loop; end if; end; when N_Qualified_Expression | N_Type_Conversion | N_Unchecked_Type_Conversion => Remove_Dimensions (Expression (N)); when N_Selected_Component => Remove_Dimensions (Selector_Name (N)); when others => null; end case; end Analyze_Dimension_Has_Etype; ------------------------------------- -- Analyze_Dimension_If_Expression -- ------------------------------------- procedure Analyze_Dimension_If_Expression (N : Node_Id) is Then_Expr : constant Node_Id := Next (First (Expressions (N))); Else_Expr : constant Node_Id := Next (Then_Expr); begin if Dimensions_Of (Then_Expr) /= Dimensions_Of (Else_Expr) then Error_Msg_N ("dimensions mismatch in conditional expression", N); else Copy_Dimensions (Then_Expr, N); end if; end Analyze_Dimension_If_Expression; ------------------------------------------ -- Analyze_Dimension_Number_Declaration -- ------------------------------------------ procedure Analyze_Dimension_Number_Declaration (N : Node_Id) is Expr : constant Node_Id := Expression (N); Id : constant Entity_Id := Defining_Identifier (N); Dim_Of_Expr : constant Dimension_Type := Dimensions_Of (Expr); begin if Exists (Dim_Of_Expr) then Set_Dimensions (Id, Dim_Of_Expr); Set_Etype (Id, Etype (Expr)); end if; end Analyze_Dimension_Number_Declaration; ------------------------------------------ -- Analyze_Dimension_Object_Declaration -- ------------------------------------------ procedure Analyze_Dimension_Object_Declaration (N : Node_Id) is Expr : constant Node_Id := Expression (N); Id : constant Entity_Id := Defining_Identifier (N); Etyp : constant Entity_Id := Etype (Id); Dim_Of_Etyp : constant Dimension_Type := Dimensions_Of (Etyp); Dim_Of_Expr : Dimension_Type; procedure Error_Dim_Msg_For_Object_Declaration (N : Node_Id; Etyp : Entity_Id; Expr : Node_Id); -- Error using Error_Msg_N at node N. Output the dimensions of the -- type Etyp and of the expression Expr. ------------------------------------------ -- Error_Dim_Msg_For_Object_Declaration -- ------------------------------------------ procedure Error_Dim_Msg_For_Object_Declaration (N : Node_Id; Etyp : Entity_Id; Expr : Node_Id) is begin Error_Msg_N ("dimensions mismatch in object declaration", N); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Etyp) & ", found " & Dimensions_Msg_Of (Expr), Expr); end Error_Dim_Msg_For_Object_Declaration; -- Start of processing for Analyze_Dimension_Object_Declaration begin -- Expression is present if Present (Expr) then Dim_Of_Expr := Dimensions_Of (Expr); -- Check dimensions match if Dim_Of_Expr /= Dim_Of_Etyp then -- Numeric literal case. Issue a warning if the object type is -- not dimensionless to indicate the literal is treated as if -- its dimension matches the type dimension. if Nkind (Original_Node (Expr)) in N_Real_Literal | N_Integer_Literal then Dim_Warning_For_Numeric_Literal (Expr, Etyp); -- Case of object is a constant whose type is a dimensioned type elsif Constant_Present (N) and then not Exists (Dim_Of_Etyp) then -- Propagate dimension from expression to object entity Set_Dimensions (Id, Dim_Of_Expr); -- Expression may have been constant-folded. If nominal type has -- dimensions, verify that expression has same type. elsif Exists (Dim_Of_Etyp) and then Etype (Expr) = Etyp then null; -- For all other cases, issue an error message else Error_Dim_Msg_For_Object_Declaration (N, Etyp, Expr); end if; end if; -- Remove dimensions in expression after checking consistency with -- given type. Remove_Dimensions (Expr); end if; end Analyze_Dimension_Object_Declaration; --------------------------------------------------- -- Analyze_Dimension_Object_Renaming_Declaration -- --------------------------------------------------- procedure Analyze_Dimension_Object_Renaming_Declaration (N : Node_Id) is Renamed_Name : constant Node_Id := Name (N); Sub_Mark : constant Node_Id := Subtype_Mark (N); procedure Error_Dim_Msg_For_Object_Renaming_Declaration (N : Node_Id; Sub_Mark : Node_Id; Renamed_Name : Node_Id); -- Error using Error_Msg_N at node N. Output the dimensions of -- Sub_Mark and of Renamed_Name. --------------------------------------------------- -- Error_Dim_Msg_For_Object_Renaming_Declaration -- --------------------------------------------------- procedure Error_Dim_Msg_For_Object_Renaming_Declaration (N : Node_Id; Sub_Mark : Node_Id; Renamed_Name : Node_Id) is begin Error_Msg_N ("dimensions mismatch in object renaming declaration", N); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Sub_Mark) & ", found " & Dimensions_Msg_Of (Renamed_Name), Renamed_Name); end Error_Dim_Msg_For_Object_Renaming_Declaration; -- Start of processing for Analyze_Dimension_Object_Renaming_Declaration begin if Dimensions_Of (Renamed_Name) /= Dimensions_Of (Sub_Mark) then Error_Dim_Msg_For_Object_Renaming_Declaration (N, Sub_Mark, Renamed_Name); end if; end Analyze_Dimension_Object_Renaming_Declaration; ----------------------------------------------- -- Analyze_Dimension_Simple_Return_Statement -- ----------------------------------------------- procedure Analyze_Dimension_Simple_Return_Statement (N : Node_Id) is Expr : constant Node_Id := Expression (N); Return_Ent : constant Entity_Id := Return_Statement_Entity (N); Return_Etyp : constant Entity_Id := Etype (Return_Applies_To (Return_Ent)); Dims_Of_Return_Etyp : constant Dimension_Type := Dimensions_Of (Return_Etyp); procedure Error_Dim_Msg_For_Simple_Return_Statement (N : Node_Id; Return_Etyp : Entity_Id; Expr : Node_Id); -- Error using Error_Msg_N at node N. Output the dimensions of the -- returned type Return_Etyp and the returned expression Expr of N. ----------------------------------------------- -- Error_Dim_Msg_For_Simple_Return_Statement -- ----------------------------------------------- procedure Error_Dim_Msg_For_Simple_Return_Statement (N : Node_Id; Return_Etyp : Entity_Id; Expr : Node_Id) is begin Error_Msg_N ("dimensions mismatch in return statement", N); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Return_Etyp) & ", found " & Dimensions_Msg_Of (Expr), Expr); end Error_Dim_Msg_For_Simple_Return_Statement; -- Start of processing for Analyze_Dimension_Simple_Return_Statement begin if Dims_Of_Return_Etyp /= Dimensions_Of (Expr) then Error_Dim_Msg_For_Simple_Return_Statement (N, Return_Etyp, Expr); Remove_Dimensions (Expr); end if; end Analyze_Dimension_Simple_Return_Statement; ------------------------------------------- -- Analyze_Dimension_Subtype_Declaration -- ------------------------------------------- procedure Analyze_Dimension_Subtype_Declaration (N : Node_Id) is Id : constant Entity_Id := Defining_Identifier (N); Dims_Of_Id : constant Dimension_Type := Dimensions_Of (Id); Dims_Of_Etyp : Dimension_Type; Etyp : Node_Id; begin -- No constraint case in subtype declaration if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then Etyp := Etype (Subtype_Indication (N)); Dims_Of_Etyp := Dimensions_Of (Etyp); if Exists (Dims_Of_Etyp) then -- If subtype already has a dimension (from Aspect_Dimension), it -- cannot inherit different dimensions from its subtype. if Exists (Dims_Of_Id) and then Dims_Of_Etyp /= Dims_Of_Id then Error_Msg_NE ("subtype& already " & Dimensions_Msg_Of (Id, True), N, Id); else Set_Dimensions (Id, Dims_Of_Etyp); Set_Symbol (Id, Symbol_Of (Etyp)); end if; end if; -- Constraint present in subtype declaration else Etyp := Etype (Subtype_Mark (Subtype_Indication (N))); Dims_Of_Etyp := Dimensions_Of (Etyp); if Exists (Dims_Of_Etyp) then Set_Dimensions (Id, Dims_Of_Etyp); Set_Symbol (Id, Symbol_Of (Etyp)); end if; end if; end Analyze_Dimension_Subtype_Declaration; --------------------------------------- -- Analyze_Dimension_Type_Conversion -- --------------------------------------- procedure Analyze_Dimension_Type_Conversion (N : Node_Id) is Expr_Root : constant Entity_Id := Dimension_System_Root (Etype (Expression (N))); Target_Root : constant Entity_Id := Dimension_System_Root (Etype (N)); begin -- If the expression has dimensions and the target type has dimensions, -- the conversion has the dimensions of the expression. Consistency is -- checked below. Converting to a non-dimensioned type such as Float -- ignores the dimensions of the expression. if Exists (Dimensions_Of (Expression (N))) and then Present (Target_Root) then Set_Dimensions (N, Dimensions_Of (Expression (N))); -- Otherwise the dimensions are those of the target type. else Analyze_Dimension_Has_Etype (N); end if; -- A conversion between types in different dimension systems (e.g. MKS -- and British units) must respect the dimensions of expression and -- type, It is up to the user to provide proper conversion factors. -- Upward conversions to root type of a dimensioned system are legal, -- and correspond to "view conversions", i.e. preserve the dimensions -- of the expression; otherwise conversion must be between types with -- then same dimensions. Conversions to a non-dimensioned type such as -- Float lose the dimensions of the expression. if Present (Expr_Root) and then Present (Target_Root) and then Etype (N) /= Target_Root and then Dimensions_Of (Expression (N)) /= Dimensions_Of (Etype (N)) then Error_Msg_N ("dimensions mismatch in conversion", N); Error_Msg_N ("\expression " & Dimensions_Msg_Of (Expression (N), True), N); Error_Msg_N ("\target type " & Dimensions_Msg_Of (Etype (N), True), N); end if; end Analyze_Dimension_Type_Conversion; -------------------------------- -- Analyze_Dimension_Unary_Op -- -------------------------------- procedure Analyze_Dimension_Unary_Op (N : Node_Id) is begin case Nkind (N) is -- Propagate the dimension if the operand is not dimensionless when N_Op_Abs | N_Op_Minus | N_Op_Plus => declare R : constant Node_Id := Right_Opnd (N); begin Move_Dimensions (R, N); end; when others => null; end case; end Analyze_Dimension_Unary_Op; --------------------------------- -- Check_Expression_Dimensions -- --------------------------------- procedure Check_Expression_Dimensions (Expr : Node_Id; Typ : Entity_Id) is begin if Is_Floating_Point_Type (Etype (Expr)) then Analyze_Dimension (Expr); if Dimensions_Of (Expr) /= Dimensions_Of (Typ) then Error_Msg_N ("dimensions mismatch in array aggregate", Expr); Error_Msg_N ("\expected dimension " & Dimensions_Msg_Of (Typ) & ", found " & Dimensions_Msg_Of (Expr), Expr); end if; end if; end Check_Expression_Dimensions; --------------------- -- Copy_Dimensions -- --------------------- procedure Copy_Dimensions (From : Node_Id; To : Node_Id) is Dims_Of_From : constant Dimension_Type := Dimensions_Of (From); begin -- Ignore if not Ada 2012 or beyond if Ada_Version < Ada_2012 then return; -- For Ada 2012, Copy the dimension of 'From to 'To' elsif Exists (Dims_Of_From) then Set_Dimensions (To, Dims_Of_From); end if; end Copy_Dimensions; ----------------------------------- -- Copy_Dimensions_Of_Components -- ----------------------------------- procedure Copy_Dimensions_Of_Components (Rec : Entity_Id) is C : Entity_Id; begin C := First_Component (Rec); while Present (C) loop if Nkind (Parent (C)) = N_Component_Declaration then Copy_Dimensions (Expression (Parent (Corresponding_Record_Component (C))), Expression (Parent (C))); end if; Next_Component (C); end loop; end Copy_Dimensions_Of_Components; -------------------------- -- Create_Rational_From -- -------------------------- -- RATIONAL ::= [-] NUMERAL [/ NUMERAL] -- A rational number is a number that can be expressed as the quotient or -- fraction a/b of two integers, where b is non-zero positive. function Create_Rational_From (Expr : Node_Id; Complain : Boolean) return Rational is Or_Node_Of_Expr : constant Node_Id := Original_Node (Expr); Result : Rational := No_Rational; function Process_Minus (N : Node_Id) return Rational; -- Create a rational from a N_Op_Minus node function Process_Divide (N : Node_Id) return Rational; -- Create a rational from a N_Op_Divide node function Process_Literal (N : Node_Id) return Rational; -- Create a rational from a N_Integer_Literal node ------------------- -- Process_Minus -- ------------------- function Process_Minus (N : Node_Id) return Rational is Right : constant Node_Id := Original_Node (Right_Opnd (N)); Result : Rational; begin -- Operand is an integer literal if Nkind (Right) = N_Integer_Literal then Result := -Process_Literal (Right); -- Operand is a divide operator elsif Nkind (Right) = N_Op_Divide then Result := -Process_Divide (Right); else Result := No_Rational; end if; return Result; end Process_Minus; -------------------- -- Process_Divide -- -------------------- function Process_Divide (N : Node_Id) return Rational is Left : constant Node_Id := Original_Node (Left_Opnd (N)); Right : constant Node_Id := Original_Node (Right_Opnd (N)); Left_Rat : Rational; Result : Rational := No_Rational; Right_Rat : Rational; begin -- Both left and right operands are integer literals if Nkind (Left) = N_Integer_Literal and then Nkind (Right) = N_Integer_Literal then Left_Rat := Process_Literal (Left); Right_Rat := Process_Literal (Right); Result := Left_Rat / Right_Rat; end if; return Result; end Process_Divide; --------------------- -- Process_Literal -- --------------------- function Process_Literal (N : Node_Id) return Rational is begin return +Whole (UI_To_Int (Intval (N))); end Process_Literal; -- Start of processing for Create_Rational_From begin -- Check the expression is either a division of two integers or an -- integer itself. Note that the check applies to the original node -- since the node could have already been rewritten. -- Integer literal case if Nkind (Or_Node_Of_Expr) = N_Integer_Literal then Result := Process_Literal (Or_Node_Of_Expr); -- Divide operator case elsif Nkind (Or_Node_Of_Expr) = N_Op_Divide then Result := Process_Divide (Or_Node_Of_Expr); -- Minus operator case elsif Nkind (Or_Node_Of_Expr) = N_Op_Minus then Result := Process_Minus (Or_Node_Of_Expr); end if; -- When Expr cannot be interpreted as a rational and Complain is true, -- generate an error message. if Complain and then Result = No_Rational then Error_Msg_N ("rational expected", Expr); end if; return Result; end Create_Rational_From; ------------------- -- Dimensions_Of -- ------------------- function Dimensions_Of (N : Node_Id) return Dimension_Type is begin return Dimension_Table.Get (N); end Dimensions_Of; ----------------------- -- Dimensions_Msg_Of -- ----------------------- function Dimensions_Msg_Of (N : Node_Id; Description_Needed : Boolean := False) return String is Dims_Of_N : constant Dimension_Type := Dimensions_Of (N); Dimensions_Msg : Name_Id; System : System_Type; begin -- Initialization of Name_Buffer Name_Len := 0; -- N is not dimensionless if Exists (Dims_Of_N) then System := System_Of (Base_Type (Etype (N))); -- When Description_Needed, add to string "has dimension " before the -- actual dimension. if Description_Needed then Add_Str_To_Name_Buffer ("has dimension "); end if; Append (Global_Name_Buffer, From_Dim_To_Str_Of_Dim_Symbols (Dims_Of_N, System, True)); -- N is dimensionless -- When Description_Needed, return "is dimensionless" elsif Description_Needed then Add_Str_To_Name_Buffer ("is dimensionless"); -- Otherwise, return "'[']" else Add_Str_To_Name_Buffer ("'[']"); end if; Dimensions_Msg := Name_Find; return Get_Name_String (Dimensions_Msg); end Dimensions_Msg_Of; -------------------------- -- Dimension_Table_Hash -- -------------------------- function Dimension_Table_Hash (Key : Node_Id) return Dimension_Table_Range is begin return Dimension_Table_Range (Key mod 511); end Dimension_Table_Hash; ------------------------------------- -- Dim_Warning_For_Numeric_Literal -- ------------------------------------- procedure Dim_Warning_For_Numeric_Literal (N : Node_Id; Typ : Entity_Id) is begin -- Consider the literal zero (integer 0 or real 0.0) to be of any -- dimension. case Nkind (Original_Node (N)) is when N_Real_Literal => if Expr_Value_R (N) = Ureal_0 then return; end if; when N_Integer_Literal => if Expr_Value (N) = Uint_0 then return; end if; when others => null; end case; -- Initialize name buffer Name_Len := 0; Append (Global_Name_Buffer, String_From_Numeric_Literal (N)); -- Insert a blank between the literal and the symbol Add_Str_To_Name_Buffer (" "); Append (Global_Name_Buffer, Symbol_Of (Typ)); Error_Msg_Name_1 := Name_Find; Error_Msg_N ("assumed to be%%??", N); end Dim_Warning_For_Numeric_Literal; ---------------------- -- Dimensions_Match -- ---------------------- function Dimensions_Match (T1 : Entity_Id; T2 : Entity_Id) return Boolean is begin return not Has_Dimension_System (Base_Type (T1)) or else Dimensions_Of (T1) = Dimensions_Of (T2); end Dimensions_Match; --------------------------- -- Dimension_System_Root -- --------------------------- function Dimension_System_Root (T : Entity_Id) return Entity_Id is Root : Entity_Id; begin Root := Base_Type (T); if Has_Dimension_System (Root) then return First_Subtype (Root); -- for example Dim_Mks else return Empty; end if; end Dimension_System_Root; ---------------------------------------- -- Eval_Op_Expon_For_Dimensioned_Type -- ---------------------------------------- -- Evaluate the expon operator for real dimensioned type. -- Note that if the exponent is an integer (denominator = 1) the node is -- evaluated by the regular Eval_Op_Expon routine (see Sem_Eval). procedure Eval_Op_Expon_For_Dimensioned_Type (N : Node_Id; Btyp : Entity_Id) is R : constant Node_Id := Right_Opnd (N); R_Value : Rational := No_Rational; begin if Is_Real_Type (Btyp) then R_Value := Create_Rational_From (R, False); end if; -- Check that the exponent is not an integer if R_Value /= No_Rational and then R_Value.Denominator /= 1 then Eval_Op_Expon_With_Rational_Exponent (N, R_Value); else Eval_Op_Expon (N); end if; end Eval_Op_Expon_For_Dimensioned_Type; ------------------------------------------ -- Eval_Op_Expon_With_Rational_Exponent -- ------------------------------------------ -- For dimensioned operand in exponentiation, exponent is allowed to be a -- Rational and not only an Integer like for dimensionless operands. For -- that particular case, the left operand is rewritten as a function call -- using the function Expon_LLF from s-llflex.ads. procedure Eval_Op_Expon_With_Rational_Exponent (N : Node_Id; Exponent_Value : Rational) is Loc : constant Source_Ptr := Sloc (N); Dims_Of_N : constant Dimension_Type := Dimensions_Of (N); L : constant Node_Id := Left_Opnd (N); Etyp_Of_L : constant Entity_Id := Etype (L); Btyp_Of_L : constant Entity_Id := Base_Type (Etyp_Of_L); Actual_1 : Node_Id; Actual_2 : Node_Id; Dim_Power : Rational; List_Of_Dims : List_Id; New_Aspect : Node_Id; New_Aspects : List_Id; New_Id : Entity_Id; New_N : Node_Id; New_Subtyp_Decl_For_L : Node_Id; System : System_Type; begin -- Case when the operand is not dimensionless if Exists (Dims_Of_N) then -- Get the corresponding System_Type to know the exact number of -- dimensions in the system. System := System_Of (Btyp_Of_L); -- Generation of a new subtype with the proper dimensions -- In order to rewrite the operator as a type conversion, a new -- dimensioned subtype with the resulting dimensions of the -- exponentiation must be created. -- Generate: -- Btyp_Of_L : constant Entity_Id := Base_Type (Etyp_Of_L); -- System : constant System_Id := -- Get_Dimension_System_Id (Btyp_Of_L); -- Num_Of_Dims : constant Number_Of_Dimensions := -- Dimension_Systems.Table (System).Dimension_Count; -- subtype T is Btyp_Of_L -- with -- Dimension => ( -- Dims_Of_N (1).Numerator / Dims_Of_N (1).Denominator, -- Dims_Of_N (2).Numerator / Dims_Of_N (2).Denominator, -- ... -- Dims_Of_N (Num_Of_Dims).Numerator / -- Dims_Of_N (Num_Of_Dims).Denominator); -- Step 1: Generate the new aggregate for the aspect Dimension New_Aspects := Empty_List; List_Of_Dims := New_List; for Position in Dims_Of_N'First .. System.Count loop Dim_Power := Dims_Of_N (Position); Append_To (List_Of_Dims, Make_Op_Divide (Loc, Left_Opnd => Make_Integer_Literal (Loc, Int (Dim_Power.Numerator)), Right_Opnd => Make_Integer_Literal (Loc, Int (Dim_Power.Denominator)))); end loop; -- Step 2: Create the new Aspect Specification for Aspect Dimension New_Aspect := Make_Aspect_Specification (Loc, Identifier => Make_Identifier (Loc, Name_Dimension), Expression => Make_Aggregate (Loc, Expressions => List_Of_Dims)); -- Step 3: Make a temporary identifier for the new subtype New_Id := Make_Temporary (Loc, 'T'); Set_Is_Internal (New_Id); -- Step 4: Declaration of the new subtype New_Subtyp_Decl_For_L := Make_Subtype_Declaration (Loc, Defining_Identifier => New_Id, Subtype_Indication => New_Occurrence_Of (Btyp_Of_L, Loc)); Append (New_Aspect, New_Aspects); Set_Parent (New_Aspects, New_Subtyp_Decl_For_L); Set_Aspect_Specifications (New_Subtyp_Decl_For_L, New_Aspects); Analyze (New_Subtyp_Decl_For_L); -- Case where the operand is dimensionless else New_Id := Btyp_Of_L; end if; -- Replacement of N by New_N -- Generate: -- Actual_1 := Long_Long_Float (L), -- Actual_2 := Long_Long_Float (Exponent_Value.Numerator) / -- Long_Long_Float (Exponent_Value.Denominator); -- (T (Expon_LLF (Actual_1, Actual_2))); -- where T is the subtype declared in step 1 -- The node is rewritten as a type conversion -- Step 1: Creation of the two parameters of Expon_LLF function call Actual_1 := Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Standard_Long_Long_Float, Loc), Expression => Relocate_Node (L)); Actual_2 := Make_Op_Divide (Loc, Left_Opnd => Make_Real_Literal (Loc, UR_From_Uint (UI_From_Int (Int (Exponent_Value.Numerator)))), Right_Opnd => Make_Real_Literal (Loc, UR_From_Uint (UI_From_Int (Int (Exponent_Value.Denominator))))); -- Step 2: Creation of New_N New_N := Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (New_Id, Loc), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Expon_LLF), Loc), Parameter_Associations => New_List ( Actual_1, Actual_2))); -- Step 3: Rewrite N with the result Rewrite (N, New_N); Set_Etype (N, New_Id); Analyze_And_Resolve (N, New_Id); end Eval_Op_Expon_With_Rational_Exponent; ------------ -- Exists -- ------------ function Exists (Dim : Dimension_Type) return Boolean is begin return Dim /= Null_Dimension; end Exists; function Exists (Str : String_Id) return Boolean is begin return Str /= No_String; end Exists; function Exists (Sys : System_Type) return Boolean is begin return Sys /= Null_System; end Exists; --------------------------------- -- Expand_Put_Call_With_Symbol -- --------------------------------- -- For procedure Put (resp. Put_Dim_Of) and function Image, defined in -- System.Dim.Float_IO or System.Dim.Integer_IO, the default string -- parameter is rewritten to include the unit symbol (or the dimension -- symbols if not a defined quantity) in the output of a dimensioned -- object. If a value is already supplied by the user for the parameter -- Symbol, it is used as is. -- Case 1. Item is dimensionless -- * Put : Item appears without a suffix -- * Put_Dim_Of : the output is [] -- Obj : Mks_Type := 2.6; -- Put (Obj, 1, 1, 0); -- Put_Dim_Of (Obj); -- The corresponding outputs are: -- $2.6 -- $[] -- Case 2. Item has a dimension -- * Put : If the type of Item is a dimensioned subtype whose -- symbol is not empty, then the symbol appears as a -- suffix. Otherwise, a new string is created and appears -- as a suffix of Item. This string results in the -- successive concatanations between each unit symbol -- raised by its corresponding dimension power from the -- dimensions of Item. -- * Put_Dim_Of : The output is a new string resulting in the successive -- concatanations between each dimension symbol raised by -- its corresponding dimension power from the dimensions of -- Item. -- subtype Random is Mks_Type -- with -- Dimension => ( -- Meter => 3, -- Candela => -1, -- others => 0); -- Obj : Random := 5.0; -- Put (Obj); -- Put_Dim_Of (Obj); -- The corresponding outputs are: -- $5.0 m**3.cd**(-1) -- $[l**3.J**(-1)] -- The function Image returns the string identical to that produced by -- a call to Put whose first parameter is a string. procedure Expand_Put_Call_With_Symbol (N : Node_Id) is Actuals : constant List_Id := Parameter_Associations (N); Loc : constant Source_Ptr := Sloc (N); Name_Call : constant Node_Id := Name (N); New_Actuals : constant List_Id := New_List; Actual : Node_Id; Dims_Of_Actual : Dimension_Type; Etyp : Entity_Id; New_Str_Lit : Node_Id := Empty; Symbols : String_Id; Is_Put_Dim_Of : Boolean := False; -- This flag is used in order to differentiate routines Put and -- Put_Dim_Of. Set to True if the procedure is one of the Put_Dim_Of -- defined in System.Dim.Float_IO or System.Dim.Integer_IO. function Has_Symbols return Boolean; -- Return True if the current Put call already has a parameter -- association for parameter "Symbols" with the correct string of -- symbols. function Is_Procedure_Put_Call return Boolean; -- Return True if the current call is a call of an instantiation of a -- procedure Put defined in the package System.Dim.Float_IO and -- System.Dim.Integer_IO. function Item_Actual return Node_Id; -- Return the item actual parameter node in the output call ----------------- -- Has_Symbols -- ----------------- function Has_Symbols return Boolean is Actual : Node_Id; Actual_Str : Node_Id; begin -- Look for a symbols parameter association in the list of actuals Actual := First (Actuals); while Present (Actual) loop -- Positional parameter association case when the actual is a -- string literal. if Nkind (Actual) = N_String_Literal then Actual_Str := Actual; -- Named parameter association case when selector name is Symbol elsif Nkind (Actual) = N_Parameter_Association and then Chars (Selector_Name (Actual)) = Name_Symbol then Actual_Str := Explicit_Actual_Parameter (Actual); -- Ignore all other cases else Actual_Str := Empty; end if; if Present (Actual_Str) then -- Return True if the actual comes from source or if the string -- of symbols doesn't have the default value (i.e. it is ""), -- in which case it is used as suffix of the generated string. if Comes_From_Source (Actual) or else String_Length (Strval (Actual_Str)) /= 0 then return True; else return False; end if; end if; Next (Actual); end loop; -- At this point, the call has no parameter association. Look to the -- last actual since the symbols parameter is the last one. return Nkind (Last (Actuals)) = N_String_Literal; end Has_Symbols; --------------------------- -- Is_Procedure_Put_Call -- --------------------------- function Is_Procedure_Put_Call return Boolean is Ent : Entity_Id; Loc : Source_Ptr; begin -- There are three different Put (resp. Put_Dim_Of) routines in each -- generic dim IO package. Verify the current procedure call is one -- of them. if Is_Entity_Name (Name_Call) then Ent := Entity (Name_Call); -- Get the original subprogram entity following the renaming chain if Present (Alias (Ent)) then Ent := Alias (Ent); end if; Loc := Sloc (Ent); -- Check the name of the entity subprogram is Put (resp. -- Put_Dim_Of) and verify this entity is located in either -- System.Dim.Float_IO or System.Dim.Integer_IO. if Loc > No_Location and then Is_Dim_IO_Package_Entity (Cunit_Entity (Get_Source_Unit (Loc))) then if Chars (Ent) = Name_Put_Dim_Of then Is_Put_Dim_Of := True; return True; elsif Chars (Ent) = Name_Put or else Chars (Ent) = Name_Image then return True; end if; end if; end if; return False; end Is_Procedure_Put_Call; ----------------- -- Item_Actual -- ----------------- function Item_Actual return Node_Id is Actual : Node_Id; begin -- Look for the item actual as a parameter association Actual := First (Actuals); while Present (Actual) loop if Nkind (Actual) = N_Parameter_Association and then Chars (Selector_Name (Actual)) = Name_Item then return Explicit_Actual_Parameter (Actual); end if; Next (Actual); end loop; -- Case where the item has been defined without an association Actual := First (Actuals); -- Depending on the procedure Put, Item actual could be first or -- second in the list of actuals. if Has_Dimension_System (Base_Type (Etype (Actual))) then return Actual; else return Next (Actual); end if; end Item_Actual; -- Start of processing for Expand_Put_Call_With_Symbol begin if Is_Procedure_Put_Call and then not Has_Symbols then Actual := Item_Actual; Dims_Of_Actual := Dimensions_Of (Actual); Etyp := Etype (Actual); -- Put_Dim_Of case if Is_Put_Dim_Of then -- Check that the item is not dimensionless -- Create the new String_Literal with the new String_Id generated -- by the routine From_Dim_To_Str_Of_Dim_Symbols. if Exists (Dims_Of_Actual) then New_Str_Lit := Make_String_Literal (Loc, From_Dim_To_Str_Of_Dim_Symbols (Dims_Of_Actual, System_Of (Base_Type (Etyp)))); -- If dimensionless, the output is [] else New_Str_Lit := Make_String_Literal (Loc, "[]"); end if; -- Put case else -- Add the symbol as a suffix of the value if the subtype has a -- unit symbol or if the parameter is not dimensionless. if Exists (Symbol_Of (Etyp)) then Symbols := Symbol_Of (Etyp); else Symbols := From_Dim_To_Str_Of_Unit_Symbols (Dims_Of_Actual, System_Of (Base_Type (Etyp))); end if; -- Check Symbols exists if Exists (Symbols) then Start_String; -- Put a space between the value and the dimension Store_String_Char (' '); Store_String_Chars (Symbols); New_Str_Lit := Make_String_Literal (Loc, End_String); end if; end if; if Present (New_Str_Lit) then -- Insert all actuals in New_Actuals Actual := First (Actuals); while Present (Actual) loop -- Copy every actuals in New_Actuals except the Symbols -- parameter association. if Nkind (Actual) = N_Parameter_Association and then Chars (Selector_Name (Actual)) /= Name_Symbol then Append_To (New_Actuals, Make_Parameter_Association (Loc, Selector_Name => New_Copy (Selector_Name (Actual)), Explicit_Actual_Parameter => New_Copy (Explicit_Actual_Parameter (Actual)))); elsif Nkind (Actual) /= N_Parameter_Association then Append_To (New_Actuals, New_Copy (Actual)); end if; Next (Actual); end loop; -- Create new Symbols param association and append to New_Actuals Append_To (New_Actuals, Make_Parameter_Association (Loc, Selector_Name => Make_Identifier (Loc, Name_Symbol), Explicit_Actual_Parameter => New_Str_Lit)); -- Rewrite and analyze the procedure call if Chars (Name_Call) = Name_Image then Rewrite (N, Make_Function_Call (Loc, Name => New_Copy (Name_Call), Parameter_Associations => New_Actuals)); Analyze_And_Resolve (N); else Rewrite (N, Make_Procedure_Call_Statement (Loc, Name => New_Copy (Name_Call), Parameter_Associations => New_Actuals)); Analyze (N); end if; end if; end if; end Expand_Put_Call_With_Symbol; ------------------------------------ -- From_Dim_To_Str_Of_Dim_Symbols -- ------------------------------------ -- Given a dimension vector and the corresponding dimension system, create -- a String_Id to output dimension symbols corresponding to the dimensions -- Dims. If In_Error_Msg is True, there is a special handling for character -- asterisk * which is an insertion character in error messages. function From_Dim_To_Str_Of_Dim_Symbols (Dims : Dimension_Type; System : System_Type; In_Error_Msg : Boolean := False) return String_Id is Dim_Power : Rational; First_Dim : Boolean := True; procedure Store_String_Oexpon; -- Store the expon operator symbol "**" in the string. In error -- messages, asterisk * is a special character and must be quoted -- to be placed literally into the message. ------------------------- -- Store_String_Oexpon -- ------------------------- procedure Store_String_Oexpon is begin if In_Error_Msg then Store_String_Chars ("'*'*"); else Store_String_Chars ("**"); end if; end Store_String_Oexpon; -- Start of processing for From_Dim_To_Str_Of_Dim_Symbols begin -- Initialization of the new String_Id Start_String; -- Store the dimension symbols inside boxes if In_Error_Msg then Store_String_Chars ("'["); else Store_String_Char ('['); end if; for Position in Dimension_Type'Range loop Dim_Power := Dims (Position); if Dim_Power /= Zero then if First_Dim then First_Dim := False; else Store_String_Char ('.'); end if; Store_String_Chars (System.Dim_Symbols (Position)); -- Positive dimension case if Dim_Power.Numerator > 0 then -- Integer case if Dim_Power.Denominator = 1 then if Dim_Power.Numerator /= 1 then Store_String_Oexpon; Store_String_Int (Int (Dim_Power.Numerator)); end if; -- Rational case when denominator /= 1 else Store_String_Oexpon; Store_String_Char ('('); Store_String_Int (Int (Dim_Power.Numerator)); Store_String_Char ('/'); Store_String_Int (Int (Dim_Power.Denominator)); Store_String_Char (')'); end if; -- Negative dimension case else Store_String_Oexpon; Store_String_Char ('('); Store_String_Char ('-'); Store_String_Int (Int (-Dim_Power.Numerator)); -- Integer case if Dim_Power.Denominator = 1 then Store_String_Char (')'); -- Rational case when denominator /= 1 else Store_String_Char ('/'); Store_String_Int (Int (Dim_Power.Denominator)); Store_String_Char (')'); end if; end if; end if; end loop; if In_Error_Msg then Store_String_Chars ("']"); else Store_String_Char (']'); end if; return End_String; end From_Dim_To_Str_Of_Dim_Symbols; ------------------------------------- -- From_Dim_To_Str_Of_Unit_Symbols -- ------------------------------------- -- Given a dimension vector and the corresponding dimension system, -- create a String_Id to output the unit symbols corresponding to the -- dimensions Dims. function From_Dim_To_Str_Of_Unit_Symbols (Dims : Dimension_Type; System : System_Type) return String_Id is Dim_Power : Rational; First_Dim : Boolean := True; begin -- Return No_String if dimensionless if not Exists (Dims) then return No_String; end if; -- Initialization of the new String_Id Start_String; for Position in Dimension_Type'Range loop Dim_Power := Dims (Position); if Dim_Power /= Zero then if First_Dim then First_Dim := False; else Store_String_Char ('.'); end if; Store_String_Chars (System.Unit_Symbols (Position)); -- Positive dimension case if Dim_Power.Numerator > 0 then -- Integer case if Dim_Power.Denominator = 1 then if Dim_Power.Numerator /= 1 then Store_String_Chars ("**"); Store_String_Int (Int (Dim_Power.Numerator)); end if; -- Rational case when denominator /= 1 else Store_String_Chars ("**"); Store_String_Char ('('); Store_String_Int (Int (Dim_Power.Numerator)); Store_String_Char ('/'); Store_String_Int (Int (Dim_Power.Denominator)); Store_String_Char (')'); end if; -- Negative dimension case else Store_String_Chars ("**"); Store_String_Char ('('); Store_String_Char ('-'); Store_String_Int (Int (-Dim_Power.Numerator)); -- Integer case if Dim_Power.Denominator = 1 then Store_String_Char (')'); -- Rational case when denominator /= 1 else Store_String_Char ('/'); Store_String_Int (Int (Dim_Power.Denominator)); Store_String_Char (')'); end if; end if; end if; end loop; return End_String; end From_Dim_To_Str_Of_Unit_Symbols; --------- -- GCD -- --------- function GCD (Left, Right : Whole) return Int is L : Whole; R : Whole; begin L := Left; R := Right; while R /= 0 loop L := L mod R; if L = 0 then return Int (R); end if; R := R mod L; end loop; return Int (L); end GCD; -------------------------- -- Has_Dimension_System -- -------------------------- function Has_Dimension_System (Typ : Entity_Id) return Boolean is begin return Exists (System_Of (Typ)); end Has_Dimension_System; ------------------------------ -- Is_Dim_IO_Package_Entity -- ------------------------------ function Is_Dim_IO_Package_Entity (E : Entity_Id) return Boolean is begin -- Check the package entity corresponds to System.Dim.Float_IO or -- System.Dim.Integer_IO. return Is_RTU (E, System_Dim_Float_IO) or else Is_RTU (E, System_Dim_Integer_IO); end Is_Dim_IO_Package_Entity; ------------------------------------- -- Is_Dim_IO_Package_Instantiation -- ------------------------------------- function Is_Dim_IO_Package_Instantiation (N : Node_Id) return Boolean is Gen_Id : constant Node_Id := Name (N); begin -- Check that the instantiated package is either System.Dim.Float_IO -- or System.Dim.Integer_IO. return Is_Entity_Name (Gen_Id) and then Is_Dim_IO_Package_Entity (Entity (Gen_Id)); end Is_Dim_IO_Package_Instantiation; ---------------- -- Is_Invalid -- ---------------- function Is_Invalid (Position : Dimension_Position) return Boolean is begin return Position = Invalid_Position; end Is_Invalid; --------------------- -- Move_Dimensions -- --------------------- procedure Move_Dimensions (From, To : Node_Id) is begin if Ada_Version < Ada_2012 then return; end if; -- Copy the dimension of 'From to 'To' and remove dimension of 'From' Copy_Dimensions (From, To); Remove_Dimensions (From); end Move_Dimensions; --------------------------------------- -- New_Copy_Tree_And_Copy_Dimensions -- --------------------------------------- function New_Copy_Tree_And_Copy_Dimensions (Source : Node_Id; Map : Elist_Id := No_Elist; New_Sloc : Source_Ptr := No_Location; New_Scope : Entity_Id := Empty) return Node_Id is New_Copy : constant Node_Id := New_Copy_Tree (Source, Map, New_Sloc, New_Scope); begin -- Move the dimensions of Source to New_Copy Copy_Dimensions (Source, New_Copy); return New_Copy; end New_Copy_Tree_And_Copy_Dimensions; ------------ -- Reduce -- ------------ function Reduce (X : Rational) return Rational is begin if X.Numerator = 0 then return Zero; end if; declare G : constant Int := GCD (X.Numerator, X.Denominator); begin return Rational'(Numerator => Whole (Int (X.Numerator) / G), Denominator => Whole (Int (X.Denominator) / G)); end; end Reduce; ----------------------- -- Remove_Dimensions -- ----------------------- procedure Remove_Dimensions (N : Node_Id) is Dims_Of_N : constant Dimension_Type := Dimensions_Of (N); begin if Exists (Dims_Of_N) then Dimension_Table.Remove (N); end if; end Remove_Dimensions; ----------------------------------- -- Remove_Dimension_In_Statement -- ----------------------------------- -- Removal of dimension in statement as part of the Analyze_Statements -- routine (see package Sem_Ch5). procedure Remove_Dimension_In_Statement (Stmt : Node_Id) is begin if Ada_Version < Ada_2012 then return; end if; -- Remove dimension in parameter specifications for accept statement if Nkind (Stmt) = N_Accept_Statement then declare Param : Node_Id := First (Parameter_Specifications (Stmt)); begin while Present (Param) loop Remove_Dimensions (Param); Next (Param); end loop; end; -- Remove dimension of name and expression in assignments elsif Nkind (Stmt) = N_Assignment_Statement then Remove_Dimensions (Expression (Stmt)); Remove_Dimensions (Name (Stmt)); end if; end Remove_Dimension_In_Statement; -------------------- -- Set_Dimensions -- -------------------- procedure Set_Dimensions (N : Node_Id; Val : Dimension_Type) is begin pragma Assert (OK_For_Dimension (Nkind (N))); pragma Assert (Exists (Val)); Dimension_Table.Set (N, Val); end Set_Dimensions; ---------------- -- Set_Symbol -- ---------------- procedure Set_Symbol (E : Entity_Id; Val : String_Id) is begin Symbol_Table.Set (E, Val); end Set_Symbol; --------------- -- Symbol_Of -- --------------- function Symbol_Of (E : Entity_Id) return String_Id is Subtype_Symbol : constant String_Id := Symbol_Table.Get (E); begin if Subtype_Symbol /= No_String then return Subtype_Symbol; else return From_Dim_To_Str_Of_Unit_Symbols (Dimensions_Of (E), System_Of (Base_Type (E))); end if; end Symbol_Of; ----------------------- -- Symbol_Table_Hash -- ----------------------- function Symbol_Table_Hash (Key : Entity_Id) return Symbol_Table_Range is begin return Symbol_Table_Range (Key mod 511); end Symbol_Table_Hash; --------------- -- System_Of -- --------------- function System_Of (E : Entity_Id) return System_Type is Type_Decl : constant Node_Id := Parent (E); begin -- Look for Type_Decl in System_Table for Dim_Sys in 1 .. System_Table.Last loop if Type_Decl = System_Table.Table (Dim_Sys).Type_Decl then return System_Table.Table (Dim_Sys); end if; end loop; return Null_System; end System_Of; end Sem_Dim;
{ "source": "starcoderdata", "programming_language": "ada" }
-- ****h* Bases/BTrade -- FUNCTION -- Provide code for hiring recruits, buying recipes, heal and train crew -- members in bases. -- SOURCE package Bases.Trade is -- **** -- ****e* BTrade/BTrade.Trade_Already_Known -- FUNCTION -- Raised when player known selected recipe -- SOURCE Trade_Already_Known: exception; -- **** -- ****e* BTrade/BTrade.Trade_Cant_Heal -- FUNCTION -- Raised when no crew members are wounded -- SOURCE Trade_Cant_Heal: exception; -- **** -- ****f* BTrade/BTrade.HireRecruit -- FUNCTION -- Hire selected recruit from bases and add him/her to player ship crew -- PARAMETERS -- RecruitIndex - Index of recruit, from base recruits list to hire -- Cost - Cost of hire of selected recruit -- DailyPayment - Daily payment of selected recruit -- TradePayment - Percent of earnings from each trade which this recruit -- will take -- ContractLength - Length of the contract with this recruit in days. 0 -- means infinite contract -- SOURCE procedure HireRecruit (RecruitIndex: Recruit_Container.Extended_Index; Cost: Positive; DailyPayment, TradePayment: Natural; ContractLenght: Integer) with Test_Case => (Name => "Test_HireRecruit", Mode => Robustness); -- **** -- ****f* BTrade/BTrade.BuyRecipe -- FUNCTION -- Buy new crafting recipe -- PARAMETERS -- RecipeIndex - Index of the recipe from base recipes list to buy -- SOURCE procedure BuyRecipe(RecipeIndex: Unbounded_String) with Pre => (RecipeIndex /= Null_Unbounded_String), Test_Case => (Name => "Test_BuyRecipe", Mode => Nominal); -- **** -- ****f* BTrade/BTrade.HealWounded -- FUNCTION -- Heals wounded crew members in bases -- PARAMETERS -- MemberIndex - Index of player ship crew member to heal or 0 for heal -- all wounded crew members -- SOURCE procedure HealWounded(MemberIndex: Crew_Container.Extended_Index) with Pre => (MemberIndex <= Player_Ship.Crew.Last_Index), Test_Case => (Name => "Test_HealWounded", Mode => Nominal); -- **** -- ****f* BTrade/BTrade.HealCost -- FUNCTION -- Count cost of healing action -- PARAMETERS -- Cost - Overall cost of heal wounded player ship crew member(s) -- Time - Time needed to heal wounded player ship crew member(s) -- MemberIndex - Index of player ship crew member to heal or 0 for heal -- all wounded crew members -- RESULT -- Parameters Cost and Time -- SOURCE procedure HealCost (Cost, Time: in out Natural; MemberIndex: Crew_Container.Extended_Index) with Pre => MemberIndex <= Player_Ship.Crew.Last_Index, Post => Cost > 0 and Time > 0, Test_Case => (Name => "Test_HealCost", Mode => Nominal); -- **** -- ****f* BTrade/BTrade.TrainCost -- FUNCTION -- Count cost of training action -- PARAMETERS -- MemberIndex - Index of player ship crew member which will be training -- SkillIndex - Index of skill of selected crew member which will be -- training -- RESULT -- Overall cost of training selected skill by selected crew member. -- Return 0 if the skill can't be trained because is maxed. -- SOURCE function TrainCost (MemberIndex: Crew_Container.Extended_Index; SkillIndex: Skills_Container.Extended_Index) return Natural with Pre => MemberIndex in Player_Ship.Crew.First_Index .. Player_Ship.Crew.Last_Index and SkillIndex in 1 .. Skills_Amount, Test_Case => (Name => "Test_TrainCost", Mode => Nominal); -- **** -- ****f* BTrade/BTrade.TrainSkill -- FUNCTION -- Train selected skill -- PARAMETERS -- MemberIndex - Index of Player_Ship crew member which train -- SkillIndex - Index of skill of selected crew member to train -- Amount - How many times train or how many money spend on training -- Is_Amount - If true, Amount variable is how many times train, -- otherwise it is amount of money to spend -- SOURCE procedure TrainSkill (MemberIndex: Crew_Container.Extended_Index; SkillIndex: Skills_Container.Extended_Index; Amount: Positive; Is_Amount: Boolean := True) with Pre => MemberIndex in Player_Ship.Crew.First_Index .. Player_Ship.Crew.Last_Index and SkillIndex in 1 .. Skills_Amount, Test_Case => (Name => "Test_TrainSkill", Mode => Nominal); -- **** end Bases.Trade;
{ "source": "starcoderdata", "programming_language": "ada" }
-- ----------------------------------------------------------------------------- with Language_Defs, Language_Utils; package Mapcodes.Languages is -- The supported languages -- The language names in Roman are the Mixed_Str images of these enums type Language_List is new Language_Defs.Language_List; -- Roman, Greek, Cyrillic, Hebrew, Devanagari, Malayalam, Georgian, Katakana, -- Thai, Lao, Armenian, Bengali, Gurmukhi, Tibetan, Arabic, Korean, Burmese, -- Khmer, Sinhalese, Thaana, Chinese, Tifinagh, Tamil, Amharic, Telugu, Odia, -- Kannada, Gujarati -- The unicode sequence to provide a language name in its language subtype Unicode_Sequence is Language_Utils.Unicode_Sequence; -- Get the Language from its name in its language -- Raises, if the output language is not known: Unknown_Language : exception; function Get_Language (Name : Unicode_Sequence) return Language_List; -- Get the language of a text (territory name or mapcode) -- All the characters must be of the same language, otherwise raises Invalid_Text : exception; function Get_Language (Input : Wide_String) return Language_List; -- The default language Default_Language : constant Language_List := Roman; -- Conversion of a text (territory name or mapcode) into a given language -- The language of the input is detected automatically -- Raises Invalid_Text if the input is not valid function Convert (Input : Wide_String; Output_Language : Language_List := Default_Language) return Wide_String; end Mapcodes.Languages;
{ "source": "starcoderdata", "programming_language": "ada" }
with foo; use foo; with Interfaces; use Interfaces; -- GNATprove GPL 2016 seems to miss a failed precondition check -- in the call at line 18. Reason is insufficient knowledge on -- others=>, causing a false negative there, which in turn hides -- a serious bug. -- Fixed in GNATprove Pro 18 (and presumably later in GPL 2017) procedure main with SPARK_Mode is -- inlined callee procedure bar (d : out Data_Type) is begin --pragma Assert (d'Length > 0); d := (others => 0); -- with this, GNATprove does not find violation in line 18 pragma Annotate (GNATprove, False_Positive, "length check might fail", "insufficient solver knowledge"); pragma Assert_And_Cut (d'Length >= 0); --d (d'First) := 0; -- with this, GNATprove indeed finds a violation in line 18 end bar; arr : Data_Type (0 .. 91) := (others => 0); i32 : Integer_32; begin bar (arr); -- essential i32 := foo.toInteger_32 (arr (60 .. 64)); -- length check proved, but actually exception end main;
{ "source": "starcoderdata", "programming_language": "ada" }
with Parse_Args.Generic_Discrete_Array_Options; package Parse_Args.Integer_Array_Options is type Integer_Array is array (Integer range <>) of Integer; type Integer_Array_Access is access Integer_Array; package Inner is new Generic_Discrete_Array_Options(Element => Integer, Element_Array => Integer_Array, Element_Array_Access => Integer_Array_Access ); subtype Element_Array_Option is Inner.Element_Array_Option; function Image (O : in Element_Array_Option) return String renames Inner.Image; function Value (O : in Element_Array_Option) return Integer_Array_Access renames Inner.Value; function Value(A : in Argument_Parser; Name : in String) return Integer_Array_Access renames Inner.Value; function Make_Option return Option_Ptr renames Inner.Make_Option; end Parse_Args.Integer_Array_Options;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Numerics.Generic_Real_Arrays; with GA_Maths; package SVD is type Real is digits 18; package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real); type SVD (Num_Rows, Num_Cols, Num_Singular, Work_Vector_Rows : Natural) is private; SVD_Exception : Exception; function Condition_Number (aMatrix : GA_Maths.Float_Matrix) return Float; function Singular_Value_Decomposition (aMatrix : Real_Arrays.Real_Matrix) return SVD; function Singular_Value_Decomposition (aMatrix : GA_Maths.Float_Matrix) return SVD; private type SVD (Num_Rows, Num_Cols, Num_Singular, Work_Vector_Rows : Natural) is record Matrix_U : Real_Arrays.Real_Matrix (1 .. Num_Rows, 1 .. Num_Cols) := (others => (others => 0.0)); Matrix_V : Real_Arrays.Real_Matrix (1 .. Num_Rows, 1 .. Num_Cols) := (others => (others => 0.0)); Matrix_W : Real_Arrays.Real_Vector (1 .. Work_Vector_Rows) :=(others => 0.0); Sorted_Singular_Values : Real_Arrays.Real_Vector (1 .. Num_Singular); end record; end SVD;
{ "source": "starcoderdata", "programming_language": "ada" }
-- DESCRIPTION used for compressed tables only -- NOTES somewhat complicated but works fast and generates efficient scanners -- $Header: /co/ua/self/arcadia/aflex/ada/src/RCS/tblcmpS.a,v 1.3 90/01/12 15:20:47 self Exp Locker: self $ with misc_defs; use misc_defs; package tblcmp is -- bldtbl - build table entries for dfa state procedure BLDTBL(STATE : in UNBOUNDED_INT_ARRAY; STATENUM, TOTALTRANS, COMSTATE, COMFREQ : in INTEGER); procedure CMPTMPS; -- expand_nxt_chk - expand the next check arrays procedure EXPAND_NXT_CHK; -- find_table_space - finds a space in the table for a state to be placed function FIND_TABLE_SPACE(STATE : in UNBOUNDED_INT_ARRAY; NUMTRANS : in INTEGER) return INTEGER; -- inittbl - initialize transition tables procedure INITTBL; -- mkdeftbl - make the default, "jam" table entries procedure MKDEFTBL; -- mkentry - create base/def and nxt/chk entries for transition array procedure MKENTRY(STATE : in UNBOUNDED_INT_ARRAY; NUMCHARS, STATENUM, DEFLINK, TOTALTRANS : in INTEGER); -- mk1tbl - create table entries for a state (or state fragment) which -- has only one out-transition procedure MK1TBL(STATE, SYM, ONENXT, ONEDEF : in INTEGER); -- mkprot - create new proto entry procedure MKPROT(STATE : in UNBOUNDED_INT_ARRAY; STATENUM, COMSTATE : in INTEGER); -- mktemplate - create a template entry based on a state, and connect the state -- to it procedure MKTEMPLATE(STATE : in UNBOUNDED_INT_ARRAY; STATENUM, COMSTATE : in INTEGER); -- mv2front - move proto queue element to front of queue procedure MV2FRONT(QELM : in INTEGER); -- place_state - place a state into full speed transition table procedure PLACE_STATE(STATE : in UNBOUNDED_INT_ARRAY; STATENUM, TRANSNUM : in INTEGER); -- stack1 - save states with only one out-transition to be processed later procedure STACK1(STATENUM, SYM, NEXTSTATE, DEFLINK : in INTEGER); -- tbldiff - compute differences between two state tables procedure TBLDIFF(STATE : in UNBOUNDED_INT_ARRAY; PR : in INTEGER; EXT : out UNBOUNDED_INT_ARRAY; RESULT : out INTEGER); end tblcmp;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Unchecked_Deallocation; package body Regions.Shared_Lists is procedure Reference (Self : not null List_Node_Access) with Inline; procedure Unreference (Self : in out List_Node_Access) with Inline; procedure Free is new Ada.Unchecked_Deallocation (List_Node, List_Node_Access); --------- -- "=" -- --------- function "=" (Left, Right : List) return Boolean is function Compare (L, R : List_Node_Access) return Boolean; -- Compare item in node chains function Compare (L, R : List_Node_Access) return Boolean is begin if L = R then return True; elsif L.Next = null then return L.Data = R.Data; elsif L.Data = R.Data then return Compare (L.Next, R.Next); else return False; end if; end Compare; begin return Left.Length = Right.Length and then Compare (Left.Head, Right.Head); end "="; ------------ -- Adjust -- ------------ overriding procedure Adjust (Self : in out List) is begin if Self.Head /= null then Reference (Self.Head); end if; end Adjust; ----------------------- -- Constant_Indexing -- ----------------------- function Constant_Indexing (Self : List; Position : Cursor) return Element_Type is pragma Unreferenced (Self); begin return Position.Item.Data; end Constant_Indexing; ---------------- -- Empty_List -- ---------------- function Empty_List return List is begin return (Ada.Finalization.Controlled with Head => null, Length => 0); end Empty_List; -------------- -- Finalize -- -------------- overriding procedure Finalize (Self : in out List) is begin Unreference (Self.Head); Self.Length := 0; end Finalize; ----------- -- First -- ----------- overriding function First (Self : Forward_Iterator) return Cursor is begin return Self.First; end First; ------------------- -- First_Element -- ------------------- function First_Element (Self : List) return Element_Type is begin return Self.Head.Data; end First_Element; ----------------- -- Has_Element -- ----------------- function Has_Element (Self : Cursor) return Boolean is begin return Self.Item /= null; end Has_Element; -------------- -- Is_Empty -- -------------- function Is_Empty (Self : List) return Boolean is begin return Self.Head = null; end Is_Empty; ------------- -- Iterate -- ------------- function Iterate (Self : List'Class) return Forward_Iterator is begin return (First => (Item => Self.Head)); end Iterate; ------------ -- Length -- ------------ function Length (Self : List) return Natural is begin return Self.Length; end Length; ---------- -- Next -- ---------- overriding function Next (Self : Forward_Iterator; Position : Cursor) return Cursor is pragma Unreferenced (Self); begin if Position.Item = null then return Position; else return (Item => Position.Item.Next); end if; end Next; ------------- -- Prepend -- ------------- procedure Prepend (Self : in out List; Item : Element_Type) is begin Self.Head := new List_Node'(Self.Head, 1, Item); Self.Length := Self.Length + 1; end Prepend; --------------- -- Reference -- --------------- procedure Reference (Self : not null List_Node_Access) is begin Self.Counter := Self.Counter + 1; end Reference; ----------------- -- Unreference -- ----------------- procedure Unreference (Self : in out List_Node_Access) is begin if Self /= null then Self.Counter := Self.Counter - 1; if Self.Counter = 0 then Destroy (Self.Data); Unreference (Self.Next); Free (Self); else Self := null; end if; end if; end Unreference; end Regions.Shared_Lists;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ package Asis.Gela.Elements.Defs is -------------------------- -- Type_Definition_Node -- -------------------------- type Type_Definition_Node is abstract new Definition_Node with private; type Type_Definition_Ptr is access all Type_Definition_Node; for Type_Definition_Ptr'Storage_Pool use Lists.Pool; function Corresponding_Type_Operators (Element : Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Type_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Type_Definition_Node) return Asis.Definition_Kinds; ----------------------------- -- Subtype_Indication_Node -- ----------------------------- type Subtype_Indication_Node is new Definition_Node with private; type Subtype_Indication_Ptr is access all Subtype_Indication_Node; for Subtype_Indication_Ptr'Storage_Pool use Lists.Pool; function New_Subtype_Indication_Node (The_Context : ASIS.Context) return Subtype_Indication_Ptr; function Get_Subtype_Mark (Element : Subtype_Indication_Node) return Asis.Expression; procedure Set_Subtype_Mark (Element : in out Subtype_Indication_Node; Value : in Asis.Expression); function Subtype_Constraint (Element : Subtype_Indication_Node) return Asis.Constraint; procedure Set_Subtype_Constraint (Element : in out Subtype_Indication_Node; Value : in Asis.Constraint); function Has_Null_Exclusion (Element : Subtype_Indication_Node) return Boolean; procedure Set_Has_Null_Exclusion (Element : in out Subtype_Indication_Node; Value : in Boolean); function Definition_Kind (Element : Subtype_Indication_Node) return Asis.Definition_Kinds; function Children (Element : access Subtype_Indication_Node) return Traverse_List; function Clone (Element : Subtype_Indication_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Subtype_Indication_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------- -- Constraint_Node -- --------------------- type Constraint_Node is abstract new Definition_Node with private; type Constraint_Ptr is access all Constraint_Node; for Constraint_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Constraint_Node) return Asis.Definition_Kinds; ------------------------------- -- Component_Definition_Node -- ------------------------------- type Component_Definition_Node is new Definition_Node with private; type Component_Definition_Ptr is access all Component_Definition_Node; for Component_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Component_Definition_Node (The_Context : ASIS.Context) return Component_Definition_Ptr; function Component_Subtype_Indication (Element : Component_Definition_Node) return Asis.Subtype_Indication; procedure Set_Component_Subtype_Indication (Element : in out Component_Definition_Node; Value : in Asis.Subtype_Indication); function Trait_Kind (Element : Component_Definition_Node) return Asis.Trait_Kinds; procedure Set_Trait_Kind (Element : in out Component_Definition_Node; Value : in Asis.Trait_Kinds); function Definition_Kind (Element : Component_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Component_Definition_Node) return Traverse_List; function Clone (Element : Component_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Component_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------------- -- Discrete_Subtype_Definition_Node -- -------------------------------------- type Discrete_Subtype_Definition_Node is abstract new Definition_Node with private; type Discrete_Subtype_Definition_Ptr is access all Discrete_Subtype_Definition_Node; for Discrete_Subtype_Definition_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Discrete_Subtype_Definition_Node) return Asis.Definition_Kinds; ------------------------- -- Discrete_Range_Node -- ------------------------- type Discrete_Range_Node is abstract new Definition_Node with private; type Discrete_Range_Ptr is access all Discrete_Range_Node; for Discrete_Range_Ptr'Storage_Pool use Lists.Pool; function Definition_Kind (Element : Discrete_Range_Node) return Asis.Definition_Kinds; ------------------------------------ -- Unknown_Discriminant_Part_Node -- ------------------------------------ type Unknown_Discriminant_Part_Node is new Definition_Node with private; type Unknown_Discriminant_Part_Ptr is access all Unknown_Discriminant_Part_Node; for Unknown_Discriminant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Unknown_Discriminant_Part_Node (The_Context : ASIS.Context) return Unknown_Discriminant_Part_Ptr; function Definition_Kind (Element : Unknown_Discriminant_Part_Node) return Asis.Definition_Kinds; function Clone (Element : Unknown_Discriminant_Part_Node; Parent : Asis.Element) return Asis.Element; ---------------------------------- -- Known_Discriminant_Part_Node -- ---------------------------------- type Known_Discriminant_Part_Node is new Definition_Node with private; type Known_Discriminant_Part_Ptr is access all Known_Discriminant_Part_Node; for Known_Discriminant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Known_Discriminant_Part_Node (The_Context : ASIS.Context) return Known_Discriminant_Part_Ptr; function Discriminants (Element : Known_Discriminant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Discriminants (Element : in out Known_Discriminant_Part_Node; Value : in Asis.Element); function Discriminants_List (Element : Known_Discriminant_Part_Node) return Asis.Element; function Definition_Kind (Element : Known_Discriminant_Part_Node) return Asis.Definition_Kinds; function Children (Element : access Known_Discriminant_Part_Node) return Traverse_List; function Clone (Element : Known_Discriminant_Part_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Known_Discriminant_Part_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------------------- -- Record_Definition_Node -- ---------------------------- type Record_Definition_Node is new Definition_Node with private; type Record_Definition_Ptr is access all Record_Definition_Node; for Record_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Record_Definition_Node (The_Context : ASIS.Context) return Record_Definition_Ptr; function Record_Components (Element : Record_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Record_Components (Element : in out Record_Definition_Node; Value : in Asis.Element); function Record_Components_List (Element : Record_Definition_Node) return Asis.Element; function Implicit_Components (Element : Record_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Components (Element : in out Record_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Record_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Record_Definition_Node) return Traverse_List; function Clone (Element : Record_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Record_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------------------- -- Null_Record_Definition_Node -- --------------------------------- type Null_Record_Definition_Node is new Definition_Node with private; type Null_Record_Definition_Ptr is access all Null_Record_Definition_Node; for Null_Record_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Null_Record_Definition_Node (The_Context : ASIS.Context) return Null_Record_Definition_Ptr; function Definition_Kind (Element : Null_Record_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Null_Record_Definition_Node; Parent : Asis.Element) return Asis.Element; ------------------------- -- Null_Component_Node -- ------------------------- type Null_Component_Node is new Definition_Node with private; type Null_Component_Ptr is access all Null_Component_Node; for Null_Component_Ptr'Storage_Pool use Lists.Pool; function New_Null_Component_Node (The_Context : ASIS.Context) return Null_Component_Ptr; function Pragmas (Element : Null_Component_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Pragmas (Element : in out Null_Component_Node; Value : in Asis.Element); function Pragmas_List (Element : Null_Component_Node) return Asis.Element; function Definition_Kind (Element : Null_Component_Node) return Asis.Definition_Kinds; function Clone (Element : Null_Component_Node; Parent : Asis.Element) return Asis.Element; ----------------------- -- Variant_Part_Node -- ----------------------- type Variant_Part_Node is new Definition_Node with private; type Variant_Part_Ptr is access all Variant_Part_Node; for Variant_Part_Ptr'Storage_Pool use Lists.Pool; function New_Variant_Part_Node (The_Context : ASIS.Context) return Variant_Part_Ptr; function Discriminant_Direct_Name (Element : Variant_Part_Node) return Asis.Name; procedure Set_Discriminant_Direct_Name (Element : in out Variant_Part_Node; Value : in Asis.Name); function Variants (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Variants (Element : in out Variant_Part_Node; Value : in Asis.Element); function Variants_List (Element : Variant_Part_Node) return Asis.Element; function Pragmas (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Pragmas (Element : in out Variant_Part_Node; Value : in Asis.Element); function Pragmas_List (Element : Variant_Part_Node) return Asis.Element; function End_Pragmas (Element : Variant_Part_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_End_Pragmas (Element : in out Variant_Part_Node; Value : in Asis.Element); function End_Pragmas_List (Element : Variant_Part_Node) return Asis.Element; function Definition_Kind (Element : Variant_Part_Node) return Asis.Definition_Kinds; function Children (Element : access Variant_Part_Node) return Traverse_List; function Clone (Element : Variant_Part_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Variant_Part_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------ -- Variant_Node -- ------------------ type Variant_Node is new Definition_Node with private; type Variant_Ptr is access all Variant_Node; for Variant_Ptr'Storage_Pool use Lists.Pool; function New_Variant_Node (The_Context : ASIS.Context) return Variant_Ptr; function Record_Components (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Record_Components (Element : in out Variant_Node; Value : in Asis.Element); function Record_Components_List (Element : Variant_Node) return Asis.Element; function Implicit_Components (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Components (Element : in out Variant_Node; Item : in Asis.Element); function Variant_Choices (Element : Variant_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Variant_Choices (Element : in out Variant_Node; Value : in Asis.Element); function Variant_Choices_List (Element : Variant_Node) return Asis.Element; function Definition_Kind (Element : Variant_Node) return Asis.Definition_Kinds; function Children (Element : access Variant_Node) return Traverse_List; function Clone (Element : Variant_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Variant_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------ -- Others_Choice_Node -- ------------------------ type Others_Choice_Node is new Definition_Node with private; type Others_Choice_Ptr is access all Others_Choice_Node; for Others_Choice_Ptr'Storage_Pool use Lists.Pool; function New_Others_Choice_Node (The_Context : ASIS.Context) return Others_Choice_Ptr; function Definition_Kind (Element : Others_Choice_Node) return Asis.Definition_Kinds; function Clone (Element : Others_Choice_Node; Parent : Asis.Element) return Asis.Element; ---------------------------- -- Access_Definition_Node -- ---------------------------- type Access_Definition_Node is abstract new Definition_Node with private; type Access_Definition_Ptr is access all Access_Definition_Node; for Access_Definition_Ptr'Storage_Pool use Lists.Pool; function Has_Null_Exclusion (Element : Access_Definition_Node) return Boolean; procedure Set_Has_Null_Exclusion (Element : in out Access_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Access_Definition_Node) return Asis.Definition_Kinds; ------------------------------------- -- Incomplete_Type_Definition_Node -- ------------------------------------- type Incomplete_Type_Definition_Node is new Definition_Node with private; type Incomplete_Type_Definition_Ptr is access all Incomplete_Type_Definition_Node; for Incomplete_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Incomplete_Type_Definition_Node (The_Context : ASIS.Context) return Incomplete_Type_Definition_Ptr; function Definition_Kind (Element : Incomplete_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Incomplete_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; -------------------------------------------- -- Tagged_Incomplete_Type_Definition_Node -- -------------------------------------------- type Tagged_Incomplete_Type_Definition_Node is new Incomplete_Type_Definition_Node with private; type Tagged_Incomplete_Type_Definition_Ptr is access all Tagged_Incomplete_Type_Definition_Node; for Tagged_Incomplete_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Tagged_Incomplete_Type_Definition_Node (The_Context : ASIS.Context) return Tagged_Incomplete_Type_Definition_Ptr; function Has_Tagged (Element : Tagged_Incomplete_Type_Definition_Node) return Boolean; procedure Set_Has_Tagged (Element : in out Tagged_Incomplete_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Tagged_Incomplete_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Tagged_Incomplete_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; ---------------------------------- -- Private_Type_Definition_Node -- ---------------------------------- type Private_Type_Definition_Node is new Definition_Node with private; type Private_Type_Definition_Ptr is access all Private_Type_Definition_Node; for Private_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Private_Type_Definition_Node (The_Context : ASIS.Context) return Private_Type_Definition_Ptr; function Trait_Kind (Element : Private_Type_Definition_Node) return Asis.Trait_Kinds; procedure Set_Trait_Kind (Element : in out Private_Type_Definition_Node; Value : in Asis.Trait_Kinds); function Corresponding_Type_Operators (Element : Private_Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Private_Type_Definition_Node; Item : in Asis.Element); function Has_Limited (Element : Private_Type_Definition_Node) return Boolean; procedure Set_Has_Limited (Element : in out Private_Type_Definition_Node; Value : in Boolean); function Has_Private (Element : Private_Type_Definition_Node) return Boolean; procedure Set_Has_Private (Element : in out Private_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Private_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Private_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; ----------------------------------------- -- Tagged_Private_Type_Definition_Node -- ----------------------------------------- type Tagged_Private_Type_Definition_Node is new Private_Type_Definition_Node with private; type Tagged_Private_Type_Definition_Ptr is access all Tagged_Private_Type_Definition_Node; for Tagged_Private_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Tagged_Private_Type_Definition_Node (The_Context : ASIS.Context) return Tagged_Private_Type_Definition_Ptr; function Has_Abstract (Element : Tagged_Private_Type_Definition_Node) return Boolean; procedure Set_Has_Abstract (Element : in out Tagged_Private_Type_Definition_Node; Value : in Boolean); function Has_Tagged (Element : Tagged_Private_Type_Definition_Node) return Boolean; procedure Set_Has_Tagged (Element : in out Tagged_Private_Type_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Tagged_Private_Type_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Tagged_Private_Type_Definition_Node; Parent : Asis.Element) return Asis.Element; --------------------------------------- -- Private_Extension_Definition_Node -- --------------------------------------- type Private_Extension_Definition_Node is new Private_Type_Definition_Node with private; type Private_Extension_Definition_Ptr is access all Private_Extension_Definition_Node; for Private_Extension_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Private_Extension_Definition_Node (The_Context : ASIS.Context) return Private_Extension_Definition_Ptr; function Ancestor_Subtype_Indication (Element : Private_Extension_Definition_Node) return Asis.Subtype_Indication; procedure Set_Ancestor_Subtype_Indication (Element : in out Private_Extension_Definition_Node; Value : in Asis.Subtype_Indication); function Implicit_Inherited_Declarations (Element : Private_Extension_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Inherited_Declarations (Element : in out Private_Extension_Definition_Node; Item : in Asis.Element); function Implicit_Inherited_Subprograms (Element : Private_Extension_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Implicit_Inherited_Subprograms (Element : in out Private_Extension_Definition_Node; Item : in Asis.Element); function Has_Synchronized (Element : Private_Extension_Definition_Node) return Boolean; procedure Set_Has_Synchronized (Element : in out Private_Extension_Definition_Node; Value : in Boolean); function Has_Abstract (Element : Private_Extension_Definition_Node) return Boolean; procedure Set_Has_Abstract (Element : in out Private_Extension_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Private_Extension_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Private_Extension_Definition_Node) return Traverse_List; function Clone (Element : Private_Extension_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Private_Extension_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------- -- Protected_Definition_Node -- ------------------------------- type Protected_Definition_Node is new Definition_Node with private; type Protected_Definition_Ptr is access all Protected_Definition_Node; for Protected_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Protected_Definition_Node (The_Context : ASIS.Context) return Protected_Definition_Ptr; function Is_Private_Present (Element : Protected_Definition_Node) return Boolean; procedure Set_Is_Private_Present (Element : in out Protected_Definition_Node; Value : in Boolean); function Visible_Part_Items (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Visible_Part_Items (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Visible_Part_Items_List (Element : Protected_Definition_Node) return Asis.Element; function Private_Part_Items (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Private_Part_Items (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Private_Part_Items_List (Element : Protected_Definition_Node) return Asis.Element; function Get_Identifier (Element : Protected_Definition_Node) return Asis.Element; procedure Set_Identifier (Element : in out Protected_Definition_Node; Value : in Asis.Element); function Corresponding_Type_Operators (Element : Protected_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Protected_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Protected_Definition_Node) return Asis.Definition_Kinds; function Children (Element : access Protected_Definition_Node) return Traverse_List; function Clone (Element : Protected_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Protected_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------- -- Task_Definition_Node -- -------------------------- type Task_Definition_Node is new Protected_Definition_Node with private; type Task_Definition_Ptr is access all Task_Definition_Node; for Task_Definition_Ptr'Storage_Pool use Lists.Pool; function New_Task_Definition_Node (The_Context : ASIS.Context) return Task_Definition_Ptr; function Is_Task_Definition_Present (Element : Task_Definition_Node) return Boolean; procedure Set_Is_Task_Definition_Present (Element : in out Task_Definition_Node; Value : in Boolean); function Definition_Kind (Element : Task_Definition_Node) return Asis.Definition_Kinds; function Clone (Element : Task_Definition_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Task_Definition_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------------------- -- Formal_Type_Definition_Node -- --------------------------------- type Formal_Type_Definition_Node is abstract new Definition_Node with private; type Formal_Type_Definition_Ptr is access all Formal_Type_Definition_Node; for Formal_Type_Definition_Ptr'Storage_Pool use Lists.Pool; function Corresponding_Type_Operators (Element : Formal_Type_Definition_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Type_Operators (Element : in out Formal_Type_Definition_Node; Item : in Asis.Element); function Definition_Kind (Element : Formal_Type_Definition_Node) return Asis.Definition_Kinds; private type Type_Definition_Node is abstract new Definition_Node with record Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; type Subtype_Indication_Node is new Definition_Node with record Subtype_Mark : aliased Asis.Expression; Subtype_Constraint : aliased Asis.Constraint; Has_Null_Exclusion : aliased Boolean := False; end record; type Constraint_Node is abstract new Definition_Node with record null; end record; type Component_Definition_Node is new Definition_Node with record Component_Subtype_Indication : aliased Asis.Subtype_Indication; Trait_Kind : aliased Asis.Trait_Kinds := An_Ordinary_Trait; end record; type Discrete_Subtype_Definition_Node is abstract new Definition_Node with record null; end record; type Discrete_Range_Node is abstract new Definition_Node with record null; end record; type Unknown_Discriminant_Part_Node is new Definition_Node with record null; end record; type Known_Discriminant_Part_Node is new Definition_Node with record Discriminants : aliased Primary_Declaration_Lists.List; end record; type Record_Definition_Node is new Definition_Node with record Record_Components : aliased Primary_Declaration_Lists.List; Implicit_Components : aliased Secondary_Declaration_Lists.List_Node; end record; type Null_Record_Definition_Node is new Definition_Node with record null; end record; type Null_Component_Node is new Definition_Node with record Pragmas : aliased Primary_Pragma_Lists.List; end record; type Variant_Part_Node is new Definition_Node with record Discriminant_Direct_Name : aliased Asis.Name; Variants : aliased Primary_Variant_Lists.List; Pragmas : aliased Primary_Pragma_Lists.List; End_Pragmas : aliased Primary_Pragma_Lists.List; end record; type Variant_Node is new Definition_Node with record Record_Components : aliased Primary_Declaration_Lists.List; Implicit_Components : aliased Secondary_Declaration_Lists.List_Node; Variant_Choices : aliased Primary_Choise_Lists.List; end record; type Others_Choice_Node is new Definition_Node with record null; end record; type Access_Definition_Node is abstract new Definition_Node with record Has_Null_Exclusion : aliased Boolean := False; end record; type Incomplete_Type_Definition_Node is new Definition_Node with record null; end record; type Tagged_Incomplete_Type_Definition_Node is new Incomplete_Type_Definition_Node with record Has_Tagged : aliased Boolean := False; end record; type Private_Type_Definition_Node is new Definition_Node with record Trait_Kind : aliased Asis.Trait_Kinds := An_Ordinary_Trait; Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; Has_Limited : aliased Boolean := False; Has_Private : aliased Boolean := False; end record; type Tagged_Private_Type_Definition_Node is new Private_Type_Definition_Node with record Has_Abstract : aliased Boolean := False; Has_Tagged : aliased Boolean := False; end record; type Private_Extension_Definition_Node is new Private_Type_Definition_Node with record Ancestor_Subtype_Indication : aliased Asis.Subtype_Indication; Implicit_Inherited_Declarations : aliased Secondary_Declaration_Lists.List_Node; Implicit_Inherited_Subprograms : aliased Secondary_Declaration_Lists.List_Node; Has_Synchronized : aliased Boolean := False; Has_Abstract : aliased Boolean := False; end record; type Protected_Definition_Node is new Definition_Node with record Is_Private_Present : aliased Boolean := False; Visible_Part_Items : aliased Primary_Declaration_Lists.List; Private_Part_Items : aliased Primary_Declaration_Lists.List; Identifier : aliased Asis.Element; Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; type Task_Definition_Node is new Protected_Definition_Node with record Is_Task_Definition_Present : aliased Boolean := False; end record; type Formal_Type_Definition_Node is abstract new Definition_Node with record Corresponding_Type_Operators : aliased Secondary_Declaration_Lists.List_Node; end record; end Asis.Gela.Elements.Defs;
{ "source": "starcoderdata", "programming_language": "ada" }
-- package Edc_Client.LED is -------------------------------------------------------------------------- -- Command string for controlling the LEDs -------------------------------------------------------------------------- subtype LED_String is String (1 .. 4); -------------------------------------------------------------------------- -- Procedures to control the red LED -------------------------------------------------------------------------- procedure Red_On with Pre => Initialized; procedure Red_Off with Pre => Initialized; procedure Red_Toggle with Pre => Initialized; -------------------------------------------------------------------------- -- Procedures to control the amber LED -------------------------------------------------------------------------- procedure Amber_On with Pre => Initialized; procedure Amber_Off with Pre => Initialized; procedure Amber_Toggle with Pre => Initialized; -------------------------------------------------------------------------- -- Procedures to control the green LED -------------------------------------------------------------------------- procedure Green_On with Pre => Initialized; procedure Green_Off with Pre => Initialized; procedure Green_Toggle with Pre => Initialized; -------------------------------------------------------------------------- -- Procedures to control the white LED -------------------------------------------------------------------------- procedure White_On with Pre => Initialized; procedure White_Off with Pre => Initialized; procedure White_Toggle with Pre => Initialized; -------------------------------------------------------------------------- -- Procedures to control the blue LED -------------------------------------------------------------------------- procedure Blue_On with Pre => Initialized; procedure Blue_Off with Pre => Initialized; procedure Blue_Toggle with Pre => Initialized; end Edc_Client.LED;
{ "source": "starcoderdata", "programming_language": "ada" }
-- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- with Ada.Text_IO; package body Symbols.IO is procedure Put_Named (Session : in Sessions.Session_Type; Set : in Symbol_Sets.Set_Type) is pragma Unreferenced (Session); use Ada.Text_IO; First : Boolean := True; begin Put ("["); for Index in Symbol_Sets.First_Index .. Symbol_Sets.Last_Index loop if Symbol_Sets.Set_Find (Set, Index) then if not First then Put (" "); end if; Put (Name_Of (Element_At (Index))); First := False; end if; end loop; Put ("]"); end Put_Named; -- -- Debug -- procedure JQ_Dump_Symbols (Session : in Sessions.Session_Type; Mode : in Integer) is use Ada.Text_IO; use Symbol_Sets; begin for Index in 0 .. Last_Index loop declare Symbol : Symbol_Access renames Element_At (Index); begin Put ("SYM "); Put (To_String (Symbol.Name)); Put (" INDEX"); Put (Symbol_Index'Image (Symbol.Index)); Put (" NSUB"); Put (Symbol.Sub_Symbol.Length'Img); Put (" KIND"); Put (Symbol_Kind'Pos (Symbol.Kind)'Img); if Mode = 1 then Put (" PREC"); if Symbol.Kind = Multi_Terminal then Put (" ("); for J in Symbol.Sub_Symbol.First_Index .. Symbol.Sub_Symbol.Last_Index loop Put (Natural'Image (Symbol.Sub_Symbol.Element (J).Precedence)); Put (" "); end loop; Put (")"); else if Symbol.Precedence = -1 then Put (" -1"); -- Hack else Put (Natural'Image (Symbol.Precedence)); end if; end if; Put (" LAMB "); Put (Boolean'Image (Symbol.Lambda)); Put (" FS "); if Symbol.First_Set = Null_Set then Put ("<null>"); else Put_Named (Session, Symbol.First_Set); end if; end if; New_Line; end; end loop; end JQ_Dump_Symbols; end Symbols.IO;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This is a simplified version of this package body to be used in when the -- Ravenscar profile and there are no exception handlers present (either of -- the restrictions No_Exception_Handlers or No_Exception_Propagation are in -- effect). This means that the only task termination cause that need to be -- taken into account is normal task termination (abort is not allowed by -- the Ravenscar profile and the restricted exception support does not -- include Exception_Occurrence). with System.Tasking; -- used for Task_Id -- Self -- Fall_Back_Handler with System.Task_Primitives.Operations; -- Used for Self -- Set_Priority -- Get_Priority with Unchecked_Conversion; package body Ada.Task_Termination is use System.Task_Primitives.Operations; use type Ada.Task_Identification.Task_Id; function To_TT is new Unchecked_Conversion (System.Tasking.Termination_Handler, Termination_Handler); function To_ST is new Unchecked_Conversion (Termination_Handler, System.Tasking.Termination_Handler); ----------------------------------- -- Current_Task_Fallback_Handler -- ----------------------------------- function Current_Task_Fallback_Handler return Termination_Handler is Self_Id : constant System.Tasking.Task_Id := Self; Caller_Priority : constant System.Any_Priority := Get_Priority (Self_Id); Result : Termination_Handler; begin -- Raise the priority to prevent race conditions when modifying -- System.Tasking.Fall_Back_Handler. Set_Priority (Self_Id, System.Any_Priority'Last); Result := To_TT (System.Tasking.Fall_Back_Handler); -- Restore the original priority Set_Priority (Self_Id, Caller_Priority); return Result; end Current_Task_Fallback_Handler; ------------------------------------- -- Set_Dependents_Fallback_Handler -- ------------------------------------- procedure Set_Dependents_Fallback_Handler (Handler : Termination_Handler) is Self_Id : constant System.Tasking.Task_Id := Self; Caller_Priority : constant System.Any_Priority := Get_Priority (Self_Id); begin -- Raise the priority to prevent race conditions when modifying -- System.Tasking.Fall_Back_Handler. Set_Priority (Self_Id, System.Any_Priority'Last); System.Tasking.Fall_Back_Handler := To_ST (Handler); -- Restore the original priority Set_Priority (Self_Id, Caller_Priority); end Set_Dependents_Fallback_Handler; end Ada.Task_Termination;
{ "source": "starcoderdata", "programming_language": "ada" }
-- implementation unit specialized for Darwin with System.Storage_Elements; private with C.malloc.malloc; package System.Unbounded_Allocators is -- Separated storage pool for local scope. pragma Preelaborate; type Unbounded_Allocator is limited private; procedure Initialize (Object : in out Unbounded_Allocator); procedure Finalize (Object : in out Unbounded_Allocator); procedure Allocate ( Allocator : Unbounded_Allocator; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); procedure Deallocate ( Allocator : Unbounded_Allocator; Storage_Address : Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); function Allocator_Of (Storage_Address : Address) return Unbounded_Allocator; private type Unbounded_Allocator is new C.malloc.malloc.malloc_zone_t_ptr; end System.Unbounded_Allocators;
{ "source": "starcoderdata", "programming_language": "ada" }
ASSIGN (X, CREATE (30)); IF NOT EQUAL (T'(X), CON (30)) THEN FAILED ("INCORRECT QUALIFICATION"); END IF; IF NOT EQUAL (T (X), CON (30)) THEN FAILED ("INCORRECT SELF CONVERSION"); END IF; ASSIGN (W, CREATE (-30)); IF NOT EQUAL (T (W), CON (-30)) THEN FAILED ("INCORRECT CONVERSION FROM PARENT"); END IF; IF NOT EQUAL (PARENT (X), CON (30)) THEN FAILED ("INCORRECT CONVERSION TO PARENT"); END IF; IF NOT (X IN T) THEN FAILED ("INCORRECT ""IN"""); END IF; IF X NOT IN T THEN FAILED ("INCORRECT ""NOT IN"""); END IF; B := FALSE; A (X'ADDRESS); IF NOT B THEN FAILED ("INCORRECT 'ADDRESS"); END IF; IF X'SIZE < T'SIZE THEN FAILED ("INCORRECT OBJECT'SIZE"); END IF; RESULT; END C34009G;
{ "source": "starcoderdata", "programming_language": "ada" }
generic type Fixed_Point_Type is delta <>; package Fmt.Generic_Ordinary_Fixed_Point_Argument is function To_Argument (X : Fixed_Point_Type) return Argument_Type'Class with Inline; function "&" (Args : Arguments; X : Fixed_Point_Type) return Arguments with Inline; private type Fixed_Point_Argument_Type is new Argument_Type with record Value : Fixed_Point_Type; Width : Natural := 0; Fill : Character := ' '; Fore : Natural := Fixed_Point_Type'Fore; Aft : Natural := Fixed_Point_Type'Aft; end record; overriding procedure Parse ( Self : in out Fixed_Point_Argument_Type; Edit : String); overriding function Get_Length ( Self : in out Fixed_Point_Argument_Type) return Natural; overriding procedure Put ( Self : in out Fixed_Point_Argument_Type; Edit : String; To : in out String); end Fmt.Generic_Ordinary_Fixed_Point_Argument;
{ "source": "starcoderdata", "programming_language": "ada" }
package body agar.gui.widget.toolbar is package cbinds is function allocate (parent : widget_access_t; bar_type : type_t; num_rows : c.int; flags : flags_t) return toolbar_access_t; pragma import (c, allocate, "AG_ToolbarNew"); procedure row (toolbar : toolbar_access_t; row_name : c.int); pragma import (c, row, "AG_ToolbarRow"); end cbinds; function allocate (parent : widget_access_t; bar_type : type_t; num_rows : natural; flags : flags_t) return toolbar_access_t is begin return cbinds.allocate (parent => parent, bar_type => bar_type, num_rows => c.int (num_rows), flags => flags); end allocate; procedure row (toolbar : toolbar_access_t; row_name : natural) is begin cbinds.row (toolbar => toolbar, row_name => c.int (row_name)); end row; function widget (toolbar : toolbar_access_t) return widget_access_t is begin return agar.gui.widget.box.widget (toolbar.box'access); end widget; end agar.gui.widget.toolbar;
{ "source": "starcoderdata", "programming_language": "ada" }
Function INI.Section_to_Vector( Object : in Instance; Section: in String:= "" ) return NSO.Types.String_Vector.Vector is Use NSO.Types.String_Vector; Begin Return Result : Vector do For Item in Object(Section).Iterate loop Declare Key : String renames KEY_VALUE_MAP.Key( Item ); Value : Value_Object renames KEY_Value_MAP.Element(Item); Image : String renames -- "ABS"(Value); String'(if Value.Kind = vt_String then Value.String_Value else ABS Value); Begin Result.Append( Image ); End; end loop; Exception when CONSTRAINT_ERROR => null; End return; End INI.Section_to_Vector;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ -- -- SPARK Proof Analysis Tool -- -- S.P.A.T. - Object representing a JSON "proof attempt" object. -- ------------------------------------------------------------------------------ private with Ada.Tags; with SPAT.Entity; with SPAT.Field_Names; with SPAT.Preconditions; package SPAT.Proof_Attempt is use all type GNATCOLL.JSON.JSON_Value_Type; --------------------------------------------------------------------------- -- Has_Required_Fields --------------------------------------------------------------------------- function Has_Required_Fields (Object : JSON_Value) return Boolean is (Preconditions.Ensure_Field (Object => Object, Field => Field_Names.Result, Kind => JSON_String_Type) and Preconditions.Ensure_Field (Object => Object, Field => Field_Names.Time, Kinds_Allowed => Preconditions.Number_Kind)); type T is new Entity.T with private; --------------------------------------------------------------------------- -- Create --------------------------------------------------------------------------- not overriding function Create (Object : JSON_Value; Prover : Subject_Name) return T with Pre => Has_Required_Fields (Object => Object); Trivial_True : constant T; -- Special Proof_Attempt instance that represents a trivially true proof. -- -- Since GNAT_CE_2020 we can also have a "trivial_true" in the check_tree -- which - unlike a proper proof attempt - has no Result nor Time value, so -- we assume "Valid" and "no time" (i.e. 0.0 s). These kind of proof -- attempts are registered to a special prover object "Trivial" (which -- subsequently appears in the "stats" objects). -- Sorting instantiations. --------------------------------------------------------------------------- -- "<" -- -- Comparison operator. --------------------------------------------------------------------------- not overriding function "<" (Left : in T; Right : in T) return Boolean; --------------------------------------------------------------------------- -- Prover --------------------------------------------------------------------------- not overriding function Prover (This : in T) return Subject_Name; --------------------------------------------------------------------------- -- Result --------------------------------------------------------------------------- not overriding function Result (This : in T) return Subject_Name; --------------------------------------------------------------------------- -- Time --------------------------------------------------------------------------- not overriding function Time (This : in T) return Duration; private type T is new Entity.T with record Prover : Subject_Name; -- Prover involved. Result : Subject_Name; -- "Valid", "Unknown", etc. Time : Duration; -- time spent during proof -- Steps -- part of the JSON data, but we don't care. end record; --------------------------------------------------------------------------- -- Image --------------------------------------------------------------------------- overriding function Image (This : in T) return String is (Ada.Tags.External_Tag (T'Class (This)'Tag) & ": (" & "Prover => " & To_String (This.Prover) & ", Result => " & To_String (This.Result) & ", Time => " & This.Time'Image & ")"); Trivial_True : constant T := T'(Entity.T with Prover => To_Name ("Trivial"), Result => To_Name ("Valid"), Time => 0.0); --------------------------------------------------------------------------- -- Prover --------------------------------------------------------------------------- not overriding function Prover (This : in T) return Subject_Name is (This.Prover); --------------------------------------------------------------------------- -- Result --------------------------------------------------------------------------- not overriding function Result (This : in T) return Subject_Name is (This.Result); --------------------------------------------------------------------------- -- Time --------------------------------------------------------------------------- not overriding function Time (This : in T) return Duration is (This.Time); end SPAT.Proof_Attempt;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Containers; use Ada.Containers; with Ada.Directories; use Ada.Directories; with Blueprint; use Blueprint; with AAA.Strings; use AAA.Strings; with Ada.Command_Line; with Ada.Text_IO; with Templates_Parser; with CLIC.TTY; with Filesystem; with Commands; package body Commands.Destroy is ------------- -- Execute -- ------------- overriding procedure Execute ( Cmd : in out Command; Args : AAA.Strings.Vector) is begin if Args.Length > 1 then declare Name : String := Element (Args, 2); Blueprint : String := Args.First_Element; Blueprint_Path : String := Compose(Get_Blueprint_Folder,Blueprint); Current : String := Current_Directory; begin Templates_Parser.Insert (Commands.Translations, Templates_Parser.Assoc ("NAME", Name)); if Exists (Blueprint_Path) then Iterate (Blueprint_Path, Current, Delete); IO.Put_Line (TT.Success("Successfully deleted " & Blueprint) & " " & TT.Warn (TT.Bold (Name))); else IO.Put_Line (TT.Error("Blueprint" & " " & Blueprint_Path & " " & "not found")); end if; end; else IO.Put_Line(TT.Error("Command requires a blueprint and a name to be specified.")); end if; end Execute; -------------------- -- Setup_Switches -- -------------------- overriding procedure Setup_Switches (Cmd : in out Command; Config : in out CLIC.Subcommand.Switches_Configuration) is use CLIC.Subcommand; begin null; end Setup_Switches; end Commands.Destroy;
{ "source": "starcoderdata", "programming_language": "ada" }
package ANSI with Pure is Reset_All : constant String; -- Resets the device to its original state. This may include (if -- applicable): reset graphic rendition, clear tabulation stops, reset -- to default font, and more. type States is (Off, On); function Shorten (Sequence : String) return String is (Sequence); -- Some consecutive commands can be combined, resulting in a shorter -- string. Currently does nothing, but included for future optimization. ----------- -- COLOR -- ----------- type Colors is (Default, -- Implementation defined according to ANSI Black, Red, Green, Yellow, Blue, Magenta, Cyan, Grey, -- Note: these light variants might not work in older terminals. In -- general, the bold + [light] color combination will result in the -- same bright color Light_Black, Light_Red, Light_Green, Light_Yellow, Light_Blue, Light_Magenta, Light_Cyan, Light_Grey); Reset : constant String; -- Back to defaults. Applies to colors & styles. function Foreground (Color : Colors) return String; function Background (Color : Colors) return String; -- Basic palette, 8/16 colors subtype Palette_RGB is Natural range 0 .. 5; -- Used for the 256-palette colors. Actual colors in this index-mode -- palette can slightly vary from terminal to terminal. function Palette_Fg (R, G, B : Palette_RGB) return String; function Palette_Bg (R, G, B : Palette_RGB) return String; subtype Greyscale is Natural range 0 .. 23; -- Drawn from the same palette mode. 0 is black, 23 is white function Foreground (Level : Greyscale) return String; function Background (Level : Greyscale) return String; subtype True_RGB is Natural range 0 .. 255; -- Modern terminals support true 24-bit RGB color function Foreground (R, G, B : True_RGB) return String; function Background (R, G, B : True_RGB) return String; Default_Foreground : constant String; Default_Background : constant String; function Color_Wrap (Text : String; Foreground : String := ""; Background : String := "") return String; -- Wraps text between opening color and closing Defaults. See the combo -- color+styles below. ------------ -- STYLES -- ------------ type Styles is (Default, -- equivalent to Default_Foreground/Background Bright, -- aka Bold Dim, -- aka Faint Italic, Underline, Blink, Rapid_Blink, -- ansi.sys only Invert, -- swaps fg/bg, aka reverse video Conceal, -- aka hide Strike, -- aka crossed-out Fraktur, -- rarely supported, gothic style Double_Underline); function Style (Style : Styles; Active : States := On) return String; -- Apply/Remove a style function Style_Wrap (Text : String; Style : Styles) return String; -- Wraps Text in the given style between On/Off sequences function Wrap (Text : String; Style : Styles; Foreground : String := ""; Background : String := "") return String; ------------ -- CURSOR -- ------------ -- Cursor movement. No effect if at edge of screen. function Back (Cells : Positive := 1) return String; function Down (Lines : Positive := 1) return String; function Forward (Cells : Positive := 1) return String; function Up (Lines : Positive := 1) return String; function Next (Lines : Positive := 1) return String; function Previous (Lines : Positive := 1) return String; -- Move to the beginning of the next/prev lines. Not in ansi.sys function Horizontal (Column : Positive := 1) return String; -- Move to a certain absolute column. Not in ansy.sys function Position (Row, Column : Positive := 1) return String; -- 1, 1 is top-left Store : constant String; -- Store cursor position. Private SCO extension, may work in current vts Restore : constant String; -- Restore cursor position to the previously stored one Hide : constant String; Show : constant String; -- DECTCEM private extension, may work in current vts -------------- -- CLEARING -- -------------- Clear_Screen : constant String; Clear_Screen_And_Buffer : constant String; -- Clear also the backscroll buffer Clear_To_Beginning_Of_Screen : constant String; Clear_To_End_Of_Screen : constant String; -- From the cursor position Clear_Line : constant String; -- Does not change cursor position (neither the two following). Clear_To_Beginning_Of_Line : constant String; Clear_To_End_Of_Line : constant String; function Scroll_Up (Lines : Positive) return String; -- Adds lines at bottom function Scroll_Down (Lines : Positive) return String; -- Adds lines at top private ESC : constant Character := ASCII.ESC; CSI : constant String := ESC & '['; Reset_All : constant String := ESC & "c"; -- Helpers for the many int-to-str conversions function Tail (S : String) return String is (S (S'First + 1 .. S'Last)); function Img (I : Natural) return String is (Tail (I'Img)); ------------ -- COLORS -- ------------ Reset : constant String := CSI & "0m"; -- Back to defaults. Applies to colors & styles. function Foreground (Color : Colors) return String is (CSI & (case Color is when Default => "39", when Black => "30", when Red => "31", when Green => "32", when Yellow => "33", when Blue => "34", when Magenta => "35", when Cyan => "36", when Grey => "37", when Light_Black => "90", when Light_Red => "91", when Light_Green => "92", when Light_Yellow => "93", when Light_Blue => "94", when Light_Magenta => "95", when Light_Cyan => "96", when Light_Grey => "97") & "m"); function Background (Color : Colors) return String is (CSI & (case Color is when Default => "49", when Black => "40", when Red => "41", when Green => "42", when Yellow => "43", when Blue => "44", when Magenta => "45", when Cyan => "46", when Grey => "47", when Light_Black => "100", when Light_Red => "101", when Light_Green => "102", when Light_Yellow => "103", when Light_Blue => "104", when Light_Magenta => "105", when Light_Cyan => "106", when Light_Grey => "107") & "m"); function Bit8 (R, G, B : Palette_RGB) return String is (Img (16 + 36 * R + 6 * G + B)); Fg : constant String := "38"; Bg : constant String := "48"; function Palette_Fg (R, G, B : Palette_RGB) return String is (CSI & Fg & ";5;" & Bit8 (R, G, B) & "m"); function Palette_Bg (R, G, B : Palette_RGB) return String is (CSI & Bg & ";5;" & Bit8 (R, G, B) & "m"); function Foreground (Level : Greyscale) return String is (CSI & Fg & ";5;" & Img (232 + Level) & "m"); function Background (Level : Greyscale) return String is (CSI & Bg & ";5;" & Img (232 + Level) & "m"); function Foreground (R, G, B : True_RGB) return String is (CSI & Fg & ";2;" & Img (R) & ";" & Img (G) & ";" & Img (B) & "m"); function Background (R, G, B : True_RGB) return String is (CSI & Bg & ";2;" & Img (R) & ";" & Img (G) & ";" & Img (B) & "m"); Default_Foreground : constant String := CSI & "39m"; Default_Background : constant String := CSI & "49m"; function Color_Wrap (Text : String; Foreground : String := ""; Background : String := "") return String is ((if Foreground /= "" then Foreground else "") & (if Background /= "" then Background else "") & Text & (if Background /= "" then Default_Background else "") & (if Foreground /= "" then Default_Foreground else "")); ------------ -- STYLES -- ------------ function Style (Style : Styles; Active : States := On) return String is (CSI & (case Active is when On => (case Style is when Default => "39", when Bright => "1", when Dim => "2", when Italic => "3", when Underline => "4", when Blink => "5", when Rapid_Blink => "6", when Invert => "7", when Conceal => "8", when Strike => "9", when Fraktur => "20", when Double_Underline => "21" ), when Off => (case Style is when Default => "49", when Bright => "22", when Dim => "22", when Italic => "23", when Underline => "24", when Blink => "25", when Rapid_Blink => "25", when Invert => "27", when Conceal => "28", when Strike => "29", when Fraktur => "23", when Double_Underline => "24" )) & "m"); function Style_Wrap (Text : String; Style : Styles) return String is (ANSI.Style (Style, On) & Text & ANSI.Style (Style, Off)); function Wrap (Text : String; Style : Styles; Foreground : String := ""; Background : String := "") return String is (Style_Wrap (Style => Style, Text => Color_Wrap (Text => Text, Foreground => Foreground, Background => Background))); ------------ -- CURSOR -- ------------ function Cursor (N : Positive; Code : Character) return String is (CSI & Img (N) & Code) with Inline_Always; -- For common Cursor sequences function Back (Cells : Positive := 1) return String is (Cursor (Cells, 'D')); function Down (Lines : Positive := 1) return String is (Cursor (Lines, 'B')); function Forward (Cells : Positive := 1) return String is (Cursor (Cells, 'C')); function Up (Lines : Positive := 1) return String is (Cursor (Lines, 'A')); function Next (Lines : Positive := 1) return String is (Cursor (Lines, 'E')); function Previous (Lines : Positive := 1) return String is (Cursor (Lines, 'F')); function Horizontal (Column : Positive := 1) return String is (Cursor (Column, 'G')); function Position (Row, Column : Positive := 1) return String is (CSI & Img (Row) & ";" & Img (Column) & "H"); Store : constant String := CSI & "s"; Restore : constant String := CSI & "u"; Hide : constant String := CSI & "?25l"; Show : constant String := CSI & "?25h"; -------------- -- CLEARING -- -------------- Clear_Screen : constant String := CSI & "2J"; Clear_Screen_And_Buffer : constant String := CSI & "3J"; Clear_To_Beginning_Of_Screen : constant String := CSI & "2J"; Clear_To_End_Of_Screen : constant String := CSI & "0J"; Clear_Line : constant String := CSI & "2K"; Clear_To_Beginning_Of_Line : constant String := CSI & "1K"; Clear_To_End_Of_Line : constant String := CSI & "0K"; function Scroll_Up (Lines : Positive) return String is (CSI & Img (Lines) & "S"); function Scroll_Down (Lines : Positive) return String is (CSI & Img (Lines) & "T"); end ANSI;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- ------------------------------------------------------------------------------ with HK_Data; use HK_Data; with Sensor; with Storage; with Ada.Real_Time; use Ada.Real_Time; package body Housekeeping is ------------------------- -- Internal operations -- ------------------------- procedure Read_Data; -- Read a value from a temperature sensor ---------------------------- -- Housekeeping task body -- ---------------------------- task body Housekeeping_Task is -- cyclic Next_Time : Time := Clock + Milliseconds (Start_Delay); begin loop delay until Next_Time; Read_Data; Next_Time := Next_Time + Milliseconds (Period); end loop; end Housekeeping_Task; ---------- -- Read -- ---------- procedure Read_Data is Reading : Sensor_Reading; Data : Sensor_Data; SC : Seconds_Count; TS : Time_Span; begin Sensor.Get (Reading); Split (Clock, SC, TS); Data := (Value => Reading, Timestamp => Mission_Time (SC)); Storage.Put (Data); end Read_Data; end Housekeeping;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT is maintained by AdaCore (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ -- Base Test Case or Test Suite -- -- This base type allows composition of both test cases and sub-suites into a -- test suite (Composite pattern) package AUnit.Tests is type Test is abstract tagged limited private; type Test_Access is access all Test'Class; private type Test is abstract tagged limited null record; end AUnit.Tests;
{ "source": "starcoderdata", "programming_language": "ada" }
with ada.Text_IO, ada.Strings.unbounded, ada.Strings.Maps; package body any_Math.any_Geometry.any_d3.any_Modeller.any_Forge is function to_Box_Model (half_Extents : in Vector_3 := (0.5, 0.5, 0.5)) return a_Model is pragma Unreferenced (half_Extents); Modeller : any_Modeller.item; begin Modeller.add_Triangle ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)); Modeller.add_Triangle ((1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 0.0)); -- TODO: Add the rest. return Modeller.Model; end to_Box_Model; function to_Capsule_Model (Length : in Real := 1.0; Radius : in Real := 0.5) return a_Model is use Functions; quality_Level : constant Positive := 4; sides_Count : constant Positive := Positive (quality_Level * 4); -- Number of sides to the cylinder (divisible by 4). type Edge is -- 'Barrel' edge. record Fore : Site; Aft : Site; end record; type Edges is array (Positive range 1 .. sides_Count) of Edge; type arch_Edges is array (Positive range 1 .. quality_Level) of Sites (1 .. sides_Count); tmp, ny, nz, start_nx, start_ny : Real; a : constant Real := Pi * 2.0 / Real (sides_Count); ca : constant Real := Cos (a); sa : constant Real := Sin (a); L : constant Real := Length * 0.5; the_Edges : Edges; Modeller : any_Modeller.item; begin -- Define cylinder body. -- ny := 1.0; nz := 0.0; -- Normal vector = (0, ny, nz) for Each in Edges'Range loop the_Edges (Each).Fore (1) := ny * Radius; the_Edges (Each).Fore (2) := nz * Radius; the_Edges (Each).Fore (3) := L; the_Edges (Each).Aft (1) := ny * Radius; the_Edges (Each).Aft (2) := nz * Radius; the_Edges (Each).Aft (3) := -L; -- Rotate ny, nz. -- tmp := ca * ny - sa * nz; nz := sa * ny + ca * nz; ny := tmp; end loop; for Each in Edges'Range loop if Each /= Edges'Last then Modeller.add_Triangle (the_Edges (Each) .Fore, the_Edges (Each) .Aft, the_Edges (Each + 1).Aft); Modeller.add_Triangle (the_Edges (Each + 1).Aft, the_Edges (Each + 1).Fore, the_Edges (Each) .Fore); else Modeller.add_Triangle (the_Edges (Each) .Fore, the_Edges (Each) .Aft, the_Edges (edges'First).Aft); Modeller.add_Triangle (the_Edges (edges'First).Aft, the_Edges (edges'First).Fore, the_Edges (Each) .Fore); end if; end loop; -- Define fore cylinder cap. -- declare the_arch_Edges : arch_Edges; begin start_nx := 0.0; start_ny := 1.0; for each_Hoop in 1 .. quality_Level loop -- Get start_n2 = rotated start_n. -- declare start_nx2 : constant Real := ca * start_nx + sa * start_ny; start_ny2 : constant Real := -sa * start_nx + ca * start_ny; begin -- Get n = start_n and n2 = start_n2. -- ny := start_ny; nz := 0.0; declare nx2 : constant Real := start_nx2; ny2 : Real := start_ny2; nz2 : Real := 0.0; begin for Each in 1 .. sides_Count loop the_arch_Edges (each_Hoop)(Each) (1) := ny2 * Radius; the_arch_Edges (each_Hoop)(Each) (2) := nz2 * Radius; the_arch_Edges (each_Hoop)(Each) (3) := nx2 * Radius + L; -- Rotate n, n2. -- tmp := ca * ny - sa * nz; nz := sa * ny + ca * nz; ny := tmp; tmp := ca * ny2 - sa * nz2; nz2 := sa * ny2 + ca * nz2; ny2 := tmp; end loop; end; start_nx := start_nx2; start_ny := start_ny2; end; end loop; for Each in 1 .. sides_Count loop if Each /= sides_Count then Modeller.add_Triangle (the_Edges (Each) .Fore, the_Edges (Each + 1).Fore, the_arch_Edges (1) (Each)); else Modeller.add_Triangle (the_Edges (Each).Fore, the_Edges (1) .Fore, the_arch_Edges (1) (Each)); end if; if Each /= sides_Count then Modeller.add_Triangle (the_Edges (Each + 1).Fore, the_arch_Edges (1) (Each + 1), the_arch_Edges (1) (Each)); else Modeller.add_Triangle (the_Edges (1).Fore, the_arch_Edges (1) (1), the_arch_Edges (1) (Each)); end if; end loop; for each_Hoop in 1 .. quality_Level - 1 loop for Each in 1 .. sides_Count loop declare function next_Hoop_Vertex return Positive is begin if Each = sides_Count then return 1; else return Each + 1; end if; end next_Hoop_Vertex; begin Modeller.add_Triangle (the_arch_Edges (each_Hoop) (Each), the_arch_Edges (each_Hoop) (next_Hoop_Vertex), the_arch_Edges (each_Hoop + 1) (Each)); if each_Hoop /= quality_Level - 1 then Modeller.add_Triangle (the_arch_Edges (each_Hoop) (next_Hoop_Vertex), the_arch_Edges (each_Hoop + 1) (next_Hoop_Vertex), the_arch_Edges (each_Hoop + 1) (Each)); end if; end; end loop; end loop; end; -- Define aft cylinder cap. -- declare the_arch_Edges : arch_Edges; begin start_nx := 0.0; start_ny := 1.0; for each_Hoop in 1 .. quality_Level loop declare -- Get start_n2 = rotated start_n. -- start_nx2 : constant Real := ca * start_nx - sa * start_ny; start_ny2 : constant Real := sa * start_nx + ca * start_ny; begin -- Get n = start_n and n2 = start_n2. -- ny := start_ny; nz := 0.0; declare nx2 : constant Real := start_nx2; ny2 : Real := start_ny2; nz2 : Real := 0.0; begin for Each in 1 .. sides_Count loop the_arch_Edges (each_Hoop) (Each) (1) := ny2 * Radius; the_arch_Edges (each_Hoop) (Each) (2) := nz2 * Radius; the_arch_Edges (each_Hoop) (Each) (3) := nx2 * Radius - L; -- Rotate n, n2 -- tmp := ca * ny - sa * nz; nz := sa * ny + ca * nz; ny := tmp; tmp := ca * ny2 - sa * nz2; nz2 := sa * ny2 + ca * nz2; ny2 := tmp; end loop; end; start_nx := start_nx2; start_ny := start_ny2; end; end loop; for Each in 1 .. sides_Count loop if Each /= sides_Count then Modeller.add_Triangle (the_Edges (Each).Aft, the_arch_Edges (1) (Each), the_Edges (Each + 1).Aft); else Modeller.add_Triangle (the_Edges (Each).Aft, the_arch_Edges (1) (Each), the_Edges (1).Aft); end if; if Each /= sides_Count then Modeller.add_Triangle (The_Edges (Each + 1).Aft, the_arch_Edges (1) (Each), the_arch_Edges (1) (Each + 1)); else Modeller.add_Triangle (the_Edges (1).Aft, the_arch_Edges (1) (Each), the_arch_Edges (1) (1)); end if; end loop; for each_Hoop in 1 .. quality_Level - 1 loop for Each in 1 .. sides_Count loop declare function next_Hoop_Vertex return Positive is begin if Each = sides_Count then return 1; else return Each + 1; end if; end next_hoop_Vertex; begin Modeller.add_Triangle (the_arch_Edges (each_Hoop) (Each), the_arch_Edges (each_Hoop + 1) (Each), the_arch_Edges (each_Hoop) (next_Hoop_Vertex)); if each_Hoop /= quality_Level - 1 then Modeller.add_Triangle (the_arch_Edges (each_Hoop) (next_hoop_Vertex), the_arch_Edges (each_Hoop + 1) (Each), the_arch_Edges (each_Hoop + 1) (next_Hoop_Vertex)); end if; end; end loop; end loop; end; return Modeller.Model; end to_capsule_Model; -- Polar to euclidian shape models. -- function to_Radians (From : in Latitude) return Radians is begin return Radians (From) * Pi / 180.0; end to_Radians; function to_Radians (From : in Longitude) return Radians is begin return Radians (From) * Pi / 180.0; end to_Radians; function polar_Model_from (model_Filename : in String) return polar_Model -- TODO: Handle different file formats. is use Functions, ada.Text_IO, ada.Strings.unbounded; the_File : File_type; the_Text : unbounded_String; begin open (the_File, in_File, model_Filename); while not end_of_File (the_File) loop append (the_Text, get_Line (the_File) & " "); end loop; declare text_Length : constant Natural := Length (the_Text); First : Positive := 1; function get_Real return Real is use ada.Strings, ada.Strings.Maps; real_Set : constant Character_Set := to_Set (Span => (Low => '0', High => '9')) or to_Set ('-' & '.'); Last : Positive; Result : Real; begin find_Token (the_Text, Set => real_Set, From => First, Test => Inside, First => First, Last => Last); Result := Real'Value (Slice (the_Text, Low => First, High => Last)); First := Last + 1; return Result; end get_Real; Lat : Latitude; Long : Longitude; Value : Integer; Distance : Real; Scale : constant Real := 10.0; -- TODO: Add a 'Scale' parameter. the_Model : polar_Model; begin while First < text_Length loop Value := Integer (get_Real); exit when Value = 360; Long := Longitude (Value); Lat := Latitude (get_Real); Distance := get_Real; the_Model (Long) (Lat).Site (1) := Scale * Distance * Cos (to_Radians (Lat)) * Sin (to_Radians (Long)); the_Model (Long) (Lat).Site (2) := Scale * Distance * Sin (to_Radians (Lat)); the_Model (Long) (Lat).Site (3) := Scale * Distance * Cos (to_Radians (Lat)) * Cos (to_Radians (Long)); end loop; return the_Model; end; end polar_Model_from; function mesh_Model_from (Model : in polar_Model) return a_Model is the_raw_Model : polar_Model := Model; the_mesh_Model : a_Model (site_Count => 2522, tri_Count => 73 * (16 * 4 + 6)); the_longitude : Longitude := 0; the_latitude : Latitude ; the_Vertex : Positive := 1; the_Triangle : Positive := 1; the_North_Pole : Positive; the_South_Pole : Positive; function Sum (the_Longitude : in Longitude; Increment : in Integer) return Longitude is Result : Integer := Integer (the_Longitude) + Increment; begin if Result >= 360 then Result := Result - 360; end if; return longitude (Result); end Sum; begin the_mesh_Model.Sites (the_Vertex) := (the_raw_model (0) (-90).Site); the_North_Pole := the_Vertex; the_raw_Model (0) (-90).Id := the_Vertex; the_Vertex := the_Vertex + 1; the_mesh_Model.Sites (the_Vertex) := (the_raw_model (0) (90).Site); the_south_Pole := the_Vertex; the_raw_Model (0) (90).Id := the_Vertex; the_Vertex := the_Vertex + 1; loop the_latitude := -90; loop if the_Latitude = -90 then the_raw_Model (the_Longitude) (the_Latitude).Id := the_North_Pole; elsif the_Latitude = 90 then the_raw_Model (the_Longitude) (the_Latitude).Id := the_South_Pole; else the_mesh_Model.Sites (the_Vertex) := the_raw_model (the_Longitude) (the_Latitude).Site; the_raw_Model (the_Longitude) (the_Latitude).Id := the_Vertex; the_Vertex := the_Vertex + 1; end if; exit when the_Latitude = 90; the_Latitude := the_Latitude + 5; end loop; exit when the_Longitude = 355; the_Longitude := the_Longitude + 5; end loop; the_Longitude := 0; loop the_mesh_Model.Triangles (the_Triangle) := (1 => the_North_Pole, 2 => the_raw_Model (Sum (the_Longitude, 5)) (-85).Id, 3 => the_raw_Model ( the_Longitude ) (-85).Id); the_Triangle := the_Triangle + 1; the_mesh_Model.Triangles (the_Triangle) := (1 => the_South_Pole, 2 => the_raw_Model (the_Longitude) (85).Id, 3 => the_raw_Model (Sum (the_Longitude, 5)) (85).Id); the_Triangle := the_Triangle + 1; the_Latitude := -85; loop the_mesh_Model.Triangles (the_Triangle) := (1 => the_raw_Model ( the_Longitude) (the_Latitude ).Id, 2 => the_raw_Model (Sum (the_Longitude, 5)) (the_Latitude ).Id, 3 => the_raw_Model ( the_Longitude) (the_Latitude + 5).Id); the_Triangle := the_Triangle + 1; the_mesh_Model.Triangles (the_Triangle) := (1 => the_raw_Model (the_Longitude) (the_Latitude + 5).Id, 2 => the_raw_Model (Sum (the_Longitude, 5)) (the_Latitude ).Id, 3 => the_raw_Model (Sum (the_Longitude, 5)) (the_Latitude + 5).Id); the_Triangle := the_Triangle + 1; the_Latitude := the_Latitude + 5; exit when the_Latitude = 85; end loop; exit when the_Longitude = 355; the_Longitude := the_Longitude + 5; end loop; the_mesh_Model.Triangles (the_Triangle) := (1 => the_North_Pole, 2 => the_raw_Model (5) (-85).Id, 3 => the_raw_Model (0) (-85).Id); the_Triangle := the_Triangle + 1; the_mesh_Model.Triangles (the_Triangle) := (1 => the_South_Pole, 2 => the_raw_Model (0) (85).Id, 3 => the_raw_Model (5) (85).Id); the_Triangle := the_Triangle + 1; the_latitude := -85; loop the_mesh_Model.Triangles (the_Triangle) := (1 => the_raw_Model (0) (the_Latitude ).Id, 2 => the_raw_Model (5) (the_Latitude ).Id, 3 => the_raw_Model (0) (the_Latitude + 5).Id); the_Triangle := the_Triangle + 1; the_mesh_Model.Triangles (the_Triangle) := (1 => the_raw_Model (0) (the_Latitude + 5).Id, 2 => the_raw_Model (5) (the_Latitude ).Id, 3 => the_raw_Model (5) (the_Latitude + 5).Id); the_Triangle := the_Triangle + 1; the_Latitude := the_Latitude + 5; exit when the_Latitude = 85; end loop; return the_mesh_Model; end mesh_Model_from; end any_Math.any_Geometry.any_d3.any_Modeller.any_Forge;
{ "source": "starcoderdata", "programming_language": "ada" }
with GL.Low_Level; package GL.Objects.Queries is pragma Preelaborate; type Query_Type is (Vertices_Submitted, Primitives_Submitted, Vertex_Shader_Invocations, Tess_Control_Shader_Invocations, Tess_Evaluation_Shader_Invocations, Geometry_Shader_Primitives_Emitted, Fragment_Shader_Invocations, Compute_Shader_Invocations, Clipping_Input_Primitives, Clipping_Output_Primitives, Geometry_Shader_Invocations, Time_Elapsed, Samples_Passed, Any_Samples_Passed, Primitives_Generated, Any_Samples_Passed_Conservative, Timestamp); -- Has to be defined here because of the subtype declaration below for Query_Type use (Vertices_Submitted => 16#82EE#, Primitives_Submitted => 16#82EF#, Vertex_Shader_Invocations => 16#82F0#, Tess_Control_Shader_Invocations => 16#82F1#, Tess_Evaluation_Shader_Invocations => 16#82F2#, Geometry_Shader_Primitives_Emitted => 16#82F3#, Fragment_Shader_Invocations => 16#82F4#, Compute_Shader_Invocations => 16#82F5#, Clipping_Input_Primitives => 16#82F6#, Clipping_Output_Primitives => 16#82F7#, Geometry_Shader_Invocations => 16#887F#, Time_Elapsed => 16#88BF#, Samples_Passed => 16#8914#, Any_Samples_Passed => 16#8C2F#, Primitives_Generated => 16#8C87#, Any_Samples_Passed_Conservative => 16#8D6A#, Timestamp => 16#8E28#); for Query_Type'Size use Low_Level.Enum'Size; subtype Async_Query_Type is Query_Type range Vertices_Submitted .. Any_Samples_Passed_Conservative; subtype Timestamp_Query_Type is Query_Type range Timestamp .. Timestamp; subtype Stream_Query_Type is Query_Type with Static_Predicate => Stream_Query_Type in Primitives_Generated; type Query_Param is (Result, Result_Available, Result_No_Wait); type Query (Target : Query_Type) is new GL_Object with private; overriding procedure Initialize_Id (Object : in out Query); overriding procedure Delete_Id (Object : in out Query); overriding function Identifier (Object : Query) return Types.Debug.Identifier is (Types.Debug.Query); type Active_Query is limited new Ada.Finalization.Limited_Controlled with private; function Begin_Query (Object : in out Query; Index : in Natural := 0) return Active_Query'Class with Pre => Object.Target in Async_Query_Type and (if Object.Target not in Stream_Query_Type then Index = 0); -- Start an asynchronous query. The value returned is of a controlled -- type, meaning you must assign it to some local variable, so that -- the query will be automatically ended when the variable goes out -- of scope. -- -- Queries of type Timestamp are not used within a scope. For such -- a query you can record the time into the query object by calling -- Record_Current_Time. -- -- Certain queries support multiple query operations; one for each -- index. The index represents the vertex output stream used in a -- Geometry Shader. These targets are: -- -- * Primitives_Generated function Result_Available (Object : in out Query) return Boolean; -- Return true if a result is available, false otherwise. This function -- can be used to avoid calling Result (and thereby stalling the CPU) -- when the result is not yet available. function Result_If_Available (Object : in out Query; Default : Boolean) return Boolean; function Result_If_Available (Object : in out Query; Default : Natural) return Natural; function Result_If_Available (Object : in out Query; Default : UInt64) return UInt64; -- Return the result if available, otherwise return the default value function Result (Object : in out Query) return Boolean; function Result (Object : in out Query) return Natural; function Result (Object : in out Query) return UInt64; -- Return the result. If the result is not yet available, then the -- CPU will stall until the result becomes available. This means -- that if you do not call Result_Available, then this function call -- will make the query synchronous. procedure Record_Current_Time (Object : in out Query); -- Record the time when the GPU has completed all previous commands -- in a query object. The result must be retrieved asynchronously using -- one of the Result functions. function Get_Current_Time return Long; -- Return the time when the GPU has received (but not necessarily -- completed) all previous commands. Calling this function stalls the CPU. private for Query_Param use (Result => 16#8866#, Result_Available => 16#8867#, Result_No_Wait => 16#9194#); for Query_Param'Size use Low_Level.Enum'Size; type Query (Target : Query_Type) is new GL_Object with null record; type Active_Query is limited new Ada.Finalization.Limited_Controlled with record Target : Query_Type; Index : Natural; Finalized : Boolean; end record; overriding procedure Finalize (Object : in out Active_Query); end GL.Objects.Queries;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Util.Http.Clients.Curl.Constants; package body Util.Http.Clients.Curl is use System; pragma Linker_Options ("-lcurl"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl"); function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access; Manager : aliased Curl_Http_Manager; -- ------------------------------ -- Register the CURL Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. -- ------------------------------ procedure Check_Code (Code : in CURL_Code; Message : in String) is begin if Code /= CURLE_OK then declare Error : constant Chars_Ptr := Curl_Easy_Strerror (Code); Msg : constant String := Interfaces.C.Strings.Value (Error); begin Log.Error ("{0}: {1}", Message, Msg); raise Connection_Error with Msg; end; end if; end Check_Code; -- ------------------------------ -- Create a new HTTP request associated with the current request manager. -- ------------------------------ procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); Request : Curl_Http_Request_Access; Data : CURL; begin Data := Curl_Easy_Init; if Data = System.Null_Address then raise Storage_Error with "curl_easy_init cannot create the CURL instance"; end if; Request := new Curl_Http_Request; Request.Data := Data; Http.Delegate := Request.all'Access; end Create; function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is begin return Curl_Http_Request'Class (Http.Delegate.all)'Access; end Get_Request; -- ------------------------------ -- This function is called by CURL when a response line was read. -- ------------------------------ function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T is Total : constant Size_T := Size * Nmemb; Line : constant String := Interfaces.C.Strings.Value (Data, Total); begin Log.Info ("RCV: {0}", Line); if Response.Parsing_Body then Ada.Strings.Unbounded.Append (Response.Content, Line); elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then Response.Parsing_Body := True; else declare Pos : constant Natural := Util.Strings.Index (Line, ':'); Start : Natural; Last : Natural; begin if Pos > 0 then Start := Pos + 1; while Start <= Line'Last and Line (Start) = ' ' loop Start := Start + 1; end loop; Last := Line'Last; while Last >= Start and (Line (Last) = ASCII.CR or Line (Last) = ASCII.LF) loop Last := Last - 1; end loop; Response.Add_Header (Name => Line (Line'First .. Pos - 1), Value => Line (Start .. Last)); end if; end; end if; return Total; end Read_Response; procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("GET {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Get; procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); use Interfaces.C; Req : constant Curl_Http_Request_Access := Get_Request (Http); Result : CURL_Code; Response : Curl_Http_Response_Access; Status : aliased C.long; begin Log.Info ("POST {0}", URI); Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION, Read_Response'Access); Check_Code (Result, "set callback"); Interfaces.C.Strings.Free (Req.URL); Req.URL := Strings.New_String (URI); Interfaces.C.Strings.Free (Req.Content); Req.Content := Strings.New_String (Data); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1); Check_Code (Result, "set header"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL); Check_Code (Result, "set url"); Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content); Check_Code (Result, "set post data"); Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length); Check_Code (Result, "set post data"); Response := new Curl_Http_Response; Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response); Check_Code (Result, "set write data"); Reply.Delegate := Response.all'Access; Result := Curl_Easy_Perform (Req.Data); Check_Code (Result, "get request"); Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access); Check_Code (Result, "get response code"); Response.Status := Natural (Status); end Do_Post; overriding procedure Finalize (Request : in out Curl_Http_Request) is begin if Request.Data /= System.Null_Address then Curl_Easy_Cleanup (Request.Data); Request.Data := System.Null_Address; end if; if Request.Headers /= null then Curl_Slist_Free_All (Request.Headers); Request.Headers := null; end if; Interfaces.C.Strings.Free (Request.URL); Interfaces.C.Strings.Free (Request.Content); end Finalize; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Curl_Http_Response) return String is begin return Ada.Strings.Unbounded.To_String (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Curl_Http_Response) return Natural is begin return Reply.Status; end Get_Status; end Util.Http.Clients.Curl;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ -- -- SPARK Proof Analysis Tool -- -- S.P.A.T. - Object representing a JSON "proof" object. -- ------------------------------------------------------------------------------ private with Ada.Tags; with SPAT.Entity_Location; with SPAT.Entity.Tree; with SPAT.Field_Names; with SPAT.Preconditions; package SPAT.Proof_Item is use all type GNATCOLL.JSON.JSON_Value_Type; --------------------------------------------------------------------------- -- Has_Required_Fields --------------------------------------------------------------------------- function Has_Required_Fields (Object : in JSON_Value; Version : in File_Version) return Boolean is (Entity_Location.Has_Required_Fields (Object => Object) and Preconditions.Ensure_Rule_Severity (Object => Object) and Preconditions.Ensure_Field (Object => Object, Field => Field_Names.Check_Tree, Kind => JSON_Array_Type, Is_Optional => (case Version is when GNAT_CE_2019 => False, when GNAT_CE_2020 => True))); type T is new Entity_Location.T with private; --------------------------------------------------------------------------- -- Create -- -- This is a dummy. The object returned by Create is empty. For the real -- "creation" of a proper object, you need to call Add_To_Tree. --------------------------------------------------------------------------- overriding function Create (Object : in JSON_Value) return T with Pre => Has_Required_Fields (Object => Object, Version => GNAT_CE_2019); --------------------------------------------------------------------------- -- "<" -- -- Comparison operator for proof items. --------------------------------------------------------------------------- overriding function "<" (Left : in Proof_Item.T; Right : in Proof_Item.T) return Boolean; --------------------------------------------------------------------------- -- Add_To_Tree --------------------------------------------------------------------------- procedure Add_To_Tree (Object : in JSON_Value; Version : in File_Version; Tree : in out Entity.Tree.T; Parent : in Entity.Tree.Cursor) with Pre => Has_Required_Fields (Object => Object, Version => Version); --------------------------------------------------------------------------- -- Has_Failed_Attempts --------------------------------------------------------------------------- not overriding function Has_Failed_Attempts (This : in T) return Boolean; --------------------------------------------------------------------------- -- Is_Unjustified --------------------------------------------------------------------------- not overriding function Is_Unjustified (This : in T) return Boolean; --------------------------------------------------------------------------- -- Has_Unproved_Attempts --------------------------------------------------------------------------- not overriding function Has_Unproved_Attempts (This : in T) return Boolean; --------------------------------------------------------------------------- -- Rule --------------------------------------------------------------------------- not overriding function Rule (This : in T) return Subject_Name; --------------------------------------------------------------------------- -- Max_Time --------------------------------------------------------------------------- not overriding function Max_Time (This : in T) return Duration; --------------------------------------------------------------------------- -- Total_Time --------------------------------------------------------------------------- not overriding function Total_Time (This : in T) return Duration; --------------------------------------------------------------------------- -- Suppressed --------------------------------------------------------------------------- not overriding function Suppressed (This : in T) return Subject_Name; --------------------------------------------------------------------------- -- Before --------------------------------------------------------------------------- function Before (Left : in Entity.T'Class; Right : in Entity.T'Class) return Boolean is (Proof_Item.T (Left) < Proof_Item.T (Right)); package By_Duration is new Entity.Tree.Generic_Sorting (Before => Before); --------------------------------------------------------------------------- -- Sort_By_Duration --------------------------------------------------------------------------- procedure Sort_By_Duration (Tree : in out Entity.Tree.T; Parent : in Entity.Tree.Cursor) renames By_Duration.Sort; type Checks_Sentinel is new Entity.T with private; --------------------------------------------------------------------------- -- Has_Failed_Attempts --------------------------------------------------------------------------- function Has_Failed_Attempts (This : in Checks_Sentinel) return Boolean; --------------------------------------------------------------------------- -- Is_Unproved --------------------------------------------------------------------------- function Is_Unproved (This : in Checks_Sentinel) return Boolean; private type Checks_Sentinel is new Entity.T with record Has_Failed_Attempts : Boolean; Is_Unproved : Boolean; end record; --------------------------------------------------------------------------- -- Image --------------------------------------------------------------------------- overriding function Image (This : in Checks_Sentinel) return String is (Ada.Tags.External_Tag (Checks_Sentinel'Class (This)'Tag) & ": " & "(Has_Failed_Attempts => " & This.Has_Failed_Attempts'Image & ", Is_Unproved => " & This.Is_Unproved'Image & ")"); --------------------------------------------------------------------------- -- Has_Failed_Attempts --------------------------------------------------------------------------- not overriding function Has_Failed_Attempts (This : in Checks_Sentinel) return Boolean is (This.Has_Failed_Attempts); --------------------------------------------------------------------------- -- Is_Unproved --------------------------------------------------------------------------- not overriding function Is_Unproved (This : in Checks_Sentinel) return Boolean is (This.Is_Unproved); type Proof_Item_Sentinel is new Entity.T with null record; --------------------------------------------------------------------------- -- Image --------------------------------------------------------------------------- overriding function Image (This : in Proof_Item_Sentinel) return String is (Ada.Tags.External_Tag (Proof_Item_Sentinel'Class (This)'Tag) & ": ()"); type T is new Entity_Location.T with record Suppressed : Subject_Name; Rule : Subject_Name; Severity : Subject_Name; Max_Time : Duration; -- Longest time spent in proof (successful or not) Total_Time : Duration; -- Accumulated proof time. Has_Failed_Attempts : Boolean; Has_Unproved_Attempts : Boolean; Is_Unjustified : Boolean; end record; --------------------------------------------------------------------------- -- Has_Failed_Attempts --------------------------------------------------------------------------- not overriding function Has_Failed_Attempts (This : in T) return Boolean is (This.Has_Failed_Attempts); --------------------------------------------------------------------------- -- Is_Unjustified --------------------------------------------------------------------------- not overriding function Is_Unjustified (This : in T) return Boolean is (This.Is_Unjustified); --------------------------------------------------------------------------- -- Has_Unproved_Attempts --------------------------------------------------------------------------- not overriding function Has_Unproved_Attempts (This : in T) return Boolean is (This.Has_Unproved_Attempts); --------------------------------------------------------------------------- -- Max_Time --------------------------------------------------------------------------- not overriding function Max_Time (This : in T) return Duration is (This.Max_Time); --------------------------------------------------------------------------- -- Rule --------------------------------------------------------------------------- not overriding function Rule (This : in T) return Subject_Name is (This.Rule); --------------------------------------------------------------------------- -- Suppressed --------------------------------------------------------------------------- not overriding function Suppressed (This : in T) return Subject_Name is (This.Suppressed); --------------------------------------------------------------------------- -- Total_Time --------------------------------------------------------------------------- not overriding function Total_Time (This : in T) return Duration is (This.Total_Time); end SPAT.Proof_Item;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------- with Interfaces; with Ada.Characters.Latin_1; with Audio.Wavefiles; with Audio.RIFF.Wav.Formats; with Audio.RIFF.Wav.GUIDs; package body WaveFiles_Gtk.Wavefile_Manager is -------------- -- Get_Info -- -------------- function Get_Info (Wavefile : String) return String is WF_In : Audio.Wavefiles.Wavefile; RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible; function Get_RIFF_GUID_String (Sub_Format : Audio.RIFF.Wav.Formats.GUID) return String; function Get_RIFF_Extended (RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible) return String; package Wav_Read renames Audio.Wavefiles; use Interfaces; function Get_RIFF_GUID_String (Sub_Format : Audio.RIFF.Wav.Formats.GUID) return String is use type Audio.RIFF.Wav.Formats.GUID; begin if Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_Undefined then return "Subformat: undefined"; elsif Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_PCM then return "Subformat: KSDATAFORMAT_SUBTYPE_PCM (IEC 60958 PCM)"; elsif Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_IEEE_Float then return "Subformat: KSDATAFORMAT_SUBTYPE_IEEE_FLOAT " & "(IEEE Floating-Point PCM)"; else return "Subformat: unknown"; end if; end Get_RIFF_GUID_String; function Get_RIFF_Extended (RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible) return String is S : constant String := ("Valid bits per sample: " & Unsigned_16'Image (RIFF_Data.Valid_Bits_Per_Sample)); begin if RIFF_Data.Size > 0 then return (S & Ada.Characters.Latin_1.LF & Get_RIFF_GUID_String (RIFF_Data.Sub_Format)); else return ""; end if; end Get_RIFF_Extended; begin Wav_Read.Open (WF_In, Wav_Read.In_File, Wavefile); RIFF_Data := Wav_Read.Format_Of_Wavefile (WF_In); Wav_Read.Close (WF_In); declare S_Wav_1 : constant String := ("Bits per sample: " & Audio.RIFF.Wav.Formats.Wav_Bit_Depth'Image (RIFF_Data.Bits_Per_Sample) & Ada.Characters.Latin_1.LF & "Channels: " & Unsigned_16'Image (RIFF_Data.Channels) & Ada.Characters.Latin_1.LF & "Samples per second: " & Audio.RIFF.Wav.Formats.Wav_Sample_Rate'Image (RIFF_Data.Samples_Per_Sec) & Ada.Characters.Latin_1.LF & "Extended size: " & Unsigned_16'Image (RIFF_Data.Size) & Ada.Characters.Latin_1.LF); S_Wav_2 : constant String := Get_RIFF_Extended (RIFF_Data); begin return "File: " & Wavefile & Ada.Characters.Latin_1.LF & S_Wav_1 & S_Wav_2; end; end Get_Info; end WaveFiles_Gtk.Wavefile_Manager;
{ "source": "starcoderdata", "programming_language": "ada" }
with SPARKNaCl.PDebug; with SPARKNaCl.Debug; with SPARKNaCl.Utils; with SPARKNaCl.Car; with Ada.Text_IO; use Ada.Text_IO; package body SPARKNaCl.Tests is GF_2 : constant Normal_GF := (2, others => 0); P : constant Normal_GF := (0 => 16#FFED#, 15 => 16#7FFF#, others => 16#FFFF#); P_Minus_1 : constant Normal_GF := (0 => 16#FFEC#, 15 => 16#7FFF#, others => 16#FFFF#); P_Plus_1 : constant Normal_GF := (0 => 16#FFEE#, 15 => 16#7FFF#, others => 16#FFFF#); procedure GF_Stress is A, B, C : Normal_GF; C2 : GF32; D : Product_GF; begin Put_Line ("GF_Stress case 1 - 0 * 0"); A := (others => 0); B := (others => 0); C := A * B; PDebug.DH16 ("Result is", C); Put_Line ("GF_Stress case 2 - FFFF * FFFF"); A := (others => 16#FFFF#); B := (others => 16#FFFF#); C := A * B; PDebug.DH16 ("Result is", C); Put_Line ("GF_Stress case 3 - Seminormal Product GF Max"); D := (0 => 132_051_011, others => 16#FFFF#); C2 := Car.Product_To_Seminormal (D); PDebug.DH32 ("Result is", C2); Put_Line ("GF_Stress case 4 - Seminormal Product tricky case"); D := (0 => 131_071, others => 16#FFFF#); C2 := Car.Product_To_Seminormal (D); PDebug.DH32 ("Result is", C2); end GF_Stress; procedure Car_Stress is A : GF64; C : Product_GF; SN : Seminormal_GF; NGF : Nearlynormal_GF; R : Normal_GF; begin -- Case 1 - using typed API A := (0 .. 14 => 65535, 15 => 65535 + 2**32); PDebug.DH64 ("Case 1 - A is", A); SN := Car.Product_To_Seminormal (A); PDebug.DH32 ("Case 1 - SN is", SN); NGF := Car.Seminormal_To_Nearlynormal (SN); PDebug.DH32 ("Case 1 - NGF is", NGF); R := Car.Nearlynormal_To_Normal (NGF); PDebug.DH16 ("Case 1 - R is", R); -- Case 2 Upper bounds on all limbs of a Product_GF C := (0 => MGFLC * MGFLP, 1 => (MGFLC - 37 * 1) * MGFLP, 2 => (MGFLC - 37 * 2) * MGFLP, 3 => (MGFLC - 37 * 3) * MGFLP, 4 => (MGFLC - 37 * 4) * MGFLP, 5 => (MGFLC - 37 * 5) * MGFLP, 6 => (MGFLC - 37 * 6) * MGFLP, 7 => (MGFLC - 37 * 7) * MGFLP, 8 => (MGFLC - 37 * 8) * MGFLP, 9 => (MGFLC - 37 * 9) * MGFLP, 10 => (MGFLC - 37 * 10) * MGFLP, 11 => (MGFLC - 37 * 11) * MGFLP, 12 => (MGFLC - 37 * 12) * MGFLP, 13 => (MGFLC - 37 * 13) * MGFLP, 14 => (MGFLC - 37 * 14) * MGFLP, 15 => (MGFLC - 37 * 15) * MGFLP); PDebug.DH64 ("Case 2 - C is", C); SN := Car.Product_To_Seminormal (C); PDebug.DH32 ("Case 2 - SN is", SN); NGF := Car.Seminormal_To_Nearlynormal (SN); PDebug.DH32 ("Case 2 - NGF is", NGF); R := Car.Nearlynormal_To_Normal (NGF); PDebug.DH16 ("Case 2 - R is", R); -- Intermediate (pre-normalization) result of -- Square (Normal_GF'(others => 16#FFFF)) A := (16#23AFB8A023B#, 16#215FBD40216#, 16#1F0FC1E01F1#, 16#1CBFC6801CC#, 16#1A6FCB201A7#, 16#181FCFC0182#, 16#15CFD46015D#, 16#137FD900138#, 16#112FDDA0113#, 16#EDFE2400EE#, 16#C8FE6E00C9#, 16#A3FEB800A4#, 16#7EFF02007F#, 16#59FF4C005A#, 16#34FF960035#, 16#FFFE00010#); PDebug.DH64 ("Case 3 - A is", A); SN := Car.Product_To_Seminormal (A); PDebug.DH32 ("Case 3 - SN is", SN); NGF := Car.Seminormal_To_Nearlynormal (SN); PDebug.DH32 ("Case 3 - NGF is", NGF); R := Car.Nearlynormal_To_Normal (NGF); PDebug.DH16 ("Case 3 - R is", R); end Car_Stress; procedure Diff_Car_Stress is C : Nearlynormal_GF; R : Normal_GF; begin C := (others => 0); PDebug.DH32 ("Case 1 - C is", C); R := Car.Nearlynormal_To_Normal (C); PDebug.DH16 ("Case 1 - R is", R); C := (others => 16#ffff#); PDebug.DH32 ("Case 2 - C is", C); R := Car.Nearlynormal_To_Normal (C); PDebug.DH16 ("Case 2 - R is", R); for I in I32 range 65536 .. 65573 loop C (0) := I; PDebug.DH32 ("Case 3," & I'Img & " C is", C); R := Car.Nearlynormal_To_Normal (C); PDebug.DH16 ("Case 3 - R is", R); end loop; C := (others => 0); for I in I32 range -38 .. -1 loop C (0) := I; PDebug.DH32 ("Case 4," & I'Img & " C is", C); R := Car.Nearlynormal_To_Normal (C); PDebug.DH16 ("Case 4 - R is", R); end loop; end Diff_Car_Stress; procedure Pack_Stress is A : Normal_GF; R : Bytes_32; Two_P : constant Normal_GF := P * GF_2; Two_P_Minus_1 : constant Normal_GF := Two_P - GF_1; Two_P_Plus_1 : constant Normal_GF := Two_P + GF_1; begin A := (others => 0); PDebug.DH16 ("Pack Stress - Case 1 - A is", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 1 - R is", R); A := (others => 65535); PDebug.DH16 ("Pack Stress - Case 2 - A is", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 2 - R is", R); A := P; PDebug.DH16 ("Pack Stress - Case 3 - A is P", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 3 - R is", R); A := P_Minus_1; PDebug.DH16 ("Pack Stress - Case 4 - A is P_Minus_1", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 4 - R is", R); A := P_Plus_1; PDebug.DH16 ("Pack Stress - Case 5 - A is P_Plus_1", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 5 - R is", R); A := Two_P; PDebug.DH16 ("Pack Stress - Case 6 - A is Two_P", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 6 - R is", R); A := Two_P_Minus_1; PDebug.DH16 ("Pack Stress - Case 7 - A is Two_P_Minus_1", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 7 - R is", R); A := Two_P_Plus_1; PDebug.DH16 ("Pack Stress - Case 8 - A is Two_P_Plus_1", A); R := Utils.Pack_25519 (A); Debug.DH ("Pack Stress - Case 8 - R is", R); end Pack_Stress; end SPARKNaCl.Tests;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; use Ada.Text_IO; procedure Crossroad is -- Colors type colors is (red, redyellow, green, yellow); -- Lamp protected Lamp is procedure Switch; function Color return colors; private currentColor : colors := red; end Lamp; protected body Lamp is procedure Switch is begin if currentColor = yellow then currentColor := red; else currentColor := colors'Succ(currentColor); end if; Put_Line("Lamp switched to " & colors'Image(currentColor)); end Switch; function Color return colors is begin return currentColor; end Color; end Lamp; -- Controller task Controller is entry Stop; end Controller; task body Controller is stopped : Boolean := false; begin while not stopped loop select accept Stop do stopped := true; end Stop; or -- red delay 3.0; Lamp.Switch; -- redyellow delay 1.0; Lamp.Switch; -- green delay 3.0; Lamp.Switch; -- yellow delay 2.0; Lamp.Switch; end select; end loop; end Controller; type String_Access is access String; task type Vehicle(plate: String_Access); type Vehicle_Access is access Vehicle; task body Vehicle is crossed : Boolean := false; begin Put_Line(plate.all & " arrived"); while not crossed loop if Lamp.Color = green then Put_Line(plate.all & " crossed"); crossed := true; else Put_Line(plate.all & " waiting"); delay 0.2; end if; end loop; end Vehicle; vehicles : array(1 .. 10) of Vehicle_Access; plate : String_Access; begin for i in 1 .. 10 loop plate := new String'("CAR" & Integer'Image(i)); vehicles(i) := new Vehicle(plate); delay 0.5; end loop; --Skip_Line(); delay 15.0; Controller.Stop; end Crossroad;
{ "source": "starcoderdata", "programming_language": "ada" }
package body Ada.Calendar.Naked is function To_Native_Time (T : Time) return System.Native_Calendar.Native_Time is begin return System.Native_Calendar.To_Native_Time (Duration (T)); end To_Native_Time; function To_Time (T : System.Native_Calendar.Native_Time) return Time is begin return Time (System.Native_Calendar.To_Time (T)); end To_Time; function Seconds_From_2150 (T : Time) return Duration is begin return Duration (T); end Seconds_From_2150; procedure Delay_Until (T : Time) is begin System.Native_Calendar.Delay_Until (To_Native_Time (T)); end Delay_Until; end Ada.Calendar.Naked;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Simple_Pages provides a simple implementation of Sites.Page -- -- and Tags.Visible, representing a single page in a usual blog-style -- -- static site. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; with Natools.Web.Sites; with Natools.Web.Tags; private with Natools.References; private with Natools.S_Expressions.Caches; private with Natools.Storage_Pools; private with Natools.Web.Containers; private with Natools.Web.Comments; private with Natools.Web.String_Tables; package Natools.Web.Simple_Pages is type Page_Template is private; procedure Set_Comments (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Set_Comment_Path_Prefix (Object : in out Page_Template; Prefix : in S_Expressions.Atom); procedure Set_Comment_Path_Suffix (Object : in out Page_Template; Suffix : in S_Expressions.Atom); procedure Set_Elements (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Set_Component (Object : in out Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class; Known_Component : out Boolean); procedure Update (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class); Default_Template : constant Page_Template; type Page_Ref is new Tags.Visible and Sites.Page with private; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref; procedure Get_Lifetime (Page : in Page_Ref; Publication : out Ada.Calendar.Time; Has_Publication : out Boolean; Expiration : out Ada.Calendar.Time; Has_Expiration : out Boolean); function Get_Tags (Page : Page_Ref) return Tags.Tag_List; procedure Register (Page : in Page_Ref; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom); overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class); overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom); type Loader is new Sites.Page_Loader with private; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom); function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class; procedure Register_Loader (Site : in out Sites.Site); private type Page_Template is record Comments : Containers.Optional_Expression; Comment_Path_Prefix : S_Expressions.Atom_Refs.Immutable_Reference; Comment_Path_Suffix : S_Expressions.Atom_Refs.Immutable_Reference; Elements : Containers.Expression_Maps.Constant_Map; Name : S_Expressions.Atom_Refs.Immutable_Reference; end record; Default_Template : constant Page_Template := (others => <>); type Page_Data is new Tags.Visible with record Self : Tags.Visible_Access; File_Path : S_Expressions.Atom_Refs.Immutable_Reference; Web_Path : S_Expressions.Atom_Refs.Immutable_Reference; Elements : Containers.Expression_Maps.Constant_Map; Tags : Web.Tags.Tag_List; Dates : Containers.Date_Maps.Constant_Map; Comment_List : Comments.Comment_List; Maps : String_Tables.String_Table_Map; end record; not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean); overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class); package Data_Refs is new References (Page_Data, Storage_Pools.Access_In_Default_Pool'Storage_Pool, Storage_Pools.Access_In_Default_Pool'Storage_Pool); type Page_Ref is new Tags.Visible and Sites.Page with record Ref : Data_Refs.Reference; end record; function Get_Tags (Page : Page_Ref) return Tags.Tag_List is (Page.Ref.Query.Data.Tags); type Loader is new Sites.Page_Loader with record File_Path : S_Expressions.Atom_Refs.Immutable_Reference; end record; end Natools.Web.Simple_Pages;
{ "source": "starcoderdata", "programming_language": "ada" }
package Sort is SIZE : constant Integer := 40; SubType v_range is Integer Range -500..500; type m_array is array(1..SIZE) of v_range; procedure MergeSort(A : in out m_array); -- Internal functions procedure MergeSort(A : in out m_array; startIndex : Integer; endIndex : Integer); procedure ParallelMergeSort(A : in out m_array; startIndex : Integer; midIndex : Integer; endIndex : Integer); procedure Merge(A : in out m_array; startIndex, midIndex, endIndex : in Integer); end sort;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- package body Ada_Pretty.Statements is -------------- -- Document -- -------------- overriding function Document (Self : Block_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is pragma Unreferenced (Pad); Result : League.Pretty_Printers.Document := Printer.New_Document; begin if Self.Declarations /= null then Result.New_Line; Result.Put ("declare"); Result.Append (Self.Declarations.Document (Printer, 0).Nest (3)); end if; Result.New_Line; Result.Put ("begin"); if Self.Statements = null then declare Nil : League.Pretty_Printers.Document := Printer.New_Document; begin Nil.New_Line; Nil.Put ("null;"); Nil.Nest (3); Result.Append (Nil); end; else Result.Append (Self.Statements.Document (Printer, 0).Nest (3)); end if; if Self.Exceptions /= null then Result.New_Line; Result.Put ("exception"); Result.Append (Self.Exceptions.Document (Printer, 0).Nest (3)); end if; Result.New_Line; Result.Put ("end;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Case_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("case "); Result.Append (Self.Expression.Document (Printer, Pad)); Result.Put (" is"); Result.Append (Self.List.Document (Printer, Pad).Nest (3)); Result.New_Line; Result.Put ("end case;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Case_Path; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("when "); Result.Append (Self.Choice.Document (Printer, Pad)); Result.Put (" =>"); Result.Append (Self.List.Document (Printer, Pad).Nest (3)); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Elsif_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.New_Line; Result.Put ("elsif "); Result.Append (Self.Condition.Document (Printer, Pad)); Result.Put (" then"); Result.Append (Self.List.Document (Printer, Pad).Nest (3)); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Extended_Return_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("return "); Result.Append (Self.Name.Document (Printer, Pad)); Result.Put (" : "); Result.Append (Self.Type_Definition.Document (Printer, Pad).Nest (2)); if Self.Initialization /= null then declare Init : League.Pretty_Printers.Document := Printer.New_Document; begin Init.New_Line; Init.Append (Self.Initialization.Document (Printer, 0)); Init.Nest (2); Init.Group; Result.Put (" :="); Result.Append (Init); end; end if; Result.New_Line; Result.Put ("do"); Result.Append (Self.Statements.Document (Printer, 0).Nest (3)); Result.New_Line; Result.Put ("end return;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : For_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("for "); Result.Append (Self.Name.Document (Printer, Pad)); declare Init : League.Pretty_Printers.Document := Printer.New_Document; begin Init.Put (" in "); Init.Append (Self.Iterator.Document (Printer, 0).Nest (2)); Init.New_Line; Init.Put ("loop"); Init.Group; Result.Append (Init); end; Result.Append (Self.Statements.Document (Printer, 0).Nest (3)); Result.New_Line; Result.Put ("end loop;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Loop_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; Init : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; if Self.Condition = null then Result.Put ("loop"); else Init.Put ("while "); Init.Append (Self.Condition.Document (Printer, Pad).Nest (2)); Init.New_Line; Init.Put ("loop"); Init.Group; Result.Append (Init); end if; Result.Append (Self.Statements.Document (Printer, 0).Nest (3)); Result.New_Line; Result.Put ("end loop;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : If_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("if "); Result.Append (Self.Condition.Document (Printer, Pad)); Result.Put (" then"); Result.Append (Self.Then_Path.Document (Printer, Pad).Nest (3)); if Self.Elsif_List /= null then Result.Append (Self.Elsif_List.Document (Printer, Pad)); end if; if Self.Else_Path /= null then Result.Append (Self.Else_Path.Document (Printer, Pad).Nest (3)); end if; Result.New_Line; Result.Put ("end if;"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Return_Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("return"); if Self.Expression /= null then Result.Put (" "); Result.Append (Self.Expression.Document (Printer, Pad)); end if; Result.Put (";"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Statement; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; if Self.Expression = null then Result.Put ("null"); else Result.Append (Self.Expression.Document (Printer, Pad)); end if; Result.Put (";"); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Assignment; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; Right : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Append (Self.Left.Document (Printer, Pad)); Result.Put (" :="); Right.New_Line; Right.Append (Self.Right.Document (Printer, Pad)); Right.Nest (2); Right.Group; Result.Append (Right); Result.Put (";"); return Result; end Document; -------------------- -- New_Assignment -- -------------------- function New_Assignment (Left : not null Node_Access; Right : not null Node_Access) return Node'Class is begin return Assignment'(Left, Right); end New_Assignment; ------------------------- -- New_Block_Statement -- ------------------------- function New_Block_Statement (Declarations : Node_Access; Statements : Node_Access; Exceptions : Node_Access) return Node'Class is begin return Block_Statement'(Declarations, Statements, Exceptions); end New_Block_Statement; -------------- -- New_Case -- -------------- function New_Case (Expression : not null Node_Access; List : not null Node_Access) return Node'Class is begin return Case_Statement'(Expression, List); end New_Case; ------------------- -- New_Case_Path -- ------------------- function New_Case_Path (Choice : not null Node_Access; List : not null Node_Access) return Node'Class is begin return Case_Path'(Choice, List); end New_Case_Path; --------------- -- New_Elsif -- --------------- function New_Elsif (Condition : not null Node_Access; List : not null Node_Access) return Node'Class is begin return Elsif_Statement'(Condition, List); end New_Elsif; ------------------------- -- New_Extended_Return -- ------------------------- function New_Extended_Return (Name : not null Node_Access; Type_Definition : not null Node_Access; Initialization : Node_Access; Statements : not null Node_Access) return Node'Class is begin return Extended_Return_Statement' (Name, Type_Definition, Initialization, Statements); end New_Extended_Return; ------------- -- New_For -- ------------- function New_For (Name : not null Node_Access; Iterator : not null Node_Access; Statements : not null Node_Access) return Node'Class is begin return For_Statement'(Name, Iterator, Statements); end New_For; ------------ -- New_If -- ------------ function New_If (Condition : not null Node_Access; Then_Path : not null Node_Access; Elsif_List : Node_Access; Else_Path : Node_Access) return Node'Class is begin return If_Statement'(Condition, Then_Path, Elsif_List, Else_Path); end New_If; -------------- -- New_Loop -- -------------- function New_Loop (Condition : Node_Access; Statements : not null Node_Access) return Node'Class is begin return Loop_Statement'(Condition, Statements); end New_Loop; ---------------- -- New_Return -- ---------------- function New_Return (Expression : Node_Access) return Node'Class is begin return Return_Statement'(Expression => Expression); end New_Return; ------------------- -- New_Statement -- ------------------- function New_Statement (Expression : Node_Access) return Node'Class is begin return Statement'(Expression => Expression); end New_Statement; end Ada_Pretty.Statements;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------- with SP.Strings; with Ada.Containers.Ordered_Maps; with Ada.Strings.Unbounded; -- Super simple text file caching. -- -- While `Async_File_Cache` provides parallel loading, access to the cache -- itself is protected. -- -- Provides a means to load entire directory structures into memory and then -- use it as needed. This is intended for text files only, in particular, to -- speed text searches of large read-only code bases. -- -- This is super simple and straightforward, but works well enough. -- It probably better done with mmap to load files directly to memory. It -- eliminates line-splitting when printing output. If this were in C++, -- it would be possible to do something like store the file as a huge byte -- block with mmap and then replace newlines with '\0' and store byte counts -- to the initial part of every string. -- package SP.Cache is use Ada.Strings.Unbounded; use SP.Strings; package File_Maps is new Ada.Containers.Ordered_Maps ( Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => String_Vectors.Vector, "<" => Ada.Strings.Unbounded."<", "=" => String_Vectors."="); -- The available in-memory contents of files loaded from files. -- -- Files are stored by full path name, with the OS's preference for path -- separators. -- -- TODO: Add monitoring of files for changes. protected type Async_File_Cache is procedure Clear; -- Cache the contents of a file, replacing any existing contents. procedure Cache_File (File_Name : Unbounded_String; Lines : String_Vectors.Vector); -- The total number of loaded files in the file cache. function Num_Files return Natural; -- The total number of loaded lines in the file cache. function Num_Lines return Natural; function Lines (File_Name : Unbounded_String) return String_Vectors.Vector; function Files return String_Vectors.Vector; function File_Line (File_Name : Unbounded_String; Line : Positive) return Unbounded_String; private -- A list of all top level directories which need to be searched. Top_Level_Directories : SP.Strings.String_Sets.Set; Contents : File_Maps.Map; end Async_File_Cache; -- Adds a directory and all of its recursive subdirectories into the file cache. function Add_Directory_Recursively (A : in out Async_File_Cache; Dir : String) return Boolean; end SP.Cache;
{ "source": "starcoderdata", "programming_language": "ada" }
with openGL.Palette, openGL.Light; package openGL.Program.lit -- -- Models an openGL program which uses lighting. -- is type Item is new openGL.Program.item with private; type View is access all Item'Class; ------------ -- Uniforms -- overriding procedure camera_Site_is (Self : in out Item; Now : in Vector_3); overriding procedure model_Matrix_is (Self : in out Item; Now : in Matrix_4x4); overriding procedure Lights_are (Self : in out Item; Now : in Light.items); overriding procedure set_Uniforms (Self : in Item); procedure specular_Color_is (Self : in out Item; Now : in Color); private type Item is new openGL.Program.item with record Lights : Light.items (1 .. 50); light_Count : Natural := 0; specular_Color : Color := Palette.Grey; -- The materials specular color. camera_Site : Vector_3; model_Transform : Matrix_4x4 := Identity_4x4; end record; end openGL.Program.lit;
{ "source": "starcoderdata", "programming_language": "ada" }
with ada.text_io; with ada.strings.fixed; with ada.strings.maps.constants; with ada.strings.unbounded; with numbers; use numbers; package strings is package natural_io is new ada.text_io.integer_io(natural); package unb renames ada.strings.unbounded; package fix renames ada.strings.fixed; procedure print (s : string) renames ada.text_io.put_line; procedure put (s : string) renames ada.text_io.put; procedure put (s : character) renames ada.text_io.put; procedure print (c : character); procedure print (us : unb.unbounded_string); function first_element (s : string) return character; function last_element (s : string) return character; function first_element (us : unb.unbounded_string) return character; function last_element (us : unb.unbounded_string) return character; function endswith (s, p : string) return boolean; function endswith (s : string; c : character) return boolean; function startswith (s, p : string) return boolean; function startswith (s : string; c : character) return boolean; function ltrim (s : string; c : character := ' ') return string; function rtrim (s : string; c : character := ' ') return string; function trim (s : string; c : character := ' ') return string; procedure clear (us : out unb.unbounded_string); function remove_ret_car (s : string) return string; function lowercase (s : string) return string; function uppercase (s : string) return string; function car (s : string) return character renames first_element; function cdr (str : string; offset : positive := 1) return string; procedure void (s : string); function "=" (us : unb.unbounded_string; s : string) return boolean; function "=" (s : string; us : unb.unbounded_string) return boolean; end strings;
{ "source": "starcoderdata", "programming_language": "ada" }
XFXUN : constant Word_T := 8#015#; -- EXTENDED MOUNT A UNIT XFXML : constant Word_T := 8#016#; -- EXTENDED MOUNT A LABELED TAPE XFHOL : constant Word_T := 8#017#; -- HOLD A QUEUE ENTRY XFUNH : constant Word_T := 8#020#; -- UNHOLD A QUEUE ENTRY XFCAN : constant Word_T := 8#021#; -- CANCEL A QUEUE ENTRY XFSTS : constant Word_T := 8#022#; -- OBTAIN RELATIONSHIP TO EXEC XFQST : constant Word_T := 8#023#; -- GET QUEUE TYPE FROM QUEUE NAME -- THE FOLLOWING FUNCTIONS ARE RESERVED FOR INTERNAL USE XFLO : constant Word_T := 8#024#; -- LABELED TAPE OPEN XFLC : constant Word_T := 8#025#; -- LABELED TAPE CLOSE XFME : constant Word_T := 8#026#; -- MOUNT ERROR XFNV : constant Word_T := 8#027#; -- MOUNT NEXT VOLUME XF30R : constant Word_T := 8#030#; -- Reserved XFSV : constant Word_T := 8#031#; -- MOUNT SPECIFIC VOLUME XFMNT : constant Word_T := 8#032#; -- Submit a job to a MOUNT queue XFBAT : constant Word_T := 8#033#; -- Submit a job to a BATCH queue XFMOD : constant Word_T := 8#034#; -- Modify parameters of a queued job XFSQT : constant Word_T := 8#035#; -- Get queue type by sequence number XFNQN : constant Word_T := 8#036#; -- Get list of queue names XFQDS : constant Word_T := 8#037#; -- Given a queuename, -- Get info on all jobs in queue XFXDU : constant Word_T := 8#040#; -- Extended Dismount -- END OF INTERNAL FUNCTIONS -- PACKET OFFSETS FOR xfxts XFP1 : constant Phys_Addr_T := 2; -- FIRST PARAMETER XFP2 : constant Phys_Addr_T := 3; -- SECOND PARAMETER XFP2L : constant Phys_Addr_T := XFP2 + 1; -- LOWER PORTION OF xfp2 XFP3 : constant Phys_Addr_T := XFP2L + 1; -- 3RD PARAMETER - RESERVED XFP4 : constant Phys_Addr_T := XFP3 + 1; -- 15-BIT PID -- PACKET TO GET SYSTEM INFORMATION (sinfo) SIRN : constant Phys_Addr_T := 0; -- SYSTEM REV, LEFT BYTE=MAJOR, RIGHT BYTE=MINOR SIRS : constant Phys_Addr_T := SIRN + 1; -- RESERVED SIMM : constant Phys_Addr_T := SIRS + 1; -- LENGTH OF PHYSICAL MEMORY (HPAGE) SIML : constant Phys_Addr_T := SIMM + 1; -- LOWER PORTION OF simm SILN : constant Phys_Addr_T := SIML + 1; -- BYTE POINTER TO RECEIVE MASTER LDU NAME SILL : constant Phys_Addr_T := SILN + 1; -- LOWER PORTION OF siln SIID : constant Phys_Addr_T := SILL + 1; -- BYTE POINTER TO RECEIVE SYSTEM IDENTIFIER SIIL : constant Phys_Addr_T := SIID + 1; -- LOWER PORTION OF siid SIPL : constant Phys_Addr_T := SIIL + 1; -- UNEXTENDED PACKET LENGTH SIOS : constant Phys_Addr_T := SIIL + 1; -- BYTE POINTER TO EXECUTING OP SYS PATHNAME SIOL : constant Phys_Addr_T := SIOS + 1; -- LOWER PORTION OF sios SSIN : constant Phys_Addr_T := SIOL + 1; -- SYSTEM IMPLEMENTATION NUMBER (savs FOR AOSVS) SIEX : constant Phys_Addr_T := SSIN + 6; -- EXTENDED PACKET LENGTH (INCLUDE 3 DOUBLE -- WORDS FOR FUTURE EXPANSIONS) SAVS : constant Word_T := 2; -- AOS/VS -- SYSTEM RECORD I/O PACKET FOR ALL DISK AND MAG. TAPEAND MCA REQUESTS FROM EITHER THE AGENT OR USER CONTEXTS. USED FOR rdb/wrb, prdb/PWRB, spage AND allocate -- Used for ?SPAGE, ?RDB, ?WDB PSTI : constant Phys_Addr_T := 0; -- RECORD COUNT (RIGHT), STATUS IN (LEFT) PSTO : constant Phys_Addr_T := PSTI + 1; -- RESERVED (LEFT) PRIORITY (RIGHT) PCAD : constant Phys_Addr_T := PSTO + 1; -- WORD ADDRESS FOR DATA PCDL : constant Phys_Addr_T := PCAD + 1; -- LOW ORDER PORTION OF pcad PRNH : constant Phys_Addr_T := PCDL + 1; -- RECORD NUMBER (HIGH) LINK # (MCA) PRNL : constant Phys_Addr_T := PRNH + 1; -- RECORD NUMBER (LOW) RETRY COUNT (MCA) PRCL : constant Phys_Addr_T := PRNL + 1; -- MAX LENGTH OF EACH RECORD (MAG TAPE) -- BYTE COUNT IN LAST BLOCK (DISK WRITES) -- BYTE COUNT (MCA) PRES : constant Phys_Addr_T := PRCL + 1; -- RESERVED WORD PBLT : constant Phys_Addr_T := PRES + 1; -- PACKET SIZE -- PACKET FOR DIRECTORY ENTRY CREATION (create) CFTYP : constant Phys_Addr_T := 0; -- ENTRY TYPE (RH) AND RECORD FORMAT (LH) CPOR : constant Phys_Addr_T := 1; -- PORT NUMBER (IPC TYPES ONLY) CHFS : constant Phys_Addr_T := 1; -- HASH FRAME SIZE (DIRECTORY TYPES ONLY) CHID : constant Phys_Addr_T := 1; -- HOST ID (frem TYPE FILES ONLY ) CCPS : constant Phys_Addr_T := 1; -- FILE CONTROL PARAMETER (OTHERS) CTIM : constant Phys_Addr_T := 2; -- POINTER TO TIME BLOCK CTIL : constant Phys_Addr_T := CTIM + 1; -- LOWER PORTION OF ctim CACP : constant Phys_Addr_T := CTIL + 1; -- POINTER TO INITIAL ACL CACL : constant Phys_Addr_T := CACP + 1; -- LOWER PORTION OF cacp CMSH : constant Phys_Addr_T := CACL + 1; -- MAX SPACE ALLOCATED (fcpd) CMSL : constant Phys_Addr_T := CMSH + 1; -- MAX SPACE ALLOCATED (LOW) CDEH : constant Phys_Addr_T := CACL + 1; -- RESERVED CDEL : constant Phys_Addr_T := CDEH + 1; -- FILE ELEMENT SIZE CMIL : constant Phys_Addr_T := CDEL + 1; -- MAXIMUM INDEX LEVEL DEPTH CMRS : constant Phys_Addr_T := CMIL + 1; -- RESERVED CLTH : constant Phys_Addr_T := CMRS + 1; -- LENGTH OF THE PARAMETER BLOCK -- ENTRY TYPE RANGES SMIN :constant Word_T := 0; -- SYSTEM MINIMUM SMAX :constant Word_T := 63; -- SYSTEM MAXIMUM DMIN :constant Word_T := smax + 1; -- DGC MINIMUM DMAX :constant Word_T := 127; -- DGC MAXIMUM UMIN :constant Word_T := dmax + 1; -- USER MINIMUM UMAX :constant Word_T := 255; -- USER MAXIMUM -- SYSTEM ENTRY TYPES -- MISC FLNK : constant Word_T := SMIN; -- LINK FSDF : constant Word_T := FLNK + 1; -- SYSTEM DATA FILE FMTF : constant Word_T := FSDF + 1; -- MAG TAPE FILE FGFN : constant Word_T := FMTF + 1; -- GENERIC FILE NAME -- DIRECTORIES (DO NOT CHANGE THEIR ORDER) FDIR : constant Word_T := 10; -- DISK DIRECTORY FLDU : constant Word_T := FDIR + 1; -- LD ROOT DIRECTORY FCPD : constant Word_T := FLDU + 1; -- CONTROL POINT DIRECTORY FMTV : constant Word_T := FCPD + 1; -- MAG TAPE VOLUME FMDR : constant Word_T := FMTV + 1; -- RESERVED FOR RT32(MEM DIRS), NOT LEGAL FOR AOS FGNR : constant Word_T := FMDR + 1; -- RESERVED FOR RT32, NOT LEGAL FOR AOS LDIR : constant Word_T := FDIR; -- LOW DIR TYPE HDIR : constant Word_T := FGNR; -- HIGH DIR TYPE LCPD : constant Word_T := FLDU; -- LOW CONTROL POINT DIR TYPE HCPD : constant Word_T := FCPD; -- HIGH CONTROL POINT DIR TYPE -- UNITS FDKU : constant Word_T := 20; -- DISK UNIT FMCU : constant Word_T := FDKU + 1; -- MULTIPROCESSOR COMMUNICATIONS UNIT FMTU : constant Word_T := FMCU + 1; -- MAG TAPE UNIT FLPU : constant Word_T := FMTU + 1; -- DATA CHANNEL LINE PRINTER FLPD : constant Word_T := FLPU + 1; -- DATA CHANNEL LP2 UNIT FLPE : constant Word_T := FLPD + 1; -- DATA CHANNEL LINE PRINTER (LASER) FPGN : constant Word_T := FLPE + 1; -- RESERVED FOR RT32(PROCESS GROUP) FLTU : constant Word_T := FLPU + 1; -- LABELLED MAG TAPE UNIT -- ***** NO LONGER USED ***** LUNT : constant Word_T := FDKU; -- LOW UNIT TYPE HUNT : constant Word_T := FPGN; -- HIGH UNIT TYPE -- IPC ENTRY TYPES FIPC : constant Word_T := 30; -- IPC PORT ENTRY -- DGC ENTRY TYPES FUDF : constant Word_T := DMIN; -- USER DATA FILE FPRG : constant Word_T := FUDF + 1; -- PROGRAM FILE FUPF : constant Word_T := FPRG + 1; -- USER PROFILE FILE FSTF : constant Word_T := FUPF + 1; -- SYMBOL TABLE FILE FTXT : constant Word_T := FSTF + 1; -- TEXT FILE FLOG : constant Word_T := FTXT + 1; -- SYSTEM LOG FILE (ACCOUNTING FILE) FNCC : constant Word_T := FLOG + 1; -- FORTRAN CARRIAGE CONTROL FILE FLCC : constant Word_T := FNCC + 1; -- FORTRAN CARRIAGE CONTROL FILE FFCC : constant Word_T := FLCC + 1; -- FORTRAN CARRIAGE CONTROL FILE FOCC : constant Word_T := FFCC + 1; -- FORTRAN CARRIAGE CONTROL FILE FPRV : constant Word_T := FOCC + 1; -- AOS/VS PROGRAM FILE FWRD : constant Word_T := FPRV + 1; -- WORD PROCESSING FAFI : constant Word_T := FWRD + 1; -- APL FILE FAWS : constant Word_T := FAFI + 1; -- APL WORKSPACE FILE FBCI : constant Word_T := FAWS + 1; -- BASIC CORE IMAGE FILE FDCF : constant Word_T := FBCI + 1; -- DEVICE CONFIGURATION FILE (NETWORKING) FLCF : constant Word_T := FDCF + 1; -- LINK CONFIGURATION FILE (NETWORKING) FLUG : constant Word_T := FLCF + 1; -- LOGICAL UNIT GROUP FILE (SNA) FRTL : constant Word_T := FLUG + 1; -- AOS/RT32 RESERVED FILE TYPE RANGE (LO) FRTH : constant Word_T := FRTL + 4; -- AOS/RT32 RESERVED FILE TYPE RANGE (HI) FUNX : constant Word_T := FRTH + 1; -- VS/UNIX FILE FBBS : constant Word_T := FUNX + 1; -- BUSINESS BASIC SYMBOL FILE FVLF : constant Word_T := FBBS + 1; -- BUSINESS BASIC VOLUME LABEL FILE FDBF : constant Word_T := FVLF + 1; -- BUSINESS BASIC DATA BASE FILE -- CEO FILE TYPES FGKM : constant Word_T := FDBF + 1; -- DG GRAPHICS KERNAL METAFILE FVDM : constant Word_T := FGKM + 1; -- VIRTUAL DEVICE METAFILE FNAP : constant Word_T := FVDM + 1; -- NAPLPS STANDARD GRAPH FILE FTRV : constant Word_T := FNAP + 1; -- TRENDVIEW COMMAND FILE FSPD : constant Word_T := FTRV + 1; -- SPREADSHEET FILE FQRY : constant Word_T := FSPD + 1; -- PRESENT QUERY MACRO FDTB : constant Word_T := FQRY + 1; -- PHD DATA TABLE FFMT : constant Word_T := FDTB + 1; -- PHD FORMAT FILE FWPT : constant Word_T := FFMT + 1; -- TEXT INTERCHANGE FORMAT FDIF : constant Word_T := FWPT + 1; -- DATA INTERCHANGE FORMAT FVIF : constant Word_T := FDIF + 1; -- VOICE IMAGE FILE FIMG : constant Word_T := FVIF + 1; -- FACSIMILE IMAGE FPRF : constant Word_T := FIMG + 1; -- PRINT READY FILE -- MORE DGC ENTRY TYPES FPIP : constant Word_T := FPRF + 1; -- PIPE FILE FTTX : constant Word_T := FPIP + 1; -- TELETEX FILE FDXF : constant Word_T := FTTX + 1; -- RESERVED FOR DXA FDXR : constant Word_T := FDXF + 1; -- RESERVED FOR DXA FCWP : constant Word_T := FDXR + 1; -- CEO WORD PROCESSOR FILE FCWT : constant Word_T := FCWP; -- CEOwrite WORD PROCESSOR FILE FRPT : constant Word_T := FCWP + 1; -- PHD REPORT FILE -- INTERPROCESS COMMUNICATION SYSTEM (IPC) PARAMETERS -- -- HIGHEST LEGAL LOCAL PORT NUMBER IMPRT : constant Natural := 2047; -- MAX LEGAL USER LOCAL PORT # MXLPN : constant Natural := 4095; -- MAX LEGAL LOCAL PORT # -- IPC MESSAGE HEADER ISFL : constant Phys_Addr_T := 0; -- SYSTEM FLAGS IUFL : constant Phys_Addr_T := 1; -- USER FLAGS -- PORT NUMBERS FOR ?ISEND IDPH : constant Phys_Addr_T := 2; -- DESTINATION PORT NUMBER (HIGH) IDPL : constant Phys_Addr_T := 3; -- DESTINATION PORT NUMBER (LOW) IOPN : constant Phys_Addr_T := 4; -- ORIGIN PORT NUMBER -- PORT NUMBERS FOR ?IREC IOPH : constant Phys_Addr_T := 2; -- ORIGIN PORT NUMBER (HIGH) IOPL : constant Phys_Addr_T := 3; -- ORIGIN PORT NUMBER (LOW) IDPN : constant Phys_Addr_T := 4; -- DESTINATION PORT NUMBER ILTH : constant Phys_Addr_T := 5; -- LENGTH OF MESSAGE OR BUFFER (IN WORDS) IPTR : constant Phys_Addr_T := 6; -- POINTER TO MESSAGE/BUFFER IPTL : constant Phys_Addr_T := IPTR+1; -- LOWER PORTION OF IPTR IPLTH : constant Phys_Addr_T := IPTL+1; -- LENGTH OF HEADER IRSV : constant Phys_Addr_T := IPTL+1; -- RESERVED IRLT : constant Phys_Addr_T := IRSV+1; -- IS.R RECEIVE BUFFER LENGTH IRPT : constant Phys_Addr_T := IRLT+1; -- IS.R RECEIVE BUFFER POINTER IRPL : constant Phys_Addr_T := IRPT+1; -- LOWER PORTION OF IRPT IPRLTH : constant Phys_Addr_T := IRPL+1; -- LENGTH OF ?IS.R HEADER -- PACKET FOR TASK DEFINITION (?TASK) DLNK : constant Phys_Addr_T := 0; -- NON-ZERO = SHORT PACKET, ZERO = EXTENDED DLNL : constant Phys_Addr_T := DLNK + 1; -- 1 LOWER PORTION OF ?DLNK DLNKB : constant Phys_Addr_T := DLNL + 1; -- 2 BACKWARDS LINK (UPPER PORTION) DLNKBL : constant Phys_Addr_T := DLNKB + 1; -- 3 BACKWARDS LINK (LOWER PORTION) DPRI : constant Phys_Addr_T := DLNKBL + 1; --4 PRIORITY, ZERO TO USE CALLER'S DID : constant Phys_Addr_T := DPRI + 1; -- 5 I.D., ZERO FOR NONE DPC : constant Phys_Addr_T := DID + 1; -- 6 STARTING ADDRESS OR RESOURCE ENTRY DPCL : constant Phys_Addr_T := DPC + 1; -- 7 LOWER PORTION OF ?DPC DAC2 : constant Phys_Addr_T := DPCL + 1; -- 8 INITIAL AC2 CONTENTS DCL2 : constant Phys_Addr_T := DAC2 + 1; -- 9 LOWER PORTION OF ?DAC2 DSTB : constant Phys_Addr_T := DCL2 + 1; -- 10 STACK BASE, MINUS ONE FOR NO STACK DSTL : constant Phys_Addr_T := DSTB + 1; -- 11 LOWER PORTION OF ?DSTB DSFLT : constant Phys_Addr_T := DSTL + 1; -- 12 STACK FAULT ROUTINE ADDR OR -1 IF SAME AS CURRENT DSSZ : constant Phys_Addr_T := DSFLT + 1;-- 13 STACK SIZE, IGNORED IF NO STACK DSSL : constant Phys_Addr_T := DSSZ + 1; -- 14 LOWER PORTION OF ?DSSZ DFLGS : constant Phys_Addr_T := DSSL + 1; -- 15 FLAGS -- DFL0 : constant Phys_Addr_T := 1B0 -- RESERVED FOR SYSTEM -- DFLRC : constant Phys_Addr_T := 1B1 -- RESOURCE CALL TASK -- DFL15 : constant Phys_Addr_T := 1B15 -- RESERVED FOR SYSTEM DRES : constant Phys_Addr_T := DFLGS + 1; -- 16 RESERVED FOR SYSTEM DNUM : constant Phys_Addr_T := DRES + 1; -- 17 NUMBER OF TASKS TO CREATE DSLTH : constant Phys_Addr_T := DNUM + 1; -- LENGTH OF SHORT PACKET DSH : constant Phys_Addr_T := DNUM + 1; -- STARTING HOUR, -1 IF IMMEDIATE DSMS : constant Phys_Addr_T := DSH + 1; -- STARTING SECOND IN HOUR, IGNORED IF IMMEDIATE DCC : constant Phys_Addr_T := DSMS + 1; -- NUMBER OF TIMES TO CREATE TASK(S) DCI : constant Phys_Addr_T := DCC + 1; -- CREATION INCREMENT IN SECONDS DXLTH :constant Phys_Addr_T := DCI + 1; -- LENGTH OF EXTENDED PACKET -- ?RNGPR PACKET OFFSETS -- RNGBP : constant Phys_Addr_T := 0; -- BYTE POINTER TO BUFFER (2 WORDS) RNGNM : constant Phys_Addr_T := RNGBP + 2; -- RING # OF RING TO CHECK RNGLB : constant Phys_Addr_T := RNGNM + 1; -- BUFFER BYTE LENGTH RNGPL : constant Phys_Addr_T := RNGLB + 1; -- PACKET LENGTH -- ?UIDSTAT UUID : constant Phys_Addr_T := 0; -- Unique task identifier UTSTAT : constant Phys_Addr_T := UUID + 1; -- Task Status Word UTID : constant Phys_Addr_T := UTSTAT + 1; -- Standard Task ID UTPRI : constant Phys_Addr_T := UTID + 1; -- Task Prioroty end PARU_32;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Finalization; with Adabots_Lua_Dispatcher; package Adabots is type Turtle is new Ada.Finalization.Limited_Controlled with private; type Turtle_Inventory_Slot is range 1 .. 16; type Stack_Count is range 0 .. 64; type Item_Detail is record Count : Stack_Count; Name : Ada.Strings.Unbounded.Unbounded_String; end record; function Create_Turtle return Turtle; function Create_Turtle (Port : Integer) return Turtle; -- Movement procedure Turn_Right (T : Turtle); procedure Turn_Left (T : Turtle); function Forward (T : Turtle) return Boolean; function Back (T : Turtle) return Boolean; function Up (T : Turtle) return Boolean; function Down (T : Turtle) return Boolean; -- Digging function Dig_Down (T : Turtle) return Boolean; function Dig_Up (T : Turtle) return Boolean; function Dig (T : Turtle) return Boolean; -- Placing function Place (T : Turtle) return Boolean; function Place_Down (T : Turtle) return Boolean; function Place_Up (T : Turtle) return Boolean; -- Inventory management procedure Select_Slot (T : Turtle; Slot : Turtle_Inventory_Slot); function Get_Item_Count (T : Turtle; Slot : Turtle_Inventory_Slot) return Stack_Count; function Get_Selected_Slot (T : Turtle) return Turtle_Inventory_Slot; -- TODO really implement these two: function Get_Item_Detail (T : Turtle) return Item_Detail; function Get_Item_Detail (T : Turtle; Slot : Turtle_Inventory_Slot) return Item_Detail; -- https://tweaked.cc/module/turtle.html#v:drop function Drop (T : Turtle; Amount : Stack_Count := 64) return Boolean; -- function DropUp (T : Turtle; Amount : Stack_Count := 64) return Boolean; -- function DropDown (T : Turtle; Amount : Stack_Count := 64) return Boolean; function Detect (T : Turtle) return Boolean; function Detect_Down (T : Turtle) return Boolean; function Detect_Up (T : Turtle) return Boolean; -- these procedures assert that the function of the same name returned true procedure Forward (T : Turtle); procedure Back (T : Turtle); procedure Up (T : Turtle); procedure Down (T : Turtle); procedure Dig_Down (T : Turtle); procedure Dig_Up (T : Turtle); procedure Dig (T : Turtle); procedure Place (T : Turtle); procedure Place_Down (T : Turtle); procedure Place_Up (T : Turtle); procedure Drop (T : Turtle; Amount : Stack_Count := 64); -- these procedures don't care what the result is procedure Maybe_Dig_Down (T : Turtle); procedure Maybe_Dig_Up (T : Turtle); procedure Maybe_Dig (T : Turtle); procedure Maybe_Place (T : Turtle); procedure Maybe_Place_Down (T : Turtle); procedure Maybe_Place_Up (T : Turtle); type Command_Computer is new Ada.Finalization.Limited_Controlled with private; function Create_Command_Computer return Command_Computer; function Create_Command_Computer (Port : Integer) return Command_Computer; type Material is (Grass, Planks, Air, Glass, Ice, Gold_Block, Sand, Bedrock, Stone); type Relative_Location is record X_Offset : Integer := 0; Y_Offset : Integer := 0; Z_Offset : Integer := 0; end record; function Image (P : Relative_Location) return String is (P.X_Offset'Image & ", " & P.Y_Offset'Image & ", " & P.Z_Offset'Image); function "+" (A, B : Relative_Location) return Relative_Location; function "-" (A, B : Relative_Location) return Relative_Location; type Absolute_Location is record X : Integer := 0; Y : Integer := 0; Z : Integer := 0; end record; function "+" (A, B : Absolute_Location) return Absolute_Location; function "+" (A : Absolute_Location; B : Relative_Location) return Absolute_Location; function Set_Block (C : Command_Computer; L : Relative_Location; B : Material) return Boolean; procedure Maybe_Set_Block (C : Command_Computer; L : Relative_Location; B : Material); procedure Set_Cube (C : Command_Computer; First : Relative_Location; Last : Relative_Location; B : Material); function Get_Block_Info (C : Command_Computer; L : Absolute_Location) return Material; private type Turtle is new Ada.Finalization.Limited_Controlled with record Dispatcher : Adabots_Lua_Dispatcher.Lua_Dispatcher; end record; function Parse_Item_Details (Table : String) return Item_Detail; type Command_Computer is new Ada.Finalization.Limited_Controlled with record Dispatcher : Adabots_Lua_Dispatcher.Lua_Dispatcher; end record; end Adabots;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Warnings (Off); pragma Ada_95; pragma Source_File_Name (ada_main, Spec_File_Name => "b__main.ads"); pragma Source_File_Name (ada_main, Body_File_Name => "b__main.adb"); pragma Suppress (Overflow_Check); package body ada_main is E78 : Short_Integer; pragma Import (Ada, E78, "memory_barriers_E"); E76 : Short_Integer; pragma Import (Ada, E76, "cortex_m__nvic_E"); E68 : Short_Integer; pragma Import (Ada, E68, "nrf__events_E"); E28 : Short_Integer; pragma Import (Ada, E28, "nrf__gpio_E"); E70 : Short_Integer; pragma Import (Ada, E70, "nrf__gpio__tasks_and_events_E"); E72 : Short_Integer; pragma Import (Ada, E72, "nrf__interrupts_E"); E34 : Short_Integer; pragma Import (Ada, E34, "nrf__rtc_E"); E37 : Short_Integer; pragma Import (Ada, E37, "nrf__spi_master_E"); E56 : Short_Integer; pragma Import (Ada, E56, "nrf__tasks_E"); E54 : Short_Integer; pragma Import (Ada, E54, "nrf__adc_E"); E84 : Short_Integer; pragma Import (Ada, E84, "nrf__clock_E"); E80 : Short_Integer; pragma Import (Ada, E80, "nrf__ppi_E"); E41 : Short_Integer; pragma Import (Ada, E41, "nrf__timers_E"); E44 : Short_Integer; pragma Import (Ada, E44, "nrf__twi_E"); E48 : Short_Integer; pragma Import (Ada, E48, "nrf__uart_E"); E06 : Short_Integer; pragma Import (Ada, E06, "nrf__device_E"); E52 : Short_Integer; pragma Import (Ada, E52, "nrf52_dk__ios_E"); E82 : Short_Integer; pragma Import (Ada, E82, "nrf52_dk__time_E"); E87 : Short_Integer; pragma Import (Ada, E87, "sensor_E"); Sec_Default_Sized_Stacks : array (1 .. 1) of aliased System.Secondary_Stack.SS_Stack (System.Parameters.Runtime_Default_Sec_Stack_Size); procedure adainit is Binder_Sec_Stacks_Count : Natural; pragma Import (Ada, Binder_Sec_Stacks_Count, "__gnat_binder_ss_count"); Default_Secondary_Stack_Size : System.Parameters.Size_Type; pragma Import (C, Default_Secondary_Stack_Size, "__gnat_default_ss_size"); Default_Sized_SS_Pool : System.Address; pragma Import (Ada, Default_Sized_SS_Pool, "__gnat_default_ss_pool"); begin null; ada_main'Elab_Body; Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; Binder_Sec_Stacks_Count := 1; Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; E78 := E78 + 1; Cortex_M.Nvic'Elab_Spec; E76 := E76 + 1; E68 := E68 + 1; E28 := E28 + 1; E70 := E70 + 1; Nrf.Interrupts'Elab_Body; E72 := E72 + 1; E34 := E34 + 1; E37 := E37 + 1; E56 := E56 + 1; E54 := E54 + 1; E84 := E84 + 1; E80 := E80 + 1; E41 := E41 + 1; E44 := E44 + 1; E48 := E48 + 1; Nrf.Device'Elab_Spec; Nrf.Device'Elab_Body; E06 := E06 + 1; NRF52_DK.IOS'ELAB_SPEC; NRF52_DK.IOS'ELAB_BODY; E52 := E52 + 1; NRF52_DK.TIME'ELAB_BODY; E82 := E82 + 1; E87 := E87 + 1; end adainit; procedure Ada_Main_Program; pragma Import (Ada, Ada_Main_Program, "_ada_main"); procedure main is Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; pragma Volatile (Ensure_Reference); begin adainit; Ada_Main_Program; end; -- BEGIN Object file/option list -- C:\GNAT\Ada_Drivers_Library\examples\NRF52_DK\project2\obj\sensor.o -- C:\GNAT\Ada_Drivers_Library\examples\NRF52_DK\project2\obj\main.o -- -LC:\GNAT\Ada_Drivers_Library\examples\NRF52_DK\project2\obj\ -- -LC:\GNAT\Ada_Drivers_Library\examples\NRF52_DK\project2\obj\ -- -LC:\GNAT\Ada_Drivers_Library\boards\NRF52_DK\obj\zfp_lib_Debug\ -- -LC:\gnat\2020-arm-elf\arm-eabi\lib\gnat\zfp-cortex-m4f\adalib\ -- -static -- -lgnat -- END Object file/option list end ada_main;
{ "source": "starcoderdata", "programming_language": "ada" }
with DOM.Core.Documents; with Project_Processor.Parsers.Parser_Tables; with XML_Utilities; with XML_Scanners; with DOM.Core.Nodes; with EU_Projects.Nodes.Action_Nodes.Tasks; with EU_Projects.Nodes.Action_Nodes.WPs; with EU_Projects.Nodes.Timed_Nodes.Milestones; with Project_Processor.Parsers.XML_Parsers.Sub_Parsers; with EU_Projects.Nodes.Timed_Nodes.Deliverables; package body Project_Processor.Parsers.XML_Parsers is use XML_Scanners; use EU_Projects.Projects; ------------ -- Create -- ------------ function Create (Params : not null access Plugins.Parameter_Maps.Map) return Parser_Type is pragma Unreferenced (Params); Result : Parser_Type; begin return Result; end Create; procedure Parse_Project (Parser : in out Parser_Type; Project : out Project_Descriptor; N : in DOM.Core.Node) is pragma Unreferenced (Parser); use EU_Projects.Nodes; Scanner : XML_Scanner := Create_Child_Scanner (N); procedure Add_Partner (N : DOM.Core.Node) is begin Project.Add_Partner (Sub_Parsers.Parse_Partner (N)); end Add_Partner; procedure Add_Milestone (N : DOM.Core.Node) is Milestone : Timed_Nodes.Milestones.Milestone_Access; begin Sub_Parsers.Parse_Milestone (N, Milestone); Project.Add_Milestone (Milestone); end Add_Milestone; procedure Add_WP (N : DOM.Core.Node) is WP : Action_Nodes.WPs.Project_WP_Access; begin Sub_Parsers.Parse_WP (N, WP); Project.Add_WP (WP); end Add_WP; procedure Handle_Configuration (N : DOM.Core.Node) is begin Sub_Parsers.Parse_Configuration (Project, N); end Handle_Configuration; procedure Add_Risk (N : DOM.Core.Node) is begin Project.Add_Risk (Sub_Parsers.Parse_Risk (N)); end Add_Risk; procedure Add_Deliverable (N : DOM.Core.Node) is Deliv : Timed_Nodes.Deliverables.Deliverable_Access; begin Sub_Parsers.Parse_Deliverable (N, Deliv); Project.Add_Deliverable (Deliv); end Add_Deliverable; begin if DOM.Core.Nodes.Node_Name (N) /= "project" then raise Parsing_Error; end if; Dom.Core.Nodes.Print (N); Scanner.Parse_Optional ("configuration", Handle_Configuration'Access); Scanner.Parse_Sequence ("partner", Add_Partner'Access); Scanner.Parse_Sequence ("wp", Add_WP'Access); Scanner.Parse_Sequence ("milestone", Add_Milestone'Access); Scanner.Parse_Sequence (Name => "deliverable", Callback => Add_Deliverable'Access, Min_Length => 0); Scanner.Parse_Sequence (Name => "risk", Callback => Add_Risk'Access, Min_Length => 0); end Parse_Project; ----------- -- Parse -- ----------- procedure Parse (Parser : in out Parser_Type; Project : out EU_Projects.Projects.Project_Descriptor; Input : String) is use DOM.Core.Documents; begin Parse_Project (Parser => Parser, Project => Project, N => Get_Element (XML_Utilities.Parse_String (Input))); Project.Freeze; end Parse; begin Parser_Tables.Register (ID => "xml", Tag => Parser_Type'Tag); end Project_Processor.Parsers.XML_Parsers;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Profile(No_Implementation_Extensions); package body Parse_Args.Testable is ------------------ -- Command_Name -- ------------------ overriding function Command_Name (A : in Testable_Argument_Parser) return String is (To_String(A.Command_Name_Override)); -------------------- -- Argument_Count -- -------------------- overriding function Argument_Count (A : in Testable_Argument_Parser) return Natural is (Natural(A.Input_Arguments.Length)); -------------- -- Argument -- -------------- overriding function Argument (A : in Testable_Argument_Parser; Number : in Positive) return String is (To_String(A.Input_Arguments(Number))); --------------------- -- Clear_Arguments -- --------------------- not overriding procedure Clear_Arguments (A : in out Testable_Argument_Parser) is begin A.Input_Arguments.Clear; end Clear_Arguments; --------------------- -- Append_Argument -- --------------------- not overriding procedure Append_Argument (A : in out Testable_Argument_Parser; S : in String) is begin A.Input_Arguments.Append(To_Unbounded_String(S)); end Append_Argument; ---------------------- -- Append_Arguments -- ---------------------- not overriding procedure Append_Arguments (A : in out Testable_Argument_Parser; S : in Unbounded_String_Array) is begin for I of S loop A.Input_Arguments.Append(I); end loop; end Append_Arguments; ---------------------- -- Set_Command_Name -- ---------------------- not overriding procedure Set_Command_Name(A : in out Testable_Argument_Parser; S : in String) is begin A.Command_Name_Override := To_Unbounded_String(S); end Set_Command_Name; end Parse_Args.Testable;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Processing for intrinsic subprogram declarations with Types; use Types; package Sem_Intr is procedure Check_Intrinsic_Call (N : Node_Id); -- Perform legality check for intrinsic call N (which is either function -- call or a procedure call node). All the normal semantic checks have -- been performed already. Check_Intrinsic_Call applies any additional -- checks required by the fact that an intrinsic subprogram is involved. procedure Check_Intrinsic_Subprogram (E : Entity_Id; N : Node_Id); -- Special processing for pragma Import or pragma Interface when the -- convention is Intrinsic. E is the Entity_Id of the spec of the -- subprogram, and N is the second (subprogram) argument of the pragma. -- Check_Intrinsic_Subprogram checks that the referenced subprogram is -- known as an intrinsic and has an appropriate profile. If so the flag -- Is_Intrinsic_Subprogram is set, otherwise an error message is posted. end Sem_Intr;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- package body Program.Nodes.Exception_Declarations is function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Colon_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Exception_Token : not null Program.Lexical_Elements .Lexical_Element_Access; With_Token : Program.Lexical_Elements.Lexical_Element_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Semicolon_Token : not null Program.Lexical_Elements .Lexical_Element_Access) return Exception_Declaration is begin return Result : Exception_Declaration := (Names => Names, Colon_Token => Colon_Token, Exception_Token => Exception_Token, With_Token => With_Token, Aspects => Aspects, Semicolon_Token => Semicolon_Token, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False) return Implicit_Exception_Declaration is begin return Result : Implicit_Exception_Declaration := (Names => Names, Aspects => Aspects, 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 Names (Self : Base_Exception_Declaration) return not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access is begin return Self.Names; end Names; overriding function Aspects (Self : Base_Exception_Declaration) return Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access is begin return Self.Aspects; end Aspects; overriding function Colon_Token (Self : Exception_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Colon_Token; end Colon_Token; overriding function Exception_Token (Self : Exception_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Exception_Token; end Exception_Token; overriding function With_Token (Self : Exception_Declaration) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.With_Token; end With_Token; overriding function Semicolon_Token (Self : Exception_Declaration) 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_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; procedure Initialize (Self : in out Base_Exception_Declaration'Class) is begin for Item in Self.Names.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; for Item in Self.Aspects.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; null; end Initialize; overriding function Is_Exception_Declaration (Self : Base_Exception_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Exception_Declaration; overriding function Is_Declaration (Self : Base_Exception_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Declaration; overriding procedure Visit (Self : not null access Base_Exception_Declaration; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Exception_Declaration (Self); end Visit; overriding function To_Exception_Declaration_Text (Self : in out Exception_Declaration) return Program.Elements.Exception_Declarations .Exception_Declaration_Text_Access is begin return Self'Unchecked_Access; end To_Exception_Declaration_Text; overriding function To_Exception_Declaration_Text (Self : in out Implicit_Exception_Declaration) return Program.Elements.Exception_Declarations .Exception_Declaration_Text_Access is pragma Unreferenced (Self); begin return null; end To_Exception_Declaration_Text; end Program.Nodes.Exception_Declarations;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ with Ada.Iterator_Interfaces; with Ada.Containers.Helpers; private with Ada.Containers.Red_Black_Trees; private with Ada.Finalization; private with Ada.Streams; private with Ada.Strings.Text_Output; generic type Element_Type is private; with function "<" (Left, Right : Element_Type) return Boolean is <>; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Ada.Containers.Ordered_Sets with SPARK_Mode => Off is pragma Annotate (CodePeer, Skip_Analysis); pragma Preelaborate; pragma Remote_Types; function Equivalent_Elements (Left, Right : Element_Type) return Boolean; type Set is tagged private with Constant_Indexing => Constant_Reference, Default_Iterator => Iterate, Iterator_Element => Element_Type; -- Aggregate => (Empty => Empty, -- Add_Unnamed => Include); pragma Preelaborable_Initialization (Set); type Cursor is private; pragma Preelaborable_Initialization (Cursor); function Has_Element (Position : Cursor) return Boolean; Empty_Set : constant Set; function Empty return Set; No_Element : constant Cursor; package Set_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element); function "=" (Left, Right : Set) return Boolean; function Equivalent_Sets (Left, Right : Set) return Boolean; function To_Set (New_Item : Element_Type) return Set; function Length (Container : Set) return Count_Type; function Is_Empty (Container : Set) return Boolean; procedure Clear (Container : in out Set); function Element (Position : Cursor) return Element_Type; procedure Replace_Element (Container : in out Set; Position : Cursor; New_Item : Element_Type); procedure Query_Element (Position : Cursor; Process : not null access procedure (Element : Element_Type)); type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; function Constant_Reference (Container : aliased Set; Position : Cursor) return Constant_Reference_Type; pragma Inline (Constant_Reference); procedure Assign (Target : in out Set; Source : Set); function Copy (Source : Set) return Set; procedure Move (Target : in out Set; Source : in out Set); procedure Insert (Container : in out Set; New_Item : Element_Type; Position : out Cursor; Inserted : out Boolean); procedure Insert (Container : in out Set; New_Item : Element_Type); procedure Include (Container : in out Set; New_Item : Element_Type); procedure Replace (Container : in out Set; New_Item : Element_Type); procedure Exclude (Container : in out Set; Item : Element_Type); procedure Delete (Container : in out Set; Item : Element_Type); procedure Delete (Container : in out Set; Position : in out Cursor); procedure Delete_First (Container : in out Set); procedure Delete_Last (Container : in out Set); procedure Union (Target : in out Set; Source : Set); function Union (Left, Right : Set) return Set; function "or" (Left, Right : Set) return Set renames Union; procedure Intersection (Target : in out Set; Source : Set); function Intersection (Left, Right : Set) return Set; function "and" (Left, Right : Set) return Set renames Intersection; procedure Difference (Target : in out Set; Source : Set); function Difference (Left, Right : Set) return Set; function "-" (Left, Right : Set) return Set renames Difference; procedure Symmetric_Difference (Target : in out Set; Source : Set); function Symmetric_Difference (Left, Right : Set) return Set; function "xor" (Left, Right : Set) return Set renames Symmetric_Difference; function Overlap (Left, Right : Set) return Boolean; function Is_Subset (Subset : Set; Of_Set : Set) return Boolean; function First (Container : Set) return Cursor; function First_Element (Container : Set) return Element_Type; function Last (Container : Set) return Cursor; function Last_Element (Container : Set) return Element_Type; function Next (Position : Cursor) return Cursor; procedure Next (Position : in out Cursor); function Previous (Position : Cursor) return Cursor; procedure Previous (Position : in out Cursor); function Find (Container : Set; Item : Element_Type) return Cursor; function Floor (Container : Set; Item : Element_Type) return Cursor; function Ceiling (Container : Set; Item : Element_Type) return Cursor; function Contains (Container : Set; Item : Element_Type) return Boolean; function "<" (Left, Right : Cursor) return Boolean; function ">" (Left, Right : Cursor) return Boolean; function "<" (Left : Cursor; Right : Element_Type) return Boolean; function ">" (Left : Cursor; Right : Element_Type) return Boolean; function "<" (Left : Element_Type; Right : Cursor) return Boolean; function ">" (Left : Element_Type; Right : Cursor) return Boolean; procedure Iterate (Container : Set; Process : not null access procedure (Position : Cursor)); procedure Reverse_Iterate (Container : Set; Process : not null access procedure (Position : Cursor)); function Iterate (Container : Set) return Set_Iterator_Interfaces.Reversible_Iterator'class; function Iterate (Container : Set; Start : Cursor) return Set_Iterator_Interfaces.Reversible_Iterator'class; generic type Key_Type (<>) is private; with function Key (Element : Element_Type) return Key_Type; with function "<" (Left, Right : Key_Type) return Boolean is <>; package Generic_Keys is function Equivalent_Keys (Left, Right : Key_Type) return Boolean; function Key (Position : Cursor) return Key_Type; function Element (Container : Set; Key : Key_Type) return Element_Type; procedure Replace (Container : in out Set; Key : Key_Type; New_Item : Element_Type); procedure Exclude (Container : in out Set; Key : Key_Type); procedure Delete (Container : in out Set; Key : Key_Type); function Find (Container : Set; Key : Key_Type) return Cursor; function Floor (Container : Set; Key : Key_Type) return Cursor; function Ceiling (Container : Set; Key : Key_Type) return Cursor; function Contains (Container : Set; Key : Key_Type) return Boolean; procedure Update_Element_Preserving_Key (Container : in out Set; Position : Cursor; Process : not null access procedure (Element : in out Element_Type)); type Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Reference_Preserving_Key (Container : aliased in out Set; Position : Cursor) return Reference_Type; function Constant_Reference (Container : aliased Set; Key : Key_Type) return Constant_Reference_Type; function Reference_Preserving_Key (Container : aliased in out Set; Key : Key_Type) return Reference_Type; private type Set_Access is access all Set; for Set_Access'Storage_Size use 0; type Key_Access is access all Key_Type; package Impl is new Helpers.Generic_Implementation; type Reference_Control_Type is new Impl.Reference_Control_Type with record Container : Set_Access; Pos : Cursor; Old_Key : Key_Access; end record; overriding procedure Finalize (Control : in out Reference_Control_Type); pragma Inline (Finalize); type Reference_Type (Element : not null access Element_Type) is record Control : Reference_Control_Type; end record; use Ada.Streams; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Reference_Type); for Reference_Type'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Reference_Type); for Reference_Type'Read use Read; end Generic_Keys; private pragma Inline (Next); pragma Inline (Previous); type Node_Type; type Node_Access is access Node_Type; type Node_Type is limited record Parent : Node_Access; Left : Node_Access; Right : Node_Access; Color : Red_Black_Trees.Color_Type := Red_Black_Trees.Red; Element : aliased Element_Type; end record; package Tree_Types is new Red_Black_Trees.Generic_Tree_Types (Node_Type, Node_Access); type Set is new Ada.Finalization.Controlled with record Tree : Tree_Types.Tree_Type; end record with Put_Image => Put_Image; procedure Put_Image (S : in out Ada.Strings.Text_Output.Sink'Class; V : Set); overriding procedure Adjust (Container : in out Set); overriding procedure Finalize (Container : in out Set) renames Clear; use Red_Black_Trees; use Tree_Types, Tree_Types.Implementation; use Ada.Finalization; use Ada.Streams; procedure Write (Stream : not null access Root_Stream_Type'Class; Container : Set); for Set'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Container : out Set); for Set'Read use Read; type Set_Access is access all Set; for Set_Access'Storage_Size use 0; type Cursor is record Container : Set_Access; Node : Node_Access; end record; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Cursor); for Cursor'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Cursor); for Cursor'Read use Read; subtype Reference_Control_Type is Implementation.Reference_Control_Type; -- It is necessary to rename this here, so that the compiler can find it type Constant_Reference_Type (Element : not null access constant Element_Type) is record Control : Reference_Control_Type := raise Program_Error with "uninitialized reference"; -- The RM says, "The default initialization of an object of -- type Constant_Reference_Type or Reference_Type propagates -- Program_Error." end record; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Constant_Reference_Type); for Constant_Reference_Type'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Constant_Reference_Type); for Constant_Reference_Type'Read use Read; -- Three operations are used to optimize in the expansion of "for ... of" -- loops: the Next(Cursor) procedure in the visible part, and the following -- Pseudo_Reference and Get_Element_Access functions. See Sem_Ch5 for -- details. function Pseudo_Reference (Container : aliased Set'Class) return Reference_Control_Type; pragma Inline (Pseudo_Reference); -- Creates an object of type Reference_Control_Type pointing to the -- container, and increments the Lock. Finalization of this object will -- decrement the Lock. type Element_Access is access all Element_Type with Storage_Size => 0; function Get_Element_Access (Position : Cursor) return not null Element_Access; -- Returns a pointer to the element designated by Position. Empty_Set : constant Set := (Controlled with others => <>); function Empty return Set is (Empty_Set); No_Element : constant Cursor := Cursor'(null, null); type Iterator is new Limited_Controlled and Set_Iterator_Interfaces.Reversible_Iterator with record Container : Set_Access; Node : Node_Access; end record with Disable_Controlled => not T_Check; overriding procedure Finalize (Object : in out Iterator); overriding function First (Object : Iterator) return Cursor; overriding function Last (Object : Iterator) return Cursor; overriding function Next (Object : Iterator; Position : Cursor) return Cursor; overriding function Previous (Object : Iterator; Position : Cursor) return Cursor; end Ada.Containers.Ordered_Sets;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Unchecked_Deallocation; -- we need to explicitly with all annotations because their package -- initialization adds them to the annotation map. with Yaml.Transformator.Annotation.Identity; with Yaml.Transformator.Annotation.Concatenation; with Yaml.Transformator.Annotation.Vars; with Yaml.Transformator.Annotation.For_Loop; with Yaml.Transformator.Annotation.Inject; pragma Unreferenced (Yaml.Transformator.Annotation.Concatenation); pragma Unreferenced (Yaml.Transformator.Annotation.Vars); pragma Unreferenced (Yaml.Transformator.Annotation.For_Loop); pragma Unreferenced (Yaml.Transformator.Annotation.Inject); package body Yaml.Transformator.Annotation_Processor is use type Text.Reference; use type Annotation.Node_Context_Type; procedure Free_Array is new Ada.Unchecked_Deallocation (Node_Array, Node_Array_Pointer); procedure Free_Transformator is new Ada.Unchecked_Deallocation (Transformator.Instance'Class, Transformator.Pointer); function New_Processor (Pool : Text.Pool.Reference; Externals : Events.Store.Reference := Events.Store.New_Store) return Pointer is (new Instance'(Ada.Finalization.Limited_Controlled with Pool => Pool, Context => Events.Context.Create (Externals), others => <>)); procedure Finalize_Finished_Annotation_Impl (Object : in out Instance) is begin if Object.Level_Count = Object.Annotations (Object.Annotation_Count).Depth and then not Object.Annotations (Object.Annotation_Count).Impl.Has_Next then if Object.Annotations (Object.Annotation_Count).Swallows_Next then Object.Current_State := Swallowing_Document_End; Object.Current := (Kind => Document_End, others => <>); end if; Free_Transformator (Object.Annotations (Object.Annotation_Count).Impl); Object.Annotation_Count := Object.Annotation_Count - 1; if Object.Annotation_Count = 0 and Object.Next_Event_Storage = Yes then if Object.Current_State = Existing then Object.Next_Event_Storage := Finishing; else Object.Next_Event_Storage := No; end if; end if; end if; end Finalize_Finished_Annotation_Impl; procedure Shift_Through (Object : in out Instance; Start : Natural; E : Event) with Pre => Start <= Object.Annotation_Count is Cur_Annotation : Natural := Start; Cur_Event : Event := E; begin while Cur_Annotation > 0 loop Object.Annotations (Cur_Annotation).Impl.Put (Cur_Event); if Object.Annotations (Cur_Annotation).Impl.Has_Next then Cur_Event := Object.Annotations (Cur_Annotation).Impl.Next; if (Cur_Annotation = Object.Annotation_Count and Object.May_Finish_Transformation) then Finalize_Finished_Annotation_Impl (Object); end if; Cur_Annotation := Cur_Annotation - 1; else loop Cur_Annotation := Cur_Annotation + 1; if Cur_Annotation > Object.Annotation_Count then if Object.May_Finish_Transformation then Finalize_Finished_Annotation_Impl (Object); end if; return; end if; if Object.Annotations (Cur_Annotation).Impl.Has_Next then Cur_Event := Object.Annotations (Cur_Annotation).Impl.Next; if (Cur_Annotation = Object.Annotation_Count and Object.May_Finish_Transformation) then Finalize_Finished_Annotation_Impl (Object); end if; Cur_Annotation := Cur_Annotation - 1; exit; end if; end loop; end if; end loop; Object.Current := Cur_Event; Object.Current_State := (if Object.Current_State = Event_Held_Back then Releasing_Held_Back else Existing); end Shift_Through; procedure Append (Object : in out Instance; E : Event) is begin if Object.Annotation_Count > 0 then if Object.Current_State = Event_Held_Back then Object.May_Finish_Transformation := Object.Held_Back.Kind in Sequence_End | Mapping_End | Scalar | Alias; if E.Kind = Annotation_Start then if Object.Annotation_Count = 1 then Object.Current := Object.Held_Back; Object.Held_Back := E; Object.Current_State := Releasing_Held_Back; return; else Shift_Through (Object, Object.Annotation_Count, Object.Held_Back); end if; else Shift_Through (Object, Object.Annotation_Count, Object.Held_Back); end if; if Object.Current_State = Existing then Object.Held_Back := E; Object.Current_State := Releasing_Held_Back; return; end if; Object.Current_State := Absent; end if; Object.May_Finish_Transformation := E.Kind in Sequence_End | Mapping_End | Scalar | Alias; Shift_Through (Object, Object.Annotation_Count, E); elsif Object.Current_State = Event_Held_Back then Object.Current := Object.Held_Back; Object.Held_Back := E; Object.Current_State := Releasing_Held_Back; else Object.Current := E; Object.Current_State := Existing; end if; end Append; generic type Element_Type is private; type Array_Type is array (Positive range <>) of Element_Type; type Pointer_Type is access Array_Type; procedure Grow (Target : in out not null Pointer_Type; Last : in out Natural); procedure Grow (Target : in out not null Pointer_Type; Last : in out Natural) is procedure Free_Array is new Ada.Unchecked_Deallocation (Array_Type, Pointer_Type); begin if Last = Target'Last then declare Old_Array : Pointer_Type := Target; begin Target := new Array_Type (1 .. Last * 2); Target (1 .. Last) := Old_Array.all; Free_Array (Old_Array); end; end if; Last := Last + 1; end Grow; procedure Grow_Levels is new Grow (Annotation.Node_Context_Type, Level_Array, Level_Array_Pointer); procedure Grow_Annotations is new Grow (Annotated_Node, Node_Array, Node_Array_Pointer); procedure Put (Object : in out Instance; E : Event) is Locals : constant Events.Store.Accessor := Object.Context.Document_Store; begin if Object.Level_Count > 0 then case Object.Levels (Object.Level_Count) is when Annotation.Mapping_Key => Object.Levels (Object.Level_Count) := Annotation.Mapping_Value; when Annotation.Mapping_Value => Object.Levels (Object.Level_Count) := Annotation.Mapping_Key; when others => null; end case; end if; case E.Kind is when Annotation_Start => Locals.Memorize (E); declare use type Annotation.Maps.Cursor; Pos : constant Annotation.Maps.Cursor := (if E.Namespace = Standard_Annotation_Namespace then Annotation.Map.Find (E.Name.Value) else Annotation.Maps.No_Element); begin Grow_Annotations (Object.Annotations, Object.Annotation_Count); if Object.Annotation_Count = 1 then Object.Next_Event_Storage := (if E.Annotation_Properties.Anchor /= Text.Empty then Searching else No); end if; declare Swallows_Previous : Boolean := False; Impl : constant Transformator.Pointer := (if Pos = Annotation.Maps.No_Element then Annotation.Identity.New_Identity else Annotation.Maps.Element (Pos).all (Object.Pool, Object.Levels (Object.Level_Count), Object.Context, Swallows_Previous)); begin Object.Annotations (Object.Annotation_Count) := (Impl => Impl, Depth => Object.Level_Count, Swallows_Next => Swallows_Previous and Object.Level_Count = 1); if Swallows_Previous then if Object.Current_State /= Event_Held_Back then raise Annotation_Error with E.Namespace & E.Name & " applied to a value of a non-scalar mapping key"; end if; Object.Current_State := Absent; end if; Object.Append (E); end; end; Grow_Levels (Object.Levels, Object.Level_Count); Object.Levels (Object.Level_Count) := Annotation.Parameter_Item; when Annotation_End => Locals.Memorize (E); Object.Append (E); Object.Level_Count := Object.Level_Count - 1; when Document_Start => Locals.Clear; Object.Held_Back := E; Object.Current_State := Event_Held_Back; Grow_Levels (Object.Levels, Object.Level_Count); Object.Levels (Object.Level_Count) := Annotation.Document_Root; when Mapping_Start => Locals.Memorize (E); Object.Append (E); Grow_Levels (Object.Levels, Object.Level_Count); Object.Levels (Object.Level_Count) := Annotation.Mapping_Value; when Sequence_Start => Locals.Memorize (E); Object.Append (E); Grow_Levels (Object.Levels, Object.Level_Count); Object.Levels (Object.Level_Count) := Annotation.Sequence_Item; when Mapping_End | Sequence_End => Object.Level_Count := Object.Level_Count - 1; Locals.Memorize (E); Object.Append (E); when Document_End => if Object.Current_State = Swallowing_Document_End then Object.Current_State := Absent; else Object.Current := E; Object.Current_State := Existing; end if; Object.Level_Count := Object.Level_Count - 1; when Scalar => Locals.Memorize (E); if Object.Levels (Object.Level_Count) = Annotation.Mapping_Key then Object.Held_Back := E; Object.Current_State := Event_Held_Back; else Object.Append (E); end if; when Alias => Locals.Memorize (E); Object.Append (E); when Stream_Start | Stream_End => Object.Append (E); end case; end Put; function Has_Next (Object : Instance) return Boolean is (Object.Current_State in Existing | Releasing_Held_Back | Localizing_Alias or (Object.Current_State = Swallowing_Document_End and Object.Current.Kind /= Document_End)); function Next (Object : in out Instance) return Event is procedure Look_For_Additional_Element is begin if Object.Current_State /= Releasing_Held_Back then Object.Current_State := Absent; end if; for Cur_Annotation in 1 .. Object.Annotation_Count loop if Object.Annotations (Cur_Annotation).Impl.Has_Next then declare Next_Event : constant Event := Object.Annotations (Cur_Annotation).Impl.Next; begin if Cur_Annotation = Object.Annotation_Count and Object.May_Finish_Transformation then Finalize_Finished_Annotation_Impl (Object); end if; Shift_Through (Object, Cur_Annotation - 1, Next_Event); end; exit; end if; end loop; if Object.Current_State = Releasing_Held_Back then Object.Current_State := Absent; if Object.Annotation_Count > 0 then Object.May_Finish_Transformation := Object.Held_Back.Kind in Sequence_End | Mapping_End | Scalar | Alias; Shift_Through (Object, Object.Annotation_Count, Object.Held_Back); else Object.Current := Object.Held_Back; Object.Current_State := Existing; end if; end if; end Look_For_Additional_Element; procedure Update_Exists_In_Output (Anchor : Text.Reference) is use type Events.Context.Cursor; begin if Anchor /= Text.Empty then declare Pos : Events.Context.Cursor := Events.Context.Position (Object.Context, Anchor); begin if Pos /= Events.Context.No_Element then declare Referenced : constant Event := Events.Context.First (Pos); begin if Referenced.Start_Position = Object.Current.Start_Position and Referenced.Kind = Object.Current.Kind then Events.Context.Set_Exists_In_Output (Pos); end if; end; end if; end; end if; end Update_Exists_In_Output; procedure Update_Next_Storage (E : Event) is begin case Object.Next_Event_Storage is when Searching => if (case E.Kind is when Annotation_Start => E.Annotation_Properties.Anchor /= Text.Empty, when Mapping_Start | Sequence_Start => E.Collection_Properties.Anchor /= Text.Empty, when Scalar => E.Scalar_Properties.Anchor /= Text.Empty, when others => False) then Object.Context.Transformed_Store.Memorize (E); Object.Next_Event_Storage := Yes; else Object.Next_Event_Storage := No; end if; when Finishing => Object.Context.Transformed_Store.Memorize (E); Object.Next_Event_Storage := No; when Yes => Object.Context.Transformed_Store.Memorize (E); when No => null; end case; end Update_Next_Storage; begin case Object.Current_State is when Existing | Releasing_Held_Back => case Object.Current.Kind is when Alias => if Object.Current_State = Releasing_Held_Back then raise Program_Error with "internal error: alias may never generated while event is held back!"; end if; declare Pos : Events.Context.Cursor := Events.Context.Position (Object.Context, Object.Current.Target); begin if not Events.Context.Exists_In_Ouput (Pos) then Events.Context.Set_Exists_In_Output (Pos); Object.Current_Stream := Events.Context.Retrieve (Pos).Optional; return Ret : constant Event := Object.Current_Stream.Value.Next do Update_Next_Storage (Ret); case Ret.Kind is when Scalar => Object.Current_Stream.Clear; Look_For_Additional_Element; when Mapping_Start | Sequence_Start => Object.Current_State := Localizing_Alias; Object.Stream_Depth := Object.Stream_Depth + 1; when others => raise Program_Error with "alias refers to " & Object.Current.Kind'Img; end case; end return; end if; end; when Scalar => Update_Exists_In_Output (Object.Current.Scalar_Properties.Anchor); when Mapping_Start | Sequence_Start => Update_Exists_In_Output (Object.Current.Collection_Properties.Anchor); when others => null; end case; return Ret : constant Event := Object.Current do Update_Next_Storage (Ret); Look_For_Additional_Element; end return; when Localizing_Alias => return Ret : constant Event := Object.Current_Stream.Value.Next do Update_Next_Storage (Ret); case Ret.Kind is when Mapping_Start | Sequence_Start => Object.Stream_Depth := Object.Stream_Depth + 1; when Mapping_End | Sequence_End => Object.Stream_Depth := Object.Stream_Depth - 1; if Object.Stream_Depth = 0 then Object.Current_Stream.Clear; Look_For_Additional_Element; end if; when others => null; end case; end return; when Swallowing_Document_End => if Object.Current.Kind = Document_End then raise Constraint_Error with "no event to retrieve"; else return Ret : constant Event := Object.Current do Update_Next_Storage (Ret); Object.Current := (Kind => Document_End, others => <>); end return; end if; when Absent | Event_Held_Back => raise Constraint_Error with "no event to retrieve"; end case; end Next; procedure Finalize (Object : in out Instance) is Ptr : Node_Array_Pointer := Object.Annotations; begin for I in 1 .. Object.Annotation_Count loop Free_Transformator (Object.Annotations (I).Impl); end loop; Free_Array (Ptr); end Finalize; end Yaml.Transformator.Annotation_Processor;
{ "source": "starcoderdata", "programming_language": "ada" }
with Gtkada.Builder; with Gtk.List_Store; with Gtk.Status_Bar; with Gtk.Text_Buffer; with Gtk.Widget; package gui is builder : Gtkada.Builder.Gtkada_Builder; topLevelWindow : Gtk.Widget.Gtk_Widget; textbuf : Gtk.Text_Buffer.Gtk_Text_Buffer; statusBar : Gtk.Status_Bar.Gtk_Status_Bar; --statusBarContext : Gtk.Status_Bar.Context_Id; machinecodeList : Gtk.List_Store.Gtk_List_Store; memoryList : Gtk.List_Store.Gtk_List_Store; registerList : Gtk.List_Store.Gtk_List_Store; procedure load; procedure setTitle(newTitle : String); procedure updateGUI_VM; end gui;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; with System; use System; with System.Address_Image; with System.Address_To_Access_Conversions; with Ada.Environment_Variables; with opencl_api_spec; with dl_loader; package body opencl is use opencl_api_spec; type C_Address_Array is array (Interfaces.C.size_t range 1 .. 64) of aliased Raw_Address; type C_Char_Buffer is array (Interfaces.C.size_t range 1 .. 1024) of aliased Interfaces.C.char; type C_SizeT_Array is array (Interfaces.C.size_t range 1 .. 64) of aliased Interfaces.C.size_t; type Context_Property is new Long_Long_Integer; pragma Convention (Convention => C, Entity => C_Address_Array); pragma Convention (Convention => C, Entity => C_Char_Buffer); package C_Addr_Arr_Conv is new System.Address_To_Access_Conversions(Object => C_Address_Array); package C_Char_Buff_Conv is new System.Address_To_Access_Conversions(Object => C_Char_Buffer); package C_SizeT_Arr_Conv is new System.Address_To_Access_Conversions(Object => C_SizeT_Array); function Convert(code: in Interfaces.C.int) return Status is result: Status; begin begin if code = -9999 then Ada.Text_IO.Put_Line("CODE 9999!"); return opencl.INVALID_VALUE; end if; result := Status'Enum_Val(code); exception when E: Constraint_Error => Ada.Text_IO.Put_Line("Status code not recognized: " & code'Image); raise; end; return result; end Convert; function Convert(code: in cl_int) return Status is begin return Convert(Interfaces.C.int(code)); end Convert; cl_lib_handle: dl_loader.Handle; function To_Ada(s: in C_Char_Buffer; size: Interfaces.C.size_t) return String is result: String(1 .. Integer(size)) := (others => ASCII.NUL); begin for idx in 1 .. size loop result(Integer(idx)) := Interfaces.C.To_Ada(s(idx)); end loop; return result; end To_Ada; function Convert(event_list: in Events) return C_Address_Array is result: C_Address_Array := (others => 0); begin for i in 1 .. event_list'Length loop result(Interfaces.C.size_t(i)) := Raw_Address(event_list(i)); end loop; return result; end Convert; --TODO better check function Get_OpenCL_Path(arch: Arch_Type) return String is is_linux: constant Boolean := Ada.Environment_Variables.Exists("HOME"); begin if is_linux then return "TODO"; else return (if arch = ARCH_64 then "C:/Windows/SysWOW64/OpenCL.dll" else "C:/Windows/System32/OpenCL.dll"); end if; end Get_OpenCL_Path; function Init(path: String) return Status is result: Boolean; begin result := dl_loader.Open(path, cl_lib_handle); if result then result := opencl_api_spec.Load_From(cl_lib_handle); end if; return (if result then SUCCESS else INVALID_VALUE); end Init; function Get_Platforms(result_status: out Status) return Platforms is function Impl(num_entries_p: Interfaces.C.unsigned; platforms_ptr_p: System.Address; num_platforms_p: access Interfaces.C.unsigned) return Interfaces.C.int with Import, Address => clGetPlatformIDs, Convention => C; num_platforms: aliased Interfaces.C.unsigned := 0; platforms_ptr: aliased C_Address_Array := (others => 0); cl_code: Interfaces.C.int; current_index: Interfaces.C.size_t := 1; null_platforms: constant Platforms(1 .. 0) := (others => 0); begin if clGetPlatformIDs = System.Null_Address then result_status := INVALID_PLATFORM; return null_platforms; end if; cl_code := Impl(platforms_ptr'Length, C_Addr_Arr_Conv.To_Address(platforms_ptr'Unchecked_Access), num_platforms'Access); result_status := Convert(cl_code); if result_status = SUCCESS then return result: Platforms(1 .. Integer(num_platforms)) do for ptr of result loop if current_index <= Interfaces.C.size_t(num_platforms) then ptr := Platform_ID(platforms_ptr(current_index)); else ptr := Platform_ID(0); end if; current_index := current_index + 1; end loop; end return; end if; return null_platforms; end Get_Platforms; function Get_Platform_Info(id: in Platform_ID; info: Platform_Info; result_status: out Status) return String is function Impl(p: Raw_Address; info: Interfaces.C.unsigned; val_size: Interfaces.C.size_t; val: System.Address; val_size_ret: access Interfaces.C.size_t) return Interfaces.C.int with Import, Address => clGetPlatformInfo, Convention => C; cl_code: Interfaces.C.Int; size_ret: aliased Interfaces.C.size_t; string_ret: aliased C_Char_Buffer; begin cl_code := Impl(Raw_Address(id), Platform_Info'Enum_Rep(info), string_ret'Length, C_Char_Buff_Conv.To_Address(string_ret'Unchecked_Access), size_ret'Access); result_status := Convert(cl_code); return To_Ada(string_ret, size_ret - 1); end Get_Platform_Info; function Get_Devices(id: in Platform_ID; dev_type: in Device_Type; result_status: out Status) return Devices is null_devices: constant Devices(1 .. 0) := (others => 0); function Impl(p: Raw_Address; dev_t: Interfaces.C.unsigned; num_entries: Interfaces.C.unsigned; out_devices: System.Address; num_devs: access Interfaces.C.unsigned) return Interfaces.C.int with Import, Address => clGetDeviceIDs, Convention => C; num_devices: aliased Interfaces.C.unsigned := 0; device_ids: aliased C_Address_Array := (others => 0); cl_res: Interfaces.C.int; begin cl_res := Impl(p => Raw_Address(id), dev_t => Device_Type'Enum_Rep(dev_type), num_entries => device_ids'Length, out_devices => C_Addr_Arr_Conv.To_Address(device_ids'Unchecked_Access), num_devs => num_devices'Access); result_status := Convert(cl_res); if result_status = SUCCESS then return devs: Devices(1 .. Integer(num_devices)) do for idx in 1 .. num_devices loop devs(Integer(idx)) := Device_ID(device_ids(Interfaces.C.size_t(idx))); end loop; end return; end if; return null_devices; end Get_Devices; function Get_Device_Info(id: in Device_ID; info: in Device_Info_Bool; result_status: out Status) return Boolean is function Impl(p: Raw_Address; dev_i: Interfaces.C.unsigned; res_size: Interfaces.C.size_t; out_info: access Interfaces.C.unsigned; info_len: System.Address) return Interfaces.C.int with Import, Address => clGetDeviceInfo, Convention => C; flag_value: aliased Interfaces.C.unsigned := 0; cl_status: Interfaces.C.int := 0; begin cl_status := Impl(p => Raw_Address(id), dev_i => Device_Info_Bool'Enum_Rep(info), res_size => Interfaces.C.unsigned'Size, out_info => flag_value'Access, info_len => System.Null_Address); result_status := Convert(cl_status); return (if flag_value = 0 then False else True); end Get_Device_Info; function Get_Device_Info(id: in Device_ID; info: in Device_Info_String; result_status: out Status) return String is function Impl(p: Raw_Address; dev_i: Interfaces.C.unsigned; res_size: Interfaces.C.size_t; out_info: System.Address; info_len: access Interfaces.C.size_t) return Interfaces.C.int with Import, Address => clGetDeviceInfo, Convention => C; null_string: constant String(1 .. 0) := (others => ' '); cl_status: Interfaces.C.int := 0; buffer: aliased C_Char_Buffer; actual_length: aliased Interfaces.C.size_t := 0; begin cl_status := Impl(p => Raw_Address(id), dev_i => Device_Info_String'Enum_Rep(info), res_size => buffer'Length, out_info => C_Char_Buff_Conv.To_Address(buffer'Unchecked_Access), info_len => actual_length'Access); result_status := Convert(cl_status); if result_status = SUCCESS then return To_Ada(buffer, actual_length - 1); end if; return null_string; end Get_Device_Info; function Create_Context(context_platform: in Platform_ID; context_device: in Device_ID; result_status: out Status) return Context_ID is function Impl(ctx_props: System.Address; num_devs: Interfaces.C.unsigned; devs: System.Address; cb: System.Address; user_data: System.Address; err_code: access Interfaces.C.int) return Raw_Address with Import, Address => clCreateContext, Convention => C; properties: aliased C_Address_Array := (others => 0); dev_ids: aliased C_Address_Array := (others => 0); err_code: aliased Interfaces.C.int := 0; ctx_id: Raw_Address := 0; begin dev_ids(1) := Raw_Address(context_device); properties(1) := Raw_Address(Context_Properties'Enum_Rep(CONTEXT_PROP_PLATFORM)); properties(2) := Raw_Address(context_platform); ctx_id := Impl(ctx_props => C_Addr_Arr_Conv.To_Address(properties'Unchecked_Access), num_devs => 1, devs => C_Addr_Arr_Conv.To_Address(dev_ids'Unchecked_Access), cb => System.Null_Address, user_data => System.Null_Address, err_code => err_code'Access); result_status := Convert(err_code); return Context_ID(ctx_id); end Create_Context; function Release_Context(id: in Context_ID) return Status is function Impl(p: Raw_Address) return Interfaces.C.int with Import, Address => clReleaseContext, Convention => C; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(Raw_Address(id)); return Convert(cl_code); end Release_Context; function Create_Program(ctx: in Context_ID; source: in String; result_status: out Status) return Program_ID is function Impl(ctx: Raw_Address; count: Interfaces.C.unsigned; strs: access Interfaces.C.Strings.chars_ptr; lengths: System.Address; err_code: access Interfaces.C.int) return Raw_Address with Import, Address => clCreateProgramWithSource, Convention => C; prog_id: Raw_Address := 0; err_code: aliased Interfaces.C.int := 0; lengths: aliased C_SizeT_Array := (others => 0); source_ptr: aliased Interfaces.C.Strings.chars_ptr; begin lengths(1) := source'Length; source_ptr := Interfaces.C.Strings.New_String(Str => source); prog_id := Impl(ctx => Raw_Address(ctx), count => 1, strs => source_ptr'Access, lengths => C_SizeT_Arr_Conv.To_Address(lengths'Unchecked_Access), err_code => err_code'Access); result_status := Convert(err_code); Interfaces.C.Strings.Free(Item => source_ptr); return Program_ID(prog_id); end Create_Program; function Build_Program(id: in Program_ID; device: in Device_ID; options: in String) return Status is function Impl(p_id: Raw_Address; num_devices: Interfaces.C.unsigned; device_list: System.Address; options: Interfaces.C.Strings.char_array_access; user_cb: System.Address; user_data: System.Address) return Interfaces.C.int with Import, Address => clBuildProgram, Convention => C; cl_code: Interfaces.C.int := 0; device_array: aliased C_Address_Array := (others => 0); opts: aliased Interfaces.C.char_array := Interfaces.C.To_C(options); begin device_array(1) := Raw_Address(device); cl_code := Impl(p_id => Raw_Address(id), num_devices => 1, device_list => C_Addr_Arr_Conv.To_Address(device_array'Unchecked_Access), options => opts'Unchecked_Access, user_cb => System.Null_Address, user_data => System.Null_Address); return Convert(cl_code); end Build_Program; function Get_Program_Build_Log(id: in Program_ID; device: in Device_ID; result_status: out Status) return String is function Impl(prog: Raw_Address; dev: Raw_Address; info: Interfaces.C.unsigned; available_size: Interfaces.C.size_t; ptr: System.Address; ret_size: access Interfaces.C.size_t) return Interfaces.C.int with Import, Address => clGetProgramBuildInfo, Convention => C; build_log_size: aliased Interfaces.C.size_t; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(prog => Raw_Address(id), dev => Raw_Address(device), info => Program_Build_Info_String'Enum_Rep(PROGRAM_BUILD_LOG), available_size => 0, ptr => System.Null_Address, ret_size => build_log_size'Access); declare type C_Char_Buff is new Interfaces.C.char_array(1 .. build_log_size); build_log_buffer: aliased C_Char_Buff := (1 .. build_log_size => Interfaces.C.To_C(ASCII.NUL)); package Char_Arr_Addr_Conv is new System.Address_To_Access_Conversions(Object => C_Char_Buff); begin cl_code := Impl(prog => Raw_Address(id), dev => Raw_Address(device), info => Program_Build_Info_String'Enum_Rep(PROGRAM_BUILD_LOG), available_size => build_log_size, ptr => Char_Arr_Addr_Conv.To_Address(build_log_buffer'Unchecked_Access), ret_size => build_log_size'Access); result_status := Convert(cl_code); return Interfaces.C.To_Ada(Interfaces.C.char_array(build_log_buffer)); end; end Get_Program_Build_Log; function Release_Program(id: in Program_ID) return Status is function Impl(p: Raw_Address) return Interfaces.C.int with Import, Address => clReleaseProgram, Convention => C; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(Raw_Address(id)); return Convert(cl_code); end Release_Program; function Create_Kernel(program: in Program_ID; name: in String; result_status: out Status) return Kernel_ID is function Impl(prog: Raw_Address; name_str: Interfaces.C.Strings.char_array_access; err_c: access Interfaces.C.int) return Raw_Address with Import, Address => clCreateKernel, Convention => C; cl_code: aliased Interfaces.C.int := 0; str_ptr: aliased Interfaces.C.char_array := Interfaces.C.To_C(name); result: Raw_Address := 0; begin result := Impl(prog => Raw_Address(program), name_str => str_ptr'Unchecked_Access, err_c => cl_code'Access); result_status := Convert(cl_code); return Kernel_ID(result); end Create_Kernel; function Release_Kernel(id: in Kernel_ID) return Status is function Impl(p: Raw_Address) return Interfaces.C.int with Import, Address => clReleaseKernel, Convention => C; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(Raw_Address(id)); return Convert(cl_code); end Release_Kernel; function Set_Kernel_Arg(id: in Kernel_ID; index: Natural; size: Positive; address: System.Address) return Status is function Impl(k_id: Raw_Address; arg_index: Interfaces.C.unsigned; arg_size: Interfaces.C.size_t; arg_addr: System.Address) return Interfaces.C.int with Import, Address => clSetKernelArg, Convention => C; cl_code: Interfaces.C.int; arg_index: constant Interfaces.C.unsigned := Interfaces.C.unsigned(index); arg_size: constant Interfaces.C.size_t := Interfaces.C.size_t(size); begin cl_code := Impl(k_id => Raw_Address(id), arg_index => arg_index, arg_size => arg_size, arg_addr => address); return Convert(cl_code); end Set_Kernel_Arg; function Enqueue_Kernel(queue: in Command_Queue; kernel: in Kernel_ID; global_offset: in Offsets; global_work_size, local_work_size: in Dimensions; event_wait_list: in Events; event: out Event_ID) return Status is function Impl(q_id, k_id: Raw_Address; dims: Interfaces.C.unsigned; glob_off, glob_ws, local_ws: access C_SizeT_Array; num_wait_events: Interfaces.C.unsigned; event_wait: System.Address; event_res: access Raw_Address) return Interfaces.C.int with Import, Address => clEnqueueNDRangeKernel, Convention => C; event_result: aliased Raw_Address; result: Interfaces.C.int := 0; global_ws_array: aliased C_SizeT_Array := (others => 0); local_ws_array: aliased C_SizeT_Array := (others => 0); global_off_array: aliased C_SizeT_Array := (others => 0); event_wait_array: aliased C_Address_Array := Convert(event_wait_list); begin for i in 1 .. global_offset'Length loop global_off_array(Interfaces.C.size_t(i)) := Interfaces.C.size_t(global_offset(i)); end loop; for i in 1 .. global_work_size'Length loop global_ws_array(Interfaces.C.size_t(i)) := Interfaces.C.size_t(global_work_size(i)); end loop; for i in 1 .. local_work_size'Length loop local_ws_array(Interfaces.C.size_t(i)) := Interfaces.C.size_t(local_work_size(i)); end loop; result := Impl(q_id => Raw_Address(queue), k_id => Raw_Address(kernel), dims => global_work_size'Length, glob_off => global_off_array'Access, glob_ws => global_ws_array'Access, local_ws => local_ws_array'Access, num_wait_events => event_wait_list'Length, event_wait => (if event_wait_list'Length = 0 then System.Null_Address else C_Addr_Arr_Conv.To_Address(event_wait_array'Unchecked_Access)), event_res => event_result'Access); event := Event_ID(event_result); return Convert(result); end Enqueue_Kernel; function Create_Command_Queue(ctx: in Context_ID; dev: in Device_ID; result_status: out Status) return Command_Queue is function Impl(ctx_id: Raw_Address; dev_id: Raw_Address; props: System.Address; err_c: access Interfaces.C.int) return Raw_Address with Import, Address => clCreateCommandQueueWithProperties, Convention => C; cl_code: aliased Interfaces.C.int := 0; result: Raw_Address := 0; begin result := Impl(ctx_id => Raw_Address(ctx), dev_id => Raw_Address(dev), props => System.Null_Address, err_c => cl_code'Access); result_status := Convert(cl_code); return Command_Queue(result); end Create_Command_Queue; function Release_Command_Queue(id: in Command_Queue) return Status is function Impl(p: Raw_Address) return Interfaces.C.int with Import, Address => clReleaseCommandQueue, Convention => C; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(Raw_Address(id)); return Convert(cl_code); end Release_Command_Queue; function Wait_For_Events(ev_list: Events) return Status is function Impl(num_events: Interfaces.C.unsigned; event_arr: access C_Address_Array) return Interfaces.C.int with Import, Address => clWaitForEvents, Convention => C; cl_code: Interfaces.C.int := 0; event_arr: aliased C_Address_Array := (others => 0); begin for i in 1 .. ev_list'Length loop event_arr(Interfaces.C.size_t(i)) := Raw_Address(ev_list(i)); end loop; cl_code := Impl(num_events => ev_list'Length, event_arr => event_arr'Access); return Convert(cl_code); end Wait_For_Events; function Release_Event(ev: in Event_ID) return Status is function Impl(p: Raw_Address) return cl_int with Import, Address => clReleaseEvent, Convention => C; cl_code: cl_int := 0; begin cl_code := Impl(Raw_Address(ev)); return Convert(cl_code); end Release_Event; function Retain_Event(ev: in Event_ID) return Status is function Impl(p: Raw_Address) return cl_int with Import, Address => clRetainEvent, Convention => C; cl_code: cl_int := 0; begin cl_code := Impl(Raw_Address(ev)); return Convert(cl_code); end Retain_Event; function Finish(queue: in Command_Queue) return Status is function Impl(p: Raw_Address) return Interfaces.C.int with Import, Address => clFinish, Convention => C; cl_code: Interfaces.C.int := 0; begin cl_code := Impl(Raw_Address(queue)); return Convert(cl_code); end Finish; function Convert(flags: in Mem_Flags) return cl_mem_flags is result: cl_mem_flags := 0; current_flag: cl_mem_flags := 0; begin for i in flags'Range loop if flags(i) then current_flag := cl_mem_flags(Mem_Flag'Enum_Rep(i)); result := result or current_flag; end if; end loop; return result; end Convert; function Create_Buffer(ctx: in Context_ID; flags: in Mem_Flags; size: Positive; host_ptr: System.Address; result_status: out Status) return Mem_ID is function Impl(ctx: Raw_Address; flags: cl_mem_flags; size: Interfaces.C.size_t; host_ptr: System.Address; result_code: access cl_int) return Raw_Address with Import, Address => clCreateBuffer, Convention => C; cl_code: aliased cl_int; size_p: constant Interfaces.C.size_t := Interfaces.C.size_t(size); raw_mem_id: Raw_Address; begin raw_mem_id := Impl(ctx => Raw_Address(ctx), flags => Convert(flags), size => size_p, host_ptr => host_ptr, result_code => cl_code'Access); result_status := Convert(cl_code); return Mem_ID(raw_mem_id); end Create_Buffer; function Enqueue_Read(queue: in Command_Queue; mem_ob: in Mem_ID; block_read: Boolean; offset: Natural; size: Positive; ptr: System.Address; events_to_wait_for: in Events; event: out Event_ID) return Status is function Impl(q: Raw_Address; mem: Raw_Address; block_read: cl_bool; offset, size: Interfaces.C.size_t; ptr: System.Address; num_wait_events: Interfaces.C.unsigned; event_wait: System.Address; event_res: access Raw_Address) return cl_int with Import, Address => clEnqueueReadBuffer, Convention => C; event_list: aliased C_Address_Array := Convert(events_to_wait_for); event_result: aliased Raw_Address; cl_code: cl_int; begin cl_code := Impl(q => Raw_Address(queue), mem => Raw_Address(mem_ob), block_read => cl_bool(if block_read then 1 else 0), offset => Interfaces.C.size_t(offset), size => Interfaces.C.size_t(size), ptr => ptr, num_wait_events => events_to_wait_for'Length, event_wait => (if events_to_wait_for'Length = 0 then System.Null_Address else C_Addr_Arr_Conv.To_Address(event_list'Unchecked_Access)), event_res => event_result'Access); event := Event_ID(event_result); return Convert(cl_code); end Enqueue_Read; function Enqueue_Write(queue: in Command_Queue; mem_ob: in Mem_ID; block_write: Boolean; offset: Natural; size: Positive; ptr: System.Address; events_to_wait_for: in Events; event: out Event_ID) return Status is function Impl(q: Raw_Address; mem: Raw_Address; block_write: cl_bool; offset, size: Interfaces.C.size_t; ptr: System.Address; num_wait_events: Interfaces.C.unsigned; event_wait: System.Address; event_res: access Raw_Address) return cl_int with Import, Address => clEnqueueWriteBuffer, Convention => C; event_list: aliased C_Address_Array := Convert(events_to_wait_for); event_result: aliased Raw_Address; cl_code: cl_int; begin cl_code := Impl(q => Raw_Address(queue), mem => Raw_Address(mem_ob), block_write => cl_bool(if block_write then 1 else 0), offset => Interfaces.C.size_t(offset), size => Interfaces.C.size_t(size), ptr => ptr, num_wait_events => events_to_wait_for'Length, event_wait => (if events_to_wait_for'Length = 0 then System.Null_Address else C_Addr_Arr_Conv.To_Address(event_list'Unchecked_Access)), event_res => event_result'Access); event := Event_ID(event_result); return Convert(cl_code); end Enqueue_Write; function Release(mem_ob: in Mem_ID) return Status is function Impl(id: Raw_Address) return Interfaces.C.int with Import, Address => clReleaseMemObject, Convention => C; cl_code: Interfaces.C.int; begin cl_code := Impl(Raw_Address(mem_ob)); return Convert(cl_code); end Release; function Get_Local_Work_Size(width, height: in Positive) return opencl.Dimensions is result: opencl.Dimensions := (1 => 1, 2 => 1); preferred_multiples: constant opencl.Dimensions := (32, 16, 8, 4, 2); begin for m of preferred_multiples loop if width rem m = 0 then result(1) := m; exit; end if; end loop; for m of preferred_multiples loop if height rem m = 0 then result(2) := m; exit; end if; end loop; return result; end Get_Local_Work_Size; end opencl;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- echo [string ...] -- -- Write arguments to the standard output -- -- The echo utility writes any specified operands, separated by single blank -- (`` '') characters and followed by a newline (``\n'') character, to the -- standard output. -- with Ada.Command_Line; with Ada.Text_IO; use Ada; procedure Echo is begin if Command_Line.Argument_Count > 0 then Text_IO.Put (Command_Line.Argument (1)); for Arg in 2 .. Command_Line.Argument_Count loop Text_IO.Put (' '); Text_IO.Put (Command_Line.Argument (Arg)); end loop; end if; Text_IO.New_Line; end Echo;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Strings.Wide_Maps; with Ada.Finalization; package Ada.Strings.Wide_Unbounded is pragma Preelaborate; type Unbounded_Wide_String is private; Null_Unbounded_Wide_String : constant Unbounded_Wide_String; function Length (Source : Unbounded_Wide_String) return Natural; type Wide_String_Access is access all Wide_String; procedure Free (X : in out Wide_String_Access); -------------------------------------------------------- -- Conversion, Concatenation, and Selection Functions -- -------------------------------------------------------- function To_Unbounded_Wide_String (Source : Wide_String) return Unbounded_Wide_String; function To_Unbounded_Wide_String (Length : Natural) return Unbounded_Wide_String; function To_Wide_String (Source : Unbounded_Wide_String) return Wide_String; procedure Set_Unbounded_Wide_String (Target : out Unbounded_Wide_String; Source : Wide_String); pragma Ada_05 (Set_Unbounded_Wide_String); procedure Append (Source : in out Unbounded_Wide_String; New_Item : Unbounded_Wide_String); procedure Append (Source : in out Unbounded_Wide_String; New_Item : Wide_String); procedure Append (Source : in out Unbounded_Wide_String; New_Item : Wide_Character); function "&" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Unbounded_Wide_String; function "&" (Left : Unbounded_Wide_String; Right : Wide_String) return Unbounded_Wide_String; function "&" (Left : Wide_String; Right : Unbounded_Wide_String) return Unbounded_Wide_String; function "&" (Left : Unbounded_Wide_String; Right : Wide_Character) return Unbounded_Wide_String; function "&" (Left : Wide_Character; Right : Unbounded_Wide_String) return Unbounded_Wide_String; function Element (Source : Unbounded_Wide_String; Index : Positive) return Wide_Character; procedure Replace_Element (Source : in out Unbounded_Wide_String; Index : Positive; By : Wide_Character); function Slice (Source : Unbounded_Wide_String; Low : Positive; High : Natural) return Wide_String; function Unbounded_Slice (Source : Unbounded_Wide_String; Low : Positive; High : Natural) return Unbounded_Wide_String; pragma Ada_05 (Unbounded_Slice); procedure Unbounded_Slice (Source : Unbounded_Wide_String; Target : out Unbounded_Wide_String; Low : Positive; High : Natural); pragma Ada_05 (Unbounded_Slice); function "=" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Boolean; function "=" (Left : Unbounded_Wide_String; Right : Wide_String) return Boolean; function "=" (Left : Wide_String; Right : Unbounded_Wide_String) return Boolean; function "<" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Boolean; function "<" (Left : Unbounded_Wide_String; Right : Wide_String) return Boolean; function "<" (Left : Wide_String; Right : Unbounded_Wide_String) return Boolean; function "<=" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Boolean; function "<=" (Left : Unbounded_Wide_String; Right : Wide_String) return Boolean; function "<=" (Left : Wide_String; Right : Unbounded_Wide_String) return Boolean; function ">" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Boolean; function ">" (Left : Unbounded_Wide_String; Right : Wide_String) return Boolean; function ">" (Left : Wide_String; Right : Unbounded_Wide_String) return Boolean; function ">=" (Left : Unbounded_Wide_String; Right : Unbounded_Wide_String) return Boolean; function ">=" (Left : Unbounded_Wide_String; Right : Wide_String) return Boolean; function ">=" (Left : Wide_String; Right : Unbounded_Wide_String) return Boolean; ------------------------ -- Search Subprograms -- ------------------------ function Index (Source : Unbounded_Wide_String; Pattern : Wide_String; Going : Direction := Forward; Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural; function Index (Source : Unbounded_Wide_String; Pattern : Wide_String; Going : Direction := Forward; Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural; function Index (Source : Unbounded_Wide_String; Set : Wide_Maps.Wide_Character_Set; Test : Membership := Inside; Going : Direction := Forward) return Natural; function Index (Source : Unbounded_Wide_String; Pattern : Wide_String; From : Positive; Going : Direction := Forward; Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural; pragma Ada_05 (Index); function Index (Source : Unbounded_Wide_String; Pattern : Wide_String; From : Positive; Going : Direction := Forward; Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural; pragma Ada_05 (Index); function Index (Source : Unbounded_Wide_String; Set : Wide_Maps.Wide_Character_Set; From : Positive; Test : Membership := Inside; Going : Direction := Forward) return Natural; pragma Ada_05 (Index); function Index_Non_Blank (Source : Unbounded_Wide_String; Going : Direction := Forward) return Natural; function Index_Non_Blank (Source : Unbounded_Wide_String; From : Positive; Going : Direction := Forward) return Natural; pragma Ada_05 (Index_Non_Blank); function Count (Source : Unbounded_Wide_String; Pattern : Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural; function Count (Source : Unbounded_Wide_String; Pattern : Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural; function Count (Source : Unbounded_Wide_String; Set : Wide_Maps.Wide_Character_Set) return Natural; procedure Find_Token (Source : Unbounded_Wide_String; Set : Wide_Maps.Wide_Character_Set; Test : Membership; First : out Positive; Last : out Natural); ------------------------------------ -- String Translation Subprograms -- ------------------------------------ function Translate (Source : Unbounded_Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping) return Unbounded_Wide_String; procedure Translate (Source : in out Unbounded_Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping); function Translate (Source : Unbounded_Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Unbounded_Wide_String; procedure Translate (Source : in out Unbounded_Wide_String; Mapping : Wide_Maps.Wide_Character_Mapping_Function); --------------------------------------- -- String Transformation Subprograms -- --------------------------------------- function Replace_Slice (Source : Unbounded_Wide_String; Low : Positive; High : Natural; By : Wide_String) return Unbounded_Wide_String; procedure Replace_Slice (Source : in out Unbounded_Wide_String; Low : Positive; High : Natural; By : Wide_String); function Insert (Source : Unbounded_Wide_String; Before : Positive; New_Item : Wide_String) return Unbounded_Wide_String; procedure Insert (Source : in out Unbounded_Wide_String; Before : Positive; New_Item : Wide_String); function Overwrite (Source : Unbounded_Wide_String; Position : Positive; New_Item : Wide_String) return Unbounded_Wide_String; procedure Overwrite (Source : in out Unbounded_Wide_String; Position : Positive; New_Item : Wide_String); function Delete (Source : Unbounded_Wide_String; From : Positive; Through : Natural) return Unbounded_Wide_String; procedure Delete (Source : in out Unbounded_Wide_String; From : Positive; Through : Natural); function Trim (Source : Unbounded_Wide_String; Side : Trim_End) return Unbounded_Wide_String; procedure Trim (Source : in out Unbounded_Wide_String; Side : Trim_End); function Trim (Source : Unbounded_Wide_String; Left : Wide_Maps.Wide_Character_Set; Right : Wide_Maps.Wide_Character_Set) return Unbounded_Wide_String; procedure Trim (Source : in out Unbounded_Wide_String; Left : Wide_Maps.Wide_Character_Set; Right : Wide_Maps.Wide_Character_Set); function Head (Source : Unbounded_Wide_String; Count : Natural; Pad : Wide_Character := Wide_Space) return Unbounded_Wide_String; procedure Head (Source : in out Unbounded_Wide_String; Count : Natural; Pad : Wide_Character := Wide_Space); function Tail (Source : Unbounded_Wide_String; Count : Natural; Pad : Wide_Character := Wide_Space) return Unbounded_Wide_String; procedure Tail (Source : in out Unbounded_Wide_String; Count : Natural; Pad : Wide_Character := Wide_Space); function "*" (Left : Natural; Right : Wide_Character) return Unbounded_Wide_String; function "*" (Left : Natural; Right : Wide_String) return Unbounded_Wide_String; function "*" (Left : Natural; Right : Unbounded_Wide_String) return Unbounded_Wide_String; private pragma Inline (Length); package AF renames Ada.Finalization; Null_Wide_String : aliased Wide_String := ""; function To_Unbounded_Wide (S : Wide_String) return Unbounded_Wide_String renames To_Unbounded_Wide_String; type Unbounded_Wide_String is new AF.Controlled with record Reference : Wide_String_Access := Null_Wide_String'Access; Last : Natural := 0; end record; -- The Unbounded_Wide_String is using a buffered implementation to increase -- speed of the Append/Delete/Insert procedures. The Reference string -- pointer above contains the current string value and extra room at the -- end to be used by the next Append routine. Last is the index of the -- string ending character. So the current string value is really -- Reference (1 .. Last). pragma Stream_Convert (Unbounded_Wide_String, To_Unbounded_Wide, To_Wide_String); pragma Finalize_Storage_Only (Unbounded_Wide_String); -- Finalization is required only for freeing storage procedure Initialize (Object : in out Unbounded_Wide_String); procedure Adjust (Object : in out Unbounded_Wide_String); procedure Finalize (Object : in out Unbounded_Wide_String); procedure Realloc_For_Chunk (Source : in out Unbounded_Wide_String; Chunk_Size : Natural); -- Adjust the size allocated for the string. Add at least Chunk_Size so it -- is safe to add a string of this size at the end of the current content. -- The real size allocated for the string is Chunk_Size + x of the current -- string size. This buffered handling makes the Append unbounded string -- routines very fast. Null_Unbounded_Wide_String : constant Unbounded_Wide_String := (AF.Controlled with Reference => Null_Wide_String'Access, Last => 0); -- Note: this declaration is illegal since library level controlled -- objects are not allowed in preelaborated units. See AI-161 for a -- discussion of this issue and an attempt to address it. Meanwhile, -- what happens in GNAT is that this check is omitted for internal -- implementation units (see check in sem_cat.adb). end Ada.Strings.Wide_Unbounded;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with HAL; with HAL.SPI; with RP.Clock; with RP.GPIO; with RP.SPI; with RP.Device; with Pico; with SPI_Slave_Pico; procedure Main_Slave_Pico is Data_In : HAL.SPI.SPI_Data_16b (1 .. 1) := (others => 0); Status_In : HAL.SPI.SPI_Status; THE_VALUE : constant HAL.UInt16 := HAL.UInt16 (16#A5A5#); Data_Out : HAL.SPI.SPI_Data_16b (1 .. 1) := (others => THE_VALUE); Status_Out : HAL.SPI.SPI_Status; use HAL; begin RP.Clock.Initialize (Pico.XOSC_Frequency); RP.Device.Timer.Enable; Pico.LED.Configure (RP.GPIO.Output); SPI_Slave_Pico.Initialize; loop -- do this to get the slave ready SPI_Slave_Pico.SPI.Transmit (Data_Out, Status_Out); for I in 1 .. 1 loop SPI_Slave_Pico.SPI.Receive (Data_In, Status_In); Data_Out (1) := not Data_In (1); SPI_Slave_Pico.SPI.Transmit (Data_Out, Status_Out); end loop; RP.Device.Timer.Delay_Milliseconds (10); Pico.LED.Toggle; end loop; end Main_Slave_Pico;
{ "source": "starcoderdata", "programming_language": "ada" }
-- implementation of package Bubble -- see bubble.ads for a specification -- which gives a brief overview of the package with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; package body Bubble is protected body State is procedure Set_All(a, b, c, d : Integer) is begin State.a := a; State.b := b; State.c := c; State.d := d; Print_State; end Set_All; entry Wait_Until_Sorted(a, b, c, d : out Integer) when (a <= b and b <= c and c <= d) is begin a := State.a; b := State.b; c := State.c; d := State.d; end Wait_Until_Sorted; -- private procedure used to help user see what happens: procedure Print_State is begin Put("a = "); Put(a,2); Put("; "); Put("b = "); Put(b,2); Put("; "); Put("c = "); Put(c,2); Put("; "); Put("d = "); Put(d,2); Put("; "); Put_Line(""); end Print_State; procedure Swap(n, m : in out Integer) is temp : Integer; begin temp := n; n := m; m := temp; end Swap; entry BubbleAB when a > b is begin Swap(a,b); Print_State; end BubbleAB; entry BubbleBC when b > c is begin Swap(b,c); Print_State; end BubbleBC; entry BubbleCD when c > d is begin Swap(c,d); Print_State; end BubbleCD; end State; -- Tasks that keep calling Bubble.. to sort the numbers asap: task body BubbleAB is begin loop State.BubbleAB; end loop; end BubbleAB; -- Tasks that keep calling Bubble.. to sort the numbers asap: task body BubbleBC is begin loop State.BubbleBC; end loop; end BubbleBC; -- Tasks that keep calling Bubble.. to sort the numbers asap: task body BubbleCD is begin loop State.BubbleCD; end loop; end BubbleCD; end Bubble;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with CSS.Core.Styles; with CSS.Core.Vectors; with CSS.Core.Values; with CSS.Core.Properties; with CSS.Core.Medias; package CSS.Core.Sheets is type CSSStylesheet is new CSS.Core.StyleSheet with record Rules : CSS.Core.Vectors.Vector; Values : CSS.Core.Values.Repository_Type; end record; type CSSStylesheet_Access is access all CSSStylesheet'Class; -- Create a CSS rule. function Create_Rule (Document : in CSSStyleSheet) return Styles.CSSStyleRule_Access; -- Create a CSS font-face rule. function Create_Rule (Document : in CSSStyleSheet) return Styles.CSSFontfaceRule_Access; -- Create a CSS media rule. function Create_Rule (Document : in CSSStyleSheet) return Medias.CSSMediaRule_Access; -- Append the CSS rule to the document. procedure Append (Document : in out CSSStylesheet; Rule : in Styles.CSSStyleRule_Access; Line : in Natural; Column : in Natural); -- Append the media rule to the document. procedure Append (Document : in out CSSStylesheet; Rule : in Medias.CSSMediaRule_Access; Line : in Natural; Column : in Natural); -- Append the font-face rule to the document. procedure Append (Document : in out CSSStylesheet; Rule : in Styles.CSSFontfaceRule_Access; Line : in Natural; Column : in Natural); -- Append the CSS rule to the media. procedure Append (Document : in out CSSStylesheet; Media : in Medias.CSSMediaRule_Access; Rule : in Styles.CSSStyleRule_Access; Line : in Natural; Column : in Natural); -- Iterate over the properties of each CSS rule. The <tt>Process</tt> procedure -- is called with the CSS rule and the property as parameter. procedure Iterate_Properties (Document : in CSSStylesheet; Process : not null access procedure (Rule : in Styles.CSSStyleRule'Class; Property : in Properties.CSSProperty)); end CSS.Core.Sheets;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Util.Strings; with AWA.Events.Action_Method; package body AWA.Mail.Beans is package Send_Mail_Binding is new AWA.Events.Action_Method.Bind (Bean => Mail_Bean, Method => Send_Mail, Name => "send"); Mail_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Send_Mail_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Mail_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "template" then return Util.Beans.Objects.To_Object (From.Template); else declare Pos : constant Util.Beans.Objects.Maps.Cursor := From.Props.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_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Mail_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "template" then From.Template := Util.Beans.Objects.To_Unbounded_String (Value); elsif Util.Strings.Starts_With (Name, "request.") then From.Params.Include (Name (Name'First + 8 .. Name'Last), Value); else From.Props.Include (Name, Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Mail_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Mail_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Format and send the mail. -- ------------------------------ procedure Send_Mail (Bean : in out Mail_Bean; Event : in AWA.Events.Module_Event'Class) is use Ada.Strings.Unbounded; begin Bean.Module.Send_Mail (To_String (Bean.Template), Bean.Props, Bean.Params, Event); end Send_Mail; -- ------------------------------ -- Create the mail bean instance. -- ------------------------------ function Create_Mail_Bean (Module : in AWA.Mail.Modules.Mail_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Mail_Bean_Access := new Mail_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Mail_Bean; end AWA.Mail.Beans;
{ "source": "starcoderdata", "programming_language": "ada" }
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- * Boston, MA 02111-1307, USA. -- type GstAppBuffer; --subtype GstAppBuffer is u_GstAppBuffer; -- gst/app/gstappbuffer.h:38 type GstAppBufferClass; --subtype GstAppBufferClass is u_GstAppBufferClass; -- gst/app/gstappbuffer.h:39 type GstAppBufferFinalizeFunc is access procedure (arg1 : System.Address); pragma Convention (C, GstAppBufferFinalizeFunc); -- gst/app/gstappbuffer.h:40 type GstAppBuffer is record buffer : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/app/gstappbuffer.h:44 finalize : GstAppBufferFinalizeFunc; -- gst/app/gstappbuffer.h:47 priv : System.Address; -- gst/app/gstappbuffer.h:48 end record; pragma Convention (C_Pass_By_Copy, GstAppBuffer); -- gst/app/gstappbuffer.h:42 --< private > type GstAppBufferClass is record buffer_class : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBufferClass; -- gst/app/gstappbuffer.h:53 end record; pragma Convention (C_Pass_By_Copy, GstAppBufferClass); -- gst/app/gstappbuffer.h:51 function gst_app_buffer_get_type return GLIB.GType; -- gst/app/gstappbuffer.h:56 pragma Import (C, gst_app_buffer_get_type, "gst_app_buffer_get_type"); function gst_app_buffer_new (data : System.Address; length : int; finalize : GstAppBufferFinalizeFunc; priv : System.Address) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/app/gstappbuffer.h:58 pragma Import (C, gst_app_buffer_new, "gst_app_buffer_new"); end GStreamer.GST_Low_Level.gstreamer_0_10_gst_app_gstappbuffer_h;
{ "source": "starcoderdata", "programming_language": "ada" }
with Linted.Errors; with Linted.KOs; with Linted.Update; with Linted.Triggers; package Linted.Update_Reader is pragma Elaborate_Body; type Event is record Data : Update.Packet; Err : Errors.Error := 0; end record; type Future is limited private with Preelaborable_Initialization; function Is_Live (F : Future) return Boolean; procedure Read (Object : KOs.KO; Signaller : Triggers.Signaller; F : out Future) with Post => Is_Live (F); procedure Read_Wait (F : in out Future; E : out Event) with Pre => Is_Live (F), Post => not Is_Live (F); procedure Read_Poll (F : in out Future; E : out Event; Init : out Boolean) with Pre => Is_Live (F), Post => (if Init then not Is_Live (F) else Is_Live (F)); private Max_Nodes : constant := 2; type Future is range 0 .. Max_Nodes + 1 with Default_Value => 0; end Linted.Update_Reader;
{ "source": "starcoderdata", "programming_language": "ada" }
-- { dg-do run } with Init9; use Init9; with Ada.Numerics; use Ada.Numerics; with Text_IO; use Text_IO; with Dump; procedure P9 is Local_R1 : R1; Local_R2 : R2; begin Put ("My_R1 :"); Dump (My_R1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_R1 : 18 2d 44 54 fb 21 09 40.*\n" } Put ("My_R2 :"); Dump (My_R2'Address, R2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_R2 : 40 09 21 fb 54 44 2d 18.*\n" } Local_R1 := My_R1; Put ("Local_R1 :"); Dump (Local_R1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R1 : 18 2d 44 54 fb 21 09 40.*\n" } Local_R2 := My_R2; Put ("Local_R2 :"); Dump (Local_R2'Address, R2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R2 : 40 09 21 fb 54 44 2d 18.*\n" } Local_R1.F := Pi; Put ("Local_R1 :"); Dump (Local_R1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R1 : 18 2d 44 54 fb 21 09 40.*\n" } Local_R2.F := Pi; Put ("Local_R2 :"); Dump (Local_R2'Address, R2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R2 : 40 09 21 fb 54 44 2d 18.*\n" } Local_R1.F := Local_R2.F; Put ("Local_R1 :"); Dump (Local_R1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R1 : 18 2d 44 54 fb 21 09 40.*\n" } Local_R2.F := Local_R1.F; Put ("Local_R2 :"); Dump (Local_R2'Address, R2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_R2 : 40 09 21 fb 54 44 2d 18.*\n" } end;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with umingw_h; package ctype_h is -- unsupported macro: isascii __isascii -- unsupported macro: toascii __toascii -- unsupported macro: iscsymf __iscsymf -- unsupported macro: iscsym __iscsym -- skipped func _isctype -- skipped func _isctype_l function isalpha (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:102 pragma Import (C, isalpha, "isalpha"); -- skipped func _isalpha_l function isupper (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:104 pragma Import (C, isupper, "isupper"); -- skipped func _isupper_l function islower (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:106 pragma Import (C, islower, "islower"); -- skipped func _islower_l function isdigit (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:108 pragma Import (C, isdigit, "isdigit"); -- skipped func _isdigit_l function isxdigit (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:110 pragma Import (C, isxdigit, "isxdigit"); -- skipped func _isxdigit_l function isspace (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:112 pragma Import (C, isspace, "isspace"); -- skipped func _isspace_l function ispunct (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:114 pragma Import (C, ispunct, "ispunct"); -- skipped func _ispunct_l function isalnum (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:116 pragma Import (C, isalnum, "isalnum"); -- skipped func _isalnum_l function isprint (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:118 pragma Import (C, isprint, "isprint"); -- skipped func _isprint_l function isgraph (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:120 pragma Import (C, isgraph, "isgraph"); -- skipped func _isgraph_l function iscntrl (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:122 pragma Import (C, iscntrl, "iscntrl"); -- skipped func _iscntrl_l function toupper (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:124 pragma Import (C, toupper, "toupper"); function tolower (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:125 pragma Import (C, tolower, "tolower"); -- skipped func _tolower -- skipped func _tolower_l -- skipped func _toupper -- skipped func _toupper_l function isblank (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:136 pragma Import (C, isblank, "isblank"); function iswalpha (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:143 pragma Import (C, iswalpha, "iswalpha"); -- skipped func _iswalpha_l function iswupper (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:145 pragma Import (C, iswupper, "iswupper"); -- skipped func _iswupper_l function iswlower (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:147 pragma Import (C, iswlower, "iswlower"); -- skipped func _iswlower_l function iswdigit (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:149 pragma Import (C, iswdigit, "iswdigit"); -- skipped func _iswdigit_l function iswxdigit (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:151 pragma Import (C, iswxdigit, "iswxdigit"); -- skipped func _iswxdigit_l function iswspace (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:153 pragma Import (C, iswspace, "iswspace"); -- skipped func _iswspace_l function iswpunct (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:155 pragma Import (C, iswpunct, "iswpunct"); -- skipped func _iswpunct_l function iswalnum (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:157 pragma Import (C, iswalnum, "iswalnum"); -- skipped func _iswalnum_l function iswprint (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:159 pragma Import (C, iswprint, "iswprint"); -- skipped func _iswprint_l function iswgraph (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:161 pragma Import (C, iswgraph, "iswgraph"); -- skipped func _iswgraph_l function iswcntrl (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:163 pragma Import (C, iswcntrl, "iswcntrl"); -- skipped func _iswcntrl_l function iswascii (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:165 pragma Import (C, iswascii, "iswascii"); function isleadbyte (u_C : int) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:166 pragma Import (C, isleadbyte, "isleadbyte"); -- skipped func _isleadbyte_l function towupper (u_C : umingw_h.wint_t) return umingw_h.wint_t; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:168 pragma Import (C, towupper, "towupper"); -- skipped func _towupper_l function towlower (u_C : umingw_h.wint_t) return umingw_h.wint_t; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:170 pragma Import (C, towlower, "towlower"); -- skipped func _towlower_l function iswctype (u_C : umingw_h.wint_t; u_Type : umingw_h.wctype_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:172 pragma Import (C, iswctype, "iswctype"); -- skipped func _iswctype_l -- skipped func _iswcsymf_l -- skipped func _iswcsym_l function is_wctype (u_C : umingw_h.wint_t; u_Type : umingw_h.wctype_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:178 pragma Import (C, is_wctype, "is_wctype"); function iswblank (u_C : umingw_h.wint_t) return int; -- c:\home\ochem\install\bin\../lib/gcc/i686-pc-mingw32/4.7.3/../../../../i686-pc-mingw32/include/ctype.h:181 pragma Import (C, iswblank, "iswblank"); end ctype_h;
{ "source": "starcoderdata", "programming_language": "ada" }
with AUnit.Assertions; with AUnit.Test_Caller; with Orka.SIMD.AVX.Doubles.Math; package body Test_SIMD_AVX_Math is use Orka; use Orka.SIMD.AVX.Doubles; use Orka.SIMD.AVX.Doubles.Math; use AUnit.Assertions; package Caller is new AUnit.Test_Caller (Test); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "(SIMD - AVX - Math) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Test Max function", Test_Max'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Min function", Test_Min'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Round_Nearest_Integer function", Test_Nearest_Integer'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Floor function", Test_Floor'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Ceil function", Test_Ceil'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Round_Truncate function", Test_Truncate'Access)); return Test_Suite'Access; end Suite; procedure Test_Max (Object : in out Test) is Left : constant m256d := (0.0, 1.0, -2.0, 1.0); Right : constant m256d := (0.0, 0.0, 1.0, 2.0); Expected : constant m256d := (0.0, 1.0, 1.0, 2.0); Result : constant m256d := Max (Left, Right); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Max; procedure Test_Min (Object : in out Test) is Left : constant m256d := (0.0, 1.0, -2.0, 1.0); Right : constant m256d := (0.0, 0.0, 1.0, 2.0); Expected : constant m256d := (0.0, 0.0, -2.0, 1.0); Result : constant m256d := Min (Left, Right); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Min; procedure Test_Nearest_Integer (Object : in out Test) is Elements : constant m256d := (-1.5, 0.6, -0.4, 1.9); Expected : constant m256d := (-2.0, 1.0, 0.0, 2.0); Result : constant m256d := Round_Nearest_Integer (Elements); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Nearest_Integer; procedure Test_Floor (Object : in out Test) is Elements : constant m256d := (-1.5, 0.6, -0.4, 1.9); Expected : constant m256d := (-2.0, 0.0, -1.0, 1.0); Result : constant m256d := Floor (Elements); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Floor; procedure Test_Ceil (Object : in out Test) is Elements : constant m256d := (-1.5, 0.2, -0.4, 1.9); Expected : constant m256d := (-1.0, 1.0, 0.0, 2.0); Result : constant m256d := Ceil (Elements); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Ceil; procedure Test_Truncate (Object : in out Test) is Elements : constant m256d := (-1.5, 0.2, -0.4, 1.9); Expected : constant m256d := (-1.0, 0.0, 0.0, 1.0); Result : constant m256d := Round_Truncate (Elements); begin for I in Index_Homogeneous loop Assert (Expected (I) = Result (I), "Unexpected Double at " & Index_Homogeneous'Image (I)); end loop; end Test_Truncate; end Test_SIMD_AVX_Math;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream from the buffer created for an output stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class) is begin Free_Buffer (Stream.Buffer); Stream.Buffer := From.Buffer; From.Buffer := null; Stream.Input := null; Stream.Read_Pos := 1; Stream.Write_Pos := From.Write_Pos + 1; Stream.Last := From.Last; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; Free_Buffer (Stream.Buffer); end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Output_Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Pos := 1; Avail := Stream.Last - Pos + 1; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data than the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; end Flush; -- ------------------------------ -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Write_Pos > 1 then Into (Into'First .. Into'First + Stream.Write_Pos - 1) := Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1); Stream.Write_Pos := 1; Last := Into'First + Stream.Write_Pos - 1; else Last := Into'First - 1; end if; end Flush; -- ------------------------------ -- Flush the buffer stream to the unbounded string. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Strings.Unbounded.Set_Unbounded_String (Into, ""); if Stream.Write_Pos > 1 then for I in 1 .. Stream.Write_Pos - 1 loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I))); end loop; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Value := Stream.Buffer (Stream.Read_Pos); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character) is use Interfaces; Val : Ada.Streams.Stream_Element; Result : Unsigned_32; begin Stream.Read (Val); -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx if Val <= 16#7F# then Char := Wide_Wide_Character'Val (Val); -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx elsif Val <= 16#DF# then Result := Shift_Left (Unsigned_32 (Val and 16#1F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx elsif Val <= 16#EF# then Result := Shift_Left (Unsigned_32 (Val and 16#0F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else Result := Shift_Left (Unsigned_32 (Val and 16#07#), 18); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); end if; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Pos : Stream_Element_Offset; Avail : Stream_Element_Offset; C : Wide_Wide_Character; begin loop Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; Stream.Read (C); Ada.Strings.Wide_Wide_Unbounded.Append (Into, C); end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Input_Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with STM32F4.RCC; use STM32F4.RCC; with Ada.Real_Time; use Ada.Real_Time; package body STM32F4.I2C is subtype I2C_SR1_Flag is I2C_Status_Flag range Start_Bit .. SMB_Alert; subtype I2C_SR2_Flag is I2C_Status_Flag range Master_Slave_Mode .. Dual_Flag; SR1_Flag_Pos : constant array (I2C_SR1_Flag) of Natural := (0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15); SR2_Flag_Pos : constant array (I2C_SR2_Flag) of Natural := (0, 1, 2, 4, 5, 6, 7); --------------- -- Configure -- --------------- procedure Configure (Port : in out I2C_Port; Clock_Speed : Word; Mode : I2C_Device_Mode; Duty_Cycle : I2C_Duty_Cycle; Own_Address : Half_Word; Ack : I2C_Acknowledgement; Ack_Address : I2C_Acknowledge_Address) is CR2, CR1 : Half_Word; CCR : Half_Word := 0; PCLK1 : constant Word := System_Clock_Frequencies.PCLK1; Freq_Range : constant Half_Word := Half_Word (PCLK1 / 1_000_000); begin -- Load CR2 and clear FREQ CR2 := Port.CR2 and (not CR2_FREQ); Port.CR2 := CR2 or Freq_Range; Set_State (Port, Disabled); if Clock_Speed <= 100_000 then CCR := Half_Word (PCLK1 / (Clock_Speed * 2)); if CCR < 4 then CCR := 4; end if; Port.TRISE := Freq_Range + 1; else -- Fast mode if Duty_Cycle = DutyCycle_2 then CCR := Half_Word (PCLK1 / (Clock_Speed * 3)); else CCR := Half_Word (PCLK1 / (Clock_Speed * 25)); CCR := CCR or DutyCycle_16_9'Enum_Rep; end if; if (CCR and CCR_CCR) = 0 then CCR := 1; end if; CCR := CCR or CCR_FS; Port.TRISE := (Freq_Range * 300) / 1000 + 1; end if; Port.CCR := CCR; Set_State (Port, Enabled); CR1 := Port.CR1; CR1 := CR1 and CR1_Clear_Mask; CR1 := CR1 or Mode'Enum_Rep or Ack'Enum_Rep; Port.CR1 := CR1; Port.OAR1 := Ack_Address'Enum_Rep or Own_Address'Enum_Rep; end Configure; --------------- -- Set_State -- --------------- procedure Set_State (Port : in out I2C_Port; State : I2C_State) is begin if State = Enabled then Port.CR1 := Port.CR1 or CR1_PE; else Port.CR1 := Port.CR1 and (not CR1_PE); end if; end Set_State; ------------------ -- Port_Enabled -- ------------------ function Port_Enabled (Port : I2C_Port) return Boolean is begin return (Port.CR1 and CR1_PE) /= 0; end Port_Enabled; -------------------- -- Generate_Start -- -------------------- procedure Generate_Start (Port : in out I2C_Port; State : I2C_State) is begin if State = Enabled then Port.CR1 := Port.CR1 or CR1_START; else Port.CR1 := Port.CR1 and (not CR1_START); end if; end Generate_Start; ------------------- -- Generate_Stop -- ------------------- procedure Generate_Stop (Port : in out I2C_Port; State : I2C_State) is begin if State = Enabled then Port.CR1 := Port.CR1 or CR1_STOP; else Port.CR1 := Port.CR1 and (not CR1_STOP); end if; end Generate_Stop; -------------------- -- Send_7Bit_Addr -- -------------------- procedure Send_7Bit_Address (Port : in out I2C_Port; Address : Byte; Direction : I2C_Direction) is Destination : Half_Word := Half_Word (Address); begin if Direction = Receiver then Destination := Destination or I2C_OAR1_ADD0; else Destination := Destination and (not I2C_OAR1_ADD0); end if; Port.DR := Destination; end Send_7Bit_Address; -------------- -- Get_Flag -- -------------- function Status (Port : I2C_Port; Flag : I2C_Status_Flag) return Boolean is begin if Flag in I2C_SR1_Flag then return (Port.SR1 and (2**SR1_Flag_Pos (Flag))) /= 0; else return (Port.SR2 and (2**SR2_Flag_Pos (Flag))) /= 0; end if; end Status; ---------------- -- Clear_Flag -- ---------------- procedure Clear_Status (Port : in out I2C_Port; Target : Clearable_I2C_Status_Flag) is begin -- note that only a subset of the status flags can be cleared Port.SR1 := not (2 ** SR1_Flag_Pos (Target)); -- we do not logically AND status bits end Clear_Status; ------------------------------- -- Clear_Address_Sent_Status -- ------------------------------- procedure Clear_Address_Sent_Status (Port : in out I2C_Port) is Temp : Half_Word with Volatile; ADDR_Mask : constant Half_Word := 2 ** SR1_Flag_Pos (Address_Sent); STOP_Mask : constant Half_Word := 2 ** SR1_Flag_Pos (Stop_Detection); begin -- To clear the ADDR flag we have to read SR2 after reading SR1. -- However, per the RM, section 27.6.7, page 850, we should only read -- SR2 if the Address_Sent flag is set in SR1, or if the Stop_Detection -- flag is cleared, because the Address_Sent flag could be set in -- the middle of reading SR1 and SR2 but will be cleared by the -- read sequence nonetheless. Temp := Port.SR1; if ((Temp and ADDR_Mask) = 1) or ((Temp and STOP_Mask) = 0) then Temp := Port.SR2; end if; end Clear_Address_Sent_Status; --------------------------------- -- Clear_Stop_Detection_Status -- --------------------------------- procedure Clear_Stop_Detection_Status (Port : in out I2C_Port) is Temp : Half_Word with Volatile, Unreferenced; begin Temp := Port.SR1; Port.CR1 := Port.CR1 or CR1_PE; end Clear_Stop_Detection_Status; ------------------- -- Wait_For_Flag -- ------------------- procedure Wait_For_State (Port : I2C_Port; Queried : I2C_Status_Flag; State : I2C_State; Time_Out : Natural := 1_000_000) is Expected : constant Boolean := State = Enabled; Deadline : constant Time := Clock + Milliseconds (Time_Out); begin while Status (Port, Queried) /= Expected loop if Clock >= Deadline then raise I2C_Timeout; end if; end loop; end Wait_For_State; --------------- -- Send_Data -- --------------- procedure Send_Data (Port : in out I2C_Port; Data : Byte) is begin Port.DR := Half_Word (Data); end Send_Data; --------------- -- Read_Data -- --------------- function Read_Data (Port : I2C_Port) return Byte is begin return Byte (Port.DR); end Read_Data; -------------------- -- Set_Ack_Config -- -------------------- procedure Set_Ack_Config (Port : in out I2C_Port; State : I2C_State) is begin if State = Enabled then Port.CR1 := Port.CR1 or CR1_ACK; else Port.CR1 := Port.CR1 and (not CR1_ACK); end if; end Set_Ack_Config; --------------------- -- Set_Nack_Config -- --------------------- procedure Set_Nack_Config (Port : in out I2C_Port; Pos : I2C_Nack_Position) is begin if Pos = Next then Port.CR1 := Port.CR1 or CR1_POS; else Port.CR1 := Port.CR1 and (not CR1_POS); end if; end Set_Nack_Config; ----------- -- Start -- ----------- procedure Start (Port : in out I2C_Port; Address : Byte; Direction : I2C_Direction) is begin Generate_Start (Port, Enabled); Wait_For_State (Port, Start_Bit, Enabled); Set_Ack_Config (Port, Enabled); Send_7Bit_Address (Port, Address, Direction); while not Status (Port, Address_Sent) loop if Status (Port, Ack_Failure) then raise Program_Error; end if; end loop; Clear_Address_Sent_Status (Port); end Start; -------------- -- Read_Ack -- -------------- function Read_Ack (Port : in out I2C_Port) return Byte is begin Set_Ack_Config (Port, Enabled); Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled); return Read_Data (Port); end Read_Ack; --------------- -- Read_Nack -- --------------- function Read_Nack (Port : in out I2C_Port) return Byte is begin Set_Ack_Config (Port, Disabled); Generate_Stop (Port, Enabled); Wait_For_State (Port, Rx_Data_Register_Not_Empty, Enabled); return Read_Data (Port); end Read_Nack; ----------- -- Write -- ----------- procedure Write (Port : in out I2C_Port; Data : Byte) is begin Wait_For_State (Port, Tx_Data_Register_Empty, Enabled); Send_Data (Port, Data); while not Status (Port, Tx_Data_Register_Empty) or else not Status (Port, Byte_Transfer_Finished) loop null; end loop; end Write; ---------- -- Stop -- ---------- procedure Stop (Port : in out I2C_Port) is begin Generate_Stop (Port, Enabled); end Stop; ---------------------- -- Enable_Interrupt -- ---------------------- procedure Enable_Interrupt (Port : in out I2C_Port; Source : I2C_Interrupt) is begin Port.CR2 := Port.CR2 or Source'Enum_Rep; end Enable_Interrupt; ----------------------- -- Disable_Interrupt -- ----------------------- procedure Disable_Interrupt (Port : in out I2C_Port; Source : I2C_Interrupt) is begin Port.CR2 := Port.CR2 and not Source'Enum_Rep; end Disable_Interrupt; ------------- -- Enabled -- ------------- function Enabled (Port : in out I2C_Port; Source : I2C_Interrupt) return Boolean is begin return (Port.CR2 and Source'Enum_Rep) = Source'Enum_Rep; end Enabled; end STM32F4.I2C;
{ "source": "starcoderdata", "programming_language": "ada" }
-- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Events -- -- Mapping to the underlying event handling system. -- -- WARNING!!!! -- I wanted to experiment with the event system and possibly hide all this and create an abstraction in another -- task so as to separate out the events from the main window. This could change. I really don't know yet. -------------------------------------------------------------------------------------------------------------------- with Ada.Unchecked_Conversion; package SDL.Events is pragma Preelaborate; type Event_Types is mod 2 ** 32 with Convention => C; type Button_State is (Released, Pressed) with Convention => C; for Button_State use (Released => 0, Pressed => 1); ----------------------------------------------------------------------------------------------------------------- -- Event types. ----------------------------------------------------------------------------------------------------------------- -- Handled via 'First attribute. First_Event : constant Event_Types := 16#0000_0000#; -- Application events. Quit : constant Event_Types := 16#0000_0100#; -- Mobile events. App_Terminating : constant Event_Types := Quit + 1; App_Low_Memory : constant Event_Types := Quit + 2; App_Will_Enter_Background : constant Event_Types := Quit + 3; App_Did_Enter_Background : constant Event_Types := Quit + 4; App_Will_Enter_Foreground : constant Event_Types := Quit + 5; App_Did_Enter_Foreground : constant Event_Types := Quit + 6; -- Clipboard events. Clipboard_Update : constant Event_Types := 16#0000_0900#; -- TODO: Audio hot plug events for 2.0.4 -- User events. User : constant Event_Types := 16#0000_8000#; Last_Event : constant Event_Types := 16#0000_FFFF#; type Padding_8 is mod 2 ** 8 with Convention => C, Size => 8; type Padding_16 is mod 2 ** 16 with Convention => C, Size => 16; type Time_Stamps is mod 2 ** 32 with Convention => C; type Common_Events is record Event_Type : Event_Types; Time_Stamp : Time_Stamps; end record with Convention => C; ----------------------------------------------------------------------------------------------------------------- -- TODO: Touch finger events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: Multi gesture events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: Dollar gesture events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: Drop events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: User events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: System window manager events ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- TODO: Audio events - 2.0.4 ----------------------------------------------------------------------------------------------------------------- private for Common_Events use record Event_Type at 0 * SDL.Word range 0 .. 31; Time_Stamp at 1 * SDL.Word range 0 .. 31; end record; -- for Text_Editing_Events use -- record -- Event_Type at 0 * SDL.Word range 0 .. 31; -- Time_Stamp at 1 * SDL.Word range 0 .. 31; -- -- ID at 2 * SDL.Word range 0 .. 31; -- State at 3 * SDL.Word range 0 .. 7; -- Repeat at 3 * SDL.Word range 8 .. 15; -- Padding_2 at 3 * SDL.Word range 16 .. 23; -- Padding_3 at 3 * SDL.Word range 24 .. 31; -- end record; end SDL.Events;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- with Program.Elements.Type_Definitions; with Program.Lexical_Elements; with Program.Elements.Definitions; package Program.Elements.Record_Types is pragma Pure (Program.Elements.Record_Types); type Record_Type is limited interface and Program.Elements.Type_Definitions.Type_Definition; type Record_Type_Access is access all Record_Type'Class with Storage_Size => 0; not overriding function Record_Definition (Self : Record_Type) return not null Program.Elements.Definitions.Definition_Access is abstract; type Record_Type_Text is limited interface; type Record_Type_Text_Access is access all Record_Type_Text'Class with Storage_Size => 0; not overriding function To_Record_Type_Text (Self : in out Record_Type) return Record_Type_Text_Access is abstract; not overriding function Abstract_Token (Self : Record_Type_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Tagged_Token (Self : Record_Type_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Limited_Token (Self : Record_Type_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Record_Types;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ pragma Compiler_Unit_Warning; with Ada.Unchecked_Deallocation; with System.OS_Lib; use System.OS_Lib; package body System.Response_File is type File_Rec; type File_Ptr is access File_Rec; type File_Rec is record Name : String_Access; Next : File_Ptr; Prev : File_Ptr; end record; -- To build a stack of response file names procedure Free is new Ada.Unchecked_Deallocation (File_Rec, File_Ptr); type Argument_List_Access is access Argument_List; procedure Free is new Ada.Unchecked_Deallocation (Argument_List, Argument_List_Access); -- Free only the allocated Argument_List, not allocated String components -------------------- -- Arguments_From -- -------------------- function Arguments_From (Response_File_Name : String; Recursive : Boolean := False; Ignore_Non_Existing_Files : Boolean := False) return Argument_List is First_File : File_Ptr := null; Last_File : File_Ptr := null; -- The stack of response files Arguments : Argument_List_Access := new Argument_List (1 .. 4); Last_Arg : Natural := 0; procedure Add_Argument (Arg : String); -- Add argument Arg to argument list Arguments, increasing Arguments -- if necessary. procedure Recurse (File_Name : String); -- Get the arguments from the file and call itself recursively if one of -- the arguments starts with character '@'. ------------------ -- Add_Argument -- ------------------ procedure Add_Argument (Arg : String) is begin if Last_Arg = Arguments'Last then declare New_Arguments : constant Argument_List_Access := new Argument_List (1 .. Arguments'Last * 2); begin New_Arguments (Arguments'Range) := Arguments.all; Arguments.all := (others => null); Free (Arguments); Arguments := New_Arguments; end; end if; Last_Arg := Last_Arg + 1; Arguments (Last_Arg) := new String'(Arg); end Add_Argument; ------------- -- Recurse -- ------------- procedure Recurse (File_Name : String) is -- Open the response file. If not found, fail or report a warning, -- depending on the value of Ignore_Non_Existing_Files. FD : constant File_Descriptor := Open_Read (File_Name, Text); Buffer_Size : constant := 1500; Buffer : String (1 .. Buffer_Size); Buffer_Length : Natural; Buffer_Cursor : Natural; End_Of_File_Reached : Boolean; Line : String (1 .. Max_Line_Length + 1); Last : Natural; First_Char : Positive; -- Index of the first character of an argument in Line Last_Char : Natural; -- Index of the last character of an argument in Line In_String : Boolean; -- True when inside a quoted string Arg : Positive; function End_Of_File return Boolean; -- True when the end of the response file has been reached procedure Get_Buffer; -- Read one buffer from the response file procedure Get_Line; -- Get one line from the response file ----------------- -- End_Of_File -- ----------------- function End_Of_File return Boolean is begin return End_Of_File_Reached and then Buffer_Cursor > Buffer_Length; end End_Of_File; ---------------- -- Get_Buffer -- ---------------- procedure Get_Buffer is begin Buffer_Length := Read (FD, Buffer (1)'Address, Buffer'Length); End_Of_File_Reached := Buffer_Length < Buffer'Length; Buffer_Cursor := 1; end Get_Buffer; -------------- -- Get_Line -- -------------- procedure Get_Line is Ch : Character; begin Last := 0; if End_Of_File then return; end if; loop Ch := Buffer (Buffer_Cursor); exit when Ch = ASCII.CR or else Ch = ASCII.LF or else Ch = ASCII.FF; Last := Last + 1; Line (Last) := Ch; if Last = Line'Last then return; end if; Buffer_Cursor := Buffer_Cursor + 1; if Buffer_Cursor > Buffer_Length then Get_Buffer; if End_Of_File then return; end if; end if; end loop; loop Ch := Buffer (Buffer_Cursor); exit when Ch /= ASCII.HT and then Ch /= ASCII.LF and then Ch /= ASCII.FF; Buffer_Cursor := Buffer_Cursor + 1; if Buffer_Cursor > Buffer_Length then Get_Buffer; if End_Of_File then return; end if; end if; end loop; end Get_Line; -- Start of processing for Recurse begin Last_Arg := 0; if FD = Invalid_FD then if Ignore_Non_Existing_Files then return; else raise File_Does_Not_Exist; end if; end if; -- Put the response file name on the stack if First_File = null then First_File := new File_Rec' (Name => new String'(File_Name), Next => null, Prev => null); Last_File := First_File; else declare Current : File_Ptr := First_File; begin loop if Current.Name.all = File_Name then raise Circularity_Detected; end if; Current := Current.Next; exit when Current = null; end loop; Last_File.Next := new File_Rec' (Name => new String'(File_Name), Next => null, Prev => Last_File); Last_File := Last_File.Next; end; end if; End_Of_File_Reached := False; Get_Buffer; -- Read the response file line by line Line_Loop : while not End_Of_File loop Get_Line; if Last = Line'Last then raise Line_Too_Long; end if; First_Char := 1; -- Get each argument on the line Arg_Loop : loop -- First, skip any white space while First_Char <= Last loop exit when Line (First_Char) /= ' ' and then Line (First_Char) /= ASCII.HT; First_Char := First_Char + 1; end loop; exit Arg_Loop when First_Char > Last; Last_Char := First_Char; In_String := False; -- Get the character one by one Character_Loop : while Last_Char <= Last loop -- Inside a string, check only for '"' if In_String then if Line (Last_Char) = '"' then -- Remove the '"' Line (Last_Char .. Last - 1) := Line (Last_Char + 1 .. Last); Last := Last - 1; -- End of string is end of argument if Last_Char > Last or else Line (Last_Char) = ' ' or else Line (Last_Char) = ASCII.HT then In_String := False; Last_Char := Last_Char - 1; exit Character_Loop; else -- If there are two consecutive '"', the quoted -- string is not closed In_String := Line (Last_Char) = '"'; if In_String then Last_Char := Last_Char + 1; end if; end if; else Last_Char := Last_Char + 1; end if; elsif Last_Char = Last then -- An opening '"' at the end of the line is an error if Line (Last) = '"' then raise No_Closing_Quote; else -- The argument ends with the line exit Character_Loop; end if; elsif Line (Last_Char) = '"' then -- Entering a quoted string: remove the '"' In_String := True; Line (Last_Char .. Last - 1) := Line (Last_Char + 1 .. Last); Last := Last - 1; else -- Outside quoted strings, white space ends the argument exit Character_Loop when Line (Last_Char + 1) = ' ' or else Line (Last_Char + 1) = ASCII.HT; Last_Char := Last_Char + 1; end if; end loop Character_Loop; -- It is an error to not close a quoted string before the end -- of the line. if In_String then raise No_Closing_Quote; end if; -- Add the argument to the list declare Arg : String (1 .. Last_Char - First_Char + 1); begin Arg := Line (First_Char .. Last_Char); Add_Argument (Arg); end; -- Next argument, if line is not finished First_Char := Last_Char + 1; end loop Arg_Loop; end loop Line_Loop; Close (FD); -- If Recursive is True, check for any argument starting with '@' if Recursive then Arg := 1; while Arg <= Last_Arg loop if Arguments (Arg)'Length > 0 and then Arguments (Arg) (1) = '@' then -- Ignore argument '@' with no file name if Arguments (Arg)'Length = 1 then Arguments (Arg .. Last_Arg - 1) := Arguments (Arg + 1 .. Last_Arg); Last_Arg := Last_Arg - 1; else -- Save the current arguments and get those in the new -- response file. declare Inc_File_Name : constant String := Arguments (Arg) (2 .. Arguments (Arg)'Last); Current_Arguments : constant Argument_List := Arguments (1 .. Last_Arg); begin Recurse (Inc_File_Name); -- Insert the new arguments where the new response -- file was imported. declare New_Arguments : constant Argument_List := Arguments (1 .. Last_Arg); New_Last_Arg : constant Positive := Current_Arguments'Length + New_Arguments'Length - 1; begin -- Grow Arguments if it is not large enough if Arguments'Last < New_Last_Arg then Last_Arg := Arguments'Last; Free (Arguments); while Last_Arg < New_Last_Arg loop Last_Arg := Last_Arg * 2; end loop; Arguments := new Argument_List (1 .. Last_Arg); end if; Last_Arg := New_Last_Arg; Arguments (1 .. Last_Arg) := Current_Arguments (1 .. Arg - 1) & New_Arguments & Current_Arguments (Arg + 1 .. Current_Arguments'Last); Arg := Arg + New_Arguments'Length; end; end; end if; else Arg := Arg + 1; end if; end loop; end if; -- Remove the response file name from the stack if First_File = Last_File then System.Strings.Free (First_File.Name); Free (First_File); First_File := null; Last_File := null; else System.Strings.Free (Last_File.Name); Last_File := Last_File.Prev; Free (Last_File.Next); end if; exception when others => Close (FD); raise; end Recurse; -- Start of processing for Arguments_From begin -- The job is done by procedure Recurse Recurse (Response_File_Name); -- Free Arguments before returning the result declare Result : constant Argument_List := Arguments (1 .. Last_Arg); begin Free (Arguments); return Result; end; exception when others => -- When an exception occurs, deallocate everything Free (Arguments); while First_File /= null loop Last_File := First_File.Next; System.Strings.Free (First_File.Name); Free (First_File); First_File := Last_File; end loop; raise; end Arguments_From; end System.Response_File;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- This code is to be used for tutorial purposes only. -- You may not redistribute this code in any form without my express permission. --------------------------------------------------------------------------------- --with Ada.Real_Time; with Interfaces.C; with Unchecked_Conversion; with Text_Io; use Text_Io; with GL; with GLU; with GL.EXT; with Ada.Strings.Maps; with Ada.Strings.Fixed; with System; with Geometrical_Methods; with GLUtils; use type GL.GLbitfield; use type GL.EXT.glLockArraysEXTPtr; use type GL.EXT.glUnlockArraysEXTPtr; package body Example is package GM renames Geometrical_Methods; procedure PrintGLInfo is begin Put_Line("GL Vendor => " & GLUtils.GL_Vendor); Put_Line("GL Version => " & GLUtils.GL_Version); Put_Line("GL Renderer => " & GLUtils.GL_Renderer); Put_Line("GL Extensions => " & GLUtils.GL_Extensions); New_Line; Put_Line("GLU Version => " & GLUtils.GLU_Version); Put_Line("GLU Extensions => " & GLUtils.GLU_Extensions); New_Line; end PrintGLInfo; procedure PrintUsage is begin Put_Line("Keys"); Put_Line("Cursor keys => Rotate"); Put_Line("Page Down/Up => Zoom in/out"); Put_Line("F1 => Toggle Fullscreen"); Put_Line("Escape => Quit"); Put_Line("N & M/N & M + Shift => Move Dot in X"); Put_Line("O & K/O & K + Shift => Move Dot in Y"); Put_Line("D/D + Shift => Move Plane"); Put_Line("R => Reset"); end PrintUsage; procedure CalculateFPS is CurrentTime : Float := Float(SDL.Timer.GetTicks) / 1000.0; ElapsedTime : Float := CurrentTime - LastElapsedTime; FramesPerSecond : String(1 .. 10); MillisecondPerFrame : String(1 .. 10); package Float_InOut is new Text_IO.Float_IO(Float); use Float_InOut; begin FrameCount := FrameCount + 1; if ElapsedTime > 1.0 then FPS := Float(FrameCount) / ElapsedTime; Put(FramesPerSecond, FPS, Aft => 2, Exp => 0); Put(MillisecondPerFrame, 1000.0 / FPS, Aft => 2, Exp => 0); SDL.Video.WM_Set_Caption_Title(Example.GetTitle & " " & FramesPerSecond & " fps " & MillisecondPerFrame & " ms/frame"); LastElapsedTime := CurrentTime; FrameCount := 0; end if; end CalculateFPS; function Initialise return Boolean is begin GL.glClearColor(0.0, 0.0, 0.0, 0.0); -- Black Background. GL.glClearDepth(1.0); -- Depth Buffer Setup. GL.glDepthFunc(GL.GL_LEQUAL); -- The Type Of Depth Testing (Less Or Equal). GL.glEnable(GL.GL_DEPTH_TEST); -- Enable Depth Testing. GL.glShadeModel(GL.GL_SMOOTH); -- Select Smooth Shading. GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); -- Set Perspective Calculations To Most Accurate. -- GL.glFrontFace(GL.GL_CCW); -- GL.glCullFace(GL.GL_NONE); -- GL.glEnable(GL.GL_CULL_FACE); return True; end Initialise; procedure Uninitialise is begin null; end Uninitialise; -- procedure Update(Ticks : in Integer) is procedure Update is Result : Interfaces.C.int; begin -- Check the modifiers if Keys(SDL.Keysym.K_LSHIFT) = True or Keys(SDL.Keysym.K_RSHIFT) = True then ShiftPressed := True; else ShiftPressed := False; end if; if Keys(SDL.Keysym.K_LCTRL) = True or Keys(SDL.Keysym.K_RCTRL) = True then CtrlPressed := True; else CtrlPressed := False; end if; if Keys(SDL.Keysym.K_F1) = True then Result := SDL.Video.WM_ToggleFullScreen(ScreenSurface); end if; -- Move the camera. if Keys(SDL.Keysym.K_LEFT) = True then CameraYSpeed := CameraYSpeed - 0.1; end if; if Keys(SDL.Keysym.K_RIGHT) = True then CameraYSpeed := CameraYSpeed + 0.1; end if; if Keys(SDL.Keysym.K_UP) = True then CameraXSpeed := CameraXSpeed - 0.1; end if; if Keys(SDL.Keysym.K_DOWN) = True then CameraXSpeed := CameraXSpeed + 0.1; end if; if Keys(SDL.Keysym.K_PAGEUP) = True then Zoom := Zoom + 0.1; end if; if Keys(SDL.Keysym.K_PAGEDOWN) = True then Zoom := Zoom - 0.1; end if; if Keys(SDL.Keysym.K_ESCAPE) = True then AppQuit := True; end if; if Keys(SDL.Keysym.K_R) = True then TestLine.StartPoint := Vector3.Object'(-1.0, 0.0, 0.0); TestLine.EndPoint := Vector3.Object'(1.0, 0.0, 0.0); TestPlane.Distance := 0.0; end if; -- Move the dot. if Keys(SDL.Keysym.K_N) = True and NPressed = False then NPressed := True; if ShiftPressed = True then TestLine.StartPoint.X := TestLine.StartPoint.X - LineSmallDelta; TestLine.EndPoint.X := TestLine.EndPoint.X - LineSmallDelta; else TestLine.StartPoint.X := TestLine.StartPoint.X - LineDelta; TestLine.EndPoint.X := TestLine.EndPoint.X - LineDelta; end if; end if; if Keys(SDL.Keysym.K_N) = False then NPressed := False; end if; if Keys(SDL.Keysym.K_M) = True and MPressed = False then MPressed := True; if ShiftPressed = True then TestLine.StartPoint.X := TestLine.StartPoint.X + LineSmallDelta; TestLine.EndPoint.X := TestLine.EndPoint.X + LineSmallDelta; else TestLine.StartPoint.X := TestLine.StartPoint.X + LineDelta; TestLine.EndPoint.X := TestLine.EndPoint.X + LineDelta; end if; end if; if Keys(SDL.Keysym.K_M) = False then MPressed := False; end if; if Keys(SDL.Keysym.K_O) = True and OPressed = False then OPressed := True; if ShiftPressed = True then TestLine.StartPoint.Y := TestLine.StartPoint.Y + LineSmallDelta; TestLine.EndPoint.Y := TestLine.EndPoint.Y + LineSmallDelta; else TestLine.StartPoint.Y := TestLine.StartPoint.Y + LineDelta; TestLine.EndPoint.Y := TestLine.EndPoint.Y + LineDelta; end if; end if; if Keys(SDL.Keysym.K_O) = False then OPressed := False; end if; if Keys(SDL.Keysym.K_K) = True and KPressed = False then KPressed := True; if ShiftPressed = True then TestLine.StartPoint.Y := TestLine.StartPoint.Y - LineSmallDelta; TestLine.EndPoint.Y := TestLine.EndPoint.Y - LineSmallDelta; else TestLine.StartPoint.Y := TestLine.StartPoint.Y - LineDelta; TestLine.EndPoint.Y := TestLine.EndPoint.Y - LineDelta; end if; end if; if Keys(SDL.Keysym.K_K) = False then KPressed := False; end if; -- Move the plane along the normal (Distance). if Keys(SDL.Keysym.K_D) = True and DPressed = False then DPressed := True; if ShiftPressed = True then TestPlane.Distance := TestPlane.Distance - 0.5; else TestPlane.Distance := TestPlane.Distance + 0.5; end if; end if; if Keys(SDL.Keysym.K_D) = False then DPressed := False; end if; end Update; procedure Draw is Collision : Boolean := False; begin GL.glClear(GL.GL_COLOR_BUFFER_BIT or GL.GL_DEPTH_BUFFER_BIT); -- Clear Screen And Depth Buffer. GL.glLoadIdentity; -- Reset The Modelview Matrix. -- Move the camera aound the scene. GL.glTranslatef(0.0, 0.0, Zoom); GL.glRotatef(CameraXSpeed, 1.0, 0.0, 0.0); -- Rotate On The Y-Axis By angle. GL.glRotatef(CameraYSpeed, 0.0, 1.0, 0.0); -- Rotate On The Y-Axis By angle. Collision := GM.CollisionDetected(TestPlane, TestLine); -- Draw plane. GL.glBegin(GL.GL_QUADS); if Collision = True then GL.glColor3f(1.0, 0.0, 0.0); else GL.glColor3f(0.0, 0.2, 0.5); end if; --GL.glColor3f(0.0, 0.2, 0.5); GL.glVertex3f(GL.GLfloat(TestPlane.Distance), -1.0, -1.0); GL.glVertex3f(GL.GLfloat(TestPlane.Distance), 1.0, -1.0); GL.glVertex3f(GL.GLfloat(TestPlane.Distance), 1.0, 1.0); GL.glVertex3f(GL.GLfloat(TestPlane.Distance), -1.0, 1.0); GL.glNormal3f(GL.GLfloat(TestPlane.Normal.X), GL.GLfloat(TestPlane.Normal.Y), GL.GLfloat(TestPlane.Normal.Z)); gl.glEnd; GL.glBegin(GL.GL_LINES); if Collision = True then GL.glColor3f(1.0, 1.0, 0.0); else GL.glColor3f(1.0, 1.0, 1.0); end if; GL.glVertex3f(GL.GLfloat(TestLine.StartPoint.X), GL.GLfloat(TestLine.StartPoint.Y), GL.GLfloat(TestLine.StartPoint.Z)); GL.glVertex3f(GL.GLfloat(TestLine.EndPoint.X), GL.GLfloat(TestLine.EndPoint.Y), GL.GLfloat(TestLine.EndPoint.Z)); GL.glEnd; GL.glFlush; -- Flush The GL Rendering Pipeline. -- Text_IO.Put_Line("Dot: " & Vector3.Output(Dot)); end Draw; function GetTitle return String is begin return Title; end GetTitle; function GetWidth return Integer is begin return Width; end GetWidth; function GetHeight return Integer is begin return Height; end GetHeight; function GetBitsPerPixel return Integer is begin return BitsPerPixel; end GetBitsPerPixel; procedure SetLastTickCount(Ticks : in Integer) is begin LastTickCount := Ticks; end SetLastTickCount; procedure SetSurface(Surface : in SDL.Video.Surface_Ptr) is begin ScreenSurface := Surface; end SetSurface; function GetSurface return SDL.Video.Surface_Ptr is begin return ScreenSurface; end GetSurface; procedure SetKey(Key : in SDL.Keysym.Key; Down : in Boolean) is begin Keys(Key) := Down; end SetKey; procedure SetActive(Active : in Boolean) is begin AppActive := Active; end SetActive; function IsActive return Boolean is begin return AppActive; end IsActive; procedure SetQuit(Quit : in Boolean) is begin AppQuit := Quit; end SetQuit; function Quit return Boolean is begin return AppQuit; end Quit; end Example;
{ "source": "starcoderdata", "programming_language": "ada" }
with GL.Objects.Textures; with GL.Types.Colors; package GL.Objects.Samplers is pragma Preelaborate; type Sampler is new GL_Object with private; type Sampler_Array is array (Positive range <>) of Sampler; procedure Bind (Object : Sampler; Unit : Textures.Texture_Unit); procedure Bind (Objects : Sampler_Array; First_Unit : Textures.Texture_Unit); overriding procedure Initialize_Id (Object : in out Sampler); overriding procedure Delete_Id (Object : in out Sampler); overriding function Identifier (Object : Sampler) return Types.Debug.Identifier is (Types.Debug.Sampler); ----------------------------------------------------------------------------- -- Sampler Parameters -- ----------------------------------------------------------------------------- use GL.Objects.Textures; procedure Set_Minifying_Filter (Object : Sampler; Filter : Minifying_Function); procedure Set_Magnifying_Filter (Object : Sampler; Filter : Magnifying_Function); procedure Set_Minimum_LoD (Object : Sampler; Level : Double); procedure Set_Maximum_LoD (Object : Sampler; Level : Double); procedure Set_LoD_Bias (Object : Sampler; Level : Double); -- Adjust the selection of a mipmap image. A positive level will -- cause larger mipmaps to be selected. A too large bias can -- result in visual aliasing, but if the bias is small enough it -- can make the texture look a bit sharper. procedure Set_Seamless_Filtering (Object : Sampler; Enable : Boolean); -- Enable seamless cubemap filtering -- -- Texture must be a Texture_Cube_Map or Texture_Cube_Map_Array. -- -- Note: this procedure requires the ARB_seamless_cubemap_per_texture -- extension. If this extension is not available, you can enable seamless -- filtering globally via GL.Toggles. procedure Set_Max_Anisotropy (Object : Sampler; Degree : Double) with Pre => Degree >= 1.0; -- Set the maximum amount of anisotropy filtering to reduce the blurring -- of textures (caused by mipmap filtering) that are viewed at an -- oblique angle. -- -- For best results, combine the use of anisotropy filtering with -- a Linear_Mipmap_Linear minification filter and a Linear maxification -- filter. ----------------------------------------------------------------------------- function Minifying_Filter (Object : Sampler) return Minifying_Function; -- Return the minification function (default is Nearest_Mipmap_Linear) function Magnifying_Filter (Object : Sampler) return Magnifying_Function; -- Return the magnification function (default is Linear) function Minimum_LoD (Object : Sampler) return Double; -- Return the minimum LOD (default is -1000) function Maximum_LoD (Object : Sampler) return Double; -- Return the maximum LOD (default is 1000) function LoD_Bias (Object : Sampler) return Double; -- Return the LOD bias for the selection of a mipmap (default is 0.0) function Seamless_Filtering (Object : Sampler) return Boolean; -- Return whether seamless filtering is enabled for cube map -- textures (default is False) function Max_Anisotropy (Object : Sampler) return Double with Post => Max_Anisotropy'Result >= 1.0; ----------------------------------------------------------------------------- procedure Set_X_Wrapping (Object : Sampler; Mode : Wrapping_Mode); procedure Set_Y_Wrapping (Object : Sampler; Mode : Wrapping_Mode); procedure Set_Z_Wrapping (Object : Sampler; Mode : Wrapping_Mode); function X_Wrapping (Object : Sampler) return Wrapping_Mode; -- Return the wrapping mode for the X direction (default is Repeat) function Y_Wrapping (Object : Sampler) return Wrapping_Mode; -- Return the wrapping mode for the Y direction (default is Repeat) function Z_Wrapping (Object : Sampler) return Wrapping_Mode; -- Return the wrapping mode for the Z direction (default is Repeat) ----------------------------------------------------------------------------- procedure Set_Border_Color (Object : Sampler; Color : Colors.Border_Color); procedure Set_Compare_X_To_Texture (Object : Sampler; Enabled : Boolean); procedure Set_Compare_Function (Object : Sampler; Func : Compare_Function); function Border_Color (Object : Sampler) return Colors.Border_Color; function Compare_X_To_Texture_Enabled (Object : Sampler) return Boolean; -- Return whether to enable comparing (default is False) function Current_Compare_Function (Object : Sampler) return Compare_Function; -- Return the comparison function (default is LEqual) private type Sampler is new GL_Object with null record; end GL.Objects.Samplers;
{ "source": "starcoderdata", "programming_language": "ada" }
package body System.Storage_Pools.Subpools.Unbounded is type Unbounded_Subpool_Access is access all Unbounded_Subpool; -- implementation overriding function Create_Subpool ( Pool : in out Unbounded_Pool_With_Subpools) return not null Subpool_Handle is Subpool : constant not null Unbounded_Subpool_Access := new Unbounded_Subpool; begin Unbounded_Allocators.Initialize (Subpool.Allocator); declare Result : constant not null Subpool_Handle := Subpool_Handle (Subpool); begin Set_Pool_Of_Subpool (Result, Pool); return Result; end; end Create_Subpool; overriding procedure Allocate_From_Subpool ( Pool : in out Unbounded_Pool_With_Subpools; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count; Subpool : not null Subpool_Handle) is pragma Unreferenced (Pool); begin Unbounded_Allocators.Allocate ( Unbounded_Subpool_Access (Subpool).Allocator, Storage_Address => Storage_Address, Size_In_Storage_Elements => Size_In_Storage_Elements, Alignment => Alignment); end Allocate_From_Subpool; overriding procedure Deallocate_Subpool ( Pool : in out Unbounded_Pool_With_Subpools; Subpool : in out Subpool_Handle) is pragma Unreferenced (Pool); begin Unbounded_Allocators.Finalize ( Unbounded_Subpool_Access (Subpool).Allocator); end Deallocate_Subpool; overriding procedure Deallocate ( Pool : in out Unbounded_Pool_With_Subpools; Storage_Address : Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count) is pragma Unreferenced (Pool); begin Unbounded_Allocators.Deallocate ( Unbounded_Allocators.Allocator_Of (Storage_Address), Storage_Address => Storage_Address, Size_In_Storage_Elements => Size_In_Storage_Elements, Alignment => Alignment); end Deallocate; end System.Storage_Pools.Subpools.Unbounded;
{ "source": "starcoderdata", "programming_language": "ada" }
with openGL.Primitive.indexed; package body openGL.Model.line.colored is --------- --- Forge -- function to_line_Model (Color : in openGL.Color; End_1, End_2 : in Vector_3 := Origin_3D) return Item is Self : Item; begin Self.Color := +Color; Self.Vertices (1).Site := End_1; Self.Vertices (2).Site := End_2; Self.set_Bounds; return Self; end to_line_Model; function new_line_Model (Color : in openGL.Color; End_1, End_2 : in Vector_3 := Origin_3D) return View is begin return new Item' (to_line_Model (Color, End_1, End_2)); end new_line_Model; -------------- --- Attributes -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views is pragma unreferenced (Textures, Fonts); use Geometry.colored; indices_Count : constant long_Index_t := 2; the_Indices : aliased Indices := (1 .. indices_Count => <>); the_Primitive : Primitive.indexed.view; begin if Self.Geometry = null then Self.Geometry := Geometry.colored.new_Geometry; end if; set_Sites: begin Self.Vertices (1).Color := (Primary => Self.Color, Alpha => opaque_Value); Self.Vertices (2).Color := (Primary => Self.Color, Alpha => opaque_Value); end set_Sites; the_Indices := (1, 2); Self.Geometry.is_Transparent (False); Self.Geometry.Vertices_are (Self.Vertices); the_Primitive := Primitive.indexed.new_Primitive (Primitive.Lines, the_Indices); Self.Geometry.add (Primitive.view (the_Primitive)); return (1 => Self.Geometry); end to_GL_Geometries; function Site (Self : in Item; for_End : in end_Id) return Vector_3 is begin return Self.Vertices (for_End).Site; end Site; procedure Site_is (Self : in out Item; Now : in Vector_3; for_End : in end_Id) is use Geometry.colored; begin Self.Vertices (for_End).Site := Now; Self.Geometry.Vertices_are (Self.Vertices); Self.set_Bounds; end Site_is; end openGL.Model.line.colored;
{ "source": "starcoderdata", "programming_language": "ada" }
package body UxAS.Comms.Transport.Receiver is ------------------------------ -- Add_Subscription_Address -- ------------------------------ procedure Add_Subscription_Address (This : in out Transport_Receiver_Base; Address : String; Result : out Boolean) is Target : constant Subscription_Address := Instance (Subscription_Address_Max_Length, Address); use Subscription_Addresses; -- a hashed map C : Cursor; begin C := Find (This.Subscriptions, Target); if C = No_Element then -- didn't find it Insert (This.Subscriptions, Target); Add_Subscription_Address_To_Socket (Transport_Receiver_Base'Class (This), Address, Result); -- dispatching end if; end Add_Subscription_Address; --------------------------------- -- Remove_Subscription_Address -- --------------------------------- procedure Remove_Subscription_Address (This : in out Transport_Receiver_Base; Address : String; Result : out Boolean) is Target : constant Subscription_Address := Instance (Subscription_Address_Max_Length, Address); use Subscription_Addresses; -- a hashed map C : Cursor; begin C := Find (This.Subscriptions, Target); if C /= No_Element then -- found it Delete (This.Subscriptions, C); Remove_Subscription_Address_From_Socket (Transport_Receiver_Base'Class (This), Address, Result); -- dispatching end if; end Remove_Subscription_Address; --------------------------------------- -- Remove_All_Subscription_Addresses -- --------------------------------------- procedure Remove_All_Subscription_Addresses (This : in out Transport_Receiver_Base; Result : out Boolean) is begin for Target of This.Subscriptions loop Remove_Subscription_Address_From_Socket (Transport_Receiver_Base'Class (This), Value (Target), Result); -- dispatching end loop; Subscription_Addresses.Clear (This.Subscriptions); Result := Subscription_Addresses.Is_Empty (This.Subscriptions); end Remove_All_Subscription_Addresses; end UxAS.Comms.Transport.Receiver;
{ "source": "starcoderdata", "programming_language": "ada" }
-- The Village of Vampire by YT, このソースコードはNYSLです with Ada.Strings.Unbounded; procedure Vampire.R3.User_Page ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Form : in Forms.Root_Form_Type'Class; Template : in String; Summaries : in Tabula.Villages.Lists.Summary_Maps.Map; User_Id : in String; User_Password : in String; User_Info : in Users.User_Info) is use type Ada.Strings.Unbounded.Unbounded_String; use type Tabula.Villages.Village_State; -- ユーザーの参加状況 Joined : aliased Ada.Strings.Unbounded.Unbounded_String; Created : aliased Ada.Strings.Unbounded.Unbounded_String; begin for I in Summaries.Iterate loop declare V : Tabula.Villages.Lists.Village_Summary renames Summaries.Constant_Reference (I); begin if V.State < Tabula.Villages.Epilogue then for J in V.People.Iterate loop if V.People.Constant_Reference (J) = User_Id then if not Joined.Is_Null then Ada.Strings.Unbounded.Append(Joined, "、"); end if; Ada.Strings.Unbounded.Append(Joined, V.Name); end if; end loop; if V.By = User_Id then Created := V.Name; end if; end if; end; end loop; declare procedure Handle ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Web.Producers.Template) is begin if Tag = "action_page" then Forms.Write_Attribute_Name (Output, "action"); Forms.Write_Link ( Output, Form, Current_Directory => ".", Resource => Forms.Self, Parameters => Form.Parameters_To_User_Page ( User_Id => User_Id, User_Password => <PASSWORD>)); elsif Tag = "userpanel" then Handle_User_Panel ( Output, Contents, Form, User_Id => User_Id, User_Password => <PASSWORD>); elsif Tag = "id" then Forms.Write_In_HTML (Output, Form, User_Id); elsif Tag = "joined" then if not Joined.Is_Null then declare procedure Handle ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Web.Producers.Template) is begin if Tag = "activevillage" then Forms.Write_In_HTML (Output, Form, Joined.Constant_Reference); else Raise_Unknown_Tag (Tag); end if; end Handle; begin Web.Producers.Produce(Output, Contents, Handler => Handle'Access); end; end if; elsif Tag = "nojoined" then if Joined.Is_Null then Web.Producers.Produce(Output, Contents); end if; elsif Tag = "created" then if not Created.Is_Null then declare procedure Handle ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Web.Producers.Template) is begin if Tag = "createdvillage" then Forms.Write_In_HTML (Output, Form, Created.Constant_Reference); else Raise_Unknown_Tag (Tag); end if; end Handle; begin Web.Producers.Produce(Output, Contents, Handler => Handle'Access); end; end if; elsif Tag = "creatable" then if Joined.Is_Null and then Created.Is_Null then Web.Producers.Produce(Output, Contents, Handler => Handle'Access); -- rec end if; elsif Tag = "href_index" then Forms.Write_Attribute_Name (Output, "href"); Forms.Write_Link ( Output, Form, Current_Directory => ".", Resource => Forms.Self, Parameters => Form.Parameters_To_Index_Page ( User_Id => User_Id, User_Password => <PASSWORD>)); else Raise_Unknown_Tag (Tag); end if; end Handle; begin Web.Producers.Produce (Output, Read (Template), Handler => Handle'Access); end; end Vampire.R3.User_Page;
{ "source": "starcoderdata", "programming_language": "ada" }
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, 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 AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 14 package Asis.Iterator ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ package Asis.Iterator is ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Asis.Iterator encapsulates the generic procedure Traverse_Element which -- allows an ASIS application to perform an iterative traversal of a -- logical syntax tree. It requires the use of two generic procedures, -- Pre_Operation, which identifies processing for the traversal, and -- Post_Operation, which identifies processing after the traversal. -- The State_Information allows processing state to be passed during the -- iteration of Traverse_Element. -- -- Package Asis.Iterator is established as a child package to highlight the -- iteration capability and to facilitate the translation of ASIS to IDL. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- 14.1 procedure Traverse_Element ------------------------------------------------------------------------------ generic type State_Information is limited private; with procedure Pre_Operation (Element : Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is <>; with procedure Post_Operation (Element : Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is <>; procedure Traverse_Element (Element : Asis.Element; Control : in out Traverse_Control; State : in out State_Information); ------------------------------------------------------------------------------ -- Element - Specifies the initial element in the traversal -- Control - Specifies what next to do with the traversal -- State_Information - Specifies other information for the traversal -- -- Traverses the element and all its component elements, if any. -- Component elements are all elements that can be obtained by a combination -- of the ASIS structural queries appropriate for the given element. -- -- If an element has one or more component elements, each is called a child -- element. An element's parent element is its Enclosing_Element. Children -- with the same parent are sibling elements. The type Traverse_Control uses -- the terms children and siblings to control the traverse. -- -- For each element, the formal procedure Pre_Operation is called when first -- visiting the element. Each of that element's children are then visited -- and finally the formal procedure Post_Operation is called for the element. -- -- The order of Element traversal is in terms of the textual representation of -- the Elements. Elements are traversed in left-to-right and top-to-bottom -- order. -- -- Traversal of Implicit Elements: -- -- Implicit elements are not traversed by default. However, they may be -- explicitly queried and then passed to the traversal instance. Implicit -- elements include implicit predefined operator declarations, implicit -- inherited subprogram declarations, implicit expanded generic specifications -- and bodies, default expressions supplied to procedure, function, and entry -- calls, etc. -- -- Applications that wish to traverse these implicit Elements shall query for -- them at the appropriate places in a traversal and then recursively call -- their instantiation of the traversal generic. (Implicit elements provided -- by ASIS do not cover all possible Ada implicit constructs. For example, -- implicit initializations for variables of an access type are not provided -- by ASIS.) -- -- Traversal of Association lists: -- -- Argument and association lists for procedure calls, function calls, entry -- calls, generic instantiations, and aggregates are traversed in their -- unnormalized forms, as if the Normalized parameter was False for those -- queries. Implementations that always normalize certain associations may -- return Is_Normalized associations. See the Implementation Permissions -- for the queries Discriminant_Associations, Generic_Actual_Part, -- Call_Statement_Parameters, Record_Component_Associations, or -- Function_Call_Parameters. -- -- Applications that wish to explicitly traverse normalized associations can -- do so by querying the appropriate locations in order to obtain the -- normalized list. The list can then be traversed by recursively calling -- the traverse instance. Once that sub-traversal is finished, the Control -- parameter can be set to Abandon_Children to skip processing of the -- unnormalized argument list. -- -- Traversal can be controlled with the Control parameter. -- -- A call to an instance of Traverse_Element will not result in calls to -- Pre_Operation or Post_Operation unless Control is set to Continue. -- -- The subprograms matching Pre_Operation and Post_Operation can set -- their Control parameter to affect the traverse: -- -- Continue -- Continues the normal depth-first traversal. -- -- Abandon_Children -- Prevents traversal of the current element's -- -- children. -- -- If set in a Pre_Operation, traversal picks up -- -- with the next sibling element of the current -- -- element. -- -- If set in a Post_Operation, this is the -- -- same as Continue, all children will already -- -- have been traversed. Traversal picks up with -- -- the Post_Operation of the parent. -- -- Abandon_Siblings -- Prevents traversal of the current element's -- -- children and remaining siblings. -- -- If set in a Pre_Operation, this abandons the -- -- associated Post_Operation for the current -- -- element. Traversal picks up with the -- -- Post_Operation of the parent. -- -- If set in a Post_Operation, traversal picks -- -- up with the Post_Operation of the parent. -- -- Terminate_Immediately -- Does exactly that. -- -- Raises ASIS_Inappropriate_Element if the element is a Nil_Element ------------------------------------------------------------------------------ end Asis.Iterator;
{ "source": "starcoderdata", "programming_language": "ada" }
--------------------------------------------------------------------------- package body Chebychev_Quadrature is Pii : constant := 3.14159_26535_89793_23846_26433_83279_50288_41971_694; Gauss_Root : Gauss_Values := (others => 0.0); Gauss_Weight : Gauss_Values := (others => 0.0); -- Arrays initialized after the "begin" below. --------------------------- -- Construct_Gauss_Roots -- --------------------------- procedure Construct_Gauss_Roots is Factor : constant Real := Pii / Real (Gauss_Index'Last); begin for i in Gauss_Index loop Gauss_Root (i) := -Cos (Factor * (Real (i) - 0.5)); end loop; end Construct_Gauss_Roots; ----------------------------- -- Construct_Gauss_Weights -- ----------------------------- procedure Construct_Gauss_Weights is Factor : constant Real := Pii / Real (Gauss_Index'Last); begin for i in Gauss_Index loop Gauss_Weight (i) := 0.5 * Factor * Abs (Sin (Factor * (Real (i) - 0.5))); end loop; end Construct_Gauss_Weights; ---------------------- -- Find_Gauss_Nodes -- ---------------------- procedure Find_Gauss_Nodes (X_Starting : in Real; X_Final : in Real; X_gauss : out Gauss_Values) is Half_Delta_X : constant Real := (X_Final - X_Starting) * 0.5; X_Center : constant Real := X_Starting + Half_Delta_X; begin for i in Gauss_Index loop X_gauss(i) := X_Center + Gauss_Root(i) * Half_Delta_X; end loop; end Find_Gauss_Nodes; ------------------ -- Get_Integral -- ------------------ procedure Get_Integral (F_val : in Function_Values; X_Starting : in Real; X_Final : in Real; Area : out Real) is Sum : Real; Delta_X : constant Real := (X_Final - X_Starting); begin Area := 0.0; Sum := 0.0; for i in Gauss_Index loop Sum := Sum + Gauss_Weight (i) * F_val (i); end loop; Area := Sum * Delta_X; end Get_Integral; begin Construct_Gauss_Roots; Construct_Gauss_Weights; end Chebychev_Quadrature;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Float_Text_IO; with Ada.IO_Exceptions; package body SI_Units.Binary is function Prefix (S : in Prefixes) return String is (case S is when None => "", when kibi => "Ki", when mebi => "Mi", when gibi => "Gi", when tebi => "Ti", when pebi => "Pi", when exbi => "Ei", when zebi => "Zi", when yobi => "Yi") with Inline => True; function Image (Value : in Item; Aft : in Ada.Text_IO.Field := Default_Aft) return String is Result : String (1 .. 5 + Ada.Text_IO.Field'Max (1, Aft)); -- "1023.[...]"; Temp : Float := Float (Value); Scale : Prefixes := None; begin if Unit /= No_Unit then -- No prefix matching if no unit name is given. while Temp >= Magnitude loop Scale := Prefixes'Succ (Scale); Temp := Temp / Magnitude; end loop; end if; Try_Numeric_To_String_Conversion : begin Ada.Float_Text_IO.Put (To => Result, Item => Temp, Aft => Aft, Exp => 0); exception when Ada.IO_Exceptions.Layout_Error => -- Value was larger than 9999 Yi<units> and didn't fit into the -- string. -- Reset Scale and return "inf"inity instead. Result (1 .. 4) := "+inf"; Result (5 .. Result'Last) := (others => ' '); end Try_Numeric_To_String_Conversion; return Trim (Result & (if Unit = No_Unit then "" else No_Break_Space & Prefix (Scale) & Unit)); end Image; end SI_Units.Binary;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with Ada.Finalization; generic type Element_Type is private; package Ahven.SList is type List is new Ada.Finalization.Controlled with private; type Cursor is private; subtype Count_Type is Natural; Invalid_Cursor : exception; List_Full : exception; -- Thrown when the size of the list exceeds Count_Type'Last. Empty_List : constant List; procedure Append (Target : in out List; Node_Data : Element_Type); -- Append an element at the end of the list. -- -- Raises List_Full if the list has already Count_Type'Last items. procedure Clear (Target : in out List); -- Remove all elements from the list. function First (Target : List) return Cursor; -- Return a cursor to the first element of the list. function Next (Position : Cursor) return Cursor; -- Move the cursor to point to the next element on the list. function Data (Position : Cursor) return Element_Type; -- Return element pointed by the cursor. function Is_Valid (Position : Cursor) return Boolean; -- Tell the validity of the cursor. The cursor -- will become invalid when you iterate it over -- the last item. function Length (Target : List) return Count_Type; -- Return the length of the list. generic with procedure Action (T : in out Element_Type) is <>; procedure For_Each (Target : List); -- A generic procedure for walk through every item -- in the list and call Action procedure for them. private type Node; type Node_Access is access Node; type Cursor is new Node_Access; procedure Remove (Ptr : Node_Access); -- A procedure to release memory pointed by Ptr. type Node is record Next : Node_Access := null; Data : Element_Type; end record; type List is new Ada.Finalization.Controlled with record First : Node_Access := null; Last : Node_Access := null; Size : Count_Type := 0; end record; procedure Initialize (Target : in out List); procedure Finalize (Target : in out List); procedure Adjust (Target : in out List); Empty_List : constant List := (Ada.Finalization.Controlled with First => null, Last => null, Size => 0); end Ahven.SList;
{ "source": "starcoderdata", "programming_language": "ada" }
with GESTE; with GESTE.Sprite; with GESTE.Tile_Bank; with Ada.Text_IO; with Console_Char_Screen; with Ada.Exceptions; procedure Layer_Priority is use type GESTE.Pix_Point; package Console_Screen is new Console_Char_Screen (Width => 9, Height => 9, Buffer_Size => 256, Init_Char => ' '); Palette : aliased constant GESTE.Palette_Type := ('1', '2', '3', '4'); Background : Character := '-'; Tiles : aliased constant GESTE.Tile_Array := (1 => ((1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1)), 2 => ((2, 2, 2, 2, 2), (2, 2, 2, 2, 2), (2, 2, 2, 2, 2), (2, 2, 2, 2, 2), (2, 2, 2, 2, 2)), 3 => ((3, 3, 3, 3, 3), (3, 3, 3, 3, 3), (3, 3, 3, 3, 3), (3, 3, 3, 3, 3), (3, 3, 3, 3, 3)), 4 => ((4, 4, 4, 4, 4), (4, 4, 4, 4, 4), (4, 4, 4, 4, 4), (4, 4, 4, 4, 4), (4, 4, 4, 4, 4)) ); Bank : aliased GESTE.Tile_Bank.Instance (Tiles'Unrestricted_Access, GESTE.No_Collisions, Palette'Unrestricted_Access); Sprite_1 : aliased GESTE.Sprite.Instance (Bank => Bank'Unrestricted_Access, Init_Frame => 1); Sprite_2 : aliased GESTE.Sprite.Instance (Bank => Bank'Unrestricted_Access, Init_Frame => 2); Sprite_3 : aliased GESTE.Sprite.Instance (Bank => Bank'Unrestricted_Access, Init_Frame => 3); Sprite_4 : aliased GESTE.Sprite.Instance (Bank => Bank'Unrestricted_Access, Init_Frame => 4); procedure Update is begin GESTE.Render_Window (Window => Console_Screen.Screen_Rect, Background => Background, Buffer => Console_Screen.Buffer, Push_Pixels => Console_Screen.Push_Pixels'Unrestricted_Access, Set_Drawing_Area => Console_Screen.Set_Drawing_Area'Unrestricted_Access); Console_Screen.Print; end Update; begin Console_Screen.Verbose; Sprite_3.Move ((3, 3)); GESTE.Add (Sprite_3'Unrestricted_Access, 3); -- Insert head on empty list Sprite_4.Move ((4, 4)); GESTE.Add (Sprite_4'Unrestricted_Access, 4); -- Insert head on non empty list Sprite_1.Move ((1, 1)); GESTE.Add (Sprite_1'Unrestricted_Access, 1); -- Insert tail Sprite_2.Move ((2, 2)); GESTE.Add (Sprite_2'Unrestricted_Access, 2); -- Insert mid Update; GESTE.Remove (Sprite_2'Unrestricted_Access); -- Remove mid Update; GESTE.Remove (Sprite_1'Unrestricted_Access); -- Remove tail Update; GESTE.Remove (Sprite_4'Unrestricted_Access); -- Remove head on non empty list Update; GESTE.Remove (Sprite_3'Unrestricted_Access); -- Remove head on empty list Update; declare begin -- Remove a layer not in the list GESTE.Remove (Sprite_3'Unrestricted_Access); exception when E : Program_Error => Ada.Text_IO.Put_Line ("Exception:" & Ada.Exceptions.Exception_Message (E)); end; end Layer_Priority;
{ "source": "starcoderdata", "programming_language": "ada" }
Gtk.About_Dialog.Set_Program_Name (V_Dialog, "BingAda"); Gtk.About_Dialog.Set_Version (V_Dialog, "0.9 Beta"); if Gtk.About_Dialog.Run (V_Dialog) /= Gtk.Dialog.Gtk_Response_Close then -- Dialog was destroyed by user, not closed through Close button null; end if; Gtk.About_Dialog.Destroy (V_Dialog); --GTK.ABOUT_DIALOG.ON_ACTIVATE_LINK (V_DIALOG,P_ON_ACTIVATE_LINK'Access); --GTK.ABOUT_DIALOG.DESTROY (V_DIALOG); end P_Show_Window; --================================================================== end Q_Bingo_Help;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_Io; use Ada.Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Nt_Console; use Nt_console; with conecta4; use conecta4; procedure imprimir_tablero (Tablero: in T_Tablero) is -- Solo para poder imprimir package P_Celda_IO is new Enumeration_IO(T_Celda); use P_Celda_IO; begin Clear_Screen; new_line; Put_Line(" El estado del tablero es:"); New_Line; -- Imprimimos indicadores para identificar mejor las columnas Set_Foreground(Light_Green); put(" "); for Indicador in 1..Max_Columnas loop put(Indicador, width=>3); put(" "); end loop; Set_Foreground; new_line; -- Imprimimos el estado actual del tablero for Fila in 1..Max_Filas loop put(" "); for Columna in 1..Max_Columnas loop if (Tablero(Fila,Columna)=Azul) then Set_Foreground(Light_Blue); elsif (Tablero(Fila,Columna)=Rojo) then Set_Foreground(Light_Red); end if; Put(Tablero(Fila,Columna)); Put(" "); Set_Foreground; end loop; New_Line; end loop; end imprimir_tablero;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------ -- AMD Élan(tm) SC 520 embedded microprocessor -- -- MMCR -> CPU Registers -- -- -- -- reference: Register Set Manual, Chapter 4 -- ------------------------------------------------------------------------ package Elan520.CPU_Registers is --------------------------------------------------------------------- -- Elan(tm) SC520 Microcontroller Revision Id (REVID) -- -- Memory Mapped, Read only -- -- MMCR Offset 00h -- --------------------------------------------------------------------- --------------------------------------------------------------------- -- sub types for Revision_Id type CPU_Id is range 0 .. 2**8 - 1; type Stepping is range 0 .. 2**4 - 1; -- the only known constant so far, anything else is an unknown -- processor type, check out http://www.amd.com for further types PRODUCT_ID_ELAN_520 : constant CPU_Id := 2#0000_0000#; --------------------------------------------------------------------- -- Revision ID at MMCR offset 16#00# --------------------------------------------------------------------- MMCR_OFFSET_REVISION_ID : constant := 16#00#; REVISION_ID_SIZE : constant := 16; type Revision_Id is record Minor_Step : Stepping; Major_Step : Stepping; Product_Id : CPU_Id; end record; for Revision_Id use record Minor_Step at 0 range 0 .. 3; Major_Step at 0 range 4 .. 7; Product_Id at 0 range 8 .. 15; end record; for Revision_Id'Size use REVISION_ID_SIZE; --------------------------------------------------------------------- -- Am5x86(r) CPU Control (CPUCTL) -- -- Memory-Mapped, Read/Write -- -- MMCR Offset 02h -- --------------------------------------------------------------------- --------------------------------------------------------------------- -- sub types for CPU control register type CPU_Clock_Speed is (MHz_100, MHz_133); for CPU_Clock_Speed use (MHz_100 => 2#01#, MHz_133 => 2#10#); for CPU_Clock_Speed'Size use 2; DEFAULT_CPU_CLOCK_SPEED : constant CPU_Clock_Speed := MHz_100; type Cache_Write_Mode is (Write_Back, Write_Through); for Cache_Write_Mode use (Write_Back => 0, Write_Through => 1); for Cache_Write_Mode'Size use 1; DEFAULT_CACHE_WRITE_MODE : constant Cache_Write_Mode := Write_Through; --------------------------------------------------------------------- -- CPU Control at MMCR offset 16#02# --------------------------------------------------------------------- MMCR_OFFSET_CPU_CONTROL : constant := 16#02#; CPU_CONTROL_SIZE : constant := 8; type CPU_Control is record Cpu_Clk_Spd : CPU_Clock_Speed; Cache_Wr_Mode : Cache_Write_Mode; end record; for CPU_Control use record CPU_Clk_Spd at 0 range 0 .. 1; Cache_Wr_Mode at 0 range 4 .. 4; end record; for CPU_Control'Size use CPU_CONTROL_SIZE; end Elan520.CPU_Registers;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.Calendar; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Permissions; with AWA.Comments.Models; with Util.Log.Loggers; with Jason.Tickets.Beans; with ADO.Sessions; with AWA.Services.Contexts; with ADO.Sessions.Entities; package body Jason.Tickets.Modules is use type ADO.Identifier; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Jason.Tickets.Module"); package Register is new AWA.Modules.Beans (Module => Ticket_Module, Module_Access => Ticket_Module_Access); -- ------------------------------ -- Initialize the tickets module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Ticket_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the tickets module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "Jason.Tickets.Beans.Ticket_Bean", Handler => Jason.Tickets.Beans.Create_Ticket_Bean'Access); Register.Register (Plugin => Plugin, Name => "Jason.Tickets.Beans.Ticket_List_Bean", Handler => Jason.Tickets.Beans.Create_Ticket_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "Jason.Tickets.Beans.Ticket_Status_List_Bean", Handler => Jason.Tickets.Beans.Create_Status_List'Access); Register.Register (Plugin => Plugin, Name => "Jason.Tickets.Beans.Ticket_Type_List_Bean", Handler => Jason.Tickets.Beans.Create_Type_List'Access); Register.Register (Plugin => Plugin, Name => "Jason.Tickets.Beans.Ticket_Report_Bean", Handler => Jason.Tickets.Beans.Create_Ticket_Report_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the tickets module. -- ------------------------------ function Get_Ticket_Module return Ticket_Module_Access is function Get is new AWA.Modules.Get (Ticket_Module, Ticket_Module_Access, NAME); begin return Get; end Get_Ticket_Module; -- ------------------------------ -- Load the ticket. -- ------------------------------ procedure Load_Ticket (Model : in Ticket_Module; Ticket : in out Jason.Tickets.Models.Ticket_Ref'Class; Project : in out Jason.Projects.Models.Project_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier) is DB : ADO.Sessions.Session := Model.Get_Session; Found : Boolean; begin if Id /= ADO.NO_IDENTIFIER then Ticket.Load (DB, Id, Found); if Found then Project.Load (DB, Ticket.Get_Project.Get_Id, Found); end if; else Project.Load (DB, Project.Get_Id, Found); end if; -- Jason.Projects.Models.Project_Ref (Project) := ; -- Ticket.Get_Project.Copy (Projects.Models.Project_Ref (Project)); if Id /= ADO.NO_IDENTIFIER and Found then Tags.Load_Tags (DB, Id); end if; end Load_Ticket; -- ------------------------------ -- Create -- ------------------------------ procedure Create (Model : in Ticket_Module; Entity : in out Jason.Tickets.Models.Ticket_Ref'Class; Project_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); User : constant ADO.Identifier := Ctx.Get_User_Identifier; Project : Jason.Projects.Models.Project_Ref; begin -- Check that the user has the create ticket permission on the given project. AWA.Permissions.Check (Permission => ACL_Create_Tickets.Permission, Entity => Project_Id); Ctx.Start; Project.Load (DB, Project_Id); Project.Set_Last_Ticket (Project.Get_Last_Ticket + 1); Entity.Set_Create_Date (Ada.Calendar.Clock); Entity.Set_Status (Jason.Tickets.Models.OPEN); Entity.Set_Creator (Ctx.Get_User); Entity.Set_Project (Project); Entity.Set_Ident (Project.Get_Last_Ticket); Entity.Save (DB); Project.Save (DB); Ctx.Commit; Log.Info ("Ticket {0} created for user {1}", ADO.Identifier'Image (Entity.Get_Id), ADO.Identifier'Image (User)); end Create; -- ------------------------------ -- Save -- ------------------------------ procedure Save (Model : in Ticket_Module; Entity : in out Jason.Tickets.Models.Ticket_Ref'Class; Comment : in String) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Cmt : AWA.Comments.Models.Comment_Ref; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin -- Check that the user has the update ticket permission on the given ticket. AWA.Permissions.Check (Permission => ACL_Update_Tickets.Permission, Entity => Entity); Ctx.Start; Entity.Set_Update_Date (Now); if Comment'Length > 0 then Cmt.Set_Author (Ctx.Get_User); Cmt.Set_Create_Date (Now); Cmt.Set_Message (Comment); Cmt.Set_Entity_Id (Entity.Get_Id); Cmt.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Models.TICKET_TABLE)); Cmt.Save (DB); end if; Entity.Save (DB); Ctx.Commit; end Save; end Jason.Tickets.Modules;
{ "source": "starcoderdata", "programming_language": "ada" }
with CSS.Parser.Parser_Goto; with CSS.Parser.Parser_Tokens; with CSS.Parser.Parser_Shift_Reduce; with CSS.Parser.Lexer_io; with CSS.Parser.Lexer; with CSS.Parser.Lexer_dfa; with CSS.Core.Selectors; with CSS.Core.Styles; with CSS.Core.Medias; with Ada.Text_IO; package body CSS.Parser.Parser is use Ada; use CSS.Parser.Lexer; use CSS.Core.Selectors; use CSS.Parser.Lexer_dfa; procedure YYParse; procedure yyerror (Message : in String := "syntax error"); Document : CSS.Core.Sheets.CSSStylesheet_Access; Current_Page : CSS.Core.Styles.CSSPageRule_Access; Current_Rule : CSS.Core.Styles.CSSStyleRule_Access; Current_Media : CSS.Core.Medias.CSSMediaRule_Access; procedure yyerror (Message : in String := "syntax error") is begin Error_Count := Error_Count + 1; Error (CSS.Parser.Lexer_Dfa.yylineno, CSS.Parser.Lexer_Dfa.yylinecol, Message); end yyerror; function Parse (Content : in String; Document : in CSS.Core.Sheets.CSSStylesheet_Access) return Integer is begin Error_Count := 0; CSS.Parser.Lexer_Dfa.yylineno := 1; CSS.Parser.Lexer_Dfa.yylinecol := 1; CSS.Parser.Lexer_IO.Open_Input (Content); CSS.Parser.Parser.Document := Document; Current_Rule := null; Current_Media := null; Current_Page := null; YYParse; Current_Rule := null; Current_Media := null; Current_Page := null; CSS.Parser.Parser.Document := null; CSS.Parser.Lexer_IO.Close_Input; Parser_Tokens.yylval := EMPTY; return Error_Count; exception when others => CSS.Parser.Parser.Document := null; CSS.Parser.Lexer_IO.Close_Input; Parser_Tokens.yylval := EMPTY; raise; end Parse; -- Warning: This file is automatically generated by AYACC. -- It is useless to modify it. Change the ".Y" & ".L" files instead. procedure YYParse is -- Rename User Defined Packages to Internal Names. package yy_goto_tables renames CSS.Parser.Parser_Goto; package yy_shift_reduce_tables renames CSS.Parser.Parser_Shift_Reduce; package yy_tokens renames CSS.Parser.Parser_Tokens; use yy_tokens, yy_goto_tables, yy_shift_reduce_tables; procedure yyerrok; procedure yyclearin; procedure handle_error; subtype goto_row is yy_goto_tables.Row; subtype reduce_row is yy_shift_reduce_tables.Row; package yy is -- the size of the value and state stacks -- Affects error 'Stack size exceeded on state_stack' stack_size : constant Natural := 256; -- subtype rule is Natural; subtype parse_state is Natural; -- subtype nonterminal is Integer; -- encryption constants default : constant := -1; first_shift_entry : constant := 0; accept_code : constant := -3001; error_code : constant := -3000; -- stack data used by the parser tos : Natural := 0; value_stack : array (0 .. stack_size) of yy_tokens.YYSType; state_stack : array (0 .. stack_size) of parse_state; -- current input symbol and action the parser is on action : Integer; rule_id : Rule; input_symbol : yy_tokens.Token := Error; -- error recovery flag error_flag : Natural := 0; -- indicates 3 - (number of valid shifts after an error occurs) look_ahead : Boolean := True; index : reduce_row; -- Is Debugging option on or off debug : constant Boolean := False; end yy; procedure shift_debug (state_id : yy.parse_state; lexeme : yy_tokens.Token); procedure reduce_debug (rule_id : Rule; state_id : yy.parse_state); function goto_state (state : yy.parse_state; sym : Nonterminal) return yy.parse_state; function parse_action (state : yy.parse_state; t : yy_tokens.Token) return Integer; pragma Inline (goto_state, parse_action); function goto_state (state : yy.parse_state; sym : Nonterminal) return yy.parse_state is index : goto_row; begin index := Goto_Offset (state); while Goto_Matrix (index).Nonterm /= sym loop index := index + 1; end loop; return Integer (Goto_Matrix (index).Newstate); end goto_state; function parse_action (state : yy.parse_state; t : yy_tokens.Token) return Integer is index : reduce_row; tok_pos : Integer; default : constant Integer := -1; begin tok_pos := yy_tokens.Token'Pos (t); index := Shift_Reduce_Offset (state); while Integer (Shift_Reduce_Matrix (index).T) /= tok_pos and then Integer (Shift_Reduce_Matrix (index).T) /= default loop index := index + 1; end loop; return Integer (Shift_Reduce_Matrix (index).Act); end parse_action; -- error recovery stuff procedure handle_error is temp_action : Integer; begin if yy.error_flag = 3 then -- no shift yet, clobber input. if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Error Recovery Clobbers " & yy_tokens.Token'Image (yy.input_symbol)); end if; if yy.input_symbol = yy_tokens.End_Of_Input then -- don't discard, if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Can't discard END_OF_INPUT, quiting..."); end if; raise yy_tokens.Syntax_Error; end if; yy.look_ahead := True; -- get next token return; -- and try again... end if; if yy.error_flag = 0 then -- brand new error yyerror ("Syntax Error"); end if; yy.error_flag := 3; -- find state on stack where error is a valid shift -- if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Looking for state with error as valid shift"); end if; loop if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Examining State " & yy.parse_state'Image (yy.state_stack (yy.tos))); end if; temp_action := parse_action (yy.state_stack (yy.tos), Error); if temp_action >= yy.first_shift_entry then if yy.tos = yy.stack_size then Text_IO.Put_Line (" -- Ayacc.YYParse: Stack size exceeded on state_stack"); raise yy_tokens.Syntax_Error; end if; yy.tos := yy.tos + 1; yy.state_stack (yy.tos) := temp_action; exit; end if; if yy.tos /= 0 then yy.tos := yy.tos - 1; end if; if yy.tos = 0 then if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Error recovery popped entire stack, aborting..."); end if; raise yy_tokens.Syntax_Error; end if; end loop; if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Shifted error token in state " & yy.parse_state'Image (yy.state_stack (yy.tos))); end if; end handle_error; -- print debugging information for a shift operation procedure shift_debug (state_id : yy.parse_state; lexeme : yy_tokens.Token) is begin Text_IO.Put_Line (" -- Ayacc.YYParse: Shift " & yy.parse_state'Image (state_id) & " on input symbol " & yy_tokens.Token'Image (lexeme)); end shift_debug; -- print debugging information for a reduce operation procedure reduce_debug (rule_id : Rule; state_id : yy.parse_state) is begin Text_IO.Put_Line (" -- Ayacc.YYParse: Reduce by rule " & Rule'Image (rule_id) & " goto state " & yy.parse_state'Image (state_id)); end reduce_debug; -- make the parser believe that 3 valid shifts have occured. -- used for error recovery. procedure yyerrok is begin yy.error_flag := 0; end yyerrok; -- called to clear input symbol that caused an error. procedure yyclearin is begin -- yy.input_symbol := YYLex; yy.look_ahead := True; end yyclearin; begin -- initialize by pushing state 0 and getting the first input symbol yy.state_stack (yy.tos) := 0; loop yy.index := Shift_Reduce_Offset (yy.state_stack (yy.tos)); if Integer (Shift_Reduce_Matrix (yy.index).T) = yy.default then yy.action := Integer (Shift_Reduce_Matrix (yy.index).Act); else if yy.look_ahead then yy.look_ahead := False; yy.input_symbol := YYLex; end if; yy.action := parse_action (yy.state_stack (yy.tos), yy.input_symbol); end if; if yy.action >= yy.first_shift_entry then -- SHIFT if yy.debug then shift_debug (yy.action, yy.input_symbol); end if; -- Enter new state if yy.tos = yy.stack_size then Text_IO.Put_Line (" Stack size exceeded on state_stack"); raise yy_tokens.Syntax_Error; end if; yy.tos := yy.tos + 1; yy.state_stack (yy.tos) := yy.action; yy.value_stack (yy.tos) := YYLVal; if yy.error_flag > 0 then -- indicate a valid shift yy.error_flag := yy.error_flag - 1; end if; -- Advance lookahead yy.look_ahead := True; elsif yy.action = yy.error_code then -- ERROR handle_error; elsif yy.action = yy.accept_code then if yy.debug then Text_IO.Put_Line (" -- Ayacc.YYParse: Accepting Grammar..."); end if; exit; else -- Reduce Action -- Convert action into a rule yy.rule_id := Rule (-1 * yy.action); -- Execute User Action -- user_action(yy.rule_id); case yy.rule_id is pragma Style_Checks (Off); when 4 => -- #line 78 Error (yy.value_stack (yy.tos).Line, yy.value_stack (yy.tos).Column, "Invalid CSS selector component"); when 32 => -- #line 158 Current_Media := null; when 33 => -- #line 161 Current_Media := null; when 38 => -- #line 176 Current_Rule := null; Error (yylval.Line, yylval.Column, "Media condition error"); when 39 => -- #line 181 Current_Rule := null; when 40 => -- #line 186 Current_Rule := null; when 41 => -- #line 189 Error (yy.value_stack (yy.tos-2).Line, yy.value_stack (yy.tos-2).Column, "Invalid media selection after " & To_String (yy.value_stack (yy.tos-2))); yyerrok; when 45 => -- #line 202 Current_Rule := null; when 46 => -- #line 207 Current_Rule := null; when 47 => -- #line 210 Current_Rule := null; when 48 => -- #line 215 Current_Rule := null; Error (yy.value_stack (yy.tos-1).line, yy.value_stack (yy.tos).line, "Found @<font-face> rule"); when 49 => -- #line 220 Append_Media (Current_Media, Document, yy.value_stack (yy.tos)); when 50 => -- #line 223 Append_Media (Current_Media, Document, yy.value_stack (yy.tos)); when 53 => -- #line 234 Append_String (YYVal, yy.value_stack (yy.tos-1), yy.value_stack (yy.tos)); when 54 => -- #line 239 Set_String (YYVal, "not ", yy.value_stack (yy.tos-2).Line, yy.value_stack (yy.tos-2).Column); Append_String (YYVal, yy.value_stack (yy.tos)); when 55 => -- #line 242 Set_String (YYVal, "not ", yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column); Append_String (YYVal, yy.value_stack (yy.tos-1)); when 56 => -- #line 245 Set_String (YYVal, "only ", yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column); Append_String (YYVal, yy.value_stack (yy.tos-1)); when 57 => -- #line 248 YYVal := yy.value_stack (yy.tos-2); Append_String (YYVal, yy.value_stack (yy.tos)); when 59 => -- #line 256 Set_String (YYVal, " and ", yy.value_stack (yy.tos-2).Line, yy.value_stack (yy.tos-2).Column); Append_String (YYVal, yy.value_stack (yy.tos)); when 60 => -- #line 259 Set_String (YYVal, "", yylval.Line, yylval.Column); when 63 => -- #line 270 YYVal := yy.value_stack (yy.tos-1); Append_String (YYVal, " "); Append_String (YYVal, yy.value_stack (yy.tos)); when 65 => -- #line 277 YYVal := yy.value_stack (yy.tos-1); Append_String (YYVal, " "); Append_String (YYVal, yy.value_stack (yy.tos)); when 67 => -- #line 284 Set_String (YYVal, "and ", yy.value_stack (yy.tos-2).Line, yy.value_stack (yy.tos-2).Column); Append_String (YYVal, yy.value_stack (yy.tos)); when 68 => -- #line 289 YYVal := yy.value_stack (yy.tos-1); Append_String (YYVal, " "); Append_String (YYVal, yy.value_stack (yy.tos)); when 70 => -- #line 296 Set_String (YYVal, "or ", yy.value_stack (yy.tos-1).Line, yy.value_stack (yy.tos-1).Column); Append_String (YYVal, yy.value_stack (yy.tos)); when 71 => -- #line 301 Set_String (YYVal, "(", yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column); Append_String (YYVal, yy.value_stack (yy.tos-3)); Append_String (YYVal, ")"); when 72 => -- #line 304 Set_String (YYVal, "(", yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column); Append_String (YYVal, yy.value_stack (yy.tos-3)); Append_String (YYVal, ")"); when 73 => -- #line 307 Set_String (YYVal, "(", yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column); Append_String (YYVal, yy.value_stack (yy.tos-3)); Append_String (YYVal, ")"); when 74 => -- #line 310 Error (yylval.Line, yylval.Column, "Invalid media in parens"); Set_String (YYVal, "", yylval.Line, yylval.Column); yyerrok; when 75 => -- #line 316 Set_String (YYVal, "<=", yylval.Line, yylval.Column); when 76 => -- #line 319 Set_String (YYVal, ">=", yylval.Line, yylval.Column); when 77 => -- #line 322 Set_String (YYVal, ">", yylval.Line, yylval.Column); when 78 => -- #line 325 Set_String (YYVal, "<", yylval.Line, yylval.Column); when 79 => -- #line 330 YYVal := yy.value_stack (yy.tos-4); Append_String (YYVal, yy.value_stack (yy.tos-2)); Append_String (YYVal, yy.value_stack (yy.tos)); when 80 => -- #line 333 YYVal := yy.value_stack (yy.tos-6); Append_String (YYVal, yy.value_stack (yy.tos-4)); Append_String (YYVal, yy.value_stack (yy.tos-2)); Append_String (YYVal, yy.value_stack (yy.tos)); when 81 => -- #line 336 YYVal := yy.value_stack (yy.tos-4); Append_String (YYVal, yy.value_stack (yy.tos-2)); Append_String (YYVal, yy.value_stack (yy.tos)); when 82 => -- #line 339 YYVal := yy.value_stack (yy.tos-4); Append_String (YYVal, ": "); Append_String (YYVal, yy.value_stack (yy.tos)); when 84 => -- #line 346 YYVal := yy.value_stack (yy.tos); when 85 => -- #line 349 YYVal := yy.value_stack (yy.tos); when 86 => -- #line 354 Current_Page := null; when 87 => -- #line 357 Current_Page := null; when 88 => -- #line 362 null; when 89 => -- #line 365 null; when 90 => -- #line 370 Current_Page := new CSS.Core.Styles.CSSPageRule; when 94 => -- #line 383 Set_Selector (YYVal, SEL_PSEUDO_ELEMENT, yy.value_stack (yy.tos)); when 95 => -- #line 388 Append_Property (Current_Page.Style, Document, yy.value_stack (yy.tos-1)); when 96 => -- #line 391 Append_Property (Current_Page.Style, Document, yy.value_stack (yy.tos-1)); when 97 => -- #line 396 YYVal := yy.value_stack (yy.tos-1); when 98 => -- #line 399 YYVal := yy.value_stack (yy.tos-1); when 99 => -- #line 404 Set_Selector_Type (YYVal, SEL_NEXT_SIBLING, yylineno, yylinecol); when 100 => -- #line 407 Set_Selector_Type (YYVal, SEL_CHILD, yylineno, yylinecol); when 101 => -- #line 410 Set_Selector_Type (YYVal, SEL_FOLLOWING_SIBLING, yylineno, yylinecol); when 104 => -- #line 421 Current_Rule := null; when 105 => -- #line 424 Current_Rule := null; Error (yy.value_stack (yy.tos-1).line, yy.value_stack (yy.tos-1).column, "Invalid CSS rule"); when 106 => -- #line 427 Current_Rule := null; when 107 => -- #line 430 Error (yy.value_stack (yy.tos-2).Line, yy.value_stack (yy.tos-2).Column, "Syntax error in CSS rule"); when 108 => -- #line 435 YYVal := yy.value_stack (yy.tos-1); when 109 => -- #line 438 YYVal := yy.value_stack (yy.tos); when 111 => -- #line 445 Error (yy.value_stack (yy.tos-1).Line, yy.value_stack (yy.tos-1).Column, "Invalid CSS selector component"); when 112 => -- #line 450 Add_Selector_List (Current_Rule, Current_Media, Document, yy.value_stack (yy.tos)); when 113 => -- #line 453 Add_Selector_List (Current_Rule, Current_Media, Document, yy.value_stack (yy.tos)); when 114 => -- #line 458 Add_Selector (yy.value_stack (yy.tos-3), yy.value_stack (yy.tos-2), yy.value_stack (yy.tos-1)); YYVal := yy.value_stack (yy.tos-3); when 115 => -- #line 461 Add_Selector (yy.value_stack (yy.tos-2), yy.value_stack (yy.tos-1)); YYVal := yy.value_stack (yy.tos-2); when 116 => -- #line 464 YYVal := yy.value_stack (yy.tos-1); when 117 => -- #line 469 Add_Selector_Filter (yy.value_stack (yy.tos-1), yy.value_stack (yy.tos)); YYVal := yy.value_stack (yy.tos-1); when 119 => -- #line 476 Set_Selector (YYVal, SEL_ELEMENT, yy.value_stack (yy.tos)); when 120 => -- #line 479 Set_Selector (YYVal, SEL_IDENT, yy.value_stack (yy.tos)); when 121 => -- #line 482 Set_Selector (YYVal, SEL_CLASS, yy.value_stack (yy.tos)); when 124 => -- #line 489 Set_Selector (YYVal, SEL_NOT, yy.value_stack (yy.tos-2)); when 129 => -- #line 504 YYVal := yy.value_stack (yy.tos); when 130 => -- #line 509 YYVal := yy.value_stack (yy.tos); when 137 => -- #line 528 Set_Selector (YYVal, SEL_HAS_ATTRIBUTE, yy.value_stack (yy.tos-2)); when 138 => -- #line 531 Set_Selector (YYVal, yy.value_stack (yy.tos-4).Sel, yy.value_stack (yy.tos-6), yy.value_stack (yy.tos-2)); when 139 => -- #line 534 Set_Selector (YYVal, yy.value_stack (yy.tos-4).Sel, yy.value_stack (yy.tos-6), yy.value_stack (yy.tos-2)); when 140 => -- #line 537 Error (yy.value_stack (yy.tos).Line, yy.value_stack (yy.tos).column, "Invalid attribute definition."); when 141 => -- #line 542 Set_Selector_Type (YYVal, SEL_EQ_ATTRIBUTE, yylineno, yylinecol); when 142 => -- #line 545 Set_Selector_Type (YYVal, SEL_CONTAIN_ATTRIBUTE, yylineno, yylinecol); when 143 => -- #line 548 Set_Selector_Type (YYVal, SEL_ORMATCH_ATTRIBUTE, yylineno, yylinecol); when 144 => -- #line 551 Set_Selector_Type (YYVal, SEL_STARTS_ATTRIBUTE, yylineno, yylinecol); when 145 => -- #line 554 Set_Selector_Type (YYVal, SEL_ENDS_ATTRIBUTE, yylineno, yylinecol); when 146 => -- #line 557 Set_Selector_Type (YYVal, SEL_MATCH_ATTRIBUTE, yylineno, yylinecol); when 147 => -- #line 562 Set_Selector (YYVal, SEL_PSEUDO_ELEMENT, yy.value_stack (yy.tos)); when 148 => -- #line 565 Set_Selector (YYVal, SEL_PSEUDO_CLASS, yy.value_stack (yy.tos)); when 149 => -- #line 568 Set_Selector (YYVal, SEL_FUNCTION, yy.value_stack (yy.tos-3)); when 152 => -- #line 579 YYVal := yy.value_stack (yy.tos); when 153 => -- #line 584 YYVal := yy.value_stack (yy.tos); when 154 => -- #line 587 YYVal := yy.value_stack (yy.tos-4); when 155 => -- #line 590 YYVal := yy.value_stack (yy.tos-1); when 156 => -- #line 595 Append_Property (Current_Rule, Current_Media, Document, yy.value_stack (yy.tos-1)); when 157 => -- #line 598 Append_Property (Current_Rule, Current_Media, Document, yy.value_stack (yy.tos)); Error (yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column, "Invalid property"); yyerrok; when 158 => -- #line 602 YYVal := yy.value_stack (yy.tos-2); Error (yy.value_stack (yy.tos-1).Line, yy.value_stack (yy.tos-1).Column, "Invalid property (2)"); yyerrok; when 159 => -- #line 605 Append_Property (Current_Rule, Current_Media, Document, yy.value_stack (yy.tos-1)); when 162 => -- #line 616 Set_Property (YYVal, yy.value_stack (yy.tos-4), yy.value_stack (yy.tos-1), True); when 163 => -- #line 619 Set_Property (YYVal, yy.value_stack (yy.tos-3), yy.value_stack (yy.tos), False); when 164 => -- #line 622 Error (yy.value_stack (yy.tos).Line, yy.value_stack (yy.tos).Column, "Missing ''' or '""' at end of string"); Set_Property (YYVal, yy.value_stack (yy.tos-3), EMPTY, False); yyclearin; when 165 => -- #line 628 Error (yy.value_stack (yy.tos).Line, yy.value_stack (yy.tos).Column, "Invalid property value: " & YYText); Set_Property (YYVal, yy.value_stack (yy.tos-2), yy.value_stack (yy.tos-2), False); yyclearin; when 166 => -- #line 634 Error (yy.value_stack (yy.tos-1).Line, yy.value_stack (yy.tos-1).Column, "Missing ':' after property name"); Set_Property (YYVal, yy.value_stack (yy.tos-1), EMPTY, False); yyclearin; when 167 => -- #line 640 Error (yylval.Line, yylval.Column, "Invalid property name"); YYVal := EMPTY; when 168 => -- #line 645 YYVal := yy.value_stack (yy.tos-1); when 169 => -- #line 648 Warning (yy.value_stack (yy.tos-1).Line, yy.value_stack (yy.tos-1).Column, "IE7 '*' symbol hack is used"); YYVal := yy.value_stack (yy.tos-1); when 171 => -- #line 657 CSS.Parser.Set_Function (YYVal, Document, yy.value_stack (yy.tos-4), yy.value_stack (yy.tos-2)); when 172 => -- #line 660 CSS.Parser.Set_Function (YYVal, Document, yy.value_stack (yy.tos-3), yy.value_stack (yy.tos-1)); when 173 => -- #line 663 Error (yy.value_stack (yy.tos-3).Line, yy.value_stack (yy.tos-3).Column, "Invalid function parameter"); when 174 => -- #line 668 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-3), yy.value_stack (yy.tos)); when 175 => -- #line 671 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-1), yy.value_stack (yy.tos)); when 176 => -- #line 674 YYVal := yy.value_stack (yy.tos); when 177 => -- #line 679 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-3), yy.value_stack (yy.tos)); when 178 => -- #line 682 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-3), yy.value_stack (yy.tos)); when 179 => -- #line 685 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-1), yy.value_stack (yy.tos)); when 180 => -- #line 688 YYVal := yy.value_stack (yy.tos); when 181 => -- #line 691 YYVal := yy.value_stack (yy.tos-1); -- CSS.Parser.Set_Parameter ($$, Document, $1, $5); when 182 => -- #line 697 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-2), yy.value_stack (yy.tos)); when 183 => -- #line 700 CSS.Parser.Set_Expr (YYVal, yy.value_stack (yy.tos-1), yy.value_stack (yy.tos)); when 185 => -- #line 707 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos)); when 186 => -- #line 710 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos)); when 187 => -- #line 713 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos)); when 188 => -- #line 716 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos-1)); when 189 => -- #line 719 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos-1)); when 190 => -- #line 722 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos-1)); when 191 => -- #line 725 CSS.Parser.Set_Value (YYVal, Document, yy.value_stack (yy.tos)); when 192 => -- #line 728 YYVal := yy.value_stack (yy.tos); when 193 => -- #line 731 Error (yy.value_stack (yy.tos).Line, yy.value_stack (yy.tos).Column, "Invalid url()"); YYVal := EMPTY; when 194 => -- #line 736 YYVal := yy.value_stack (yy.tos-1); when 195 => -- #line 739 YYVal := yy.value_stack (yy.tos-1); when 196 => -- #line 742 YYVal := yy.value_stack (yy.tos-1); when 197 => -- #line 745 YYVal := yy.value_stack (yy.tos-1); when 198 => -- #line 748 YYVal := yy.value_stack (yy.tos-1); when 199 => -- #line 751 YYVal := yy.value_stack (yy.tos-1); when 200 => -- #line 754 YYVal := yy.value_stack (yy.tos-1); when 201 => -- #line 757 YYVal := yy.value_stack (yy.tos-1); when 202 => -- #line 762 Set_Color (YYVal, yy.value_stack (yy.tos-1)); pragma Style_Checks (On); when others => null; end case; -- Pop RHS states and goto next state yy.tos := yy.tos - Rule_Length (yy.rule_id) + 1; if yy.tos > yy.stack_size then Text_IO.Put_Line (" Stack size exceeded on state_stack"); raise yy_tokens.Syntax_Error; end if; yy.state_stack (yy.tos) := goto_state (yy.state_stack (yy.tos - 1), Get_LHS_Rule (yy.rule_id)); yy.value_stack (yy.tos) := YYVal; if yy.debug then reduce_debug (yy.rule_id, goto_state (yy.state_stack (yy.tos - 1), Get_LHS_Rule (yy.rule_id))); end if; end if; end loop; end YYParse; end CSS.Parser.Parser;
{ "source": "starcoderdata", "programming_language": "ada" }
with System.Storage_Elements; with TLSF.Config; with TLSF.Bitmaps; with TLSF.Mem_Block_Size; use TLSF.Config; use TLSF.Bitmaps; use TLSF.Mem_Block_Size; package body TLSF.Mem_Blocks is subtype Free_Block_Header is Block_Header (Free); subtype Occupied_Block_Header is Block_Header (Occupied); Block_Header_Size : constant SSE.Storage_Count := Block_Header'Max_Size_In_Storage_Elements; Occupied_Block_Header_Size : constant SSE.Storage_Count := Occupied_Block_Header'Max_Size_In_Storage_Elements; Free_Block_Header_Size : constant SSE.Storage_Count := Free_Block_Header'Max_SizRound_Size_Up(e_In_Storage_Elements; Aligned_Block_Header_Size : constant SSE.Storage_Count := Align (Block_Header'Max_Size_In_Storage_Elements); Aligned_Occupied_Block_Header_Size : constant SSE.Storage_Count := Align (Occupied_Block_Header'Max_Size_In_Storage_Elements); Aligned_Free_Block_Header_Size : constant SSE.Storage_Count := Align (Free_Block_Header'Max_Size_In_Storage_Elements); Small_Block_Size : constant := 2 ** FL_Index_Shift; use type SSE.Storage_Offset; use type SSE.Storage_Count; pragma Assert (Small_Block_Size >= Block_Header_Size); -- should be >= Block_Header max size in storage elements function Adjust_And_Align_Size (S : SSE.Storage_Count) return Size is (Align (Aligned_Occupied_Block_Header_Size + S)); function Is_Free_Block_Too_Large (Free_Block : not null access Block_Header; Block_Size : Size) return Boolean is (Free_Block.Size >= Block_Size + Small_Block_Size); procedure Block_Make_Occupied (Block : not null access Block_Header) is Blk : Block_Header with Import, Address => Block.all'Address; begin Blk := Block_Header'(Status => Occupied, Prev_Block => Block.Prev_Block, Prev_Block_Status => Block.Prev_Block_Status, Next_Block_Status => Block.Next_Block_Status, Size => Block.Size); end Block_Make_Occupied; procedure Block_Make_Free (Block : not null access Block_Header) is BA : Block_Header with Import, Address => Block.all'Address; BH : Free_Block_Header := Free_Block_Header' (Status => Free, Prev_Block => Block.Prev_Block, Prev_Block_Status => Block.Prev_Block_Status, Next_Block_Status => Block.Next_Block_Status, Size => Block.Size, Free_List => Free_Blocks_List'(Prev => null, Next => null)); -- Blk : Block_Header with Import, Address => Block.all'Address; begin BA := BH; --Blk := end Block_Make_Free; function Address_To_Block_Header_Ptr (Addr : System.Address) return not null access Block_Header is use type SSE.Storage_Count; Block_Addr : System.Address := (Addr - Aligned_Occupied_Block_Header_Size); Block : aliased Block_Header with Import, Address => Block_Addr; begin return Block'Unchecked_Access; end Address_To_Block_Header_Ptr; function Block_Header_Ptr_To_Address (Block : not null access constant Block_Header) return System.Address is use type SSE.Storage_Count; begin return Block.all'Address + Aligned_Occupied_Block_Header_Size; end Block_Header_Ptr_To_Address; procedure Notify_Neighbors_Of_Block_Status (Block : access Block_Header) is Next_Block : access Block_Header := Get_Next_Block (Block); Prev_Block : access Block_Header := Get_Prev_Block (Block); begin if Next_Block /= null then Next_Block.Prev_Block_Status := Block.Status; end if; if Prev_Block /= null then Prev_Block.Next_Block_Status := Block.Status; end if; end Notify_Neighbors_Of_Block_Status; function Split_Free_Block (Free_Block : not null access Block_Header; New_Block_Size : Size) return not null access Block_Header is Remaining_Block_Size : Size := Free_Block.Size - New_Block_Size; Remaining_Block : aliased Block_Header with Import, Address => Free_Block.all'Address + New_Block_Size; begin Block_Make_Free ( Remaining_Block'Access ); Remaining_Block := Block_Header' (Status => Free, Prev_Block => Free_Block.all'Unchecked_Access, Prev_Block_Status => Occupied, Next_Block_Status => Free_Block.Next_Block_Status, Size => Remaining_Block_Size, Free_List => Free_Blocks_List'(Prev => null, Next => null)); Free_Block.Size := New_Block_Size; Free_Block.Next_Block_Status := Free; return Remaining_Block'Unchecked_Access; end Split_Free_Block; function Insert_To_Free_Blocks_List (Block_To_Insert : not null access Block_Header; Block_In_List : access Block_Header) return not null access Block_Header is begin if Block_In_List /= null then Block_To_Insert.Free_List.Next := Block_In_List; Block_To_Insert.Free_List.Prev := Block_In_List.Free_List.Prev; Block_In_List.Free_List.Prev := Block_To_Insert; return Block_In_List.all'Unchecked_Access; else Block_To_Insert.Free_List := Free_Blocks_List'(Prev => Block_To_Insert.all'Unchecked_Access, Next => Block_To_Insert.all'Unchecked_Access); return Block_To_Insert.all'Unchecked_Access; end if; end Insert_To_Free_Blocks_List; function Get_Next_Block ( Block : not null access Block_Header) return access Block_Header is Next_Block : aliased Block_Header with Import, Address => Block.all'Address + Block.Size; begin return (if Block.Next_Block_Status /= Absent then Next_Block'Unchecked_Access else null); end Get_Next_Block; function Get_Prev_Block ( Block : not null access Block_Header) return access Block_Header is begin return (if Block.Prev_Block_Status /= Absent then Block.Prev_Block else null); end Get_Prev_Block; function Init_First_Free_Block ( Addr : System.Address; Sz : SSE.Storage_Count) return not null access Block_Header is Free_Block_Hdr : aliased Block_Header with Import, Address => Addr; begin Free_Block_Hdr := Block_Header' (Status => Free, Prev_Block => null, Prev_Block_Status => Absent, Next_Block_Status => Absent, Size => Size(Sz), Free_List => Free_Blocks_List'(Prev => null, Next => null)); return Free_Block_Hdr'Unchecked_Access; end Init_First_Free_Block; function Block_Was_Last_In_Free_List (Block : not null access constant Block_Header) return Boolean is -- ERROR here -- since list is cyclic: -- /-------\ -- A B -- \--------/ -- when two last items remain A ->next = B and A->prev = B, so as B (Block.Free_List.Prev = Block.Free_List.Next); function Unlink_Block_From_Free_List (Block : not null access Block_Header) return access Block_Header is begin Block.Free_List.Prev.Free_List.Next := Block.Free_List.Next; Block.Free_List.Next.Free_List.Prev := Block.Free_List.Prev; return (if Block_Was_Last_In_Free_List (Block) then null else Block.Free_List.Next); end Unlink_Block_From_Free_List; procedure Merge_Two_Adjacent_Free_Blocks (Block : not null access Block_Header) is Next_Block : access Block_Header := Get_Next_Block (Block); begin Block.Next_Block_Status := Next_Block.Next_Block_Status; Block.Size := Block.Size + Next_Block.Size; end Merge_Two_Adjacent_Free_Blocks; function Is_Block_Free (Block : access Block_Header) return Boolean is (Block /= null and then Block.Status = Free); function Search_Suitable_Block (FL : First_Level_Index; SL : Second_Level_Index; Bmp : Levels_Bitmap; FB_List : Free_Lists) return not null access Block_Header is Block_Hdr : access Block_Header := null; SL_From : Second_Level_Index := SL; FL_From : First_Level_Index := FL; begin Search_Present (Bmp, FL_From, SL_From); Block_Hdr := FB_List (FL_From, SL_From); pragma Assert (Block_Hdr /= null); -- run-time exception will be raised if no block found return Block_Hdr; end Search_Suitable_Block; procedure Remove_Free_Block_From_Lists_And_Bitmap (Block : not null access Block_Header; FB_List : in out Free_Lists; Bmp : in out Levels_Bitmap) is FL : First_Level_Index; SL : Second_Level_Index; begin Mapping_Insert (Block.Size, FL, SL); FB_List (FL, SL) := Unlink_Block_From_Free_List (Block); if FB_List (FL, SL) = null then Set_Not_Present (Bmp, FL, SL); end if; end Remove_Free_Block_From_Lists_And_Bitmap; procedure Insert_Free_Block_To_Lists_And_Bitmap (Block : not null access Block_Header; FB_List : in out Free_Lists; Bmp : in out Levels_Bitmap) is FL : First_Level_Index; SL : Second_Level_Index; begin Mapping_Insert (Block.Size, FL, SL); FB_List (FL, SL) := Insert_To_Free_Blocks_List (Block_To_Insert => Block, Block_In_List => FB_List (FL, SL)); Set_Present (Bmp, FL, SL); end Insert_Free_Block_To_Lists_And_Bitmap; end TLSF.Mem_Blocks;
{ "source": "starcoderdata", "programming_language": "ada" }
with AVR.TIMERS; -- with AVR.INTERRUPTS; -- ============================================================================= -- Package AVR.TIMERS.CLOCK -- -- Implements the clock functions. This timer is used for handling the clock: -- - TIMER1_COMPA (16 bits timer) -- ============================================================================= package AVR.TIMERS.CLOCK is subtype Time_Hour_Type is Integer; subtype Time_Minute_Type is Integer range 0 .. 59; subtype Time_Second_Type is Integer range 0 .. 59; type Time_Type is record HH : Time_Hour_Type; MM : Time_Minute_Type; SS : Time_Second_Type; end record; -- Initialize Clock Timer procedure Initialize (Timer : TIMERS.Timer_Type); function Get_Current_Time_In_Nanoseconds return Unsigned_64; function Get_Current_Time_In_Seconds return Unsigned_64; function Get_Current_Time return Time_Type; -- Schedule tick update when Timer1_ChannelA overflows procedure Schedule_Update_Clock; -- pragma Machine_Attribute -- (Entity => Schedule_Update_Clock, -- Attribute_Name => "signal"); -- pragma Export -- (Convention => C, -- Entity => Schedule_Update_Clock, -- External_Name => AVR.INTERRUPTS.TIMER1_OVF); private Priv_Clock_Cycles : Unsigned_64 := 0; end AVR.TIMERS.CLOCK;
{ "source": "starcoderdata", "programming_language": "ada" }
with GNAT.OS_Lib; with Ada.Text_IO; with Parameters; with System; package body Unix is package OSL renames GNAT.OS_Lib; package TIO renames Ada.Text_IO; package PM renames Parameters; ---------------------- -- process_status -- ---------------------- function process_status (pid : pid_t) return process_exit is result : constant uInt8 := nohang_waitpid (pid); begin case result is when 0 => return still_running; when 1 => return exited_normally; when others => return exited_with_error; end case; end process_status; ----------------------- -- screen_attached -- ----------------------- function screen_attached return Boolean is begin return CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 1; end screen_attached; ----------------------- -- cone_of_silence -- ----------------------- procedure cone_of_silence (deploy : Boolean) is result : uInt8; begin if not screen_attached then return; end if; if deploy then result := silent_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control OFF command failed"); end if; else result := chatty_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control ON command failed"); end if; end if; end cone_of_silence; ----------------------------- -- ignore_background_tty -- ----------------------------- procedure ignore_background_tty is result : uInt8; begin result := ignore_tty_write; if result > 0 then TIO.Put_Line ("Notice: ignoring background tty write signal failed"); end if; result := ignore_tty_read; if result > 0 then TIO.Put_Line ("Notice: ignoring background tty read signal failed"); end if; end ignore_background_tty; ------------------------- -- kill_process_tree -- ------------------------- procedure kill_process_tree (process_group : pid_t) is use type IC.int; result : constant IC.int := signal_runaway (process_group); begin if result /= 0 then TIO.Put_Line ("Notice: failed to signal pid " & process_group'Img); end if; end kill_process_tree; ------------------------ -- external_command -- ------------------------ function external_command (command : String) return Boolean is Args : OSL.Argument_List_Access; Exit_Status : Integer; begin Args := OSL.Argument_String_To_List (command); Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return Exit_Status = 0; end external_command; ------------------- -- fork_failed -- ------------------- function fork_failed (pid : pid_t) return Boolean is begin if pid < 0 then return True; end if; return False; end fork_failed; ---------------------- -- launch_process -- ---------------------- function launch_process (command : String) return pid_t is procid : OSL.Process_Id; Args : OSL.Argument_List_Access; begin Args := OSL.Argument_String_To_List (command); procid := OSL.Non_Blocking_Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return pid_t (OSL.Pid_To_Integer (procid)); end launch_process; ---------------------------- -- env_variable_defined -- ---------------------------- function env_variable_defined (variable : String) return Boolean is test : String := OSL.Getenv (variable).all; begin return (test /= ""); end env_variable_defined; -------------------------- -- env_variable_value -- -------------------------- function env_variable_value (variable : String) return String is begin return OSL.Getenv (variable).all; end env_variable_value; ------------------ -- pipe_close -- ------------------ function pipe_close (OpenFile : CSM.FILEs) return Integer is res : constant CSM.int := pclose (FileStream => OpenFile); u16 : Interfaces.Unsigned_16; begin u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8); if Integer (u16) > 0 then return Integer (u16); end if; return Integer (res); end pipe_close; --------------------- -- piped_command -- --------------------- function piped_command (command : String; status : out Integer) return JT.Text is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("re")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return result; end piped_command; -------------------------- -- piped_mute_command -- -------------------------- function piped_mute_command (command : String; abnormal : out JT.Text) return Boolean is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; status : Integer; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("re")); abnormal := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return status = 0; end piped_mute_command; ----------------- -- pipe_read -- ----------------- function pipe_read (OpenFile : CSM.FILEs) return JT.Text is -- Allocate 2kb at a time buffer : String (1 .. 2048) := (others => ' '); result : JT.Text := JT.blank; charbuf : CSM.int; marker : Natural := 0; begin loop charbuf := CSM.fgetc (OpenFile); if charbuf = CSM.EOF then if marker >= buffer'First then JT.SU.Append (result, buffer (buffer'First .. marker)); end if; exit; end if; if marker = buffer'Last then JT.SU.Append (result, buffer); marker := buffer'First; else marker := marker + 1; end if; buffer (marker) := Character'Val (charbuf); end loop; return result; end pipe_read; ----------------- -- true_path -- ----------------- function true_path (provided_path : String) return String is use type ICS.chars_ptr; buffer : IC.char_array (0 .. 1024) := (others => IC.nul); result : ICS.chars_ptr; path : IC.char_array := IC.To_C (provided_path); begin result := realpath (pathname => path, resolved_path => buffer); if result = ICS.Null_Ptr then return ""; end if; return ICS.Value (result); exception when others => return ""; end true_path; end Unix;
{ "source": "starcoderdata", "programming_language": "ada" }
with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32_SVD.USART; use STM32_SVD.USART; package body STM32GD.USART.Peripheral is type USART_Periph_Access is access all USART_Peripheral; function USART_Periph return USART_Periph_Access is begin return (if USART = USART_1 then STM32_SVD.USART.USART1_Periph'Access elsif USART = USART_2 then STM32_SVD.USART.USART2_Periph'Access else STM32_SVD.USART.USART3_Periph'Access); end USART_Periph; procedure Enable is begin case USART is when USART_1 => RCC_Periph.APB2ENR.USART1EN := 1; when USART_2 => RCC_Periph.APB1ENR.USART2EN := 1; when USART_3 => RCC_Periph.APB1ENR.USART3EN := 1; end case; end Enable; procedure Disable is begin case USART is when USART_1 => RCC_Periph.APB2ENR.USART1EN := 0; when USART_2 => RCC_Periph.APB1ENR.USART2EN := 0; when USART_3 => RCC_Periph.APB1ENR.USART3EN := 0; end case; end Disable; procedure Init is Int_Scale : constant UInt32 := 4; Int_Divider : constant UInt32 := (25 * UInt32 (Clock)) / (Int_Scale * Speed); Frac_Divider : constant UInt32 := Int_Divider rem 100; begin USART_Periph.BRR.DIV_Fraction := STM32_SVD.USART.BRR_DIV_Fraction_Field (((Frac_Divider * 16) + 50) / 100 mod 16); USART_Periph.BRR.DIV_Mantissa := STM32_SVD.USART.BRR_DIV_Mantissa_Field (Int_Divider / 100); USART_Periph.CR1.UE := 1; USART_Periph.CR1.TE := 1; USART_Periph.CR1.RE := 1; end Init; procedure Transmit (Data : in Byte) is begin while USART_Periph.SR.TXE = 0 loop null; end loop; USART_Periph.DR.DR := UInt9 (Data); end Transmit; function Data_Available return Boolean is begin return USART_Periph.SR.RXNE = 1; end Data_Available; function Receive return Byte is begin while USART_Periph.SR.RXNE = 0 loop null; end loop; return Byte (USART_Periph.DR.DR and 16#FF#); end Receive; end STM32GD.USART.Peripheral;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with BigInteger; use BigInteger; package body Problem_25 is package IO renames Ada.Text_IO; procedure Solve is term : Positive := 3; n : BigInt := BigInteger.Create(2); n_1 : BigInt := BigInteger.Create(1); n_2 : BigInt := BigInteger.Create(1); begin while Magnitude(n) < 1_000 loop term := term + 1; n_2 := n_1; n_1 := n; n := n_1 + n_2; end loop; IO.Put_Line(Positive'Image(term)); end Solve; end Problem_25;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ with Ada.Containers.Generic_Array_Sort; with System; use type System.Address; package body Ada.Containers.Bounded_Vectors is pragma Warnings (Off, "variable ""Busy*"" is not referenced"); pragma Warnings (Off, "variable ""Lock*"" is not referenced"); -- See comment in Ada.Containers.Helpers ----------------------- -- Local Subprograms -- ----------------------- function To_Array_Index (Index : Index_Type'Base) return Count_Type'Base; --------- -- "&" -- --------- function "&" (Left, Right : Vector) return Vector is LN : constant Count_Type := Length (Left); RN : constant Count_Type := Length (Right); N : Count_Type'Base; -- length of result J : Count_Type'Base; -- for computing intermediate index values Last : Index_Type'Base; -- Last index of result begin -- We decide that the capacity of the result is the sum of the lengths -- of the vector parameters. We could decide to make it larger, but we -- have no basis for knowing how much larger, so we just allocate the -- minimum amount of storage. -- Here we handle the easy cases first, when one of the vector -- parameters is empty. (We say "easy" because there's nothing to -- compute, that can potentially overflow.) if LN = 0 then if RN = 0 then return Empty_Vector; end if; return Vector'(Capacity => RN, Elements => Right.Elements (1 .. RN), Last => Right.Last, others => <>); end if; if RN = 0 then return Vector'(Capacity => LN, Elements => Left.Elements (1 .. LN), Last => Left.Last, others => <>); end if; -- Neither of the vector parameters is empty, so must compute the length -- of the result vector and its last index. (This is the harder case, -- because our computations must avoid overflow.) -- There are two constraints we need to satisfy. The first constraint is -- that a container cannot have more than Count_Type'Last elements, so -- we must check the sum of the combined lengths. Note that we cannot -- simply add the lengths, because of the possibility of overflow. if Checks and then LN > Count_Type'Last - RN then raise Constraint_Error with "new length is out of range"; end if; -- It is now safe to compute the length of the new vector, without fear -- of overflow. N := LN + RN; -- The second constraint is that the new Last index value cannot -- exceed Index_Type'Last. We use the wider of Index_Type'Base and -- Count_Type'Base as the type for intermediate values. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then -- We perform a two-part test. First we determine whether the -- computed Last value lies in the base range of the type, and then -- determine whether it lies in the range of the index (sub)type. -- Last must satisfy this relation: -- First + Length - 1 <= Last -- We regroup terms: -- First - 1 <= Last - Length -- Which can rewrite as: -- No_Index <= Last - Length if Checks and then Index_Type'Base'Last - Index_Type'Base (N) < No_Index then raise Constraint_Error with "new length is out of range"; end if; -- We now know that the computed value of Last is within the base -- range of the type, so it is safe to compute its value: Last := No_Index + Index_Type'Base (N); -- Finally we test whether the value is within the range of the -- generic actual index subtype: if Checks and then Last > Index_Type'Last then raise Constraint_Error with "new length is out of range"; end if; elsif Index_Type'First <= 0 then -- Here we can compute Last directly, in the normal way. We know that -- No_Index is less than 0, so there is no danger of overflow when -- adding the (positive) value of length. J := Count_Type'Base (No_Index) + N; -- Last if Checks and then J > Count_Type'Base (Index_Type'Last) then raise Constraint_Error with "new length is out of range"; end if; -- We know that the computed value (having type Count_Type) of Last -- is within the range of the generic actual index subtype, so it is -- safe to convert to Index_Type: Last := Index_Type'Base (J); else -- Here Index_Type'First (and Index_Type'Last) is positive, so we -- must test the length indirectly (by working backwards from the -- largest possible value of Last), in order to prevent overflow. J := Count_Type'Base (Index_Type'Last) - N; -- No_Index if Checks and then J < Count_Type'Base (No_Index) then raise Constraint_Error with "new length is out of range"; end if; -- We have determined that the result length would not create a Last -- index value outside of the range of Index_Type, so we can now -- safely compute its value. Last := Index_Type'Base (Count_Type'Base (No_Index) + N); end if; declare LE : Elements_Array renames Left.Elements (1 .. LN); RE : Elements_Array renames Right.Elements (1 .. RN); begin return Vector'(Capacity => N, Elements => LE & RE, Last => Last, others => <>); end; end "&"; function "&" (Left : Vector; Right : Element_Type) return Vector is LN : constant Count_Type := Length (Left); begin -- We decide that the capacity of the result is the sum of the lengths -- of the parameters. We could decide to make it larger, but we have no -- basis for knowing how much larger, so we just allocate the minimum -- amount of storage. -- We must compute the length of the result vector and its last index, -- but in such a way that overflow is avoided. We must satisfy two -- constraints: the new length cannot exceed Count_Type'Last, and the -- new Last index cannot exceed Index_Type'Last. if Checks and then LN = Count_Type'Last then raise Constraint_Error with "new length is out of range"; end if; if Checks and then Left.Last >= Index_Type'Last then raise Constraint_Error with "new length is out of range"; end if; return Vector'(Capacity => LN + 1, Elements => Left.Elements (1 .. LN) & Right, Last => Left.Last + 1, others => <>); end "&"; function "&" (Left : Element_Type; Right : Vector) return Vector is RN : constant Count_Type := Length (Right); begin -- We decide that the capacity of the result is the sum of the lengths -- of the parameters. We could decide to make it larger, but we have no -- basis for knowing how much larger, so we just allocate the minimum -- amount of storage. -- We compute the length of the result vector and its last index, but in -- such a way that overflow is avoided. We must satisfy two constraints: -- the new length cannot exceed Count_Type'Last, and the new Last index -- cannot exceed Index_Type'Last. if Checks and then RN = Count_Type'Last then raise Constraint_Error with "new length is out of range"; end if; if Checks and then Right.Last >= Index_Type'Last then raise Constraint_Error with "new length is out of range"; end if; return Vector'(Capacity => 1 + RN, Elements => Left & Right.Elements (1 .. RN), Last => Right.Last + 1, others => <>); end "&"; function "&" (Left, Right : Element_Type) return Vector is begin -- We decide that the capacity of the result is the sum of the lengths -- of the parameters. We could decide to make it larger, but we have no -- basis for knowing how much larger, so we just allocate the minimum -- amount of storage. -- We must compute the length of the result vector and its last index, -- but in such a way that overflow is avoided. We must satisfy two -- constraints: the new length cannot exceed Count_Type'Last (here, we -- know that that condition is satisfied), and the new Last index cannot -- exceed Index_Type'Last. if Checks and then Index_Type'First >= Index_Type'Last then raise Constraint_Error with "new length is out of range"; end if; return Vector'(Capacity => 2, Elements => (Left, Right), Last => Index_Type'First + 1, others => <>); end "&"; --------- -- "=" -- --------- overriding function "=" (Left, Right : Vector) return Boolean is begin if Left.Last /= Right.Last then return False; end if; if Left.Length = 0 then return True; end if; declare -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. Lock_Left : With_Lock (Left.TC'Unrestricted_Access); Lock_Right : With_Lock (Right.TC'Unrestricted_Access); begin for J in Count_Type range 1 .. Left.Length loop if Left.Elements (J) /= Right.Elements (J) then return False; end if; end loop; end; return True; end "="; ------------ -- Assign -- ------------ procedure Assign (Target : in out Vector; Source : Vector) is begin if Target'Address = Source'Address then return; end if; if Checks and then Target.Capacity < Source.Length then raise Capacity_Error -- ??? with "Target capacity is less than Source length"; end if; Target.Clear; Target.Elements (1 .. Source.Length) := Source.Elements (1 .. Source.Length); Target.Last := Source.Last; end Assign; ------------ -- Append -- ------------ procedure Append (Container : in out Vector; New_Item : Vector) is begin if New_Item.Is_Empty then return; end if; if Checks and then Container.Last >= Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Container.Insert (Container.Last + 1, New_Item); end Append; procedure Append (Container : in out Vector; New_Item : Element_Type; Count : Count_Type := 1) is begin if Count = 0 then return; end if; if Checks and then Container.Last >= Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Container.Insert (Container.Last + 1, New_Item, Count); end Append; -------------- -- Capacity -- -------------- function Capacity (Container : Vector) return Count_Type is begin return Container.Elements'Length; end Capacity; ----------- -- Clear -- ----------- procedure Clear (Container : in out Vector) is begin TC_Check (Container.TC); Container.Last := No_Index; end Clear; ------------------------ -- Constant_Reference -- ------------------------ function Constant_Reference (Container : aliased Vector; Position : Cursor) return Constant_Reference_Type is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; if Checks and then Position.Index > Position.Container.Last then raise Constraint_Error with "Position cursor is out of range"; end if; declare A : Elements_Array renames Container.Elements; J : constant Count_Type := To_Array_Index (Position.Index); TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access; begin return R : constant Constant_Reference_Type := (Element => A (J)'Access, Control => (Controlled with TC)) do Lock (TC.all); end return; end; end Constant_Reference; function Constant_Reference (Container : aliased Vector; Index : Index_Type) return Constant_Reference_Type is begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; end if; declare A : Elements_Array renames Container.Elements; J : constant Count_Type := To_Array_Index (Index); TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access; begin return R : constant Constant_Reference_Type := (Element => A (J)'Access, Control => (Controlled with TC)) do Lock (TC.all); end return; end; end Constant_Reference; -------------- -- Contains -- -------------- function Contains (Container : Vector; Item : Element_Type) return Boolean is begin return Find_Index (Container, Item) /= No_Index; end Contains; ---------- -- Copy -- ---------- function Copy (Source : Vector; Capacity : Count_Type := 0) return Vector is C : Count_Type; begin if Capacity = 0 then C := Source.Length; elsif Capacity >= Source.Length then C := Capacity; elsif Checks then raise Capacity_Error with "Requested capacity is less than Source length"; end if; return Target : Vector (C) do Target.Elements (1 .. Source.Length) := Source.Elements (1 .. Source.Length); Target.Last := Source.Last; end return; end Copy; ------------ -- Delete -- ------------ procedure Delete (Container : in out Vector; Index : Extended_Index; Count : Count_Type := 1) is Old_Last : constant Index_Type'Base := Container.Last; Old_Len : constant Count_Type := Container.Length; New_Last : Index_Type'Base; Count2 : Count_Type'Base; -- count of items from Index to Old_Last Off : Count_Type'Base; -- Index expressed as offset from IT'First begin -- Delete removes items from the vector, the number of which is the -- minimum of the specified Count and the items (if any) that exist from -- Index to Container.Last. There are no constraints on the specified -- value of Count (it can be larger than what's available at this -- position in the vector, for example), but there are constraints on -- the allowed values of the Index. -- As a precondition on the generic actual Index_Type, the base type -- must include Index_Type'Pred (Index_Type'First); this is the value -- that Container.Last assumes when the vector is empty. However, we do -- not allow that as the value for Index when specifying which items -- should be deleted, so we must manually check. (That the user is -- allowed to specify the value at all here is a consequence of the -- declaration of the Extended_Index subtype, which includes the values -- in the base range that immediately precede and immediately follow the -- values in the Index_Type.) if Checks and then Index < Index_Type'First then raise Constraint_Error with "Index is out of range (too small)"; end if; -- We do allow a value greater than Container.Last to be specified as -- the Index, but only if it's immediately greater. This allows the -- corner case of deleting no items from the back end of the vector to -- be treated as a no-op. (It is assumed that specifying an index value -- greater than Last + 1 indicates some deeper flaw in the caller's -- algorithm, so that case is treated as a proper error.) if Index > Old_Last then if Checks and then Index > Old_Last + 1 then raise Constraint_Error with "Index is out of range (too large)"; end if; return; end if; -- Here and elsewhere we treat deleting 0 items from the container as a -- no-op, even when the container is busy, so we simply return. if Count = 0 then return; end if; -- The tampering bits exist to prevent an item from being deleted (or -- otherwise harmfully manipulated) while it is being visited. Query, -- Update, and Iterate increment the busy count on entry, and decrement -- the count on exit. Delete checks the count to determine whether it is -- being called while the associated callback procedure is executing. TC_Check (Container.TC); -- We first calculate what's available for deletion starting at -- Index. Here and elsewhere we use the wider of Index_Type'Base and -- Count_Type'Base as the type for intermediate values. (See function -- Length for more information.) if Count_Type'Base'Last >= Index_Type'Pos (Index_Type'Base'Last) then Count2 := Count_Type'Base (Old_Last) - Count_Type'Base (Index) + 1; else Count2 := Count_Type'Base (Old_Last - Index + 1); end if; -- If more elements are requested (Count) for deletion than are -- available (Count2) for deletion beginning at Index, then everything -- from Index is deleted. There are no elements to slide down, and so -- all we need to do is set the value of Container.Last. if Count >= Count2 then Container.Last := Index - 1; return; end if; -- There are some elements aren't being deleted (the requested count was -- less than the available count), so we must slide them down to -- Index. We first calculate the index values of the respective array -- slices, using the wider of Index_Type'Base and Count_Type'Base as the -- type for intermediate calculations. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then Off := Count_Type'Base (Index - Index_Type'First); New_Last := Old_Last - Index_Type'Base (Count); else Off := Count_Type'Base (Index) - Count_Type'Base (Index_Type'First); New_Last := Index_Type'Base (Count_Type'Base (Old_Last) - Count); end if; -- The array index values for each slice have already been determined, -- so we just slide down to Index the elements that weren't deleted. declare EA : Elements_Array renames Container.Elements; Idx : constant Count_Type := EA'First + Off; begin EA (Idx .. Old_Len - Count) := EA (Idx + Count .. Old_Len); Container.Last := New_Last; end; end Delete; procedure Delete (Container : in out Vector; Position : in out Cursor; Count : Count_Type := 1) is pragma Warnings (Off, Position); begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; if Checks and then Position.Index > Container.Last then raise Program_Error with "Position index is out of range"; end if; Delete (Container, Position.Index, Count); Position := No_Element; end Delete; ------------------ -- Delete_First -- ------------------ procedure Delete_First (Container : in out Vector; Count : Count_Type := 1) is begin if Count = 0 then return; elsif Count >= Length (Container) then Clear (Container); return; else Delete (Container, Index_Type'First, Count); end if; end Delete_First; ----------------- -- Delete_Last -- ----------------- procedure Delete_Last (Container : in out Vector; Count : Count_Type := 1) is begin -- It is not permitted to delete items while the container is busy (for -- example, we're in the middle of a passive iteration). However, we -- always treat deleting 0 items as a no-op, even when we're busy, so we -- simply return without checking. if Count = 0 then return; end if; -- The tampering bits exist to prevent an item from being deleted (or -- otherwise harmfully manipulated) while it is being visited. Query, -- Update, and Iterate increment the busy count on entry, and decrement -- the count on exit. Delete_Last checks the count to determine whether -- it is being called while the associated callback procedure is -- executing. TC_Check (Container.TC); -- There is no restriction on how large Count can be when deleting -- items. If it is equal or greater than the current length, then this -- is equivalent to clearing the vector. (In particular, there's no need -- for us to actually calculate the new value for Last.) -- If the requested count is less than the current length, then we must -- calculate the new value for Last. For the type we use the widest of -- Index_Type'Base and Count_Type'Base for the intermediate values of -- our calculation. (See the comments in Length for more information.) if Count >= Container.Length then Container.Last := No_Index; elsif Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then Container.Last := Container.Last - Index_Type'Base (Count); else Container.Last := Index_Type'Base (Count_Type'Base (Container.Last) - Count); end if; end Delete_Last; ------------- -- Element -- ------------- function Element (Container : Vector; Index : Index_Type) return Element_Type is begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; else return Container.Elements (To_Array_Index (Index)); end if; end Element; function Element (Position : Cursor) return Element_Type is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; else return Position.Container.Element (Position.Index); end if; end Element; -------------- -- Finalize -- -------------- procedure Finalize (Object : in out Iterator) is begin Unbusy (Object.Container.TC); end Finalize; ---------- -- Find -- ---------- function Find (Container : Vector; Item : Element_Type; Position : Cursor := No_Element) return Cursor is begin if Position.Container /= null then if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; if Checks and then Position.Index > Container.Last then raise Program_Error with "Position index is out of range"; end if; end if; -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. declare Lock : With_Lock (Container.TC'Unrestricted_Access); begin for J in Position.Index .. Container.Last loop if Container.Elements (To_Array_Index (J)) = Item then return Cursor'(Container'Unrestricted_Access, J); end if; end loop; return No_Element; end; end Find; ---------------- -- Find_Index -- ---------------- function Find_Index (Container : Vector; Item : Element_Type; Index : Index_Type := Index_Type'First) return Extended_Index is -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. Lock : With_Lock (Container.TC'Unrestricted_Access); begin for Indx in Index .. Container.Last loop if Container.Elements (To_Array_Index (Indx)) = Item then return Indx; end if; end loop; return No_Index; end Find_Index; ----------- -- First -- ----------- function First (Container : Vector) return Cursor is begin if Is_Empty (Container) then return No_Element; else return (Container'Unrestricted_Access, Index_Type'First); end if; end First; function First (Object : Iterator) return Cursor is begin -- The value of the iterator object's Index component influences the -- behavior of the First (and Last) selector function. -- When the Index component is No_Index, this means the iterator -- object was constructed without a start expression, in which case the -- (forward) iteration starts from the (logical) beginning of the entire -- sequence of items (corresponding to Container.First, for a forward -- iterator). -- Otherwise, this is iteration over a partial sequence of items. -- When the Index component isn't No_Index, the iterator object was -- constructed with a start expression, that specifies the position -- from which the (forward) partial iteration begins. if Object.Index = No_Index then return First (Object.Container.all); else return Cursor'(Object.Container, Object.Index); end if; end First; ------------------- -- First_Element -- ------------------- function First_Element (Container : Vector) return Element_Type is begin if Checks and then Container.Last = No_Index then raise Constraint_Error with "Container is empty"; end if; return Container.Elements (To_Array_Index (Index_Type'First)); end First_Element; ----------------- -- First_Index -- ----------------- function First_Index (Container : Vector) return Index_Type is pragma Unreferenced (Container); begin return Index_Type'First; end First_Index; --------------------- -- Generic_Sorting -- --------------------- package body Generic_Sorting is --------------- -- Is_Sorted -- --------------- function Is_Sorted (Container : Vector) return Boolean is begin if Container.Last <= Index_Type'First then return True; end if; -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. declare Lock : With_Lock (Container.TC'Unrestricted_Access); EA : Elements_Array renames Container.Elements; begin for J in 1 .. Container.Length - 1 loop if EA (J + 1) < EA (J) then return False; end if; end loop; return True; end; end Is_Sorted; ----------- -- Merge -- ----------- procedure Merge (Target, Source : in out Vector) is I, J : Count_Type; begin -- The semantics of Merge changed slightly per AI05-0021. It was -- originally the case that if Target and Source denoted the same -- container object, then the GNAT implementation of Merge did -- nothing. However, it was argued that RM05 did not precisely -- specify the semantics for this corner case. The decision of the -- ARG was that if Target and Source denote the same non-empty -- container object, then Program_Error is raised. if Source.Is_Empty then return; end if; if Checks and then Target'Address = Source'Address then raise Program_Error with "Target and Source denote same non-empty container"; end if; if Target.Is_Empty then Move (Target => Target, Source => Source); return; end if; TC_Check (Source.TC); I := Target.Length; Target.Set_Length (I + Source.Length); -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. declare TA : Elements_Array renames Target.Elements; SA : Elements_Array renames Source.Elements; Lock_Target : With_Lock (Target.TC'Unchecked_Access); Lock_Source : With_Lock (Source.TC'Unchecked_Access); begin J := Target.Length; while not Source.Is_Empty loop pragma Assert (Source.Length <= 1 or else not (SA (Source.Length) < SA (Source.Length - 1))); if I = 0 then TA (1 .. J) := SA (1 .. Source.Length); Source.Last := No_Index; exit; end if; pragma Assert (I <= 1 or else not (TA (I) < TA (I - 1))); if SA (Source.Length) < TA (I) then TA (J) := TA (I); I := I - 1; else TA (J) := SA (Source.Length); Source.Last := Source.Last - 1; end if; J := J - 1; end loop; end; end Merge; ---------- -- Sort -- ---------- procedure Sort (Container : in out Vector) is procedure Sort is new Generic_Array_Sort (Index_Type => Count_Type, Element_Type => Element_Type, Array_Type => Elements_Array, "<" => "<"); begin if Container.Last <= Index_Type'First then return; end if; -- The exception behavior for the vector container must match that -- for the list container, so we check for cursor tampering here -- (which will catch more things) instead of for element tampering -- (which will catch fewer things). It's true that the elements of -- this vector container could be safely moved around while (say) an -- iteration is taking place (iteration only increments the busy -- counter), and so technically all we would need here is a test for -- element tampering (indicated by the lock counter), that's simply -- an artifact of our array-based implementation. Logically Sort -- requires a check for cursor tampering. TC_Check (Container.TC); -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. declare Lock : With_Lock (Container.TC'Unchecked_Access); begin Sort (Container.Elements (1 .. Container.Length)); end; end Sort; end Generic_Sorting; ------------------------ -- Get_Element_Access -- ------------------------ function Get_Element_Access (Position : Cursor) return not null Element_Access is begin return Position.Container.Elements (To_Array_Index (Position.Index))'Access; end Get_Element_Access; ----------------- -- Has_Element -- ----------------- function Has_Element (Position : Cursor) return Boolean is begin if Position.Container = null then return False; end if; return Position.Index <= Position.Container.Last; end Has_Element; ------------ -- Insert -- ------------ procedure Insert (Container : in out Vector; Before : Extended_Index; New_Item : Element_Type; Count : Count_Type := 1) is EA : Elements_Array renames Container.Elements; Old_Length : constant Count_Type := Container.Length; Max_Length : Count_Type'Base; -- determined from range of Index_Type New_Length : Count_Type'Base; -- sum of current length and Count Index : Index_Type'Base; -- scratch for intermediate values J : Count_Type'Base; -- scratch begin -- As a precondition on the generic actual Index_Type, the base type -- must include Index_Type'Pred (Index_Type'First); this is the value -- that Container.Last assumes when the vector is empty. However, we do -- not allow that as the value for Index when specifying where the new -- items should be inserted, so we must manually check. (That the user -- is allowed to specify the value at all here is a consequence of the -- declaration of the Extended_Index subtype, which includes the values -- in the base range that immediately precede and immediately follow the -- values in the Index_Type.) if Checks and then Before < Index_Type'First then raise Constraint_Error with "Before index is out of range (too small)"; end if; -- We do allow a value greater than Container.Last to be specified as -- the Index, but only if it's immediately greater. This allows for the -- case of appending items to the back end of the vector. (It is assumed -- that specifying an index value greater than Last + 1 indicates some -- deeper flaw in the caller's algorithm, so that case is treated as a -- proper error.) if Checks and then Before > Container.Last and then Before > Container.Last + 1 then raise Constraint_Error with "Before index is out of range (too large)"; end if; -- We treat inserting 0 items into the container as a no-op, even when -- the container is busy, so we simply return. if Count = 0 then return; end if; -- There are two constraints we need to satisfy. The first constraint is -- that a container cannot have more than Count_Type'Last elements, so -- we must check the sum of the current length and the insertion -- count. Note that we cannot simply add these values, because of the -- possibility of overflow. if Checks and then Old_Length > Count_Type'Last - Count then raise Constraint_Error with "Count is out of range"; end if; -- It is now safe compute the length of the new vector, without fear of -- overflow. New_Length := Old_Length + Count; -- The second constraint is that the new Last index value cannot exceed -- Index_Type'Last. In each branch below, we calculate the maximum -- length (computed from the range of values in Index_Type), and then -- compare the new length to the maximum length. If the new length is -- acceptable, then we compute the new last index from that. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then -- We have to handle the case when there might be more values in the -- range of Index_Type than in the range of Count_Type. if Index_Type'First <= 0 then -- We know that No_Index (the same as Index_Type'First - 1) is -- less than 0, so it is safe to compute the following sum without -- fear of overflow. Index := No_Index + Index_Type'Base (Count_Type'Last); if Index <= Index_Type'Last then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the -- maximum number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than in Count_Type, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last - No_Index); end if; else -- No_Index is equal or greater than 0, so we can safely compute -- the difference without fear of overflow (which we would have to -- worry about if No_Index were less than 0, but that case is -- handled above). if Index_Type'Last - No_Index >= Count_Type'Pos (Count_Type'Last) then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the -- maximum number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than in Count_Type, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last - No_Index); end if; end if; elsif Index_Type'First <= 0 then -- We know that No_Index (the same as Index_Type'First - 1) is less -- than 0, so it is safe to compute the following sum without fear of -- overflow. J := Count_Type'Base (No_Index) + Count_Type'Last; if J <= Count_Type'Base (Index_Type'Last) then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the maximum -- number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than Count_Type does, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last) - Count_Type'Base (No_Index); end if; else -- No_Index is equal or greater than 0, so we can safely compute the -- difference without fear of overflow (which we would have to worry -- about if No_Index were less than 0, but that case is handled -- above). Max_Length := Count_Type'Base (Index_Type'Last) - Count_Type'Base (No_Index); end if; -- We have just computed the maximum length (number of items). We must -- now compare the requested length to the maximum length, as we do not -- allow a vector expand beyond the maximum (because that would create -- an internal array with a last index value greater than -- Index_Type'Last, with no way to index those elements). if Checks and then New_Length > Max_Length then raise Constraint_Error with "Count is out of range"; end if; -- The tampering bits exist to prevent an item from being harmfully -- manipulated while it is being visited. Query, Update, and Iterate -- increment the busy count on entry, and decrement the count on -- exit. Insert checks the count to determine whether it is being called -- while the associated callback procedure is executing. TC_Check (Container.TC); if Checks and then New_Length > Container.Capacity then raise Capacity_Error with "New length is larger than capacity"; end if; J := To_Array_Index (Before); if Before > Container.Last then -- The new items are being appended to the vector, so no -- sliding of existing elements is required. EA (J .. New_Length) := (others => New_Item); else -- The new items are being inserted before some existing -- elements, so we must slide the existing elements up to their -- new home. EA (J + Count .. New_Length) := EA (J .. Old_Length); EA (J .. J + Count - 1) := (others => New_Item); end if; if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then Container.Last := No_Index + Index_Type'Base (New_Length); else Container.Last := Index_Type'Base (Count_Type'Base (No_Index) + New_Length); end if; end Insert; procedure Insert (Container : in out Vector; Before : Extended_Index; New_Item : Vector) is N : constant Count_Type := Length (New_Item); B : Count_Type; -- index Before converted to Count_Type begin -- Use Insert_Space to create the "hole" (the destination slice) into -- which we copy the source items. Insert_Space (Container, Before, Count => N); if N = 0 then -- There's nothing else to do here (vetting of parameters was -- performed already in Insert_Space), so we simply return. return; end if; B := To_Array_Index (Before); if Container'Address /= New_Item'Address then -- This is the simple case. New_Item denotes an object different -- from Container, so there's nothing special we need to do to copy -- the source items to their destination, because all of the source -- items are contiguous. Container.Elements (B .. B + N - 1) := New_Item.Elements (1 .. N); return; end if; -- We refer to array index value Before + N - 1 as J. This is the last -- index value of the destination slice. -- New_Item denotes the same object as Container, so an insertion has -- potentially split the source items. The destination is always the -- range [Before, J], but the source is [Index_Type'First, Before) and -- (J, Container.Last]. We perform the copy in two steps, using each of -- the two slices of the source items. declare subtype Src_Index_Subtype is Count_Type'Base range 1 .. B - 1; Src : Elements_Array renames Container.Elements (Src_Index_Subtype); begin -- We first copy the source items that precede the space we -- inserted. (If Before equals Index_Type'First, then this first -- source slice will be empty, which is harmless.) Container.Elements (B .. B + Src'Length - 1) := Src; end; declare subtype Src_Index_Subtype is Count_Type'Base range B + N .. Container.Length; Src : Elements_Array renames Container.Elements (Src_Index_Subtype); begin -- We next copy the source items that follow the space we inserted. Container.Elements (B + N - Src'Length .. B + N - 1) := Src; end; end Insert; procedure Insert (Container : in out Vector; Before : Cursor; New_Item : Vector) is Index : Index_Type'Base; begin if Checks and then Before.Container /= null and then Before.Container /= Container'Unchecked_Access then raise Program_Error with "Before cursor denotes wrong container"; end if; if Is_Empty (New_Item) then return; end if; if Before.Container = null or else Before.Index > Container.Last then if Checks and then Container.Last = Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Index := Container.Last + 1; else Index := Before.Index; end if; Insert (Container, Index, New_Item); end Insert; procedure Insert (Container : in out Vector; Before : Cursor; New_Item : Vector; Position : out Cursor) is Index : Index_Type'Base; begin if Checks and then Before.Container /= null and then Before.Container /= Container'Unchecked_Access then raise Program_Error with "Before cursor denotes wrong container"; end if; if Is_Empty (New_Item) then if Before.Container = null or else Before.Index > Container.Last then Position := No_Element; else Position := (Container'Unchecked_Access, Before.Index); end if; return; end if; if Before.Container = null or else Before.Index > Container.Last then if Checks and then Container.Last = Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Index := Container.Last + 1; else Index := Before.Index; end if; Insert (Container, Index, New_Item); Position := Cursor'(Container'Unchecked_Access, Index); end Insert; procedure Insert (Container : in out Vector; Before : Cursor; New_Item : Element_Type; Count : Count_Type := 1) is Index : Index_Type'Base; begin if Checks and then Before.Container /= null and then Before.Container /= Container'Unchecked_Access then raise Program_Error with "Before cursor denotes wrong container"; end if; if Count = 0 then return; end if; if Before.Container = null or else Before.Index > Container.Last then if Checks and then Container.Last = Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Index := Container.Last + 1; else Index := Before.Index; end if; Insert (Container, Index, New_Item, Count); end Insert; procedure Insert (Container : in out Vector; Before : Cursor; New_Item : Element_Type; Position : out Cursor; Count : Count_Type := 1) is Index : Index_Type'Base; begin if Checks and then Before.Container /= null and then Before.Container /= Container'Unchecked_Access then raise Program_Error with "Before cursor denotes wrong container"; end if; if Count = 0 then if Before.Container = null or else Before.Index > Container.Last then Position := No_Element; else Position := (Container'Unchecked_Access, Before.Index); end if; return; end if; if Before.Container = null or else Before.Index > Container.Last then if Checks and then Container.Last = Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Index := Container.Last + 1; else Index := Before.Index; end if; Insert (Container, Index, New_Item, Count); Position := Cursor'(Container'Unchecked_Access, Index); end Insert; procedure Insert (Container : in out Vector; Before : Extended_Index; Count : Count_Type := 1) is New_Item : Element_Type; -- Default-initialized value pragma Warnings (Off, New_Item); begin Insert (Container, Before, New_Item, Count); end Insert; procedure Insert (Container : in out Vector; Before : Cursor; Position : out Cursor; Count : Count_Type := 1) is New_Item : Element_Type; -- Default-initialized value pragma Warnings (Off, New_Item); begin Insert (Container, Before, New_Item, Position, Count); end Insert; ------------------ -- Insert_Space -- ------------------ procedure Insert_Space (Container : in out Vector; Before : Extended_Index; Count : Count_Type := 1) is EA : Elements_Array renames Container.Elements; Old_Length : constant Count_Type := Container.Length; Max_Length : Count_Type'Base; -- determined from range of Index_Type New_Length : Count_Type'Base; -- sum of current length and Count Index : Index_Type'Base; -- scratch for intermediate values J : Count_Type'Base; -- scratch begin -- As a precondition on the generic actual Index_Type, the base type -- must include Index_Type'Pred (Index_Type'First); this is the value -- that Container.Last assumes when the vector is empty. However, we do -- not allow that as the value for Index when specifying where the new -- items should be inserted, so we must manually check. (That the user -- is allowed to specify the value at all here is a consequence of the -- declaration of the Extended_Index subtype, which includes the values -- in the base range that immediately precede and immediately follow the -- values in the Index_Type.) if Checks and then Before < Index_Type'First then raise Constraint_Error with "Before index is out of range (too small)"; end if; -- We do allow a value greater than Container.Last to be specified as -- the Index, but only if it's immediately greater. This allows for the -- case of appending items to the back end of the vector. (It is assumed -- that specifying an index value greater than Last + 1 indicates some -- deeper flaw in the caller's algorithm, so that case is treated as a -- proper error.) if Checks and then Before > Container.Last and then Before > Container.Last + 1 then raise Constraint_Error with "Before index is out of range (too large)"; end if; -- We treat inserting 0 items into the container as a no-op, even when -- the container is busy, so we simply return. if Count = 0 then return; end if; -- There are two constraints we need to satisfy. The first constraint is -- that a container cannot have more than Count_Type'Last elements, so -- we must check the sum of the current length and the insertion count. -- Note that we cannot simply add these values, because of the -- possibility of overflow. if Checks and then Old_Length > Count_Type'Last - Count then raise Constraint_Error with "Count is out of range"; end if; -- It is now safe compute the length of the new vector, without fear of -- overflow. New_Length := Old_Length + Count; -- The second constraint is that the new Last index value cannot exceed -- Index_Type'Last. In each branch below, we calculate the maximum -- length (computed from the range of values in Index_Type), and then -- compare the new length to the maximum length. If the new length is -- acceptable, then we compute the new last index from that. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then -- We have to handle the case when there might be more values in the -- range of Index_Type than in the range of Count_Type. if Index_Type'First <= 0 then -- We know that No_Index (the same as Index_Type'First - 1) is -- less than 0, so it is safe to compute the following sum without -- fear of overflow. Index := No_Index + Index_Type'Base (Count_Type'Last); if Index <= Index_Type'Last then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the -- maximum number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than in Count_Type, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last - No_Index); end if; else -- No_Index is equal or greater than 0, so we can safely compute -- the difference without fear of overflow (which we would have to -- worry about if No_Index were less than 0, but that case is -- handled above). if Index_Type'Last - No_Index >= Count_Type'Pos (Count_Type'Last) then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the -- maximum number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than in Count_Type, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last - No_Index); end if; end if; elsif Index_Type'First <= 0 then -- We know that No_Index (the same as Index_Type'First - 1) is less -- than 0, so it is safe to compute the following sum without fear of -- overflow. J := Count_Type'Base (No_Index) + Count_Type'Last; if J <= Count_Type'Base (Index_Type'Last) then -- We have determined that range of Index_Type has at least as -- many values as in Count_Type, so Count_Type'Last is the maximum -- number of items that are allowed. Max_Length := Count_Type'Last; else -- The range of Index_Type has fewer values than Count_Type does, -- so the maximum number of items is computed from the range of -- the Index_Type. Max_Length := Count_Type'Base (Index_Type'Last) - Count_Type'Base (No_Index); end if; else -- No_Index is equal or greater than 0, so we can safely compute the -- difference without fear of overflow (which we would have to worry -- about if No_Index were less than 0, but that case is handled -- above). Max_Length := Count_Type'Base (Index_Type'Last) - Count_Type'Base (No_Index); end if; -- We have just computed the maximum length (number of items). We must -- now compare the requested length to the maximum length, as we do not -- allow a vector expand beyond the maximum (because that would create -- an internal array with a last index value greater than -- Index_Type'Last, with no way to index those elements). if Checks and then New_Length > Max_Length then raise Constraint_Error with "Count is out of range"; end if; -- The tampering bits exist to prevent an item from being harmfully -- manipulated while it is being visited. Query, Update, and Iterate -- increment the busy count on entry, and decrement the count on -- exit. Insert checks the count to determine whether it is being called -- while the associated callback procedure is executing. TC_Check (Container.TC); -- An internal array has already been allocated, so we need to check -- whether there is enough unused storage for the new items. if Checks and then New_Length > Container.Capacity then raise Capacity_Error with "New length is larger than capacity"; end if; -- In this case, we're inserting space into a vector that has already -- allocated an internal array, and the existing array has enough -- unused storage for the new items. if Before <= Container.Last then -- The space is being inserted before some existing elements, -- so we must slide the existing elements up to their new home. J := To_Array_Index (Before); EA (J + Count .. New_Length) := EA (J .. Old_Length); end if; -- New_Last is the last index value of the items in the container after -- insertion. Use the wider of Index_Type'Base and Count_Type'Base to -- compute its value from the New_Length. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then Container.Last := No_Index + Index_Type'Base (New_Length); else Container.Last := Index_Type'Base (Count_Type'Base (No_Index) + New_Length); end if; end Insert_Space; procedure Insert_Space (Container : in out Vector; Before : Cursor; Position : out Cursor; Count : Count_Type := 1) is Index : Index_Type'Base; begin if Checks and then Before.Container /= null and then Before.Container /= Container'Unchecked_Access then raise Program_Error with "Before cursor denotes wrong container"; end if; if Count = 0 then if Before.Container = null or else Before.Index > Container.Last then Position := No_Element; else Position := (Container'Unchecked_Access, Before.Index); end if; return; end if; if Before.Container = null or else Before.Index > Container.Last then if Checks and then Container.Last = Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; end if; Index := Container.Last + 1; else Index := Before.Index; end if; Insert_Space (Container, Index, Count => Count); Position := Cursor'(Container'Unchecked_Access, Index); end Insert_Space; -------------- -- Is_Empty -- -------------- function Is_Empty (Container : Vector) return Boolean is begin return Container.Last < Index_Type'First; end Is_Empty; ------------- -- Iterate -- ------------- procedure Iterate (Container : Vector; Process : not null access procedure (Position : Cursor)) is Busy : With_Busy (Container.TC'Unrestricted_Access); begin for Indx in Index_Type'First .. Container.Last loop Process (Cursor'(Container'Unrestricted_Access, Indx)); end loop; end Iterate; function Iterate (Container : Vector) return Vector_Iterator_Interfaces.Reversible_Iterator'Class is V : constant Vector_Access := Container'Unrestricted_Access; begin -- The value of its Index component influences the behavior of the First -- and Last selector functions of the iterator object. When the Index -- component is No_Index (as is the case here), this means the iterator -- object was constructed without a start expression. This is a complete -- iterator, meaning that the iteration starts from the (logical) -- beginning of the sequence of items. -- Note: For a forward iterator, Container.First is the beginning, and -- for a reverse iterator, Container.Last is the beginning. return It : constant Iterator := (Limited_Controlled with Container => V, Index => No_Index) do Busy (Container.TC'Unrestricted_Access.all); end return; end Iterate; function Iterate (Container : Vector; Start : Cursor) return Vector_Iterator_Interfaces.Reversible_Iterator'Class is V : constant Vector_Access := Container'Unrestricted_Access; begin -- It was formerly the case that when Start = No_Element, the partial -- iterator was defined to behave the same as for a complete iterator, -- and iterate over the entire sequence of items. However, those -- semantics were unintuitive and arguably error-prone (it is too easy -- to accidentally create an endless loop), and so they were changed, -- per the ARG meeting in Denver on 2011/11. However, there was no -- consensus about what positive meaning this corner case should have, -- and so it was decided to simply raise an exception. This does imply, -- however, that it is not possible to use a partial iterator to specify -- an empty sequence of items. if Checks and then Start.Container = null then raise Constraint_Error with "Start position for iterator equals No_Element"; end if; if Checks and then Start.Container /= V then raise Program_Error with "Start cursor of Iterate designates wrong vector"; end if; if Checks and then Start.Index > V.Last then raise Constraint_Error with "Start position for iterator equals No_Element"; end if; -- The value of its Index component influences the behavior of the First -- and Last selector functions of the iterator object. When the Index -- component is not No_Index (as is the case here), it means that this -- is a partial iteration, over a subset of the complete sequence of -- items. The iterator object was constructed with a start expression, -- indicating the position from which the iteration begins. Note that -- the start position has the same value irrespective of whether this is -- a forward or reverse iteration. return It : constant Iterator := (Limited_Controlled with Container => V, Index => Start.Index) do Busy (Container.TC'Unrestricted_Access.all); end return; end Iterate; ---------- -- Last -- ---------- function Last (Container : Vector) return Cursor is begin if Is_Empty (Container) then return No_Element; else return (Container'Unrestricted_Access, Container.Last); end if; end Last; function Last (Object : Iterator) return Cursor is begin -- The value of the iterator object's Index component influences the -- behavior of the Last (and First) selector function. -- When the Index component is No_Index, this means the iterator object -- was constructed without a start expression, in which case the -- (reverse) iteration starts from the (logical) beginning of the entire -- sequence (corresponding to Container.Last, for a reverse iterator). -- Otherwise, this is iteration over a partial sequence of items. When -- the Index component is not No_Index, the iterator object was -- constructed with a start expression, that specifies the position from -- which the (reverse) partial iteration begins. if Object.Index = No_Index then return Last (Object.Container.all); else return Cursor'(Object.Container, Object.Index); end if; end Last; ------------------ -- Last_Element -- ------------------ function Last_Element (Container : Vector) return Element_Type is begin if Checks and then Container.Last = No_Index then raise Constraint_Error with "Container is empty"; end if; return Container.Elements (Container.Length); end Last_Element; ---------------- -- Last_Index -- ---------------- function Last_Index (Container : Vector) return Extended_Index is begin return Container.Last; end Last_Index; ------------ -- Length -- ------------ function Length (Container : Vector) return Count_Type is L : constant Index_Type'Base := Container.Last; F : constant Index_Type := Index_Type'First; begin -- The base range of the index type (Index_Type'Base) might not include -- all values for length (Count_Type). Contrariwise, the index type -- might include values outside the range of length. Hence we use -- whatever type is wider for intermediate values when calculating -- length. Note that no matter what the index type is, the maximum -- length to which a vector is allowed to grow is always the minimum -- of Count_Type'Last and (IT'Last - IT'First + 1). -- For example, an Index_Type with range -127 .. 127 is only guaranteed -- to have a base range of -128 .. 127, but the corresponding vector -- would have lengths in the range 0 .. 255. In this case we would need -- to use Count_Type'Base for intermediate values. -- Another case would be the index range -2**63 + 1 .. -2**63 + 10. The -- vector would have a maximum length of 10, but the index values lie -- outside the range of Count_Type (which is only 32 bits). In this -- case we would need to use Index_Type'Base for intermediate values. if Count_Type'Base'Last >= Index_Type'Pos (Index_Type'Base'Last) then return Count_Type'Base (L) - Count_Type'Base (F) + 1; else return Count_Type (L - F + 1); end if; end Length; ---------- -- Move -- ---------- procedure Move (Target : in out Vector; Source : in out Vector) is begin if Target'Address = Source'Address then return; end if; if Checks and then Target.Capacity < Source.Length then raise Capacity_Error -- ??? with "Target capacity is less than Source length"; end if; TC_Check (Target.TC); TC_Check (Source.TC); -- Clear Target now, in case element assignment fails Target.Last := No_Index; Target.Elements (1 .. Source.Length) := Source.Elements (1 .. Source.Length); Target.Last := Source.Last; Source.Last := No_Index; end Move; ---------- -- Next -- ---------- function Next (Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; elsif Position.Index < Position.Container.Last then return (Position.Container, Position.Index + 1); else return No_Element; end if; end Next; function Next (Object : Iterator; Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; end if; if Checks and then Position.Container /= Object.Container then raise Program_Error with "Position cursor of Next designates wrong vector"; end if; return Next (Position); end Next; procedure Next (Position : in out Cursor) is begin if Position.Container = null then return; elsif Position.Index < Position.Container.Last then Position.Index := Position.Index + 1; else Position := No_Element; end if; end Next; ------------- -- Prepend -- ------------- procedure Prepend (Container : in out Vector; New_Item : Vector) is begin Insert (Container, Index_Type'First, New_Item); end Prepend; procedure Prepend (Container : in out Vector; New_Item : Element_Type; Count : Count_Type := 1) is begin Insert (Container, Index_Type'First, New_Item, Count); end Prepend; -------------- -- Previous -- -------------- procedure Previous (Position : in out Cursor) is begin if Position.Container = null then return; elsif Position.Index > Index_Type'First then Position.Index := Position.Index - 1; else Position := No_Element; end if; end Previous; function Previous (Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; elsif Position.Index > Index_Type'First then return (Position.Container, Position.Index - 1); else return No_Element; end if; end Previous; function Previous (Object : Iterator; Position : Cursor) return Cursor is begin if Position.Container = null then return No_Element; end if; if Checks and then Position.Container /= Object.Container then raise Program_Error with "Position cursor of Previous designates wrong vector"; end if; return Previous (Position); end Previous; ---------------------- -- Pseudo_Reference -- ---------------------- function Pseudo_Reference (Container : aliased Vector'Class) return Reference_Control_Type is TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access; begin return R : constant Reference_Control_Type := (Controlled with TC) do Lock (TC.all); end return; end Pseudo_Reference; ------------------- -- Query_Element -- ------------------- procedure Query_Element (Container : Vector; Index : Index_Type; Process : not null access procedure (Element : Element_Type)) is Lock : With_Lock (Container.TC'Unrestricted_Access); V : Vector renames Container'Unrestricted_Access.all; begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; end if; Process (V.Elements (To_Array_Index (Index))); end Query_Element; procedure Query_Element (Position : Cursor; Process : not null access procedure (Element : Element_Type)) is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; Query_Element (Position.Container.all, Position.Index, Process); end Query_Element; ---------- -- Read -- ---------- procedure Read (Stream : not null access Root_Stream_Type'Class; Container : out Vector) is Length : Count_Type'Base; Last : Index_Type'Base := No_Index; begin Clear (Container); Count_Type'Base'Read (Stream, Length); Reserve_Capacity (Container, Capacity => Length); for Idx in Count_Type range 1 .. Length loop Last := Last + 1; Element_Type'Read (Stream, Container.Elements (Idx)); Container.Last := Last; end loop; end Read; procedure Read (Stream : not null access Root_Stream_Type'Class; Position : out Cursor) is begin raise Program_Error with "attempt to stream vector cursor"; end Read; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Reference_Type) is begin raise Program_Error with "attempt to stream reference"; end Read; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Constant_Reference_Type) is begin raise Program_Error with "attempt to stream reference"; end Read; --------------- -- Reference -- --------------- function Reference (Container : aliased in out Vector; Position : Cursor) return Reference_Type is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; if Checks and then Position.Index > Position.Container.Last then raise Constraint_Error with "Position cursor is out of range"; end if; declare A : Elements_Array renames Container.Elements; J : constant Count_Type := To_Array_Index (Position.Index); TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access; begin return R : constant Reference_Type := (Element => A (J)'Access, Control => (Controlled with TC)) do Lock (TC.all); end return; end; end Reference; function Reference (Container : aliased in out Vector; Index : Index_Type) return Reference_Type is begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; end if; declare A : Elements_Array renames Container.Elements; J : constant Count_Type := To_Array_Index (Index); TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access; begin return R : constant Reference_Type := (Element => A (J)'Access, Control => (Controlled with TC)) do Lock (TC.all); end return; end; end Reference; --------------------- -- Replace_Element -- --------------------- procedure Replace_Element (Container : in out Vector; Index : Index_Type; New_Item : Element_Type) is begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; end if; TE_Check (Container.TC); Container.Elements (To_Array_Index (Index)) := New_Item; end Replace_Element; procedure Replace_Element (Container : in out Vector; Position : Cursor; New_Item : Element_Type) is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; if Checks and then Position.Index > Container.Last then raise Constraint_Error with "Position cursor is out of range"; end if; TE_Check (Container.TC); Container.Elements (To_Array_Index (Position.Index)) := New_Item; end Replace_Element; ---------------------- -- Reserve_Capacity -- ---------------------- procedure Reserve_Capacity (Container : in out Vector; Capacity : Count_Type) is begin if Checks and then Capacity > Container.Capacity then raise Capacity_Error with "Capacity is out of range"; end if; end Reserve_Capacity; ---------------------- -- Reverse_Elements -- ---------------------- procedure Reverse_Elements (Container : in out Vector) is E : Elements_Array renames Container.Elements; Idx : Count_Type; Jdx : Count_Type; begin if Container.Length <= 1 then return; end if; -- The exception behavior for the vector container must match that for -- the list container, so we check for cursor tampering here (which will -- catch more things) instead of for element tampering (which will catch -- fewer things). It's true that the elements of this vector container -- could be safely moved around while (say) an iteration is taking place -- (iteration only increments the busy counter), and so technically -- all we would need here is a test for element tampering (indicated -- by the lock counter), that's simply an artifact of our array-based -- implementation. Logically Reverse_Elements requires a check for -- cursor tampering. TC_Check (Container.TC); Idx := 1; Jdx := Container.Length; while Idx < Jdx loop declare EI : constant Element_Type := E (Idx); begin E (Idx) := E (Jdx); E (Jdx) := EI; end; Idx := Idx + 1; Jdx := Jdx - 1; end loop; end Reverse_Elements; ------------------ -- Reverse_Find -- ------------------ function Reverse_Find (Container : Vector; Item : Element_Type; Position : Cursor := No_Element) return Cursor is Last : Index_Type'Base; begin if Checks and then Position.Container /= null and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; Last := (if Position.Container = null or else Position.Index > Container.Last then Container.Last else Position.Index); -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. declare Lock : With_Lock (Container.TC'Unrestricted_Access); begin for Indx in reverse Index_Type'First .. Last loop if Container.Elements (To_Array_Index (Indx)) = Item then return Cursor'(Container'Unrestricted_Access, Indx); end if; end loop; return No_Element; end; end Reverse_Find; ------------------------ -- Reverse_Find_Index -- ------------------------ function Reverse_Find_Index (Container : Vector; Item : Element_Type; Index : Index_Type := Index_Type'Last) return Extended_Index is -- Per AI05-0022, the container implementation is required to detect -- element tampering by a generic actual subprogram. Lock : With_Lock (Container.TC'Unrestricted_Access); Last : constant Index_Type'Base := Index_Type'Min (Container.Last, Index); begin for Indx in reverse Index_Type'First .. Last loop if Container.Elements (To_Array_Index (Indx)) = Item then return Indx; end if; end loop; return No_Index; end Reverse_Find_Index; --------------------- -- Reverse_Iterate -- --------------------- procedure Reverse_Iterate (Container : Vector; Process : not null access procedure (Position : Cursor)) is Busy : With_Busy (Container.TC'Unrestricted_Access); begin for Indx in reverse Index_Type'First .. Container.Last loop Process (Cursor'(Container'Unrestricted_Access, Indx)); end loop; end Reverse_Iterate; ---------------- -- Set_Length -- ---------------- procedure Set_Length (Container : in out Vector; Length : Count_Type) is Count : constant Count_Type'Base := Container.Length - Length; begin -- Set_Length allows the user to set the length explicitly, instead of -- implicitly as a side-effect of deletion or insertion. If the -- requested length is less than the current length, this is equivalent -- to deleting items from the back end of the vector. If the requested -- length is greater than the current length, then this is equivalent to -- inserting "space" (nonce items) at the end. if Count >= 0 then Container.Delete_Last (Count); elsif Checks and then Container.Last >= Index_Type'Last then raise Constraint_Error with "vector is already at its maximum length"; else Container.Insert_Space (Container.Last + 1, -Count); end if; end Set_Length; ---------- -- Swap -- ---------- procedure Swap (Container : in out Vector; I, J : Index_Type) is E : Elements_Array renames Container.Elements; begin if Checks and then I > Container.Last then raise Constraint_Error with "I index is out of range"; end if; if Checks and then J > Container.Last then raise Constraint_Error with "J index is out of range"; end if; if I = J then return; end if; TE_Check (Container.TC); declare EI_Copy : constant Element_Type := E (To_Array_Index (I)); begin E (To_Array_Index (I)) := E (To_Array_Index (J)); E (To_Array_Index (J)) := EI_Copy; end; end Swap; procedure Swap (Container : in out Vector; I, J : Cursor) is begin if Checks and then I.Container = null then raise Constraint_Error with "I cursor has no element"; end if; if Checks and then J.Container = null then raise Constraint_Error with "J cursor has no element"; end if; if Checks and then I.Container /= Container'Unrestricted_Access then raise Program_Error with "I cursor denotes wrong container"; end if; if Checks and then J.Container /= Container'Unrestricted_Access then raise Program_Error with "J cursor denotes wrong container"; end if; Swap (Container, I.Index, J.Index); end Swap; -------------------- -- To_Array_Index -- -------------------- function To_Array_Index (Index : Index_Type'Base) return Count_Type'Base is Offset : Count_Type'Base; begin -- We know that -- Index >= Index_Type'First -- hence we also know that -- Index - Index_Type'First >= 0 -- The issue is that even though 0 is guaranteed to be a value in -- the type Index_Type'Base, there's no guarantee that the difference -- is a value in that type. To prevent overflow we use the wider -- of Count_Type'Base and Index_Type'Base to perform intermediate -- calculations. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then Offset := Count_Type'Base (Index - Index_Type'First); else Offset := Count_Type'Base (Index) - Count_Type'Base (Index_Type'First); end if; -- The array index subtype for all container element arrays -- always starts with 1. return 1 + Offset; end To_Array_Index; --------------- -- To_Cursor -- --------------- function To_Cursor (Container : Vector; Index : Extended_Index) return Cursor is begin if Index not in Index_Type'First .. Container.Last then return No_Element; end if; return Cursor'(Container'Unrestricted_Access, Index); end To_Cursor; -------------- -- To_Index -- -------------- function To_Index (Position : Cursor) return Extended_Index is begin if Position.Container = null then return No_Index; end if; if Position.Index <= Position.Container.Last then return Position.Index; end if; return No_Index; end To_Index; --------------- -- To_Vector -- --------------- function To_Vector (Length : Count_Type) return Vector is Index : Count_Type'Base; Last : Index_Type'Base; begin if Length = 0 then return Empty_Vector; end if; -- We create a vector object with a capacity that matches the specified -- Length, but we do not allow the vector capacity (the length of the -- internal array) to exceed the number of values in Index_Type'Range -- (otherwise, there would be no way to refer to those components via an -- index). We must therefore check whether the specified Length would -- create a Last index value greater than Index_Type'Last. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then -- We perform a two-part test. First we determine whether the -- computed Last value lies in the base range of the type, and then -- determine whether it lies in the range of the index (sub)type. -- Last must satisfy this relation: -- First + Length - 1 <= Last -- We regroup terms: -- First - 1 <= Last - Length -- Which can rewrite as: -- No_Index <= Last - Length if Checks and then Index_Type'Base'Last - Index_Type'Base (Length) < No_Index then raise Constraint_Error with "Length is out of range"; end if; -- We now know that the computed value of Last is within the base -- range of the type, so it is safe to compute its value: Last := No_Index + Index_Type'Base (Length); -- Finally we test whether the value is within the range of the -- generic actual index subtype: if Checks and then Last > Index_Type'Last then raise Constraint_Error with "Length is out of range"; end if; elsif Index_Type'First <= 0 then -- Here we can compute Last directly, in the normal way. We know that -- No_Index is less than 0, so there is no danger of overflow when -- adding the (positive) value of Length. Index := Count_Type'Base (No_Index) + Length; -- Last if Checks and then Index > Count_Type'Base (Index_Type'Last) then raise Constraint_Error with "Length is out of range"; end if; -- We know that the computed value (having type Count_Type) of Last -- is within the range of the generic actual index subtype, so it is -- safe to convert to Index_Type: Last := Index_Type'Base (Index); else -- Here Index_Type'First (and Index_Type'Last) is positive, so we -- must test the length indirectly (by working backwards from the -- largest possible value of Last), in order to prevent overflow. Index := Count_Type'Base (Index_Type'Last) - Length; -- No_Index if Checks and then Index < Count_Type'Base (No_Index) then raise Constraint_Error with "Length is out of range"; end if; -- We have determined that the value of Length would not create a -- Last index value outside of the range of Index_Type, so we can now -- safely compute its value. Last := Index_Type'Base (Count_Type'Base (No_Index) + Length); end if; return V : Vector (Capacity => Length) do V.Last := Last; end return; end To_Vector; function To_Vector (New_Item : Element_Type; Length : Count_Type) return Vector is Index : Count_Type'Base; Last : Index_Type'Base; begin if Length = 0 then return Empty_Vector; end if; -- We create a vector object with a capacity that matches the specified -- Length, but we do not allow the vector capacity (the length of the -- internal array) to exceed the number of values in Index_Type'Range -- (otherwise, there would be no way to refer to those components via an -- index). We must therefore check whether the specified Length would -- create a Last index value greater than Index_Type'Last. if Index_Type'Base'Last >= Count_Type'Pos (Count_Type'Last) then -- We perform a two-part test. First we determine whether the -- computed Last value lies in the base range of the type, and then -- determine whether it lies in the range of the index (sub)type. -- Last must satisfy this relation: -- First + Length - 1 <= Last -- We regroup terms: -- First - 1 <= Last - Length -- Which can rewrite as: -- No_Index <= Last - Length if Checks and then Index_Type'Base'Last - Index_Type'Base (Length) < No_Index then raise Constraint_Error with "Length is out of range"; end if; -- We now know that the computed value of Last is within the base -- range of the type, so it is safe to compute its value: Last := No_Index + Index_Type'Base (Length); -- Finally we test whether the value is within the range of the -- generic actual index subtype: if Checks and then Last > Index_Type'Last then raise Constraint_Error with "Length is out of range"; end if; elsif Index_Type'First <= 0 then -- Here we can compute Last directly, in the normal way. We know that -- No_Index is less than 0, so there is no danger of overflow when -- adding the (positive) value of Length. Index := Count_Type'Base (No_Index) + Length; -- same value as V.Last if Checks and then Index > Count_Type'Base (Index_Type'Last) then raise Constraint_Error with "Length is out of range"; end if; -- We know that the computed value (having type Count_Type) of Last -- is within the range of the generic actual index subtype, so it is -- safe to convert to Index_Type: Last := Index_Type'Base (Index); else -- Here Index_Type'First (and Index_Type'Last) is positive, so we -- must test the length indirectly (by working backwards from the -- largest possible value of Last), in order to prevent overflow. Index := Count_Type'Base (Index_Type'Last) - Length; -- No_Index if Checks and then Index < Count_Type'Base (No_Index) then raise Constraint_Error with "Length is out of range"; end if; -- We have determined that the value of Length would not create a -- Last index value outside of the range of Index_Type, so we can now -- safely compute its value. Last := Index_Type'Base (Count_Type'Base (No_Index) + Length); end if; return V : Vector (Capacity => Length) do V.Elements := (others => New_Item); V.Last := Last; end return; end To_Vector; -------------------- -- Update_Element -- -------------------- procedure Update_Element (Container : in out Vector; Index : Index_Type; Process : not null access procedure (Element : in out Element_Type)) is Lock : With_Lock (Container.TC'Unchecked_Access); begin if Checks and then Index > Container.Last then raise Constraint_Error with "Index is out of range"; end if; Process (Container.Elements (To_Array_Index (Index))); end Update_Element; procedure Update_Element (Container : in out Vector; Position : Cursor; Process : not null access procedure (Element : in out Element_Type)) is begin if Checks and then Position.Container = null then raise Constraint_Error with "Position cursor has no element"; end if; if Checks and then Position.Container /= Container'Unrestricted_Access then raise Program_Error with "Position cursor denotes wrong container"; end if; Update_Element (Container, Position.Index, Process); end Update_Element; ----------- -- Write -- ----------- procedure Write (Stream : not null access Root_Stream_Type'Class; Container : Vector) is N : Count_Type; begin N := Container.Length; Count_Type'Base'Write (Stream, N); for J in 1 .. N loop Element_Type'Write (Stream, Container.Elements (J)); end loop; end Write; procedure Write (Stream : not null access Root_Stream_Type'Class; Position : Cursor) is begin raise Program_Error with "attempt to stream vector cursor"; end Write; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Reference_Type) is begin raise Program_Error with "attempt to stream reference"; end Write; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Constant_Reference_Type) is begin raise Program_Error with "attempt to stream reference"; end Write; end Ada.Containers.Bounded_Vectors;
{ "source": "starcoderdata", "programming_language": "ada" }
-- 40333139 -- Last Updated on 19th April 2019 -- main.adb with Trident; use Trident; with Ada.Text_IO; use Ada.Text_IO; procedure Main is begin Put_Line("--------------------------------------------------------"); Put_Line(" ___ _ _ "); Put_Line(" / __|_ _| |__ _ __ __ _ _ _(_)_ _ ___ "); Put_Line(" \__ \ || | '_ \ ' \/ _` | '_| | ' \/ -_) "); Put_Line(" |___/\_,_|_.__/_|_|_\__,_|_| |_|_||_\___| "); Put_Line(" ___ _ _ ___ _ "); Put_Line(" / __|___ _ _| |_ _ _ ___| | / __|_ _ __| |_ ___ _ __ "); Put_Line("| (__/ _ \ ' \ _| '_/ _ \ | \__ \ || (_-< _/ -_) ' \ "); Put_Line(" \___\___/_||_\__|_| \___/_| |___/\_, /__/\__\___|_|_|_|"); Put_Line(" |__/ "); Put_Line("--------------------------------------------------------"); Put_Line("Attempting to Start Submarine..."); OperateSubmarine; Put("Is Nuclear Submarine Operational?: "); Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Open both Doors..."); OpenAirlockTwo; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Closing Airlock Door One..."); CloseAirlockOne; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.CloseAirlockOne'Image); Put_Line("Closing Airlock Door Two..."); CloseAirlockTwo; Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.CloseAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put("Is Nuclear Submarine Operational?: "); OperateSubmarine; Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Airlock Door one lock is: "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put("Airlock Door two lock is: "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Locking both Airlock Doors"); LockAirlockOne; LockAirlockTwo; Put("Airlock Door One is: "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put("Airlock Door Two is: "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Open Airlock Door One..."); OpenAirlockOne; Put("Status of Airlock Door one: "); Put(TridentSubmarine.CloseAirlockOne'Image); Put(" and "); Put_Line(TridentSubmarine.LockAirlockOne'Image); Put_Line("Attempting to Open Airlock Door Two..."); OpenAirlockTwo; Put("Status of Airlock Door Two: "); Put(TridentSubmarine.CloseAirlockTwo'Image); Put(" and "); Put_Line(TridentSubmarine.LockAirlockTwo'Image); Put_Line("---------------------------------------------------"); Put("Is Nuclear Submarine Operational?: "); OperateSubmarine; Put_Line(TridentSubmarine.operating'Image); Put("Is Weapons System Available?: "); WeaponsSystemCheck; Put_Line(TridentSubmarine.WeaponsAvailablity'Image); Put_Line("---------------------------------------------------"); Put("Is Weapons System Ready to Fire?: "); ReadyToFire; Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Store Torpedoes..."); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Store; Put(TridentSubmarine.storedTorpedoes'Image); Put(" Torpedo: "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Put("Number of Torpedoes Stored: "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- One; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Two; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Three; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Four; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Five; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); -- Six; Put_Line("Attempting to Load Torpedo..."); Load; Put("Loading Torpedo: "); Put_Line(TridentSubmarine.loaded'Image); Put_Line("Attempting to Fire Torpedo..."); Put("Is Weapons System Ready to Fire?: "); Put_Line(TridentSubmarine.loadedTorpedoes'Image); Fire; Put(TridentSubmarine.firingTorpedoes'Image); Put(" Torpedo! Remaining "); Put_Line(TridentSubmarine.torpedoes'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting to Dive!"); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" at "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put_Line("---------------------------------------------------"); DiveCheck; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" from "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); Put_Line("---------------------------------------------------"); Put_Line("Resurfacing..."); EmergencySurface; Put("Depth Status: "); DepthPosition; Put_Line(TridentSubmarine.depthPositionCheck'Image); DepthTest; Put(TridentSubmarine.diveOperational'Image); Put(" at "); Put(TridentSubmarine.depthRange'Image); Put_Line(" metres..."); Put_Line("---------------------------------------------------"); Put_Line("Attempting Life Support Check!"); DiveCheck; Put("Life Support System: "); --100 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --90 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --80 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --70 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --60 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --50 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --40 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --30 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --20 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --10 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); Put("Life Support System: "); --0 LifeSupportCheck; Put(TridentSubmarine.lifeSupportStatus'Image); OxygenTest; Put(" - Oxygen Percentage: "); Put_Line(TridentSubmarine.oxygenRange'Image); LifeSupportCheck; Put_Line(TridentSubmarine.lifeSupportStatus'Image); Put_Line("---------------------------------------------------"); Put_Line("Attempting Reactor Temperature Check!"); DiveCheck; ReactorCheck; Put_Line("---------------------------------------------------"); end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ -- Very simple reporter to console package AUnit.Reporter.Text is type Text_Reporter is new Reporter with private; procedure Set_Use_ANSI_Colors (Engine : in out Text_Reporter; Value : Boolean); -- Setting this value will enable colors output on an ANSI compatible -- terminal. -- By default, no color is used. procedure Report (Engine : Text_Reporter; R : in out Result'Class; Options : AUnit_Options := Default_Options); procedure Report_OK_Tests (Engine : Text_Reporter; R : in out Result'Class); procedure Report_Fail_Tests (Engine : Text_Reporter; R : in out Result'Class); procedure Report_Error_Tests (Engine : Text_Reporter; R : in out Result'Class); -- These subprograms implement the various parts of the Report. You -- can therefore chose in which order to report the various categories, -- and whether or not to report them. -- After calling any of these, the list of results has been modified in -- R, so you should get the counts first. private type Text_Reporter is new Reporter with record Use_ANSI : Boolean := False; end record; end AUnit.Reporter.Text;
{ "source": "starcoderdata", "programming_language": "ada" }
-- { dg-do compile } -- { dg-options "-gnatws -O3" } with Discr21_Pkg; use Discr21_Pkg; package body Discr21 is type Index is new Natural range 0 .. 100; type Arr is array (Index range <> ) of Position; type Rec(Size : Index := 1) is record A : Arr(1 .. Size); end record; Data : Rec; function To_V(pos : Position) return VPosition is begin return To_Position(pos.x, pos.y, pos.z); end; procedure Read(Data : Rec) is pos : VPosition := To_V (Data.A(1)); begin null; end; procedure Test is begin Read (Data); end; end Discr21;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with HAL; package Edc_Client.Matrix.Word is -------------------------------------------------------------------------- -- Shows the least significant byte on the matrix -- This is equivalent of the right byte on the matrix -------------------------------------------------------------------------- procedure Show_LSB (Value : HAL.UInt8) with Pre => Initialized; -------------------------------------------------------------------------- -- Shows the most significant byte on the matrix -- This is equivalent of the left byte on the matrix -------------------------------------------------------------------------- procedure Show_MSB (Value : HAL.UInt8) with Pre => Initialized; -------------------------------------------------------------------------- -- Shows the full word on the matrix -------------------------------------------------------------------------- procedure Show_Word (Value : HAL.UInt16) with Pre => Initialized; end Edc_Client.Matrix.Word;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Wiki.Strings; private with Ada.Containers.Vectors; private with Ada.Finalization; private with Util.Refs; -- == Attributes == -- The `Attributes` package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the `Attribute_List` -- with some operations to append or query for an attribute. Attributes are used for -- the Wiki document representation to describe the HTML attributes that were parsed and -- several parameters that describe Wiki content (links, ...). -- -- The Wiki filters and Wiki plugins have access to the attributes before they are added -- to the Wiki document. They can check them or modify them according to their needs. -- -- The Wiki renderers use the attributes to render the final HTML content. package Wiki.Attributes is pragma Preelaborate; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List is private; -- Find the attribute with the given name. function Find (List : in Attribute_List; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.WString); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)); private type Attribute (Name_Length, Value_Length : Natural) is limited new Util.Refs.Ref_Entity with record Name : String (1 .. Name_Length); Value : Wiki.Strings.WString (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Refs is new Util.Refs.Indefinite_References (Attribute, Attribute_Access); use Attribute_Refs; subtype Attribute_Ref is Attribute_Refs.Ref; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Ref); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List); end Wiki.Attributes;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Strings.UTF_Encoding; with Ada.Strings.Unbounded; package CommonText is package SU renames Ada.Strings.Unbounded; subtype Text is SU.Unbounded_String; subtype UTF8 is Ada.Strings.UTF_Encoding.UTF_8_String; blank : constant Text := SU.Null_Unbounded_String; -- converters : Text <==> String function USS (US : Text) return String; function SUS (S : String) return Text; -- converters : UTF8 <==> String function UTF8S (S8 : UTF8) return String; function SUTF8 (S : String) return UTF8; -- True if the string is zero length function IsBlank (US : Text) return Boolean; function IsBlank (S : String) return Boolean; -- True if strings are identical function equivalent (A, B : Text) return Boolean; function equivalent (A : Text; B : String) return Boolean; -- Trim both sides function trim (US : Text) return Text; function trim (S : String) return String; -- unpadded numeric image function int2str (A : Integer) return String; function int2text (A : Integer) return Text; -- convert boolean to lowercase string function bool2str (A : Boolean) return String; function bool2text (A : Boolean) return Text; -- shorthand for index function pinpoint (S : String; fragment : String) return Natural; function contains (S : String; fragment : String) return Boolean; function contains (US : Text; fragment : String) return Boolean; -- Return half of a string split by separator function part_1 (S : String; separator : String := "/") return String; function part_2 (S : String; separator : String := "/") return String; -- Replace a single character with another single character (first found) function replace (S : String; reject, shiny : Character) return String; -- Numeric image with left-padded zeros function zeropad (N : Natural; places : Positive) return String; -- Returns length of string function len (US : Text) return Natural; function len (S : String) return Natural; -- Returns number of instances of a given character in a given string function count_char (S : String; focus : Character) return Natural; -- Provides a mask of the given sql string, all quoted text set to '#' -- including the quote marks themselves. function redact_quotes (sql : String) return String; -- Removes leading and trailing whitespace, and any trailing semicolon function trim_sql (sql : String) return String; -- After masking, return number of queries separated by semicolons function count_queries (trimmed_sql : String) return Natural; -- Returns a single query given a multiquery and an index starting from 1 function subquery (trimmed_sql : String; index : Positive) return String; -- With "set" imput of comma-separated values, return number of items function num_set_items (nv : String) return Natural; end CommonText;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- pragma Ada_2012; with Skill.Types.Pools; package Skill.Iterators.Type_Hierarchy_Iterator is use type Skill.Types.Pools.Pool; type Iterator is tagged record Current : Skill.Types.Pools.Pool; End_Height : Natural; end record; procedure Init (This : access Iterator'Class; First : Skill.Types.Pools.Pool := null); function Element (This : access Iterator'Class) return Skill.Types.Pools.Pool is (This.Current); function Has_Next (This : access Iterator'Class) return Boolean is (null /= This.Current); procedure Next (This : access Iterator'Class); function Next (This : access Iterator'Class) return Skill.Types.Pools.Pool; end Skill.Iterators.Type_Hierarchy_Iterator;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ package Asis.Gela.Elements.Expr is ------------------------- -- Box_Expression_Node -- ------------------------- type Box_Expression_Node is new Expression_Node with private; type Box_Expression_Ptr is access all Box_Expression_Node; for Box_Expression_Ptr'Storage_Pool use Lists.Pool; function New_Box_Expression_Node (The_Context : ASIS.Context) return Box_Expression_Ptr; function Expression_Kind (Element : Box_Expression_Node) return Asis.Expression_Kinds; function Clone (Element : Box_Expression_Node; Parent : Asis.Element) return Asis.Element; ----------------------- -- Base_Literal_Node -- ----------------------- type Base_Literal_Node is abstract new Expression_Node with private; type Base_Literal_Ptr is access all Base_Literal_Node; for Base_Literal_Ptr'Storage_Pool use Lists.Pool; function Value_Image (Element : Base_Literal_Node) return Wide_String; procedure Set_Value_Image (Element : in out Base_Literal_Node; Value : in Wide_String); -------------------------- -- Integer_Literal_Node -- -------------------------- type Integer_Literal_Node is new Base_Literal_Node with private; type Integer_Literal_Ptr is access all Integer_Literal_Node; for Integer_Literal_Ptr'Storage_Pool use Lists.Pool; function New_Integer_Literal_Node (The_Context : ASIS.Context) return Integer_Literal_Ptr; function Expression_Kind (Element : Integer_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : Integer_Literal_Node; Parent : Asis.Element) return Asis.Element; ----------------------- -- Real_Literal_Node -- ----------------------- type Real_Literal_Node is new Base_Literal_Node with private; type Real_Literal_Ptr is access all Real_Literal_Node; for Real_Literal_Ptr'Storage_Pool use Lists.Pool; function New_Real_Literal_Node (The_Context : ASIS.Context) return Real_Literal_Ptr; function Expression_Kind (Element : Real_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : Real_Literal_Node; Parent : Asis.Element) return Asis.Element; ------------------------- -- String_Literal_Node -- ------------------------- type String_Literal_Node is new Base_Literal_Node with private; type String_Literal_Ptr is access all String_Literal_Node; for String_Literal_Ptr'Storage_Pool use Lists.Pool; function New_String_Literal_Node (The_Context : ASIS.Context) return String_Literal_Ptr; function Expression_Kind (Element : String_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : String_Literal_Node; Parent : Asis.Element) return Asis.Element; -------------------------- -- Base_Identifier_Node -- -------------------------- type Base_Identifier_Node is abstract new Expression_Node with private; type Base_Identifier_Ptr is access all Base_Identifier_Node; for Base_Identifier_Ptr'Storage_Pool use Lists.Pool; function Name_Image (Element : Base_Identifier_Node) return Wide_String; procedure Set_Name_Image (Element : in out Base_Identifier_Node; Value : in Wide_String); function Corresponding_Name_Declaration (Element : Base_Identifier_Node) return Asis.Declaration; procedure Set_Corresponding_Name_Declaration (Element : in out Base_Identifier_Node; Value : in Asis.Declaration); function Corresponding_Name_Definition_List (Element : Base_Identifier_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Corresponding_Name_Definition_List (Element : in out Base_Identifier_Node; Item : in Asis.Element); function Corresponding_Generic_Element (Element : Base_Identifier_Node) return Asis.Defining_Name; procedure Set_Corresponding_Generic_Element (Element : in out Base_Identifier_Node; Value : in Asis.Defining_Name); --------------------- -- Identifier_Node -- --------------------- type Identifier_Node is new Base_Identifier_Node with private; type Identifier_Ptr is access all Identifier_Node; for Identifier_Ptr'Storage_Pool use Lists.Pool; function New_Identifier_Node (The_Context : ASIS.Context) return Identifier_Ptr; function Expression_Kind (Element : Identifier_Node) return Asis.Expression_Kinds; function Clone (Element : Identifier_Node; Parent : Asis.Element) return Asis.Element; -------------------------- -- Operator_Symbol_Node -- -------------------------- type Operator_Symbol_Node is new Base_Identifier_Node with private; type Operator_Symbol_Ptr is access all Operator_Symbol_Node; for Operator_Symbol_Ptr'Storage_Pool use Lists.Pool; function New_Operator_Symbol_Node (The_Context : ASIS.Context) return Operator_Symbol_Ptr; function Operator_Kind (Element : Operator_Symbol_Node) return Asis.Operator_Kinds; procedure Set_Operator_Kind (Element : in out Operator_Symbol_Node; Value : in Asis.Operator_Kinds); function Expression_Kind (Element : Operator_Symbol_Node) return Asis.Expression_Kinds; function Clone (Element : Operator_Symbol_Node; Parent : Asis.Element) return Asis.Element; ---------------------------- -- Character_Literal_Node -- ---------------------------- type Character_Literal_Node is new Base_Identifier_Node with private; type Character_Literal_Ptr is access all Character_Literal_Node; for Character_Literal_Ptr'Storage_Pool use Lists.Pool; function New_Character_Literal_Node (The_Context : ASIS.Context) return Character_Literal_Ptr; function Expression_Kind (Element : Character_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : Character_Literal_Node; Parent : Asis.Element) return Asis.Element; ------------------------------ -- Enumeration_Literal_Node -- ------------------------------ type Enumeration_Literal_Node is new Base_Identifier_Node with private; type Enumeration_Literal_Ptr is access all Enumeration_Literal_Node; for Enumeration_Literal_Ptr'Storage_Pool use Lists.Pool; function New_Enumeration_Literal_Node (The_Context : ASIS.Context) return Enumeration_Literal_Ptr; function Expression_Kind (Element : Enumeration_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : Enumeration_Literal_Node; Parent : Asis.Element) return Asis.Element; ------------------------------- -- Explicit_Dereference_Node -- ------------------------------- type Explicit_Dereference_Node is new Expression_Node with private; type Explicit_Dereference_Ptr is access all Explicit_Dereference_Node; for Explicit_Dereference_Ptr'Storage_Pool use Lists.Pool; function New_Explicit_Dereference_Node (The_Context : ASIS.Context) return Explicit_Dereference_Ptr; function Prefix (Element : Explicit_Dereference_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Explicit_Dereference_Node; Value : in Asis.Expression); function Expression_Kind (Element : Explicit_Dereference_Node) return Asis.Expression_Kinds; function Children (Element : access Explicit_Dereference_Node) return Traverse_List; function Clone (Element : Explicit_Dereference_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Explicit_Dereference_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------ -- Function_Call_Node -- ------------------------ type Function_Call_Node is new Expression_Node with private; type Function_Call_Ptr is access all Function_Call_Node; for Function_Call_Ptr'Storage_Pool use Lists.Pool; function New_Function_Call_Node (The_Context : ASIS.Context) return Function_Call_Ptr; function Prefix (Element : Function_Call_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Function_Call_Node; Value : in Asis.Expression); function Is_Prefix_Call (Element : Function_Call_Node) return Boolean; procedure Set_Is_Prefix_Call (Element : in out Function_Call_Node; Value : in Boolean); function Is_Dispatching_Call (Element : Function_Call_Node) return Boolean; procedure Set_Is_Dispatching_Call (Element : in out Function_Call_Node; Value : in Boolean); function Corresponding_Called_Function (Element : Function_Call_Node) return Asis.Declaration; procedure Set_Corresponding_Called_Function (Element : in out Function_Call_Node; Value : in Asis.Declaration); function Function_Call_Parameters (Element : Function_Call_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Function_Call_Parameters (Element : in out Function_Call_Node; Value : in Asis.Element); function Function_Call_Parameters_List (Element : Function_Call_Node) return Asis.Element; function Normalized_Function_Call_Parameters (Element : Function_Call_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Normalized_Function_Call_Parameters (Element : in out Function_Call_Node; Item : in Asis.Element); function Is_Call_On_Dispatching_Operation (Element : Function_Call_Node) return Boolean; procedure Set_Is_Call_On_Dispatching_Operation (Element : in out Function_Call_Node; Value : in Boolean); function Record_Aggregate (Element : Function_Call_Node) return Asis.Element; procedure Set_Record_Aggregate (Element : in out Function_Call_Node; Value : in Asis.Element); function Expression_Kind (Element : Function_Call_Node) return Asis.Expression_Kinds; function Children (Element : access Function_Call_Node) return Traverse_List; function Clone (Element : Function_Call_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Function_Call_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------------------- -- Indexed_Component_Node -- ---------------------------- type Indexed_Component_Node is new Expression_Node with private; type Indexed_Component_Ptr is access all Indexed_Component_Node; for Indexed_Component_Ptr'Storage_Pool use Lists.Pool; function New_Indexed_Component_Node (The_Context : ASIS.Context) return Indexed_Component_Ptr; function Prefix (Element : Indexed_Component_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Indexed_Component_Node; Value : in Asis.Expression); function Index_Expressions (Element : Indexed_Component_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Index_Expressions (Element : in out Indexed_Component_Node; Value : in Asis.Element); function Index_Expressions_List (Element : Indexed_Component_Node) return Asis.Element; function Expression_Kind (Element : Indexed_Component_Node) return Asis.Expression_Kinds; function Children (Element : access Indexed_Component_Node) return Traverse_List; function Clone (Element : Indexed_Component_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Indexed_Component_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------- -- Slice_Node -- ---------------- type Slice_Node is new Expression_Node with private; type Slice_Ptr is access all Slice_Node; for Slice_Ptr'Storage_Pool use Lists.Pool; function New_Slice_Node (The_Context : ASIS.Context) return Slice_Ptr; function Prefix (Element : Slice_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Slice_Node; Value : in Asis.Expression); function Slice_Range (Element : Slice_Node) return Asis.Discrete_Range; procedure Set_Slice_Range (Element : in out Slice_Node; Value : in Asis.Discrete_Range); function Expression_Kind (Element : Slice_Node) return Asis.Expression_Kinds; function Children (Element : access Slice_Node) return Traverse_List; function Clone (Element : Slice_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Slice_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ----------------------------- -- Selected_Component_Node -- ----------------------------- type Selected_Component_Node is new Expression_Node with private; type Selected_Component_Ptr is access all Selected_Component_Node; for Selected_Component_Ptr'Storage_Pool use Lists.Pool; function New_Selected_Component_Node (The_Context : ASIS.Context) return Selected_Component_Ptr; function Prefix (Element : Selected_Component_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Selected_Component_Node; Value : in Asis.Expression); function Selector (Element : Selected_Component_Node) return Asis.Expression; procedure Set_Selector (Element : in out Selected_Component_Node; Value : in Asis.Expression); function Expression_Kind (Element : Selected_Component_Node) return Asis.Expression_Kinds; function Children (Element : access Selected_Component_Node) return Traverse_List; function Clone (Element : Selected_Component_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Selected_Component_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------ -- Attribute_Reference_Node -- ------------------------------ type Attribute_Reference_Node is new Expression_Node with private; type Attribute_Reference_Ptr is access all Attribute_Reference_Node; for Attribute_Reference_Ptr'Storage_Pool use Lists.Pool; function New_Attribute_Reference_Node (The_Context : ASIS.Context) return Attribute_Reference_Ptr; function Prefix (Element : Attribute_Reference_Node) return Asis.Expression; procedure Set_Prefix (Element : in out Attribute_Reference_Node; Value : in Asis.Expression); function Attribute_Kind (Element : Attribute_Reference_Node) return Asis.Attribute_Kinds; procedure Set_Attribute_Kind (Element : in out Attribute_Reference_Node; Value : in Asis.Attribute_Kinds); function Attribute_Designator_Identifier (Element : Attribute_Reference_Node) return Asis.Expression; procedure Set_Attribute_Designator_Identifier (Element : in out Attribute_Reference_Node; Value : in Asis.Expression); function Attribute_Designator_Expressions (Element : Attribute_Reference_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Attribute_Designator_Expressions (Element : in out Attribute_Reference_Node; Value : in Asis.Element); function Attribute_Designator_Expressions_List (Element : Attribute_Reference_Node) return Asis.Element; function Expression_Kind (Element : Attribute_Reference_Node) return Asis.Expression_Kinds; function Children (Element : access Attribute_Reference_Node) return Traverse_List; function Clone (Element : Attribute_Reference_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Attribute_Reference_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------- -- Base_Record_Aggregate_Node -- -------------------------------- type Base_Record_Aggregate_Node is abstract new Expression_Node with private; type Base_Record_Aggregate_Ptr is access all Base_Record_Aggregate_Node; for Base_Record_Aggregate_Ptr'Storage_Pool use Lists.Pool; function Record_Component_Associations (Element : Base_Record_Aggregate_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Record_Component_Associations (Element : in out Base_Record_Aggregate_Node; Value : in Asis.Element); function Record_Component_Associations_List (Element : Base_Record_Aggregate_Node) return Asis.Element; function Normalized_Record_Component_Associations (Element : Base_Record_Aggregate_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Add_To_Normalized_Record_Component_Associations (Element : in out Base_Record_Aggregate_Node; Item : in Asis.Element); function Children (Element : access Base_Record_Aggregate_Node) return Traverse_List; --------------------------- -- Record_Aggregate_Node -- --------------------------- type Record_Aggregate_Node is new Base_Record_Aggregate_Node with private; type Record_Aggregate_Ptr is access all Record_Aggregate_Node; for Record_Aggregate_Ptr'Storage_Pool use Lists.Pool; function New_Record_Aggregate_Node (The_Context : ASIS.Context) return Record_Aggregate_Ptr; function Expression_Kind (Element : Record_Aggregate_Node) return Asis.Expression_Kinds; function Clone (Element : Record_Aggregate_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Record_Aggregate_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------ -- Extension_Aggregate_Node -- ------------------------------ type Extension_Aggregate_Node is new Base_Record_Aggregate_Node with private; type Extension_Aggregate_Ptr is access all Extension_Aggregate_Node; for Extension_Aggregate_Ptr'Storage_Pool use Lists.Pool; function New_Extension_Aggregate_Node (The_Context : ASIS.Context) return Extension_Aggregate_Ptr; function Extension_Aggregate_Expression (Element : Extension_Aggregate_Node) return Asis.Expression; procedure Set_Extension_Aggregate_Expression (Element : in out Extension_Aggregate_Node; Value : in Asis.Expression); function Expression_Kind (Element : Extension_Aggregate_Node) return Asis.Expression_Kinds; function Children (Element : access Extension_Aggregate_Node) return Traverse_List; function Clone (Element : Extension_Aggregate_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Extension_Aggregate_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------- -- Base_Array_Aggregate_Node -- ------------------------------- type Base_Array_Aggregate_Node is abstract new Expression_Node with private; type Base_Array_Aggregate_Ptr is access all Base_Array_Aggregate_Node; for Base_Array_Aggregate_Ptr'Storage_Pool use Lists.Pool; function Array_Component_Associations (Element : Base_Array_Aggregate_Node; Include_Pragmas : in Boolean := False) return Asis.Element_List; procedure Set_Array_Component_Associations (Element : in out Base_Array_Aggregate_Node; Value : in Asis.Element); function Array_Component_Associations_List (Element : Base_Array_Aggregate_Node) return Asis.Element; function Children (Element : access Base_Array_Aggregate_Node) return Traverse_List; ------------------------------------- -- Positional_Array_Aggregate_Node -- ------------------------------------- type Positional_Array_Aggregate_Node is new Base_Array_Aggregate_Node with private; type Positional_Array_Aggregate_Ptr is access all Positional_Array_Aggregate_Node; for Positional_Array_Aggregate_Ptr'Storage_Pool use Lists.Pool; function New_Positional_Array_Aggregate_Node (The_Context : ASIS.Context) return Positional_Array_Aggregate_Ptr; function Expression_Kind (Element : Positional_Array_Aggregate_Node) return Asis.Expression_Kinds; function Clone (Element : Positional_Array_Aggregate_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Positional_Array_Aggregate_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------- -- Named_Array_Aggregate_Node -- -------------------------------- type Named_Array_Aggregate_Node is new Base_Array_Aggregate_Node with private; type Named_Array_Aggregate_Ptr is access all Named_Array_Aggregate_Node; for Named_Array_Aggregate_Ptr'Storage_Pool use Lists.Pool; function New_Named_Array_Aggregate_Node (The_Context : ASIS.Context) return Named_Array_Aggregate_Ptr; function Expression_Kind (Element : Named_Array_Aggregate_Node) return Asis.Expression_Kinds; function Clone (Element : Named_Array_Aggregate_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Named_Array_Aggregate_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ----------------------------- -- Base_Short_Circuit_Node -- ----------------------------- type Base_Short_Circuit_Node is abstract new Expression_Node with private; type Base_Short_Circuit_Ptr is access all Base_Short_Circuit_Node; for Base_Short_Circuit_Ptr'Storage_Pool use Lists.Pool; function Short_Circuit_Operation_Left_Expression (Element : Base_Short_Circuit_Node) return Asis.Expression; procedure Set_Short_Circuit_Operation_Left_Expression (Element : in out Base_Short_Circuit_Node; Value : in Asis.Expression); function Short_Circuit_Operation_Right_Expression (Element : Base_Short_Circuit_Node) return Asis.Expression; procedure Set_Short_Circuit_Operation_Right_Expression (Element : in out Base_Short_Circuit_Node; Value : in Asis.Expression); function Children (Element : access Base_Short_Circuit_Node) return Traverse_List; --------------------------------- -- And_Then_Short_Circuit_Node -- --------------------------------- type And_Then_Short_Circuit_Node is new Base_Short_Circuit_Node with private; type And_Then_Short_Circuit_Ptr is access all And_Then_Short_Circuit_Node; for And_Then_Short_Circuit_Ptr'Storage_Pool use Lists.Pool; function New_And_Then_Short_Circuit_Node (The_Context : ASIS.Context) return And_Then_Short_Circuit_Ptr; function Expression_Kind (Element : And_Then_Short_Circuit_Node) return Asis.Expression_Kinds; function Clone (Element : And_Then_Short_Circuit_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access And_Then_Short_Circuit_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------- -- Or_Else_Short_Circuit_Node -- -------------------------------- type Or_Else_Short_Circuit_Node is new Base_Short_Circuit_Node with private; type Or_Else_Short_Circuit_Ptr is access all Or_Else_Short_Circuit_Node; for Or_Else_Short_Circuit_Ptr'Storage_Pool use Lists.Pool; function New_Or_Else_Short_Circuit_Node (The_Context : ASIS.Context) return Or_Else_Short_Circuit_Ptr; function Expression_Kind (Element : Or_Else_Short_Circuit_Node) return Asis.Expression_Kinds; function Clone (Element : Or_Else_Short_Circuit_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Or_Else_Short_Circuit_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ----------------------------------- -- In_Range_Membership_Test_Node -- ----------------------------------- type In_Range_Membership_Test_Node is new Expression_Node with private; type In_Range_Membership_Test_Ptr is access all In_Range_Membership_Test_Node; for In_Range_Membership_Test_Ptr'Storage_Pool use Lists.Pool; function New_In_Range_Membership_Test_Node (The_Context : ASIS.Context) return In_Range_Membership_Test_Ptr; function Membership_Test_Expression (Element : In_Range_Membership_Test_Node) return Asis.Expression; procedure Set_Membership_Test_Expression (Element : in out In_Range_Membership_Test_Node; Value : in Asis.Expression); function Membership_Test_Range (Element : In_Range_Membership_Test_Node) return Asis.Range_Constraint; procedure Set_Membership_Test_Range (Element : in out In_Range_Membership_Test_Node; Value : in Asis.Range_Constraint); function Expression_Kind (Element : In_Range_Membership_Test_Node) return Asis.Expression_Kinds; function Children (Element : access In_Range_Membership_Test_Node) return Traverse_List; function Clone (Element : In_Range_Membership_Test_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access In_Range_Membership_Test_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); --------------------------------------- -- Not_In_Range_Membership_Test_Node -- --------------------------------------- type Not_In_Range_Membership_Test_Node is new In_Range_Membership_Test_Node with private; type Not_In_Range_Membership_Test_Ptr is access all Not_In_Range_Membership_Test_Node; for Not_In_Range_Membership_Test_Ptr'Storage_Pool use Lists.Pool; function New_Not_In_Range_Membership_Test_Node (The_Context : ASIS.Context) return Not_In_Range_Membership_Test_Ptr; function Expression_Kind (Element : Not_In_Range_Membership_Test_Node) return Asis.Expression_Kinds; function Clone (Element : Not_In_Range_Membership_Test_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Not_In_Range_Membership_Test_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------------------------- -- In_Type_Membership_Test_Node -- ---------------------------------- type In_Type_Membership_Test_Node is new Expression_Node with private; type In_Type_Membership_Test_Ptr is access all In_Type_Membership_Test_Node; for In_Type_Membership_Test_Ptr'Storage_Pool use Lists.Pool; function New_In_Type_Membership_Test_Node (The_Context : ASIS.Context) return In_Type_Membership_Test_Ptr; function Membership_Test_Expression (Element : In_Type_Membership_Test_Node) return Asis.Expression; procedure Set_Membership_Test_Expression (Element : in out In_Type_Membership_Test_Node; Value : in Asis.Expression); function Membership_Test_Subtype_Mark (Element : In_Type_Membership_Test_Node) return Asis.Expression; procedure Set_Membership_Test_Subtype_Mark (Element : in out In_Type_Membership_Test_Node; Value : in Asis.Expression); function Expression_Kind (Element : In_Type_Membership_Test_Node) return Asis.Expression_Kinds; function Children (Element : access In_Type_Membership_Test_Node) return Traverse_List; function Clone (Element : In_Type_Membership_Test_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access In_Type_Membership_Test_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------------------- -- Not_In_Type_Membership_Test_Node -- -------------------------------------- type Not_In_Type_Membership_Test_Node is new In_Type_Membership_Test_Node with private; type Not_In_Type_Membership_Test_Ptr is access all Not_In_Type_Membership_Test_Node; for Not_In_Type_Membership_Test_Ptr'Storage_Pool use Lists.Pool; function New_Not_In_Type_Membership_Test_Node (The_Context : ASIS.Context) return Not_In_Type_Membership_Test_Ptr; function Expression_Kind (Element : Not_In_Type_Membership_Test_Node) return Asis.Expression_Kinds; function Clone (Element : Not_In_Type_Membership_Test_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Not_In_Type_Membership_Test_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ----------------------- -- Null_Literal_Node -- ----------------------- type Null_Literal_Node is new Expression_Node with private; type Null_Literal_Ptr is access all Null_Literal_Node; for Null_Literal_Ptr'Storage_Pool use Lists.Pool; function New_Null_Literal_Node (The_Context : ASIS.Context) return Null_Literal_Ptr; function Expression_Kind (Element : Null_Literal_Node) return Asis.Expression_Kinds; function Clone (Element : Null_Literal_Node; Parent : Asis.Element) return Asis.Element; ----------------------------------- -- Parenthesized_Expression_Node -- ----------------------------------- type Parenthesized_Expression_Node is new Expression_Node with private; type Parenthesized_Expression_Ptr is access all Parenthesized_Expression_Node; for Parenthesized_Expression_Ptr'Storage_Pool use Lists.Pool; function New_Parenthesized_Expression_Node (The_Context : ASIS.Context) return Parenthesized_Expression_Ptr; function Expression_Parenthesized (Element : Parenthesized_Expression_Node) return Asis.Expression; procedure Set_Expression_Parenthesized (Element : in out Parenthesized_Expression_Node; Value : in Asis.Expression); function Expression_Kind (Element : Parenthesized_Expression_Node) return Asis.Expression_Kinds; function Children (Element : access Parenthesized_Expression_Node) return Traverse_List; function Clone (Element : Parenthesized_Expression_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Parenthesized_Expression_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); -------------------------- -- Base_Conversion_Node -- -------------------------- type Base_Conversion_Node is abstract new Expression_Node with private; type Base_Conversion_Ptr is access all Base_Conversion_Node; for Base_Conversion_Ptr'Storage_Pool use Lists.Pool; function Converted_Or_Qualified_Subtype_Mark (Element : Base_Conversion_Node) return Asis.Expression; procedure Set_Converted_Or_Qualified_Subtype_Mark (Element : in out Base_Conversion_Node; Value : in Asis.Expression); function Converted_Or_Qualified_Expression (Element : Base_Conversion_Node) return Asis.Expression; procedure Set_Converted_Or_Qualified_Expression (Element : in out Base_Conversion_Node; Value : in Asis.Expression); function Children (Element : access Base_Conversion_Node) return Traverse_List; -------------------------- -- Type_Conversion_Node -- -------------------------- type Type_Conversion_Node is new Base_Conversion_Node with private; type Type_Conversion_Ptr is access all Type_Conversion_Node; for Type_Conversion_Ptr'Storage_Pool use Lists.Pool; function New_Type_Conversion_Node (The_Context : ASIS.Context) return Type_Conversion_Ptr; function Expression_Kind (Element : Type_Conversion_Node) return Asis.Expression_Kinds; function Clone (Element : Type_Conversion_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Type_Conversion_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ------------------------------- -- Qualified_Expression_Node -- ------------------------------- type Qualified_Expression_Node is new Base_Conversion_Node with private; type Qualified_Expression_Ptr is access all Qualified_Expression_Node; for Qualified_Expression_Ptr'Storage_Pool use Lists.Pool; function New_Qualified_Expression_Node (The_Context : ASIS.Context) return Qualified_Expression_Ptr; function Expression_Kind (Element : Qualified_Expression_Node) return Asis.Expression_Kinds; function Clone (Element : Qualified_Expression_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Qualified_Expression_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ---------------------------------- -- Allocation_From_Subtype_Node -- ---------------------------------- type Allocation_From_Subtype_Node is new Expression_Node with private; type Allocation_From_Subtype_Ptr is access all Allocation_From_Subtype_Node; for Allocation_From_Subtype_Ptr'Storage_Pool use Lists.Pool; function New_Allocation_From_Subtype_Node (The_Context : ASIS.Context) return Allocation_From_Subtype_Ptr; function Allocator_Subtype_Indication (Element : Allocation_From_Subtype_Node) return Asis.Subtype_Indication; procedure Set_Allocator_Subtype_Indication (Element : in out Allocation_From_Subtype_Node; Value : in Asis.Subtype_Indication); function Expression_Kind (Element : Allocation_From_Subtype_Node) return Asis.Expression_Kinds; function Children (Element : access Allocation_From_Subtype_Node) return Traverse_List; function Clone (Element : Allocation_From_Subtype_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Allocation_From_Subtype_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); ----------------------------------------------- -- Allocation_From_Qualified_Expression_Node -- ----------------------------------------------- type Allocation_From_Qualified_Expression_Node is new Expression_Node with private; type Allocation_From_Qualified_Expression_Ptr is access all Allocation_From_Qualified_Expression_Node; for Allocation_From_Qualified_Expression_Ptr'Storage_Pool use Lists.Pool; function New_Allocation_From_Qualified_Expression_Node (The_Context : ASIS.Context) return Allocation_From_Qualified_Expression_Ptr; function Allocator_Qualified_Expression (Element : Allocation_From_Qualified_Expression_Node) return Asis.Expression; procedure Set_Allocator_Qualified_Expression (Element : in out Allocation_From_Qualified_Expression_Node; Value : in Asis.Expression); function Expression_Kind (Element : Allocation_From_Qualified_Expression_Node) return Asis.Expression_Kinds; function Children (Element : access Allocation_From_Qualified_Expression_Node) return Traverse_List; function Clone (Element : Allocation_From_Qualified_Expression_Node; Parent : Asis.Element) return Asis.Element; procedure Copy (Source : in Asis.Element; Target : access Allocation_From_Qualified_Expression_Node; Cloner : in Cloner_Class; Parent : in Asis.Element); private type Box_Expression_Node is new Expression_Node with record null; end record; type Base_Literal_Node is abstract new Expression_Node with record Value_Image : aliased Unbounded_Wide_String; end record; type Integer_Literal_Node is new Base_Literal_Node with record null; end record; type Real_Literal_Node is new Base_Literal_Node with record null; end record; type String_Literal_Node is new Base_Literal_Node with record null; end record; type Base_Identifier_Node is abstract new Expression_Node with record Name_Image : aliased Unbounded_Wide_String; Corresponding_Name_Declaration : aliased Asis.Declaration; Corresponding_Name_Definition_List : aliased Secondary_Definition_Lists.List_Node; Corresponding_Generic_Element : aliased Asis.Defining_Name; end record; type Identifier_Node is new Base_Identifier_Node with record null; end record; type Operator_Symbol_Node is new Base_Identifier_Node with record Operator_Kind : aliased Asis.Operator_Kinds := Not_An_Operator; end record; type Character_Literal_Node is new Base_Identifier_Node with record null; end record; type Enumeration_Literal_Node is new Base_Identifier_Node with record null; end record; type Explicit_Dereference_Node is new Expression_Node with record Prefix : aliased Asis.Expression; end record; type Function_Call_Node is new Expression_Node with record Prefix : aliased Asis.Expression; Is_Prefix_Call : aliased Boolean := True; Is_Dispatching_Call : aliased Boolean := False; Corresponding_Called_Function : aliased Asis.Declaration; Function_Call_Parameters : aliased Primary_Association_Lists.List; Normalized_Function_Call_Parameters : aliased Secondary_Association_Lists.List_Node; Is_Call_On_Dispatching_Operation : aliased Boolean := False; Record_Aggregate : aliased Asis.Element; end record; type Indexed_Component_Node is new Expression_Node with record Prefix : aliased Asis.Expression; Index_Expressions : aliased Primary_Expression_Lists.List; end record; type Slice_Node is new Expression_Node with record Prefix : aliased Asis.Expression; Slice_Range : aliased Asis.Discrete_Range; end record; type Selected_Component_Node is new Expression_Node with record Prefix : aliased Asis.Expression; Selector : aliased Asis.Expression; end record; type Attribute_Reference_Node is new Expression_Node with record Prefix : aliased Asis.Expression; Attribute_Kind : aliased Asis.Attribute_Kinds := Not_An_Attribute; Attribute_Designator_Identifier : aliased Asis.Expression; Attribute_Designator_Expressions : aliased Primary_Expression_Lists.List; end record; type Base_Record_Aggregate_Node is abstract new Expression_Node with record Record_Component_Associations : aliased Primary_Association_Lists.List; Normalized_Record_Component_Associations : aliased Secondary_Association_Lists.List_Node; end record; type Record_Aggregate_Node is new Base_Record_Aggregate_Node with record null; end record; type Extension_Aggregate_Node is new Base_Record_Aggregate_Node with record Extension_Aggregate_Expression : aliased Asis.Expression; end record; type Base_Array_Aggregate_Node is abstract new Expression_Node with record Array_Component_Associations : aliased Primary_Association_Lists.List; end record; type Positional_Array_Aggregate_Node is new Base_Array_Aggregate_Node with record null; end record; type Named_Array_Aggregate_Node is new Base_Array_Aggregate_Node with record null; end record; type Base_Short_Circuit_Node is abstract new Expression_Node with record Short_Circuit_Operation_Left_Expression : aliased Asis.Expression; Short_Circuit_Operation_Right_Expression : aliased Asis.Expression; end record; type And_Then_Short_Circuit_Node is new Base_Short_Circuit_Node with record null; end record; type Or_Else_Short_Circuit_Node is new Base_Short_Circuit_Node with record null; end record; type In_Range_Membership_Test_Node is new Expression_Node with record Membership_Test_Expression : aliased Asis.Expression; Membership_Test_Range : aliased Asis.Range_Constraint; end record; type Not_In_Range_Membership_Test_Node is new In_Range_Membership_Test_Node with record null; end record; type In_Type_Membership_Test_Node is new Expression_Node with record Membership_Test_Expression : aliased Asis.Expression; Membership_Test_Subtype_Mark : aliased Asis.Expression; end record; type Not_In_Type_Membership_Test_Node is new In_Type_Membership_Test_Node with record null; end record; type Null_Literal_Node is new Expression_Node with record null; end record; type Parenthesized_Expression_Node is new Expression_Node with record Expression_Parenthesized : aliased Asis.Expression; end record; type Base_Conversion_Node is abstract new Expression_Node with record Converted_Or_Qualified_Subtype_Mark : aliased Asis.Expression; Converted_Or_Qualified_Expression : aliased Asis.Expression; end record; type Type_Conversion_Node is new Base_Conversion_Node with record null; end record; type Qualified_Expression_Node is new Base_Conversion_Node with record null; end record; type Allocation_From_Subtype_Node is new Expression_Node with record Allocator_Subtype_Indication : aliased Asis.Subtype_Indication; end record; type Allocation_From_Qualified_Expression_Node is new Expression_Node with record Allocator_Qualified_Expression : aliased Asis.Expression; end record; end Asis.Gela.Elements.Expr;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- This package provides handlers for enumerative types. Since the -- type is not fixed in advance, the package needs to be generic. -- generic type Value_Type is (<>); package Line_Parsers.Receivers.Enumeration_Receivers is type Receiver_Type is new Abstract_Parameter_Handler with private; function Is_Set (Handler : Receiver_Type) return Boolean; overriding procedure Receive (Handler : in out Receiver_Type; Name : String; Value : String; Position : Natural); function Get (Handler : Receiver_Type) return Value_Type with Pre => Handler.Is_Set; overriding function Reusable (Handler : Receiver_Type) return Boolean; private type Receiver_Type is new Abstract_Parameter_Handler with record Value : Value_Type; Set : Boolean := False; end record; function Is_Set (Handler : Receiver_Type) return Boolean is (Handler.Set); function Reusable (Handler : Receiver_Type) return Boolean is (False); function Get (Handler : Receiver_Type) return Value_Type is (Handler.Value); end Line_Parsers.Receivers.Enumeration_Receivers;
{ "source": "starcoderdata", "programming_language": "ada" }
-------------------------------------------------------------------------------- with CL.API; with CL.Enumerations; with CL.Helpers; package body CL.Events is procedure Adjust (Object : in out Event) is use type System.Address; begin if Object.Location /= System.Null_Address then Helpers.Error_Handler (API.Retain_Event (Object.Location)); end if; end Adjust; procedure Finalize (Object : in out Event) is use type System.Address; begin if Object.Location /= System.Null_Address then Helpers.Error_Handler (API.Release_Event (Object.Location)); end if; end Finalize; procedure Wait_For (Subject : Event) is List : constant Event_List (1..1) := (1 => Subject'Unchecked_Access); begin Wait_For (List); end Wait_For; procedure Wait_For (Subjects : Event_List) is Raw_List : Address_List (Subjects'Range); begin for Index in Subjects'Range loop Raw_List (Index) := Subjects (Index).Location; end loop; Helpers.Error_Handler (API.Wait_For_Events (Subjects'Length, Raw_List (1)'Address)); end Wait_For; function Command_Queue (Source : Event) return Command_Queues.Queue is function Getter is new Helpers.Get_Parameter (Return_T => System.Address, Parameter_T => Enumerations.Event_Info, C_Getter => API.Get_Event_Info); function New_CQ_Reference is new Helpers.New_Reference (Object_T => Command_Queues.Queue); begin return New_CQ_Reference (Getter (Source, Enumerations.Command_Queue)); end Command_Queue; function Kind (Source : Event) return Command_Type is function Getter is new Helpers.Get_Parameter (Return_T => Command_Type, Parameter_T => Enumerations.Event_Info, C_Getter => API.Get_Event_Info); begin return Getter (Source, Enumerations.Command_T); end Kind; function Reference_Count (Source : Event) return UInt is function Getter is new Helpers.Get_Parameter (Return_T => UInt, Parameter_T => Enumerations.Event_Info, C_Getter => API.Get_Event_Info); begin return Getter (Source, Enumerations.Reference_Count); end Reference_Count; function Status (Source : Event) return Execution_Status is function Getter is new Helpers.Get_Parameter (Return_T => Execution_Status, Parameter_T => Enumerations.Event_Info, C_Getter => API.Get_Event_Info); begin return Getter (Source, Enumerations.Command_Execution_Status); end Status; function Profiling_Info_ULong is new Helpers.Get_Parameter (Return_T => ULong, Parameter_T => Enumerations.Profiling_Info, C_Getter => API.Get_Event_Profiling_Info); function Queued_At (Source : Event) return ULong is begin return Profiling_Info_ULong (Source, Enumerations.Command_Queued); end Queued_At; function Submitted_At (Source : Event) return ULong is begin return Profiling_Info_ULong (Source, Enumerations.Submit); end Submitted_At; function Started_At (Source : Event) return ULong is begin return Profiling_Info_ULong (Source, Enumerations.Start); end Started_At; function Ended_At (Source : Event) return ULong is begin return Profiling_Info_ULong (Source, Enumerations.P_End); end Ended_At; end CL.Events;
{ "source": "starcoderdata", "programming_language": "ada" }