content
stringlengths
23
1.05M
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics; with GL.Types; with Orka.Behaviors; with Orka.Contexts; with Orka.Transforms.Singles.Matrices; with Orka.Transforms.Doubles.Vectors; private with Orka.Transforms.Doubles.Matrices; private with Orka.Types; package Orka.Cameras is pragma Preelaborate; package Transforms renames Orka.Transforms.Singles.Matrices; subtype Vector4 is Orka.Transforms.Doubles.Vectors.Vector4; use type GL.Types.Double; subtype Angle is GL.Types.Double range -Ada.Numerics.Pi .. Ada.Numerics.Pi; subtype Distance is GL.Types.Double range 0.0 .. GL.Types.Double'Last; Default_Scale : Vector4 := (0.002, 0.002, 1.0, 0.0); ----------------------------------------------------------------------------- type Camera_Lens is record Width, Height : Positive; FOV : GL.Types.Single; Reversed_Z : Boolean; end record; function Projection_Matrix (Object : Camera_Lens) return Transforms.Matrix4; function Create_Lens (Width, Height : Positive; FOV : GL.Types.Single; Context : Contexts.Context'Class) return Camera_Lens; ----------------------------------------------------------------------------- type Camera is abstract tagged private; type Camera_Ptr is not null access all Camera'Class; procedure Update (Object : in out Camera; Delta_Time : Duration) is abstract; procedure Set_Input_Scale (Object : in out Camera; X, Y, Z : GL.Types.Double); procedure Set_Up_Direction (Object : in out Camera; Direction : Vector4); function Lens (Object : Camera) return Camera_Lens; procedure Set_Lens (Object : in out Camera; Lens : Camera_Lens); function View_Matrix (Object : Camera) return Transforms.Matrix4 is abstract; function View_Matrix_Inverse (Object : Camera) return Transforms.Matrix4 is abstract; -- Return the inverse of the view matrix function View_Position (Object : Camera) return Vector4 is abstract; -- Return the position of the camera in world space function Projection_Matrix (Object : Camera) return Transforms.Matrix4; function Create_Camera (Lens : Camera_Lens) return Camera is abstract; type Observing_Camera is interface; procedure Look_At (Object : in out Observing_Camera; Target : Behaviors.Behavior_Ptr) is abstract; -- Orient the camera such that it looks at the given target function Target_Position (Object : Observing_Camera) return Vector4 is abstract; -- Return the position of the target the camera looks at ----------------------------------------------------------------------------- -- First person camera's -- ----------------------------------------------------------------------------- type First_Person_Camera is abstract new Camera with private; procedure Set_Position (Object : in out First_Person_Camera; Position : Vector4); overriding function View_Position (Object : First_Person_Camera) return Vector4; ----------------------------------------------------------------------------- -- Third person camera's -- ----------------------------------------------------------------------------- type Third_Person_Camera is abstract new Camera and Observing_Camera with private; overriding procedure Look_At (Object : in out Third_Person_Camera; Target : Behaviors.Behavior_Ptr); overriding function Target_Position (Object : Third_Person_Camera) return Vector4; private type Camera is abstract tagged record Lens : Camera_Lens; Scale : Vector4 := Default_Scale; Up : Vector4 := (0.0, 1.0, 0.0, 0.0); end record; type First_Person_Camera is abstract new Camera with record Position : Vector4 := (0.0, 0.0, 0.0, 1.0); end record; type Third_Person_Camera is abstract new Camera and Observing_Camera with record Target : Behaviors.Behavior_Ptr := Behaviors.Null_Behavior; end record; function Clamp_Distance is new Orka.Types.Clamp (GL.Types.Double, Distance); function Normalize_Angle is new Orka.Types.Normalize_Periodic (GL.Types.Double, Angle); subtype Matrix4 is Orka.Transforms.Doubles.Matrices.Matrix4; Y_Axis : constant Vector4 := (0.0, 1.0, 0.0, 0.0); function Look_At (Target, Camera, Up_World : Vector4) return Matrix4; function Rotate_To_Up (Object : Camera'Class) return Matrix4; protected type Change_Updater is procedure Set (Value : Vector4); procedure Get (Value : in out Vector4); private Change : Vector4 := (0.0, 0.0, 0.0, 0.0); Is_Set : Boolean := False; end Change_Updater; type Change_Updater_Ptr is not null access Change_Updater; end Orka.Cameras;
procedure Array_Collection is A : array (-3 .. -1) of Integer := (1, 2, 3); begin A (-3) := 3; A (-2) := 2; A (-1) := 1; end Array_Collection;
with AUnit; use AUnit; with AUnit.Test_Cases; use AUnit.Test_Cases; package ImageTests is type ImageTest is new AUnit.Test_Cases.Test_Case with null record; procedure Register_Tests(T: in out ImageTest); function Name(T: ImageTest) return Message_String; procedure testPixelArray(T : in out Test_Cases.Test_Case'Class); procedure testImageThresholding(T: in out Test_Cases.Test_Case'Class); procedure testImageIO(T: in out Test_Cases.Test_Case'Class); end ImageTests;
with MPFR.Root_FR; private with Ada.Finalization; package MPC.Root_C is pragma Preelaborate; type MP_Complex ( Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision) is private; function Re (X : MP_Complex) return MPFR.Root_FR.MP_Float; function Im (X : MP_Complex) return MPFR.Root_FR.MP_Float; function Compose (Re, Im : MPFR.Root_FR.MP_Float) return MP_Complex; function Compose ( Re : Long_Long_Float; Real_Precision : MPFR.Precision; Im : MPFR.Root_FR.MP_Float) return MP_Complex; function Image ( Value : MP_Complex; Base : Number_Base := 10; Rounding : MPC.Rounding) return String; function Value ( Image : String; Base : Number_Base := 10; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function "=" (Left, Right : MP_Complex) return Boolean; function "<" (Left, Right : MP_Complex) return Boolean; function ">" (Left, Right : MP_Complex) return Boolean; function "<=" (Left, Right : MP_Complex) return Boolean; function ">=" (Left, Right : MP_Complex) return Boolean; function Copy ( -- Positive Right : MP_Complex; Real_Precision : MPFR.Precision := MPFR.Default_Precision; Imaginary_Precision : MPFR.Precision := MPFR.Default_Precision; Rounding : MPC.Rounding := Default_Rounding) return MP_Complex; function Negative ( Right : MP_Complex; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function Add ( Left, Right : MP_Complex; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function Subtract ( Left, Right : MP_Complex; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function Multiply ( Left, Right : MP_Complex; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function Divide ( Left, Right : MP_Complex; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; function Power ( Left : MP_Complex; Right : Integer; Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision; Rounding : MPC.Rounding) return MP_Complex; private package Controlled is type MP_Complex is private; function Create ( Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision) return MP_Complex; function Reference (Item : in out Root_C.MP_Complex) return not null access C.mpc.mpc_struct; function Constant_Reference (Item : Root_C.MP_Complex) return not null access constant C.mpc.mpc_struct; pragma Inline (Reference); pragma Inline (Constant_Reference); private type MP_Complex is new Ada.Finalization.Controlled with record Raw : aliased C.mpc.mpc_t := (others => (others => (others => (others => <>)))); end record; overriding procedure Initialize (Object : in out MP_Complex); overriding procedure Adjust (Object : in out MP_Complex); overriding procedure Finalize (Object : in out MP_Complex); end Controlled; -- [gcc-4.8/4.9/5.0] derivation with discriminants makes many problems. type MP_Complex ( Real_Precision : MPFR.Precision; Imaginary_Precision : MPFR.Precision) is record Data : Controlled.MP_Complex := Controlled.Create (Real_Precision, Imaginary_Precision); end record; end MPC.Root_C;
with Ada.Text_IO; with Huffman; procedure Main is package Char_Natural_Huffman_Tree is new Huffman (Symbol_Type => Character, Put => Ada.Text_IO.Put, Symbol_Sequence => String, Frequency_Type => Natural); Tree : Char_Natural_Huffman_Tree.Huffman_Tree; Frequencies : Char_Natural_Huffman_Tree.Frequency_Maps.Map; Input_String : constant String := "this is an example for huffman encoding"; begin -- build frequency map for I in Input_String'Range loop declare use Char_Natural_Huffman_Tree.Frequency_Maps; Position : constant Cursor := Frequencies.Find (Input_String (I)); begin if Position = No_Element then Frequencies.Insert (Key => Input_String (I), New_Item => 1); else Frequencies.Replace_Element (Position => Position, New_Item => Element (Position) + 1); end if; end; end loop; -- create huffman tree Char_Natural_Huffman_Tree.Create_Tree (Tree => Tree, Frequencies => Frequencies); -- dump encodings Char_Natural_Huffman_Tree.Dump_Encoding (Tree => Tree); -- encode example string declare Code : constant Char_Natural_Huffman_Tree.Bit_Sequence := Char_Natural_Huffman_Tree.Encode (Tree => Tree, Symbols => Input_String); begin Char_Natural_Huffman_Tree.Put (Code); Ada.Text_IO.Put_Line (Char_Natural_Huffman_Tree.Decode (Tree => Tree, Code => Code)); end; end Main;
package body Pck is function Create_Small return Data_Small is begin return (others => 1); end Create_Small; function Create_Large return Data_Large is begin return (others => 2); end Create_Large; end Pck;
package body NCurses is procedure Start_Color_Init is begin Start_Color; Init_Color_Pair(1, COLOR_WHITE, COLOR_BLACK); Init_Color_Pair(2, COLOR_BLACK, COLOR_WHITE); Init_Color_Pair(3, COLOR_RED, COLOR_BLACK); Setup; end Start_Color_Init; procedure Pretty_Print_Window (Item : in String) is begin Print_Window(Item & ASCII.nul); end Pretty_Print_Window; procedure Pretty_Print_Line_Window (Item : in String) is begin Print_Window(Item & ASCII.lf & ASCII.nul); end Pretty_Print_Line_Window; end NCurses;
generic type element_t is private; package generic_linked_list is -- Exception levée en l'absence de noeud no_node : exception; -- Forward declaration du type node_t -- car celui contient de pointeur de son type -- et qu'on souhaite utiliser l'alias node_ptr type node_t is private; -- Déclaration du type pointeur vers node_t type node_ptr is access node_t; -- Créer une liste chaine avec un élément -- Renvoie le noeud de la chaine crée -- ATTENTION: destroy la liste une fois son utilisation terminée -- sinon risque de fuite mémoire function create(element : element_t) return node_ptr; -- Ajoute un élément à la fin de la liste chainée function add_after(node : node_ptr; element : element_t) return node_ptr; procedure add_after(node : node_ptr; element : element_t); -- Retire l'élement suivant l'élément passé en -- paramètre de la liste chainée -- Exception: no_node si aucun noeud suivant procedure remove_next(node : node_ptr); -- Indique si la liste contient un élément suivant function has_next(node : node_ptr) return boolean; -- Avance au noeud suivant -- Exception: no_node si aucun noeud suivant function move_next(node : node_ptr) return node_ptr; -- Renvoie l'élément porté par le noeud function elem(node : node_ptr) return element_t; -- Détruit la liste (noeud courrant & noeuds suivants) -- Les noeuds avant le noeud passé en paramètre sont ignorés procedure destroy(node : in out node_ptr); -- Définit un pointeur de fonction pour une fonction to_string sur element_t type to_string_function_t is access function (elem : element_t) return string; -- Donne une représentation textuelle de la liste (chacun des éléments) function to_string(node : node_ptr; to_string : to_string_function_t) return string; private -- Implémentation du type node_t -- privé type node_t is record -- l'élément porté par le noeud element : element_t; -- le noeud suivant next_node : node_ptr; end record; end generic_linked_list;
with GL_gl_h; use GL_gl_h; package Display.Basic.GLFonts is function getCharTexture(Char : Character) return GLUint; end Display.Basic.GLFonts;
package openGL.Palette -- -- Provides a pallete of named colors. -- -- Color values are sourced from WikiPaedia: -- -- - http://en.wikipedia.org/wiki/Primary_color -- - http://en.wikipedia.org/wiki/Secondary_color -- - http://en.wikipedia.org/wiki/Tertiary_color -- - http://en.wikipedia.org/wiki/List_of_colors -- is -------------------- -- Color Primitives -- -- Shades -- type Shade_Level is digits 7 range 0.0 .. 1.0; function Shade_of (Self : in Color; Level : in Shade_Level) return Color; -- -- Darkens a color by the given shade level factor. -- Color Mixing -- type mix_Factor is digits 7 range 0.0 .. 1.0; -- 0.0 returns 'Self', 1.0 returns 'Other'. function mixed (Self : in Color; Other : in Color; Mix : in mix_Factor := 0.5) return Color; -- -- Combines two colors. -- Similarity -- default_Similarity : constant Primary; function is_similar (Self : in Color; To : in Color; Similarity : in Primary := default_Similarity) return Boolean; -- -- Returns true if the none of the red, green, blue components of 'Self' -- differ from 'to' by more than 'Similarity'. -- Random Colors -- function random_Color return Color; ---------------- -- Named Colors -- -- Achromatic -- White : constant Color; Black : constant Color; Grey : constant Color; -- Primary -- Red : constant Color; Green : constant Color; Blue : constant Color; -- Secondary -- Yellow : constant Color; Cyan : constant Color; Magenta : constant Color; -- Tertiary -- Azure : constant Color; Violet : constant Color; Rose : constant Color; Orange : constant Color; Chartreuse : constant Color; spring_Green : constant Color; -- Named (TODO: sort named colors into primary, secondary and tertiary categories). -- Air_Force_blue : constant Color; Alice_blue : constant Color; Alizarin : constant Color; Amaranth : constant Color; Amaranth_cerise : constant Color; Amaranth_deep_purple : constant Color; Amaranth_magenta : constant Color; Amaranth_pink : constant Color; Amaranth_purple : constant Color; Amber : constant Color; Amber_SAE_ECE : constant Color; American_rose : constant Color; Amethyst : constant Color; Android_Green : constant Color; Anti_flash_white : constant Color; Antique_fuchsia : constant Color; Antique_white : constant Color; Apple_green : constant Color; Apricot : constant Color; Aqua : constant Color; Aquamarine : constant Color; Army_green : constant Color; Arsenic : constant Color; Ash_grey : constant Color; Asparagus : constant Color; Atomic_tangerine : constant Color; Auburn : constant Color; Aureolin : constant Color; Azure_mist : constant Color; Baby_blue : constant Color; Baby_pink : constant Color; Battleship_grey : constant Color; Beige : constant Color; Bistre : constant Color; Bittersweet : constant Color; Blue_pigment : constant Color; Blue_RYB : constant Color; Blue_green : constant Color; Blue_violet : constant Color; Bole : constant Color; Bondi_blue : constant Color; Boston_University_Red : constant Color; Brandeis_Blue : constant Color; Brass : constant Color; Brick_red : constant Color; Bright_cerulean : constant Color; Bright_green : constant Color; Bright_lavender : constant Color; Bright_maroon : constant Color; Bright_pink : constant Color; Bright_turquoise : constant Color; Bright_ube : constant Color; Brilliant_lavender : constant Color; Brilliant_rose : constant Color; Brink_Pink : constant Color; British_racing_green : constant Color; Bronze : constant Color; Brown : constant Color; Brown_web : constant Color; Buff : constant Color; Bulgarian_rose : constant Color; Burgundy : constant Color; Burnt_orange : constant Color; Burnt_sienna : constant Color; Burnt_umber : constant Color; Byzantine : constant Color; Byzantium : constant Color; Cadet_blue : constant Color; Cadmium_Green : constant Color; Cadmium_Orange : constant Color; Cadmium_Red : constant Color; Cadmium_Yellow : constant Color; Cambridge_Blue : constant Color; Camel : constant Color; Camouflage_green : constant Color; Canary_yellow : constant Color; Candy_apple_red : constant Color; Candy_pink : constant Color; Caput_mortuum : constant Color; Cardinal : constant Color; Carmine : constant Color; Carmine_pink : constant Color; Carmine_red : constant Color; Carnation_pink : constant Color; Carnelian : constant Color; Carolina_blue : constant Color; Caribbean_green : constant Color; Carrot_orange : constant Color; Ceil : constant Color; Celadon : constant Color; Celestial_blue : constant Color; Cerise : constant Color; Cerise_pink : constant Color; Cerulean : constant Color; Cerulean_blue : constant Color; Chamoisee : constant Color; Champagne : constant Color; Charcoal : constant Color; Chartreuse_web : constant Color; Cherry_blossom_pink : constant Color; Chestnut : constant Color; Chocolate : constant Color; Chrome_yellow : constant Color; Cinereous : constant Color; Cinnabar : constant Color; Cinnamon : constant Color; Citrine : constant Color; Classic_rose : constant Color; Cobalt : constant Color; Columbia_blue : constant Color; Cool_black : constant Color; Cool_grey : constant Color; Copper : constant Color; Copper_rose : constant Color; Coquelicot : constant Color; Coral : constant Color; Coral_pink : constant Color; Coral_red : constant Color; Cordovan : constant Color; Corn : constant Color; Cornsilk : constant Color; Cornflower_blue : constant Color; Cosmic_latte : constant Color; Cotton_candy : constant Color; Cream : constant Color; Crimson : constant Color; Crimson_glory : constant Color; Cyan_process : constant Color; Dandelion : constant Color; Dark_blue : constant Color; Dark_brown : constant Color; Dark_byzantium : constant Color; Dark_candy_apple_red : constant Color; Dark_cerulean : constant Color; Dark_champagne : constant Color; Dark_chestnut : constant Color; Dark_coral : constant Color; Dark_cyan : constant Color; Dark_electric_blue : constant Color; Dark_goldenrod : constant Color; Dark_green : constant Color; Dark_jungle_green : constant Color; Dark_khaki : constant Color; Dark_lava : constant Color; Dark_lavender : constant Color; Dark_magenta : constant Color; Dark_midnight_blue : constant Color; Dark_orange : constant Color; Dark_pastel_green : constant Color; Dark_pink : constant Color; Dark_powder_blue : constant Color; Dark_raspberry : constant Color; Dark_red : constant Color; Dark_salmon : constant Color; Dark_scarlet : constant Color; Dark_sienna : constant Color; Dark_slate_gray : constant Color; Dark_spring_green : constant Color; Dark_tan : constant Color; Dark_tangerine : constant Color; Dark_taupe : constant Color; Dark_terra_cotta : constant Color; Dark_turquoise : constant Color; Dark_violet : constant Color; Dartmouth_green : constant Color; Davys_grey : constant Color; Deep_carmine : constant Color; Deep_carmine_pink : constant Color; Deep_carrot_orange : constant Color; Deep_cerise : constant Color; Deep_champagne : constant Color; Deep_chestnut : constant Color; Deep_fuchsia : constant Color; Deep_jungle_green : constant Color; Deep_lilac : constant Color; Deep_magenta : constant Color; Deep_peach : constant Color; Deep_pink : constant Color; Deep_saffron : constant Color; Deep_sky_blue : constant Color; Denim : constant Color; Desert : constant Color; Desert_sand : constant Color; Dim_gray : constant Color; Dodger_blue : constant Color; Dogwood_Rose : constant Color; Drab : constant Color; Duke_blue : constant Color; Earth_yellow : constant Color; Ecru : constant Color; Eggplant : constant Color; Eggshell : constant Color; Egyptian_blue : constant Color; Electric_blue : constant Color; Electric_cyan : constant Color; Electric_green : constant Color; Electric_indigo : constant Color; Electric_lavender : constant Color; Electric_lime : constant Color; Electric_purple : constant Color; Electric_ultramarine : constant Color; Electric_violet : constant Color; Emerald : constant Color; Eton_blue : constant Color; Fallow : constant Color; Falu_red : constant Color; Fandango : constant Color; Fashion_fuchsia : constant Color; Fawn : constant Color; Feldgrau : constant Color; Fern_green : constant Color; Field_drab : constant Color; Firebrick : constant Color; Fire_engine_red : constant Color; Flame : constant Color; Flamingo_pink : constant Color; Flavescent : constant Color; Flax : constant Color; Forest_green : constant Color; Forest_green_web : constant Color; French_Beige : constant Color; French_Rose : constant Color; Fuchsia : constant Color; Fuchsia_Pink : constant Color; Fulvous : constant Color; Gamboge : constant Color; Ghost_white : constant Color; Glaucous : constant Color; Gold_metallic : constant Color; Gold_web : constant Color; Golden_brown : constant Color; Golden_poppy : constant Color; Golden_yellow : constant Color; Goldenrod : constant Color; Gray : constant Color; Gray_asparagus : constant Color; Green_web : constant Color; Green_pigment : constant Color; Green_RYB : constant Color; Green_yellow : constant Color; Grullo : constant Color; Halaya_ube : constant Color; Han_Blue : constant Color; Han_Purple : constant Color; Harlequin : constant Color; Heliotrope : constant Color; Hollywood_cerise : constant Color; Honeydew : constant Color; Hot_magenta : constant Color; Hot_pink : constant Color; Hunter_green : constant Color; Iceberg : constant Color; Icterine : constant Color; India_green : constant Color; Indian_yellow : constant Color; Indigo : constant Color; Indigo_web : constant Color; International_Klein_Blue : constant Color; International_orange : constant Color; Iris : constant Color; Isabelline : constant Color; Islamic_green : constant Color; Ivory : constant Color; Jade : constant Color; Jazzberry_jam : constant Color; Jonquil : constant Color; June_bud : constant Color; Jungle_green : constant Color; Kelly_green : constant Color; Khaki_web : constant Color; Khaki : constant Color; Languid_lavender : constant Color; Lava : constant Color; Lavender_floral : constant Color; Lavender_web : constant Color; Lavender_blue : constant Color; Lavender_blush : constant Color; Lavender_gray : constant Color; Lavender_indigo : constant Color; Lavender_magenta : constant Color; Lavender_mist : constant Color; Lavender_pink : constant Color; Lavender_purple : constant Color; Lavender_rose : constant Color; Lawn_green : constant Color; Lemon : constant Color; Lemon_chiffon : constant Color; Light_apricot : constant Color; Light_blue : constant Color; Light_carmine_pink : constant Color; Light_coral : constant Color; Light_cornflower_blue : constant Color; Light_fuchsia_pink : constant Color; Light_khaki : constant Color; Light_mauve : constant Color; Light_pink : constant Color; Light_sea_green : constant Color; Light_salmon : constant Color; Light_salmon_pink : constant Color; Light_sky_blue : constant Color; Light_slate_gray : constant Color; Light_Thulian_pink : constant Color; Lilac : constant Color; Lime : constant Color; Lime_web : constant Color; Lime_green : constant Color; Linen : constant Color; Liver : constant Color; Lust : constant Color; Magenta_dye : constant Color; Magenta_process : constant Color; Magic_mint : constant Color; Magnolia : constant Color; Mahogany : constant Color; Maize : constant Color; Majorelle_Blue : constant Color; Malachite : constant Color; Maroon_web : constant Color; Maroon : constant Color; Mauve : constant Color; Mauve_taupe : constant Color; Maya_blue : constant Color; Medium_aquamarine : constant Color; Medium_blue : constant Color; Medium_candy_apple_red : constant Color; Medium_carmine : constant Color; Medium_champagne : constant Color; Medium_electric_blue : constant Color; Medium_jungle_green : constant Color; Medium_lavender_magenta : constant Color; Medium_Persian_blue : constant Color; Medium_purple : constant Color; Medium_red_violet : constant Color; Medium_sea_green : constant Color; Medium_spring_bud : constant Color; Medium_spring_green : constant Color; Medium_taupe : constant Color; Medium_teal_blue : constant Color; Medium_turquoise : constant Color; Midnight_blue : constant Color; Midnight_green : constant Color; Eagle_green : constant Color; Mikado_yellow : constant Color; Mint_green : constant Color; Misty_rose : constant Color; Moccasin : constant Color; Mode_Beige : constant Color; Mordant_red : constant Color; Moss_green : constant Color; Mountbatten_pink : constant Color; Mulberry : constant Color; Mustard : constant Color; Myrtle : constant Color; MSU_Green : constant Color; Nadeshiko_pink : constant Color; Napier_Green : constant Color; Naples_Yellow : constant Color; Navajo_white : constant Color; Navy_Blue : constant Color; Ochre : constant Color; Office_green : constant Color; Old_Gold : constant Color; Old_Lace : constant Color; Old_lavender : constant Color; Old_Rose : constant Color; Olive : constant Color; Olive_Drab_web : constant Color; Olive_Drab : constant Color; Olivine : constant Color; Onyx : constant Color; Opera_mauve : constant Color; Orange_color_wheel : constant Color; Orange_RYB : constant Color; Orange_web : constant Color; Orange_peel : constant Color; Orange_red : constant Color; Orchid : constant Color; Oxford_Blue : constant Color; OU_Crimson_Red : constant Color; Pale_Amaranth_Pink : constant Color; Pale_blue : constant Color; Pale_brown : constant Color; Pale_carmine : constant Color; Pale_cerulean : constant Color; Pale_chestnut : constant Color; Pale_copper : constant Color; Pale_cornflower_blue : constant Color; Pale_gold : constant Color; Pale_magenta : constant Color; Pale_pink : constant Color; Pale_red_violet : constant Color; Pale_robin_egg_blue : constant Color; Pale_silver : constant Color; Pale_spring_bud : constant Color; Pale_taupe : constant Color; Palatinate_blue : constant Color; Palatinate_purple : constant Color; Pansy_purple : constant Color; Papaya_whip : constant Color; Pastel_green : constant Color; Pastel_pink : constant Color; Paynes_grey : constant Color; Peach : constant Color; Peach_orange : constant Color; Peach_puff : constant Color; Peach_yellow : constant Color; Pear : constant Color; Pearl : constant Color; Periwinkle : constant Color; Persian_blue : constant Color; Persian_green : constant Color; Persian_indigo : constant Color; Persian_orange : constant Color; Persian_red : constant Color; Persian_pink : constant Color; Persian_rose : constant Color; Persimmon : constant Color; Phthalo_blue : constant Color; Phthalo_green : constant Color; Piggy_pink : constant Color; Pine_green : constant Color; Pink : constant Color; Pink_orange : constant Color; Pistachio : constant Color; Platinum : constant Color; Plum : constant Color; Portland_Orange : constant Color; Powder_blue : constant Color; Princeton_Orange : constant Color; Prussian_blue : constant Color; Psychedelic_purple : constant Color; Puce : constant Color; Pumpkin : constant Color; Purple_web : constant Color; Purple : constant Color; Purple_Heart : constant Color; Purple_mountain_majesty : constant Color; Purple_taupe : constant Color; Radical_Red : constant Color; Raspberry : constant Color; Raspberry_glace : constant Color; Raspberry_pink : constant Color; Raspberry_rose : constant Color; Raw_umber : constant Color; Razzle_dazzle_rose : constant Color; Razzmatazz : constant Color; Red_pigment : constant Color; Red_RYB : constant Color; Red_violet : constant Color; Rich_black : constant Color; Rich_brilliant_lavender : constant Color; Rich_carmine : constant Color; Rich_electric_blue : constant Color; Rich_lavender : constant Color; Rich_maroon : constant Color; Rifle_green : constant Color; Robin_egg_blue : constant Color; Rose_Ebony : constant Color; Rose_Gold : constant Color; Rose_Madder : constant Color; Rose_pink : constant Color; Rose_quartz : constant Color; Rose_taupe : constant Color; Rose_vale : constant Color; Rosewood : constant Color; Rosso_corsa : constant Color; Rosy_brown : constant Color; Royal_azure : constant Color; Royal_blue : constant Color; Royal_blue_web : constant Color; Royal_fuchsia : constant Color; Royal_purple : constant Color; Ruby : constant Color; Rufous : constant Color; Russet : constant Color; Rust : constant Color; Sacramento_State_green : constant Color; Saddle_brown : constant Color; Safety_orange : constant Color; blaze_orange : constant Color; Saffron : constant Color; St_Patricks_blue : constant Color; Salmon : constant Color; Salmon_pink : constant Color; Sand : constant Color; Sand_dune : constant Color; Sandy_brown : constant Color; Sandy_taupe : constant Color; Sangria : constant Color; Sap_green : constant Color; Sapphire : constant Color; Satin_sheen_gold : constant Color; Scarlet : constant Color; School_bus_yellow : constant Color; Sea_green : constant Color; Seal_brown : constant Color; Seashell : constant Color; Selective_yellow : constant Color; Sepia : constant Color; Shamrock_green : constant Color; Shocking_pink : constant Color; Sienna : constant Color; Silver : constant Color; Skobeloff : constant Color; Sky_blue : constant Color; Sky_magenta : constant Color; Slate_gray : constant Color; Smalt : constant Color; Smoky_black : constant Color; Snow : constant Color; Splashed_white : constant Color; Spring_bud : constant Color; Steel_blue : constant Color; Straw : constant Color; Sunglow : constant Color; Sunset : constant Color; Tan : constant Color; Tangelo : constant Color; Tangerine : constant Color; Tangerine_yellow : constant Color; Taupe : constant Color; Taupe_gray : constant Color; Tea_green : constant Color; Tea_rose_orange : constant Color; Tea_rose : constant Color; Teal : constant Color; Teal_blue : constant Color; Tenne : constant Color; Tawny : constant Color; Terra_cotta : constant Color; Thistle : constant Color; Thulian_pink : constant Color; Tiffany_Blue : constant Color; Tomato : constant Color; Torch_red : constant Color; Tropical_rain_forest : constant Color; Turkish_Rose : constant Color; Turquoise : constant Color; Turquoise_blue : constant Color; Tuscan_red : constant Color; Twilight_lavender : constant Color; Tyrian_purple : constant Color; Ube : constant Color; Ultramarine : constant Color; Ultramarine_blue : constant Color; Ultra_pink : constant Color; Umber : constant Color; United_Nations_blue : constant Color; Upsdell_red : constant Color; UP_Forest_green : constant Color; UP_Maroon : constant Color; Vegas_Gold : constant Color; Venetian_red : constant Color; Vermilion : constant Color; Violet_web : constant Color; Violet_RYB : constant Color; Viridian : constant Color; Vivid_auburn : constant Color; Vivid_burgundy : constant Color; Vivid_violet : constant Color; Warm_black : constant Color; Wenge : constant Color; Wheat : constant Color; White_smoke : constant Color; Wild_blue_yonder : constant Color; Wisteria : constant Color; Xanadu : constant Color; Yale_Blue : constant Color; Yellow_process : constant Color; Yellow_RYB : constant Color; Yellow_green : constant Color; private default_Similarity : constant Primary := to_Primary (3); White : constant Color := (1.0, 1.0, 1.0); Black : constant Color := (0.0, 0.0, 0.0); Grey : constant Color := (0.5, 0.5, 0.5); Red : constant Color := (1.0, 0.0, 0.0); Green : constant Color := (0.0, 1.0, 0.0); Blue : constant Color := (0.0, 0.0, 1.0); Yellow : constant Color := (1.0, 1.0, 0.0); Cyan : constant Color := (0.0, 1.0, 1.0); Magenta : constant Color := (1.0, 0.0, 1.0); Azure : constant Color := +( 0, 127, 255); Violet : constant Color := +(139, 0, 255); Rose : constant Color := +(255, 0, 127); Orange : constant Color := +(255, 127, 0); Chartreuse : constant Color := +(223, 255, 0); spring_Green : constant Color := +( 0, 255, 127); Air_Force_blue : constant Color := +(93, 138, 168); Alice_blue : constant Color := +(240, 248, 255); Alizarin : constant Color := +(227, 38, 54); Amaranth : constant Color := +(229, 43, 80); Amaranth_cerise : constant Color := +(205, 38, 130); Amaranth_deep_purple : constant Color := +(159, 43, 104); Amaranth_magenta : constant Color := +(237, 60, 202); Amaranth_pink : constant Color := +(241, 156, 187); Amaranth_purple : constant Color := +(171, 39, 79); Amber : constant Color := +(255, 191, 0); Amber_SAE_ECE : constant Color := +(255, 126, 0); American_rose : constant Color := +(255, 3, 62); Amethyst : constant Color := +(153, 102, 204); Android_Green : constant Color := +(164, 198, 57); Anti_flash_white : constant Color := +(242, 243, 244); Antique_fuchsia : constant Color := +(145, 92, 131); Antique_white : constant Color := +(250, 235, 215); Apple_green : constant Color := +(141, 182, 0); Apricot : constant Color := +(251, 206, 177); Aqua : constant Color := +(0, 255, 255); Aquamarine : constant Color := +(127, 255, 212); Army_green : constant Color := +(75, 83, 32); Arsenic : constant Color := +(59, 68, 75); Ash_grey : constant Color := +(178, 190, 181); Asparagus : constant Color := +(135, 169, 107); Atomic_tangerine : constant Color := +(255, 153, 102); Auburn : constant Color := +(109, 53, 26); Aureolin : constant Color := +(253, 238, 0); Azure_mist : constant Color := +(240, 255, 255); Baby_blue : constant Color := +(224, 255, 255); Baby_pink : constant Color := +(244, 194, 194); Battleship_grey : constant Color := +(132, 132, 130); Beige : constant Color := +(245, 245, 220); Bistre : constant Color := +(61, 43, 31); Bittersweet : constant Color := +(254, 111, 94); Blue_pigment : constant Color := +(51, 51, 153); Blue_RYB : constant Color := +(2, 71, 254); Blue_green : constant Color := +(0, 221, 221); Blue_violet : constant Color := +(138, 43, 226); Bole : constant Color := +(121, 68, 59); Bondi_blue : constant Color := +(0, 149, 182); Boston_University_Red : constant Color := +(204, 0, 0); Brandeis_Blue : constant Color := +(0, 112, 255); Brass : constant Color := +(181, 166, 66); Brick_red : constant Color := +(203, 65, 84); Bright_cerulean : constant Color := +(29, 172, 214); Bright_green : constant Color := +(102, 255, 0); Bright_lavender : constant Color := +(191, 148, 228); Bright_maroon : constant Color := +(195, 33, 72); Bright_pink : constant Color := +(255, 0, 127); Bright_turquoise : constant Color := +(8, 232, 222); Bright_ube : constant Color := +(209, 159, 232); Brilliant_lavender : constant Color := +(244, 187, 255); Brilliant_rose : constant Color := +(255, 85, 163); Brink_Pink : constant Color := +(251, 96, 127); British_racing_green : constant Color := +(0, 66, 37); Bronze : constant Color := +(205, 127, 50); Brown : constant Color := +(150, 75, 0); Brown_web : constant Color := +(165, 42, 42); Buff : constant Color := +(240, 220, 130); Bulgarian_rose : constant Color := +(72, 6, 7); Burgundy : constant Color := +(128, 0, 32); Burnt_orange : constant Color := +(204, 85, 0); Burnt_sienna : constant Color := +(233, 116, 81); Burnt_umber : constant Color := +(138, 51, 36); Byzantine : constant Color := +(189, 51, 164); Byzantium : constant Color := +(112, 41, 99); Cadet_blue : constant Color := +(95, 158, 160); Cadmium_Green : constant Color := +(0, 107, 60); Cadmium_Orange : constant Color := +(237, 135, 45); Cadmium_Red : constant Color := +(227, 0, 34); Cadmium_Yellow : constant Color := +(255, 246, 0); Cambridge_Blue : constant Color := +(153, 204, 204); Camel : constant Color := +(193, 154, 107); Camouflage_green : constant Color := +(120, 134, 107); Canary_yellow : constant Color := +(255, 239, 0); Candy_apple_red : constant Color := +(255, 8, 0); Candy_pink : constant Color := +(228, 113, 122); Caput_mortuum : constant Color := +(89, 39, 32); Cardinal : constant Color := +(196, 30, 58); Carmine : constant Color := +(150, 0, 24); Carmine_pink : constant Color := +(235, 76, 66); Carmine_red : constant Color := +(255, 0, 51); Carnation_pink : constant Color := +(255, 166, 201); Carnelian : constant Color := +(179, 27, 27); Carolina_blue : constant Color := +(153, 186, 227); Caribbean_green : constant Color := +(0, 204, 153); Carrot_orange : constant Color := +(237, 145, 33); Ceil : constant Color := +(147, 162, 208); Celadon : constant Color := +(172, 225, 175); Celestial_blue : constant Color := +(73, 151, 208); Cerise : constant Color := +(222, 49, 99); Cerise_pink : constant Color := +(236, 59, 131); Cerulean : constant Color := +(0, 123, 167); Cerulean_blue : constant Color := +(42, 82, 190); Chamoisee : constant Color := +(160, 120, 90); Champagne : constant Color := +(247, 231, 206); Charcoal : constant Color := +(54, 69, 79); Chartreuse_web : constant Color := +(127, 255, 0); Cherry_blossom_pink : constant Color := +(255, 183, 197); Chestnut : constant Color := +(205, 92, 92); Chocolate : constant Color := +(123, 63, 0); Chrome_yellow : constant Color := +(255, 167, 0); Cinereous : constant Color := +(152, 129, 123); Cinnabar : constant Color := +(227, 66, 52); Cinnamon : constant Color := +(210, 105, 30); Citrine : constant Color := +(228, 208, 10); Classic_rose : constant Color := +(251, 204, 231); Cobalt : constant Color := +(0, 71, 171); Columbia_blue : constant Color := +(155, 221, 255); Cool_black : constant Color := +(0, 46, 99); Cool_grey : constant Color := +(140, 146, 172); Copper : constant Color := +(184, 115, 51); Copper_rose : constant Color := +(153, 102, 102); Coquelicot : constant Color := +(255, 56, 0); Coral : constant Color := +(255, 127, 80); Coral_pink : constant Color := +(248, 131, 121); Coral_red : constant Color := +(255, 64, 64); Cordovan : constant Color := +(137, 63, 69); Corn : constant Color := +(251, 236, 93); Cornsilk : constant Color := +(255, 248, 220); Cornflower_blue : constant Color := +(100, 149, 237); Cosmic_latte : constant Color := +(255, 248, 231); Cotton_candy : constant Color := +(255, 188, 217); Cream : constant Color := +(255, 253, 208); Crimson : constant Color := +(220, 20, 60); Crimson_glory : constant Color := +(190, 0, 50); Cyan_process : constant Color := +(0, 183, 235); Dandelion : constant Color := +(240, 225, 48); Dark_blue : constant Color := +(0, 0, 139); Dark_brown : constant Color := +(101, 67, 33); Dark_byzantium : constant Color := +(93, 57, 84); Dark_candy_apple_red : constant Color := +(164, 0, 0); Dark_cerulean : constant Color := +(8, 69, 126); Dark_champagne : constant Color := +(194, 178, 128); Dark_chestnut : constant Color := +(152, 105, 96); Dark_coral : constant Color := +(205, 91, 69); Dark_cyan : constant Color := +(0, 139, 139); Dark_electric_blue : constant Color := +(83, 104, 120); Dark_goldenrod : constant Color := +(184, 134, 11); Dark_green : constant Color := +(1, 50, 32); Dark_jungle_green : constant Color := +(26, 36, 33); Dark_khaki : constant Color := +(189, 183, 107); Dark_lava : constant Color := +(72, 60, 50); Dark_lavender : constant Color := +(115, 79, 150); Dark_magenta : constant Color := +(139, 0, 139); Dark_midnight_blue : constant Color := +(0, 51, 102); Dark_orange : constant Color := +(255, 140, 0); Dark_pastel_green : constant Color := +(3, 192, 60); Dark_pink : constant Color := +(231, 84, 128); Dark_powder_blue : constant Color := +(0, 51, 153); Dark_raspberry : constant Color := +(135, 38, 87); Dark_red : constant Color := +(139, 0, 0); Dark_salmon : constant Color := +(233, 150, 122); Dark_scarlet : constant Color := +(86, 3, 25); Dark_sienna : constant Color := +(60, 20, 20); Dark_slate_gray : constant Color := +(47, 79, 79); Dark_spring_green : constant Color := +(23, 114, 69); Dark_tan : constant Color := +(145, 129, 81); Dark_tangerine : constant Color := +(255, 168, 18); Dark_taupe : constant Color := +(72, 60, 50); Dark_terra_cotta : constant Color := +(204, 78, 92); Dark_turquoise : constant Color := +(0, 206, 209); Dark_violet : constant Color := +(148, 0, 211); Dartmouth_green : constant Color := +(13, 128, 15); Davys_grey : constant Color := +(85, 85, 85); Deep_carmine : constant Color := +(169, 32, 62); Deep_carmine_pink : constant Color := +(239, 48, 56); Deep_carrot_orange : constant Color := +(233, 105, 44); Deep_cerise : constant Color := +(218, 50, 135); Deep_champagne : constant Color := +(250, 214, 165); Deep_chestnut : constant Color := +(185, 78, 72); Deep_fuchsia : constant Color := +(193, 84, 193); Deep_jungle_green : constant Color := +(0, 75, 73); Deep_lilac : constant Color := +(153, 85, 187); Deep_magenta : constant Color := +(205, 0, 204); Deep_peach : constant Color := +(255, 203, 164); Deep_pink : constant Color := +(255, 20, 147); Deep_saffron : constant Color := +(255, 153, 51); Deep_sky_blue : constant Color := +(0, 191, 255); Denim : constant Color := +(21, 96, 189); Desert : constant Color := +(193, 154, 107); Desert_sand : constant Color := +(237, 201, 175); Dim_gray : constant Color := +(105, 105, 105); Dodger_blue : constant Color := +(30, 144, 255); Dogwood_Rose : constant Color := +(215, 24, 104); Drab : constant Color := +(150, 113, 23); Duke_blue : constant Color := +(0, 0, 156); Earth_yellow : constant Color := +(225, 169, 95); Ecru : constant Color := +(194, 178, 128); Eggplant : constant Color := +(97, 64, 81); Eggshell : constant Color := +(240, 234, 214); Egyptian_blue : constant Color := +(16, 52, 166); Electric_blue : constant Color := +(125, 249, 255); Electric_cyan : constant Color := +(0, 255, 255); Electric_green : constant Color := +(0, 255, 0); Electric_indigo : constant Color := +(111, 0, 255); Electric_lavender : constant Color := +(244, 187, 255); Electric_lime : constant Color := +(204, 255, 0); Electric_purple : constant Color := +(191, 0, 255); Electric_ultramarine : constant Color := +(63, 0, 255); Electric_violet : constant Color := +(139, 0, 255); Emerald : constant Color := +(80, 200, 120); Eton_blue : constant Color := +(150, 200, 162); Fallow : constant Color := +(193, 154, 107); Falu_red : constant Color := +(128, 24, 24); Fandango : constant Color := +(184, 84, 137); Fashion_fuchsia : constant Color := +(244, 0, 161); Fawn : constant Color := +(229, 170, 112); Feldgrau : constant Color := +(77, 93, 83); Fern_green : constant Color := +(79, 121, 66); Field_drab : constant Color := +(108, 84, 30); Firebrick : constant Color := +(178, 34, 34); Fire_engine_red : constant Color := +(206, 22, 32); Flame : constant Color := +(226, 88, 34); Flamingo_pink : constant Color := +(252, 142, 172); Flavescent : constant Color := +(247, 233, 142); Flax : constant Color := +(238, 220, 130); Forest_green : constant Color := +(1, 68, 33); Forest_green_web : constant Color := +(34, 139, 34); French_Beige : constant Color := +(166, 123, 91); French_Rose : constant Color := +(246, 74, 138); Fuchsia : constant Color := +(255, 0, 255); Fuchsia_Pink : constant Color := +(255, 119, 255); Fulvous : constant Color := +(220, 132, 0); Gamboge : constant Color := +(228, 155, 15); Ghost_white : constant Color := +(248, 248, 255); Glaucous : constant Color := +(96, 130, 182); Gold_metallic : constant Color := +(212, 175, 55); Gold_web : constant Color := +(255, 215, 0); Golden_brown : constant Color := +(153, 101, 21); Golden_poppy : constant Color := +(252, 194, 0); Golden_yellow : constant Color := +(255, 223, 0); Goldenrod : constant Color := +(218, 165, 32); Gray : constant Color := +(128, 128, 128); Gray_asparagus : constant Color := +(70, 89, 69); Green_web : constant Color := +(0, 128, 0); Green_pigment : constant Color := +(0, 165, 80); Green_RYB : constant Color := +(102, 176, 50); Green_yellow : constant Color := +(173, 255, 47); Grullo : constant Color := +(169, 154, 134); Halaya_ube : constant Color := +(102, 56, 84); Han_Blue : constant Color := +(82, 24, 250); Han_Purple : constant Color := +(82, 24, 250); Harlequin : constant Color := +(63, 255, 0); Heliotrope : constant Color := +(223, 115, 255); Hollywood_cerise : constant Color := +(244, 0, 161); Honeydew : constant Color := +(240, 255, 240); Hot_magenta : constant Color := +(255, 0, 204); Hot_pink : constant Color := +(255, 105, 180); Hunter_green : constant Color := +(53, 94, 59); Iceberg : constant Color := +(113, 166, 210); Icterine : constant Color := +(252, 247, 94); India_green : constant Color := +(19, 136, 8); Indian_yellow : constant Color := +(227, 168, 87); Indigo : constant Color := +(0, 65, 106); Indigo_web : constant Color := +(75, 0, 130); International_Klein_Blue : constant Color := +(0, 47, 167); International_orange : constant Color := +(255, 79, 0); Iris : constant Color := +(90, 79, 207); Isabelline : constant Color := +(244, 240, 236); Islamic_green : constant Color := +(0, 144, 0); Ivory : constant Color := +(255, 255, 240); Jade : constant Color := +(0, 168, 107); Jazzberry_jam : constant Color := +(165, 11, 94); Jonquil : constant Color := +(250, 218, 94); June_bud : constant Color := +(189, 218, 87); Jungle_green : constant Color := +(41, 171, 135); Kelly_green : constant Color := +(76, 187, 23); Khaki_web : constant Color := +(195, 176, 145); Khaki : constant Color := +(240, 230, 140); Languid_lavender : constant Color := +(214, 202, 221); Lava : constant Color := +(207, 16, 32); Lavender_floral : constant Color := +(181, 126, 220); Lavender_web : constant Color := +(230, 230, 250); Lavender_blue : constant Color := +(204, 204, 255); Lavender_blush : constant Color := +(255, 240, 245); Lavender_gray : constant Color := +(196, 195, 208); Lavender_indigo : constant Color := +(148, 87, 235); Lavender_magenta : constant Color := +(238, 130, 238); Lavender_mist : constant Color := +(230, 230, 250); Lavender_pink : constant Color := +(251, 174, 210); Lavender_purple : constant Color := +(150, 123, 182); Lavender_rose : constant Color := +(251, 160, 227); Lawn_green : constant Color := +(124, 252, 0); Lemon : constant Color := +(255, 247, 0); Lemon_chiffon : constant Color := +(255, 250, 205); Light_apricot : constant Color := +(253, 213, 177); Light_blue : constant Color := +(173, 216, 230); Light_carmine_pink : constant Color := +(230, 103, 97); Light_coral : constant Color := +(240, 128, 128); Light_cornflower_blue : constant Color := +(173, 216, 230); Light_fuchsia_pink : constant Color := +(249, 132, 229); Light_khaki : constant Color := +(240, 230, 140); Light_mauve : constant Color := +(220, 208, 255); Light_pink : constant Color := +(255, 182, 193); Light_sea_green : constant Color := +(32, 178, 170); Light_salmon : constant Color := +(255, 160, 122); Light_salmon_pink : constant Color := +(255, 153, 153); Light_sky_blue : constant Color := +(135, 206, 250); Light_slate_gray : constant Color := +(119, 136, 153); Light_Thulian_pink : constant Color := +(230, 143, 172); Lilac : constant Color := +(200, 162, 200); Lime : constant Color := +(191, 255, 0); Lime_web : constant Color := +(0, 255, 0); Lime_green : constant Color := +(50, 205, 50); Linen : constant Color := +(250, 240, 230); Liver : constant Color := +(83, 75, 79); Lust : constant Color := +(230, 32, 32); Magenta_dye : constant Color := +(202, 21, 123); Magenta_process : constant Color := +(255, 0, 144); Magic_mint : constant Color := +(170, 240, 209); Magnolia : constant Color := +(248, 244, 255); Mahogany : constant Color := +(192, 64, 0); Maize : constant Color := +(251, 236, 94); Majorelle_Blue : constant Color := +(96, 80, 220); Malachite : constant Color := +(11, 218, 81); Maroon_web : constant Color := +(128, 0, 0); Maroon : constant Color := +(176, 48, 96); Mauve : constant Color := +(224, 176, 255); Mauve_taupe : constant Color := +(145, 95, 109); Maya_blue : constant Color := +(115, 194, 251); Medium_aquamarine : constant Color := +(0, 84, 180); Medium_blue : constant Color := +(0, 0, 205); Medium_candy_apple_red : constant Color := +(226, 6, 44); Medium_carmine : constant Color := +(175, 64, 53); Medium_champagne : constant Color := +(243, 229, 171); Medium_electric_blue : constant Color := +(3, 80, 150); Medium_jungle_green : constant Color := +(28, 53, 45); Medium_lavender_magenta : constant Color := +(204, 153, 204); Medium_Persian_blue : constant Color := +(0, 103, 165); Medium_purple : constant Color := +(147, 112, 219); Medium_red_violet : constant Color := +(187, 51, 133); Medium_sea_green : constant Color := +(60, 179, 113); Medium_spring_bud : constant Color := +(201, 220, 137); Medium_spring_green : constant Color := +(0, 250, 154); Medium_taupe : constant Color := +(103, 76, 71); Medium_teal_blue : constant Color := +(0, 84, 180); Medium_turquoise : constant Color := +(72, 209, 204); Midnight_blue : constant Color := +(25, 25, 112); Midnight_green : constant Color := +(0, 73, 83); Eagle_green : constant Color := +(0, 73, 83); Mikado_yellow : constant Color := +(255, 196, 12); Mint_green : constant Color := +(152, 255, 152); Misty_rose : constant Color := +(255, 228, 225); Moccasin : constant Color := +(250, 235, 215); Mode_Beige : constant Color := +(150, 113, 23); Mordant_red : constant Color := +(174, 12, 0); Moss_green : constant Color := +(173, 223, 173); Mountbatten_pink : constant Color := +(153, 122, 141); Mulberry : constant Color := +(197, 75, 140); Mustard : constant Color := +(255, 219, 88); Myrtle : constant Color := +(33, 66, 30); MSU_Green : constant Color := +(0, 102, 51); Nadeshiko_pink : constant Color := +(246, 173, 198); Napier_Green : constant Color := +(42, 128, 0); Naples_Yellow : constant Color := +(250, 218, 94); Navajo_white : constant Color := +(255, 222, 173); Navy_Blue : constant Color := +(0, 0, 128); Ochre : constant Color := +(204, 119, 34); Office_green : constant Color := +(0, 128, 0); Old_Gold : constant Color := +(207, 181, 59); Old_Lace : constant Color := +(253, 245, 230); Old_lavender : constant Color := +(121, 104, 120); Old_Rose : constant Color := +(192, 128, 129); Olive : constant Color := +(128, 128, 0); Olive_Drab_web : constant Color := +(107, 142, 35); Olive_Drab : constant Color := +(60, 52, 31); Olivine : constant Color := +(154, 185, 115); Onyx : constant Color := +(15, 15, 15); Opera_mauve : constant Color := +(183, 132, 167); Orange_color_wheel : constant Color := +(255, 127, 0); Orange_RYB : constant Color := +(251, 153, 2); Orange_web : constant Color := +(255, 165, 0); Orange_peel : constant Color := +(255, 159, 0); Orange_red : constant Color := +(255, 69, 0); Orchid : constant Color := +(218, 112, 214); Oxford_Blue : constant Color := +(0, 33, 71); OU_Crimson_Red : constant Color := +(153, 0, 0); Pale_Amaranth_Pink : constant Color := +(221, 190, 195); Pale_blue : constant Color := +(175, 238, 238); Pale_brown : constant Color := +(152, 118, 84); Pale_carmine : constant Color := +(175, 64, 53); Pale_cerulean : constant Color := +(155, 196, 226); Pale_chestnut : constant Color := +(221, 173, 175); Pale_copper : constant Color := +(218, 138, 103); Pale_cornflower_blue : constant Color := +(171, 205, 239); Pale_gold : constant Color := +(230, 190, 138); Pale_magenta : constant Color := +(249, 132, 229); Pale_pink : constant Color := +(250, 218, 221); Pale_red_violet : constant Color := +(219, 112, 147); Pale_robin_egg_blue : constant Color := +(150, 222, 209); Pale_silver : constant Color := +(201, 192, 187); Pale_spring_bud : constant Color := +(236, 235, 189); Pale_taupe : constant Color := +(188, 152, 126); Palatinate_blue : constant Color := +(39, 59, 226); Palatinate_purple : constant Color := +(104, 40, 96); Pansy_purple : constant Color := +(120, 24, 74); Papaya_whip : constant Color := +(255, 239, 213); Pastel_green : constant Color := +(119, 221, 119); Pastel_pink : constant Color := +(255, 209, 220); Paynes_grey : constant Color := +(64, 64, 72); Peach : constant Color := +(255, 229, 180); Peach_orange : constant Color := +(255, 204, 153); Peach_puff : constant Color := +(255, 218, 185); Peach_yellow : constant Color := +(250, 223, 173); Pear : constant Color := +(209, 226, 49); Pearl : constant Color := +(240, 234, 214); Periwinkle : constant Color := +(204, 204, 255); Persian_blue : constant Color := +(28, 57, 187); Persian_green : constant Color := +(0, 166, 147); Persian_indigo : constant Color := +(50, 18, 122); Persian_orange : constant Color := +(217, 144, 88); Persian_red : constant Color := +(204, 51, 51); Persian_pink : constant Color := +(247, 127, 190); Persian_rose : constant Color := +(254, 40, 162); Persimmon : constant Color := +(236, 88, 0); Phthalo_blue : constant Color := +(0, 15, 137); Phthalo_green : constant Color := +(18, 53, 36); Piggy_pink : constant Color := +(253, 221, 230); Pine_green : constant Color := +(1, 121, 111); Pink : constant Color := +(255, 192, 203); Pink_orange : constant Color := +(255, 153, 102); Pistachio : constant Color := +(147, 197, 114); Platinum : constant Color := +(229, 228, 226); Plum : constant Color := +(204, 153, 204); Portland_Orange : constant Color := +(255, 90, 54); Powder_blue : constant Color := +(176, 224, 230); Princeton_Orange : constant Color := +(215, 71, 33); Prussian_blue : constant Color := +(0, 49, 83); Psychedelic_purple : constant Color := +(221, 0, 255); Puce : constant Color := +(204, 136, 153); Pumpkin : constant Color := +(255, 117, 24); Purple_web : constant Color := +(127, 0, 127); Purple : constant Color := +(160, 92, 240); Purple_Heart : constant Color := +(105, 53, 156); Purple_mountain_majesty : constant Color := +(150, 120, 182); Purple_taupe : constant Color := +(80, 64, 77); Radical_Red : constant Color := +(255, 53, 94); Raspberry : constant Color := +(227, 11, 92); Raspberry_glace : constant Color := +(145, 95, 109); Raspberry_pink : constant Color := +(226, 80, 155); Raspberry_rose : constant Color := +(179, 68, 108); Raw_umber : constant Color := +(130, 102, 68); Razzle_dazzle_rose : constant Color := +(255, 51, 204); Razzmatazz : constant Color := +(227, 37, 107); Red_pigment : constant Color := +(237, 28, 36); Red_RYB : constant Color := +(254, 39, 18); Red_violet : constant Color := +(199, 21, 133); Rich_black : constant Color := +(0, 64, 64); Rich_brilliant_lavender : constant Color := +(241, 167, 254); Rich_carmine : constant Color := +(215, 0, 64); Rich_electric_blue : constant Color := +(8, 146, 208); Rich_lavender : constant Color := +(170, 97, 204); Rich_maroon : constant Color := +(176, 48, 96); Rifle_green : constant Color := +(65, 72, 51); Robin_egg_blue : constant Color := +(0, 204, 204); Rose_Ebony : constant Color := +(103, 76, 71); Rose_Gold : constant Color := +(183, 110, 121); Rose_Madder : constant Color := +(227, 38, 54); Rose_pink : constant Color := +(255, 102, 204); Rose_quartz : constant Color := +(170, 152, 169); Rose_taupe : constant Color := +(144, 93, 93); Rose_vale : constant Color := +(171, 78, 82); Rosewood : constant Color := +(101, 0, 11); Rosso_corsa : constant Color := +(212, 0, 0); Rosy_brown : constant Color := +(188, 143, 143); Royal_azure : constant Color := +(0, 56, 168); Royal_blue : constant Color := +(0, 35, 102); Royal_blue_web : constant Color := +(65, 105, 225); Royal_fuchsia : constant Color := +(202, 44, 146); Royal_purple : constant Color := +(107, 63, 160); Ruby : constant Color := +(224, 17, 95); Rufous : constant Color := +(168, 28, 7); Russet : constant Color := +(128, 70, 27); Rust : constant Color := +(183, 65, 14); Sacramento_State_green : constant Color := +(0, 86, 63); Saddle_brown : constant Color := +(139, 69, 19); Safety_orange : constant Color := +(255, 102, 0); blaze_orange : constant Color := +(255, 102, 0); Saffron : constant Color := +(244, 196, 48); St_Patricks_blue : constant Color := +(35, 41, 122); Salmon : constant Color := +(255, 140, 105); Salmon_pink : constant Color := +(255, 145, 164); Sand : constant Color := +(194, 178, 128); Sand_dune : constant Color := +(150, 113, 23); Sandy_brown : constant Color := +(244, 164, 96); Sandy_taupe : constant Color := +(150, 113, 23); Sangria : constant Color := +(146, 0, 10); Sap_green : constant Color := +(80, 125, 42); Sapphire : constant Color := +(8, 37, 103); Satin_sheen_gold : constant Color := +(203, 161, 53); Scarlet : constant Color := +(255, 32, 0); School_bus_yellow : constant Color := +(255, 216, 0); Sea_green : constant Color := +(46, 139, 87); Seal_brown : constant Color := +(50, 20, 20); Seashell : constant Color := +(255, 245, 238); Selective_yellow : constant Color := +(255, 186, 0); Sepia : constant Color := +(112, 66, 20); Shamrock_green : constant Color := +(0, 158, 96); Shocking_pink : constant Color := +(252, 15, 192); Sienna : constant Color := +(136, 45, 23); Silver : constant Color := +(192, 192, 192); Skobeloff : constant Color := +(0, 122, 116); Sky_blue : constant Color := +(135, 206, 235); Sky_magenta : constant Color := +(207, 113, 175); Slate_gray : constant Color := +(112, 128, 144); Smalt : constant Color := +(0, 51, 153); Smoky_black : constant Color := +(16, 12, 8); Snow : constant Color := +(255, 250, 250); Splashed_white : constant Color := +(254, 253, 255); Spring_bud : constant Color := +(167, 252, 0); Steel_blue : constant Color := +(70, 130, 180); Straw : constant Color := +(228, 117, 111); Sunglow : constant Color := +(255, 204, 51); Sunset : constant Color := +(250, 214, 165); Tan : constant Color := +(210, 180, 140); Tangelo : constant Color := +(249, 77, 0); Tangerine : constant Color := +(242, 133, 0); Tangerine_yellow : constant Color := +(255, 204, 0); Taupe : constant Color := +(72, 60, 50); Taupe_gray : constant Color := +(139, 133, 137); Tea_green : constant Color := +(208, 240, 192); Tea_rose_orange : constant Color := +(248, 131, 121); Tea_rose : constant Color := +(244, 194, 194); Teal : constant Color := +(0, 128, 128); Teal_blue : constant Color := +(54, 117, 136); Tenne : constant Color := +(205, 87, 0); Tawny : constant Color := +(205, 87, 0); Terra_cotta : constant Color := +(226, 114, 91); Thistle : constant Color := +(216, 191, 216); Thulian_pink : constant Color := +(222, 111, 161); Tiffany_Blue : constant Color := +(10, 186, 181); Tomato : constant Color := +(255, 99, 71); Torch_red : constant Color := +(253, 14, 53); Tropical_rain_forest : constant Color := +(0, 117, 94); Turkish_Rose : constant Color := +(181, 114, 129); Turquoise : constant Color := +(48, 213, 200); Turquoise_blue : constant Color := +(0, 191, 255); Tuscan_red : constant Color := +(123, 54, 54); Twilight_lavender : constant Color := +(138, 73, 107); Tyrian_purple : constant Color := +(102, 2, 60); Ube : constant Color := +(136, 120, 195); Ultramarine : constant Color := +(18, 10, 143); Ultramarine_blue : constant Color := +(65, 102, 245); Ultra_pink : constant Color := +(255, 111, 255); Umber : constant Color := +(99, 81, 71); United_Nations_blue : constant Color := +(91, 146, 229); Upsdell_red : constant Color := +(174, 22, 32); UP_Forest_green : constant Color := +(1, 68, 33); UP_Maroon : constant Color := +(123, 17, 19); Vegas_Gold : constant Color := +(197, 179, 88); Venetian_red : constant Color := +(200, 8, 21); Vermilion : constant Color := +(227, 66, 51); Violet_wheel : constant Color := +(128, 0, 255); Violet_web : constant Color := +(238, 130, 238); Violet_RYB : constant Color := +(134, 1, 175); Viridian : constant Color := +(64, 130, 109); Vivid_auburn : constant Color := +(147, 39, 36); Vivid_burgundy : constant Color := +(159, 29, 53); Vivid_violet : constant Color := +(153, 0, 255); Warm_black : constant Color := +(0, 66, 66); Wenge : constant Color := +(100, 84, 82); Wheat : constant Color := +(245, 222, 179); White_smoke : constant Color := +(245, 245, 245); Wild_blue_yonder : constant Color := +(162, 173, 208); Wisteria : constant Color := +(201, 160, 220); Xanadu : constant Color := +(115, 134, 120); Yale_Blue : constant Color := +(15, 77, 146); Yellow_process : constant Color := +(255, 239, 0); Yellow_RYB : constant Color := +(254, 254, 51); Yellow_green : constant Color := +(154, 205, 50); end openGL.Palette;
with Ada.Text_IO; use Ada.Text_IO; package body I_Am_Ada is procedure Ada_Procedure is begin Put_Line(" Hello, I am Ada code."); end Ada_Procedure; begin Put_Line("I_Am_Ada is elaborated"); end I_Am_Ada;
with System; with STM32GD; with STM32_SVD; use STM32_SVD; with STM32_SVD.Flash; use STM32_SVD.Flash; with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32_SVD.PWR; use STM32_SVD.PWR; with STM32_SVD.GPIO; use STM32_SVD.GPIO; with STM32_SVD.RTC; use STM32_SVD.RTC; with Startup; procedure Main is procedure Deactivate_Peripherals is begin RCC_Periph.AHBENR := ( IOPAEN => 1, IOPBEN => 1, IOPCEN => 1, IOPDEN => 1, IOPFEN => 1, Reserved_7_16 => 0, Reserved_23_31 => 0, others => 0); GPIOA_Periph.MODER.Val := 16#FFFF_FFFF#; GPIOB_Periph.MODER.Val := 16#FFFF_FFFF#; GPIOC_Periph.MODER.Val := 16#FFFF_FFFF#; GPIOD_Periph.MODER.Val := 16#FFFF_FFFF#; GPIOF_Periph.MODER.Val := 16#FFFF_FFFF#; RCC_Periph.AHBENR := ( Reserved_7_16 => 0, Reserved_23_31 => 0, others => 0); RCC_Periph.APB1ENR := ( Reserved_2_3 => 0, Reserved_5_7 => 0, Reserved_9_10 => 0, Reserved_12_13 => 0, Reserved_15_16 => 0, Reserved_18_20 => 0, Reserved_23_27 => 0, Reserved_29_31 => 0, others => 0); RCC_Periph.APB2ENR := ( Reserved_1_8 => 0, Reserved_19_21 => 0, Reserved_23_31 => 0, others => 0); end Deactivate_Peripherals; procedure Start_RTC is begin RCC_Periph.CSR.LSION := 1; while RCC_Periph.CSR.LSIRDY = 0 loop null; end loop; RCC_Periph.BDCR.RTCSEL := 2#10#; RCC_Periph.BDCR.RTCEN := 1; end Start_RTC; procedure Sleep is begin loop STM32GD.WFI; end loop; end Sleep; procedure Stop is SCB_SCR : aliased STM32_SVD.UInt32 with Address => System'To_Address (16#E000ED10#); SCR : UInt32; begin PWR_Periph.CR.LPDS := 1; PWR_Periph.CR.PDDS := 0; SCR := SCB_SCR or 2#100#; SCB_SCR := SCR; Deactivate_Peripherals; Sleep; end Stop; procedure Standby is SCB_SCR : aliased STM32_SVD.UInt32 with Address => System'To_Address (16#E000ED10#); SCR : UInt32; begin PWR_Periph.CR.LPDS := 1; PWR_Periph.CR.PDDS := 1; SCR := SCB_SCR or 2#100#; SCB_SCR := SCR; Deactivate_Peripherals; Sleep; end Standby; begin RCC_Periph.APB1ENR.PWREN := 1; loop Start_RTC; -- Sleep; -- Low_Power_Sleep; Stop; -- Standby; end loop; end Main;
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <reznikmm@gmail.com> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- with Ada.Streams; -- see 13.13.1 package System.RPC is type Partition_Id is range 0 .. implementation_defined; Communication_Error : exception; type Params_Stream_Type (Initial_Size : Ada.Streams.Stream_Element_Count) is new Ada.Streams.Root_Stream_Type with private; procedure Read (Stream : in out Params_Stream_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); procedure Write (Stream : in out Params_Stream_Type; Item : in Ada.Streams.Stream_Element_Array); -- Synchronous call procedure Do_RPC (Partition : in Partition_Id; Params : access Params_Stream_Type; Result : access Params_Stream_Type); -- Asynchronous call procedure Do_APC (Partition : in Partition_Id; Params : access Params_Stream_Type); -- The handler for incoming RPCs type RPC_Receiver is access procedure (Params : access Params_Stream_Type; Result : access Params_Stream_Type); procedure Establish_RPC_Receiver (Partition : in Partition_Id; Receiver : in RPC_Receiver); private pragma Import (Ada, Params_Stream_Type); end System.RPC;
with Ada.Real_Time; use Ada.Real_Time; with HIL.GPIO; use HIL.GPIO; package body Crash is procedure Last_Chance_Handler (Source_Location : System.Address; Line : Integer) is next : Time := Clock; PERIOD : constant Time_Span := Milliseconds(1000); begin write (RED_LED, HIGH); loop next := next + PERIOD; delay until next; end loop; end Last_Chance_Handler; end Crash;
with Ada.Containers; use Ada.Containers; with Ada.Text_IO; use Ada.Text_IO; with AUnit.Assertions; use AUnit.Assertions; with GNAT.Source_Info; use GNAT.Source_Info; with Langkit_Support.Text; use Langkit_Support.Text; with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; with Rejuvenation; use Rejuvenation; with Rejuvenation.Finder; use Rejuvenation.Finder; with Rejuvenation.Match_Patterns; use Rejuvenation.Match_Patterns; with Rejuvenation.Patterns; use Rejuvenation.Patterns; with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory; with Shared; use Shared; package body Test_Exercises_Match is procedure Test_Rejuvenation_Finder_Public_Subp_Definition_With_3_Parameters (T : in out Test_Case'Class); procedure Test_Rejuvenation_Finder_Public_Subp_Definition_With_3_Parameters (T : in out Test_Case'Class) is pragma Unreferenced (T); function Valid_Node (Node : Ada_Node'Class) return Boolean; function Valid_Node (Node : Ada_Node'Class) return Boolean is begin if Node.Kind = Ada_Subp_Spec then declare SS : constant Subp_Spec := Node.As_Subp_Spec; begin return not Inside_Private_Part (SS) and then Is_Part_Of_Subp_Def (SS) and then Nr_Of_Parameters (SS) = 3; end; else return False; end if; end Valid_Node; Unit : constant Analysis_Unit := Analyze_File ("src/count_subprogram.ads"); Found_Nodes : constant Node_List.Vector := Find (Unit.Root, Valid_Node'Access); begin Put_Line ("Begin - " & Enclosing_Entity); for Found_Node of Found_Nodes loop declare SS : constant Subp_Spec := Found_Node.As_Subp_Spec; begin Put_Line ("Found " & Image (SS.F_Subp_Name.Text)); end; end loop; Put_Line ("Done - " & Enclosing_Entity); end Test_Rejuvenation_Finder_Public_Subp_Definition_With_3_Parameters; procedure Test_Rejuvenation_Find_Assign_Condition_In_If_Statement (T : in out Test_Case'Class); procedure Test_Rejuvenation_Find_Assign_Condition_In_If_Statement (T : in out Test_Case'Class) is pragma Unreferenced (T); Unit : constant Analysis_Unit := Analyze_File ("src/assignmentbyifexamples.adb"); Pattern_Assign_Condition_In_If_Statement : constant Pattern := Make_Pattern ("if $S_Condition then $S_Variable := True; " & "else $S_Variable := False; end if;", If_Stmt_Rule); Found_Matches : constant Match_Pattern_List.Vector := Find_Full (Unit.Root, Pattern_Assign_Condition_In_If_Statement); begin Put_Line ("Begin - " & Enclosing_Entity); Assert (Found_Matches.Length = 2, "Two instances in unit expected, got " & Found_Matches.Length'Image); for Found_Match of Found_Matches loop declare Condition : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Condition"); Variable : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Variable"); begin Put_Line (Image (Found_Match.Get_Nodes.First_Element.Full_Sloc_Image) & Variable & " := " & Condition & ";"); end; end loop; Put_Line ("End - " & Enclosing_Entity); end Test_Rejuvenation_Find_Assign_Condition_In_If_Statement; procedure Test_Rejuvenation_Find_Windows_New_Line (T : in out Test_Case'Class); procedure Test_Rejuvenation_Find_Windows_New_Line (T : in out Test_Case'Class) is pragma Unreferenced (T); procedure Handle_Matches (Matches : Match_Pattern_List.Vector); procedure Handle_Matches (Matches : Match_Pattern_List.Vector) is begin for Match of Matches loop declare Node : constant Ada_Node := Match.Get_Nodes.First_Element; begin Put_Line (Image (Node.Full_Sloc_Image) & " Found New_Line"); end; end loop; end Handle_Matches; Unit : constant Analysis_Unit := Analyze_File ("src/newlineexamples.adb"); Pattern1_New_Line : constant Pattern := Make_Pattern ("ASCII.CR & ASCII.LF", Expr_Rule); Found1_Matches : constant Match_Pattern_List.Vector := Find_Full (Unit.Root, Pattern1_New_Line); Pattern2_New_Line : constant Pattern := Make_Pattern ("(1 => ASCII.CR, 2 => ASCII.LF)", Expr_Rule); Found2_Matches : constant Match_Pattern_List.Vector := Find_Full (Unit.Root, Pattern2_New_Line); PrefixKey : constant String := "$S_prefix"; Pattern3_New_Line : constant Pattern := Make_Pattern (PrefixKey & " & ASCII.CR & ASCII.LF", Expr_Rule); Found3_Matches : constant Match_Pattern_List.Vector := Find_Full (Unit.Root, Pattern3_New_Line); begin Put_Line ("Begin - " & Enclosing_Entity); Put_Line ("Pattern 1"); Handle_Matches (Found1_Matches); Put_Line ("Pattern 2"); Handle_Matches (Found2_Matches); Put_Line ("Pattern 3"); Handle_Matches (Found3_Matches); Put_Line ("Done - " & Enclosing_Entity); end Test_Rejuvenation_Find_Windows_New_Line; -- TODO: Add real world example usable in open source -- procedure Test_Rejuvenation_Find_Modify_Item -- (T : in out Test_Case'Class); -- Test plumbing overriding function Name (T : Exercise_Match_Test_Case) return AUnit.Message_String is pragma Unreferenced (T); begin return AUnit.Format ("Exercises Match Pattern"); end Name; overriding procedure Register_Tests (T : in out Exercise_Match_Test_Case) is begin Registration.Register_Routine (T, Test_Rejuvenation_Finder_Public_Subp_Definition_With_3_Parameters' Access, "Use Rejuvenation Finder to find Subp_Specs with 3 Parameters"); Registration.Register_Routine (T, Test_Rejuvenation_Find_Assign_Condition_In_If_Statement'Access, "Use Rejuvenation to find assign condition in if statements"); Registration.Register_Routine (T, Test_Rejuvenation_Find_Windows_New_Line'Access, "Use Rejuvenation to find Windows New Line"); end Register_Tests; end Test_Exercises_Match;
-- Abstract : -- -- Generalized LR parser state. -- -- Copyright (C) 2014-2015, 2017 - 2020 Free Software Foundation, Inc. -- -- This file is part of the WisiToken package. -- -- The WisiToken package is free software; you can redistribute it -- and/or modify it under terms of the GNU General Public License as -- published by the Free Software Foundation; either version 3, or -- (at your option) any later version. This library is distributed in -- the hope that it will be useful, but WITHOUT ANY WARRANTY; without -- even the implied warranty of MERCHAN- TABILITY or FITNESS FOR A -- PARTICULAR PURPOSE. -- -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); with Ada.Iterator_Interfaces; with SAL.Gen_Indefinite_Doubly_Linked_Lists; with SAL.Gen_Unbounded_Definite_Stacks; with WisiToken.Syntax_Trees; package WisiToken.Parse.LR.Parser_Lists is type Parser_Stack_Item is record State : Unknown_State_Index := Unknown_State; Token : Node_Index := Invalid_Node_Index; end record; package Parser_Stacks is new SAL.Gen_Unbounded_Definite_Stacks (Parser_Stack_Item); function Parser_Stack_Image (Stack : in Parser_Stacks.Stack; Descriptor : in WisiToken.Descriptor; Tree : in Syntax_Trees.Tree; Depth : in SAL.Base_Peek_Type := 0) return String; -- If Depth = 0, put all of Stack. Otherwise put Min (Depth, -- Stack.Depth) items. -- -- Unique name for calling from debugger function Image (Stack : in Parser_Stacks.Stack; Descriptor : in WisiToken.Descriptor; Tree : in Syntax_Trees.Tree; Depth : in SAL.Base_Peek_Type := 0) return String renames Parser_Stack_Image; type Base_Parser_State is tagged record -- Visible components for direct access Shared_Token : Base_Token_Index := Invalid_Token_Index; -- Last token read from Shared_Parser.Terminals. Recover_Insert_Delete : aliased Recover_Op_Arrays.Vector; -- Tokens that were inserted or deleted during error recovery. -- Contains only Insert and Delete ops. Filled by error recover, used -- by main parse and Execute_Actions. -- -- Not emptied between error recovery sessions, so Execute_Actions -- knows about all insert/delete. Recover_Insert_Delete_Current : Recover_Op_Arrays.Extended_Index := Recover_Op_Arrays.No_Index; -- Next item in Recover_Insert_Delete to be processed by main parse; -- No_Index if all done. Current_Token : Node_Index := Invalid_Node_Index; -- Current terminal, in Tree Inc_Shared_Token : Boolean := True; Stack : Parser_Stacks.Stack; -- There is no need to use a branched stack; max stack length is -- proportional to source text nesting depth, not source text length. Tree : aliased Syntax_Trees.Tree; -- We use a branched tree to avoid copying large trees for each -- spawned parser; tree size is proportional to source text size. In -- normal parsing, parallel parsers are short-lived; they each process -- a few tokens, to resolve a grammar conflict. -- -- When there is only one parser, tree nodes are written directly to -- the shared tree (via the branched tree, with Flush => True). -- -- When there is more than one, tree nodes are written to the -- branched tree. Then when all but one parsers are terminated, the -- remaining branched tree is flushed into the shared tree. Recover : aliased LR.McKenzie_Data := (others => <>); Zombie_Token_Count : Base_Token_Index := 0; -- If Zombie_Token_Count > 0, this parser has errored, but is waiting -- to see if other parsers do also. Resume_Active : Boolean := False; Resume_Token_Goal : Base_Token_Index := Invalid_Token_Index; Conflict_During_Resume : Boolean := False; -- Resume is complete for this parser Shared_Token reaches this -- Resume_Token_Goal. Errors : Parse_Error_Lists.List; end record; type Parser_State is new Base_Parser_State with private; type State_Access is access all Parser_State; type List is tagged private with Constant_Indexing => Constant_Reference, Variable_Indexing => Reference, Default_Iterator => Iterate, Iterator_Element => Parser_State; function New_List (Shared_Tree : in Syntax_Trees.Base_Tree_Access) return List; function Last_Label (List : in Parser_Lists.List) return Natural; function Count (List : in Parser_Lists.List) return SAL.Base_Peek_Type; type Cursor (<>) is tagged private; function First (List : aliased in out Parser_Lists.List'Class) return Cursor; procedure Next (Cursor : in out Parser_Lists.Cursor); function Is_Done (Cursor : in Parser_Lists.Cursor) return Boolean; function Has_Element (Cursor : in Parser_Lists.Cursor) return Boolean is (not Is_Done (Cursor)); function Label (Cursor : in Parser_Lists.Cursor) return Natural; function Total_Recover_Cost (Cursor : in Parser_Lists.Cursor) return Integer; function Max_Recover_Ops_Length (Cursor : in Parser_Lists.Cursor) return Ada.Containers.Count_Type; function Min_Recover_Cost (Cursor : in Parser_Lists.Cursor) return Integer; procedure Set_Verb (Cursor : in Parser_Lists.Cursor; Verb : in All_Parse_Action_Verbs); function Verb (Cursor : in Parser_Lists.Cursor) return All_Parse_Action_Verbs; procedure Terminate_Parser (Parsers : in out List; Current : in out Cursor'Class; Message : in String; Trace : in out WisiToken.Trace'Class; Terminals : in Base_Token_Arrays.Vector); -- Terminate Current. Current is set to no element. -- -- Terminals is used to report the current token in the message. procedure Duplicate_State (Parsers : in out List; Current : in out Cursor'Class; Trace : in out WisiToken.Trace'Class; Terminals : in Base_Token_Arrays.Vector); -- If any other parser in Parsers has a stack equivalent to Current, -- Terminate one of them. Current is either unchanged, or advanced to -- the next parser. -- -- Terminals is used to report the current token in the message. type State_Reference (Element : not null access Parser_State) is null record with Implicit_Dereference => Element; function State_Ref (Position : in Cursor) return State_Reference with Pre => Has_Element (Position); -- Direct access to visible components of Parser_State function First_State_Ref (List : in Parser_Lists.List'Class) return State_Reference with Pre => List.Count > 0; -- Direct access to visible components of first parser's Parser_State type Constant_State_Reference (Element : not null access constant Parser_State) is null record with Implicit_Dereference => Element; function First_Constant_State_Ref (List : in Parser_Lists.List'Class) return Constant_State_Reference with Pre => List.Count > 0; -- Direct access to visible components of first parser's Parser_State procedure Put_Top_10 (Trace : in out WisiToken.Trace'Class; Cursor : in Parser_Lists.Cursor); -- Put image of top 10 stack items to Trace. procedure Prepend_Copy (List : in out Parser_Lists.List; Cursor : in Parser_Lists.Cursor'Class); -- Copy parser at Cursor, prepend to current list. New copy will not -- appear in Cursor.Next ...; it is accessible as First (List). -- -- Copy.Recover is set to default. ---------- -- Stuff for iterators, to allow -- 'for Parser of Parsers loop' -- 'for I in Parsers.Iterate loop' -- -- requires Parser_State to be not an incomplete type. -- We'd like to use Cursor here, but we want that to be tagged, to -- allow 'Cursor.operation' syntax, and the requirements of -- iterators prevent a tagged iterator type (two tagged types on -- First in this package body). So we use Parser_Node_Access as -- the iterator type for Iterators, and typical usage is: -- -- for I in Parsers.Iterate loop -- declare -- Cursor : Parser_Lists.Cursor renames To_Cursor (Parsers, I); -- begin -- Cursor.<cursor operation> -- -- ... Parsers (I).<visible parser_state component> ... -- end; -- end loop; -- -- or: -- for Current_Parser of Parsers loop -- ... Current_Parser.<visible parser_state component> ... -- end loop; type Parser_Node_Access (<>) is private; function To_Cursor (Ptr : in Parser_Node_Access) return Cursor; type Constant_Reference_Type (Element : not null access constant Parser_State) is null record with Implicit_Dereference => Element; function Constant_Reference (Container : aliased in List'Class; Position : in Parser_Node_Access) return Constant_Reference_Type; pragma Inline (Constant_Reference); function Reference (Container : aliased in out List'Class; Position : in Parser_Node_Access) return State_Reference; pragma Inline (Reference); function Persistent_State_Ref (Position : in Parser_Node_Access) return State_Access; function Has_Element (Iterator : in Parser_Node_Access) return Boolean; package Iterator_Interfaces is new Ada.Iterator_Interfaces (Parser_Node_Access, Has_Element); function Iterate (Container : aliased in out List) return Iterator_Interfaces.Forward_Iterator'Class; -- Access to some private Parser_State components function Label (Iterator : in Parser_State) return Natural; procedure Set_Verb (Iterator : in out Parser_State; Verb : in All_Parse_Action_Verbs); function Verb (Iterator : in Parser_State) return All_Parse_Action_Verbs; private type Parser_State is new Base_Parser_State with record Label : Natural; -- for debugging/verbosity Verb : All_Parse_Action_Verbs := Shift; -- current action to perform end record; package Parser_State_Lists is new SAL.Gen_Indefinite_Doubly_Linked_Lists (Parser_State); type List is tagged record Elements : aliased Parser_State_Lists.List; Parser_Label : Natural; -- label of last added parser. end record; type Cursor (Elements : access Parser_State_Lists.List) is tagged record Ptr : Parser_State_Lists.Cursor; end record; type Parser_Node_Access (Elements : access Parser_State_Lists.List) is record Ptr : Parser_State_Lists.Cursor; end record; end WisiToken.Parse.LR.Parser_Lists;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . W I D E _ T E X T _ I O . E N U M E R A T I O N _ A U X -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the routines for Ada.Wide_Text_IO.Enumeration_IO -- that are shared among separate instantiations. private package Ada.Wide_Text_IO.Enumeration_Aux is procedure Get_Enum_Lit (File : File_Type; Buf : out Wide_String; Buflen : out Natural); -- Reads an enumeration literal value from the file, folds to upper case, -- and stores the result in Buf, setting Buflen to the number of stored -- characters (Buf has a lower bound of 1). If more than Buflen characters -- are present in the literal, Data_Error is raised. procedure Scan_Enum_Lit (From : Wide_String; Start : out Natural; Stop : out Natural); -- Scans an enumeration literal at the start of From, skipping any leading -- spaces. Sets Start to the first character, Stop to the last character. -- Raises End_Error if no enumeration literal is found. procedure Put (File : File_Type; Item : Wide_String; Width : Field; Set : Type_Set); -- Outputs the enumeration literal image stored in Item to the given File, -- using the given Width and Set parameters (Item is always in upper case). procedure Puts (To : out Wide_String; Item : Wide_String; Set : Type_Set); -- Stores the enumeration literal image stored in Item to the string To, -- padding with trailing spaces if necessary to fill To. Set is used to end Ada.Wide_Text_IO.Enumeration_Aux;
with Ada.IO_Exceptions; with Ada.Environment_Encoding.Encoding_Streams; with Ada.Environment_Encoding.Names; with Ada.Environment_Encoding.Strings; with Ada.Environment_Encoding.Wide_Strings; with Ada.Environment_Encoding.Wide_Wide_Strings; with Ada.Streams.Unbounded_Storage_IO; procedure nls is package USIO renames Ada.Streams.Unbounded_Storage_IO; use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; Japanease_A : constant String := ( Character'Val (16#e3#), Character'Val (16#81#), Character'Val (16#82#)); Mongolian_Birga : constant String := ( Character'Val (16#e1#), Character'Val (16#a0#), Character'Val (16#80#)); begin Ada.Debug.Put (Ada.Environment_Encoding.Image (Ada.Environment_Encoding.Current_Encoding)); -- status check declare E : Ada.Environment_Encoding.Strings.Encoder; pragma Warnings (Off, E); begin if Ada.Environment_Encoding.Strings.Encode (E, "") = (1 .. 0 => <>) then null; end if; raise Program_Error; -- bad exception when Ada.Environment_Encoding.Status_Error => null; end; -- decoding declare D : Ada.Environment_Encoding.Strings.Decoder := Ada.Environment_Encoding.Strings.From (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Strings.Decode (D, (1 .. 0 => <>)) = ""); pragma Assert (Ada.Environment_Encoding.Strings.Decode (D, (1 => 16#41#)) = "A"); pragma Assert (Ada.Environment_Encoding.Strings.Decode (D, (16#41#, 16#42#)) = "AB"); pragma Assert (Ada.Environment_Encoding.Strings.Decode (D, (16#82#, 16#a0#)) = Japanease_A); null; end; declare WD : Ada.Environment_Encoding.Wide_Strings.Decoder := Ada.Environment_Encoding.Wide_Strings.From (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Wide_Strings.Decode (WD, (16#41#, 16#42#)) = "AB"); null; end; declare WWD : Ada.Environment_Encoding.Wide_Wide_Strings.Decoder := Ada.Environment_Encoding.Wide_Wide_Strings.From (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Wide_Wide_Strings.Decode (WWD, (16#41#, 16#42#)) = "AB"); null; end; -- encoding declare E : Ada.Environment_Encoding.Strings.Encoder := Ada.Environment_Encoding.Strings.To (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Strings.Encode (E, "") = (1 .. 0 => <>)); pragma Assert (Ada.Environment_Encoding.Strings.Encode (E, "A") = (1 => 16#41#)); pragma Assert (Ada.Environment_Encoding.Strings.Encode (E, "AB") = (16#41#, 16#42#)); pragma Assert (Ada.Environment_Encoding.Strings.Encode (E, Japanease_A) = (16#82#, 16#a0#)); -- substitute declare Default : constant Ada.Streams.Stream_Element_Array := Ada.Environment_Encoding.Strings.Substitute (E); Mongolian_Birga_In_Windows_31J : constant Ada.Streams.Stream_Element_Array := Ada.Environment_Encoding.Strings.Encode (E, Mongolian_Birga); begin pragma Assert (Mongolian_Birga_In_Windows_31J = Default or else Mongolian_Birga_In_Windows_31J = Default & Default & Default); null; end; Ada.Environment_Encoding.Strings.Set_Substitute (E, (16#81#, 16#51#)); -- fullwidth low line in Windows-31J declare Mongolian_Birga_In_Windows_31J : constant Ada.Streams.Stream_Element_Array := Ada.Environment_Encoding.Strings.Encode (E, Mongolian_Birga); begin pragma Assert (Mongolian_Birga_In_Windows_31J = (16#81#, 16#51#) or else Mongolian_Birga_In_Windows_31J = (16#81#, 16#51#, 16#81#, 16#51#, 16#81#, 16#51#)); null; end; end; declare WE : Ada.Environment_Encoding.Wide_Strings.Encoder := Ada.Environment_Encoding.Wide_Strings.To (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Wide_Strings.Encode (WE, "AB") = (16#41#, 16#42#)); null; end; declare WWE : Ada.Environment_Encoding.Wide_Wide_Strings.Encoder := Ada.Environment_Encoding.Wide_Wide_Strings.To (Ada.Environment_Encoding.Names.Windows_31J); begin pragma Assert (Ada.Environment_Encoding.Wide_Wide_Strings.Encode (WWE, "AB") = (16#41#, 16#42#)); null; end; -- reading declare Buffer : USIO.Buffer_Type; E : aliased Ada.Environment_Encoding.Encoding_Streams.Inout_Type := Ada.Environment_Encoding.Encoding_Streams.Open ( Ada.Environment_Encoding.Names.UTF_8, Ada.Environment_Encoding.Names.Windows_31J, USIO.Stream (Buffer)); S : String (1 .. 3); One_Element : String (1 .. 1); begin for I in 1 .. 100 loop Ada.Streams.Write ( USIO.Stream (Buffer).all, (16#82#, 16#a0#)); end loop; Ada.Streams.Set_Index ( Ada.Streams.Seekable_Stream_Type'Class (USIO.Stream (Buffer).all), 1); for I in 1 .. 100 loop String'Read ( Ada.Environment_Encoding.Encoding_Streams.Stream (E), S); pragma Assert (S = Japanease_A); end loop; begin String'Read ( Ada.Environment_Encoding.Encoding_Streams.Stream (E), One_Element); raise Program_Error; exception when Ada.IO_Exceptions.End_Error => null; end; end; -- writing declare Buffer : USIO.Buffer_Type; E : aliased Ada.Environment_Encoding.Encoding_Streams.Inout_Type := Ada.Environment_Encoding.Encoding_Streams.Open ( Ada.Environment_Encoding.Names.Windows_31J, Ada.Environment_Encoding.Names.UTF_8, USIO.Stream (Buffer)); S : String (1 .. 3); begin for I in 1 .. 100 loop Ada.Streams.Write ( Ada.Environment_Encoding.Encoding_Streams.Stream (E).all, (16#82#, 16#a0#)); end loop; Ada.Environment_Encoding.Encoding_Streams.Finish (E); Ada.Streams.Set_Index ( Ada.Streams.Seekable_Stream_Type'Class (USIO.Stream (Buffer).all), 1); pragma Assert (USIO.Size (Buffer) = 300); for I in 1 .. 100 loop String'Read ( USIO.Stream (Buffer), S); pragma Assert (S = Japanease_A); end loop; end; pragma Debug (Ada.Debug.Put ("OK")); end nls;
with Ada.Exception_Identification.From_Here; with System.Address_To_Named_Access_Conversions; with C.errno; with C.stdlib; with C.sys.file; with C.sys.mman; with C.sys.stat; with C.sys.types; package body System.Native_IO is use Ada.Exception_Identification.From_Here; use type Ada.IO_Modes.File_Shared; use type Ada.IO_Modes.File_Shared_Spec; use type Ada.Streams.Stream_Element_Offset; use type Storage_Elements.Storage_Offset; use type C.char; -- Name_Character use type C.char_array; -- Name_String use type C.char_ptr; -- Name_Pointer use type C.size_t; use type C.unsigned_int; use type C.unsigned_short; use type C.sys.types.off_t; pragma Compile_Time_Error ( C.sys.types.off_t'Size /= 64, "off_t is not 64bit"); function strlen (s : not null access constant C.char) return C.size_t with Import, Convention => Intrinsic, External_Name => "__builtin_strlen"; package Name_Pointer_Conv is new Address_To_Named_Access_Conversions (Name_Character, Name_Pointer); Temp_Variable : constant C.char_array := "TMPDIR" & C.char'Val (0); Temp_Template : constant C.char_array := "ADAXXXXXX" & C.char'Val (0); -- implementation procedure Free (Item : in out Name_Pointer) is begin C.stdlib.free (C.void_ptr (Name_Pointer_Conv.To_Address (Item))); Item := null; end Free; procedure New_External_Name ( Item : String; Out_Item : aliased out Name_Pointer) is begin Out_Item := Name_Pointer_Conv.To_Pointer ( Address ( C.stdlib.malloc ( Item'Length * Zero_Terminated_Strings.Expanding + 2))); -- '*' & NUL if Out_Item = null then raise Storage_Error; end if; declare Out_Item_All : Name_String (0 .. 1); -- at least for Out_Item_All'Address use Name_Pointer_Conv.To_Address (Out_Item); begin Out_Item_All (0) := '*'; Zero_Terminated_Strings.To_C (Item, Out_Item_All (1)'Access); end; end New_External_Name; procedure Open_Temporary ( Handle : aliased out Handle_Type; Out_Item : aliased out Name_Pointer) is Temp_Template_Length : constant C.size_t := Temp_Template'Length - 1; Temp_Dir : C.char_ptr; Out_Length : C.size_t; begin -- compose template Temp_Dir := C.stdlib.getenv (Temp_Variable (0)'Access); if Temp_Dir /= null and then Temp_Dir.all /= C.char'Val (0) then -- environment variable TMPDIR Out_Length := strlen (Temp_Dir); Out_Item := Name_Pointer_Conv.To_Pointer ( Address ( C.stdlib.malloc ( Out_Length + Temp_Template_Length + 2))); -- '/' & NUL if Out_Item = null then raise Storage_Error; end if; declare Temp_Dir_All : C.char_array (0 .. Out_Length - 1); for Temp_Dir_All'Address use Name_Pointer_Conv.To_Address (Temp_Dir); Out_Item_All : C.char_array (0 .. Out_Length - 1); for Out_Item_All'Address use Name_Pointer_Conv.To_Address (Out_Item); begin Out_Item_All := Temp_Dir_All; end; else -- current directory Out_Item := C.unistd.getcwd (null, 0); Out_Length := strlen (Out_Item); -- reuse the memory from malloc (similar to reallocf) declare New_Out_Item : constant C.char_ptr := Name_Pointer_Conv.To_Pointer ( Address ( C.stdlib.realloc ( C.void_ptr (Name_Pointer_Conv.To_Address (Out_Item)), Out_Length + Temp_Template_Length + 2))); -- '/' & NUL begin if New_Out_Item = null then raise Storage_Error; end if; Out_Item := New_Out_Item; end; end if; declare Out_Item_All : C.char_array ( 0 .. Out_Length + Temp_Template_Length + 1); -- '/' & NUL for Out_Item_All'Address use Name_Pointer_Conv.To_Address (Out_Item); begin -- append slash if Out_Item_All (Out_Length - 1) /= '/' then Out_Item_All (Out_Length) := '/'; Out_Length := Out_Length + 1; end if; -- append template Out_Item_All (Out_Length .. Out_Length + Temp_Template_Length) := Temp_Template; -- including nul end; -- open declare use C.stdlib; -- Linux, POSIX.1-2008 use C.unistd; -- Darwin, FreeBSD begin Handle := mkstemp (Out_Item); end; if Handle < 0 then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; Set_Close_On_Exec (Handle); end Open_Temporary; procedure Open_Ordinary ( Method : Open_Method; Handle : aliased out Handle_Type; Mode : File_Mode; Name : not null Name_Pointer; Form : Packed_Form) is O_EXLOCK_Is_Missing : constant Boolean := C.fcntl.O_EXLOCK = 0; Masked_Mode : constant File_Mode := Mode and Read_Write_Mask; Flags : C.unsigned_int; Modes : constant := 8#644#; Shared : Ada.IO_Modes.File_Shared; errno : C.signed_int; begin -- modes if Form.Shared /= Ada.IO_Modes.By_Mode then Shared := Ada.IO_Modes.File_Shared (Form.Shared); else if Masked_Mode = Read_Only_Mode then Shared := Ada.IO_Modes.Read_Only; else Shared := Ada.IO_Modes.Deny; end if; end if; Flags := Masked_Mode; case Method is when Create => Shared := Ada.IO_Modes.Deny; if Mode = Read_Only_Mode then -- In_File Flags := C.fcntl.O_RDWR; end if; Flags := Flags or C.fcntl.O_CREAT; if Mode = Write_Only_Mode then -- Out_File Flags := Flags or C.fcntl.O_TRUNC; end if; if not Form.Overwrite then Flags := Flags or C.fcntl.O_EXCL; end if; when Open => if Mode = Write_Only_Mode then -- Out_File Flags := Flags or C.fcntl.O_TRUNC; end if; when Reset => null; -- no truncation end case; if (Mode and Append_Mode) /= 0 then Flags := Flags or C.fcntl.O_APPEND; end if; if Shared /= Ada.IO_Modes.Allow then if not O_EXLOCK_Is_Missing then declare Lock_Flags : constant array ( Ada.IO_Modes.File_Shared range Ada.IO_Modes.Read_Only .. Ada.IO_Modes.Deny) of C.unsigned_int := ( Ada.IO_Modes.Read_Only => C.fcntl.O_SHLOCK, Ada.IO_Modes.Deny => C.fcntl.O_EXLOCK); begin Flags := Flags or Lock_Flags (Shared); end; if not Form.Wait then -- O_NONBLOCK makes open to return immediately and EWOULDBLOCK -- instead of waiting, when a file is already locked. Flags := Flags or C.fcntl.O_NONBLOCK; end if; else null; -- use flock end if; end if; Flags := Flags or C.fcntl.O_CLOEXEC; -- open Handle := C.fcntl.open (Name, C.signed_int (Flags), Modes); if Handle < 0 then errno := C.errno.errno; case errno is when C.errno.ENOTDIR | C.errno.ENAMETOOLONG | C.errno.ENOENT | C.errno.EEXIST -- O_EXCL | C.errno.EISDIR => Raise_Exception (Name_Error'Identity); when C.errno.EWOULDBLOCK => Raise_Exception (Tasking_Error'Identity); -- Is it suitable? when others => Raise_Exception (IO_Exception_Id (errno)); end case; end if; declare O_CLOEXEC_Is_Missing : constant Boolean := C.fcntl.O_CLOEXEC = 0; pragma Warnings (Off, O_CLOEXEC_Is_Missing); begin if O_CLOEXEC_Is_Missing then -- set FD_CLOEXEC if O_CLOEXEC is missing Set_Close_On_Exec (Handle); end if; end; if Shared /= Ada.IO_Modes.Allow then if not O_EXLOCK_Is_Missing then if not Form.Wait then -- Unset O_NONBLOCK for normal use. Unset (Handle, Mask => not C.fcntl.O_NONBLOCK); end if; else declare Race_Is_Raising : constant Boolean := not Form.Wait; Operation_Table : constant array ( Ada.IO_Modes.File_Shared range Ada.IO_Modes.Read_Only .. Ada.IO_Modes.Deny) of C.unsigned_int := ( Ada.IO_Modes.Read_Only => C.sys.file.LOCK_SH, Ada.IO_Modes.Deny => C.sys.file.LOCK_EX); operation : C.unsigned_int; begin operation := Operation_Table (Shared); if Race_Is_Raising then operation := operation or C.sys.file.LOCK_NB; end if; if C.sys.file.flock (Handle, C.signed_int (operation)) < 0 then errno := C.errno.errno; case errno is when C.errno.EWOULDBLOCK => Raise_Exception (Tasking_Error'Identity); -- Is Tasking_Error suitable? when others => Raise_Exception (Use_Error'Identity); end case; end if; end; end if; end if; end Open_Ordinary; procedure Close_Ordinary ( Handle : Handle_Type; Name : Name_Pointer; Raise_On_Error : Boolean) is pragma Unreferenced (Name); Error : Boolean; begin Error := C.unistd.close (Handle) < 0; if Error and then Raise_On_Error then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; end Close_Ordinary; procedure Delete_Ordinary ( Handle : Handle_Type; Name : Name_Pointer; Raise_On_Error : Boolean) is Error : Boolean; begin Error := C.unistd.close (Handle) < 0; if not Error then Error := C.unistd.unlink (Name) < 0; end if; if Error and then Raise_On_Error then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; end Delete_Ordinary; procedure Set_Close_On_Exec (Handle : Handle_Type) is Error : Boolean; begin Error := C.fcntl.fcntl ( Handle, C.fcntl.F_SETFD, C.fcntl.FD_CLOEXEC) < 0; if Error then Raise_Exception (Use_Error'Identity); end if; end Set_Close_On_Exec; procedure Unset (Handle : Handle_Type; Mask : File_Mode) is Flags, New_Flags : C.signed_int; begin Flags := C.fcntl.fcntl (Handle, C.fcntl.F_GETFL); if Flags < 0 then Raise_Exception (Use_Error'Identity); end if; New_Flags := C.signed_int (C.unsigned_int (Flags) and Mask); if New_Flags /= Flags then declare Error : Boolean; begin Error := C.fcntl.fcntl (Handle, C.fcntl.F_SETFL, New_Flags) < 0; if Error then Raise_Exception (Use_Error'Identity); end if; end; end if; end Unset; function Is_Terminal (Handle : Handle_Type) return Boolean is begin return C.unistd.isatty (Handle) /= 0; end Is_Terminal; function Is_Seekable (Handle : Handle_Type) return Boolean is begin return C.unistd.lseek ( Handle, 0, C.unistd.SEEK_CUR) >= 0; end Is_Seekable; function Block_Size (Handle : Handle_Type) return Ada.Streams.Stream_Element_Count is Result : Ada.Streams.Stream_Element_Count; begin if Is_Terminal (Handle) then Result := 0; -- no buffering for terminal else declare Info : aliased C.sys.stat.struct_stat; File_Type : C.sys.types.mode_t; begin if C.sys.stat.fstat (Handle, Info'Access) < 0 then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; File_Type := Info.st_mode and C.sys.stat.S_IFMT; if File_Type = C.sys.stat.S_IFIFO or else File_Type = C.sys.stat.S_IFSOCK then Result := 0; -- no buffering for pipe and socket else -- disk file Result := Ada.Streams.Stream_Element_Offset'Max ( 2, -- Buffer_Length /= 1 Ada.Streams.Stream_Element_Offset (Info.st_blksize)); end if; end; end if; return Result; end Block_Size; procedure Read ( Handle : Handle_Type; Item : Address; Length : Ada.Streams.Stream_Element_Offset; Out_Length : out Ada.Streams.Stream_Element_Offset) is Read_Size : C.sys.types.ssize_t; begin Read_Size := C.unistd.read ( Handle, C.void_ptr (Item), C.size_t (Length)); Out_Length := Ada.Streams.Stream_Element_Offset (Read_Size); end Read; procedure Write ( Handle : Handle_Type; Item : Address; Length : Ada.Streams.Stream_Element_Offset; Out_Length : out Ada.Streams.Stream_Element_Offset) is Written_Size : C.sys.types.ssize_t; begin Written_Size := C.unistd.write ( Handle, C.void_const_ptr (Item), C.size_t (Length)); Out_Length := Ada.Streams.Stream_Element_Offset (Written_Size); if Out_Length < 0 then case C.errno.errno is when C.errno.EPIPE => Out_Length := 0; when others => null; end case; end if; end Write; procedure Flush (Handle : Handle_Type) is begin if C.unistd.fsync (Handle) < 0 then case C.errno.errno is when C.errno.EINVAL => null; -- means fd is not file but FIFO, etc. when others => Raise_Exception (Device_Error'Identity); end case; end if; end Flush; procedure Set_Relative_Index ( Handle : Handle_Type; Relative_To : Ada.Streams.Stream_Element_Offset; Whence : Whence_Type; New_Index : out Ada.Streams.Stream_Element_Offset) is Offset : C.sys.types.off_t; begin Offset := C.unistd.lseek ( Handle, C.sys.types.off_t (Relative_To), Whence); if Offset < 0 then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; New_Index := Ada.Streams.Stream_Element_Offset (Offset) + 1; end Set_Relative_Index; function Index (Handle : Handle_Type) return Ada.Streams.Stream_Element_Offset is Offset : C.sys.types.off_t; begin Offset := C.unistd.lseek (Handle, 0, C.unistd.SEEK_CUR); if Offset < 0 then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; return Ada.Streams.Stream_Element_Offset (Offset) + 1; end Index; function Size (Handle : Handle_Type) return Ada.Streams.Stream_Element_Count is Info : aliased C.sys.stat.struct_stat; begin if C.sys.stat.fstat (Handle, Info'Access) < 0 then Raise_Exception (IO_Exception_Id (C.errno.errno)); end if; return Ada.Streams.Stream_Element_Offset (Info.st_size); end Size; procedure Open_Pipe ( Reading_Handle : aliased out Handle_Type; Writing_Handle : aliased out Handle_Type) is Handles : aliased C.signed_int_array (0 .. 1); begin if C.unistd.pipe (Handles (0)'Access) < 0 then Raise_Exception (Use_Error'Identity); else Set_Close_On_Exec (Handles (0)); Set_Close_On_Exec (Handles (1)); Reading_Handle := Handles (0); Writing_Handle := Handles (1); end if; end Open_Pipe; procedure Map ( Mapping : out Mapping_Type; Handle : Handle_Type; Mode : File_Mode; Private_Copy : Boolean; Offset : Ada.Streams.Stream_Element_Offset; Size : Ada.Streams.Stream_Element_Count) is Mapped_Address : C.void_ptr; begin if Size = 0 then Mapped_Address := C.void_ptr (System'To_Address (1)); -- dummy value else declare Prot : C.unsigned_int; Flags : C.unsigned_int; Mapped_Offset : constant C.sys.types.off_t := C.sys.types.off_t (Offset) - 1; Mapped_Size : constant C.size_t := C.size_t (Size); begin if Private_Copy then Prot := C.sys.mman.PROT_READ or C.sys.mman.PROT_WRITE; Flags := C.sys.mman.MAP_FILE or C.sys.mman.MAP_PRIVATE; else if Mode = Read_Only_Mode then Prot := C.sys.mman.PROT_READ; elsif Mode = Write_Only_Mode then Prot := C.sys.mman.PROT_WRITE; -- may fail in mostly platforms else -- Read_Write_Mode Prot := C.sys.mman.PROT_READ or C.sys.mman.PROT_WRITE; end if; Flags := C.sys.mman.MAP_FILE or C.sys.mman.MAP_SHARED; end if; Mapped_Address := C.sys.mman.mmap ( C.void_ptr (Null_Address), Mapped_Size, C.signed_int (Prot), C.signed_int (Flags), Handle, Mapped_Offset); if Address (Mapped_Address) = Address (C.sys.mman.MAP_FAILED) then Raise_Exception (Use_Error'Identity); end if; end; end if; Mapping.Storage_Address := Address (Mapped_Address); Mapping.Storage_Size := Storage_Elements.Storage_Offset (Size); end Map; procedure Unmap ( Mapping : in out Mapping_Type; Raise_On_Error : Boolean) is begin if Mapping.Storage_Size > 0 then if C.sys.mman.munmap ( C.void_ptr (Mapping.Storage_Address), C.size_t (Mapping.Storage_Size)) < 0 and then Raise_On_Error then Raise_Exception (Use_Error'Identity); end if; end if; Mapping.Storage_Address := Null_Address; Mapping.Storage_Size := 0; end Unmap; function IO_Exception_Id (errno : C.signed_int) return Ada.Exception_Identification.Exception_Id is begin case errno is when C.errno.EIO => return Device_Error'Identity; when others => return Use_Error'Identity; end case; end IO_Exception_Id; end System.Native_IO;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with AUnit.Assertions; with AUnit.Test_Caller; with Orka.SIMD.AVX.Doubles.Arithmetic; with Orka.Transforms.Doubles.Matrices; package body Test_Transforms_Doubles_Matrices is use Orka; use Orka.Transforms.Doubles.Matrices; use AUnit.Assertions; use type Vector4; package EF is new Ada.Numerics.Generic_Elementary_Functions (Float_64); function To_Radians (Angle : Float_64) return Float_64 renames Vectors.To_Radians; function Is_Equivalent (Expected, Result : Float_64) return Boolean is (abs (Result - Expected) <= 2.0 * Float_64'Model_Epsilon); procedure Assert_Equivalent (Expected, Result : Vector4) is begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected element " & Expected (I)'Image & " instead of " & Result (I)'Image & " at " & I'Image); end loop; end Assert_Equivalent; procedure Assert_Equivalent (Expected, Result : Vector4; Column : Index_Homogeneous) is begin for Row in Index_Homogeneous loop Assert (Is_Equivalent (Expected (Row), Result (Row)), "Unexpected element " & Expected (Row)'Image & " instead of " & Result (Row)'Image & " at (" & Column'Image & ", " & Row'Image & ")"); end loop; end Assert_Equivalent; 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 := "(Transforms - Doubles - Matrices) "; begin Test_Suite.Add_Test (Caller.Create (Name & "Test T function", Test_T'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rx function", Test_Rx'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Ry function", Test_Ry'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rz function", Test_Rz'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test R function", Test_R'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test S function", Test_S'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test '+' operator (translate)", Test_Add_Offset'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test '*' operator (scale)", Test_Multiply_Factor'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_At_Origin procedure", Test_Rotate_At_Origin'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate procedure", Test_Rotate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_X_At_Origin procedure", Test_Rotate_X_At_Origin'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Y_At_Origin procedure", Test_Rotate_Y_At_Origin'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Z_At_Origin procedure", Test_Rotate_Z_At_Origin'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_X procedure", Test_Rotate_X'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Y procedure", Test_Rotate_Y'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Rotate_Z procedure", Test_Rotate_Z'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Translate procedure", Test_Translate'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Scale_Factors procedure", Test_Scale_Factors'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Scale_Factor procedure", Test_Scale_Factor'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Transpose function", Test_Transpose'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Diagonal function", Test_Diagonal'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Main_Diagonal function", Test_Main_Diagonal'Access)); Test_Suite.Add_Test (Caller.Create (Name & "Test Trace function", Test_Trace'Access)); return Test_Suite'Access; end Suite; procedure Test_T (Object : in out Test) is Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), Offset); Result : constant Matrix4 := T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_T; procedure Test_Rx (Object : in out Test) is Angle : constant Float_64 := 60.0; CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, CA, SA, 0.0), (0.0, -SA, CA, 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := Rx (To_Radians (Angle)); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rx; procedure Test_Ry (Object : in out Test) is Angle : constant Float_64 := 60.0; CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, 0.0, -SA, 0.0), (0.0, 1.0, 0.0, 0.0), (SA, 0.0, CA, 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := Ry (To_Radians (Angle)); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Ry; procedure Test_Rz (Object : in out Test) is Angle : constant Float_64 := 60.0; CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, SA, 0.0, 0.0), (-SA, CA, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := Rz (To_Radians (Angle)); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rz; procedure Test_R (Object : in out Test) is Angle : constant Float_64 := 90.0; Expected : constant Matrix4 := Rz (To_Radians (Angle)) * Ry (To_Radians (Angle)) * Rx (To_Radians (Angle)); Result : constant Matrix4 := R ((0.0, 1.0, 0.0, 1.0), To_Radians (Angle)); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_R; procedure Test_S (Object : in out Test) is Factors : constant Vector4 := (2.0, 3.0, 4.0, 1.0); Expected : constant Matrix4 := ((Factors (X), 0.0, 0.0, 0.0), (0.0, Factors (Y), 0.0, 0.0), (0.0, 0.0, Factors (Z), 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := S (Factors); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_S; procedure Test_Add_Offset (Object : in out Test) is use Orka.SIMD.AVX.Doubles.Arithmetic; -- W of sum must be 1.0 Offset_A : constant Vector4 := (2.0, 3.0, 4.0, 1.0); Offset_B : constant Vector4 := (-5.0, 3.0, 6.0, 0.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), Offset_A + Offset_B); Result : constant Matrix4 := Offset_A + (Offset_B + Identity_Matrix); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Add_Offset; procedure Test_Multiply_Factor (Object : in out Test) is Factor_A : constant Float_64 := 2.0; Factor_B : constant Float_64 := 2.0; Total : constant Float_64 := Factor_A * Factor_B; Expected : constant Matrix4 := ((Total, 0.0, 0.0, 0.0), (0.0, Total, 0.0, 0.0), (0.0, 0.0, Total, 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := Factor_A * (Factor_B * Identity_Matrix); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Multiply_Factor; procedure Test_Rotate_At_Origin (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); Expected : constant Matrix4 := Rz (To_Radians (Angle)) * Ry (To_Radians (Angle)) * Rx (To_Radians (Angle)) * T (Offset); Result : constant Matrix4 := R ((0.0, 1.0, 0.0, 1.0), To_Radians (Angle)) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_At_Origin; procedure Test_Rotate (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vectors.Point := (2.0, 3.0, 4.0, 1.0); Expected : Matrix4 := Rz (To_Radians (Angle)) * Ry (To_Radians (Angle)) * Rx (To_Radians (Angle)); Result : constant Matrix4 := R ((0.0, 1.0, 0.0, 1.0), To_Radians (Angle), Offset) * T (Offset); begin Expected (W) := Vector4 (Offset); for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate; procedure Test_Rotate_X_At_Origin (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, CA, SA, 0.0), (0.0, -SA, CA, 0.0), (2.0, -4.0, 3.0, 1.0)); Result : constant Matrix4 := Rx (To_Radians (Angle)) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_X_At_Origin; procedure Test_Rotate_Y_At_Origin (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, 0.0, -SA, 0.0), (0.0, 1.0, 0.0, 0.0), (SA, 0.0, CA, 0.0), (4.0, 3.0, -2.0, 1.0)); Result : constant Matrix4 := Ry (To_Radians (Angle)) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_Y_At_Origin; procedure Test_Rotate_Z_At_Origin (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, SA, 0.0, 0.0), (-SA, CA, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (-3.0, 2.0, 4.0, 1.0)); Result : constant Matrix4 := Rz (To_Radians (Angle)) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_Z_At_Origin; procedure Test_Rotate_X (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vectors.Point := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, CA, SA, 0.0), (0.0, -SA, CA, 0.0), Vector4 (Offset)); Result : constant Matrix4 := Rx (To_Radians (Angle), Offset) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_X; procedure Test_Rotate_Y (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vectors.Point := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, 0.0, -SA, 0.0), (0.0, 1.0, 0.0, 0.0), (SA, 0.0, CA, 0.0), Vector4 (Offset)); Result : constant Matrix4 := Ry (To_Radians (Angle), Offset) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_Y; procedure Test_Rotate_Z (Object : in out Test) is Angle : constant Float_64 := 90.0; Offset : constant Vectors.Point := (2.0, 3.0, 4.0, 1.0); CA : constant Float_64 := EF.Cos (Angle, 360.0); SA : constant Float_64 := EF.Sin (Angle, 360.0); Expected : constant Matrix4 := ((CA, SA, 0.0, 0.0), (-SA, CA, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), Vector4 (Offset)); Result : constant Matrix4 := Rz (To_Radians (Angle), Offset) * T (Offset); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Rotate_Z; procedure Test_Translate (Object : in out Test) is Offset : constant Vector4 := (2.0, 3.0, 4.0, 1.0); Expected : constant Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), Offset); Result : constant Matrix4 := Offset + Identity_Matrix; begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Translate; procedure Test_Scale_Factors (Object : in out Test) is Factors : constant Vector4 := (2.0, 3.0, 4.0, 0.0); Expected : constant Matrix4 := ((Factors (X), 0.0, 0.0, 0.0), (0.0, Factors (Y), 0.0, 0.0), (0.0, 0.0, Factors (Z), 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := S (Factors) * Identity_Matrix; begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Scale_Factors; procedure Test_Scale_Factor (Object : in out Test) is Factor : constant Float_64 := 2.0; Expected : constant Matrix4 := ((Factor, 0.0, 0.0, 0.0), (0.0, Factor, 0.0, 0.0), (0.0, 0.0, Factor, 0.0), (0.0, 0.0, 0.0, 1.0)); Result : constant Matrix4 := Factor * Identity_Matrix; begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Scale_Factor; procedure Test_Transpose (Object : in out Test) is Value : constant Matrix4 := ((1.0, 11.0, 14.0, 16.0), (5.0, 2.0, 12.0, 15.0), (8.0, 6.0, 3.0, 13.0), (10.0, 9.0, 7.0, 4.0)); Expected : constant Matrix4 := ((1.0, 5.0, 8.0, 10.0), (11.0, 2.0, 6.0, 9.0), (14.0, 12.0, 3.0, 7.0), (16.0, 15.0, 13.0, 4.0)); Result : constant Matrix4 := Transpose (Value); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Transpose; procedure Test_Diagonal (Object : in out Test) is Values : constant Vector4 := (2.0, 3.0, 4.0, 5.0); A : Float_64 renames Values (X); B : Float_64 renames Values (Y); C : Float_64 renames Values (Z); D : Float_64 renames Values (W); Expected : constant Matrix4 := ((A, 0.0, 0.0, 0.0), (0.0, B, 0.0, 0.0), (0.0, 0.0, C, 0.0), (0.0, 0.0, 0.0, D)); Result : constant Matrix4 := Diagonal (Values); begin for I in Index_Homogeneous loop Assert_Equivalent (Expected (I), Result (I), I); end loop; end Test_Diagonal; procedure Test_Main_Diagonal (Object : in out Test) is Expected : constant Vector4 := (2.0, 3.0, 4.0, 5.0); Result : constant Vector4 := Main_Diagonal (Diagonal (Expected)); begin Assert_Equivalent (Expected, Result); end Test_Main_Diagonal; procedure Test_Trace (Object : in out Test) is Values : constant Vector4 := (2.0, 3.0, 4.0, 5.0); Expected : constant Float_64 := Values (X) + Values (Y) + Values (Z) + Values (W); Result : constant Float_64 := Trace (Diagonal (Values)); begin Assert (Is_Equivalent (Expected, Result), "Unexpected Double"); end Test_Trace; end Test_Transforms_Doubles_Matrices;
generic Capacite : Integer ; package matrice_pleine is type T_Vecteur_float is array(1..Capacite) of float ; type T_Vecteur_integer is array(1..Capacite) of integer ; type T_Matrice is array(1..Capacite) of T_Vecteur_float; -- nom : Initialiser -- Sémantique : initialiser une matrice pleine. -- Parametres : M out T_Matrice procedure initialiser(M : out T_Matrice); -- Nom : Est_Ligne_Null -- Sémantique : savoir si une ligne d'une matrice pleine est nulle ou non. -- Paramétres : -- M : in T_Matrice la matrice pleine à examiner. -- indice : in entier est l'indice de la ligne de la matrice. -- Pre-condition : 0=<indice <= Capacite -- Post-condition : retourner true si la ligne est nulle et false sinon. --Est ce qu'une ligne d'une matrice pleine est nulle? function Est_Ligne_Nulle(M : in T_Matrice ; indice : integer) return boolean ; -- Ecrire un vecteur reel dans un fichier. procedure Ecrire(vect : in T_Vecteur_float; fichier : in String; alpha : in float;Nb_iteration : in integer); -- Ecrire un vecteur entier dans un fichier. procedure Ecrire(vect : in T_Vecteur_integer; fichier : in String); -- Realiser le produit d'une matrice avec un vecteur. function Produit(Mat : in T_Matrice ;V : in T_Vecteur_float) return T_Vecteur_float; -- Calculer la matrice des hyperliens contenant l'entier 1 dans chaque position de lien du réseaux -- ainsi que le vecteur contenant le nombre des hyperliens de chque noeud. procedure vecteur_hyperliens(fichier : in String ;V : out T_Vecteur_integer ;M : out T_Matrice) ; -- Calculer la matrice H. procedure calculh(M : in out T_Matrice ;V : T_Vecteur_integer) ; -- Transformer la matrice H en S. procedure calculS(H : in out T_Matrice); -- Transformer S en G. procedure calculG(S : in out T_Matrice); -- Trier le vecteur poids ainsi que le vecteur des indices. procedure Trier(V : in out T_Vecteur_float ;V_indice : out T_Vecteur_integer); end matrice_pleine;
pragma License (Unrestricted); -- implementation unit required by compiler with System.Unsigned_Types; package System.Val_LLU is pragma Pure; -- required for Modular'Value by compiler (s-valllu.ads) function Value_Long_Long_Unsigned (Str : String) return Unsigned_Types.Long_Long_Unsigned; end System.Val_LLU;
-- C45112B.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT THE BOUNDS OF THE RESULT OF A LOGICAL ARRAY OPERATION -- ARE THE BOUNDS OF THE LEFT OPERAND WHEN THE OPERANDS ARE NULL -- ARRAYS. -- RJW 2/3/86 WITH REPORT; USE REPORT; PROCEDURE C45112B IS TYPE ARR IS ARRAY(INTEGER RANGE <>) OF BOOLEAN; A1 : ARR(IDENT_INT(4) .. IDENT_INT(3)); A2 : ARR(IDENT_INT(2) .. IDENT_INT(1)); SUBTYPE CARR IS ARR (IDENT_INT (A1'FIRST) .. IDENT_INT (A1'LAST)); PROCEDURE CHECK (X : ARR; N1, N2 : STRING) IS BEGIN IF X'FIRST /= A1'FIRST OR X'LAST /= A1'LAST THEN FAILED ( "WRONG BOUNDS FOR " & N1 & " FOR " & N2 ); END IF; END CHECK; BEGIN TEST ( "C45112B", "CHECK THE BOUNDS OF THE RESULT OF LOGICAL " & "ARRAY OPERATIONS ON NULL ARRAYS" ); BEGIN DECLARE AAND : CONSTANT ARR := A1 AND A2; AOR : CONSTANT ARR := A1 OR A2; AXOR : CONSTANT ARR := A1 XOR A2; BEGIN CHECK (AAND, "INITIALIZATION OF CONSTANT ARRAY ", "'AND'" ); CHECK (AOR, "INITIALIZATION OF CONSTANT ARRAY ", "'OR'" ); CHECK (AXOR, "INITIALIZATION OF CONSTANT ARRAY ", "'XOR'" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => FAILED ( "CONSTRAINT_ERROR RAISED DURING " & "INTIALIZATIONS" ); WHEN OTHERS => FAILED ( "OTHER EXCEPTION RAISED DURING " & "INITIALIZATIONS" ); END; DECLARE PROCEDURE PROC (A : ARR; STR : STRING) IS BEGIN CHECK (A, "FORMAL PARAMETER FOR CONSTRAINED ARRAY", STR); END PROC; BEGIN PROC ((A1 AND A2), "'AND'" ); PROC ((A1 OR A2), "'OR'" ); PROC ((A1 XOR A2), "'XOR'" ); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED DURING TEST FOR FORMAL " & "PARAMETERS" ); END; DECLARE FUNCTION FUNCAND RETURN ARR IS BEGIN RETURN A1 AND A2; END FUNCAND; FUNCTION FUNCOR RETURN ARR IS BEGIN RETURN A1 OR A2; END FUNCOR; FUNCTION FUNCXOR RETURN ARR IS BEGIN RETURN A1 XOR A2; END FUNCXOR; BEGIN CHECK (FUNCAND, "RETURN STATEMENT", "'AND'"); CHECK (FUNCOR, "RETURN STATEMENT", "'OR'"); CHECK (FUNCXOR, "RETURN STATEMENT", "'XOR'"); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED DURING TEST FOR RETURN " & "FROM FUNCTION" ); END; BEGIN DECLARE GENERIC X : IN ARR; PACKAGE PKG IS FUNCTION G RETURN ARR; END PKG; PACKAGE BODY PKG IS FUNCTION G RETURN ARR IS BEGIN RETURN X; END G; END PKG; PACKAGE PAND IS NEW PKG(X => A1 AND A2); PACKAGE POR IS NEW PKG(X => A1 OR A2); PACKAGE PXOR IS NEW PKG(X => A1 XOR A2); BEGIN CHECK (PAND.G, "GENERIC FORMAL PARAMETER", "'AND'"); CHECK (POR.G, "GENERIC FORMAL PARAMETER", "'OR'"); CHECK (PXOR.G, "GENERIC FORMAL PARAMMETER", "'XOR'"); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED DURING GENERIC " & "INSTANTIATION" ); END; DECLARE TYPE ACC IS ACCESS ARR; AC : ACC; BEGIN AC := NEW ARR'(A1 AND A2); CHECK (AC.ALL, "ALLOCATION", "'AND'"); AC := NEW ARR'(A1 OR A2); CHECK (AC.ALL, "ALLOCATION", "'OR'"); AC := NEW ARR'(A1 XOR A2); CHECK (AC.ALL, "ALLOCATION", "'XOR'"); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED ON ALLOCATION" ); END; BEGIN CHECK (CARR' (A1 AND A2), "QUALIFIED EXPRESSION", "'AND'"); CHECK (CARR' (A1 OR A2), "QUALIFIED EXPRESSION", "'OR'"); CHECK (CARR' (A1 XOR A2), "QUALIFIED EXPRESSION", "'XOR'"); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED ON QUALIFIED EXPRESSION" ); END; DECLARE TYPE REC IS RECORD RCA : CARR; END RECORD; R1 : REC; BEGIN R1 := (RCA => (A1 AND A2)); CHECK (R1.RCA, "AGGREGATE", "'AND'"); R1 := (RCA => (A1 OR A2)); CHECK (R1.RCA, "AGGREGATE", "'OR'"); R1 := (RCA => (A1 XOR A2)); CHECK (R1.RCA, "AGGREGATE", "'XOR'"); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED ON AGGREGATE" ); END; BEGIN DECLARE TYPE RECDEF IS RECORD RCDF1 : CARR := A1 AND A2; RCDF2 : CARR := A1 OR A2; RCDF3 : CARR := A1 XOR A2; END RECORD; RD : RECDEF; BEGIN CHECK (RD.RCDF1, "DEFAULT RECORD", "'AND'"); CHECK (RD.RCDF2, "DEFAULT RECORD", "'OR'"); CHECK (RD.RCDF3, "DEFAULT RECORD", "'XOR'"); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED ON DEFAULT RECORD" ); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED DURING INITIALIZATION OF " & "DEFAULT RECORD" ); END; DECLARE PROCEDURE PDEF (X : CARR := A1 AND A2; Y : CARR := A1 OR A2; Z : CARR := A1 XOR A2 ) IS BEGIN CHECK (X, "DEFAULT PARAMETER", "'AND'"); CHECK (Y, "DEFAULT PARAMETER", "'OR'"); CHECK (Z, "DEFAULT PARAMETER", "'XOR'"); END PDEF; BEGIN PDEF; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED ON DEFAULT PARM" ); END; RESULT; END C45112B;
-- { dg-excess-errors "cannot generate code" } package Lto12_Pkg is type R (Kind : Boolean := False) is record case Kind is when True => I : Integer; when others => null; end case; end record; function F return R; end Lto12_Pkg;
-- nymph_logging.ads - Main package for use by NymphRPC clients (Spec). -- -- 2017/07/01, Maya Posch -- (c) Nyanko.ws type LogFunction is not null access procedure (level: in integer, text: in string);
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . G N A T _ I N T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1995-2008, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- 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). -- -- -- ------------------------------------------------------------------------------ -- This package contains the utility routines used for calling the GNAT -- compiler from inside the ASIS implementation routines to create a tree -- file. These routines may be used by ASIS-based tools as well. The idea is -- to call GNAT in a black-box manner. The current version of this package -- borrows most of the ideas and the code patterns from the body of the -- GNAT Make package (which defines the gnatmake-related routines). -- Unfortunately, GNAT do not provide the public interface to these -- routines, so we simply have copied the code from make.adb with some -- modifications. -- -- This package also contains the routine which reads the tree file with -- checking the GNAT-ASIS versions compartibility. with Ada.Calendar; use Ada.Calendar; with A4G.A_Types; use A4G.A_Types; with A4G.A_Debug; with GNAT.OS_Lib; use GNAT.OS_Lib; with Types; use Types; package A4G.GNAT_Int is ----------------------------------- -- Compiler Variables & Routines -- ----------------------------------- Nul_Argument_List : constant Argument_List (1 .. 0) := (others => null); -- The flags listed below are used to form the appropriate GNAT or -- gnatmake call to create the tree file Comp_Flag : constant String_Access := new String'("-c"); GNAT_Flag : constant String_Access := new String'("-gnatg"); GNAT_Flag_ct : constant String_Access := new String'("-gnatct"); GNAT_Flag_t : constant String_Access := new String'("-gnatt"); GNAT_Flag_ws : constant String_Access := new String'("-gnatws"); GNAT_Flag_yN : constant String_Access := new String'("-gnatyN"); GNAT_Flag_05 : constant String_Access := new String'("-gnat05"); GCC_Flag_X : constant String_Access := new String'("-x"); GCC_Par_Ada : constant String_Access := new String'("ada"); GCC_Flag_o : constant String_Access := new String'("-o"); GNATMAKE_Flag_q : constant String_Access := new String'("-q"); GNATMAKE_Flag_u : constant String_Access := new String'("-u"); GNATMAKE_Flag_f : constant String_Access := new String'("-f"); GNATMAKE_Flag_cargs : constant String_Access := new String'("-cargs"); -- Display_Executed_Programs : Boolean renames A4G.A_Debug.Debug_Mode; -- Set to True if name of commands should be output on stderr. -- Now this flag is toughtly binded with the flag setting the -- ASIS Debug Mode. Is it a good decision? function Execute (Program : String_Access; Args : Argument_List; Compiler_Out : String := ""; Display_Call : Boolean := A4G.A_Debug.Debug_Mode) return Boolean; -- Executes Program. If the program is not set (the actual for Program is -- null), executes the gcc command Args contains the arguments to be passed -- to Program. If the program is executed successfully True is returned. -- -- If Compiler_Out is a non-empty string, this string is treated as the -- name of a text file to redirect the compiler output into (if the file -- does not exist, it is created). Othervise the compiler output is -- sent to Stderr. -- -- If Display_Call is ON, outputs into Stderr the command used to execure -- Program. procedure Create_Tree (Source_File : String_Access; Context : Context_Id; Is_Predefined : Boolean; Success : out Boolean); -- Tries to create the tree output file for the given source file -- in the context of a given Context. Uses the "standard" GNAT -- installation to do this procedure Tree_In_With_Version_Check (Desc : File_Descriptor; Cont : Context_Id; Success : out Boolean); -- Desc is the file descriptor for the file containing the tree file -- created by the compiler, Cont is the Id of the Context this tree is -- supposed to belong to. This routine reads in the content of the tree -- file and makes the GNAT-ASIS version check as a part of tree reading. -- If the version check fails or if any error corresponding to the problems -- with the expected tree format is detected, Program_Error is raised with -- the exception message "Inconsistent versions of GNAT and ASIS". If -- the tree can not be read in because of any other reason (for example, -- it is not compile-only), the Success parameter is set OFF and the -- continuation depends on the Context parameters. If the tree has been -- read in successfully and if it is compile-only, Success is set ON. -- -- Before calling this procedure, a caller should put the name of the tree -- file to read into A_Name_Buffer. -- -- NOTE: the procedure always closes Desc before returning. Closing it -- the second time is erroneous. function A_Time (T : Time_Stamp_Type) return Time; -- Converts GNAT file time stamp into the corresponding value -- of Asis_Time. end A4G.GNAT_Int;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P A R . C H 5 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ pragma Style_Checks (All_Checks); -- Turn off subprogram body ordering check. Subprograms are in order by RM -- section rather than alphabetical. with Sinfo.CN; use Sinfo.CN; separate (Par) package body Ch5 is -- Local functions, used only in this chapter function P_Case_Statement return Node_Id; function P_Case_Statement_Alternative return Node_Id; function P_Exit_Statement return Node_Id; function P_Goto_Statement return Node_Id; function P_If_Statement return Node_Id; function P_Label return Node_Id; function P_Null_Statement return Node_Id; function P_Assignment_Statement (LHS : Node_Id) return Node_Id; -- Parse assignment statement. On entry, the caller has scanned the left -- hand side (passed in as Lhs), and the colon-equal (or some symbol -- taken to be an error equivalent such as equal). function P_Begin_Statement (Block_Name : Node_Id := Empty) return Node_Id; -- Parse begin-end statement. If Block_Name is non-Empty on entry, it is -- the N_Identifier node for the label on the block. If Block_Name is -- Empty on entry (the default), then the block statement is unlabeled. function P_Declare_Statement (Block_Name : Node_Id := Empty) return Node_Id; -- Parse declare block. If Block_Name is non-Empty on entry, it is -- the N_Identifier node for the label on the block. If Block_Name is -- Empty on entry (the default), then the block statement is unlabeled. function P_For_Statement (Loop_Name : Node_Id := Empty) return Node_Id; -- Parse for statement. If Loop_Name is non-Empty on entry, it is -- the N_Identifier node for the label on the loop. If Loop_Name is -- Empty on entry (the default), then the for statement is unlabeled. function P_Iterator_Specification (Def_Id : Node_Id) return Node_Id; -- Parse an iterator specification. The defining identifier has already -- been scanned, as it is the common prefix between loop and iterator -- specification. function P_Loop_Statement (Loop_Name : Node_Id := Empty) return Node_Id; -- Parse loop statement. If Loop_Name is non-Empty on entry, it is -- the N_Identifier node for the label on the loop. If Loop_Name is -- Empty on entry (the default), then the loop statement is unlabeled. function P_While_Statement (Loop_Name : Node_Id := Empty) return Node_Id; -- Parse while statement. If Loop_Name is non-Empty on entry, it is -- the N_Identifier node for the label on the loop. If Loop_Name is -- Empty on entry (the default), then the while statement is unlabeled. function Set_Loop_Block_Name (L : Character) return Name_Id; -- Given a letter 'L' for a loop or 'B' for a block, returns a name -- of the form L_nn or B_nn where nn is a serial number obtained by -- incrementing the variable Loop_Block_Count. procedure Then_Scan; -- Scan past THEN token, testing for illegal junk after it --------------------------------- -- 5.1 Sequence of Statements -- --------------------------------- -- SEQUENCE_OF_STATEMENTS ::= STATEMENT {STATEMENT} {LABEL} -- Note: the final label is an Ada 2012 addition. -- STATEMENT ::= -- {LABEL} SIMPLE_STATEMENT | {LABEL} COMPOUND_STATEMENT -- SIMPLE_STATEMENT ::= NULL_STATEMENT -- | ASSIGNMENT_STATEMENT | EXIT_STATEMENT -- | GOTO_STATEMENT | PROCEDURE_CALL_STATEMENT -- | RETURN_STATEMENT | ENTRY_CALL_STATEMENT -- | REQUEUE_STATEMENT | DELAY_STATEMENT -- | ABORT_STATEMENT | RAISE_STATEMENT -- | CODE_STATEMENT -- COMPOUND_STATEMENT ::= -- IF_STATEMENT | CASE_STATEMENT -- | LOOP_STATEMENT | BLOCK_STATEMENT -- | ACCEPT_STATEMENT | SELECT_STATEMENT -- This procedure scans a sequence of statements. The caller sets SS_Flags -- to indicate acceptable termination conditions for the sequence: -- SS_Flags.Eftm Terminate on ELSIF -- SS_Flags.Eltm Terminate on ELSE -- SS_Flags.Extm Terminate on EXCEPTION -- SS_Flags.Ortm Terminate on OR -- SS_Flags.Tatm Terminate on THEN ABORT (Token = ABORT on return) -- SS_Flags.Whtm Terminate on WHEN -- SS_Flags.Unco Unconditional terminate after scanning one statement -- In addition, the scan is always terminated by encountering END or the -- end of file (EOF) condition. If one of the six above terminators is -- encountered with the corresponding SS_Flags flag not set, then the -- action taken is as follows: -- If the keyword occurs to the left of the expected column of the end -- for the current sequence (as recorded in the current end context), -- then it is assumed to belong to an outer context, and is considered -- to terminate the sequence of statements. -- If the keyword occurs to the right of, or in the expected column of -- the end for the current sequence, then an error message is output, -- the keyword together with its associated context is skipped, and -- the statement scan continues until another terminator is found. -- Note that the first action means that control can return to the caller -- with Token set to a terminator other than one of those specified by the -- SS parameter. The caller should treat such a case as equivalent to END. -- In addition, the flag SS_Flags.Sreq is set to True to indicate that at -- least one real statement (other than a pragma) is required in the -- statement sequence. During the processing of the sequence, this -- flag is manipulated to indicate the current status of the requirement -- for a statement. For example, it is turned off by the occurrence of a -- statement, and back on by a label (which requires a following statement) -- Error recovery: cannot raise Error_Resync. If an error occurs during -- parsing a statement, then the scan pointer is advanced past the next -- semicolon and the parse continues. function P_Sequence_Of_Statements (SS_Flags : SS_Rec) return List_Id is Statement_Required : Boolean; -- This flag indicates if a subsequent statement (other than a pragma) -- is required. It is initialized from the Sreq flag, and modified as -- statements are scanned (a statement turns it off, and a label turns -- it back on again since a statement must follow a label). -- Note : this final requirement is lifted in Ada 2012. Statement_Seen : Boolean; -- In Ada 2012, a label can end a sequence of statements, but the -- sequence cannot contain only labels. This flag is set whenever a -- label is encountered, to enforce this rule at the end of a sequence. Declaration_Found : Boolean := False; -- This flag is set True if a declaration is encountered, so that the -- error message about declarations in the statement part is only -- given once for a given sequence of statements. Scan_State_Label : Saved_Scan_State; Scan_State : Saved_Scan_State; Statement_List : List_Id; Block_Label : Name_Id; Id_Node : Node_Id; Name_Node : Node_Id; procedure Junk_Declaration; -- Procedure called to handle error of declaration encountered in -- statement sequence. procedure Test_Statement_Required; -- Flag error if Statement_Required flag set ---------------------- -- Junk_Declaration -- ---------------------- procedure Junk_Declaration is begin if (not Declaration_Found) or All_Errors_Mode then Error_Msg_SC -- CODEFIX ("declarations must come before BEGIN"); Declaration_Found := True; end if; Skip_Declaration (Statement_List); end Junk_Declaration; ----------------------------- -- Test_Statement_Required -- ----------------------------- procedure Test_Statement_Required is function All_Pragmas return Boolean; -- Return True if statement list is all pragmas ----------------- -- All_Pragmas -- ----------------- function All_Pragmas return Boolean is S : Node_Id; begin S := First (Statement_List); while Present (S) loop if Nkind (S) /= N_Pragma then return False; else Next (S); end if; end loop; return True; end All_Pragmas; -- Start of processing for Test_Statement_Required begin if Statement_Required then -- Check no statement required after label in Ada 2012, and that -- it is OK to have nothing but pragmas in a statement sequence. if Ada_Version >= Ada_2012 and then not Is_Empty_List (Statement_List) and then ((Nkind (Last (Statement_List)) = N_Label and then Statement_Seen) or else All_Pragmas) then -- This Ada 2012 construct not allowed in a compiler unit Check_Compiler_Unit ("null statement list", Token_Ptr); declare Null_Stm : constant Node_Id := Make_Null_Statement (Token_Ptr); begin Set_Comes_From_Source (Null_Stm, False); Append_To (Statement_List, Null_Stm); end; -- If not Ada 2012, or not special case above, give error message else Error_Msg_BC -- CODEFIX ("statement expected"); end if; end if; end Test_Statement_Required; -- Start of processing for P_Sequence_Of_Statements begin Statement_List := New_List; Statement_Required := SS_Flags.Sreq; Statement_Seen := False; loop Ignore (Tok_Semicolon); begin if Style_Check then Style.Check_Indentation; end if; -- Deal with reserved identifier (in assignment or call) if Is_Reserved_Identifier then Save_Scan_State (Scan_State); -- at possible bad identifier Scan; -- and scan past it -- We have an reserved word which is spelled in identifier -- style, so the question is whether it really is intended -- to be an identifier. if -- If followed by a semicolon, then it is an identifier, -- with the exception of the cases tested for below. (Token = Tok_Semicolon and then Prev_Token /= Tok_Return and then Prev_Token /= Tok_Null and then Prev_Token /= Tok_Raise and then Prev_Token /= Tok_End and then Prev_Token /= Tok_Exit) -- If followed by colon, colon-equal, or dot, then we -- definitely have an identifier (could not be reserved) or else Token = Tok_Colon or else Token = Tok_Colon_Equal or else Token = Tok_Dot -- Left paren means we have an identifier except for those -- reserved words that can legitimately be followed by a -- left paren. or else (Token = Tok_Left_Paren and then Prev_Token /= Tok_Case and then Prev_Token /= Tok_Delay and then Prev_Token /= Tok_If and then Prev_Token /= Tok_Elsif and then Prev_Token /= Tok_Return and then Prev_Token /= Tok_When and then Prev_Token /= Tok_While and then Prev_Token /= Tok_Separate) then -- Here we have an apparent reserved identifier and the -- token past it is appropriate to this usage (and would -- be a definite error if this is not an identifier). What -- we do is to use P_Identifier to fix up the identifier, -- and then fall into the normal processing. Restore_Scan_State (Scan_State); -- back to the ID Scan_Reserved_Identifier (Force_Msg => False); -- Not a reserved identifier after all (or at least we can't -- be sure that it is), so reset the scan and continue. else Restore_Scan_State (Scan_State); -- back to the reserved word end if; end if; -- Now look to see what kind of statement we have case Token is -- Case of end or EOF when Tok_End | Tok_EOF => -- These tokens always terminate the statement sequence Test_Statement_Required; exit; -- Case of ELSIF when Tok_Elsif => -- Terminate if Eftm set or if the ELSIF is to the left -- of the expected column of the end for this sequence if SS_Flags.Eftm or else Start_Column < Scope.Table (Scope.Last).Ecol then Test_Statement_Required; exit; -- Otherwise complain and skip past ELSIF Condition then else Error_Msg_SC ("ELSIF not allowed here"); Scan; -- past ELSIF Discard_Junk_Node (P_Expression_No_Right_Paren); Then_Scan; Statement_Required := False; end if; -- Case of ELSE when Tok_Else => -- Terminate if Eltm set or if the else is to the left -- of the expected column of the end for this sequence if SS_Flags.Eltm or else Start_Column < Scope.Table (Scope.Last).Ecol then Test_Statement_Required; exit; -- Otherwise complain and skip past else else Error_Msg_SC ("ELSE not allowed here"); Scan; -- past ELSE Statement_Required := False; end if; -- Case of exception when Tok_Exception => Test_Statement_Required; -- If Extm not set and the exception is not to the left of -- the expected column of the end for this sequence, then we -- assume it belongs to the current sequence, even though it -- is not permitted. if not SS_Flags.Extm and then Start_Column >= Scope.Table (Scope.Last).Ecol then Error_Msg_SC ("exception handler not permitted here"); Scan; -- past EXCEPTION Discard_Junk_List (Parse_Exception_Handlers); end if; -- Always return, in the case where we scanned out handlers -- that we did not expect, Parse_Exception_Handlers returned -- with Token being either end or EOF, so we are OK. exit; -- Case of OR when Tok_Or => -- Terminate if Ortm set or if the or is to the left of the -- expected column of the end for this sequence. if SS_Flags.Ortm or else Start_Column < Scope.Table (Scope.Last).Ecol then Test_Statement_Required; exit; -- Otherwise complain and skip past or else Error_Msg_SC ("OR not allowed here"); Scan; -- past or Statement_Required := False; end if; -- Case of THEN (deal also with THEN ABORT) when Tok_Then => Save_Scan_State (Scan_State); -- at THEN Scan; -- past THEN -- Terminate if THEN ABORT allowed (ATC case) exit when SS_Flags.Tatm and then Token = Tok_Abort; -- Otherwise we treat THEN as some kind of mess where we did -- not see the associated IF, but we pick up assuming it had -- been there. Restore_Scan_State (Scan_State); -- to THEN Append_To (Statement_List, P_If_Statement); Statement_Required := False; -- Case of WHEN (error because we are not in a case) when Tok_Others | Tok_When => -- Terminate if Whtm set or if the WHEN is to the left of -- the expected column of the end for this sequence. if SS_Flags.Whtm or else Start_Column < Scope.Table (Scope.Last).Ecol then Test_Statement_Required; exit; -- Otherwise complain and skip when Choice {| Choice} => else Error_Msg_SC ("WHEN not allowed here"); Scan; -- past when Discard_Junk_List (P_Discrete_Choice_List); TF_Arrow; Statement_Required := False; end if; -- Cases of statements starting with an identifier when Tok_Identifier => Check_Bad_Layout; -- Save scan pointers and line number in case block label Id_Node := Token_Node; Block_Label := Token_Name; Save_Scan_State (Scan_State_Label); -- at possible label Scan; -- past Id -- Check for common case of assignment, since it occurs -- frequently, and we want to process it efficiently. if Token = Tok_Colon_Equal then Scan; -- past the colon-equal Append_To (Statement_List, P_Assignment_Statement (Id_Node)); Statement_Required := False; -- Check common case of procedure call, another case that -- we want to speed up as much as possible. elsif Token = Tok_Semicolon then Change_Name_To_Procedure_Call_Statement (Id_Node); Append_To (Statement_List, Id_Node); Scan; -- past semicolon Statement_Required := False; -- Here is the special test for a suspicious label, more -- accurately a suspicious name, which we think perhaps -- should have been a label. If next token is one of -- LOOP, FOR, WHILE, DECLARE, BEGIN, then make an entry -- in the suspicious label table. if Token = Tok_Loop or else Token = Tok_For or else Token = Tok_While or else Token = Tok_Declare or else Token = Tok_Begin then Suspicious_Labels.Append ((Proc_Call => Id_Node, Semicolon_Loc => Prev_Token_Ptr, Start_Token => Token_Ptr)); end if; -- Check for case of "go to" in place of "goto" elsif Token = Tok_Identifier and then Block_Label = Name_Go and then Token_Name = Name_To then Error_Msg_SP -- CODEFIX ("goto is one word"); Append_To (Statement_List, P_Goto_Statement); Statement_Required := False; -- Check common case of = used instead of :=, just so we -- give a better error message for this special misuse. elsif Token = Tok_Equal then T_Colon_Equal; -- give := expected message Append_To (Statement_List, P_Assignment_Statement (Id_Node)); Statement_Required := False; -- Check case of loop label or block label elsif Token = Tok_Colon or else (Token in Token_Class_Labeled_Stmt and then not Token_Is_At_Start_Of_Line) then T_Colon; -- past colon (if there, or msg for missing one) -- Test for more than one label loop exit when Token /= Tok_Identifier; Save_Scan_State (Scan_State); -- at second Id Scan; -- past Id if Token = Tok_Colon then Error_Msg_SP ("only one label allowed on block or loop"); Scan; -- past colon on extra label -- Use the second label as the "real" label Scan_State_Label := Scan_State; -- We will set Error_name as the Block_Label since -- we really don't know which of the labels might -- be used at the end of the loop or block. Block_Label := Error_Name; -- If Id with no colon, then backup to point to the -- Id and we will issue the message below when we try -- to scan out the statement as some other form. else Restore_Scan_State (Scan_State); -- to second Id exit; end if; end loop; -- Loop_Statement (labeled Loop_Statement) if Token = Tok_Loop then Append_To (Statement_List, P_Loop_Statement (Id_Node)); -- While statement (labeled loop statement with WHILE) elsif Token = Tok_While then Append_To (Statement_List, P_While_Statement (Id_Node)); -- Declare statement (labeled block statement with -- DECLARE part) elsif Token = Tok_Declare then Append_To (Statement_List, P_Declare_Statement (Id_Node)); -- Begin statement (labeled block statement with no -- DECLARE part) elsif Token = Tok_Begin then Append_To (Statement_List, P_Begin_Statement (Id_Node)); -- For statement (labeled loop statement with FOR) elsif Token = Tok_For then Append_To (Statement_List, P_For_Statement (Id_Node)); -- Improper statement follows label. If we have an -- expression token, then assume the colon was part -- of a misplaced declaration. elsif Token not in Token_Class_Eterm then Restore_Scan_State (Scan_State_Label); Junk_Declaration; -- Otherwise complain we have inappropriate statement else Error_Msg_AP ("loop or block statement must follow label"); end if; Statement_Required := False; -- Here we have an identifier followed by something -- other than a colon, semicolon or assignment symbol. -- The only valid possibility is a name extension symbol elsif Token in Token_Class_Namext then Restore_Scan_State (Scan_State_Label); -- to Id Name_Node := P_Name; -- Skip junk right parens in this context Ignore (Tok_Right_Paren); -- Check context following call if Token = Tok_Colon_Equal then Scan; -- past colon equal Append_To (Statement_List, P_Assignment_Statement (Name_Node)); Statement_Required := False; -- Check common case of = used instead of := elsif Token = Tok_Equal then T_Colon_Equal; -- give := expected message Append_To (Statement_List, P_Assignment_Statement (Name_Node)); Statement_Required := False; -- Check apostrophe cases elsif Token = Tok_Apostrophe then Append_To (Statement_List, P_Code_Statement (Name_Node)); Statement_Required := False; -- The only other valid item after a name is ; which -- means that the item we just scanned was a call. elsif Token = Tok_Semicolon then Change_Name_To_Procedure_Call_Statement (Name_Node); Append_To (Statement_List, Name_Node); Scan; -- past semicolon Statement_Required := False; -- A slash following an identifier or a selected -- component in this situation is most likely a period -- (see location of keys on keyboard). elsif Token = Tok_Slash and then (Nkind (Name_Node) = N_Identifier or else Nkind (Name_Node) = N_Selected_Component) then Error_Msg_SC -- CODEFIX ("""/"" should be ""."""); Statement_Required := False; raise Error_Resync; -- Else we have a missing semicolon else TF_Semicolon; -- Normal processing as though semicolon were present Change_Name_To_Procedure_Call_Statement (Name_Node); Append_To (Statement_List, Name_Node); Statement_Required := False; end if; -- If junk after identifier, check if identifier is an -- instance of an incorrectly spelled keyword. If so, we -- do nothing. The Bad_Spelling_Of will have reset Token -- to the appropriate keyword, so the next time round the -- loop we will process the modified token. Note that we -- check for ELSIF before ELSE here. That's not accidental. -- We don't want to identify a misspelling of ELSE as -- ELSIF, and in particular we do not want to treat ELSEIF -- as ELSE IF. else Restore_Scan_State (Scan_State_Label); -- to identifier if Bad_Spelling_Of (Tok_Abort) or else Bad_Spelling_Of (Tok_Accept) or else Bad_Spelling_Of (Tok_Case) or else Bad_Spelling_Of (Tok_Declare) or else Bad_Spelling_Of (Tok_Delay) or else Bad_Spelling_Of (Tok_Elsif) or else Bad_Spelling_Of (Tok_Else) or else Bad_Spelling_Of (Tok_End) or else Bad_Spelling_Of (Tok_Exception) or else Bad_Spelling_Of (Tok_Exit) or else Bad_Spelling_Of (Tok_For) or else Bad_Spelling_Of (Tok_Goto) or else Bad_Spelling_Of (Tok_If) or else Bad_Spelling_Of (Tok_Loop) or else Bad_Spelling_Of (Tok_Or) or else Bad_Spelling_Of (Tok_Pragma) or else Bad_Spelling_Of (Tok_Raise) or else Bad_Spelling_Of (Tok_Requeue) or else Bad_Spelling_Of (Tok_Return) or else Bad_Spelling_Of (Tok_Select) or else Bad_Spelling_Of (Tok_When) or else Bad_Spelling_Of (Tok_While) then null; -- If not a bad spelling, then we really have junk else Scan; -- past identifier again -- If next token is first token on line, then we -- consider that we were missing a semicolon after -- the identifier, and process it as a procedure -- call with no parameters. if Token_Is_At_Start_Of_Line then Change_Name_To_Procedure_Call_Statement (Id_Node); Append_To (Statement_List, Id_Node); T_Semicolon; -- to give error message Statement_Required := False; -- Otherwise we give a missing := message and -- simply abandon the junk that is there now. else T_Colon_Equal; -- give := expected message raise Error_Resync; end if; end if; end if; -- Statement starting with operator symbol. This could be -- a call, a name starting an assignment, or a qualified -- expression. when Tok_Operator_Symbol => Check_Bad_Layout; Name_Node := P_Name; -- An attempt at a range attribute or a qualified expression -- must be illegal here (a code statement cannot possibly -- allow qualification by a function name). if Token = Tok_Apostrophe then Error_Msg_SC ("apostrophe illegal here"); raise Error_Resync; end if; -- Scan possible assignment if we have a name if Expr_Form = EF_Name and then Token = Tok_Colon_Equal then Scan; -- past colon equal Append_To (Statement_List, P_Assignment_Statement (Name_Node)); else Change_Name_To_Procedure_Call_Statement (Name_Node); Append_To (Statement_List, Name_Node); end if; TF_Semicolon; Statement_Required := False; -- Label starting with << which must precede real statement -- Note: in Ada 2012, the label may end the sequence. when Tok_Less_Less => if Present (Last (Statement_List)) and then Nkind (Last (Statement_List)) /= N_Label then Statement_Seen := True; end if; Append_To (Statement_List, P_Label); Statement_Required := True; -- Pragma appearing as a statement in a statement sequence when Tok_Pragma => Check_Bad_Layout; Append_To (Statement_List, P_Pragma); -- Abort_Statement when Tok_Abort => Check_Bad_Layout; Append_To (Statement_List, P_Abort_Statement); Statement_Required := False; -- Accept_Statement when Tok_Accept => Check_Bad_Layout; Append_To (Statement_List, P_Accept_Statement); Statement_Required := False; -- Begin_Statement (Block_Statement with no declare, no label) when Tok_Begin => Check_Bad_Layout; Append_To (Statement_List, P_Begin_Statement); Statement_Required := False; -- Case_Statement when Tok_Case => Check_Bad_Layout; Append_To (Statement_List, P_Case_Statement); Statement_Required := False; -- Block_Statement with DECLARE and no label when Tok_Declare => Check_Bad_Layout; Append_To (Statement_List, P_Declare_Statement); Statement_Required := False; -- Delay_Statement when Tok_Delay => Check_Bad_Layout; Append_To (Statement_List, P_Delay_Statement); Statement_Required := False; -- Exit_Statement when Tok_Exit => Check_Bad_Layout; Append_To (Statement_List, P_Exit_Statement); Statement_Required := False; -- Loop_Statement with FOR and no label when Tok_For => Check_Bad_Layout; Append_To (Statement_List, P_For_Statement); Statement_Required := False; -- Goto_Statement when Tok_Goto => Check_Bad_Layout; Append_To (Statement_List, P_Goto_Statement); Statement_Required := False; -- If_Statement when Tok_If => Check_Bad_Layout; Append_To (Statement_List, P_If_Statement); Statement_Required := False; -- Loop_Statement when Tok_Loop => Check_Bad_Layout; Append_To (Statement_List, P_Loop_Statement); Statement_Required := False; -- Null_Statement when Tok_Null => Check_Bad_Layout; Append_To (Statement_List, P_Null_Statement); Statement_Required := False; -- Raise_Statement when Tok_Raise => Check_Bad_Layout; Append_To (Statement_List, P_Raise_Statement); Statement_Required := False; -- Requeue_Statement when Tok_Requeue => Check_Bad_Layout; Append_To (Statement_List, P_Requeue_Statement); Statement_Required := False; -- Return_Statement when Tok_Return => Check_Bad_Layout; Append_To (Statement_List, P_Return_Statement); Statement_Required := False; -- Select_Statement when Tok_Select => Check_Bad_Layout; Append_To (Statement_List, P_Select_Statement); Statement_Required := False; -- While_Statement (Block_Statement with while and no loop) when Tok_While => Check_Bad_Layout; Append_To (Statement_List, P_While_Statement); Statement_Required := False; -- Anything else is some kind of junk, signal an error message -- and then raise Error_Resync, to merge with the normal -- handling of a bad statement. when others => if Token in Token_Class_Declk then Junk_Declaration; else Error_Msg_BC -- CODEFIX ("statement expected"); raise Error_Resync; end if; end case; -- On error resynchronization, skip past next semicolon, and, since -- we are still in the statement loop, look for next statement. We -- set Statement_Required False to avoid an unnecessary error message -- complaining that no statement was found (i.e. we consider the -- junk to satisfy the requirement for a statement being present). exception when Error_Resync => Resync_Past_Semicolon_Or_To_Loop_Or_Then; Statement_Required := False; end; exit when SS_Flags.Unco; end loop; return Statement_List; end P_Sequence_Of_Statements; -------------------- -- 5.1 Statement -- -------------------- --------------------------- -- 5.1 Simple Statement -- --------------------------- -- Parsed by P_Sequence_Of_Statements (5.1) ----------------------------- -- 5.1 Compound Statement -- ----------------------------- -- Parsed by P_Sequence_Of_Statements (5.1) ------------------------- -- 5.1 Null Statement -- ------------------------- -- NULL_STATEMENT ::= null; -- The caller has already checked that the current token is null -- Error recovery: cannot raise Error_Resync function P_Null_Statement return Node_Id is Null_Stmt_Node : Node_Id; begin Null_Stmt_Node := New_Node (N_Null_Statement, Token_Ptr); Scan; -- past NULL TF_Semicolon; return Null_Stmt_Node; end P_Null_Statement; ---------------- -- 5.1 Label -- ---------------- -- LABEL ::= <<label_STATEMENT_IDENTIFIER>> -- STATEMENT_IDENTIFIER ::= DIRECT_NAME -- The IDENTIFIER of a STATEMENT_IDENTIFIER shall be an identifier -- (not an OPERATOR_SYMBOL) -- The caller has already checked that the current token is << -- Error recovery: can raise Error_Resync function P_Label return Node_Id is Label_Node : Node_Id; begin Label_Node := New_Node (N_Label, Token_Ptr); Scan; -- past << Set_Identifier (Label_Node, P_Identifier (C_Greater_Greater)); T_Greater_Greater; Append_Elmt (Label_Node, Label_List); return Label_Node; end P_Label; ------------------------------- -- 5.1 Statement Identifier -- ------------------------------- -- Statement label is parsed by P_Label (5.1) -- Loop label is parsed by P_Loop_Statement (5.5), P_For_Statement (5.5) -- or P_While_Statement (5.5) -- Block label is parsed by P_Begin_Statement (5.6) or -- P_Declare_Statement (5.6) ------------------------------- -- 5.2 Assignment Statement -- ------------------------------- -- ASSIGNMENT_STATEMENT ::= -- variable_NAME := EXPRESSION; -- Error recovery: can raise Error_Resync function P_Assignment_Statement (LHS : Node_Id) return Node_Id is Assign_Node : Node_Id; begin Assign_Node := New_Node (N_Assignment_Statement, Prev_Token_Ptr); Set_Name (Assign_Node, LHS); Set_Expression (Assign_Node, P_Expression_No_Right_Paren); TF_Semicolon; return Assign_Node; end P_Assignment_Statement; ----------------------- -- 5.3 If Statement -- ----------------------- -- IF_STATEMENT ::= -- if CONDITION then -- SEQUENCE_OF_STATEMENTS -- {elsif CONDITION then -- SEQUENCE_OF_STATEMENTS} -- [else -- SEQUENCE_OF_STATEMENTS] -- end if; -- The caller has checked that the initial token is IF (or in the error -- case of a mysterious THEN, the initial token may simply be THEN, in -- which case, no condition (or IF) was scanned). -- Error recovery: can raise Error_Resync function P_If_Statement return Node_Id is If_Node : Node_Id; Elsif_Node : Node_Id; Loc : Source_Ptr; procedure Add_Elsif_Part; -- An internal procedure used to scan out a single ELSIF part. On entry -- the ELSIF (or an ELSE which has been determined should be ELSIF) is -- scanned out and is in Prev_Token. procedure Check_If_Column; -- An internal procedure used to check that THEN, ELSE, or ELSIF -- appear in the right place if column checking is enabled (i.e. if -- they are the first token on the line, then they must appear in -- the same column as the opening IF). procedure Check_Then_Column; -- This procedure carries out the style checks for a THEN token -- Note that the caller has set Loc to the Source_Ptr value for -- the previous IF or ELSIF token. function Else_Should_Be_Elsif return Boolean; -- An internal routine used to do a special error recovery check when -- an ELSE is encountered. It determines if the ELSE should be treated -- as an ELSIF. A positive decision (TRUE returned, is made if the ELSE -- is followed by a sequence of tokens, starting on the same line as -- the ELSE, which are not expression terminators, followed by a THEN. -- On entry, the ELSE has been scanned out. procedure Add_Elsif_Part is begin if No (Elsif_Parts (If_Node)) then Set_Elsif_Parts (If_Node, New_List); end if; Elsif_Node := New_Node (N_Elsif_Part, Prev_Token_Ptr); Loc := Prev_Token_Ptr; Set_Condition (Elsif_Node, P_Condition); Check_Then_Column; Then_Scan; Set_Then_Statements (Elsif_Node, P_Sequence_Of_Statements (SS_Eftm_Eltm_Sreq)); Append (Elsif_Node, Elsif_Parts (If_Node)); end Add_Elsif_Part; procedure Check_If_Column is begin if RM_Column_Check and then Token_Is_At_Start_Of_Line and then Start_Column /= Scope.Table (Scope.Last).Ecol then Error_Msg_Col := Scope.Table (Scope.Last).Ecol; Error_Msg_SC ("(style) this token should be@"); end if; end Check_If_Column; procedure Check_Then_Column is begin if Token = Tok_Then then Check_If_Column; if Style_Check then Style.Check_Then (Loc); end if; end if; end Check_Then_Column; function Else_Should_Be_Elsif return Boolean is Scan_State : Saved_Scan_State; begin if Token_Is_At_Start_Of_Line then return False; else Save_Scan_State (Scan_State); loop if Token in Token_Class_Eterm then Restore_Scan_State (Scan_State); return False; else Scan; -- past non-expression terminating token if Token = Tok_Then then Restore_Scan_State (Scan_State); return True; end if; end if; end loop; end if; end Else_Should_Be_Elsif; -- Start of processing for P_If_Statement begin If_Node := New_Node (N_If_Statement, Token_Ptr); Push_Scope_Stack; Scope.Table (Scope.Last).Etyp := E_If; Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scope.Table (Scope.Last).Labl := Error; Scope.Table (Scope.Last).Node := If_Node; if Token = Tok_If then Loc := Token_Ptr; Scan; -- past IF Set_Condition (If_Node, P_Condition); -- Deal with misuse of IF expression => used instead -- of WHEN expression => if Token = Tok_Arrow then Error_Msg_SC -- CODEFIX ("THEN expected"); Scan; -- past the arrow Pop_Scope_Stack; -- remove unneeded entry raise Error_Resync; end if; Check_Then_Column; else Error_Msg_SC ("no IF for this THEN"); Set_Condition (If_Node, Error); end if; Then_Scan; Set_Then_Statements (If_Node, P_Sequence_Of_Statements (SS_Eftm_Eltm_Sreq)); -- This loop scans out else and elsif parts loop if Token = Tok_Elsif then Check_If_Column; if Present (Else_Statements (If_Node)) then Error_Msg_SP ("ELSIF cannot appear after ELSE"); end if; Scan; -- past ELSIF Add_Elsif_Part; elsif Token = Tok_Else then Check_If_Column; Scan; -- past ELSE if Else_Should_Be_Elsif then Error_Msg_SP -- CODEFIX ("ELSE should be ELSIF"); Add_Elsif_Part; else -- Here we have an else that really is an else if Present (Else_Statements (If_Node)) then Error_Msg_SP ("only one ELSE part allowed"); Append_List (P_Sequence_Of_Statements (SS_Eftm_Eltm_Sreq), Else_Statements (If_Node)); else Set_Else_Statements (If_Node, P_Sequence_Of_Statements (SS_Eftm_Eltm_Sreq)); end if; end if; -- If anything other than ELSE or ELSIF, exit the loop. The token -- had better be END (and in fact it had better be END IF), but -- we will let End_Statements take care of checking that. else exit; end if; end loop; End_Statements; return If_Node; end P_If_Statement; -------------------- -- 5.3 Condition -- -------------------- -- CONDITION ::= boolean_EXPRESSION function P_Condition return Node_Id is begin return P_Condition (P_Expression_No_Right_Paren); end P_Condition; function P_Condition (Cond : Node_Id) return Node_Id is begin -- It is never possible for := to follow a condition, so if we get -- a := we assume it is a mistyped equality. Note that we do not try -- to reconstruct the tree correctly in this case, but we do at least -- give an accurate error message. if Token = Tok_Colon_Equal then while Token = Tok_Colon_Equal loop Error_Msg_SC -- CODEFIX (""":="" should be ""="""); Scan; -- past junk := Discard_Junk_Node (P_Expression_No_Right_Paren); end loop; return Cond; -- Otherwise check for redundant parentheses -- If the condition is a conditional or a quantified expression, it is -- parenthesized in the context of a condition, because of a separate -- syntax rule. else if Style_Check and then Paren_Count (Cond) > 0 then if not Nkind_In (Cond, N_If_Expression, N_Case_Expression, N_Quantified_Expression) or else Paren_Count (Cond) > 1 then Style.Check_Xtra_Parens (First_Sloc (Cond)); end if; end if; -- And return the result return Cond; end if; end P_Condition; ------------------------- -- 5.4 Case Statement -- ------------------------- -- CASE_STATEMENT ::= -- case EXPRESSION is -- CASE_STATEMENT_ALTERNATIVE -- {CASE_STATEMENT_ALTERNATIVE} -- end case; -- The caller has checked that the first token is CASE -- Can raise Error_Resync function P_Case_Statement return Node_Id is Case_Node : Node_Id; Alternatives_List : List_Id; First_When_Loc : Source_Ptr; begin Case_Node := New_Node (N_Case_Statement, Token_Ptr); Push_Scope_Stack; Scope.Table (Scope.Last).Etyp := E_Case; Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scope.Table (Scope.Last).Labl := Error; Scope.Table (Scope.Last).Node := Case_Node; Scan; -- past CASE Set_Expression (Case_Node, P_Expression_No_Right_Paren); TF_Is; -- Prepare to parse case statement alternatives Alternatives_List := New_List; P_Pragmas_Opt (Alternatives_List); First_When_Loc := Token_Ptr; -- Loop through case statement alternatives loop -- If we have a WHEN or OTHERS, then that's fine keep going. Note -- that it is a semantic check to ensure the proper use of OTHERS if Token = Tok_When or else Token = Tok_Others then Append (P_Case_Statement_Alternative, Alternatives_List); -- If we have an END, then probably we are at the end of the case -- but we only exit if Check_End thinks the END was reasonable. elsif Token = Tok_End then exit when Check_End; -- Here if token is other than WHEN, OTHERS or END. We definitely -- have an error, but the question is whether or not to get out of -- the case statement. We don't want to get out early, or we will -- get a slew of junk error messages for subsequent when tokens. -- If the token is not at the start of the line, or if it is indented -- with respect to the current case statement, then the best guess is -- that we are still supposed to be inside the case statement. We -- complain about the missing WHEN, and discard the junk statements. elsif not Token_Is_At_Start_Of_Line or else Start_Column > Scope.Table (Scope.Last).Ecol then Error_Msg_BC ("WHEN (case statement alternative) expected"); -- Here is a possibility for infinite looping if we don't make -- progress. So try to process statements, otherwise exit declare Error_Ptr : constant Source_Ptr := Scan_Ptr; begin Discard_Junk_List (P_Sequence_Of_Statements (SS_Whtm)); exit when Scan_Ptr = Error_Ptr and then Check_End; end; -- Here we have a junk token at the start of the line and it is -- not indented. If Check_End thinks there is a missing END, then -- we will get out of the case, otherwise we keep going. else exit when Check_End; end if; end loop; -- Make sure we have at least one alternative if No (First_Non_Pragma (Alternatives_List)) then Error_Msg ("WHEN expected, must have at least one alternative in case", First_When_Loc); return Error; else Set_Alternatives (Case_Node, Alternatives_List); return Case_Node; end if; end P_Case_Statement; ------------------------------------- -- 5.4 Case Statement Alternative -- ------------------------------------- -- CASE_STATEMENT_ALTERNATIVE ::= -- when DISCRETE_CHOICE_LIST => -- SEQUENCE_OF_STATEMENTS -- The caller has checked that the initial token is WHEN or OTHERS -- Error recovery: can raise Error_Resync function P_Case_Statement_Alternative return Node_Id is Case_Alt_Node : Node_Id; begin if Style_Check then Style.Check_Indentation; end if; Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Token_Ptr); T_When; -- past WHEN (or give error in OTHERS case) Set_Discrete_Choices (Case_Alt_Node, P_Discrete_Choice_List); TF_Arrow; Set_Statements (Case_Alt_Node, P_Sequence_Of_Statements (SS_Sreq_Whtm)); return Case_Alt_Node; end P_Case_Statement_Alternative; ------------------------- -- 5.5 Loop Statement -- ------------------------- -- LOOP_STATEMENT ::= -- [LOOP_STATEMENT_IDENTIFIER:] -- [ITERATION_SCHEME] loop -- SEQUENCE_OF_STATEMENTS -- end loop [loop_IDENTIFIER]; -- ITERATION_SCHEME ::= -- while CONDITION -- | for LOOP_PARAMETER_SPECIFICATION -- The parsing of loop statements is handled by one of three functions -- P_Loop_Statement, P_For_Statement or P_While_Statement depending -- on the initial keyword in the construct (excluding the identifier) -- P_Loop_Statement -- This function parses the case where no iteration scheme is present -- The caller has checked that the initial token is LOOP. The parameter -- is the node identifiers for the loop label if any (or is set to Empty -- if there is no loop label). -- Error recovery : cannot raise Error_Resync function P_Loop_Statement (Loop_Name : Node_Id := Empty) return Node_Id is Loop_Node : Node_Id; Created_Name : Node_Id; begin Push_Scope_Stack; Scope.Table (Scope.Last).Labl := Loop_Name; Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scope.Table (Scope.Last).Etyp := E_Loop; Loop_Node := New_Node (N_Loop_Statement, Token_Ptr); TF_Loop; if No (Loop_Name) then Created_Name := Make_Identifier (Sloc (Loop_Node), Set_Loop_Block_Name ('L')); Set_Comes_From_Source (Created_Name, False); Set_Has_Created_Identifier (Loop_Node, True); Set_Identifier (Loop_Node, Created_Name); Scope.Table (Scope.Last).Labl := Created_Name; else Set_Identifier (Loop_Node, Loop_Name); end if; Append_Elmt (Loop_Node, Label_List); Set_Statements (Loop_Node, P_Sequence_Of_Statements (SS_Sreq)); End_Statements (Loop_Node); return Loop_Node; end P_Loop_Statement; -- P_For_Statement -- This function parses a loop statement with a FOR iteration scheme -- The caller has checked that the initial token is FOR. The parameter -- is the node identifier for the block label if any (or is set to Empty -- if there is no block label). -- Note: the caller fills in the Identifier field if a label was present -- Error recovery: can raise Error_Resync function P_For_Statement (Loop_Name : Node_Id := Empty) return Node_Id is Loop_Node : Node_Id; Iter_Scheme_Node : Node_Id; Loop_For_Flag : Boolean; Created_Name : Node_Id; Spec : Node_Id; begin Push_Scope_Stack; Scope.Table (Scope.Last).Labl := Loop_Name; Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scope.Table (Scope.Last).Etyp := E_Loop; Loop_For_Flag := (Prev_Token = Tok_Loop); Scan; -- past FOR Iter_Scheme_Node := New_Node (N_Iteration_Scheme, Token_Ptr); Spec := P_Loop_Parameter_Specification; if Nkind (Spec) = N_Loop_Parameter_Specification then Set_Loop_Parameter_Specification (Iter_Scheme_Node, Spec); else Set_Iterator_Specification (Iter_Scheme_Node, Spec); end if; -- The following is a special test so that a miswritten for loop such -- as "loop for I in 1..10;" is handled nicely, without making an extra -- entry in the scope stack. We don't bother to actually fix up the -- tree in this case since it's not worth the effort. Instead we just -- eat up the loop junk, leaving the entry for what now looks like an -- unmodified loop intact. if Loop_For_Flag and then Token = Tok_Semicolon then Error_Msg_SC ("LOOP belongs here, not before FOR"); Pop_Scope_Stack; return Error; -- Normal case else Loop_Node := New_Node (N_Loop_Statement, Token_Ptr); if No (Loop_Name) then Created_Name := Make_Identifier (Sloc (Loop_Node), Set_Loop_Block_Name ('L')); Set_Comes_From_Source (Created_Name, False); Set_Has_Created_Identifier (Loop_Node, True); Set_Identifier (Loop_Node, Created_Name); Scope.Table (Scope.Last).Labl := Created_Name; else Set_Identifier (Loop_Node, Loop_Name); end if; TF_Loop; Set_Statements (Loop_Node, P_Sequence_Of_Statements (SS_Sreq)); End_Statements (Loop_Node); Set_Iteration_Scheme (Loop_Node, Iter_Scheme_Node); Append_Elmt (Loop_Node, Label_List); return Loop_Node; end if; end P_For_Statement; -- P_While_Statement -- This procedure scans a loop statement with a WHILE iteration scheme -- The caller has checked that the initial token is WHILE. The parameter -- is the node identifier for the block label if any (or is set to Empty -- if there is no block label). -- Error recovery: cannot raise Error_Resync function P_While_Statement (Loop_Name : Node_Id := Empty) return Node_Id is Loop_Node : Node_Id; Iter_Scheme_Node : Node_Id; Loop_While_Flag : Boolean; Created_Name : Node_Id; begin Push_Scope_Stack; Scope.Table (Scope.Last).Labl := Loop_Name; Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scope.Table (Scope.Last).Etyp := E_Loop; Loop_While_Flag := (Prev_Token = Tok_Loop); Iter_Scheme_Node := New_Node (N_Iteration_Scheme, Token_Ptr); Scan; -- past WHILE Set_Condition (Iter_Scheme_Node, P_Condition); -- The following is a special test so that a miswritten for loop such -- as "loop while I > 10;" is handled nicely, without making an extra -- entry in the scope stack. We don't bother to actually fix up the -- tree in this case since it's not worth the effort. Instead we just -- eat up the loop junk, leaving the entry for what now looks like an -- unmodified loop intact. if Loop_While_Flag and then Token = Tok_Semicolon then Error_Msg_SC ("LOOP belongs here, not before WHILE"); Pop_Scope_Stack; return Error; -- Normal case else Loop_Node := New_Node (N_Loop_Statement, Token_Ptr); TF_Loop; if No (Loop_Name) then Created_Name := Make_Identifier (Sloc (Loop_Node), Set_Loop_Block_Name ('L')); Set_Comes_From_Source (Created_Name, False); Set_Has_Created_Identifier (Loop_Node, True); Set_Identifier (Loop_Node, Created_Name); Scope.Table (Scope.Last).Labl := Created_Name; else Set_Identifier (Loop_Node, Loop_Name); end if; Set_Statements (Loop_Node, P_Sequence_Of_Statements (SS_Sreq)); End_Statements (Loop_Node); Set_Iteration_Scheme (Loop_Node, Iter_Scheme_Node); Append_Elmt (Loop_Node, Label_List); return Loop_Node; end if; end P_While_Statement; --------------------------------------- -- 5.5 Loop Parameter Specification -- --------------------------------------- -- LOOP_PARAMETER_SPECIFICATION ::= -- DEFINING_IDENTIFIER in [reverse] DISCRETE_SUBTYPE_DEFINITION -- Error recovery: cannot raise Error_Resync function P_Loop_Parameter_Specification return Node_Id is Loop_Param_Specification_Node : Node_Id; ID_Node : Node_Id; Scan_State : Saved_Scan_State; begin Save_Scan_State (Scan_State); ID_Node := P_Defining_Identifier (C_In); -- If the next token is OF, it indicates an Ada 2012 iterator. If the -- next token is a colon, this is also an Ada 2012 iterator, including -- a subtype indication for the loop parameter. Otherwise we parse the -- construct as a loop parameter specification. Note that the form -- "for A in B" is ambiguous, and must be resolved semantically: if B -- is a discrete subtype this is a loop specification, but if it is an -- expression it is an iterator specification. Ambiguity is resolved -- during analysis of the loop parameter specification. if Token = Tok_Of or else Token = Tok_Colon then Error_Msg_Ada_2012_Feature ("iterator", Token_Ptr); return P_Iterator_Specification (ID_Node); end if; -- The span of the Loop_Parameter_Specification starts at the -- defining identifier. Loop_Param_Specification_Node := New_Node (N_Loop_Parameter_Specification, Sloc (ID_Node)); Set_Defining_Identifier (Loop_Param_Specification_Node, ID_Node); if Token = Tok_Left_Paren then Error_Msg_SC ("subscripted loop parameter not allowed"); Restore_Scan_State (Scan_State); Discard_Junk_Node (P_Name); elsif Token = Tok_Dot then Error_Msg_SC ("selected loop parameter not allowed"); Restore_Scan_State (Scan_State); Discard_Junk_Node (P_Name); end if; T_In; if Token = Tok_Reverse then Scan; -- past REVERSE Set_Reverse_Present (Loop_Param_Specification_Node, True); end if; Set_Discrete_Subtype_Definition (Loop_Param_Specification_Node, P_Discrete_Subtype_Definition); return Loop_Param_Specification_Node; exception when Error_Resync => return Error; end P_Loop_Parameter_Specification; ---------------------------------- -- 5.5.1 Iterator_Specification -- ---------------------------------- function P_Iterator_Specification (Def_Id : Node_Id) return Node_Id is Node1 : Node_Id; begin Node1 := New_Node (N_Iterator_Specification, Sloc (Def_Id)); Set_Defining_Identifier (Node1, Def_Id); if Token = Tok_Colon then Scan; -- past : Set_Subtype_Indication (Node1, P_Subtype_Indication); end if; if Token = Tok_Of then Set_Of_Present (Node1); Scan; -- past OF elsif Token = Tok_In then Scan; -- past IN elsif Prev_Token = Tok_In and then Present (Subtype_Indication (Node1)) then -- Simplest recovery is to transform it into an element iterator. -- Error message on 'in" has already been emitted when parsing the -- optional constraint. Set_Of_Present (Node1); Error_Msg_N ("subtype indication is only legal on an element iterator", Subtype_Indication (Node1)); else return Error; end if; if Token = Tok_Reverse then Scan; -- past REVERSE Set_Reverse_Present (Node1, True); end if; Set_Name (Node1, P_Name); return Node1; end P_Iterator_Specification; -------------------------- -- 5.6 Block Statement -- -------------------------- -- BLOCK_STATEMENT ::= -- [block_STATEMENT_IDENTIFIER:] -- [declare -- DECLARATIVE_PART] -- begin -- HANDLED_SEQUENCE_OF_STATEMENTS -- end [block_IDENTIFIER]; -- The parsing of block statements is handled by one of the two functions -- P_Declare_Statement or P_Begin_Statement depending on whether or not -- a declare section is present -- P_Declare_Statement -- This function parses a block statement with DECLARE present -- The caller has checked that the initial token is DECLARE -- Error recovery: cannot raise Error_Resync function P_Declare_Statement (Block_Name : Node_Id := Empty) return Node_Id is Block_Node : Node_Id; Created_Name : Node_Id; begin Block_Node := New_Node (N_Block_Statement, Token_Ptr); Push_Scope_Stack; Scope.Table (Scope.Last).Etyp := E_Name; Scope.Table (Scope.Last).Lreq := Present (Block_Name); Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Labl := Block_Name; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scan; -- past DECLARE if No (Block_Name) then Created_Name := Make_Identifier (Sloc (Block_Node), Set_Loop_Block_Name ('B')); Set_Comes_From_Source (Created_Name, False); Set_Has_Created_Identifier (Block_Node, True); Set_Identifier (Block_Node, Created_Name); Scope.Table (Scope.Last).Labl := Created_Name; else Set_Identifier (Block_Node, Block_Name); end if; Append_Elmt (Block_Node, Label_List); Parse_Decls_Begin_End (Block_Node); return Block_Node; end P_Declare_Statement; -- P_Begin_Statement -- This function parses a block statement with no DECLARE present -- The caller has checked that the initial token is BEGIN -- Error recovery: cannot raise Error_Resync function P_Begin_Statement (Block_Name : Node_Id := Empty) return Node_Id is Block_Node : Node_Id; Created_Name : Node_Id; begin Block_Node := New_Node (N_Block_Statement, Token_Ptr); Push_Scope_Stack; Scope.Table (Scope.Last).Etyp := E_Name; Scope.Table (Scope.Last).Lreq := Present (Block_Name); Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Labl := Block_Name; Scope.Table (Scope.Last).Sloc := Token_Ptr; if No (Block_Name) then Created_Name := Make_Identifier (Sloc (Block_Node), Set_Loop_Block_Name ('B')); Set_Comes_From_Source (Created_Name, False); Set_Has_Created_Identifier (Block_Node, True); Set_Identifier (Block_Node, Created_Name); Scope.Table (Scope.Last).Labl := Created_Name; else Set_Identifier (Block_Node, Block_Name); end if; Append_Elmt (Block_Node, Label_List); Scope.Table (Scope.Last).Ecol := Start_Column; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scan; -- past BEGIN Set_Handled_Statement_Sequence (Block_Node, P_Handled_Sequence_Of_Statements); End_Statements (Handled_Statement_Sequence (Block_Node)); return Block_Node; end P_Begin_Statement; ------------------------- -- 5.7 Exit Statement -- ------------------------- -- EXIT_STATEMENT ::= -- exit [loop_NAME] [when CONDITION]; -- The caller has checked that the initial token is EXIT -- Error recovery: can raise Error_Resync function P_Exit_Statement return Node_Id is Exit_Node : Node_Id; function Missing_Semicolon_On_Exit return Boolean; -- This function deals with the following specialized situation -- -- when 'x' => -- exit [identifier] -- when 'y' => -- -- This looks like a messed up EXIT WHEN, when in fact the problem -- is a missing semicolon. It is called with Token pointing to the -- WHEN token, and returns True if a semicolon is missing before -- the WHEN as in the above example. ------------------------------- -- Missing_Semicolon_On_Exit -- ------------------------------- function Missing_Semicolon_On_Exit return Boolean is State : Saved_Scan_State; begin if not Token_Is_At_Start_Of_Line then return False; elsif Scope.Table (Scope.Last).Etyp /= E_Case then return False; else Save_Scan_State (State); Scan; -- past WHEN Scan; -- past token after WHEN if Token = Tok_Arrow then Restore_Scan_State (State); return True; else Restore_Scan_State (State); return False; end if; end if; end Missing_Semicolon_On_Exit; -- Start of processing for P_Exit_Statement begin Exit_Node := New_Node (N_Exit_Statement, Token_Ptr); Scan; -- past EXIT if Token = Tok_Identifier then Set_Name (Exit_Node, P_Qualified_Simple_Name); elsif Style_Check then -- This EXIT has no name, so check that -- the innermost loop is unnamed too. Check_No_Exit_Name : for J in reverse 1 .. Scope.Last loop if Scope.Table (J).Etyp = E_Loop then if Present (Scope.Table (J).Labl) and then Comes_From_Source (Scope.Table (J).Labl) then -- Innermost loop in fact had a name, style check fails Style.No_Exit_Name (Scope.Table (J).Labl); end if; exit Check_No_Exit_Name; end if; end loop Check_No_Exit_Name; end if; if Token = Tok_When and then not Missing_Semicolon_On_Exit then Scan; -- past WHEN Set_Condition (Exit_Node, P_Condition); -- Allow IF instead of WHEN, giving error message elsif Token = Tok_If then T_When; Scan; -- past IF used in place of WHEN Set_Condition (Exit_Node, P_Expression_No_Right_Paren); end if; TF_Semicolon; return Exit_Node; end P_Exit_Statement; ------------------------- -- 5.8 Goto Statement -- ------------------------- -- GOTO_STATEMENT ::= goto label_NAME; -- The caller has checked that the initial token is GOTO (or TO in the -- error case where GO and TO were incorrectly separated). -- Error recovery: can raise Error_Resync function P_Goto_Statement return Node_Id is Goto_Node : Node_Id; begin Goto_Node := New_Node (N_Goto_Statement, Token_Ptr); Scan; -- past GOTO (or TO) Set_Name (Goto_Node, P_Qualified_Simple_Name_Resync); Append_Elmt (Goto_Node, Goto_List); No_Constraint; TF_Semicolon; return Goto_Node; end P_Goto_Statement; --------------------------- -- Parse_Decls_Begin_End -- --------------------------- -- This function parses the construct: -- DECLARATIVE_PART -- begin -- HANDLED_SEQUENCE_OF_STATEMENTS -- end [NAME]; -- The caller has built the scope stack entry, and created the node to -- whose Declarations and Handled_Statement_Sequence fields are to be -- set. On return these fields are filled in (except in the case of a -- task body, where the handled statement sequence is optional, and may -- thus be Empty), and the scan is positioned past the End sequence. -- If the BEGIN is missing, then the parent node is used to help construct -- an appropriate missing BEGIN message. Possibilities for the parent are: -- N_Block_Statement declare block -- N_Entry_Body entry body -- N_Package_Body package body (begin part optional) -- N_Subprogram_Body procedure or function body -- N_Task_Body task body -- Note: in the case of a block statement, there is definitely a DECLARE -- present (because a Begin statement without a DECLARE is handled by the -- P_Begin_Statement procedure, which does not call Parse_Decls_Begin_End. -- Error recovery: cannot raise Error_Resync procedure Parse_Decls_Begin_End (Parent : Node_Id) is Body_Decl : Node_Id; Decls : List_Id; Parent_Nkind : Node_Kind; Spec_Node : Node_Id; HSS : Node_Id; procedure Missing_Begin (Msg : String); -- Called to post a missing begin message. In the normal case this is -- posted at the start of the current token. A special case arises when -- P_Declarative_Items has previously found a missing begin, in which -- case we replace the original error message. procedure Set_Null_HSS (Parent : Node_Id); -- Construct an empty handled statement sequence and install in Parent -- Leaves HSS set to reference the newly constructed statement sequence. ------------------- -- Missing_Begin -- ------------------- procedure Missing_Begin (Msg : String) is begin if Missing_Begin_Msg = No_Error_Msg then Error_Msg_BC (Msg); else Change_Error_Text (Missing_Begin_Msg, Msg); -- Purge any messages issued after than, since a missing begin -- can cause a lot of havoc, and it is better not to dump these -- cascaded messages on the user. Purge_Messages (Get_Location (Missing_Begin_Msg), Prev_Token_Ptr); end if; end Missing_Begin; ------------------ -- Set_Null_HSS -- ------------------ procedure Set_Null_HSS (Parent : Node_Id) is Null_Stm : Node_Id; begin Null_Stm := Make_Null_Statement (Token_Ptr); Set_Comes_From_Source (Null_Stm, False); HSS := Make_Handled_Sequence_Of_Statements (Token_Ptr, Statements => New_List (Null_Stm)); Set_Comes_From_Source (HSS, False); Set_Handled_Statement_Sequence (Parent, HSS); end Set_Null_HSS; -- Start of processing for Parse_Decls_Begin_End begin Decls := P_Declarative_Part; if Ada_Version = Ada_83 then Check_Later_Vs_Basic_Declarations (Decls, During_Parsing => True); end if; -- Here is where we deal with the case of IS used instead of semicolon. -- Specifically, if the last declaration in the declarative part is a -- subprogram body still marked as having a bad IS, then this is where -- we decide that the IS should really have been a semicolon and that -- the body should have been a declaration. Note that if the bad IS -- had turned out to be OK (i.e. a decent begin/end was found for it), -- then the Bad_Is_Detected flag would have been reset by now. Body_Decl := Last (Decls); if Present (Body_Decl) and then Nkind (Body_Decl) = N_Subprogram_Body and then Bad_Is_Detected (Body_Decl) then -- OK, we have the case of a bad IS, so we need to fix up the tree. -- What we have now is a subprogram body with attached declarations -- and a possible statement sequence. -- First step is to take the declarations that were part of the bogus -- subprogram body and append them to the outer declaration chain. -- In other words we append them past the body (which we will later -- convert into a declaration). Append_List (Declarations (Body_Decl), Decls); -- Now take the handled statement sequence of the bogus body and -- set it as the statement sequence for the outer construct. Note -- that it may be empty (we specially allowed a missing BEGIN for -- a subprogram body marked as having a bad IS -- see below). Set_Handled_Statement_Sequence (Parent, Handled_Statement_Sequence (Body_Decl)); -- Next step is to convert the old body node to a declaration node Spec_Node := Specification (Body_Decl); Change_Node (Body_Decl, N_Subprogram_Declaration); Set_Specification (Body_Decl, Spec_Node); -- Final step is to put the declarations for the parent where -- they belong, and then fall through the IF to scan out the -- END statements. Set_Declarations (Parent, Decls); -- This is the normal case (i.e. any case except the bad IS case) -- If we have a BEGIN, then scan out the sequence of statements, and -- also reset the expected column for the END to match the BEGIN. else Set_Declarations (Parent, Decls); if Token = Tok_Begin then if Style_Check then Style.Check_Indentation; end if; Error_Msg_Col := Scope.Table (Scope.Last).Ecol; if RM_Column_Check and then Token_Is_At_Start_Of_Line and then Start_Column /= Error_Msg_Col then Error_Msg_SC ("(style) BEGIN in wrong column, should be@"); else Scope.Table (Scope.Last).Ecol := Start_Column; end if; Scope.Table (Scope.Last).Sloc := Token_Ptr; Scan; -- past BEGIN Set_Handled_Statement_Sequence (Parent, P_Handled_Sequence_Of_Statements); -- No BEGIN present else Parent_Nkind := Nkind (Parent); -- A special check for the missing IS case. If we have a -- subprogram body that was marked as having a suspicious -- IS, and the current token is END, then we simply confirm -- the suspicion, and do not require a BEGIN to be present if Parent_Nkind = N_Subprogram_Body and then Token = Tok_End and then Scope.Table (Scope.Last).Etyp = E_Suspicious_Is then Scope.Table (Scope.Last).Etyp := E_Bad_Is; -- Otherwise BEGIN is not required for a package body, so we -- don't mind if it is missing, but we do construct a dummy -- one (so that we have somewhere to set End_Label). -- However if we have something other than a BEGIN which -- looks like it might be statements, then we signal a missing -- BEGIN for these cases as well. We define "something which -- looks like it might be statements" as a token other than -- END, EOF, or a token which starts declarations. elsif Parent_Nkind = N_Package_Body and then (Token = Tok_End or else Token = Tok_EOF or else Token in Token_Class_Declk) then Set_Null_HSS (Parent); -- These are cases in which a BEGIN is required and not present else Set_Null_HSS (Parent); -- Prepare to issue error message Error_Msg_Sloc := Scope.Table (Scope.Last).Sloc; Error_Msg_Node_1 := Scope.Table (Scope.Last).Labl; -- Now issue appropriate message if Parent_Nkind = N_Block_Statement then Missing_Begin ("missing BEGIN for DECLARE#!"); elsif Parent_Nkind = N_Entry_Body then Missing_Begin ("missing BEGIN for ENTRY#!"); elsif Parent_Nkind = N_Subprogram_Body then if Nkind (Specification (Parent)) = N_Function_Specification then Missing_Begin ("missing BEGIN for function&#!"); else Missing_Begin ("missing BEGIN for procedure&#!"); end if; -- The case for package body arises only when -- we have possible statement junk present. elsif Parent_Nkind = N_Package_Body then Missing_Begin ("missing BEGIN for package body&#!"); else pragma Assert (Parent_Nkind = N_Task_Body); Missing_Begin ("missing BEGIN for task body&#!"); end if; -- Here we pick up the statements after the BEGIN that -- should have been present but was not. We don't insist -- on statements being present if P_Declarative_Part had -- already found a missing BEGIN, since it might have -- swallowed a lone statement into the declarative part. if Missing_Begin_Msg /= No_Error_Msg and then Token = Tok_End then null; else Set_Handled_Statement_Sequence (Parent, P_Handled_Sequence_Of_Statements); end if; end if; end if; end if; -- Here with declarations and handled statement sequence scanned if Present (Handled_Statement_Sequence (Parent)) then End_Statements (Handled_Statement_Sequence (Parent)); else End_Statements; end if; -- We know that End_Statements removed an entry from the scope stack -- (because it is required to do so under all circumstances). We can -- therefore reference the entry it removed one past the stack top. -- What we are interested in is whether it was a case of a bad IS. if Scope.Table (Scope.Last + 1).Etyp = E_Bad_Is then Error_Msg -- CODEFIX ("|IS should be "";""", Scope.Table (Scope.Last + 1).S_Is); Set_Bad_Is_Detected (Parent, True); end if; end Parse_Decls_Begin_End; ------------------------- -- Set_Loop_Block_Name -- ------------------------- function Set_Loop_Block_Name (L : Character) return Name_Id is begin Name_Buffer (1) := L; Name_Buffer (2) := '_'; Name_Len := 2; Loop_Block_Count := Loop_Block_Count + 1; Add_Nat_To_Name_Buffer (Loop_Block_Count); return Name_Find; end Set_Loop_Block_Name; --------------- -- Then_Scan -- --------------- procedure Then_Scan is begin TF_Then; while Token = Tok_Then loop Error_Msg_SC -- CODEFIX ("redundant THEN"); TF_Then; end loop; if Token = Tok_And or else Token = Tok_Or then Error_Msg_SC ("unexpected logical operator"); Scan; -- past logical operator if (Prev_Token = Tok_And and then Token = Tok_Then) or else (Prev_Token = Tok_Or and then Token = Tok_Else) then Scan; end if; Discard_Junk_Node (P_Expression); end if; if Token = Tok_Then then Scan; end if; end Then_Scan; end Ch5;
with Ada.Text_IO; with String_Int; procedure Euler13 is Num_Addends: constant Positive := 100; Addend_Size: constant Positive := 50; use type String_Int.Number; Result: String_Int.Number(1 .. Addend_Size + Num_Addends) := (others => '0'); Len: Positive := Addend_Size; begin for I in Positive range 1 .. Num_Addends loop declare Sum: constant String_Int.Number := Result(1 .. Len) + String_Int.From_String(Ada.Text_IO.Get_Line); begin Len := Sum'Length; Result(1 .. Len) := Sum; end; end loop; Ada.Text_IO.Put_Line(String_Int.To_String(Result(1 .. 10))); end Euler13;
pragma License (Unrestricted); -- Ada 2012 generic type Index_Type is (<>); with function Before (Left, Right : Index_Type) return Boolean; with procedure Swap (Left, Right : Index_Type); procedure Ada.Containers.Generic_Sort (First, Last : Index_Type'Base); pragma Pure (Ada.Containers.Generic_Sort);
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- SQL Database Access -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with League.Calendars.ISO_8601; with League.Strings.Internals; with Matreshka.Internals.Utf16; with Matreshka.Internals.Strings.C; with Matreshka.Internals.SQL_Drivers.Oracle.Plug_In; package body Matreshka.Internals.SQL_Drivers.Oracle.Queries is use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_16; use type Interfaces.Integer_8; use type Sb2; use type SQL.Parameter_Directions; use type Plug_In.Control_Side; use type System.Storage_Elements.Storage_Count; procedure Free is new Ada.Unchecked_Deallocation (Bound_Value_Node, Bound_Value_Access); procedure Free is new Ada.Unchecked_Deallocation (Defined_Value_Array, Defined_Value_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (System.Storage_Elements.Storage_Array, Storage_Array_Access); type Utf16_Code_Unit_Access is access all Matreshka.Internals.Utf16.Utf16_Code_Unit; function OCICallbackInBind (ictxp : Bound_Value_Access; bindp : Oracle.Bind; iter : Ub4; index : Ub4; bufpp : access Utf16_Code_Unit_Access; alenp : access Ub4; piecep : access Ub1; indp : access Sb2_Ptr) return Error_Code; pragma Convention (C, OCICallbackInBind); function OCICallbackOutBind (octxp : Bound_Value_Access; bindp : Oracle.Bind; iter : Ub4; index : Ub4; bufpp : access Utf16_Code_Unit_Access; alenp : access Ub4_Ptr; piecep : access Ub1; indp : access Sb2_Ptr; rcodepp : access Sb2_Ptr) return Error_Code; pragma Convention (C, OCICallbackOutBind); function "+" (Left : Matreshka.Internals.Utf16.Utf16_String_Index; Right : Ub4) return Matreshka.Internals.Utf16.Utf16_String_Index; UTC_TZ : constant Wide_String := "+00:00"; --------- -- "+" -- --------- function "+" (Left : Matreshka.Internals.Utf16.Utf16_String_Index; Right : Ub4) return Matreshka.Internals.Utf16.Utf16_String_Index is use type Matreshka.Internals.Utf16.Utf16_String_Index; begin return Left + Matreshka.Internals.Utf16.Utf16_String_Index (Right) / 2; end "+"; ---------------- -- Bind_Value -- ---------------- overriding procedure Bind_Value (Self : not null access OCI_Query; Name : League.Strings.Universal_String; Value : League.Holders.Holder; Direction : SQL.Parameter_Directions) is Code : Error_Code; Pos : Parameter_Maps.Cursor; Ok : Boolean; procedure Bind (Name : League.Strings.Universal_String; Item : in out Bound_Value_Access); ---------- -- Bind -- ---------- procedure Bind (Name : League.Strings.Universal_String; Item : in out Bound_Value_Access) is Length : Ub4; Plugin : Plug_In_Access := Plug_In_Access (Self.DB.Plugins); Control : Plug_In.Control_Side := Plug_In.Driver; Extra_Type : Data_Type; Extra_Size : System.Storage_Elements.Storage_Count := 0; begin while Plugin /= null loop Plugin.Check_Parameter (Value, Control, Extra_Type, Extra_Size); exit when Control = Plug_In.Plug_In; Plugin := Plugin.Next; end loop; if Item /= null and then Item.Length < Extra_Size then Free (Item); end if; if Item = null then Item := new Bound_Value_Node (Extra_Size); end if; Item.Value := Value; Item.Direction := Direction; Item.Plugin := Plugin; Item.Extra_Type := Extra_Type; Item.Extra_Size := Extra_Size; if Item.Plugin /= null then Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Extra (1)'Address, Ub4 (Item.Extra_Size), Item.Extra_Type, Item.Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then Free (Item); return; -- How to report errors? end if; Item.Plugin.Encode (Value, Item.Extra (1 .. Item.Extra_Size)); elsif League.Holders.Is_Universal_String (Value) then Length := 64 * 1024; -- 64kbyte max length of out string param if Direction = SQL.In_Parameter then if League.Holders.Is_Empty (Value) then Length := 2; else Length := Ub4 (League.Strings.Internals.Internal (League.Holders.Element (Value)).Unused) * 2 + 2; end if; end if; Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Value_Length => Length, Value_Type => SQLT_STR, Mode => OCI_DATA_AT_EXEC); if Databases.Check_Error (Self.DB, Code) then Free (Item); return; -- How to report errors? end if; Code := OCIBindDynamic (Item.Bind, Self.DB.Error, Item.all'Address, OCICallbackInBind'Address, Item.all'Address, OCICallbackOutBind'Address); Item.String_Size := 0; elsif League.Holders.Is_Abstract_Integer (Value) then Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Int'Address, Item.Int'Size / 8, SQLT_INT, Item.Is_Null'Access); if not League.Holders.Is_Empty (Value) then Item.Int := League.Holders.Element (Value); end if; elsif League.Holders.Is_Abstract_Float (Value) then Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Float'Address, Item.Float'Size / 8, SQLT_FLT, Item.Is_Null'Access); if not League.Holders.Is_Empty (Value) then Item.Float := League.Holders.Element (Value); end if; elsif League.Holders.Is_Date (Value) then declare Aux : League.Calendars.Date; begin Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Date'Address, Item.Date'Size / 8, SQLT_ODT, Item.Is_Null'Access); if not League.Holders.Is_Empty (Value) then Aux := League.Holders.Element (Value); Item.Date := Utils.Encode_Date (Aux); end if; end; elsif League.Holders.Is_Date_Time (Value) then if Item.Timestamp = null then Code := OCIDescriptorAlloc (Databases.Env, Item.Timestamp'Access, OCI_DTYPE_TIMESTAMP_TZ); end if; Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Timestamp'Address, Item.Timestamp'Size / 8, SQLT_TIMESTAMP_TZ, Item.Is_Null'Access); if not League.Holders.Is_Empty (Value) then declare use type Size_T; Aux : constant League.Calendars.Date_Time := League.Holders.Element (Value); Year : League.Calendars.ISO_8601.Year_Number; Month : League.Calendars.ISO_8601.Month_Number; Day : League.Calendars.ISO_8601.Day_Number; Hour : League.Calendars.ISO_8601.Hour_Number; Minute : League.Calendars.ISO_8601.Minute_Number; Second : League.Calendars.ISO_8601.Second_Number; Fraction : League.Calendars.ISO_8601.Nanosecond_100_Number; begin League.Calendars.ISO_8601.Split (Aux, Year, Month, Day, Hour, Minute, Second, Fraction); Code := OCIDateTimeConstruct (Env => Databases.Env, Error => Self.DB.Error, Date => Item.Timestamp, Year => Sb2 (Year), Month => Ub1 (Month), Day => Ub1 (Day), Hour => Ub1 (Hour), Min => Ub1 (Minute), Sec => Ub1 (Second), Fract => Ub4 (Fraction) * 100, TZ => UTC_TZ (UTC_TZ'First)'Address, TZ_Len => UTC_TZ'Length * 2); end; end if; elsif League.Holders.Is_Empty (Value) then Code := OCIBindByName (Self.Handle, Item.Bind'Access, Self.DB.Error, League.Strings.Internals.Internal (Name).Value, Ub4 (League.Strings.Internals.Internal (Name).Unused) * 2, Item.Int'Address, Item.Int'Size / 8, SQLT_INT, Item.Is_Null'Access); else Free (Item); return; end if; if Databases.Check_Error (Self.DB, Code) then Free (Item); return; -- How to report errors? end if; Item.Is_Null := -Boolean'Pos (League.Holders.Is_Empty (Value) or Direction = SQL.Out_Parameter); end Bind; begin if Self.State = Prepared then Self.Parameters.Insert (Name, null, Pos, Ok); Self.Parameters.Update_Element (Pos, Bind'Access); end if; end Bind_Value; ----------------- -- Bound_Value -- ----------------- overriding function Bound_Value (Self : not null access OCI_Query; Name : League.Strings.Universal_String) return League.Holders.Holder is Empty : League.Holders.Holder; Pos : constant Parameter_Maps.Cursor := Self.Parameters.Find (Name); Item : Bound_Value_Access; begin if Parameter_Maps.Has_Element (Pos) then Item := Parameter_Maps.Element (Pos); end if; if Item = null then return Empty; else return Item.Value; end if; end Bound_Value; ------------------- -- Error_Message -- ------------------- overriding function Error_Message (Self : not null access OCI_Query) return League.Strings.Universal_String is begin return Self.DB.Error_Message; end Error_Message; ------------- -- Execute -- ------------- overriding function Execute (Self : not null access OCI_Query) return Boolean is procedure Fixup_Parameter (Position : Parameter_Maps.Cursor); --------------------- -- Fixup_Parameter -- --------------------- procedure Fixup_Parameter (Position : Parameter_Maps.Cursor) is use type Matreshka.Internals.Strings.Shared_String_Access; Ok : Boolean; Item : constant Bound_Value_Access := Parameter_Maps.Element (Position); begin if Item = null or else Item.Direction = SQL.In_Parameter then return; elsif Item.String /= null then Item.String.Unused := Item.String.Unused + Item.String_Size; Matreshka.Internals.Strings.C.Validate_And_Fixup (Item.String, Item.String.Unused, Ok); League.Holders.Replace_Element (Item.Value, League.Strings.Internals.Wrap (Item.String)); Item.String := null; Item.String_Size := 0; if Item.Is_Null = -1 then League.Holders.Clear (Item.Value); end if; elsif League.Holders.Is_Abstract_Integer (Item.Value) then if Item.Is_Null = 0 then League.Holders.Replace_Element (Item.Value, Item.Int); else League.Holders.Clear (Item.Value); end if; elsif League.Holders.Is_Abstract_Float (Item.Value) then if Item.Is_Null = 0 then League.Holders.Replace_Element (Item.Value, Item.Float); else League.Holders.Clear (Item.Value); end if; elsif Item.Is_Null /= 0 then League.Holders.Clear (Item.Value); end if; end Fixup_Parameter; Count : aliased Ub4; Code : Error_Code; begin -- Execute if Self.State not in Ready then return False; end if; Code := OCIStmtExecute (Self.DB.Service, Self.Handle, Self.DB.Error, Iters => Boolean'Pos (not Self.Is_Select)); if Databases.Check_Error (Self.DB, Code) then return False; end if; Self.Parameters.Iterate (Fixup_Parameter'Access); if Self.Is_Select and not Self.Is_Described then Self.Is_Described := True; Self.Column_Count := 0; Code := OCIAttrGet (Target => Self.Handle, Target_Type => OCI_HTYPE_STMT, Buffer => Count'Address, Length => null, Attr => OCI_ATTR_PARAM_COUNT, Error => Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; if Self.Columns /= null and then Self.Columns'Length < Count then Free (Self.Columns); end if; if Self.Columns = null and Count > 0 then Self.Columns := new Defined_Value_Array (1 .. Positive (Count)); end if; for J in 1 .. Natural (Count) loop declare Param : aliased Parameter; Column : Plug_In.Column_Description; Plugin : Plug_In_Access := Plug_In_Access (Self.DB.Plugins); Control : Plug_In.Control_Side := Plug_In.Driver; begin Code := OCIParamGet (Self.Handle, OCI_HTYPE_STMT, Self.DB.Error, Param'Access, Ub4 (J)); if Databases.Check_Error (Self.DB, Code) then return False; end if; Code := OCIAttrGet (Param, OCI_DTYPE_PARAM, Column.Column_Type'Address, null, OCI_ATTR_DATA_TYPE, Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; Code := OCIAttrGet (Param, OCI_DTYPE_PARAM, Column.Size'Address, null, OCI_ATTR_DATA_SIZE, Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; Code := OCIAttrGet (Param, OCI_DTYPE_PARAM, Column.Precision'Address, null, OCI_ATTR_PRECISION, Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; Code := OCIAttrGet (Param, OCI_DTYPE_PARAM, Column.Scale'Address, null, OCI_ATTR_SCALE, Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; -- Look for plugin while Plugin /= null loop Plugin.Check_Column (Column, Control, Self.Columns (J).Extra_Type, Self.Columns (J).Extra_Size); exit when Control = Plug_In.Plug_In; Plugin := Plugin.Next; end loop; Self.Columns (J).Plugin := Plugin; if Plugin /= null then -- Drop insufficient Extra space if Self.Columns (J).Extra /= null and then Self.Columns (J).Extra'Length < Self.Columns (J).Extra_Size then Free (Self.Columns (J).Extra); end if; -- Allocate Extra space if Self.Columns (J).Extra = null then Self.Columns (J).Extra := new System.Storage_Elements.Storage_Array (1 .. Self.Columns (J).Extra_Size); end if; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).Extra (1)'Address, Value_Length => Ub4 (Self.Columns (J).Extra_Size), Value_Type => Self.Columns (J).Extra_Type, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; elsif Column.Column_Type in SQLT_CHR | SQLT_AFC then Self.Columns (J).Column_Type := String_Column; Self.Columns (J).Size := Utf16.Utf16_String_Index (Column.Size + 1); declare use Matreshka.Internals.Strings; Ptr : Shared_String_Access renames Self.Columns (J).String; begin if Ptr = null then Ptr := Allocate (Self.Columns (J).Size); elsif not Can_Be_Reused (Ptr, Self.Columns (J).Size) then Dereference (Ptr); Ptr := Allocate (Self.Columns (J).Size); end if; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Ptr.Value (0)'Address, Value_Length => Ptr.Value'Length * 2, Value_Type => SQLT_STR, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; end; elsif Column.Column_Type in SQLT_NUM | SQLT_IBFLOAT | SQLT_IBDOUBLE then if Column.Column_Type = SQLT_NUM and Column.Scale = 0 then Self.Columns (J).Column_Type := Integer_Column; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).Int'Address, Value_Length => Self.Columns (J).Int'Size / 8, Value_Type => SQLT_INT, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; else Self.Columns (J).Column_Type := Float_Column; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).Float'Address, Value_Length => Self.Columns (J).Float'Size / 8, Value_Type => SQLT_FLT, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; end if; elsif Column.Column_Type in SQLT_DAT then Self.Columns (J).Column_Type := Date_Column; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).Date'Address, Value_Length => Self.Columns (J).Date'Size / 8, Value_Type => SQLT_ODT, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; elsif Column.Column_Type in SQLT_TIMESTAMP | SQLT_TIMESTAMP_TZ | SQLT_TIMESTAMP_LTZ then if Self.Columns (J).Timestamp = null then Code := OCIDescriptorAlloc (Databases.Env, Self.Columns (J).Timestamp'Access, OCI_DTYPE_TIMESTAMP_TZ); end if; Self.Columns (J).Column_Type := Time_Column; Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).Timestamp'Address, Value_Length => Self.Columns (J).Timestamp'Size / 8, Value_Type => SQLT_TIMESTAMP_TZ, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then return False; end if; else exit; -- raise Constraint_Error with "Unsupported type"; end if; Code := OCIDescriptorFree (Param, OCI_DTYPE_PARAM); if Databases.Check_Error (Self.DB, Code) then return False; end if; end; Self.Column_Count := J; end loop; end if; if Self.Is_Select then Self.State := Executed; else Self.State := No_More_Rows; end if; return True; end Execute; ------------ -- Finish -- ------------ overriding procedure Finish (Self : not null access OCI_Query) is Code : Error_Code; begin if Self.State in Active then if Self.State in Fetching then -- Cancel cursor by fetching no rows Code := OCIStmtFetch2 (Self.Handle, Self.DB.Error, Rows => 0); if Databases.Check_Error (Self.DB, Code) then null; -- How to report errors? end if; end if; Self.State := Prepared; end if; end Finish; ---------------- -- Invalidate -- ---------------- overriding procedure Invalidate (Self : not null access OCI_Query) is procedure Drop (Pos : Parameter_Maps.Cursor); ---------- -- Drop -- ---------- procedure Drop (Pos : Parameter_Maps.Cursor) is Code : Error_Code; Item : Bound_Value_Access := Parameter_Maps.Element (Pos); begin if Item /= null and then Item.Timestamp /= null then Code := OCIHandleFree (Item.Timestamp, OCI_DTYPE_TIMESTAMP_TZ); if Databases.Check_Error (Self.DB, Code) then null; -- How to report errors? end if; Item.Timestamp := null; end if; Free (Item); Self.Parameters.Replace_Element (Pos, null); end Drop; Code : Error_Code; begin if Self.Handle /= null then Code := OCIHandleFree (Self.Handle, OCI_HTYPE_STMT); if Databases.Check_Error (Self.DB, Code) then null; -- How to report errors? end if; Self.Handle := null; end if; Self.Parameters.Iterate (Drop'Access); if Self.Columns /= null then declare use Matreshka.Internals.Strings; begin for J in Self.Columns'Range loop if Self.Columns (J).String /= null then Dereference (Self.Columns (J).String); elsif Self.Columns (J).Timestamp /= null then Code := OCIHandleFree (Self.Columns (J).Timestamp, OCI_DTYPE_TIMESTAMP_TZ); Self.Columns (J).Timestamp := null; end if; end loop; Free (Self.Columns); end; end if; -- Call Invalidate of parent tagged type. Abstract_Query (Self.all).Invalidate; end Invalidate; --------------- -- Is_Active -- --------------- overriding function Is_Active (Self : not null access OCI_Query) return Boolean is begin return Self.State in Active; end Is_Active; -------------- -- Is_Valid -- -------------- overriding function Is_Valid (Self : not null access OCI_Query) return Boolean is begin return Self.State = Has_Row; end Is_Valid; ---------- -- Next -- ---------- overriding function Next (Self : not null access OCI_Query) return Boolean is use Matreshka.Internals.Strings; Ok : Boolean; Code : Error_Code; begin if Self.State not in Fetching then return False; end if; -- Rebind used strings columns for J in 1 .. Self.Column_Count loop if Self.Columns (J).Plugin = null and then Self.Columns (J).Column_Type = String_Column and then not Can_Be_Reused (Self.Columns (J).String, Self.Columns (J).Size) then Dereference (Self.Columns (J).String); Self.Columns (J).String := Allocate (Self.Columns (J).Size); Code := OCIDefineByPos (Stmt => Self.Handle, Target => Self.Columns (J).Define'Access, Error => Self.DB.Error, Position => Ub4 (J), Value => Self.Columns (J).String.Value (0)'Address, Value_Length => Self.Columns (J).String.Value'Length * 2, Value_Type => SQLT_STR, Indicator => Self.Columns (J).Is_Null'Access); if Databases.Check_Error (Self.DB, Code) then Self.State := No_More_Rows; return False; end if; end if; end loop; Code := OCIStmtFetch2 (Self.Handle, Self.DB.Error); if Code = OCI_NO_DATA or else Databases.Check_Error (Self.DB, Code) then Self.State := No_More_Rows; else Self.State := Has_Row; -- validate not null string columns for J in 1 .. Self.Column_Count loop if Self.Columns (J).Column_Type = String_Column and Self.Columns (J).Is_Null = 0 then Matreshka.Internals.Strings.C.Validate_And_Fixup (Self.Columns (J).String, Ok); end if; end loop; end if; return Self.State = Has_Row; end Next; ----------------------- -- OCICallbackInBind -- ----------------------- function OCICallbackInBind (ictxp : Bound_Value_Access; bindp : Oracle.Bind; iter : Ub4; index : Ub4; bufpp : access Utf16_Code_Unit_Access; alenp : access Ub4; piecep : access Ub1; indp : access Sb2_Ptr) return Error_Code is pragma Unreferenced (bindp); pragma Unreferenced (iter); pragma Unreferenced (index); begin piecep.all := OCI_ONE_PIECE; indp.all := ictxp.Is_Null'Access; if ictxp.Is_Null = -1 then bufpp.all := null; alenp.all := 0; return OCI_CONTINUE; end if; alenp.all := Ub4 (League.Strings.Internals.Internal (League.Holders.Element (ictxp.Value)).Unused) * 2 + 2; bufpp.all := League.Strings.Internals.Internal (League.Holders.Element (ictxp.Value)).Value (0)'Access; return OCI_CONTINUE; end OCICallbackInBind; ------------------------ -- OCICallbackOutBind -- ------------------------ function OCICallbackOutBind (octxp : Bound_Value_Access; bindp : Oracle.Bind; iter : Ub4; index : Ub4; bufpp : access Utf16_Code_Unit_Access; alenp : access Ub4_Ptr; piecep : access Ub1; indp : access Sb2_Ptr; rcodepp : access Sb2_Ptr) return Error_Code is pragma Unreferenced (bindp); pragma Unreferenced (iter); pragma Unreferenced (index); pragma Unreferenced (Rcodepp); use Matreshka.Internals.Strings; use type Ub1; use type Matreshka.Internals.Utf16.Utf16_String_Index; begin if piecep.all = OCI_ONE_PIECE then piecep.all := OCI_FIRST_PIECE; if not League.Holders.Is_Empty (octxp.Value) then octxp.String := League.Strings.Internals.Internal (League.Holders.Element (octxp.Value)); else octxp.String := null; end if; if octxp.String /= null and then Can_Be_Reused (octxp.String, octxp.String.Capacity - 1) then Reference (octxp.String); League.Holders.Replace_Element (octxp.Value, League.Strings.Empty_Universal_String); else octxp.String := Allocate (64); -- Some initial size end if; octxp.String.Unused := 0; else piecep.all := OCI_NEXT_PIECE; octxp.String.Unused := octxp.String.Unused + octxp.String_Size; Mutate (octxp.String, 8 * octxp.String.Capacity); end if; octxp.String_Size := Ub4 ((octxp.String.Capacity - octxp.String.Unused) * 2); bufpp.all := octxp.String.Value (octxp.String.Unused)'Access; alenp.all := octxp.String_Size'Access; indp.all := octxp.Is_Null'Access; return OCI_CONTINUE; end OCICallbackOutBind; ------------- -- Prepare -- ------------- overriding function Prepare (Self : not null access OCI_Query; Query : League.Strings.Universal_String) return Boolean is Kind : aliased Ub2; Code : Error_Code; begin if Self.Handle = null then Code := OCIHandleAlloc (Databases.Env, Self.Handle'Access, OCI_HTYPE_STMT); if Databases.Check_Error (Self.DB, Code) then return False; end if; end if; Code := OCIStmtPrepare (Self.Handle, Self.DB.Error, League.Strings.Internals.Internal (Query).Value, Ub4 (League.Strings.Internals.Internal (Query).Unused) * 2); if Databases.Check_Error (Self.DB, Code) then return False; end if; Code := OCIAttrGet (Target => Self.Handle, Target_Type => OCI_HTYPE_STMT, Buffer => Kind'Address, Length => null, Attr => OCI_ATTR_STMT_TYPE, Error => Self.DB.Error); if Databases.Check_Error (Self.DB, Code) then return False; end if; Self.Is_Described := False; Self.Is_Select := Kind = OCI_STMT_SELECT; Self.State := Prepared; return True; end Prepare; ----------- -- Value -- ----------- overriding function Value (Self : not null access OCI_Query; Index : Positive) return League.Holders.Holder is Value : League.Holders.Holder; begin if Self.State /= Has_Row or else Index > Self.Column_Count then return Value; elsif Self.Columns (Index).Plugin /= null then if Self.Columns (Index).Is_Null = 0 then Self.Columns (Index).Plugin.Decode (Value, Self.Columns (Index).Extra (1 .. Self.Columns (Index).Extra_Size)); end if; elsif Self.Columns (Index).Column_Type = String_Column then League.Holders.Set_Tag (Value, League.Holders.Universal_String_Tag); if Self.Columns (Index).Is_Null = 0 then League.Holders.Replace_Element (Value, League.Strings.Internals.Create (Self.Columns (Index).String)); end if; elsif Self.Columns (Index).Column_Type = Integer_Column then League.Holders.Set_Tag (Value, League.Holders.Universal_Integer_Tag); if Self.Columns (Index).Is_Null = 0 then League.Holders.Replace_Element (Value, Self.Columns (Index).Int); end if; elsif Self.Columns (Index).Column_Type = Float_Column then League.Holders.Set_Tag (Value, League.Holders.Universal_Float_Tag); if Self.Columns (Index).Is_Null = 0 then League.Holders.Replace_Element (Value, Self.Columns (Index).Float); end if; elsif Self.Columns (Index).Column_Type = Date_Column then League.Holders.Set_Tag (Value, League.Holders.Date_Tag); if Self.Columns (Index).Is_Null = 0 then League.Holders.Replace_Element (Value, Utils.Decode_Date (Self.Columns (Index).Date)); end if; elsif Self.Columns (Index).Column_Type = Time_Column then League.Holders.Set_Tag (Value, League.Holders.Date_Time_Tag); if Self.Columns (Index).Is_Null = 0 then declare Aux : League.Calendars.Date_Time; Code : Error_Code; Year : aliased Sb2; Month : aliased Ub1; Day : aliased Ub1; Hour : aliased Ub1; Min : aliased Ub1; Sec : aliased Ub1; Fract : aliased Ub4; begin Code := OCIDateTimeGetDate (Env => Databases.Env, Error => Self.DB.Error, Date => Self.Columns (Index).Timestamp, Year => Year'Access, Month => Month'Access, Day => Day'Access); if Databases.Check_Error (Self.DB, Code) then return Value; end if; Code := OCIDateTimeGetTime (Env => Databases.Env, Error => Self.DB.Error, Date => Self.Columns (Index).Timestamp, Hour => Hour'Access, Min => Min'Access, Sec => Sec'Access, Fract => Fract'Access); if Databases.Check_Error (Self.DB, Code) then return Value; end if; Aux := League.Calendars.ISO_8601.Create (League.Calendars.ISO_8601.Year_Number (Year), League.Calendars.ISO_8601.Month_Number (Month), League.Calendars.ISO_8601.Day_Number (Day), League.Calendars.ISO_8601.Hour_Number (Hour), League.Calendars.ISO_8601.Minute_Number (Min), League.Calendars.ISO_8601.Second_Number (Sec), League.Calendars.ISO_8601.Nanosecond_100_Number (Fract / 100)); -- ??? where timezone should go??? League.Holders.Replace_Element (Value, Aux); end; end if; end if; return Value; end Value; end Matreshka.Internals.SQL_Drivers.Oracle.Queries;
-- Copyright (c) 2019-2020 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Calendar; with Ada.Containers.Synchronized_Queue_Interfaces; with Ada.Containers.Unbounded_Synchronized_Queues; with Ada.Containers.Vectors; with Ada.Finalization; with GNAT.Sockets; with League.Stream_Element_Vectors; with Torrent.Metainfo_Files; with Torrent.Storages; limited with Torrent.Downloaders; package Torrent.Connections is type Connection is tagged; type Connection_Access is access all Connection'Class; type Connection_Access_Array is array (Positive range <>) of Connection_Access; package Queue_Interfaces is new Ada.Containers.Synchronized_Queue_Interfaces (Connection_Access); package Queues is new Ada.Containers.Unbounded_Synchronized_Queues (Queue_Interfaces); type Interval is record From : Piece_Offset; -- Starts from zero To : Piece_Offset; end record; package Interval_Vectors is new Ada.Containers.Vectors (Positive, Interval); procedure Insert (List : in out Interval_Vectors.Vector; Value : Interval); type Piece_Interval is record Piece : Piece_Index; Span : Interval; end record; subtype Piece_Interval_Count is Natural range 0 .. 8; type Piece_Interval_Array is array (Positive range <>) of Piece_Interval; type Piece_Intervals (Length : Piece_Interval_Count := 0) is record List : Piece_Interval_Array (1 .. Length); end record; type Piece_State is record Piece : Piece_Count; Intervals : Interval_Vectors.Vector; end record; type Connection_State_Listener is synchronized interface; type Connection_State_Listener_Access is access all Connection_State_Listener'Class with Storage_Size => 0; not overriding function We_Are_Intrested (Self : Connection_State_Listener; Map : Boolean_Array) return Boolean is abstract; not overriding procedure Reserve_Intervals (Self : in out Connection_State_Listener; Map : Boolean_Array; Value : out Piece_State) is abstract; not overriding procedure Unreserve_Intervals (Self : in out Connection_State_Listener; Map : Piece_Interval_Array) is abstract; not overriding procedure Interval_Saved (Self : in out Connection_State_Listener; Piece : Piece_Index; Value : Interval; Last : out Boolean) is abstract; not overriding procedure Piece_Completed (Self : in out Connection_State_Listener; Piece : Piece_Index; Ok : Boolean) is abstract; not overriding procedure Interval_Sent (Self : in out Connection_State_Listener; Size : Piece_Offset) is abstract; type Connection (Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access; Downloader : not null access Torrent.Downloaders.Downloader'Class; Storage : not null Torrent.Storages.Storage_Access; Piece_Count : Piece_Index) is tagged limited private; procedure Initialize (Self : in out Connection'Class; My_Id : SHA1; Peer : GNAT.Sockets.Sock_Addr_Type; Listener : Connection_State_Listener_Access); type Piece_Index_Array is array (Piece_Index range <>) of Piece_Index; procedure Do_Handshake (Self : in out Connection'Class; Socket : GNAT.Sockets.Socket_Type; Completed : Piece_Index_Array; Inbound : Boolean); function Peer (Self : Connection'Class) return GNAT.Sockets.Sock_Addr_Type; function Connected (Self : Connection'Class) return Boolean; function Intrested (Self : Connection'Class) return Boolean; function Downloaded (Self : in out Connection'Class) return Piece_Offset; -- Return amount of data received since last call. function Serve_Needed (Self : Connection'Class) return Boolean; -- Connection has some pending messages to send them right now procedure Set_Choked (Self : in out Connection'Class; Value : Boolean); procedure Serve (Self : in out Connection'Class; Limit : Ada.Calendar.Time); -- Process input messages and seed some data if unchoked. Limit is a time -- when it should complete. package Connection_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Connection_Access); procedure Serve_All (Selector : GNAT.Sockets.Selector_Type; Vector : in out Connection_Vectors.Vector; Except : Connection_Access_Array; Limit : Ada.Calendar.Time); function Is_Valid_Piece (Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access; Storage : in out Torrent.Storages.Storage; Piece : Piece_Index) return Boolean; private package Piece_Interval_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Piece_Interval, "=" => "="); type Natural_Array is array (Positive range <>) of Natural; type Sent_Piece_Intervals (Length : Piece_Interval_Count := 0) is record Request : Piece_Intervals (Length); Expire : Natural_Array (1 .. Length); end record; type Connection (Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access; Downloader : not null access Torrent.Downloaders.Downloader'Class; Storage : not null Torrent.Storages.Storage_Access; Piece_Count : Piece_Index) is limited new Ada.Finalization.Limited_Controlled with record Peer : GNAT.Sockets.Sock_Addr_Type; Socket : GNAT.Sockets.Socket_Type; Sent_Handshake : Boolean; Got_Handshake : Boolean; Closed : Boolean; We_Choked : Boolean; He_Choked : Boolean; Choked_Sent : Boolean; -- If He_Choked is in action He_Intrested : Boolean; We_Intrested : Boolean; Current_Piece : Piece_State; My_Peer_Id : SHA1; Unparsed : League.Stream_Element_Vectors.Stream_Element_Vector := League.Stream_Element_Vectors.Empty_Stream_Element_Vector; Pipelined : Sent_Piece_Intervals; Requests : Piece_Interval_Vectors.Vector; Last_Request : Natural; Last_Completed : Torrent.Piece_Count; Listener : Connection_State_Listener_Access; Downloaded : Piece_Offset; Piece_Map : Boolean_Array (1 .. Piece_Count); end record; end Torrent.Connections;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . E X C E P T I O N S . L A S T _ C H A N C E _ H A N D L E R -- -- -- -- B o d y -- -- -- -- Copyright (C) 2003-2005, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Default version for most targets with System.Standard_Library; use System.Standard_Library; -- Used for Adafinal with System.Soft_Links; -- Used for Task_Termination_Handler -- Task_Termination_NT procedure Ada.Exceptions.Last_Chance_Handler (Except : Exception_Occurrence) is procedure Unhandled_Terminate; pragma No_Return (Unhandled_Terminate); pragma Import (C, Unhandled_Terminate, "__gnat_unhandled_terminate"); -- Perform system dependent shutdown code function Exception_Message_Length (X : Exception_Occurrence) return Natural; pragma Import (Ada, Exception_Message_Length, "__gnat_exception_msg_len"); procedure Append_Info_Exception_Message (X : Exception_Occurrence; Info : in out String; Ptr : in out Natural); pragma Import (Ada, Append_Info_Exception_Message, "__gnat_append_info_e_msg"); procedure Append_Info_Exception_Information (X : Exception_Occurrence; Info : in out String; Ptr : in out Natural); pragma Import (Ada, Append_Info_Exception_Information, "__gnat_append_info_e_info"); procedure To_Stderr (S : String); pragma Import (Ada, To_Stderr, "__gnat_to_stderr"); -- Little routine to output string to stderr Ptr : Natural := 0; Nobuf : String (1 .. 0); Nline : constant String := String'(1 => ASCII.LF); -- Convenient shortcut begin -- Do not execute any task termination code when shutting down the system. -- The Adafinal procedure would execute the task termination routine for -- normal termination, but we have already executed the task termination -- procedure because of an unhandled exception. System.Soft_Links.Task_Termination_Handler := System.Soft_Links.Task_Termination_NT'Access; -- Let's shutdown the runtime now. The rest of the procedure needs to be -- careful not to use anything that would require runtime support. In -- particular, functions returning strings are banned since the sec stack -- is no longer functional. This is particularly important to note for the -- Exception_Information output. We used to allow the tailored version to -- show up here, which turned out to be a bad idea as it might involve a -- traceback decorator the length of which we don't control. Potentially -- heavy primary/secondary stack use or dynamic allocations right before -- this point are not welcome, moving the output before the finalization -- raises order of outputs concerns, and decorators are intended to only -- be used with exception traces, which should have been issued already. System.Standard_Library.Adafinal; -- Check for special case of raising _ABORT_SIGNAL, which is not -- really an exception at all. We recognize this by the fact that -- it is the only exception whose name starts with underscore. if To_Ptr (Except.Id.Full_Name) (1) = '_' then To_Stderr (Nline); To_Stderr ("Execution terminated by abort of environment task"); To_Stderr (Nline); -- If no tracebacks, we print the unhandled exception in the old style -- (i.e. the style used before ZCX was implemented). We do this to -- retain compatibility. elsif Except.Num_Tracebacks = 0 then To_Stderr (Nline); To_Stderr ("raised "); To_Stderr (To_Ptr (Except.Id.Full_Name) (1 .. Except.Id.Name_Length - 1)); if Exception_Message_Length (Except) /= 0 then To_Stderr (" : "); Append_Info_Exception_Message (Except, Nobuf, Ptr); end if; To_Stderr (Nline); -- Traceback exists else To_Stderr (Nline); To_Stderr ("Execution terminated by unhandled exception"); To_Stderr (Nline); Append_Info_Exception_Information (Except, Nobuf, Ptr); end if; Unhandled_Terminate; end Ada.Exceptions.Last_Chance_Handler;
package glx.BufferSwapComplete is type Item is record the_Type : aliased C.int; Serial : aliased C.unsigned_long; send_Event : aliased Bool; Display : System.Address; Drawable : aliased glx.Drawable; Event_type : aliased C.int; UST : aliased Integer_64; MSC : aliased Integer_64; SBC : aliased Integer_64; end record; type Items is array (C.size_t range <>) of aliased BufferSwapComplete.item; type Pointer is access all BufferSwapComplete.item; type Pointers is array (C.size_t range <>) of aliased BufferSwapComplete.Pointer; type Pointer_Pointer is access all BufferSwapComplete.Pointer; function Construct return BufferSwapComplete.item; private pragma Import (C, Construct, "Ada_new_GLXBufferSwapComplete"); end glx.BufferSwapComplete;
-- Display Serial Interface package HAL.DSI is subtype DSI_Virtual_Channel_ID is UInt2; type DSI_Data is array (Positive range <>) of Byte; type DSI_Pkt_Data_Type is (DCS_Short_Pkt_Write_P0, -- DCS Short write, no parameter DCS_Short_Pkt_Write_P1, -- DCS Short write, one parameter Gen_Short_Pkt_Write_P0, -- Generic Short write, no parameter Gen_Short_Pkt_Write_P1, -- Generic Short write, one parameter Gen_Short_Pkt_Write_P2, -- Generic Short write, two parameters DCS_Long_Pkt_Write, -- DCS Long write Gen_Long_Pkt_Write, -- Generic Long write DCS_Short_Pkt_Read, -- DCS Short read Gen_Short_Pkg_Read_P0, -- Gen read, no parameter Gen_Short_Pkg_Read_P1, -- Gen read, one parameter Gen_Short_Pkg_Read_P2); -- Gen read, two parameter subtype DSI_Short_Write_Packet_Data_Type is DSI_Pkt_Data_Type range DCS_Short_Pkt_Write_P0 .. Gen_Short_Pkt_Write_P2; subtype DSI_Long_Write_Packet_Data_Type is DSI_Pkt_Data_Type range DCS_Long_Pkt_Write .. Gen_Long_Pkt_Write; type DSI_Port is limited interface; type DSI_Port_Ref is not null access all DSI_Port'Class; procedure DSI_Short_Write (Port : in out DSI_Port; Channel_ID : DSI_Virtual_Channel_ID; Mode : DSI_Short_Write_Packet_Data_Type; Param1 : Byte; Param2 : Byte) is abstract; procedure DSI_Long_Write (Port : in out DSI_Port; Channel_Id : DSI_Virtual_Channel_ID; Mode : DSI_Long_Write_Packet_Data_Type; Param1 : Byte; Parameters : DSI_Data) is abstract; end HAL.DSI;
package Parse_Goto is type Small_Integer is range -32_000 .. 32_000; type Goto_Entry is record Nonterm : Small_Integer; Newstate : Small_Integer; end record; --pragma suppress(index_check); subtype Row is Integer range -1 .. Integer'Last; type Goto_Parse_Table is array (Row range <>) of Goto_Entry; Goto_Matrix : constant Goto_Parse_Table := ((-1,-1) -- Dummy Entry. -- State 0 ,(-3, 1),(-2, 2) -- State 1 ,(-4, 3) -- State 2 -- State 3 ,(-8, 10) ,(-5, 9) -- State 4 -- State 5 -- State 6 -- State 7 -- State 8 -- State 9 ,(-6, 12) -- State 10 -- State 11 -- State 12 ,(-7, 14) -- State 13 ,(-9, 15) -- State 14 ,(-18, 28),(-17, 26),(-16, 24),(-15, 25) ,(-12, 20),(-11, 18),(-10, 34) -- State 15 -- State 16 -- State 17 -- State 18 ,(-18, 28) ,(-17, 26),(-16, 24),(-15, 25),(-12, 37) -- State 19 ,(-18, 28),(-17, 26),(-16, 24),(-15, 25) ,(-12, 40) -- State 20 ,(-13, 42) -- State 21 -- State 22 -- State 23 ,(-14, 45) -- State 24 ,(-18, 28) ,(-17, 26),(-15, 48) -- State 25 ,(-18, 28),(-17, 49) -- State 26 -- State 27 -- State 28 -- State 29 -- State 30 ,(-19, 54) -- State 31 ,(-18, 28),(-17, 26),(-16, 24) ,(-15, 25),(-12, 55) -- State 32 -- State 33 ,(-20, 56) -- State 34 -- State 35 -- State 36 -- State 37 ,(-13, 60) -- State 38 ,(-18, 28),(-17, 26),(-16, 24),(-15, 25) ,(-12, 61) -- State 39 -- State 40 ,(-13, 62) -- State 41 -- State 42 -- State 43 ,(-18, 28),(-17, 26) ,(-15, 63) -- State 44 -- State 45 -- State 46 -- State 47 -- State 48 ,(-18, 28),(-17, 49) -- State 49 -- State 50 -- State 51 -- State 52 -- State 53 -- State 54 -- State 55 -- State 56 -- State 57 ,(-20, 72) -- State 58 -- State 59 -- State 60 -- State 61 ,(-13, 73) -- State 62 -- State 63 ,(-18, 28),(-17, 49) -- State 64 -- State 65 -- State 66 -- State 67 -- State 68 -- State 69 -- State 70 -- State 71 -- State 72 -- State 73 -- State 74 -- State 75 -- State 76 -- State 77 -- State 78 -- State 79 -- State 80 -- State 81 -- State 82 ); -- The offset vector GOTO_OFFSET : array (0.. 82) of Integer := ( 0, 2, 3, 3, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 8, 15, 15, 15, 15, 20, 25, 26, 26, 26, 27, 30, 32, 32, 32, 32, 32, 33, 38, 38, 39, 39, 39, 39, 40, 45, 45, 46, 46, 46, 49, 49, 49, 49, 49, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 53, 53, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55); subtype Rule is Natural; subtype Nonterminal is Integer; Rule_Length : array (Rule range 0 .. 52) of Natural := ( 2, 5, 0, 5, 0, 2, 1, 1, 1, 3, 1, 1, 4, 0, 0, 4, 3, 3, 2, 2, 1, 1, 3, 3, 1, 1, 1, 0, 3, 2, 1, 2, 2, 1, 2, 2, 2, 6, 5, 4, 1, 1, 1, 3, 3, 1, 3, 4, 4, 2, 0, 2, 0); Get_LHS_Rule: array (Rule range 0 .. 52) of Nonterminal := (-1, -2,-3,-4,-4,-4,-5,-8,-8, -9,-9,-9,-6,-6,-7,-10,-10, -10,-10,-10,-10,-10,-11,-14,-14, -14,-13,-13,-12,-12,-12,-16,-15, -15,-17,-17,-17,-17,-17,-17,-17, -17,-17,-17,-17,-17,-18,-18,-20, -20,-20,-19,-19); end Parse_Goto;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ package body Gela.Hash.CRC.b32 is Keys : constant array (CRC32 range 0 .. 255) of CRC32 := (0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918000, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117); subtype Byte is CRC32 range 0 .. 255; procedure Update_Hash (This : in out Hasher; Value : in Byte); pragma Inline (Update_Hash); ------------ -- Update -- ------------ procedure Update (This : in out Hasher; Value : in String) is begin This.Length := This.Length + Value'Length; if This.Length > Maximum_Length then raise Maximum_Length_Error; end if; for J in Value'Range loop Update_Hash (This, Character'Pos (Value (J))); end loop; end Update; ----------------- -- Wide_Update -- ----------------- procedure Wide_Update (This : in out Hasher; Value : in Wide_String) is begin This.Length := This.Length + 2 * Value'Length; if This.Length > Maximum_Length then raise Maximum_Length_Error; end if; for J in Value'Range loop Update_Hash (This, Wide_Character'Pos (Value (J)) and 16#FF#); Update_Hash (This, Shift_Right (Wide_Character'Pos (Value (J)), 8)); end loop; end Wide_Update; ---------------------- -- Wide_Wide_Update -- ---------------------- procedure Wide_Wide_Update (This : in out Hasher; Value : in Wide_Wide_String) is subtype W is Wide_Wide_Character; begin This.Length := This.Length + 4 * Value'Length; if This.Length > Maximum_Length then raise Maximum_Length_Error; end if; for J in Value'Range loop Update_Hash (This, W'Pos (Value (J)) and 16#FF#); Update_Hash (This, Shift_Right (W'Pos (Value (J)), 8) and 16#FF#); Update_Hash (This, Shift_Right (W'Pos (Value (J)), 16) and 16#FF#); Update_Hash (This, Shift_Right (W'Pos (Value (J)), 24)); end loop; end Wide_Wide_Update; ------------ -- Update -- ------------ procedure Update (This : in out Hasher; Value : in Ada.Streams.Stream_Element_Array) is begin This.Length := This.Length + Value'Length; if This.Length > Maximum_Length then raise Maximum_Length_Error; end if; for J in Value'Range loop Update_Hash (This, CRC32 (Value (J))); end loop; end Update; --------------- -- Calculate -- --------------- function Calculate (Value : in String) return CRC32 is H : Hasher; begin Update (H, Value); return Result (H); end Calculate; -------------------- -- Wide_Calculate -- -------------------- function Wide_Calculate (Value : in Wide_String) return CRC32 is H : Hasher; begin Wide_Update (H, Value); return Result (H); end Wide_Calculate; --------------- -- Calculate -- --------------- function Wide_Wide_Calculate (Value : in Wide_Wide_String) return CRC32 is H : Hasher; begin Wide_Wide_Update (H, Value); return Result (H); end Wide_Wide_Calculate; --------------- -- Calculate -- --------------- function Calculate (Value : in Ada.Streams.Stream_Element_Array) return CRC32 is H : Hasher; begin Update (H, Value); return Result (H); end Calculate; ------------- -- To_Hash -- ------------- function To_Hash (T : in CRC32) return Hash_Type is begin return Hash_Type (T); end To_Hash; --------------- -- Calculate -- --------------- function Calculate (Value : in String) return Hash_Type is begin return To_Hash (Calculate (Value)); end Calculate; -------------------- -- Wide_Calculate -- -------------------- function Wide_Calculate (Value : in Wide_String) return Hash_Type is begin return To_Hash (Wide_Calculate (Value)); end Wide_Calculate; --------------- -- Calculate -- --------------- function Wide_Wide_Calculate (Value : in Wide_Wide_String) return Hash_Type is begin return To_Hash (Wide_Wide_Calculate (Value)); end Wide_Wide_Calculate; --------------- -- Calculate -- --------------- function Calculate (Value : in Ada.Streams.Stream_Element_Array) return Hash_Type is begin return To_Hash (Calculate (Value)); end Calculate; ------------ -- Update -- ------------ procedure Update_Hash (This : in out Hasher; Value : in Byte) is begin This.Cm_Reg := Shift_Right (This.Cm_Reg, 8) xor Keys (Value xor (This.Cm_Reg and 16#0000_00FF#)); end Update_Hash; ------------ -- Result -- ------------ function Result (This : in Hasher) return CRC32 is begin return This.Cm_Reg xor 16#FFFFFFFF#; end Result; end Gela.Hash.CRC.b32; ------------------------------------------------------------------------------ -- Copyright (c) 2006, Andry Ogorodnik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- * this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- * notice, this list of conditions and the following disclaimer in the -- * documentation and/or other materials provided with the distribution. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; end Security.Controllers;
package body problem_16 is function Solution_1( I : Integer) return Integer is Length : constant Integer := 1 + Integer(Float(I)*0.30103); Arr : array( Natural range 0 .. Length) of Natural := (0 => 1, others => 0); Carry : Integer := 0; Sum : Integer := 0; begin for J in 1 .. I loop Carry := 0; for Z in 0 .. Length loop declare Product : Integer := 2*Arr(Z) + Carry; begin Arr(z) := Product mod 10; Carry := Product / 10; end; end loop; end loop; for J in 0 .. Length loop Sum := Sum + Arr(J); end loop; return Sum; end Solution_1; procedure Test_Solution_1 is Solution : constant Integer := 1366; begin Assert( Solution_1(1000) = Solution ); end Test_Solution_1; function Get_Solutions return Solution_Case is Ret : Solution_Case; begin Set_Name( Ret, "Problem 16" ); Add_Test( Ret, Test_Solution_1'Access ); return Ret; end Get_Solutions; end problem_16;
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd. -- -- SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from rp2040.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; -- Simple PWM package RP_SVD.PWM is pragma Preelaborate; --------------- -- Registers -- --------------- type CH0_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH0_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH0_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH0_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH0_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH0_DIV_FRAC_Field is HAL.UInt4; subtype CH0_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH0_DIV_Register is record FRAC : CH0_DIV_FRAC_Field := 16#0#; INT : CH0_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH0_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH0_CTR_CH0_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH0_CTR_Register is record CH0_CTR : CH0_CTR_CH0_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH0_CTR_Register use record CH0_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH0_CC_A_Field is HAL.UInt16; subtype CH0_CC_B_Field is HAL.UInt16; -- Counter compare values type CH0_CC_Register is record A : CH0_CC_A_Field := 16#0#; B : CH0_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH0_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH0_TOP_CH0_TOP_Field is HAL.UInt16; -- Counter wrap value type CH0_TOP_Register is record CH0_TOP : CH0_TOP_CH0_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH0_TOP_Register use record CH0_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH1_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH1_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH1_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH1_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH1_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH1_DIV_FRAC_Field is HAL.UInt4; subtype CH1_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH1_DIV_Register is record FRAC : CH1_DIV_FRAC_Field := 16#0#; INT : CH1_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH1_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH1_CTR_CH1_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH1_CTR_Register is record CH1_CTR : CH1_CTR_CH1_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH1_CTR_Register use record CH1_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH1_CC_A_Field is HAL.UInt16; subtype CH1_CC_B_Field is HAL.UInt16; -- Counter compare values type CH1_CC_Register is record A : CH1_CC_A_Field := 16#0#; B : CH1_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH1_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH1_TOP_CH1_TOP_Field is HAL.UInt16; -- Counter wrap value type CH1_TOP_Register is record CH1_TOP : CH1_TOP_CH1_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH1_TOP_Register use record CH1_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH2_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH2_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH2_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH2_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH2_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH2_DIV_FRAC_Field is HAL.UInt4; subtype CH2_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH2_DIV_Register is record FRAC : CH2_DIV_FRAC_Field := 16#0#; INT : CH2_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH2_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH2_CTR_CH2_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH2_CTR_Register is record CH2_CTR : CH2_CTR_CH2_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH2_CTR_Register use record CH2_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH2_CC_A_Field is HAL.UInt16; subtype CH2_CC_B_Field is HAL.UInt16; -- Counter compare values type CH2_CC_Register is record A : CH2_CC_A_Field := 16#0#; B : CH2_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH2_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH2_TOP_CH2_TOP_Field is HAL.UInt16; -- Counter wrap value type CH2_TOP_Register is record CH2_TOP : CH2_TOP_CH2_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH2_TOP_Register use record CH2_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH3_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH3_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH3_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH3_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH3_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH3_DIV_FRAC_Field is HAL.UInt4; subtype CH3_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH3_DIV_Register is record FRAC : CH3_DIV_FRAC_Field := 16#0#; INT : CH3_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH3_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH3_CTR_CH3_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH3_CTR_Register is record CH3_CTR : CH3_CTR_CH3_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH3_CTR_Register use record CH3_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH3_CC_A_Field is HAL.UInt16; subtype CH3_CC_B_Field is HAL.UInt16; -- Counter compare values type CH3_CC_Register is record A : CH3_CC_A_Field := 16#0#; B : CH3_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH3_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH3_TOP_CH3_TOP_Field is HAL.UInt16; -- Counter wrap value type CH3_TOP_Register is record CH3_TOP : CH3_TOP_CH3_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH3_TOP_Register use record CH3_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH4_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH4_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH4_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH4_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH4_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH4_DIV_FRAC_Field is HAL.UInt4; subtype CH4_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH4_DIV_Register is record FRAC : CH4_DIV_FRAC_Field := 16#0#; INT : CH4_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH4_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH4_CTR_CH4_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH4_CTR_Register is record CH4_CTR : CH4_CTR_CH4_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH4_CTR_Register use record CH4_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH4_CC_A_Field is HAL.UInt16; subtype CH4_CC_B_Field is HAL.UInt16; -- Counter compare values type CH4_CC_Register is record A : CH4_CC_A_Field := 16#0#; B : CH4_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH4_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH4_TOP_CH4_TOP_Field is HAL.UInt16; -- Counter wrap value type CH4_TOP_Register is record CH4_TOP : CH4_TOP_CH4_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH4_TOP_Register use record CH4_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH5_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH5_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH5_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH5_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH5_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH5_DIV_FRAC_Field is HAL.UInt4; subtype CH5_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH5_DIV_Register is record FRAC : CH5_DIV_FRAC_Field := 16#0#; INT : CH5_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH5_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH5_CTR_CH5_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH5_CTR_Register is record CH5_CTR : CH5_CTR_CH5_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH5_CTR_Register use record CH5_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH5_CC_A_Field is HAL.UInt16; subtype CH5_CC_B_Field is HAL.UInt16; -- Counter compare values type CH5_CC_Register is record A : CH5_CC_A_Field := 16#0#; B : CH5_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH5_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH5_TOP_CH5_TOP_Field is HAL.UInt16; -- Counter wrap value type CH5_TOP_Register is record CH5_TOP : CH5_TOP_CH5_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH5_TOP_Register use record CH5_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH6_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH6_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH6_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH6_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH6_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH6_DIV_FRAC_Field is HAL.UInt4; subtype CH6_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH6_DIV_Register is record FRAC : CH6_DIV_FRAC_Field := 16#0#; INT : CH6_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH6_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH6_CTR_CH6_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH6_CTR_Register is record CH6_CTR : CH6_CTR_CH6_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH6_CTR_Register use record CH6_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH6_CC_A_Field is HAL.UInt16; subtype CH6_CC_B_Field is HAL.UInt16; -- Counter compare values type CH6_CC_Register is record A : CH6_CC_A_Field := 16#0#; B : CH6_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH6_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH6_TOP_CH6_TOP_Field is HAL.UInt16; -- Counter wrap value type CH6_TOP_Register is record CH6_TOP : CH6_TOP_CH6_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH6_TOP_Register use record CH6_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; type CH7_CSR_DIVMODE_Field is (-- Free-running counting at rate dictated by fractional divider DIV, -- Fractional divider operation is gated by the PWM B pin. LEVEL, -- Counter advances with each rising edge of the PWM B pin. RISE, -- Counter advances with each falling edge of the PWM B pin. FALL) with Size => 2; for CH7_CSR_DIVMODE_Field use (DIV => 0, LEVEL => 1, RISE => 2, FALL => 3); -- Control and status register type CH7_CSR_Register is record -- Enable the PWM channel. EN : Boolean := False; -- 1: Enable phase-correct modulation. 0: Trailing-edge PH_CORRECT : Boolean := False; -- Invert output A A_INV : Boolean := False; -- Invert output B B_INV : Boolean := False; DIVMODE : CH7_CSR_DIVMODE_Field := RP_SVD.PWM.DIV; -- After a write operation all bits in the field are cleared (set to -- zero). Retard the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running. PH_RET : Boolean := False; -- After a write operation all bits in the field are cleared (set to -- zero). Advance the phase of the counter by 1 count, while it is -- running.\n Self-clearing. Write a 1, and poll until low. Counter must -- be running\n at less than full speed (div_int + div_frac / 16 > 1) PH_ADV : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH7_CSR_Register use record EN at 0 range 0 .. 0; PH_CORRECT at 0 range 1 .. 1; A_INV at 0 range 2 .. 2; B_INV at 0 range 3 .. 3; DIVMODE at 0 range 4 .. 5; PH_RET at 0 range 6 .. 6; PH_ADV at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CH7_DIV_FRAC_Field is HAL.UInt4; subtype CH7_DIV_INT_Field is HAL.UInt8; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. type CH7_DIV_Register is record FRAC : CH7_DIV_FRAC_Field := 16#0#; INT : CH7_DIV_INT_Field := 16#1#; -- unspecified Reserved_12_31 : HAL.UInt20 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH7_DIV_Register use record FRAC at 0 range 0 .. 3; INT at 0 range 4 .. 11; Reserved_12_31 at 0 range 12 .. 31; end record; subtype CH7_CTR_CH7_CTR_Field is HAL.UInt16; -- Direct access to the PWM counter type CH7_CTR_Register is record CH7_CTR : CH7_CTR_CH7_CTR_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH7_CTR_Register use record CH7_CTR at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype CH7_CC_A_Field is HAL.UInt16; subtype CH7_CC_B_Field is HAL.UInt16; -- Counter compare values type CH7_CC_Register is record A : CH7_CC_A_Field := 16#0#; B : CH7_CC_B_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH7_CC_Register use record A at 0 range 0 .. 15; B at 0 range 16 .. 31; end record; subtype CH7_TOP_CH7_TOP_Field is HAL.UInt16; -- Counter wrap value type CH7_TOP_Register is record CH7_TOP : CH7_TOP_CH7_TOP_Field := 16#FFFF#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CH7_TOP_Register use record CH7_TOP at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- EN_CH array type EN_CH_Field_Array is array (0 .. 7) of Boolean with Component_Size => 1, Size => 8; -- Type definition for EN_CH type EN_CH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CH as a value Val : HAL.UInt8; when True => -- CH as an array Arr : EN_CH_Field_Array; end case; end record with Unchecked_Union, Size => 8; for EN_CH_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- This register aliases the CSR_EN bits for all channels.\n Writing to -- this register allows multiple channels to be enabled\n or disabled -- simultaneously, so they can run in perfect sync.\n For each channel, -- there is only one physical EN register bit,\n which can be accessed -- through here or CHx_CSR. type EN_Register is record CH : EN_CH_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for EN_Register use record CH at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- INTR_CH array type INTR_CH_Field_Array is array (0 .. 7) of Boolean with Component_Size => 1, Size => 8; -- Type definition for INTR_CH type INTR_CH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CH as a value Val : HAL.UInt8; when True => -- CH as an array Arr : INTR_CH_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTR_CH_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Raw Interrupts type INTR_Register is record -- Write data bit of one shall clear (set to zero) the corresponding bit -- in the field. CH : INTR_CH_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTR_Register use record CH at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- INTE_CH array type INTE_CH_Field_Array is array (0 .. 7) of Boolean with Component_Size => 1, Size => 8; -- Type definition for INTE_CH type INTE_CH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CH as a value Val : HAL.UInt8; when True => -- CH as an array Arr : INTE_CH_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTE_CH_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Interrupt Enable type INTE_Register is record CH : INTE_CH_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTE_Register use record CH at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- INTF_CH array type INTF_CH_Field_Array is array (0 .. 7) of Boolean with Component_Size => 1, Size => 8; -- Type definition for INTF_CH type INTF_CH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CH as a value Val : HAL.UInt8; when True => -- CH as an array Arr : INTF_CH_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTF_CH_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Interrupt Force type INTF_Register is record CH : INTF_CH_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTF_Register use record CH at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; -- INTS_CH array type INTS_CH_Field_Array is array (0 .. 7) of Boolean with Component_Size => 1, Size => 8; -- Type definition for INTS_CH type INTS_CH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- CH as a value Val : HAL.UInt8; when True => -- CH as an array Arr : INTS_CH_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTS_CH_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Interrupt status after masking & forcing type INTS_Register is record -- Read-only. CH : INTS_CH_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTS_Register use record CH at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Simple PWM type PWM_Peripheral is record -- Control and status register CH0_CSR : aliased CH0_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH0_DIV : aliased CH0_DIV_Register; -- Direct access to the PWM counter CH0_CTR : aliased CH0_CTR_Register; -- Counter compare values CH0_CC : aliased CH0_CC_Register; -- Counter wrap value CH0_TOP : aliased CH0_TOP_Register; -- Control and status register CH1_CSR : aliased CH1_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH1_DIV : aliased CH1_DIV_Register; -- Direct access to the PWM counter CH1_CTR : aliased CH1_CTR_Register; -- Counter compare values CH1_CC : aliased CH1_CC_Register; -- Counter wrap value CH1_TOP : aliased CH1_TOP_Register; -- Control and status register CH2_CSR : aliased CH2_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH2_DIV : aliased CH2_DIV_Register; -- Direct access to the PWM counter CH2_CTR : aliased CH2_CTR_Register; -- Counter compare values CH2_CC : aliased CH2_CC_Register; -- Counter wrap value CH2_TOP : aliased CH2_TOP_Register; -- Control and status register CH3_CSR : aliased CH3_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH3_DIV : aliased CH3_DIV_Register; -- Direct access to the PWM counter CH3_CTR : aliased CH3_CTR_Register; -- Counter compare values CH3_CC : aliased CH3_CC_Register; -- Counter wrap value CH3_TOP : aliased CH3_TOP_Register; -- Control and status register CH4_CSR : aliased CH4_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH4_DIV : aliased CH4_DIV_Register; -- Direct access to the PWM counter CH4_CTR : aliased CH4_CTR_Register; -- Counter compare values CH4_CC : aliased CH4_CC_Register; -- Counter wrap value CH4_TOP : aliased CH4_TOP_Register; -- Control and status register CH5_CSR : aliased CH5_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH5_DIV : aliased CH5_DIV_Register; -- Direct access to the PWM counter CH5_CTR : aliased CH5_CTR_Register; -- Counter compare values CH5_CC : aliased CH5_CC_Register; -- Counter wrap value CH5_TOP : aliased CH5_TOP_Register; -- Control and status register CH6_CSR : aliased CH6_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH6_DIV : aliased CH6_DIV_Register; -- Direct access to the PWM counter CH6_CTR : aliased CH6_CTR_Register; -- Counter compare values CH6_CC : aliased CH6_CC_Register; -- Counter wrap value CH6_TOP : aliased CH6_TOP_Register; -- Control and status register CH7_CSR : aliased CH7_CSR_Register; -- INT and FRAC form a fixed-point fractional number.\n Counting rate is -- system clock frequency divided by this number.\n Fractional division -- uses simple 1st-order sigma-delta. CH7_DIV : aliased CH7_DIV_Register; -- Direct access to the PWM counter CH7_CTR : aliased CH7_CTR_Register; -- Counter compare values CH7_CC : aliased CH7_CC_Register; -- Counter wrap value CH7_TOP : aliased CH7_TOP_Register; -- This register aliases the CSR_EN bits for all channels.\n Writing to -- this register allows multiple channels to be enabled\n or disabled -- simultaneously, so they can run in perfect sync.\n For each channel, -- there is only one physical EN register bit,\n which can be accessed -- through here or CHx_CSR. EN : aliased EN_Register; -- Raw Interrupts INTR : aliased INTR_Register; -- Interrupt Enable INTE : aliased INTE_Register; -- Interrupt Force INTF : aliased INTF_Register; -- Interrupt status after masking & forcing INTS : aliased INTS_Register; end record with Volatile; for PWM_Peripheral use record CH0_CSR at 16#0# range 0 .. 31; CH0_DIV at 16#4# range 0 .. 31; CH0_CTR at 16#8# range 0 .. 31; CH0_CC at 16#C# range 0 .. 31; CH0_TOP at 16#10# range 0 .. 31; CH1_CSR at 16#14# range 0 .. 31; CH1_DIV at 16#18# range 0 .. 31; CH1_CTR at 16#1C# range 0 .. 31; CH1_CC at 16#20# range 0 .. 31; CH1_TOP at 16#24# range 0 .. 31; CH2_CSR at 16#28# range 0 .. 31; CH2_DIV at 16#2C# range 0 .. 31; CH2_CTR at 16#30# range 0 .. 31; CH2_CC at 16#34# range 0 .. 31; CH2_TOP at 16#38# range 0 .. 31; CH3_CSR at 16#3C# range 0 .. 31; CH3_DIV at 16#40# range 0 .. 31; CH3_CTR at 16#44# range 0 .. 31; CH3_CC at 16#48# range 0 .. 31; CH3_TOP at 16#4C# range 0 .. 31; CH4_CSR at 16#50# range 0 .. 31; CH4_DIV at 16#54# range 0 .. 31; CH4_CTR at 16#58# range 0 .. 31; CH4_CC at 16#5C# range 0 .. 31; CH4_TOP at 16#60# range 0 .. 31; CH5_CSR at 16#64# range 0 .. 31; CH5_DIV at 16#68# range 0 .. 31; CH5_CTR at 16#6C# range 0 .. 31; CH5_CC at 16#70# range 0 .. 31; CH5_TOP at 16#74# range 0 .. 31; CH6_CSR at 16#78# range 0 .. 31; CH6_DIV at 16#7C# range 0 .. 31; CH6_CTR at 16#80# range 0 .. 31; CH6_CC at 16#84# range 0 .. 31; CH6_TOP at 16#88# range 0 .. 31; CH7_CSR at 16#8C# range 0 .. 31; CH7_DIV at 16#90# range 0 .. 31; CH7_CTR at 16#94# range 0 .. 31; CH7_CC at 16#98# range 0 .. 31; CH7_TOP at 16#9C# range 0 .. 31; EN at 16#A0# range 0 .. 31; INTR at 16#A4# range 0 .. 31; INTE at 16#A8# range 0 .. 31; INTF at 16#AC# range 0 .. 31; INTS at 16#B0# range 0 .. 31; end record; -- Simple PWM PWM_Periph : aliased PWM_Peripheral with Import, Address => PWM_Base; end RP_SVD.PWM;
with Interfaces; with Interfaces.C; with Interfaces.C.Pointers; with Interfaces.C.Strings; with System; with USB.Protocol; use Interfaces; use Interfaces.C; use USB.Protocol; package USB.LibUSB1 is ---- Library initialisation and finalisation type Status is ( Error_Not_Supported, Error_No_Mem, Error_Interrupted, Error_Pipe, Error_Overflow, Error_Timeout, Error_Busy, Error_Not_Found, Error_No_Device, Error_Access, Error_Invalid_Param, Error_IO, Success ); for Status use ( -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0 ); pragma Convention(C, Status); type Context_Access is new System.Address; --type Context_Access_Access is access all Context_Access; --pragma Convention(C, Context_Access_Access); type Log_Level is ( None, Error, Warning, Info, Debug ); for Log_Level use ( 0, 1, 2, 3, 4 ); pragma Convention(C, Log_Level); function Init_Lib(Context: access Context_Access) return Status; pragma Import(C, Init_Lib, "libusb_init"); procedure Exit_Lib(Ctx: Context_Access); pragma Import(C, Exit_Lib, "libusb_exit"); procedure Set_Debug(Ctx: Context_Access; Level: Log_Level); pragma Import(C, Set_Debug, "libusb_set_debug"); ---- Device handling and enumeration type ssize_t is range 1-size_t'Modulus/2..size_t'Modulus/2-1; for ssize_t'Size use size_t'Size; pragma Convention(C, ssize_t); type Device_Handle_Access is new System.Address; type Device_Access is new System.Address; type Device_Access_Array is array(ssize_t range <>) of aliased Device_Access; package Device_Access_Lists is new Interfaces.C.Pointers( Index => ssize_t, Element => Device_Access, Element_Array => Device_Access_Array, Default_Terminator => Device_Access(System.Null_Address)); type Speed is ( Speed_Unknown, Speed_Low, Speed_Full, Speed_High, Speed_Super ); for Speed use ( 0, 1, 2, 3, 4 ); pragma Convention(C, Speed); type Bus_Number is mod 2**8; pragma Convention(C, Bus_Number); type Port_Number is mod 2**8; pragma Convention(C, Port_Number); type Port_Number_Array is array(Integer range <>) of aliased Port_Number; package Port_Number_Lists is new Interfaces.C.Pointers( Index => Integer, Element => Port_Number, Element_Array => Port_Number_Array, Default_Terminator => Port_Number'(0)); type Device_Address is mod 2**8; pragma Convention(C, Device_Address); function Get_Device_List(Ctx: Context_Access; List: access Device_Access_Lists.Pointer) return ssize_t; pragma Import(C, Get_Device_List, "libusb_get_device_list"); procedure Free_Device_List(List: Device_Access_Lists.Pointer; Unref_Devices: Int); pragma Import(C, Free_Device_List, "libusb_free_device_list"); function Get_Bus_Number(Dev: Device_Access) return Bus_Number; pragma Import(C, Get_Bus_Number, "libusb_get_bus_number"); function Get_Port_Number(Dev: Device_Access) return Port_Number; pragma Import(C, Get_Port_Number, "libusb_get_port_number"); function Get_Port_Numbers(Dev: Device_Access; Port_Numbers: Port_Number_Lists.Pointer; Port_Numbers_Len: Integer) return int; pragma Import(C, Get_Port_Numbers, "libusb_get_port_numbers"); function Get_Port_Path(Ctx: Context_Access; Dev: Device_Access; Port_Numbers: Port_Number_Lists.Pointer; Port_Numbers_Len: Integer) return Integer; pragma Import(C, Get_Port_Path, "libusb_get_port_path"); function Get_Parent(Dev: Device_Access) return Device_Access; pragma Import(C, Get_Parent, "libusb_get_parent"); function Get_Device_Address(Dev: Device_Access) return Device_Address; pragma Import(C, Get_Device_Address, "libusb_get_device_address"); function Get_Device_Speed(Dev: Device_Access) return Speed; pragma Import(C, Get_Device_Speed, "libusb_get_device_speed"); function Get_Max_Packet_Size(Dev: Device_Access; Endpoint: unsigned_char) return int; -- ?? endpoint address? pragma Import(C, Get_Max_Packet_Size, "libusb_get_max_packet_size"); function Get_Max_Iso_Packet_Size(Dev: Device_Access; Endpoint: unsigned_char) return int; pragma Import(C, Get_Max_Iso_Packet_Size, "libusb_get_max_iso_packet_size"); function Ref_Device(Dev: Device_Access) return Device_Access; pragma Import(C, Ref_Device, "libusb_ref_device"); procedure Unref_Device(Dev: Device_Access); pragma Import(C, Unref_Device, "libusb_unref_device"); function Open(Dev: Device_Access; Handle: access Device_Handle_Access) return Status; pragma Import(C, Open, "libusb_open"); function Open_Device_with_VID_PID(Ctx: Context_Access; VID: USB.Protocol.Vendor_Id; PID: USB.Protocol.Product_Id) return Device_Handle_Access; pragma Import(C, Open_Device_with_VID_PID, "libusb_open_device_with_vid_pid"); procedure Close(Dev_Handle: Device_Handle_Access); pragma Import(C, Close, "libusb_close"); function Get_Device(Dev_Handle: Device_Handle_Access) return Device_Access; pragma Import(C, Get_Device, "libusb_get_device"); function Get_Configuration(Dev: Device_Handle_Access; Config: access int) return Status; pragma Import(C, Get_Configuration, "libusb_get_configuration"); function Set_Configuration(Dev: Device_Handle_Access; Configuration: int) return Status; pragma Import(C, Set_Configuration, "libusb_set_configuration"); function Claim_Interface(Dev: Device_Handle_Access; Interface_Number: int) return Status; pragma Import(C, Claim_Interface, "libusb_claim_interface"); function Release_Interface(Dev: Device_Handle_Access; Interface_Number: int) return Status; pragma Import(C, Release_Interface, "libusb_release_interface"); function Set_Interface_Alt_Setting(Dev: Device_Handle_Access; Interface_Number: int; Alternate_Setting: int) return Status; pragma Import(C, Set_Interface_Alt_Setting, "libusb_set_interface_alt_setting"); function Clear_Halt(Dev: Device_Handle_Access; Endpoint: int) return Status; pragma Import(C, Clear_Halt, "libusb_clear_halt"); function Reset_Device(Dev: Device_Handle_Access) return Status; pragma Import(C, Reset_Device, "libusb_reset_device"); function Kernel_Driver_Active(Dev: Device_Handle_Access; Interface_Number: int) return int; pragma Import(C, Kernel_Driver_Active, "libusb_kernel_driver_active"); function Detach_Kernel_Driver(Dev: Device_Handle_Access; Interface_Number: int) return Status; pragma Import(C, Detach_Kernel_Driver, "libusb_detach_kernel_driver"); function Attach_Kernel_Driver(Dev: Device_Handle_Access; Interface_Number: int) return Status; pragma Import(C, Attach_Kernel_Driver, "libusb_attach_kernel_driver"); function Set_Auto_Detach_Kernel_Driver(Dev: Device_Handle_Access; Enable: int) return Status; pragma Import(C, Set_Auto_Detach_Kernel_Driver, "libusb_set_auto_detach_kernel_driver"); ---- Miscellaneus API_Version: constant Integer := 16#01000104#; type Lib_Capability is ( Cap_Has_Capability, Cap_Has_Hotplug, Cap_Has_HID_Access, Cap_Supports_Detach_Kernel_Driver ); for Lib_Capability use ( 16#0000#, 16#0001#, 16#0100#, 16#0101# ); pragma Convention(C, Lib_Capability); type Version_Number is mod 2**16 with Size => 16, Convention => C; type Lib_Version is record Major, Minor, Micro, Nano: Version_Number; Rc, Describe: Strings.chars_ptr; end record; function Has_Capability(Capability: Lib_Capability) return int; pragma Import(C, Has_Capability, "libusb_has_capability"); function Error_Name(Error_Code: int) return Strings.chars_ptr; pragma Import(C, Error_Name, "libusb_error_name"); function Get_Version return access constant Lib_Version; pragma Import(C, Get_Version, "libusb_get_version"); function SetLocale(Locale: Strings.chars_ptr) return Status; pragma Import(C, SetLocale, "libusb_setlocale"); function StrError(errcode: Status) return Strings.chars_ptr; pragma Import(C, StrError, "libusb_strerror"); ---- Descriptors type Transfer_Type is ( Transfer_Type_Control, Transfer_Type_Isochronous, Transfer_Type_Bulk, Transfer_Type_Interrupt, Transfer_Type_Bulk_Stream ); for Transfer_Type use ( 0, 1, 2, 3, 4 ); pragma Convention(C, Transfer_Type); -- Those records corresponds to USB standard ones, -- except several fields added by LibUSB. -- Including standard record as element of this -- could break compatibility due to C alignment issues. type Endpoint_Descriptor is record -- Descriptor: USB.Protocol.Endpoint_Descriptor; bLength: Unsigned_8; bDescriptorType: Descriptor_Type; bEndpointAddress: Endpoint_Address; bmAttributes: Endpoint_Descriptors.Attributes; wMaxPacketSize: Unsigned_16; bInterval: Unsigned_8; bRefresh: Unsigned_8; bSynchAddress: Unsigned_8; Extra: System.Address; Extra_Length: Integer; end record; pragma Convention(C, Endpoint_Descriptor); type Endpoint_Descriptor_Array is array(Integer range <>) of aliased Endpoint_Descriptor; Endpoint_Descriptor_Default_Terminator: constant Endpoint_Descriptor := ( 0, DT_Endpoint, 0, ( Endpoint_Descriptors.Transfer_Type_Control, Endpoint_Descriptors.Iso_Sync_Type_None, Endpoint_Descriptors.Iso_Usage_Type_Data ), 0, 0, 0, 0, System.Null_Address, 0 ); -- just for pointers to compile package Endpoint_Descriptor_Lists is new Interfaces.C.Pointers( Index => Integer, Element => Endpoint_Descriptor, Element_Array => Endpoint_Descriptor_Array, Default_Terminator => Endpoint_Descriptor_Default_Terminator); type Interface_Descriptor is record -- Descriptor: USB.Protocol.Interface_Descriptor; bLength: Unsigned_8; bDescriptorType: Descriptor_Type; bInterfaceNumber: Unsigned_8; bAlternateSetting: Unsigned_8; bNumEndpoints: Unsigned_8; bInterfaceClass: Class_Code; bInterfaceSubClass: Unsigned_8; bInterfaceProtocol: Unsigned_8; iInterface: Unsigned_8; Endpoint: Endpoint_Descriptor_Lists.Pointer; Extra: System.Address; Extra_Length: Integer; end record; pragma Convention(C, Interface_Descriptor); type Interface_List is record AltSetting: Endpoint_Descriptor_Lists.Pointer; Num_AltSetting: Integer; end record; type Configuration_Descriptor is record -- Descriptor: USB.Protocol.Configuration_Descriptor; bLength: Unsigned_8; bDescriptorType: Descriptor_Type; wTotalLength: Unsigned_16; bNumInterfaces: Unsigned_8; bConfigurationValue: Unsigned_8; iConfiguration: Unsigned_8; bmAttributes: Configuration_Descriptors.Attributes; bMaxPower: Unsigned_8; Interface_List: LibUSB1.Interface_List; Extra: System.Address; Extra_Length: Integer; end record; pragma Convention(C, Configuration_Descriptor); type Configuration_Descriptor_Access is access all Configuration_Descriptor; pragma Convention(C, Configuration_Descriptor_Access); type SS_Endpoint_Companion_Descriptor_Access is access all Superspeed_Endpoint_Companion_Descriptor; pragma Convention(C, SS_Endpoint_Companion_Descriptor_Access); type BOS_Descriptor_Access is access all BOS_Descriptor; pragma Convention(C, BOS_Descriptor_Access); type USB_2_0_Extension_Descriptor_Access is access all USB_2_0_Extension_Descriptor; pragma Convention(C, USB_2_0_Extension_Descriptor_Access); type SS_USB_Device_Capability_Descriptor_Access is access all Superspeed_USB_Device_Capability_Descriptor; pragma Convention(C, SS_USB_Device_Capability_Descriptor_Access); type Container_Id_Descriptor_Access is access all Container_Id_Descriptor; pragma Convention(C, Container_Id_Descriptor_Access); function Get_Device_Descriptor( Dev: Device_Access; Desc: out Device_Descriptor ) return Status; pragma Import(C, Get_Device_Descriptor, "libusb_get_device_descriptor"); function Get_Active_Config_Descriptor( Dev: Device_Access; Config: access Configuration_Descriptor_Access ) return Status; pragma Import(C, Get_Active_Config_Descriptor, "libusb_get_active_config_descriptor"); function Get_Config_Descriptor( Dev: Device_Access; Config_Index: Unsigned_8; Config: out Configuration_Descriptor_Access ) return Status; pragma Import(C, Get_Config_Descriptor, "libusb_get_config_descriptor"); function Get_Config_Descriptor_by_Value( Dev: Device_Access; bConfigurationValue: Unsigned_8; Config: out Configuration_Descriptor_Access ) return Status; pragma Import(C, Get_Config_Descriptor_by_Value, "libusb_get_config_descriptor_by_value"); procedure Free_Config_Descriptor(Config: Configuration_Descriptor_Access); pragma Import(C, Free_Config_Descriptor, "libusb_free_config_descriptor"); function Get_SS_Endpoint_Companion_Descriptor( Ctx: Context_Access; Endpoint: access constant Endpoint_Descriptor; Ep_Comp: out SS_Endpoint_Companion_Descriptor_Access ) return Status; pragma Import(C, Get_SS_Endpoint_Companion_Descriptor, "libusb_get_ss_endpoint_companion_descriptor"); procedure Free_SS_Endpoint_Companion_Descriptor( Ep_Comp: SS_Endpoint_Companion_Descriptor_Access ); pragma Import(C, Free_SS_Endpoint_Companion_Descriptor, "libusb_free_ss_endpoint_companion_descriptor"); function Get_BOS_Descriptor( Handle: Device_Handle_Access; BOS: out BOS_Descriptor_Access ) return Status; pragma Import(C, Get_BOS_Descriptor, "libusb_get_bos_descriptor"); procedure Free_BOS_Descriptor(BOS: BOS_Descriptor_Access); pragma Import(C, Free_BOS_Descriptor, "libusb_free_bos_descriptor"); function Get_USB_2_0_Extension_Descriptor( Ctx: Context_Access; Dev_Cap: access BOS_Device_Capability_Descriptor; USB_2_0_Extension: out USB_2_0_Extension_Descriptor_Access ) return Status; pragma Import(C, Get_USB_2_0_Extension_Descriptor, "libusb_get_usb_2_0_endpoint_descriptor"); procedure Free_USB_2_0_Extension_Descriptor( USB_2_0_Extension: USB_2_0_Extension_Descriptor_Access ); pragma Import(C, Free_USB_2_0_Extension_Descriptor, "libusb_free_usb_2_0_extension_descriptor"); function Get_SS_USB_Device_Capability_Descriptor( Ctx: Context_Access; Dev_Cap: access BOS_Device_Capability_Descriptor; SS_USB_Device_Cap: out SS_USB_Device_Capability_Descriptor_Access ) return Status; pragma Import(C, Get_SS_USB_Device_Capability_Descriptor, "libusb_get_ss_usb_device_capability_descriptor"); procedure Free_SS_USB_Device_Capability_Descriptor( SS_USB_Device_Cap: SS_USB_Device_Capability_Descriptor_Access ); pragma Import(C, Free_SS_USB_Device_Capability_Descriptor, "libusb_free_ss_usb_device_capability_descriptor"); function Get_Container_Id_Descriptor( Ctx: Context_Access; Dev_Cap: access BOS_Device_Capability_Descriptor; Container_Id: out Container_Id_Descriptor_Access ) return Status; pragma Import(C, Get_Container_Id_Descriptor, "libusb_get_container_id_descriptor"); procedure Free_Container_Id_Descriptor( Container_Id: Container_Id_Descriptor_Access ); pragma Import(C, Free_Container_id_Descriptor, "libusb_free_container_id_descriptor"); function Get_String_Descriptor_ASCII( Dev: Device_Handle_Access; Desc_Index: Unsigned_8; Data: Char_Array; Length: int ) return int; pragma Import(C, Get_String_Descriptor_ASCII, "libusb_get_string_descriptor_ascii"); ---- Device hotplug event notification Hotplug_Match_Any: constant Integer := -1; type Hotplug_Callback_Handle is new Integer; type Hotplug_Event is ( Hotplug_Event_Device_Arrived, Hotplug_Event_Device_Left ); for Hotplug_Event use ( Hotplug_Event_Device_Arrived => 16#01#, Hotplug_Event_Device_Left => 16#02# ); pragma Convention(C, Hotplug_Event); type Hotplug_Flag is new Unsigned; -- cannot make it stucture Hotplug_No_Flags: constant Hotplug_Flag := 0; Hotplug_Enumerate: constant Hotplug_Flag := 1 * 2**0; type Hotplug_Callback_Fn is access function( Ctx: Context_Access; Device: Device_Access; Event: Hotplug_Event; User_Data: System.Address ) return int; pragma Convention(C, Hotplug_Callback_Fn); function Hotplug_Register_Callback( Ctx: Context_Access; events: Hotplug_Event; flags: Hotplug_Flag; Vendor: int; Product: int; Dev_Class: int; Cb_Fn: Hotplug_Callback_Fn; User_Data: System.Address; Handle: out Hotplug_Callback_Handle ) return Status; pragma Import(C, Hotplug_Register_Callback, "libusb_hotplug_register_callback"); function Hotplug_Deregister_Callback( Ctx: Context_Access; Handle: Hotplug_Callback_Handle ) return Status; pragma Import(C, Hotplug_Deregister_Callback, "libusb_hotplug_deregister_callback"); ---- Asynchronous device I/O type Transfer_Status is ( Transfer_Completed, Transfer_Error, Transfer_Timed_Out, Transfer_Cancelled, Transfer_Stall, Transfer_No_Device, Transfer_Overflow ); pragma Convention(C, Transfer_Status); type Iso_Packet_Descriptor is record Length: unsigned; Actual_Length: unsigned; Status: Transfer_Status; end record; pragma Convention(C, Iso_Packet_Descriptor); type Transfer_Flags is record Short_Not_Ok: Boolean; Free_Buffer: Boolean; Free_Transfer: Boolean; Add_Zero_Packet: Boolean; end record; for Transfer_Flags use record Short_Not_Ok at 0 range 0 .. 0; Free_Buffer at 0 range 1 .. 1; Free_Transfer at 0 range 2 .. 2; Add_Zero_Packet at 0 range 3 .. 3; end record; for Transfer_Flags'Size use 8; pragma Convention(C_Pass_by_Copy, Transfer_Flags); type Transfer; type Transfer_Cb_Fn is access procedure(A_Transfer: Transfer); pragma Convention(C, Transfer_Cb_Fn); type Iso_Packet_Descriptor_Array is array (0 .. -1) of Iso_Packet_Descriptor; type Transfer is record Dev_Handle: Device_Handle_Access; Flags: Transfer_Flags; Endpoint: Unsigned_8; A_Type: Unsigned_8; -- Transfer_type Timeout: Unsigned; Status: Transfer_Status; Length: int; Actual_Length: int; Callback: Transfer_Cb_Fn; User_Data: System.Address; Buffer: System.Address; Num_Iso_Packets: int; Iso_Packet_Desc: Iso_Packet_Descriptor_Array; end record; pragma Convention(C, Transfer); type Transfer_Access is access Transfer; function Alloc_Streams( Dev: Device_Handle_Access; Num_Streams: Unsigned_32; Endpoints: System.Address; Num_Endpoints: int ) return int; pragma Import(C, Alloc_Streams, "libusb_alloc_streams"); function Free_Streams( Dev: Device_Handle_Access; Endpoints: System.Address; Num_Endpoints: int ) return int; pragma Import(C, Free_Streams, "libusb_free_streams"); function Alloc_Transfer( Iso_Packets: int ) return Transfer_Access; pragma Import(C, Alloc_Transfer, "libusb_alloc_transfer"); procedure Free_Transfer( A_Transfer: Transfer_Access ); pragma Import(C, Free_Transfer, "libusb_free_transfer"); function Submit_Transfer( A_Transfer: Transfer_Access ) return int; pragma Import(C, Submit_Transfer, "libusb_submit_transfer"); function Cancel_Transfer( A_Transfer: Transfer_Access ) return int; pragma Import(C, Cancel_Transfer, "libusb_cancel_transfer"); procedure Transfer_Set_Stream_Id( A_Transfer: Transfer_Access; Stream_Id: Unsigned_32 ); pragma Import(C, Transfer_Set_Stream_Id, "libusb_transfer_set_stream_id"); function Transfer_Get_Stream_Id( A_Transfer: Transfer_Access ) return Unsigned_32; pragma Import(C, Transfer_Get_Stream_Id, "libusb_transfer_get_stream_id"); ---- Polling and timing type PollFD is record FD: int; Events: short; end record; pragma Convention(C, PollFD); type PollFD_Access is access constant PollFD; pragma Convention(C, PollFD_Access); type PollFD_Access_Array is array(Integer range <>) of aliased PollFD_Access; package PollFD_Access_Lists is new Interfaces.C.Pointers( Index => Integer, Element => PollFD_Access, Element_Array => PollFD_Access_Array, Default_Terminator => null); type PollFD_Added_Cb is access procedure( FD: int; Events: short; User_Data: System.Address ); pragma Convention(C, PollFD_Added_Cb); type PollFD_Removed_Cb is access procedure( FD: int; User_Data: System.Address ); pragma Convention(C, PollFD_Removed_Cb); function Try_Lock_Events( Ctx: Context_Access ) return int; pragma Import(C, Try_Lock_Events, "libusb_try_lock_events"); procedure Lock_Events( Ctx: Context_Access ); pragma Import(C, Lock_Events, "libusb_lock_events"); procedure Unlock_Events( Ctx: Context_Access ); pragma Import(C, Unlock_Events, "libusb_unlock_events"); function Event_Handling_Ok( Ctx: Context_Access ) return int; pragma Import(C, Event_Handling_Ok, "libusb_event_handling_ok"); function Event_Handler_Active( Ctx: Context_Access ) return int; pragma Import(C, Event_Handler_Active, "libusb_event_handler_active"); procedure Lock_Event_Waiters( Ctx: Context_Access ); pragma Import(C, Lock_Event_Waiters, "libusb_lock_event_waiters"); procedure Unlock_Event_Waiters( Ctx: Context_Access ); pragma Import(C, Unlock_Event_Waiters, "libusb_unlock_event_waiters"); type Timeval_Access is new System.Address; -- TODO: actual timeval function Wait_For_Event( Ctx: Context_Access; Tv: Timeval_Access ) return int; pragma Import(C, Wait_For_Event, "libusb_wait_for_event"); function Handle_Events_Timeout_Completed( Ctx: Context_Access; Tv: Timeval_Access; Completed: in out int ) return int; pragma Import(C, Handle_Events_Timeout_Completed, "libusb_handle_events_timeout_completed"); function Handle_Events_Timeout( Ctx: Context_Access; Tv: Timeval_Access ) return int; pragma Import(C, Handle_Events_Timeout, "libusb_handle_events_timeout"); function Handle_Events( Ctx: Context_Access ) return int; pragma Import(C, Handle_Events, "libusb_handle_events"); function Handle_Events_Completed( Ctx: Context_Access; Completed: in out int ) return int; pragma Import(C, Handle_Events_Completed, "libusb_handle_events_completed"); function Handle_Events_Locked( Ctx: Context_Access; Tv: Timeval_Access ) return int; pragma Import(C, Handle_Events_Locked, "libusb_handle_events_locked"); function PollFDs_Handle_Timeouts( Ctx: Context_Access ) return int; pragma Import(C, PollFDs_Handle_Timeouts, "libusb_pollfds_handle_timeouts"); function Get_Next_Timeout( Ctx: Context_Access; Tv: Timeval_Access ) return int; pragma Import(C, Get_Next_Timeout, "libusb_get_next_timeout"); procedure Set_PollFD_Notifiers( Ctx: Context_Access; Added_Cb: PollFD_Added_Cb; Removed_Cb: PollFD_Removed_Cb; User_Data: System.Address ); pragma Import(C, Set_PollFD_Notifiers, "libusb_set_pollfd_notifiers"); function Get_PollFDs( Ctx: Context_Access ) return PollFD_Access_Lists.Pointer; pragma Import(C, Get_PollFDs, "libusb_get_pollfds"); procedure Free_PollFDs( PollFDs: PollFD_Access_Lists.Pointer ); pragma Import(C, Free_PollFDs, "libusb_free_pollfds"); ---- Synchronous deivce I/O function Control_Transfer( Dev_Handle: Device_Handle_Access; bmRequestType: Request_Type; bRequest: Request_Code; wValue: Unsigned_16; wIndex: Unsigned_16; data: System.Address; wLength: Unsigned_16; Timeout: Unsigned ) return Integer; pragma Import(C, Control_Transfer, "libusb_control_transfer"); function Bulk_Transfer( Dev_Handle: Device_Handle_Access; Endpoint: Unsigned_Char; Data: System.Address; Length: Integer; Transferres: out Integer; Timeout: Unsigned ) return Integer; pragma Import(C, Bulk_Transfer, "libusb_bulk_transfer"); function Interrupt_Transfer( Dev_Handle: Device_Handle_Access; Endpoint: Unsigned_Char; Data: System.Address; Length: Integer; Transferres: out Integer; Timeout: Unsigned ) return Integer; pragma Import(C, Interrupt_Transfer, "libusb_interrupt_transfer"); end USB.LibUSB1;
with u1; package u3 is type t is new u1.t; end u3;
with Interfaces.C.Strings; use Interfaces.C.Strings; package body Pigpio_Ada is Pi_Library_Call_Failed : exception; -- IN GNAT, the standard predefined Ada types correspond to the Standard C -- types -- Essential -- ... procedure PiGpioInitialise is function GpioInitialise return Integer; pragma Import(C, GpioInitialise, External_Name => "gpioInitialise"); Result : Integer := GpioInitialise; begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiGpioInitialise; -- ... procedure PiGpioTerminate is procedure GpioTerminate; pragma Import(C, gpioTerminate, External_Name => "gpioTerminate"); begin GpioTerminate; end PiGpioTerminate; -- Beginner -- ... procedure PiGpioSetMode (gpio : in GPIO_Range; mode : in GPIO_Mode) is function GpioSetMode (g, m : Integer) return Integer; pragma Import(C, GpioSetMode, External_Name => "gpioSetMode"); Result : Integer := GpioSetMode(gpio, mode); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiGpioSetMode; -- ... function PiGpioGetMode (gpio : GPIO_Range) return GPIO_Mode is function GpioGetMode (g : Integer) return Integer; pragma Import(C, GpioGetMode, External_Name => "gpioGetMode"); Result : Integer := GpioGetMode(gpio); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; return GPIO_Mode(Result); end PiGpioGetMode; -- ... procedure PiGpioSetPullUpDown (gpio : in GPIO_Range; pud : in GPIO_PUD) is function GpioSetPullUpDown (g, pud : Integer) return Integer; pragma Import(C, GpioSetPullUpDown, External_Name => "gpioSetPullUpDown"); Result : Integer := GpioSetPullUpDown(gpio, pud); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiGpioSetPullUpDown; -- ... function PiGpioRead (gpio : GPIO_Range) return GPIO_Level is function GpioRead (g : Integer) return Integer; pragma Import(C, GpioRead, External_Name => "gpioRead"); Result : Integer := GpioRead(gpio); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; return GPIO_Level(Result); end PiGpioRead; -- ... procedure PiGpioWrite (gpio : in GPIO_Range; level : in GPIO_Level ) is function GpioWrite(g, lv : Integer) return Integer; pragma Import (C, GpioWrite, External_Name => "gpioWrite"); Result : Integer := GpioWrite(gpio, level); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiGpioWrite; -- ... procedure PiGpioSetTimerFunc (time, millis : in Natural; callback : access procedure) is function GpioSetTimerFunc (tm, ms : Integer; cb : access procedure) return Integer; pragma Import(C, GpioSetTimerFunc, External_Name => "gpioSetTimerFunc"); Result : Integer := GpioSetTimerFunc (time, millis, callback); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Integer(Result)) & " )"; end if; end PiGpioSetTimerFunc; -- Serial -- ... function PiSerOpen(sertty : String; baud : SpeedSelection; serFlags : Natural := 0) return Handle is -- The baud rate must be one of 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, -- 4800, 9600, 19200, 38400, 57600, 115200 or 230400. function SerOpen(stty : chars_ptr; bd, flgs : Integer) return Integer; pragma Import (C, SerOpen, External_Name => "serOpen"); CChars : chars_ptr := New_String(sertty); Ser_Handle : Integer := SerOpen(CChars, Speed(baud), serFlags); begin Free(CChars); if Ser_Handle < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Ser_Handle) & " )"; end if; return Handle(Ser_Handle); end PiSerOpen; -- ... procedure PiSerClose(hdl : in Handle) is function SerClose (h : Integer) return Integer; pragma Import (C, SerClose, External_Name => "serClose"); Result : Integer := SerClose(hdl); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiSerClose; -- ... procedure PiSerWriteByte(hdl: in Handle; value: in UByte) is function SerWriteByte(h, v : Integer) return Integer; pragma Import (C, SerWriteByte, External_Name => "serWriteByte"); Result : Integer := SerWriteByte(hdl, value); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiSerWriteByte; -- ... function PiSerReadByte(hdl : Handle) return UByte is function SerReadByte(h : Integer) return Integer; pragma Import (C, SerReadByte, External_Name => "serReadByte"); Result : Integer := SerReadByte(hdl); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; return UByte(Result); end PiSerReadByte; -- Utilities -- ... function PiGpioVersion return Positive is function GpioVersion return Integer; pragma Import(C, GpioVersion, external_Name => "gpioVersion"); Result : Integer := GpioVersion; begin return Positive(GpioVersion); end PiGpioVersion; -- ... procedure PiGpioSleep (timetype : in Time_Type; seconds : in Natural; micros : in Natural) is function GpioSleep(typ, s, mis : Integer) return Integer; pragma Import(C, GpioSleep, External_name => "gpioSleep"); Result : Integer := GpioSleep(timetype, seconds, micros); begin if Result < 0 then raise Pi_Library_Call_Failed with "Library call failed for pigpio (" & Integer'Image(Result) & " )"; end if; end PiGpioSleep; end Pigpio_Ada;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; with Ada.Characters.Handling; with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Directories; with Ada.Text_IO; with GNAT.Perfect_Hash_Generators; package body Natools.Static_Hash_Maps is package String_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (String); procedure Add_Categorization (Path : in String; Categorization : in Package_Categorization); function File_Name (Package_Name : in String) return String; -- Convert a package name into a file name, the GNAT way function Image (Pos : Natural) return String; -- Trimmed image, for suffix construction function Image (Offset : Ada.Calendar.Time_Zones.Time_Offset) return String; procedure Put_Categorization (Output : in Ada.Text_IO.File_Type; Categorization : in Package_Categorization; Name : in String := ""); procedure Write_Map_Body (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type); procedure Write_Map_Hash_Package (Map : in Map_Description); procedure Write_Map_Private_Spec (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type); procedure Write_Map_Public_Spec (Map : in Map_Description; File : in Ada.Text_IO.File_Type); procedure Write_Map_With (Map : in Map_Description; File : in Ada.Text_IO.File_Type); -- Output fragments relevant for the given map procedure Write_Package (Pkg : in Map_Package; Spec_File, Body_File : in Ada.Text_IO.File_Type; Test : in Boolean := False); -- Output a complete map package procedure Write_Test (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type); -- Output test loop for the hash function ------------------------ -- Package Generators -- ------------------------ procedure Add_Categorization (Path : in String; Categorization : in Package_Categorization) is File : Ada.Text_IO.File_Type; Matches : Natural := 0; Contents : String_Lists.List; begin if Categorization = Default_Categorization then return; end if; Ada.Text_IO.Open (File, Ada.Text_IO.In_File, Path); while not Ada.Text_IO.End_Of_File (File) loop Contents.Append (Ada.Text_IO.Get_Line (File)); end loop; Ada.Text_IO.Close (File); Ada.Text_IO.Open (File, Ada.Text_IO.Out_File, Path); for Line of Contents loop Ada.Text_IO.Put_Line (File, Line); if Line'Length >= 8 and then Line (Line'First .. Line'First + 7) = "package " and then Line (Line'Last - 2 .. Line'Last) = " is" then Matches := Matches + 1; Put_Categorization (File, Categorization); end if; end loop; Ada.Text_IO.Close (File); pragma Assert (Matches = 1); end Add_Categorization; function File_Name (Package_Name : in String) return String is Result : String := Ada.Characters.Handling.To_Lower (Package_Name); begin for I in Result'Range loop if Result (I) = '.' then Result (I) := '-'; end if; end loop; return Result; end File_Name; function Image (Pos : Natural) return String is Result : constant String := Natural'Image (Pos); begin pragma Assert (Result (Result'First) = ' '); return Result (Result'First + 1 .. Result'Last); end Image; function Image (Offset : Ada.Calendar.Time_Zones.Time_Offset) return String is use type Ada.Calendar.Time_Zones.Time_Offset; H : constant Natural := Natural (abs Offset) / 60; M : constant Natural := Natural (abs Offset) mod 60; Sign : Character := '+'; begin if Offset < 0 then Sign := '-'; end if; return String'(1 => Sign, 2 => Character'Val (48 + H / 10), 3 => Character'Val (48 + H mod 10), 4 => Character'Val (48 + M / 10), 5 => Character'Val (48 + M mod 10)); end Image; procedure Put_Categorization (Output : in Ada.Text_IO.File_Type; Categorization : in Package_Categorization; Name : in String := "") is function Prefix return String; function Suffix return String; function Prefix return String is begin if Name = "" then return " pragma "; else return "pragma "; end if; end Prefix; function Suffix return String is begin if Name = "" then return ""; else return " (" & Name & ')'; end if; end Suffix; begin case Categorization is when Pure => Ada.Text_IO.Put_Line (Output, Prefix & "Pure" & Suffix & ';'); when Preelaborate => Ada.Text_IO.Put_Line (Output, Prefix & "Preelaborate" & Suffix & ';'); when Default_Categorization => null; end case; end Put_Categorization; procedure Write_Map_Body (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type) is begin if Map.Indefinite then Ada.Text_IO.Put_Line (File, " function " & Prefix & "_Elements (Hash : " & Prefix & "_Hash)"); Ada.Text_IO.Put_Line (File, " return " & To_String (Map.Element_Type) & " is"); Ada.Text_IO.Put_Line (File, " begin"); Ada.Text_IO.Put_Line (File, " case Hash is"); declare Pos : Natural := 0; Cursor : Node_Lists.Cursor := Map.Nodes.First; begin while Node_Lists.Has_Element (Cursor) loop Ada.Text_IO.Put_Line (File, " when " & Image (Pos) & " =>"); Ada.Text_IO.Put_Line (File, " return " & To_String (Node_Lists.Element (Cursor).Name) & ';'); Node_Lists.Next (Cursor); Pos := Pos + 1; end loop; end; Ada.Text_IO.Put_Line (File, " end case;"); Ada.Text_IO.Put_Line (File, " end " & Prefix & "_Elements;"); Ada.Text_IO.New_Line (File); end if; Ada.Text_IO.Put_Line (File, " function " & To_String (Map.Function_Name) & " (Key : String) return " & To_String (Map.Element_Type) & " is"); Ada.Text_IO.Put_Line (File, " N : constant Natural"); Ada.Text_IO.Put_Line (File, " := " & To_String (Map.Hash_Package_Name) & ".Hash (Key);"); Ada.Text_IO.Put_Line (File, " begin"); Ada.Text_IO.Put_Line (File, " if " & Prefix & "_Keys (N).all = Key then"); Ada.Text_IO.Put_Line (File, " return " & Prefix & "_Elements (N);"); Ada.Text_IO.Put_Line (File, " else"); if To_String (Map.Not_Found) /= "" then Ada.Text_IO.Put_Line (File, " return " & To_String (Map.Not_Found) & ';'); else Ada.Text_IO.Put_Line (File, " raise Constraint_Error " & "with ""Key """""" & Key & """""" not in map"";"); end if; Ada.Text_IO.Put_Line (File, " end if;"); Ada.Text_IO.Put_Line (File, " end " & To_String (Map.Function_Name) & ';'); end Write_Map_Body; procedure Write_Map_Hash_Package (Map : in Map_Description) is Seed : Natural := 2; NK : constant Float := Float (Map.Nodes.Length); NV : Natural := Natural (Map.Nodes.Length) * 2 + 1; Cursor : Node_Lists.Cursor := Map.Nodes.First; begin while Node_Lists.Has_Element (Cursor) loop GNAT.Perfect_Hash_Generators.Insert (To_String (Node_Lists.Element (Cursor).Key)); Node_Lists.Next (Cursor); end loop; loop begin GNAT.Perfect_Hash_Generators.Initialize (Seed, Float (NV) / NK); GNAT.Perfect_Hash_Generators.Compute; exit; exception when GNAT.Perfect_Hash_Generators.Too_Many_Tries => null; end; Seed := Seed * NV; begin GNAT.Perfect_Hash_Generators.Initialize (Seed, Float (NV) / NK); GNAT.Perfect_Hash_Generators.Compute; exit; exception when GNAT.Perfect_Hash_Generators.Too_Many_Tries => null; end; NV := NV + 1; Seed := NV; end loop; GNAT.Perfect_Hash_Generators.Produce (To_String (Map.Hash_Package_Name)); GNAT.Perfect_Hash_Generators.Finalize; exception when others => GNAT.Perfect_Hash_Generators.Finalize; raise; end Write_Map_Hash_Package; procedure Write_Map_Private_Spec (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type) is Last : constant Natural := Positive (Map.Nodes.Length) - 1; Pos : Natural; Cursor : Node_Lists.Cursor; begin Pos := 0; Cursor := Map.Nodes.First; while Node_Lists.Has_Element (Cursor) loop Ada.Text_IO.Put_Line (File, " " & Prefix & "_Key_" & Image (Pos) & " : aliased constant String := """ & To_String (Node_Lists.Element (Cursor).Key) & """;"); Pos := Pos + 1; Node_Lists.Next (Cursor); end loop; Ada.Text_IO.Put_Line (File, " " & Prefix & "_Keys : constant array (0 .. " & Image (Last) & ") of access constant String"); Pos := 0; Cursor := Map.Nodes.First; while Node_Lists.Has_Element (Cursor) loop if Pos = 0 then Ada.Text_IO.Put (File, " := ("); else Ada.Text_IO.Put (File, " "); end if; Ada.Text_IO.Put (File, Prefix & "_Key_" & Image (Pos) & "'Access"); if Pos = Last then Ada.Text_IO.Put_Line (File, ");"); else Ada.Text_IO.Put_Line (File, ","); end if; Pos := Pos + 1; Node_Lists.Next (Cursor); end loop; if Map.Indefinite then Ada.Text_IO.Put_Line (File, " subtype " & Prefix & "_Hash is Natural range 0 .. " & Image (Last) & ';'); Ada.Text_IO.Put_Line (File, " function " & Prefix & "_Elements (Hash : " & Prefix & "_Hash)"); Ada.Text_IO.Put_Line (File, " return " & To_String (Map.Element_Type) & ';'); else Ada.Text_IO.Put_Line (File, " " & Prefix & "_Elements : constant array (0 .. " & Image (Last) & ") of " & To_String (Map.Element_Type)); Pos := 0; Cursor := Map.Nodes.First; while Node_Lists.Has_Element (Cursor) loop if Pos = 0 then Ada.Text_IO.Put (File, " := ("); else Ada.Text_IO.Put (File, " "); end if; Ada.Text_IO.Put (File, To_String (Node_Lists.Element (Cursor).Name)); if Pos = Last then Ada.Text_IO.Put_Line (File, ");"); else Ada.Text_IO.Put_Line (File, ","); end if; Pos := Pos + 1; Node_Lists.Next (Cursor); end loop; end if; end Write_Map_Private_Spec; procedure Write_Map_Public_Spec (Map : in Map_Description; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, " function " & To_String (Map.Function_Name) & " (Key : String) return " & To_String (Map.Element_Type) & ';'); end Write_Map_Public_Spec; procedure Write_Map_With (Map : in Map_Description; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "with " & To_String (Map.Hash_Package_Name) & ';'); end Write_Map_With; procedure Write_Package (Pkg : in Map_Package; Spec_File, Body_File : in Ada.Text_IO.File_Type; Test : in Boolean := False) is type Stage is (Hash_Package, Public_Spec, Private_Spec, Body_With, Body_Contents, Test_Body); Current_Stage : Stage; Map_Pos : Natural := 0; procedure Process (Element : in Map_Description); procedure Query (Cursor : in Map_Lists.Cursor); procedure Process (Element : in Map_Description) is Prefix : constant String := "Map_" & Image (Map_Pos + 1); begin case Current_Stage is when Hash_Package => Write_Map_Hash_Package (Element); Add_Categorization (Ada.Directories.Compose ("", File_Name (To_String (Element.Hash_Package_Name)), "ads"), Pkg.Categorization); when Public_Spec => Write_Map_Public_Spec (Element, Spec_File); when Private_Spec => Ada.Text_IO.New_Line (Spec_File); Write_Map_Private_Spec (Element, Prefix, Spec_File); when Body_With => Write_Map_With (Element, Body_File); when Body_Contents => Ada.Text_IO.New_Line (Body_File); Write_Map_Body (Element, Prefix, Body_File); Ada.Text_IO.New_Line (Body_File); when Test_Body => Write_Test (Element, Prefix, Body_File); Ada.Text_IO.New_Line (Body_File); end case; Map_Pos := Map_Pos + 1; end Process; procedure Query (Cursor : in Map_Lists.Cursor) is begin Map_Lists.Query_Element (Cursor, Process'Access); end Query; begin Current_Stage := Hash_Package; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Write_Headers : declare Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Offset : constant Ada.Calendar.Time_Zones.Time_Offset := Ada.Calendar.Time_Zones.UTC_Time_Offset (Now); Header : constant String := "-- Generated at " & Ada.Calendar.Formatting.Image (Now, False, Offset) & ' ' & Image (Offset) & " by Natools.Static_Hash_Maps"; Description : constant String := To_String (Pkg.Description); begin Ada.Text_IO.Put_Line (Spec_File, Header); Ada.Text_IO.Put_Line (Body_File, Header); if Description'Length > 0 then Ada.Text_IO.Put_Line (Spec_File, "-- " & Description); Ada.Text_IO.Put_Line (Body_File, "-- " & Description); end if; Ada.Text_IO.New_Line (Spec_File); Ada.Text_IO.New_Line (Body_File); end Write_Headers; if Test then declare Name : constant String := To_String (Pkg.Name) & '.' & To_String (Pkg.Test_Child); begin Ada.Text_IO.Put_Line (Spec_File, "function " & Name); Ada.Text_IO.Put_Line (Spec_File, " return Boolean;"); Put_Categorization (Spec_File, Pkg.Categorization, Name); Current_Stage := Body_With; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.Put_Line (Body_File, "function " & Name); Ada.Text_IO.Put_Line (Body_File, " return Boolean is"); Ada.Text_IO.Put_Line (Body_File, "begin"); Current_Stage := Test_Body; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.Put_Line (Body_File, " return True;"); Ada.Text_IO.Put_Line (Body_File, "end " & Name & ';'); end; return; end if; if Pkg.Priv then Ada.Text_IO.Put (Spec_File, "private "); end if; Ada.Text_IO.Put_Line (Spec_File, "package " & To_String (Pkg.Name) & " is"); Put_Categorization (Spec_File, Pkg.Categorization); Ada.Text_IO.New_Line (Spec_File); declare Declarations : constant String := To_String (Pkg.Extra_Declarations); begin if Declarations'Length > 0 then Ada.Text_IO.Put_Line (Spec_File, Declarations); Ada.Text_IO.New_Line (Spec_File); end if; end; Current_Stage := Public_Spec; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.New_Line (Spec_File); Ada.Text_IO.Put_Line (Spec_File, "private"); Current_Stage := Private_Spec; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.New_Line (Spec_File); Ada.Text_IO.Put_Line (Spec_File, "end " & To_String (Pkg.Name) & ';'); Current_Stage := Body_With; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.New_Line (Body_File); Ada.Text_IO.Put_Line (Body_File, "package body " & To_String (Pkg.Name) & " is"); Current_Stage := Body_Contents; Map_Pos := 0; Pkg.Maps.Iterate (Query'Access); Ada.Text_IO.Put_Line (Body_File, "end " & To_String (Pkg.Name) & ';'); end Write_Package; procedure Write_Test (Map : in Map_Description; Prefix : in String; File : in Ada.Text_IO.File_Type) is Key_Array_Name : constant String := Prefix & "_Keys"; begin Ada.Text_IO.Put_Line (File, " for I in " & Key_Array_Name & "'Range loop"); Ada.Text_IO.Put_Line (File, " if " & To_String (Map.Hash_Package_Name) & ".Hash"); Ada.Text_IO.Put_Line (File, " (" & Key_Array_Name & " (I).all) /= I"); Ada.Text_IO.Put_Line (File, " then"); Ada.Text_IO.Put_Line (File, " return False;"); Ada.Text_IO.Put_Line (File, " end if;"); Ada.Text_IO.Put_Line (File, " end loop;"); end Write_Test; ------------------------------- -- Key-Name Pair Constructor -- ------------------------------- function Node (Key, Name : String) return Map_Node is begin return (Key => Hold (Key), Name => Hold (Name)); end Node; --------------------------------- -- Map Description Subprograms -- --------------------------------- procedure Reset (Self : out Map_Description) is begin Self := (Element_Type => Hold (""), Hash_Package_Name => Hold (""), Function_Name => Hold (""), Not_Found => Hold (""), Nodes => Node_Lists.Empty_List, Indefinite => False); end Reset; procedure Insert (Self : in out Map_Description; Key : in String; Element_Name : in String) is begin Self.Nodes.Append (Node (Key, Element_Name)); end Insert; procedure Set_Definite (Self : in out Map_Description) is begin Self.Indefinite := False; end Set_Definite; procedure Set_Element_Type (Self : in out Map_Description; Name : in String) is begin Self.Element_Type := Hold (Name); end Set_Element_Type; procedure Set_Function_Name (Self : in out Map_Description; Name : in String) is begin Self.Function_Name := Hold (Name); end Set_Function_Name; procedure Set_Hash_Package_Name (Self : in out Map_Description; Name : in String) is begin Self.Hash_Package_Name := Hold (Name); end Set_Hash_Package_Name; procedure Set_Indefinite (Self : in out Map_Description; Indefinite : in Boolean := True) is begin Self.Indefinite := Indefinite; end Set_Indefinite; procedure Set_Not_Found (Self : in out Map_Description; Name : in String) is begin Self.Not_Found := Hold (Name); end Set_Not_Found; function Map (Element_Type : String; Nodes : Node_Array; Hash_Package_Name : String := ""; Function_Name : String := "Element"; Not_Found : String := ""; Indefinite : Boolean := False) return Map_Description is Result : Map_Description := (Element_Type => Hold (Element_Type), Hash_Package_Name => Hold (Hash_Package_Name), Function_Name => Hold (Function_Name), Not_Found => Hold (Not_Found), Nodes => Node_Lists.Empty_List, Indefinite => Indefinite); begin for I in Nodes'Range loop Result.Nodes.Append (Nodes (I)); end loop; return Result; end Map; ---------------------------- -- Map Package Primitives -- ---------------------------- procedure Open (Self : in out Map_Package; Name : in String; Private_Child : in Boolean := False) is begin Self.Name := Hold (Name); Self.Description := Hold (""); Self.Priv := Private_Child; Self.Maps.Clear; end Open; procedure Close (Self : in out Map_Package) is begin Self.Name := Hold (""); Self.Maps.Clear; end Close; procedure Set_Categorization (Self : in out Map_Package; Categorization : in Package_Categorization) is begin Self.Categorization := Categorization; end Set_Categorization; procedure Set_Description (Self : in out Map_Package; Description : in String) is begin Self.Description := Hold (Description); end Set_Description; procedure Set_Extra_Declarations (Self : in out Map_Package; Declarations : in String) is begin Self.Extra_Declarations := Hold (Declarations); end Set_Extra_Declarations; procedure Set_Private_Child (Self : in out Map_Package; Private_Child : in Boolean := True) is begin Self.Priv := Private_Child; end Set_Private_Child; procedure Set_Test_Child (Self : in out Map_Package; Test_Child : in String) is begin Self.Test_Child := Hold (Test_Child); end Set_Test_Child; procedure Add_Map (Self : in out Map_Package; Map : in Map_Description) is begin if To_String (Self.Name) = "" then raise Constraint_Error with "Add_Map on non-opened static hash map package"; end if; Self.Maps.Append (Map); end Add_Map; procedure Commit (Self : in out Map_Package) is begin if To_String (Self.Name) = "" then raise Constraint_Error with "Commit on static hash map package without a name"; end if; if Self.Maps.Is_Empty then raise Constraint_Error with "Commit on static hash map package without any map"; end if; declare Package_Name : constant String := To_String (Self.Name); Base_Name : constant String := File_Name (Package_Name); Spec_File, Body_File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Spec_File, Name => Ada.Directories.Compose ("", Base_Name, "ads")); Ada.Text_IO.Create (File => Body_File, Name => Ada.Directories.Compose ("", Base_Name, "adb")); Write_Package (Self, Spec_File, Body_File); Ada.Text_IO.Close (Spec_File); Ada.Text_IO.Close (Body_File); end; if To_String (Self.Test_Child) /= "" then declare Unit_Name : constant String := To_String (Self.Name) & '.' & To_String (Self.Test_Child); Base_Name : constant String := File_Name (Unit_Name); Spec_File, Body_File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Spec_File, Name => Ada.Directories.Compose ("", Base_Name, "ads")); Ada.Text_IO.Create (File => Body_File, Name => Ada.Directories.Compose ("", Base_Name, "adb")); Write_Package (Self, Spec_File, Body_File, Test => True); Ada.Text_IO.Close (Spec_File); Ada.Text_IO.Close (Body_File); end; end if; end Commit; ------------------------- -- Combined Procedures -- ------------------------- procedure Generate_Package (Name : in String; Single_Map : in Map_Description; Private_Child : in Boolean := False) is Object : Map_Package; begin Open (Object, Name, Private_Child); Add_Map (Object, Single_Map); Commit (Object); end Generate_Package; procedure Generate_Package (Name : in String; Maps : in Map_Array; Private_Child : in Boolean := False) is Object : Map_Package; begin Open (Object, Name, Private_Child); for I in Maps'Range loop Add_Map (Object, Maps (I)); end loop; Commit (Object); end Generate_Package; end Natools.Static_Hash_Maps;
package body Forward_AD.Hamiltonian is function Func (Q, V : in Real_Array; T : in Real) return AD_Type is N : constant Nat := Q'Length; begin pragma Assert (Q'Length = V'Length); return Var (1.0, 1, 1); end Func; end Forward_AD.Hamiltonian;
pragma Ada_2012; generic type Element is mod <>; type Index is range <>; type Element_Array is array (Index range <>) of Element; with function Character_To_Value (C : Character) return Element; with function Value_To_Character (E : Element) return Character; Padding : in Character := '='; package Base64_Generic with Pure, Preelaborate is pragma Compile_Time_Error (Element'Modulus /= 256, "'Element' type must be mod 2**8, i.e. represent a byte"); Base64_Error : exception; function Encode (Input : Element_Array) return String; function Decode (Input : String) return Element_Array; end Base64_Generic;
-- All Ada comments begin with "--" and extend to the end of the line
with Ada.Containers; use Ada.Containers; with Ada.Containers.Hashed_Maps; package Tarmi.Symbols is type Symbol_R (N : Positive) is new Datum_R with record Name : String_Type (1 .. N); end record; type Symbol is not null access constant Symbol_R; type String_Type_A is not null access constant String_Type; function Hash_String (Key : String_Type_A) return Hash_Type; function Keys_Equal (Left, Right : String_Type_A) return Boolean ; package Hashed_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Type_A, Element_Type => Symbol, Hash => Hash_String, Equivalent_Keys => Keys_Equal); Symbol_Table : Hashed_Maps.Map ; function Interned (Name : String_Type_A) return Symbol; function Interned (Name : String_Type) return Symbol; end Tarmi.Symbols;
with Ada.Numerics.Discrete_Random; package body Miller_Rabin is function Is_Prime (N : Number; K : Positive := 10) return Result_Type is subtype Number_Range is Number range 2 .. N - 1; package Random is new Ada.Numerics.Discrete_Random (Number_Range); function Mod_Exp (Base, Exponent, Modulus : Number) return Number is Result : Number := 1; begin for E in 1 .. Exponent loop Result := Result * Base mod Modulus; end loop; return Result; end Mod_Exp; Generator : Random.Generator; D : Number := N - 1; S : Natural := 0; X : Number; begin -- exclude 2 and even numbers if N = 2 then return Probably_Prime; elsif N mod 2 = 0 then return Composite; end if; -- write N-1 as 2**S * D, with D mod 2 /= 0 while D mod 2 = 0 loop D := D / 2; S := S + 1; end loop; -- initialize RNG Random.Reset (Generator); for Loops in 1 .. K loop X := Mod_Exp(Random.Random (Generator), D, N); if X /= 1 and X /= N - 1 then Inner : for R in 1 .. S - 1 loop X := Mod_Exp (X, 2, N); if X = 1 then return Composite; end if; exit Inner when X = N - 1; end loop Inner; if X /= N - 1 then return Composite; end if; end if; end loop; return Probably_Prime; end Is_Prime; end Miller_Rabin;
with gel_demo_Client; procedure launch_Client -- -- Launches the remote client. -- is begin gel_demo_Client.item.start; end launch_Client;
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with MAT.Types; with System.Address_Image; with Interfaces; procedure MAT.Frames.Print (File : in File_Type; F : in Frame_Type) is use MAT.Types; use Interfaces; Depth : constant Natural := F.Depth; Child : Frame_Type; procedure Print_Address (File : in File_Type; Addr : in Target_Addr); function Hex_Image (Val : Target_Addr; Len : Positive) return String; function Hex_Image (Val : Target_Addr; Len : Positive) return String is Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; S : String (1 .. Len) := (others => '0'); P : Target_Addr := Val; N : Target_Addr; I : Positive := Len; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Natural (N + 1)); exit when I = 1; I := I - 1; end loop; return S; end Hex_Image; procedure Print_Address (File : in File_Type; Addr : in Target_Addr) is begin Put (File, Hex_Image (Addr, 20)); end Print_Address; begin Set_Col (File, Positive_Count (Depth + 1)); if F.Parent = null then Put_Line (File, "R " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address)); else Put_Line (File, "F " & Natural'Image (F.Used) & " - " & System.Address_Image (F.all'Address) & " - P=" & System.Address_Image (F.Parent.all'Address)); end if; Set_Col (File, Positive_Count (Depth + 1)); Print_Address (File, F.Pc); Put_Line (File, " D " & Natural'Image (Depth)); Child := F.Children; while Child /= null loop Print (File, Child); Child := Child.Next; end loop; end MAT.Frames.Print;
----------------------------------------------------------------------- -- util-properties-discrete -- Generic package for get/set of discrete properties -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- generic type Property_Type is (<>); -- with function To_String (Val : Property_Type) return String is <>; -- with function From_String (Val : String) return Property_Type is <>; package Util.Properties.Discrete is -- Get the property value function Get (Self : in Manager'Class; Name : in String) return Property_Type; -- Get the property value. -- Return the default if the property does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in Property_Type) return Property_Type; -- Set the property value procedure Set (Self : in out Manager'Class; Name : in String; Value : in Property_Type); end Util.Properties.Discrete;
with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line; procedure Comma_Quibble is begin case Argument_Count is when 0 => Ada.Text_IO.Put_Line("{}"); when 1 => Ada.Text_IO.Put_Line("{" & Argument(1) & "}"); when others => Ada.Text_IO.Put("{"); for I in 1 .. Argument_Count-2 loop Ada.Text_IO.Put(Argument(I) & ", "); end loop; Ada.Text_IO.Put(Argument(Argument_Count-1) & " and " & Argument(Argument_Count) & "}"); end case; end Comma_Quibble;
with Interfaces.C.Strings, System; use type Interfaces.C.Strings.chars_ptr, System.Address; package body FLTK.Images.Shared is function fl_shared_image_get (F : in Interfaces.C.char_array; W, H : in Interfaces.C.int) return System.Address; pragma Import (C, fl_shared_image_get, "fl_shared_image_get"); pragma Inline (fl_shared_image_get); function fl_shared_image_get2 (I : in System.Address) return System.Address; pragma Import (C, fl_shared_image_get2, "fl_shared_image_get2"); pragma Inline (fl_shared_image_get2); function fl_shared_image_find (N : in Interfaces.C.char_array; W, H : in Interfaces.C.int) return System.Address; pragma Import (C, fl_shared_image_find, "fl_shared_image_find"); pragma Inline (fl_shared_image_find); procedure fl_shared_image_release (I : in System.Address); pragma Import (C, fl_shared_image_release, "fl_shared_image_release"); pragma Inline (fl_shared_image_release); function fl_shared_image_copy (I : in System.Address; W, H : in Interfaces.C.int) return System.Address; pragma Import (C, fl_shared_image_copy, "fl_shared_image_copy"); pragma Inline (fl_shared_image_copy); function fl_shared_image_copy2 (I : in System.Address) return System.Address; pragma Import (C, fl_shared_image_copy2, "fl_shared_image_copy2"); pragma Inline (fl_shared_image_copy2); procedure fl_shared_image_color_average (I : in System.Address; C : in Interfaces.C.int; B : in Interfaces.C.C_float); pragma Import (C, fl_shared_image_color_average, "fl_shared_image_color_average"); pragma Inline (fl_shared_image_color_average); procedure fl_shared_image_desaturate (I : in System.Address); pragma Import (C, fl_shared_image_desaturate, "fl_shared_image_desaturate"); pragma Inline (fl_shared_image_desaturate); function fl_shared_image_name (I : in System.Address) return Interfaces.C.Strings.chars_ptr; pragma Import (C, fl_shared_image_name, "fl_shared_image_name"); pragma Inline (fl_shared_image_name); procedure fl_shared_image_reload (I : in System.Address); pragma Import (C, fl_shared_image_reload, "fl_shared_image_reload"); pragma Inline (fl_shared_image_reload); procedure fl_shared_image_scaling_algorithm (A : in Interfaces.C.int); pragma Import (C, fl_shared_image_scaling_algorithm, "fl_shared_image_scaling_algorithm"); pragma Inline (fl_shared_image_scaling_algorithm); procedure fl_shared_image_scale (I : in System.Address; W, H, P, E : in Interfaces.C.int); pragma Import (C, fl_shared_image_scale, "fl_shared_image_scale"); pragma Inline (fl_shared_image_scale); procedure fl_shared_image_draw (I : in System.Address; X, Y, W, H, CX, CY : in Interfaces.C.int); pragma Import (C, fl_shared_image_draw, "fl_shared_image_draw"); pragma Inline (fl_shared_image_draw); procedure fl_shared_image_draw2 (I : in System.Address; X, Y : in Interfaces.C.int); pragma Import (C, fl_shared_image_draw2, "fl_shared_image_draw2"); pragma Inline (fl_shared_image_draw2); overriding procedure Finalize (This : in out Shared_Image) is begin if This.Void_Ptr /= System.Null_Address and then This in Shared_Image'Class then fl_shared_image_release (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Image (This)); end Finalize; package body Forge is function Create (Filename : in String; W, H : in Integer) return Shared_Image is begin return This : Shared_Image do This.Void_Ptr := fl_shared_image_get (Interfaces.C.To_C (Filename), Interfaces.C.int (W), Interfaces.C.int (H)); end return; end Create; function Create (From : in FLTK.Images.RGB.RGB_Image'Class) return Shared_Image is begin return This : Shared_Image do This.Void_Ptr := fl_shared_image_get2 (Wrapper (From).Void_Ptr); end return; end Create; function Find (Name : in String; W, H : in Integer := 0) return Shared_Image is begin return This : Shared_Image do This.Void_Ptr := fl_shared_image_find (Interfaces.C.To_C (Name), Interfaces.C.int (W), Interfaces.C.int (H)); if This.Void_Ptr = System.Null_Address then raise No_Image_Error; end if; end return; end Find; end Forge; function Copy (This : in Shared_Image; Width, Height : in Natural) return Shared_Image'Class is begin return Copied : Shared_Image do Copied.Void_Ptr := fl_shared_image_copy (This.Void_Ptr, Interfaces.C.int (Width), Interfaces.C.int (Height)); end return; end Copy; function Copy (This : in Shared_Image) return Shared_Image'Class is begin return Copied : Shared_Image do Copied.Void_Ptr := fl_shared_image_copy2 (This.Void_Ptr); end return; end Copy; procedure Color_Average (This : in out Shared_Image; Col : in Color; Amount : in Blend) is begin fl_shared_image_color_average (This.Void_Ptr, Interfaces.C.int (Col), Interfaces.C.C_float (Amount)); end Color_Average; procedure Desaturate (This : in out Shared_Image) is begin fl_shared_image_desaturate (This.Void_Ptr); end Desaturate; function Name (This : in Shared_Image) return String is Ptr : Interfaces.C.Strings.chars_ptr := fl_shared_image_name (This.Void_Ptr); begin if Ptr = Interfaces.C.Strings.Null_Ptr then return ""; else return Interfaces.C.Strings.Value (Ptr); end if; end Name; procedure Reload (This : in out Shared_Image) is begin fl_shared_image_reload (This.Void_Ptr); end Reload; procedure Set_Scaling_Algorithm (To : in Scaling_Kind) is begin fl_shared_image_scaling_algorithm (Scaling_Kind'Pos (To)); end Set_Scaling_Algorithm; procedure Scale (This : in out Shared_Image; W, H : in Integer; Proportional : in Boolean := True; Can_Expand : in Boolean := False) is begin fl_shared_image_scale (This.Void_Ptr, Interfaces.C.int (W), Interfaces.C.int (H), Boolean'Pos (Proportional), Boolean'Pos (Can_Expand)); end Scale; procedure Draw (This : in Shared_Image; X, Y, W, H : in Integer; CX, CY : in Integer := 0) is begin fl_shared_image_draw (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.int (CX), Interfaces.C.int (CY)); end Draw; procedure Draw (This : in Shared_Image; X, Y : in Integer) is begin fl_shared_image_draw2 (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y)); end Draw; end FLTK.Images.Shared;
with Ada.Text_IO; use Ada.Text_IO; procedure test_endianess is begin if Standard'Default_Bit_Order = 1 then Put_Line ("This is a litle-endian machine. " & " (Standard'Default_Bit_Order = " & Integer'Image (Standard'Default_Bit_Order) & ")"); else Put_Line ("This is a big-endian machine. " & " (Standard'Default_Bit_Order = " & Integer'Image (Standard'Default_Bit_Order) & ")"); end if; end test_endianess;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2019, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with ESF; with LibRISCV.Sim.Log; with LibRISCV.Sim.Shutdown; package body LibRISCV.Sim.Memory_Bus is ------------ -- Load_B -- ------------ procedure Load_B (This : Instance; Addr : Address; Data : out Byte; Res : out Access_Result) is begin if Addr in This.RAM_Base .. This.RAM_Base + This.RAM'Length - 1 then Data := This.RAM (Positive (Addr - This.RAM_Base + 1)); Res := Success; else if Sim.Log.Mem_Access then Sim.Log.Put_Line ("Load_B invalid access at 0x" & Hex (Addr)); end if; Res := Failure; end if; if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Load_B Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; end Load_B; ------------ -- Load_H -- ------------ procedure Load_H (This : Instance; Addr : Address; Data : out Halfword; Res : out Access_Result) is Input : array (Address range 0 .. 1) of Byte; begin for Offset in Input'Range loop This.Load_B (Addr + Offset, Input (Offset), Res); if Res /= Success then Data := 0; return; end if; end loop; Data := Halfword (Shift_Left (Word (Input (1)), 8) or Word (Input (0))); Res := Success; if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Load_H Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; end Load_H; ------------ -- Load_W -- ------------ procedure Load_W (This : Instance; Addr : Address; Data : out Word; Res : out Access_Result) is Input : array (Address range 0 .. 3) of Byte; begin for Offset in Input'Range loop This.Load_B (Addr + Offset, Input (Offset), Res); if Res /= Success then Data := 0; return; end if; end loop; Data := Shift_Left (Word (Input (3)), 24) or Shift_Left (Word (Input (2)), 16) or Shift_Left (Word (Input (1)), 8) or Word (Input (0)); Res := Success; if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Load_W Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; end Load_W; ------------- -- Store_B -- ------------- procedure Store_B (This : in out Instance; Addr : Address; Data : Byte; Res : out Access_Result) is begin if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Store_B Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; if Addr in This.RAM_Base .. This.RAM_Base + This.RAM'Length - 1 then This.RAM (Positive (Addr - This.RAM_Base + 1)) := Data; Res := Success; elsif Addr = 16#F0000000# then if Sim.Log.Console then Sim.Log.Put ((1 => Character'Val (Data))); end if; Res := Success; else if Sim.Log.Mem_Access then Sim.Log.Put_Line ("Store_B invalid access at 0x" & Hex (Addr)); end if; Res := Failure; end if; end Store_B; ------------- -- Store_H -- ------------- procedure Store_H (This : in out Instance; Addr : Address; Data : Halfword; Res : out Access_Result) is B : Byte; Tmp_Data : Halfword := Data; begin if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Store_H Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; for Offset in Address range 0 .. 1 loop B := Byte (Tmp_Data and 16#FF#); This.Store_B (Addr + Offset, B, Res); if Res /= Success then return; end if; Tmp_Data := Shift_Right (Tmp_Data, 8); end loop; end Store_H; ------------- -- Store_W -- ------------- procedure Store_W (This : in out Instance; Addr : Address; Data : Word; Res : out Access_Result) is B : Byte; Tmp_Data : Word := Data; begin if Sim.Log.Mem_Access then Sim.Log.Put_Line (ESF.Fmt ("Store_W Addr: 0x\s Data: 0x\s", Hex (Addr), Hex (Data))); end if; if This.HTIF_Enabled and then This.Tohost_Set and then Addr = This.Tohost_Addr and then Data = 1 then Sim.Shutdown.Request; Res := Success; else for Offset in Address range 0 .. 3 loop B := Byte (Tmp_Data and 16#FF#); This.Store_B (Addr + Offset, B, Res); if Res /= Success then return; end if; Tmp_Data := Shift_Right (Tmp_Data, 8); end loop; end if; end Store_W; ----------------- -- Enable_HTIF -- ----------------- procedure Enable_HTIF (This : in out Instance) is begin This.HTIF_Enabled := True; end Enable_HTIF; ---------------- -- Set_Tohost -- ---------------- procedure Set_Tohost (This : in out Instance; Addr : Address) is begin This.Tohost_Addr := Addr; This.Tohost_Set := True; end Set_Tohost; end LibRISCV.Sim.Memory_Bus;
with Libadalang.Analysis; use Libadalang.Analysis; with Utils.Char_Vectors; use Utils.Char_Vectors; with Utils.Command_Lines; use Utils.Command_Lines; with Utils.Tools; use Utils.Tools; with Pp.Scanner; use Pp; package JSON_Gen.Actions is type Json_Gen_Tool is new Tool_State with private; procedure Format_Vector (Cmd : Command_Line; Input : Char_Vector; Node : Ada_Node; In_Range : Char_Subrange; Output : out Char_Vector; Out_Range : out Char_Subrange; Messages : out Pp.Scanner.Source_Message_Vector); private overriding procedure Init (Tool : in out Json_Gen_Tool; Cmd : in out Command_Line); overriding procedure Per_File_Action (Tool : in out Json_Gen_Tool; Cmd : Command_Line; File_Name : String; Input : String; BOM_Seen : Boolean; Unit : Analysis_Unit); overriding procedure Final (Tool : in out Json_Gen_Tool; Cmd : Command_Line); overriding procedure Tool_Help (Tool : Json_Gen_Tool); type Json_Gen_Tool is new Tool_State with record Ignored_Out_Range : Char_Subrange; Ignored_Messages : Scanner.Source_Message_Vector; end record; -- For Debugging: procedure Dump (Tool : in out Json_Gen_Tool; Message : String := ""); end JSON_Gen.Actions;
-- This file is generated by SWIG. Please do *not* modify by hand. -- with Interfaces.C; with Interfaces.C.Strings; with Interfaces.C; package gmp_c is -- mp_limb_t -- subtype mp_limb_t is Interfaces.C.unsigned_long; type mp_limb_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.mp_limb_t; -- mp_limb_signed_t -- subtype mp_limb_signed_t is Interfaces.C.long; type mp_limb_signed_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.mp_limb_signed_t; -- mp_bitcnt_t -- subtype mp_bitcnt_t is Interfaces.C.unsigned_long; type mp_bitcnt_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.mp_bitcnt_t; -- mp_size_t -- subtype mp_size_t is Interfaces.C.long; type mp_size_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.mp_size_t; -- mp_exp_t -- subtype mp_exp_t is Interfaces.C.long; type mp_exp_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.mp_exp_t; -- gmp_randalg_t -- type gmp_randalg_t is (GMP_RAND_ALG_DEFAULT); for gmp_randalg_t use (GMP_RAND_ALG_DEFAULT => 0); pragma Convention (C, gmp_randalg_t); type gmp_randalg_t_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.gmp_randalg_t; -- anonymous_enum_1 -- type anonymous_enum_1 is (GMP_ERROR_NONE, GMP_ERROR_UNSUPPORTED_ARGUMENT, GMP_ERROR_DIVISION_BY_ZERO, GMP_ERROR_SQRT_OF_NEGATIVE, GMP_ERROR_INVALID_ARGUMENT); for anonymous_enum_1 use (GMP_ERROR_NONE => 0, GMP_ERROR_UNSUPPORTED_ARGUMENT => 1, GMP_ERROR_DIVISION_BY_ZERO => 2, GMP_ERROR_SQRT_OF_NEGATIVE => 4, GMP_ERROR_INVALID_ARGUMENT => 8); pragma Convention (C, anonymous_enum_1); type anonymous_enum_1_array is array (Interfaces.C.size_t range <>) of aliased gmp_c.anonymous_enum_1; GMP_RAND_ALG_LC : aliased constant gmp_c.gmp_randalg_t := GMP_RAND_ALG_DEFAULT; a_a_GMP_HAVE_HOST_CPU_FAMILY_power : constant := 0; a_a_GMP_HAVE_HOST_CPU_FAMILY_powerpc : constant := 0; GMP_LIMB_BITS : constant := 64; GMP_NAIL_BITS : constant := 0; a_a_GNU_MP_a_a : constant := 5; a_a_GMP_LIBGMP_DLL : constant := 0; a_a_GMP_MP_SIZE_T_INT : constant := 0; a_a_GMP_INLINE_PROTOTYPES : constant := 0; bits_per_limb : aliased Interfaces.C.int; errno : aliased Interfaces.C.int; version : aliased Interfaces.C.Strings.chars_ptr; a_a_GNU_MP_VERSION : constant := 6; a_a_GNU_MP_VERSION_MINOR : constant := 1; a_a_GNU_MP_VERSION_PATCHLEVEL : constant := 0; a_a_GNU_MP_RELEASE : constant := 60100; private pragma Import (Cpp, bits_per_limb, "_ZN5gmp_c13bits_per_limbE"); pragma Import (Cpp, errno, "_ZN5gmp_c5errnoE"); pragma Import (Cpp, version, "_ZN5gmp_c7versionE"); end gmp_c;
with Memory.Container; use Memory.Container; package Memory.Cache is type Cache_Type is new Container_Type with private; type Cache_Pointer is access all Cache_Type'Class; type Policy_Type is (LRU, -- Least recently used MRU, -- Most recently used FIFO, -- First-in, first-out PLRU -- Pseudo-LRU ); function Create_Cache(mem : access Memory_Type'Class; line_count : Positive := 1; line_size : Positive := 8; associativity : Positive := 1; latency : Time_Type := 1; policy : Policy_Type := LRU; write_back : Boolean := True) return Cache_Pointer; function Random_Cache(next : access Memory_Type'Class; generator : Distribution_Type; max_cost : Cost_Type) return Memory_Pointer; overriding function Clone(mem : Cache_Type) return Memory_Pointer; overriding procedure Permute(mem : in out Cache_Type; generator : in Distribution_Type; max_cost : in Cost_Type); overriding procedure Reset(mem : in out Cache_Type; context : in Natural); overriding procedure Read(mem : in out Cache_Type; address : in Address_Type; size : in Positive); overriding procedure Write(mem : in out Cache_Type; address : in Address_Type; size : in Positive); overriding function To_String(mem : Cache_Type) return Unbounded_String; overriding function Get_Cost(mem : Cache_Type) return Cost_Type; overriding procedure Generate(mem : in Cache_Type; sigs : in out Unbounded_String; code : in out Unbounded_String); overriding procedure Adjust(mem : in out Cache_Type); overriding procedure Finalize(mem : in out Cache_Type); function Get_Line_Size(mem : Cache_Type) return Positive; function Get_Line_Count(mem : Cache_Type) return Positive; function Get_Associativity(mem : Cache_Type) return Positive; function Get_Policy(mem : Cache_Type) return Policy_Type; private type Cache_Data is record address : Address_Type := Address_Type'Last; age : Long_Integer := 0; dirty : Boolean := False; end record; type Cache_Data_Pointer is access Cache_Data; package Cache_Vectors is new Vectors(Natural, Cache_Data_Pointer); type Cache_Type is new Container_Type with record line_size : Positive := 8; line_count : Positive := 1; associativity : Positive := 1; latency : Time_Type := 1; data : Cache_Vectors.Vector; policy : Policy_Type := LRU; write_back : Boolean := True; end record; end Memory.Cache;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Ada.Wide_Wide_Text_IO; with Regions.Tests; procedure Regions.Run is begin Regions.Tests.Test_Standard; Ada.Wide_Wide_Text_IO.Put_Line ("Hello!"); end Regions.Run;
with Entities; use Entities; with Vectors2D; use Vectors2D; with Ada.Containers.Doubly_Linked_Lists; with Circles; with Rectangles; package Collisions is -- Collision type, holding meaningful information -- about a collision type Collision is record A : EntityClassAcc; B : EntityClassAcc; Normal : Vec2D; Penetration : Float; end record; pragma Pack (Collision); package ColsList is new Ada.Containers.Doubly_Linked_Lists(Collision); type ColsListAcc is access ColsList.List; -- Return True if A collides with B; else false -- Fills Col with data about the collision function Collide(A, B : not null EntityClassAcc; Col : out Collision) return Boolean; -- A fast approximation of collision detection. Usefull for when precision is not important function CollideEx(A, B : not null EntityClassAcc) return Boolean; -- This procedure is called when there is a collision -- It impulses on A and B so that they no longer collide -- Solves for friction too procedure Resolve(Col : in Collision); -- This procedure, called after the collision resolution -- Ensures that objects do not sink in each other procedure PosCorrection(Col : in Collision); -- Tells if Pos is inside Ent function IsInside(Pos : Vec2D; Ent : not null EntityClassAcc) return Boolean; -- Returns an approximation of the area of the overlap for this collision -- Used for Archimede's force function OverlapArea(Col : in Collision) return Float; private function Friction(A, B : Float) return Float; function CircleOnCircle(Col : in out Collision) return Boolean; function RectangleOnRectangle(Col : in out Collision) return Boolean; function RectangleOnCircle(Col : in out Collision) return Boolean; function CircleOnRectangle(Col : in out Collision) return Boolean; function OverlapAreaCircleRectangle(A : Circles.CircleAcc; B : Rectangles.RectangleAcc) return Float; function OverlapAreaCircleCircle(A, B : Circles.CircleAcc) return Float; function OverlapAreaRectangleRectangle(PosA, DimA, PosB, DimB : Vec2D) return Float; type CollideFunc is access function (Col : in out Collision) return Boolean; type DispatcherArr is array (EntityTypes, EntityTypes) of CollideFunc; Dispatcher : constant DispatcherArr := (EntCircle => (EntCircle => CircleOnCircle'Access, EntRectangle => CircleOnRectangle'Access), EntRectangle => (EntCircle => RectangleOnCircle'Access, EntRectangle => RectangleOnRectangle'Access)); end Collisions;
procedure LightTrigger (dir : in Direction) is begin if Pedestrian_Button(North) = 1 then --Will need to be a sub procedure taking in param of direction. PedestrianLightSwitcher(North); --Temporary call to the north light for development. end if; --Pressed end LightTrigger;
with Interfaces; use Interfaces; with LV.Area; generic Width : Interfaces.Integer_16; Height : Interfaces.Integer_16; package SDL_Display is Screen_Rect : constant LV.Area.Area_T := (0, 0, Width - 1, Height - 1); procedure Initialize; subtype SDL_Pixel is Unsigned_16; function To_SDL_Color (R, G, B : Unsigned_8) return SDL_Pixel; end SDL_Display;
with Resources8; with Ada.Command_Line; with Ada.Text_IO; procedure Test8 is use Resources8; C : Content_Access := Get_Content ("config/test8.xml"); begin if C = null then Ada.Text_IO.Put_Line ("FAIL: No content 'config/test8.xml'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; if C'Length /= 37 then Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'config/test8.xml'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; C := Get_Content ("CONFIG/TEST8.XML"); if C = null then Ada.Text_IO.Put_Line ("FAIL: No content 'config/test8.xml'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; C := Get_Content ("CoNfIg/TeSt8.XmL"); if C = null then Ada.Text_IO.Put_Line ("FAIL: No content 'config/test8.xml'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Ada.Text_IO.Put ("PASS: "); Ada.Text_IO.Put_Line (C.all); end Test8;
with Ada.Text_IO; with Ada.Streams; with Ada.Characters.Latin_1; with Ada.Text_IO.Text_Streams; with Ada.Streams.Stream_IO; with Ada.Calendar; with Ada.Calendar.Time_Zones; with Ada.Calendar.Formatting; with Ada.Command_Line; with GNAT.Calendar.Time_IO; with GNAT.Regpat; with GNAT.Formatted_String; with Ada.Storage_IO; --with AWS; procedure Ada_Time is use Ada.Text_IO; use Ada.Characters.Latin_1; use Ada.Text_IO.Text_Streams; use Ada.Calendar; use Ada.Calendar.Time_Zones; use Ada.Command_Line; use GNAT.Calendar.Time_IO; Now : Time := Clock; function Unix_Time return Time is use Ada.Calendar.Formatting; U_Year : Year_Number; U_Month : Month_Number; U_Day : Day_Number; U_Hour : Hour_Number; U_Minute : Minute_Number; U_Second : Second_Number; U_Duration : Second_Duration; begin Split (Date => Now, Year => U_Year, Month => U_Month, Day => U_Day, Hour => U_Hour, Minute => U_Minute, Second => U_Second, Sub_Second => U_Duration, Time_Zone => 0); return Time_Of (Year => U_Year, Month => U_Month, Day => U_Day, Hour => U_Hour, Minute => U_Minute, Second => U_Second, Sub_Second => U_Duration, Time_Zone => UTC_Time_Offset); end Unix_Time; function To_Multimedia (Time : String; Fraction : Boolean := True) return String -- Convert pure seconds ***.*** to multimedia time string **h**m**s Fraction -- boolean value specifies whether to include the fractional part of the -- time: **h**m**.***s is begin null; return ""; end To_Multimedia; function To_Clock (Time : String; Fraction : Boolean := True) return String -- Convert pure seconds ***.*** to multimedia time string **:**:** Fraction -- boolean value specifies whether to include the fractional part of the -- time: **h**m**.***s is begin null; return ""; end To_Clock; function To_Seconds (Time : String) return String -- Convert a Multimedia time string **h**m**s or **:**:**.*** to pure -- seconds ***.*** is begin null; return ""; end To_Seconds; function "+" (Left : String; Right : String) return String is use Ada.Characters.Latin_1; begin return Left & LF & Right; end "+"; -- Unix_Time : Time := -- Value (Date => Image (Date => Now, Include_Time_Fraction => True), -- Time_Zone => UTC_Time_Offset); begin for A in 1 .. Argument_Count loop if Argument (A) = "-iso" or Argument (A) = "-I" or Argument (A) = "-i" then String'Write (Stream (Current_Output), Image (Date => Now, Picture => "%Y-%m-%d")); elsif Argument (A) = "-n" or Argument (A) = "-nano" then String'Write (Stream (Current_Output), Image (Date => Unix_Time, Picture => "%s.%o")); elsif Argument (A) (1) = '+' then declare Feature_Argument : String := Argument (A); begin String'Write (Stream (Current_Output), Image (Date => Now, Picture => Picture_String (Feature_Argument (Feature_Argument'First + 1 .. Feature_Argument'Last)))); end; elsif Argument (A) = "-h" or Argument (A) = "--help" then String'Write (Stream (Current_Error), Command_Name & " [ -n ] [ +<format_string> ] [ -I ]" + "" + "Print unix time in base 10 by default." + "With '-n', include nano seconds." + "With '-i', '-I', or '--iso' print ISO date." + "With a custom format string starting with '+', print current time with given GNU Date format." + "With '-h' or '--help' print this message." + "With '-g' or '--gnu-help' print the Gnat GNU Date format directives." + "" + "(c) Micah Waddoups <dev@micahwelf.us>"); elsif Argument (A) = "-g" or Argument (A) = "--gnu-help" then String'Write (Stream (Current_Error), " % a literal %" + " n a newline" + " t a horizontal tab" + "" + " Time fields:" + "" + " %H hour (00..23)" + " %I hour (01..12)" + " %k hour ( 0..23)" + " %l hour ( 1..12)" + " %M minute (00..59)" + " %p locale's AM or PM" + " %r time, 12-hour (hh:mm:ss [AP]M)" + " %s seconds since 1970-01-01 00:00:00 UTC" + " (a nonstandard extension)" + " %S second (00..59)" + " %T time, 24-hour (hh:mm:ss)" + "" + " Date fields:" + "" + " %a locale's abbreviated weekday name (Sun..Sat)" + " %A locale's full weekday name, variable length" + " (Sunday..Saturday)" + " %b locale's abbreviated month name (Jan..Dec)" + " %B locale's full month name, variable length" + " (January..December)" + " %c locale's date and time (Sat Nov 04 12:02:33 EST 1989)" + " %d day of month (01..31)" + " %D date (mm/dd/yy)" + " %h same as %b" + " %j day of year (001..366)" + " %m month (01..12)" + " %U week number of year with Sunday as first day of week" + " (00..53)" + " %w day of week (0..6) with 0 corresponding to Sunday" + " %W week number of year with Monday as first day of week" + " (00..53)" + " %x locale's date representation (mm/dd/yy)" + " %y last two digits of year (00..99)" + " %Y year (1970...)" + "" + " By default, date pads numeric fields with zeroes. GNU date" + " recognizes the following nonstandard numeric modifiers:" + "" + " - (hyphen) do not pad the field" + " _ (underscore) pad the field with spaces" + "" + " Here are some GNAT extensions to the GNU Date specification:" + "" + " %i milliseconds (3 digits)" + " %e microseconds (6 digits)" + " %o nanoseconds (9 digits)" + "" + "" & Copyright_Sign & "(c) Free Software Foundation, Inc. -- GNAT, the Ada Compiler" + "(c) Micah Waddoups <dev@micahwelf.us>"); else String'Write (Stream (Current_Output), Image (Date => Unix_Time, Picture => "%s")); end if; end loop; if Argument_Count = 0 then String'Write (Stream (Current_Output), Image (Date => Unix_Time, Picture => "%s")); end if; end Ada_Time; -- This is a string to describe date and time output format. The string -- is a set of standard character and special tag that are replaced by the -- corresponding values. It follows the GNU Date specification. Here are the -- recognized directives : -- -- % a literal % -- n a newline -- t a horizontal tab -- -- Time fields: -- -- %H hour (00..23) -- %I hour (01..12) -- %k hour ( 0..23) -- %l hour ( 1..12) -- %M minute (00..59) -- %p locale's AM or PM -- %r time, 12-hour (hh:mm:ss [AP]M) -- %s seconds since 1970-01-01 00:00:00 UTC -- (a nonstandard extension) -- %S second (00..59) -- %T time, 24-hour (hh:mm:ss) -- -- Date fields: -- -- %a locale's abbreviated weekday name (Sun..Sat) -- %A locale's full weekday name, variable length -- (Sunday..Saturday) -- %b locale's abbreviated month name (Jan..Dec) -- %B locale's full month name, variable length -- (January..December) -- %c locale's date and time (Sat Nov 04 12:02:33 EST 1989) -- %d day of month (01..31) -- %D date (mm/dd/yy) -- %h same as %b -- %j day of year (001..366) -- %m month (01..12) -- %U week number of year with Sunday as first day of week -- (00..53) -- %w day of week (0..6) with 0 corresponding to Sunday -- %W week number of year with Monday as first day of week -- (00..53) -- %x locale's date representation (mm/dd/yy) -- %y last two digits of year (00..99) -- %Y year (1970...) -- -- By default, date pads numeric fields with zeroes. GNU date -- recognizes the following nonstandard numeric modifiers: -- -- - (hyphen) do not pad the field -- _ (underscore) pad the field with spaces -- -- Here are some GNAT extensions to the GNU Date specification: -- -- %i milliseconds (3 digits) -- %e microseconds (6 digits) -- %o nanoseconds (9 digits)
-- { dg-do compile } -- { dg-options "-gnatws" } procedure aliased1 is type E is (One, Two); type R (D : E := One) is record case D is when One => I1 : Integer; I2 : Integer; when Two => B1 : Boolean; end case; end record; type Data_Type is record Data : R; end record; type Array_Type is array (Natural range <>) of Data_Type; function Get return Array_Type is Ret : Array_Type (1 .. 2); begin return Ret; end; Object : aliased Array_Type := Get; begin null; end;
------------------------------------------------------------------------ -- Copyright (C) 2010-2020 by Heisenbug Ltd. (github@heisenbug.eu) -- -- This work is free. You can redistribute it and/or modify it under -- the terms of the Do What The Fuck You Want To Public License, -- Version 2, as published by Sam Hocevar. See the LICENSE file for -- more details. ------------------------------------------------------------------------ pragma License (Unrestricted); with Ada.Real_Time; with Ada.Text_IO; -- Using Ada.Text_IO in tasking context is not -- safe, but use it for the sake of a simple example. with Local_Message_Passing; with Message_Types; ------------------------------------------------------------------------ -- The sender task package. ------------------------------------------------------------------------ package body Sender is -- Instantiate the Local_Message_Passing package, so we get the -- Handle type to access a mailbox. package LMP is new Local_Message_Passing (Message => Message_Types.The_Message); Our_Message : constant Message_Types.The_Message := "Can you hear me? "; task Send_Messages; task body Send_Messages is MB : LMP.Handle; begin Ada.Text_IO.Put_Line ("Sender: Waiting for mailbox to get exported..."); -- Import the mailbox. This initializes our Handle. -- In this example, the receiver task delays for a second before -- exporting the mailbox, so you should see a small delay. LMP.Import_Mailbox (Name => "MY_MAILBOX", Hnd => MB, Max_Wait => Ada.Real_Time.Milliseconds (2000)); Ada.Text_IO.Put_Line ("Sender: Mailbox found, I start sending messages now."); loop -- Blocking send. Waits until there is space in the message -- queue. LMP.Send (Mbx => MB, Msg => Our_Message); delay 1.0; -- Wait a second... (literally) end loop; exception when LMP.No_Such_Mailbox => Ada.Text_IO.Put_Line ("Sender died: Could not find mailbox!"); end Send_Messages; end Sender;
with Agar; with Agar.Object; with Agar.Data_Source; with System.Address_To_Access_Conversions; with Interfaces.C; -- -- Example of an Agar object class called "Animal". -- package Animal is package OBJ renames Agar.Object; package DS renames Agar.Data_Source; package C renames Interfaces.C; use type C.int; use type C.C_float; use type C.double; Success : constant C.int := 0; Error : constant C.int := -1; ----------------------- -- Class Description -- ----------------------- type Ecological_Group_t is (Undefined, Carnivore, Herbivore, Omnivore, Detritivore, Parasite); type Animal_Class is limited record Class : OBJ.Class; -- Agar(Object) -> Animal -- more fields -- Ecological_Group : Ecological_Group_t; Description : String (1 .. 200); end record with Convention => C; type Animal_Class_Access is access all Animal_Class with Convention => C; --------------------- -- Object Instance -- --------------------- type Animal is limited record Object : OBJ.Object; -- Agar(Object) -> Animal -- more fields -- Age : Interfaces.Unsigned_8; Exp : Interfaces.Unsigned_16; Name : String (1 .. 20); Bio : String (1 .. 100); X : C.double; Y : C.double; Z : C.double; end record with Convention => C; type Animal_Access is access all Animal with Convention => C; package C_cls is new System.Address_To_Access_Conversions (Animal_Class); Generic_Object_Class : OBJ.Class_Access := null; Animal_Object_Class : C_cls.Object_Pointer := null; function Create_Class return OBJ.Class_Not_Null_Access; procedure Destroy_Class; procedure Init (Object : OBJ.Object_Access) with Convention => C; procedure Destroy (Object : OBJ.Object_Access) with Convention => C; function Load (Object : OBJ.Object_Access; Source : DS.Data_Source_Access; Version : OBJ.Version_Access) return C.int with Convention => C; function Save (Object : OBJ.Object_Access; Dest : DS.Data_Source_Access) return C.int with Convention => C; end Animal;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; package body Matreshka.CLDR.Collation_Data is use type Matreshka.Internals.Unicode.Ucd.Collation_Weight; procedure Free is new Ada.Unchecked_Deallocation (Collation_Record, Collation_Record_Access); procedure Free is new Ada.Unchecked_Deallocation (Collation_Element_Array, Collation_Element_Array_Access); function Lookup (Data : Collation_Information; Item : Code_Point_Array) return Collation_Record_Access; procedure Attach (Data : in out Collation_Information; After : Collation_Record_Access; Item : Collation_Record_Access); -- Attach given collation record into the list of relative position of -- collation records immidiately after specified collation record. procedure Detach (Data : in out Collation_Information; Item : Collation_Record_Access); -- Detach given collation record from the list of relative position of -- collation records. procedure Recompute_Trinary (Current_Record : Collation_Record_Access); -- Resolves conflict at trinary level. ------------ -- Attach -- ------------ procedure Attach (Data : in out Collation_Information; After : Collation_Record_Access; Item : Collation_Record_Access) is begin if Data.Greater_Record = After then Data.Greater_Record := Item; end if; Item.Greater_Or_Equal := After.Greater_Or_Equal; Item.Less_Or_Equal := After; if After.Greater_Or_Equal /= null then After.Greater_Or_Equal.Less_Or_Equal := Item; end if; After.Greater_Or_Equal := Item; end Attach; ------------ -- Detach -- ------------ procedure Detach (Data : in out Collation_Information; Item : Collation_Record_Access) is begin -- Remove all other collation records. if Data.Lower_Record = Item then Data.Lower_Record := Item.Greater_Or_Equal; end if; if Data.Greater_Record = Item then Data.Greater_Record := Item.Less_Or_Equal; end if; if Item.Less_Or_Equal /= null then Item.Less_Or_Equal.Greater_Or_Equal := Item.Greater_Or_Equal; end if; if Item.Greater_Or_Equal /= null then Item.Greater_Or_Equal.Less_Or_Equal := Item.Less_Or_Equal; end if; Item.Less_Or_Equal := null; Item.Greater_Or_Equal := null; end Detach; ------------ -- Lookup -- ------------ function Lookup (Data : Collation_Information; Item : Code_Point_Array) return Collation_Record_Access is Current : Collation_Record_Access := Data.Collations (Item (Item'First)); begin while Current /= null loop exit when Current.Contractors.all = Item; Current := Current.Next; end loop; return Current; end Lookup; ----------------------- -- Recompute_Trinary -- ----------------------- procedure Recompute_Trinary (Current_Record : Collation_Record_Access) is Next_Record : constant Collation_Record_Access := Current_Record.Greater_Or_Equal; begin Current_Record.Collations (1).Trinary := Current_Record.Collations (1).Trinary + 1; if Next_Record.Collations (1).Primary = Current_Record.Collations (1).Primary and Next_Record.Collations (1).Secondary = Current_Record.Collations (1).Secondary and Next_Record.Collations (1).Trinary <= Current_Record.Collations (1).Trinary then raise Program_Error; end if; end Recompute_Trinary; ------------- -- Reorder -- ------------- procedure Reorder (Data : in out Collation_Information; Reset_Code : Matreshka.Internals.Unicode.Code_Point; Operator : Collation_Operator; Relation_Code : Matreshka.Internals.Unicode.Code_Point) is Reset_Record : constant Collation_Record_Access := Lookup (Data, (1 => Reset_Code)); Relation_Record : constant Collation_Record_Access := Lookup (Data, (1 => Relation_Code)); Next_Record : Collation_Record_Access; begin -- Detach relation collation record. Detach (Data, Relation_Record); -- Constructs collation elements. Free (Relation_Record.Collations); Relation_Record.Collations := new Collation_Element_Array'(Reset_Record.Collations.all); if Relation_Record.Collations'Length /= 1 then raise Program_Error; end if; case Operator is when Identically => raise Program_Error; when Primary => Relation_Record.Collations (1).Primary := Relation_Record.Collations (1).Primary + 1; Relation_Record.Collations (1).Secondary := 16#0020#; Relation_Record.Collations (1).Trinary := 16#0002#; -- Skip all elements with primary weight equal to reset position. Next_Record := Reset_Record.Greater_Or_Equal; while Next_Record.Collations (1).Primary = Reset_Record.Collations (1).Primary loop Next_Record := Next_Record.Greater_Or_Equal; end loop; -- And insert new collation record before it. Attach (Data, Next_Record.Less_Or_Equal, Relation_Record); if Next_Record.Collations (1).Primary <= Relation_Record.Collations (1).Primary then -- Reordering of the following records are not supported (and -- generally not need to be supported due to construction of -- initial data). raise Program_Error; end if; when Secondary => Relation_Record.Collations (1).Secondary := Relation_Record.Collations (1).Secondary + 1; Next_Record := Reset_Record.Greater_Or_Equal; -- Skip all elements with primary and secondary weights equal to -- reset positon. while Next_Record.Collations (1).Primary = Reset_Record.Collations (1).Primary and Next_Record.Collations (1).Secondary = Reset_Record.Collations (1).Secondary loop Next_Record := Next_Record.Greater_Or_Equal; end loop; -- And insert new collation record before it. Attach (Data, Next_Record.Less_Or_Equal, Relation_Record); if Next_Record.Collations (1).Primary = Relation_Record.Collations (1).Primary and Next_Record.Collations (1).Secondary <= Relation_Record.Collations (1).Secondary then raise Program_Error; end if; when Trinary => Relation_Record.Collations (1).Trinary := Relation_Record.Collations (1).Trinary + 1; Next_Record := Reset_Record.Greater_Or_Equal; -- Skip all elements with primary, secondary and trinary weights -- equal to reset positon. while Next_Record.Collations (1).Primary = Reset_Record.Collations (1).Primary and Next_Record.Collations (1).Secondary = Reset_Record.Collations (1).Secondary and Next_Record.Collations (1).Trinary = Reset_Record.Collations (1).Trinary loop Next_Record := Next_Record.Greater_Or_Equal; end loop; -- And insert new collation record before it. Attach (Data, Next_Record.Less_Or_Equal, Relation_Record); if Next_Record.Collations (1).Primary = Relation_Record.Collations (1).Primary and Next_Record.Collations (1).Secondary = Relation_Record.Collations (1).Secondary and Next_Record.Collations (1).Trinary <= Relation_Record.Collations (1).Trinary then Recompute_Trinary (Next_Record); end if; end case; end Reorder; --------------------------- -- Suppress_Contractions -- --------------------------- procedure Suppress_Contractions (Data : in out Collation_Information; Code : Matreshka.Internals.Unicode.Code_Point) is Current : Collation_Record_Access; Next : Collation_Record_Access; begin Current := Data.Collations (Code); while Current /= null loop Next := Current.Next; if Current.Contractors'Length = 1 then -- Only one collation record can be provides for single code -- point by construction. Left this collation record. Data.Collations (Code) := Current; Current.Next := null; else -- Remove all other collation records. if Data.Lower_Record = Current then Data.Lower_Record := Current.Greater_Or_Equal; end if; if Data.Greater_Record = Current then Data.Greater_Record := Current.Less_Or_Equal; end if; if Current.Less_Or_Equal /= null then Current.Less_Or_Equal.Greater_Or_Equal := Current.Greater_Or_Equal; end if; if Current.Greater_Or_Equal /= null then Current.Greater_Or_Equal.Less_Or_Equal := Current.Less_Or_Equal; end if; Free (Current); end if; Current := Next; end loop; end Suppress_Contractions; end Matreshka.CLDR.Collation_Data;
-- MIT License -- -- Copyright (c) 2020 Max Reznik -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. with Ada.Unchecked_Conversion; with League.Text_Codecs; package body PB_Support.Internal is use type Ada.Streams.Stream_Element_Count; procedure Write (Self : in out Stream; Value : Boolean) with Inline; procedure Write (Self : in out Stream; Value : Interfaces.IEEE_Float_32) with Inline; procedure Write (Self : in out Stream; Value : Interfaces.IEEE_Float_64) with Inline; procedure Write (Self : in out Stream; Value : League.Strings.Universal_String) with Inline; procedure Write (Self : in out Stream; Value : League.Stream_Element_Vectors.Stream_Element_Vector) with Inline; procedure Write_Varint (Self : in out Stream; Value : Interfaces.Unsigned_32) with Inline; procedure Write_Varint (Self : in out Stream; Value : Interfaces.Unsigned_64) with Inline; procedure Write_Varint (Self : in out Stream; Value : Interfaces.Integer_64) with Inline; procedure Write_Zigzag (Self : in out Stream; Value : Interfaces.Integer_32) with Inline; procedure Write_Zigzag (Self : in out Stream; Value : Interfaces.Integer_64) with Inline; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Integer_32) with Inline; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Integer_64) with Inline; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Unsigned_32) with Inline; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Unsigned_64) with Inline; ---------- -- Size -- ---------- function Size (Value : Interfaces.Unsigned_32) return Ada.Streams.Stream_Element_Count is use type Interfaces.Unsigned_32; Left : Interfaces.Unsigned_32 := Value; Last : Ada.Streams.Stream_Element_Count := 0; begin while Left >= 16#80# loop Last := Last + 1; Left := Interfaces.Shift_Right (Left, 7); end loop; Last := Last + 1; return Last; end Size; function Size (Value : Interfaces.Unsigned_64) return Ada.Streams.Stream_Element_Count is use type Interfaces.Unsigned_64; Left : Interfaces.Unsigned_64 := Value; Last : Ada.Streams.Stream_Element_Count := 0; begin while Left >= 16#80# loop Last := Last + 1; Left := Interfaces.Shift_Right (Left, 7); end loop; Last := Last + 1; return Last; end Size; function Size (Value : Interfaces.Integer_32) return Ada.Streams.Stream_Element_Count is use type Interfaces.Integer_32; begin if Value < 0 then return 10; else return Size (Interfaces.Unsigned_32 (Value)); end if; end Size; function Size (Value : Interfaces.Integer_64) return Ada.Streams.Stream_Element_Count is use type Interfaces.Integer_64; begin if Value < 0 then return 10; else return Size (Interfaces.Unsigned_64 (Value)); end if; end Size; ------------------- -- Start_Message -- ------------------- not overriding procedure Start_Message (Self : in out Stream) is begin Self.Level := Self.Level + 1; if Self.Level = 2 then Self.Riffling := not Self.Riffling; if Self.Riffling then Self.Size.Clear; Self.Size.Set_Length (0); Self.Index := 1; end if; end if; if Self.Riffling then Self.Size.Append (Self.Written); Self.Stack.Append (Self.Size.Last_Index); elsif Self.Level > 1 then Self.Write (Self.Size (Self.Index)); Self.Index := Self.Index + 1; end if; end Start_Message; ----------------- -- End_Message -- ----------------- not overriding function End_Message (Self : in out Stream) return Boolean is Id : Message_Id; begin if Self.Riffling then Id := Self.Stack.Last_Element; Self.Stack.Delete_Last; Self.Size (Id) := Self.Written - Self.Size (Id); Self.Write (Self.Size (Id)); end if; Self.Level := Self.Level - 1; return Self.Level = 1 and Self.Riffling; end End_Message; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : Boolean) is begin Self.Write_Key ((Field, Var_Int)); Self.Write (Value); end Write; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : Boolean) is begin if Self.Riffling then Self.Written := Self.Written + 1; elsif Value then Self.Parent.Write ((1 => 1)); else Self.Parent.Write ((1 => 0)); end if; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : PB_Support.Boolean_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write (Field, Value.Get (J)); end loop; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : Interfaces.IEEE_Float_32) is begin Self.Write_Key ((Field, Fixed_32)); Self.Write (Value); end Write; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : Interfaces.IEEE_Float_32) is begin if Self.Riffling then Self.Written := Self.Written + 4; else Interfaces.IEEE_Float_32'Write (Self.Parent, Value); end if; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : PB_Support.IEEE_Float_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write (Field, Value.Get (J)); end loop; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : PB_Support.IEEE_Float_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write (Field, Value.Get (J)); end loop; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : Interfaces.IEEE_Float_64) is begin Self.Write_Key ((Field, Fixed_64)); Self.Write (Value); end Write; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : Interfaces.IEEE_Float_64) is begin if Self.Riffling then Self.Written := Self.Written + 8; else Interfaces.IEEE_Float_64'Write (Self.Parent, Value); end if; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : League.Strings.Universal_String) is begin Self.Write_Key ((Field, Length_Delimited)); Self.Write (Value); end Write; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : League.Strings.Universal_String) is Codec : constant League.Text_Codecs.Text_Codec := League.Text_Codecs.Codec (League.Strings.To_Universal_String ("utf-8")); Data : constant League.Stream_Element_Vectors.Stream_Element_Vector := Codec.Encode (Value); begin Self.Write (Data); end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : League.String_Vectors.Universal_String_Vector) is begin for J in 1 .. Value.Length loop Self.Write (Field, Value.Element (J)); end loop; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : PB_Support.Stream_Element_Vector_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write (Field, Value.Get (J)); end loop; end Write; ----------- -- Write -- ----------- not overriding procedure Write (Self : in out Stream; Field : Field_Number; Value : League.Stream_Element_Vectors.Stream_Element_Vector) is begin Self.Write_Key ((Field, Length_Delimited)); Self.Write (Value); end Write; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : League.Stream_Element_Vectors.Stream_Element_Vector) is begin Self.Write (Value.Length); if Self.Riffling then Self.Written := Self.Written + Value.Length; else Self.Parent.Write (Value.To_Stream_Element_Array); end if; end Write; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_32) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Varint (Value); end Write_Varint; ------------------ -- Write_Varint -- ------------------ procedure Write_Varint (Self : in out Stream; Value : Interfaces.Unsigned_32) is use type Interfaces.Unsigned_32; Left : Interfaces.Unsigned_32 := Value; Data : Ada.Streams.Stream_Element_Array (1 .. 32 / 7 + 1); Last : Ada.Streams.Stream_Element_Count := 0; begin while Left >= 16#80# loop Last := Last + 1; Data (Last) := Ada.Streams.Stream_Element ((Left and 16#7F#) + 16#80#); Left := Interfaces.Shift_Right (Left, 7); end loop; Last := Last + 1; if Self.Riffling then Self.Written := Self.Written + Last; else Data (Last) := Ada.Streams.Stream_Element'Mod (Left); Self.Parent.Write (Data (1 .. Last)); end if; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Varint (Field, Value.Get (J)); end loop; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_64) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Varint (Value); end Write_Varint; ------------------ -- Write_Varint -- ------------------ procedure Write_Varint (Self : in out Stream; Value : Interfaces.Unsigned_64) is use type Interfaces.Unsigned_64; Left : Interfaces.Unsigned_64 := Value; Data : Ada.Streams.Stream_Element_Array (1 .. 64 / 7 + 1); Last : Ada.Streams.Stream_Element_Count := 0; begin while Left >= 16#80# loop Last := Last + 1; Data (Last) := Ada.Streams.Stream_Element ((Left and 16#7F#) + 16#80#); Left := Interfaces.Shift_Right (Left, 7); end loop; Last := Last + 1; if Self.Riffling then Self.Written := Self.Written + Last; else Data (Last) := Ada.Streams.Stream_Element'Mod (Left); Self.Parent.Write (Data (1 .. Last)); end if; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Varint (Value); end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Value : Interfaces.Integer_32) is begin -- "If you use int32 or int64 as the type for a negative number, the -- resulting varint is always ten bytes long" Self.Write_Varint (Interfaces.Integer_64 (Value)); end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Varint (Field, Value.Get (J)); end loop; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Varint (Field, Value.Get (J)); end loop; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Varint (Field, Value.Get (J)); end loop; end Write_Varint; ------------------ -- Write_Varint -- ------------------ not overriding procedure Write_Varint (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Varint (Value); end Write_Varint; ------------------ -- Write_Varint -- ------------------ procedure Write_Varint (Self : in out Stream; Value : Interfaces.Integer_64) is function Cast is new Ada.Unchecked_Conversion (Interfaces.Integer_64, Interfaces.Unsigned_64); begin Self.Write_Varint (Cast (Value)); end Write_Varint; not overriding procedure Write_Varint_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_32; Default : Interfaces.Unsigned_32) is use type Interfaces.Unsigned_32; begin if Value /= Default then Self.Write_Varint (Field, Value); end if; end Write_Varint_Option; not overriding procedure Write_Varint_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_64; Default : Interfaces.Unsigned_64) is use type Interfaces.Unsigned_64; begin if Value /= Default then Self.Write_Varint (Field, Value); end if; end Write_Varint_Option; not overriding procedure Write_Varint_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32; Default : Interfaces.Integer_32) is use type Interfaces.Integer_32; begin if Value /= Default then Self.Write_Varint (Field, Value); end if; end Write_Varint_Option; not overriding procedure Write_Varint_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64; Default : Interfaces.Integer_64) is use type Interfaces.Integer_64; begin if Value /= Default then Self.Write_Varint (Field, Value); end if; end Write_Varint_Option; not overriding procedure Write_Varint_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_32_Vectors.Vector) is Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (Value.Get (J)); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Varint (Value.Get (J)); end loop; end if; end Write_Varint_Packed; not overriding procedure Write_Varint_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_64_Vectors.Vector) is Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (Value.Get (J)); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Varint (Value.Get (J)); end loop; end if; end Write_Varint_Packed; not overriding procedure Write_Varint_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (Value.Get (J)); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Varint (Value.Get (J)); end loop; end if; end Write_Varint_Packed; not overriding procedure Write_Varint_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (Value.Get (J)); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Varint (Value.Get (J)); end loop; end if; end Write_Varint_Packed; ----------- -- Write -- ----------- procedure Write (Self : in out Stream; Value : Ada.Streams.Stream_Element_Count) is begin Self.Write_Varint (Interfaces.Unsigned_32 (Value)); end Write; ----------- -- Write -- ----------- overriding procedure Write (Stream : in out Internal.Stream; Item : Ada.Streams.Stream_Element_Array) is begin raise Program_Error with "Unexpected call to Write procedure"; end Write; --------------- -- Write_Key -- --------------- not overriding procedure Write_Key (Self : in out Stream; Value : Key) is use type Interfaces.Unsigned_32; Integer : constant Interfaces.Unsigned_32 := Interfaces.Shift_Left (Interfaces.Unsigned_32 (Value.Field), 3) + Wire_Type'Pos (Value.Encoding); begin Self.Write_Varint (Integer); end Write_Key; not overriding procedure Write_Option (Self : in out Stream; Field : Field_Number; Value : Boolean; Default : Boolean) is begin if Value /= Default then Self.Write (Field, Value); end if; end Write_Option; not overriding procedure Write_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.IEEE_Float_32; Default : Interfaces.IEEE_Float_32) is use type Interfaces.IEEE_Float_32; begin if Value /= Default then Self.Write (Field, Value); end if; end Write_Option; not overriding procedure Write_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.IEEE_Float_64; Default : Interfaces.IEEE_Float_64) is use type Interfaces.IEEE_Float_64; begin if Value /= Default then Self.Write (Field, Value); end if; end Write_Option; not overriding procedure Write_Option (Self : in out Stream; Field : Field_Number; Value : League.Strings.Universal_String; Default : League.Strings.Universal_String := League.Strings.Empty_Universal_String) is use type League.Strings.Universal_String; begin if Value /= Default then Self.Write (Field, Value); end if; end Write_Option; not overriding procedure Write_Option (Self : in out Stream; Field : Field_Number; Value : League.Stream_Element_Vectors.Stream_Element_Vector; Default : League.Stream_Element_Vectors.Stream_Element_Vector := League.Stream_Element_Vectors.Empty_Stream_Element_Vector) is use type League.Stream_Element_Vectors.Stream_Element_Vector; begin if Value /= Default then Self.Write (Field, Value); end if; end Write_Option; not overriding procedure Write_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Boolean_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length); Data : Ada.Streams.Stream_Element_Array (1 .. Length); begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in Data'Range loop Data (J) := Boolean'Pos (Value.Get (Positive (J))); end loop; Self.Parent.Write (Data); end if; end Write_Packed; not overriding procedure Write_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.IEEE_Float_32_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 4; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write (Value.Get (J)); end loop; end if; end Write_Packed; not overriding procedure Write_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.IEEE_Float_64_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 8; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write (Value.Get (J)); end loop; end if; end Write_Packed; procedure Write_Zigzag (Self : in out Stream; Value : Interfaces.Integer_32) is use Interfaces; Unsigned : constant Interfaces.Unsigned_32 := 2 * Interfaces.Unsigned_32 (abs Value) + Boolean'Pos (Value < 0); begin Self.Write_Varint (Unsigned); end Write_Zigzag; procedure Write_Zigzag (Self : in out Stream; Value : Interfaces.Integer_64) is use Interfaces; Unsigned : constant Interfaces.Unsigned_64 := 2 * Interfaces.Unsigned_64 (abs Value) + Boolean'Pos (Value < 0); begin Self.Write_Varint (Unsigned); end Write_Zigzag; ------------------ -- Write_Zigzag -- ------------------ not overriding procedure Write_Zigzag (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Zigzag (Value); end Write_Zigzag; not overriding procedure Write_Zigzag (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64) is begin Self.Write_Key ((Field, Var_Int)); Self.Write_Zigzag (Value); end Write_Zigzag; not overriding procedure Write_Zigzag (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Zigzag (Field, Value.Get (J)); end loop; end Write_Zigzag; not overriding procedure Write_Zigzag (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Zigzag (Field, Value.Get (J)); end loop; end Write_Zigzag; not overriding procedure Write_Zigzag_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32; Default : Interfaces.Integer_32) is use type Interfaces.Integer_32; begin if Value /= Default then Self.Write_Zigzag (Field, Value); end if; end Write_Zigzag_Option; not overriding procedure Write_Zigzag_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64; Default : Interfaces.Integer_64) is use type Interfaces.Integer_64; begin if Value /= Default then Self.Write_Zigzag (Field, Value); end if; end Write_Zigzag_Option; not overriding procedure Write_Zigzag_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is use type Interfaces.Integer_32; use type Interfaces.Unsigned_32; Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (2 * Interfaces.Unsigned_32 (abs Value.Get (J))); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Zigzag (Value.Get (J)); end loop; end if; end Write_Zigzag_Packed; not overriding procedure Write_Zigzag_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is use type Interfaces.Integer_64; use type Interfaces.Unsigned_64; Length : Ada.Streams.Stream_Element_Count := 0; begin if Value.Length = 0 then return; end if; for J in 1 .. Value.Length loop Length := Length + Size (2 * Interfaces.Unsigned_64 (abs Value.Get (J))); end loop; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Zigzag (Value.Get (J)); end loop; end if; end Write_Zigzag_Packed; ----------------- -- Write_Fixed -- ----------------- procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Integer_32) is begin if Self.Riffling then Self.Written := Self.Written + 4; else Interfaces.Integer_32'Write (Self.Parent, Value); end if; end Write_Fixed; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Integer_64) is begin if Self.Riffling then Self.Written := Self.Written + 8; else Interfaces.Integer_64'Write (Self.Parent, Value); end if; end Write_Fixed; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Unsigned_32) is begin if Self.Riffling then Self.Written := Self.Written + 4; else Interfaces.Unsigned_32'Write (Self.Parent, Value); end if; end Write_Fixed; procedure Write_Fixed (Self : in out Stream; Value : Interfaces.Unsigned_64) is begin if Self.Riffling then Self.Written := Self.Written + 8; else Interfaces.Unsigned_64'Write (Self.Parent, Value); end if; end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32) is begin Self.Write_Key ((Field, Fixed_32)); Self.Write_Fixed (Value); end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64) is begin Self.Write_Key ((Field, Fixed_64)); Self.Write_Fixed (Value); end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_32) is begin Self.Write_Key ((Field, Fixed_32)); Self.Write_Fixed (Value); end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_64) is begin Self.Write_Key ((Field, Fixed_64)); Self.Write_Fixed (Value); end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Fixed (Field, Value.Get (J)); end loop; end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Fixed (Field, Value.Get (J)); end loop; end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_32_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Fixed (Field, Value.Get (J)); end loop; end Write_Fixed; not overriding procedure Write_Fixed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_64_Vectors.Vector) is begin for J in 1 .. Value.Length loop Self.Write_Fixed (Field, Value.Get (J)); end loop; end Write_Fixed; not overriding procedure Write_Fixed_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_32; Default : Interfaces.Unsigned_32) is use type Interfaces.Unsigned_32; begin if Value /= Default then Self.Write_Fixed (Field, Value); end if; end Write_Fixed_Option; not overriding procedure Write_Fixed_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Unsigned_64; Default : Interfaces.Unsigned_64) is use type Interfaces.Unsigned_64; begin if Value /= Default then Self.Write_Fixed (Field, Value); end if; end Write_Fixed_Option; not overriding procedure Write_Fixed_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_32; Default : Interfaces.Integer_32) is use type Interfaces.Integer_32; begin if Value /= Default then Self.Write_Fixed (Field, Value); end if; end Write_Fixed_Option; not overriding procedure Write_Fixed_Option (Self : in out Stream; Field : Field_Number; Value : Interfaces.Integer_64; Default : Interfaces.Integer_64) is use type Interfaces.Integer_64; begin if Value /= Default then Self.Write_Fixed (Field, Value); end if; end Write_Fixed_Option; not overriding procedure Write_Fixed_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_32_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 4; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Fixed (Value.Get (J)); end loop; end if; end Write_Fixed_Packed; not overriding procedure Write_Fixed_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Integer_64_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 8; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Fixed (Value.Get (J)); end loop; end if; end Write_Fixed_Packed; not overriding procedure Write_Fixed_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_32_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 4; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Fixed (Value.Get (J)); end loop; end if; end Write_Fixed_Packed; not overriding procedure Write_Fixed_Packed (Self : in out Stream; Field : Field_Number; Value : PB_Support.Unsigned_64_Vectors.Vector) is Length : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Value.Length) * 8; begin if Value.Length = 0 then return; end if; Self.Write_Key ((Field, Length_Delimited)); Self.Write (Length); if Self.Riffling then Self.Written := Self.Written + Length; else for J in 1 .. Value.Length loop Self.Write_Fixed (Value.Get (J)); end loop; end if; end Write_Fixed_Packed; end PB_Support.Internal;
-- $Header: /cf/ua/arcadia/alex-ayacc/ayacc/src/RCS/cli__read_command_line.a,v 1.1 88/08/08 12:08:33 arcadia Exp $ --*************************************************************************** -- This file is subject to the Arcadia License Agreement. -- -- (see notice in ayacc.a) -- --*************************************************************************** --| --| Notes: This routine contains the machine specific details of how --| Ayacc obtains the command line arguments from the host Operating --| System. This version assumes Alsys running on DOS machines. --| (modified by Sriram Sankar) --| --| The only requirement on this subunit is that it place the string --| of characters typed by the user on the command line into the --| parameter "Command_Args". --| with DOS; use DOS; separate (Command_Line_Interface) procedure Read_Command_Line (Command_Args : out Command_Line_Type) is Parms : constant String := Get_Parms; begin Command_Args(Command_Args'First .. Command_Args'First+Parms'Length-1) := Parms; Command_Args(Command_Args'First+Parms'Length .. Command_Args'Last) := (others => ' '); end Read_Command_Line;
with System; use System; -- with Ada.Text_IO; package body STM32GD.USART.Peripheral is procedure putchar (Data : in Character) with Import => true, Convention => C; procedure Init is begin null; end Init; procedure Transmit (Data : in Byte) is begin putchar (Character'Val (Data)); end Transmit; function Receive return Byte is begin return 0; end Receive; end STM32GD.USART.Peripheral;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ equals used in skill -- -- |___/_|\_\_|_|____| by: Timm Felden -- -- -- pragma Ada_2012; with Ada.Containers; with Ada.Strings.Hash; with Skill.Types; with Skill.Types.Pools; with Interfaces; -- the trick of this package is to instantiate equals codes as Skill.Equals.equals -- independent of the type! :) package Skill.Equals is -- pragma Preelaborate; use type Skill.Types.String_Access; use Interfaces; function Equals (A, B : Skill.Types.String_Access) return Boolean is (A = B or else ((null /= A and null /= B) and then A.all = B.all) ); use type Skill.Types.Pools.Pool; function Equals (A, B : Skill.Types.Pools.Pool) return Boolean is (A = B); function Equals (A, B : Interfaces.Integer_8) return Boolean is (A = B); function Equals (A, B : Interfaces.Integer_16) return Boolean is (A = B); function Equals (A, B : Interfaces.Integer_32) return Boolean is (A = B); function Equals (A, B : Interfaces.Integer_64) return Boolean is (A = B); end Skill.Equals;
with mwc_constants; use mwc_constants; generic type Parent_Random_Int is mod <>; package LCG_Rand with Spark_Mode => On is pragma Pure (LCG_Rand); pragma Assert (Parent_Random_Int'Modulus > 2**63-1); pragma Assert (m0 < Parent_Random_Int'Last); pragma Assert (m1 < Parent_Random_Int'Last); subtype Valid_LCG_0_Range is Parent_Random_Int range 1 .. m0 - 1; subtype Valid_LCG_1_Range is Parent_Random_Int range 1 .. m1 - 1; procedure Get_Random_LCG_64_0 (X0 : in out Parent_Random_Int); pragma Inline (Get_Random_LCG_64_0); -- x0 = 0 gives period of 1; needs to be rejected as a seed. procedure Get_Random_LCG_64_1 (X1 : in out Parent_Random_Int); pragma Inline (Get_Random_LCG_64_1); -- x1 = 0 gives period of 1; needs to be rejected as a seed. procedure Get_Random_LCG_64_Combined (S0 : in out Parent_Random_Int; S1 : in out Parent_Random_Int; Random_x : out Parent_Random_Int); -- result -- S1 = 0 and S2 = 0 give reduced periods; need to be rejected as a seeds. end LCG_Rand;
with volatile1; use volatile1; package volatile2 is type PData_Array is access Data_Array; type Result_Desc is record Data : PData_Array; end record; type Result is access Result_Desc; procedure Copy; end volatile2;
-- C74306A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- AFTER THE FULL DECLARATION OF A DEFERRED CONSTANT, THE VALUE OF -- THE CONSTANT MAY BE USED IN ANY EXPRESSION, PARTICULARLY -- EXPRESSIONS IN WHICH THE USE WOULD BE ILLEGAL BEFORE THE FULL -- DECLARATION. -- HISTORY: -- BCB 03/14/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE C74306A IS GENERIC TYPE GENERAL_PURPOSE IS LIMITED PRIVATE; Y : IN OUT GENERAL_PURPOSE; FUNCTION IDENT (X : GENERAL_PURPOSE) RETURN GENERAL_PURPOSE; FUNCTION IDENT (X : GENERAL_PURPOSE) RETURN GENERAL_PURPOSE IS BEGIN IF EQUAL(3,3) THEN RETURN X; END IF; RETURN Y; END IDENT; PACKAGE P IS TYPE T IS PRIVATE; C : CONSTANT T; PRIVATE TYPE T IS RANGE 1 .. 100; TYPE A IS ARRAY(1..2) OF T; TYPE B IS ARRAY(INTEGER RANGE <>) OF T; TYPE D (DISC : T) IS RECORD NULL; END RECORD; C : CONSTANT T := 50; PARAM : T := 99; FUNCTION IDENT_T IS NEW IDENT (T, PARAM); FUNCTION F (X : T := C) RETURN T; SUBTYPE RAN IS T RANGE 1 .. C; SUBTYPE IND IS B(1..INTEGER(C)); SUBTYPE DIS IS D (DISC => C); OBJ : T := C; CON : CONSTANT T := C; ARR : A := (5, C); PAR : T := IDENT_T (C); RANOBJ : T RANGE 1 .. C := C; INDOBJ : B(1..INTEGER(C)); DIS_VAL : DIS; REN : T RENAMES C; GENERIC FOR_PAR : T := C; PACKAGE GENPACK IS VAL : T; END GENPACK; GENERIC IN_PAR : IN T; PACKAGE NEWPACK IS IN_VAL : T; END NEWPACK; END P; USE P; PACKAGE BODY P IS TYPE A1 IS ARRAY(1..2) OF T; TYPE B1 IS ARRAY(INTEGER RANGE <>) OF T; TYPE D1 (DISC1 : T) IS RECORD NULL; END RECORD; SUBTYPE RAN1 IS T RANGE 1 .. C; SUBTYPE IND1 IS B1(1..INTEGER(C)); SUBTYPE DIS1 IS D1 (DISC1 => C); OBJ1 : T := C; FUNCVAR : T; CON1 : CONSTANT T := C; ARR1 : A1 := (5, C); PAR1 : T := IDENT_T (C); RANOBJ1 : T RANGE 1 .. C := C; INDOBJ1 : B1(1..INTEGER(C)); DIS_VAL1 : DIS1; REN1 : T RENAMES C; FUNCTION F (X : T := C) RETURN T IS BEGIN RETURN C; END F; PACKAGE BODY GENPACK IS BEGIN VAL := FOR_PAR; END GENPACK; PACKAGE BODY NEWPACK IS BEGIN IN_VAL := IN_PAR; END NEWPACK; PACKAGE PACK IS NEW GENPACK (FOR_PAR => C); PACKAGE NPACK IS NEW NEWPACK (IN_PAR => C); BEGIN TEST ("C74306A", "AFTER THE FULL DECLARATION OF A DEFERRED " & "CONSTANT, THE VALUE OF THE CONSTANT MAY " & "BE USED IN ANY EXPRESSION, PARTICULARLY " & "EXPRESSIONS IN WHICH THE USE WOULD BE " & "ILLEGAL BEFORE THE FULL DECLARATION"); IF OBJ /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR OBJ"); END IF; IF CON /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR CON"); END IF; IF ARR /= (IDENT_T(5), IDENT_T(50)) THEN FAILED ("IMPROPER VALUES FOR ARR"); END IF; IF PAR /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR PAR"); END IF; IF OBJ1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR OBJ1"); END IF; IF CON1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR CON1"); END IF; IF ARR1 /= (IDENT_T(5), IDENT_T(50)) THEN FAILED ("IMPROPER VALUES FOR ARR1"); END IF; IF PAR1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR PAR1"); END IF; IF PACK.VAL /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR PACK.VAL"); END IF; IF NPACK.IN_VAL /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR NPACK.IN_VAL"); END IF; IF RAN'LAST /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR RAN'LAST"); END IF; IF RANOBJ /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR RANOBJ"); END IF; IF IND'LAST /= IDENT_INT(50) THEN FAILED ("IMPROPER VALUE FOR IND'LAST"); END IF; IF INDOBJ'LAST /= IDENT_INT(50) THEN FAILED ("IMPROPER VALUE FOR INDOBJ'LAST"); END IF; IF DIS_VAL.DISC /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR DIS_VAL.DISC"); END IF; IF REN /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR REN"); END IF; IF RAN1'LAST /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR RAN1'LAST"); END IF; IF RANOBJ1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR RANOBJ1"); END IF; IF IND1'LAST /= IDENT_INT(50) THEN FAILED ("IMPROPER VALUE FOR IND1'LAST"); END IF; IF INDOBJ1'LAST /= IDENT_INT(50) THEN FAILED ("IMPROPER VALUE FOR INDOBJ1'LAST"); END IF; IF DIS_VAL1.DISC1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR DIS_VAL1.DISC1"); END IF; IF REN1 /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR REN1"); END IF; FUNCVAR := F(C); IF FUNCVAR /= IDENT_T(50) THEN FAILED ("IMPROPER VALUE FOR FUNCVAR"); END IF; RESULT; END P; BEGIN DECLARE TYPE ARR IS ARRAY(1..2) OF T; VAL1 : T := C; VAL2 : ARR := (C, C); VAL3 : T RENAMES C; BEGIN NULL; END; NULL; END C74306A;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with AdaBase.Statement; package AdaBase.Interfaces.Connection is type iConnection is interface; package AS renames AdaBase.Statement; -- Autocommit procedure setAutoCommit (conn : out iConnection; auto : Boolean) is null; function autoCommit (conn : iConnection) return Boolean is abstract; -- Column Header Case Mode procedure setCaseMode (conn : out iConnection; mode : Case_Modes) is null; function getCaseMode (conn : iConnection) return Case_Modes is abstract; -- Set Compression Mode (if supported) procedure setCompressed (conn : out iConnection; compressed : Boolean) is null; function compressed (conn : iConnection) return Boolean is abstract; -- Set Buffered Queries (aka prefetch, if supported) procedure setUseBuffer (conn : out iConnection; buffered : Boolean) is null; function useBuffer (conn : iConnection) return Boolean is abstract; -- Set processing of multiple statements per query (if supported) procedure setMultiQuery (conn : out iConnection; multiple : Boolean) is null; function multiquery (conn : iConnection) return Boolean is abstract; -- Set maximum size of result that buffer must accommodate (if supported) procedure setMaxBlobSize (conn : out iConnection; maxsize : BLOB_Maximum) is null; function maxBlobSize (conn : iConnection) return BLOB_Maximum is abstract; -- Set transaction Isolation level procedure setTransactionIsolation (conn : out iConnection; isolation : Trax_Isolation) is null; function transactionIsolation (conn : iConnection) return Trax_Isolation is abstract; -- Set Character Set (only prior to connection) -- procedure set_character_set (conn : out iConnection; charset : String) is null; function character_set (conn : out iConnection) return String is abstract; -- properties function serverVersion (conn : iConnection) return String is abstract; function serverInfo (conn : iConnection) return String is abstract; function clientVersion (conn : iConnection) return String is abstract; function clientInfo (conn : iConnection) return String is abstract; function description (conn : iConnection) return String is abstract; function connected (conn : iConnection) return Boolean is abstract; -- Error information associated with last query function SqlState (conn : iConnection) return SQL_State is abstract; function driverMessage (conn : iConnection) return String is abstract; function driverCode (conn : iConnection) return Driver_Codes is abstract; -- Information associated with previous successful query function lastInsertID (conn : iConnection) return Trax_ID is abstract; function rows_affected_by_execution (conn : iConnection) return Affected_Rows is abstract; -- Commands procedure commit (conn : out iConnection) is null; procedure rollback (conn : out iConnection) is null; procedure disconnect (conn : out iConnection) is null; procedure execute (conn : out iConnection; sql : String) is null; procedure connect (conn : out iConnection; database : String; username : String := blankstring; password : String := blankstring; hostname : String := blankstring; socket : String := blankstring; port : Posix_Port := portless) is null; end AdaBase.Interfaces.Connection;
-- -- Copyright (C) 2020, AdaCore -- -- This spec has been automatically generated from FU540.svd -- This is a version for the E54 CPU Coreplex, high-performance, 64-bit -- RV64IMAFDC core -- MCU package Ada.Interrupts.Names is -- All identifiers in this unit are implementation defined pragma Implementation_Defined; ---------------- -- Interrupts -- ---------------- Watchdog_Interrupt : constant Interrupt_ID := 1; RTC_Interrupt : constant Interrupt_ID := 2; UART0_Interrupt : constant Interrupt_ID := 3; UART1_Interrupt : constant Interrupt_ID := 4; GPIO_0_Interrupt : constant Interrupt_ID := 7; GPIO_1_Interrupt : constant Interrupt_ID := 8; GPIO_2_Interrupt : constant Interrupt_ID := 9; GPIO_3_Interrupt : constant Interrupt_ID := 10; GPIO_4_Interrupt : constant Interrupt_ID := 11; GPIO_5_Interrupt : constant Interrupt_ID := 12; GPIO_6_Interrupt : constant Interrupt_ID := 13; GPIO_7_Interrupt : constant Interrupt_ID := 14; GPIO_8_Interrupt : constant Interrupt_ID := 15; GPIO_9_Interrupt : constant Interrupt_ID := 16; GPIO_10_Interrupt : constant Interrupt_ID := 17; GPIO_11_Interrupt : constant Interrupt_ID := 18; GPIO_12_Interrupt : constant Interrupt_ID := 19; GPIO_14_Interrupt : constant Interrupt_ID := 21; GPIO_15_Interrupt : constant Interrupt_ID := 22; PWMO_CMP0_Interrupt : constant Interrupt_ID := 40; PWMO_CMP1_Interrupt : constant Interrupt_ID := 41; PWMO_CMP2_Interrupt : constant Interrupt_ID := 42; PWMO_CMP3_Interrupt : constant Interrupt_ID := 43; PWM1_CMP0_Interrupt : constant Interrupt_ID := 44; PWM1_CMP1_Interrupt : constant Interrupt_ID := 45; PWM1_CMP2_Interrupt : constant Interrupt_ID := 46; PWM1_CMP3_Interrupt : constant Interrupt_ID := 47; PWM2_CMP0_Interrupt : constant Interrupt_ID := 48; PWM2_CMP1_Interrupt : constant Interrupt_ID := 49; PWM2_CMP2_Interrupt : constant Interrupt_ID := 50; PWM2_CMP3_Interrupt : constant Interrupt_ID := 51; end Ada.Interrupts.Names;
-- AC3106A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT AN ACTUAL GENERIC IN OUT PARAMETER CAN BE: -- A) ANY SUBCOMPONENT THAT DOES NOT DEPEND ON A DISCRIMINANT, -- EVEN IF THE ENCLOSING VARIABLE IS UNCONSTRAINED; -- B) ANY SUBCOMPONENT OF AN UNCONSTAINED VARIABLE OF A -- RECORD TYPE IF THE DISCRIMINANTS OF THE -- VARIABLE DO NOT HAVE DEFAULTS AND THE VARIABLE IS NOT -- A GENERIC FORMAL IN OUT PARAMETER; -- C) ANY COMPONENT OF AN OBJECT DESIGNATED BY AN ACCESS -- VALUE. -- HISTORY: -- RJW 11/07/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE AC3106A IS SUBTYPE INT IS INTEGER RANGE 0 .. 10; TYPE REC (D : INT := 0) IS RECORD A : INTEGER := 5; CASE D IS WHEN OTHERS => V : INTEGER := 5; END CASE; END RECORD; TYPE AR_REC IS ARRAY (1 .. 10) OF REC; TYPE R_REC IS RECORD E : REC; END RECORD; TYPE A_STRING IS ACCESS STRING; TYPE A_REC IS ACCESS REC; TYPE A_AR_REC IS ACCESS AR_REC; TYPE A_R_REC IS ACCESS R_REC; TYPE DIS (L : INT := 1) IS RECORD S : STRING (1 .. L) := "A"; R : REC (L); AS : A_STRING (1 .. L) := NEW STRING (1 .. L); AR : A_REC (L) := NEW REC (1); RC : REC (3); ARU : A_REC := NEW REC; V_AR : AR_REC; V_R : R_REC; AC_AR : A_AR_REC := NEW AR_REC; AC_R : A_R_REC := NEW R_REC; END RECORD; TYPE A_DIS IS ACCESS DIS; AD : A_DIS := NEW DIS; TYPE DIS2 (L : INT) IS RECORD S : STRING (1 .. L); R : REC (L); AS : A_STRING (1 .. L); AR : A_REC (L); END RECORD; X : DIS; SUBTYPE REC3 IS REC (3); GENERIC GREC3 : IN OUT REC3; PACKAGE PREC3 IS END PREC3; SUBTYPE REC0 IS REC (0); GENERIC GREC0 : IN OUT REC0; PACKAGE PREC0 IS END PREC0; GENERIC GINT : IN OUT INTEGER; PACKAGE PINT IS END PINT; GENERIC GA_REC : IN OUT A_REC; PACKAGE PA_REC IS END PA_REC; GENERIC GAR_REC : IN OUT AR_REC; PACKAGE PAR_REC IS END PAR_REC; GENERIC GR_REC : IN OUT R_REC; PACKAGE PR_REC IS END PR_REC; GENERIC GA_AR_REC : IN OUT A_AR_REC; PACKAGE PA_AR_REC IS END PA_AR_REC; GENERIC GA_R_REC : IN OUT A_R_REC; PACKAGE PA_R_REC IS END PA_R_REC; TYPE BUFFER (SIZE : INT) IS RECORD POS : NATURAL := 0; VAL : STRING (1 .. SIZE); END RECORD; SUBTYPE BUFF_5 IS BUFFER (5); GENERIC Y : IN OUT CHARACTER; PACKAGE P_CHAR IS END P_CHAR; SUBTYPE STRING5 IS STRING (1 .. 5); GENERIC GSTRING : STRING5; PACKAGE P_STRING IS END P_STRING; GENERIC GA_STRING : A_STRING; PACKAGE P_A_STRING IS END P_A_STRING; GENERIC X : IN OUT BUFF_5; PACKAGE P_BUFF IS RX : BUFF_5 RENAMES X; END P_BUFF; Z : BUFFER (1) := (SIZE => 1, POS =>82, VAL =>"R"); BEGIN TEST ("AC3106A", "CHECK THE PERMITTED FORMS OF AN ACTUAL " & "GENERIC IN OUT PARAMETER"); DECLARE -- A) PACKAGE NPINT3 IS NEW PINT (X.RC.A); PACKAGE NPINT4 IS NEW PINT (X.RC.V); PACKAGE NPREC3 IS NEW PREC3 (X.RC); PACKAGE NPA_REC IS NEW PA_REC (X.ARU); PACKAGE NPINT5 IS NEW PINT (X.ARU.A); PACKAGE NPINT6 IS NEW PINT (X.ARU.V); PACKAGE NPAR_REC IS NEW PAR_REC (X.V_AR); PACKAGE NPREC01 IS NEW PREC0 (X.V_AR (1)); PACKAGE NPR_REC IS NEW PR_REC (X.V_R); PACKAGE NPREC02 IS NEW PREC0 (X.V_R.E); PACKAGE NPINT7 IS NEW PINT (X.V_R.E.A); PACKAGE NP_BUFF IS NEW P_BUFF (Z); USE NP_BUFF; PACKAGE NP_CHAR3 IS NEW P_CHAR (RX.VAL (1)); PROCEDURE PROC (X : IN OUT BUFFER) IS PACKAGE NP_CHAR4 IS NEW P_CHAR (X.VAL (1)); BEGIN NULL; END; BEGIN NULL; END; -- A) DECLARE -- B) PROCEDURE PROC (Y : IN OUT DIS2) IS PACKAGE NP_STRING IS NEW P_STRING (Y.S); PACKAGE NP_CHAR IS NEW P_CHAR (Y.S (1)); PACKAGE NP_A_STRING IS NEW P_A_STRING (Y.AS); PACKAGE NP_CHAR2 IS NEW P_CHAR (Y.AS (1)); PACKAGE NPINT3 IS NEW PINT (Y.R.A); PACKAGE NPINT4 IS NEW PINT (Y.R.V); PACKAGE NPREC3 IS NEW PREC3 (Y.R); PACKAGE NPA_REC IS NEW PA_REC (Y.AR); PACKAGE NPINT5 IS NEW PINT (Y.AR.A); PACKAGE NPINT6 IS NEW PINT (Y.AR.V); BEGIN NULL; END; BEGIN NULL; END; -- B) DECLARE -- C) PACKAGE NP_CHAR IS NEW P_CHAR (AD.S (1)); PACKAGE NP_A_STRING IS NEW P_A_STRING (AD.AS); PACKAGE NP_CHAR2 IS NEW P_CHAR (AD.AS (1)); PACKAGE NPINT3 IS NEW PINT (AD.R.A); PACKAGE NPINT4 IS NEW PINT (AD.R.V); PACKAGE NPREC3 IS NEW PREC3 (AD.R); PACKAGE NPA_REC IS NEW PA_REC (AD.AR); PACKAGE NPINT5 IS NEW PINT (AD.AR.A); PACKAGE NPINT6 IS NEW PINT (AD.AR.V); BEGIN NULL; END; -- C) RESULT; END AC3106A;
-- Copyright (c) 2019-2020 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Streams; package Torrent is pragma Pure; subtype SHA1 is Ada.Streams.Stream_Element_Array (1 .. 20); subtype SHA1_Image is Wide_Wide_String (1 .. 40); function Image (Value : SHA1) return SHA1_Image; subtype Piece_Offset is Ada.Streams.Stream_Element_Count; type Piece_Count is new Natural; subtype Piece_Index is Piece_Count range 1 .. Piece_Count'Last; type Boolean_Array is array (Piece_Index range <>) of Boolean with Pack; Max_Interval_Size : constant := 16 * 1024; Seed_Time : constant Duration := 10.0; end Torrent;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.I2C is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR1_DNF_Field is HAL.UInt4; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is completed. -- The latency of the second write access can be up to 2 x PCLK1 + 6 x -- I2CCLK. type CR1_Register is record -- Peripheral enable Note: When PE=0, the I2C SCL and SDA lines are -- released. Internal state machines and status bits are put back to -- their reset value. When cleared, PE must be kept low for at least 3 -- APB clock cycles. PE : Boolean := False; -- TX Interrupt enable TXIE : Boolean := False; -- RX Interrupt enable RXIE : Boolean := False; -- Address match Interrupt enable (slave only) ADDRIE : Boolean := False; -- Not acknowledge received Interrupt enable NACKIE : Boolean := False; -- STOP detection Interrupt enable STOPIE : Boolean := False; -- Transfer Complete interrupt enable Note: Any of these events will -- generate an interrupt: Transfer Complete (TC) Transfer Complete -- Reload (TCR) TCIE : Boolean := False; -- Error interrupts enable Note: Any of these errors generate an -- interrupt: Arbitration Loss (ARLO) Bus Error detection (BERR) -- Overrun/Underrun (OVR) Timeout detection (TIMEOUT) PEC error -- detection (PECERR) Alert pin event detection (ALERT) ERRIE : Boolean := False; -- Digital noise filter These bits are used to configure the digital -- noise filter on SDA and SCL input. The digital filter will filter -- spikes with a length of up to DNF[3:0] * tI2CCLK ... Note: If the -- analog filter is also enabled, the digital filter is added to the -- analog filter. This filter can only be programmed when the I2C is -- disabled (PE = 0). DNF : CR1_DNF_Field := 16#0#; -- Analog noise filter OFF Note: This bit can only be programmed when -- the I2C is disabled (PE = 0). ANFOFF : Boolean := False; -- unspecified Reserved_13_13 : HAL.Bit := 16#0#; -- DMA transmission requests enable TXDMAEN : Boolean := False; -- DMA reception requests enable RXDMAEN : Boolean := False; -- Slave byte control This bit is used to enable hardware byte control -- in slave mode. SBC : Boolean := False; -- Clock stretching disable This bit is used to disable clock stretching -- in slave mode. It must be kept cleared in master mode. Note: This bit -- can only be programmed when the I2C is disabled (PE = 0). NOSTRETCH : Boolean := False; -- Wakeup from Stop mode enable Note: If the Wakeup from Stop mode -- feature is not supported, this bit is reserved and forced by hardware -- to 0. Please refer to Section25.3: I2C implementation. Note: WUPEN -- can be set only when DNF = 0000 WUPEN : Boolean := False; -- General call enable GCEN : Boolean := False; -- SMBus Host address enable Note: If the SMBus feature is not -- supported, this bit is reserved and forced by hardware to 0. Please -- refer to Section25.3: I2C implementation. SMBHEN : Boolean := False; -- SMBus Device Default address enable Note: If the SMBus feature is not -- supported, this bit is reserved and forced by hardware to 0. Please -- refer to Section25.3: I2C implementation. SMBDEN : Boolean := False; -- SMBus alert enable Device mode (SMBHEN=0): Host mode (SMBHEN=1): -- Note: When ALERTEN=0, the SMBA pin can be used as a standard GPIO. If -- the SMBus feature is not supported, this bit is reserved and forced -- by hardware to 0. Please refer to Section25.3: I2C implementation. ALERTEN : Boolean := False; -- PEC enable Note: If the SMBus feature is not supported, this bit is -- reserved and forced by hardware to 0. Please refer to Section25.3: -- I2C implementation. PECEN : Boolean := False; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR1_Register use record PE at 0 range 0 .. 0; TXIE at 0 range 1 .. 1; RXIE at 0 range 2 .. 2; ADDRIE at 0 range 3 .. 3; NACKIE at 0 range 4 .. 4; STOPIE at 0 range 5 .. 5; TCIE at 0 range 6 .. 6; ERRIE at 0 range 7 .. 7; DNF at 0 range 8 .. 11; ANFOFF at 0 range 12 .. 12; Reserved_13_13 at 0 range 13 .. 13; TXDMAEN at 0 range 14 .. 14; RXDMAEN at 0 range 15 .. 15; SBC at 0 range 16 .. 16; NOSTRETCH at 0 range 17 .. 17; WUPEN at 0 range 18 .. 18; GCEN at 0 range 19 .. 19; SMBHEN at 0 range 20 .. 20; SMBDEN at 0 range 21 .. 21; ALERTEN at 0 range 22 .. 22; PECEN at 0 range 23 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype CR2_SADD_Field is HAL.UInt10; subtype CR2_NBYTES_Field is HAL.UInt8; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is completed. -- The latency of the second write access can be up to 2 x PCLK1 + 6 x -- I2CCLK. type CR2_Register is record -- Slave address bit 7:1 (master mode) In 7-bit addressing mode (ADD10 = -- 0): These bits should be written with the 7-bit slave address to be -- sent In 10-bit addressing mode (ADD10 = 1): These bits should be -- written with bits 10:1 of the slave address to be sent. Note: -- Changing these bits when the START bit is set is not allowed. SADD : CR2_SADD_Field := 16#0#; -- Transfer direction (master mode) Note: Changing this bit when the -- START bit is set is not allowed. RD_WRN : Boolean := False; -- 10-bit addressing mode (master mode) Note: Changing this bit when the -- START bit is set is not allowed. ADD10 : Boolean := False; -- 10-bit address header only read direction (master receiver mode) -- Note: Changing this bit when the START bit is set is not allowed. HEAD10R : Boolean := False; -- Start generation This bit is set by software, and cleared by hardware -- after the Start followed by the address sequence is sent, by an -- arbitration loss, by a timeout error detection, or when PE = 0. It -- can also be cleared by software by writing 1 to the ADDRCF bit in the -- I2C_ICR register. If the I2C is already in master mode with AUTOEND = -- 0, setting this bit generates a Repeated Start condition when -- RELOAD=0, after the end of the NBYTES transfer. Otherwise setting -- this bit will generate a START condition once the bus is free. Note: -- Writing 0 to this bit has no effect. The START bit can be set even if -- the bus is BUSY or I2C is in slave mode. This bit has no effect when -- RELOAD is set. START : Boolean := False; -- Stop generation (master mode) The bit is set by software, cleared by -- hardware when a Stop condition is detected, or when PE = 0. In Master -- Mode: Note: Writing 0 to this bit has no effect. STOP : Boolean := False; -- NACK generation (slave mode) The bit is set by software, cleared by -- hardware when the NACK is sent, or when a STOP condition or an -- Address matched is received, or when PE=0. Note: Writing 0 to this -- bit has no effect. This bit is used in slave mode only: in master -- receiver mode, NACK is automatically generated after last byte -- preceding STOP or RESTART condition, whatever the NACK bit value. -- When an overrun occurs in slave receiver NOSTRETCH mode, a NACK is -- automatically generated whatever the NACK bit value. When hardware -- PEC checking is enabled (PECBYTE=1), the PEC acknowledge value does -- not depend on the NACK value. NACK : Boolean := False; -- Number of bytes The number of bytes to be transmitted/received is -- programmed there. This field is dont care in slave mode with SBC=0. -- Note: Changing these bits when the START bit is set is not allowed. NBYTES : CR2_NBYTES_Field := 16#0#; -- NBYTES reload mode This bit is set and cleared by software. RELOAD : Boolean := False; -- Automatic end mode (master mode) This bit is set and cleared by -- software. Note: This bit has no effect in slave mode or when the -- RELOAD bit is set. AUTOEND : Boolean := False; -- Packet error checking byte This bit is set by software, and cleared -- by hardware when the PEC is transferred, or when a STOP condition or -- an Address matched is received, also when PE=0. Note: Writing 0 to -- this bit has no effect. This bit has no effect when RELOAD is set. -- This bit has no effect is slave mode when SBC=0. If the SMBus feature -- is not supported, this bit is reserved and forced by hardware to 0. -- Please refer to Section25.3: I2C implementation. PECBYTE : Boolean := False; -- unspecified Reserved_27_31 : HAL.UInt5 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR2_Register use record SADD at 0 range 0 .. 9; RD_WRN at 0 range 10 .. 10; ADD10 at 0 range 11 .. 11; HEAD10R at 0 range 12 .. 12; START at 0 range 13 .. 13; STOP at 0 range 14 .. 14; NACK at 0 range 15 .. 15; NBYTES at 0 range 16 .. 23; RELOAD at 0 range 24 .. 24; AUTOEND at 0 range 25 .. 25; PECBYTE at 0 range 26 .. 26; Reserved_27_31 at 0 range 27 .. 31; end record; subtype OAR1_OA1_Field is HAL.UInt10; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is completed. -- The latency of the second write access can be up to 2 x PCLK1 + 6 x -- I2CCLK. type OAR1_Register is record -- Interface address 7-bit addressing mode: dont care 10-bit addressing -- mode: bits 9:8 of address Note: These bits can be written only when -- OA1EN=0. OA1[7:1]: Interface address Bits 7:1 of address Note: These -- bits can be written only when OA1EN=0. OA1[0]: Interface address -- 7-bit addressing mode: dont care 10-bit addressing mode: bit 0 of -- address Note: This bit can be written only when OA1EN=0. OA1 : OAR1_OA1_Field := 16#0#; -- Own Address 1 10-bit mode Note: This bit can be written only when -- OA1EN=0. OA1MODE : Boolean := False; -- unspecified Reserved_11_14 : HAL.UInt4 := 16#0#; -- Own Address 1 enable OA1EN : Boolean := False; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OAR1_Register use record OA1 at 0 range 0 .. 9; OA1MODE at 0 range 10 .. 10; Reserved_11_14 at 0 range 11 .. 14; OA1EN at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype OAR2_OA2_Field is HAL.UInt7; subtype OAR2_OA2MSK_Field is HAL.UInt3; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is completed. -- The latency of the second write access can be up to 2 x PCLK1 + 6 x -- I2CCLK. type OAR2_Register is record -- unspecified Reserved_0_0 : HAL.Bit := 16#0#; -- Interface address bits 7:1 of address Note: These bits can be written -- only when OA2EN=0. OA2 : OAR2_OA2_Field := 16#0#; -- Own Address 2 masks Note: These bits can be written only when -- OA2EN=0. As soon as OA2MSK is not equal to 0, the reserved I2C -- addresses (0b0000xxx and 0b1111xxx) are not acknowledged even if the -- comparison matches. OA2MSK : OAR2_OA2MSK_Field := 16#0#; -- unspecified Reserved_11_14 : HAL.UInt4 := 16#0#; -- Own Address 2 enable OA2EN : Boolean := False; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OAR2_Register use record Reserved_0_0 at 0 range 0 .. 0; OA2 at 0 range 1 .. 7; OA2MSK at 0 range 8 .. 10; Reserved_11_14 at 0 range 11 .. 14; OA2EN at 0 range 15 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype TIMINGR_SCLL_Field is HAL.UInt8; subtype TIMINGR_SCLH_Field is HAL.UInt8; subtype TIMINGR_SDADEL_Field is HAL.UInt4; subtype TIMINGR_SCLDEL_Field is HAL.UInt4; subtype TIMINGR_PRESC_Field is HAL.UInt4; -- Access: No wait states type TIMINGR_Register is record -- SCL low period (master mode) This field is used to generate the SCL -- low period in master mode. tSCLL = (SCLL+1) x tPRESC Note: SCLL is -- also used to generate tBUF and tSU:STA timings. SCLL : TIMINGR_SCLL_Field := 16#0#; -- SCL high period (master mode) This field is used to generate the SCL -- high period in master mode. tSCLH = (SCLH+1) x tPRESC Note: SCLH is -- also used to generate tSU:STO and tHD:STA timing. SCLH : TIMINGR_SCLH_Field := 16#0#; -- Data hold time This field is used to generate the delay tSDADEL -- between SCL falling edge and SDA edge. In master mode and in slave -- mode with NOSTRETCH = 0, the SCL line is stretched low during -- tSDADEL. tSDADEL= SDADEL x tPRESC Note: SDADEL is used to generate -- tHD:DAT timing. SDADEL : TIMINGR_SDADEL_Field := 16#0#; -- Data setup time This field is used to generate a delay tSCLDEL -- between SDA edge and SCL rising edge. In master mode and in slave -- mode with NOSTRETCH = 0, the SCL line is stretched low during -- tSCLDEL. tSCLDEL = (SCLDEL+1) x tPRESC Note: tSCLDEL is used to -- generate tSU:DAT timing. SCLDEL : TIMINGR_SCLDEL_Field := 16#0#; -- unspecified Reserved_24_27 : HAL.UInt4 := 16#0#; -- Timing prescaler This field is used to prescale I2CCLK in order to -- generate the clock period tPRESC used for data setup and hold -- counters (refer to I2C timings on page9) and for SCL high and low -- level counters (refer to I2C master initialization on page24). tPRESC -- = (PRESC+1) x tI2CCLK PRESC : TIMINGR_PRESC_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TIMINGR_Register use record SCLL at 0 range 0 .. 7; SCLH at 0 range 8 .. 15; SDADEL at 0 range 16 .. 19; SCLDEL at 0 range 20 .. 23; Reserved_24_27 at 0 range 24 .. 27; PRESC at 0 range 28 .. 31; end record; subtype TIMEOUTR_TIMEOUTA_Field is HAL.UInt12; subtype TIMEOUTR_TIMEOUTB_Field is HAL.UInt12; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is completed. -- The latency of the second write access can be up to 2 x PCLK1 + 6 x -- I2CCLK. type TIMEOUTR_Register is record -- Bus Timeout A This field is used to configure: The SCL low timeout -- condition tTIMEOUT when TIDLE=0 tTIMEOUT= (TIMEOUTA+1) x 2048 x -- tI2CCLK The bus idle condition (both SCL and SDA high) when TIDLE=1 -- tIDLE= (TIMEOUTA+1) x 4 x tI2CCLK Note: These bits can be written -- only when TIMOUTEN=0. TIMEOUTA : TIMEOUTR_TIMEOUTA_Field := 16#0#; -- Idle clock timeout detection Note: This bit can be written only when -- TIMOUTEN=0. TIDLE : Boolean := False; -- unspecified Reserved_13_14 : HAL.UInt2 := 16#0#; -- Clock timeout enable TIMOUTEN : Boolean := False; -- Bus timeout B This field is used to configure the cumulative clock -- extension timeout: In master mode, the master cumulative clock low -- extend time (tLOW:MEXT) is detected In slave mode, the slave -- cumulative clock low extend time (tLOW:SEXT) is detected tLOW:EXT= -- (TIMEOUTB+1) x 2048 x tI2CCLK Note: These bits can be written only -- when TEXTEN=0. TIMEOUTB : TIMEOUTR_TIMEOUTB_Field := 16#0#; -- unspecified Reserved_28_30 : HAL.UInt3 := 16#0#; -- Extended clock timeout enable TEXTEN : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TIMEOUTR_Register use record TIMEOUTA at 0 range 0 .. 11; TIDLE at 0 range 12 .. 12; Reserved_13_14 at 0 range 13 .. 14; TIMOUTEN at 0 range 15 .. 15; TIMEOUTB at 0 range 16 .. 27; Reserved_28_30 at 0 range 28 .. 30; TEXTEN at 0 range 31 .. 31; end record; subtype ISR_ADDCODE_Field is HAL.UInt7; -- Access: No wait states type ISR_Register is record -- Transmit data register empty (transmitters) This bit is set by -- hardware when the I2C_TXDR register is empty. It is cleared when the -- next data to be sent is written in the I2C_TXDR register. This bit -- can be written to 1 by software in order to flush the transmit data -- register I2C_TXDR. Note: This bit is set by hardware when PE=0. TXE : Boolean := True; -- Transmit interrupt status (transmitters) This bit is set by hardware -- when the I2C_TXDR register is empty and the data to be transmitted -- must be written in the I2C_TXDR register. It is cleared when the next -- data to be sent is written in the I2C_TXDR register. This bit can be -- written to 1 by software when NOSTRETCH=1 only, in order to generate -- a TXIS event (interrupt if TXIE=1 or DMA request if TXDMAEN=1). Note: -- This bit is cleared by hardware when PE=0. TXIS : Boolean := False; -- Read-only. Receive data register not empty (receivers) This bit is -- set by hardware when the received data is copied into the I2C_RXDR -- register, and is ready to be read. It is cleared when I2C_RXDR is -- read. Note: This bit is cleared by hardware when PE=0. RXNE : Boolean := False; -- Read-only. Address matched (slave mode) This bit is set by hardware -- as soon as the received slave address matched with one of the enabled -- slave addresses. It is cleared by software by setting ADDRCF bit. -- Note: This bit is cleared by hardware when PE=0. ADDR : Boolean := False; -- Read-only. Not Acknowledge received flag This flag is set by hardware -- when a NACK is received after a byte transmission. It is cleared by -- software by setting the NACKCF bit. Note: This bit is cleared by -- hardware when PE=0. NACKF : Boolean := False; -- Read-only. Stop detection flag This flag is set by hardware when a -- Stop condition is detected on the bus and the peripheral is involved -- in this transfer: either as a master, provided that the STOP -- condition is generated by the peripheral. or as a slave, provided -- that the peripheral has been addressed previously during this -- transfer. It is cleared by software by setting the STOPCF bit. Note: -- This bit is cleared by hardware when PE=0. STOPF : Boolean := False; -- Read-only. Transfer Complete (master mode) This flag is set by -- hardware when RELOAD=0, AUTOEND=0 and NBYTES data have been -- transferred. It is cleared by software when START bit or STOP bit is -- set. Note: This bit is cleared by hardware when PE=0. TC : Boolean := False; -- Read-only. Transfer Complete Reload This flag is set by hardware when -- RELOAD=1 and NBYTES data have been transferred. It is cleared by -- software when NBYTES is written to a non-zero value. Note: This bit -- is cleared by hardware when PE=0. This flag is only for master mode, -- or for slave mode when the SBC bit is set. TCR : Boolean := False; -- Read-only. Bus error This flag is set by hardware when a misplaced -- Start or Stop condition is detected whereas the peripheral is -- involved in the transfer. The flag is not set during the address -- phase in slave mode. It is cleared by software by setting BERRCF bit. -- Note: This bit is cleared by hardware when PE=0. BERR : Boolean := False; -- Read-only. Arbitration lost This flag is set by hardware in case of -- arbitration loss. It is cleared by software by setting the ARLOCF -- bit. Note: This bit is cleared by hardware when PE=0. ARLO : Boolean := False; -- Read-only. Overrun/Underrun (slave mode) This flag is set by hardware -- in slave mode with NOSTRETCH=1, when an overrun/underrun error -- occurs. It is cleared by software by setting the OVRCF bit. Note: -- This bit is cleared by hardware when PE=0. OVR : Boolean := False; -- Read-only. PEC Error in reception This flag is set by hardware when -- the received PEC does not match with the PEC register content. A NACK -- is automatically sent after the wrong PEC reception. It is cleared by -- software by setting the PECCF bit. Note: This bit is cleared by -- hardware when PE=0. If the SMBus feature is not supported, this bit -- is reserved and forced by hardware to 0. Please refer to Section25.3: -- I2C implementation. PECERR : Boolean := False; -- Read-only. Timeout or tLOW detection flag This flag is set by -- hardware when a timeout or extended clock timeout occurred. It is -- cleared by software by setting the TIMEOUTCF bit. Note: This bit is -- cleared by hardware when PE=0. If the SMBus feature is not supported, -- this bit is reserved and forced by hardware to 0. Please refer to -- Section25.3: I2C implementation. TIMEOUT : Boolean := False; -- Read-only. SMBus alert This flag is set by hardware when SMBHEN=1 -- (SMBus host configuration), ALERTEN=1 and a SMBALERT event (falling -- edge) is detected on SMBA pin. It is cleared by software by setting -- the ALERTCF bit. Note: This bit is cleared by hardware when PE=0. If -- the SMBus feature is not supported, this bit is reserved and forced -- by hardware to 0. Please refer to Section25.3: I2C implementation. ALERT : Boolean := False; -- unspecified Reserved_14_14 : HAL.Bit := 16#0#; -- Read-only. Bus busy This flag indicates that a communication is in -- progress on the bus. It is set by hardware when a START condition is -- detected. It is cleared by hardware when a Stop condition is -- detected, or when PE=0. BUSY : Boolean := False; -- Read-only. Transfer direction (Slave mode) This flag is updated when -- an address match event occurs (ADDR=1). DIR : Boolean := False; -- Read-only. Address match code (Slave mode) These bits are updated -- with the received address when an address match event occurs (ADDR = -- 1). In the case of a 10-bit address, ADDCODE provides the 10-bit -- header followed by the 2 MSBs of the address. ADDCODE : ISR_ADDCODE_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record TXE at 0 range 0 .. 0; TXIS at 0 range 1 .. 1; RXNE at 0 range 2 .. 2; ADDR at 0 range 3 .. 3; NACKF at 0 range 4 .. 4; STOPF at 0 range 5 .. 5; TC at 0 range 6 .. 6; TCR at 0 range 7 .. 7; BERR at 0 range 8 .. 8; ARLO at 0 range 9 .. 9; OVR at 0 range 10 .. 10; PECERR at 0 range 11 .. 11; TIMEOUT at 0 range 12 .. 12; ALERT at 0 range 13 .. 13; Reserved_14_14 at 0 range 14 .. 14; BUSY at 0 range 15 .. 15; DIR at 0 range 16 .. 16; ADDCODE at 0 range 17 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- Access: No wait states type ICR_Register is record -- unspecified Reserved_0_2 : HAL.UInt3 := 16#0#; -- Write-only. Address matched flag clear Writing 1 to this bit clears -- the ADDR flag in the I2C_ISR register. Writing 1 to this bit also -- clears the START bit in the I2C_CR2 register. ADDRCF : Boolean := False; -- Write-only. Not Acknowledge flag clear Writing 1 to this bit clears -- the ACKF flag in I2C_ISR register. NACKCF : Boolean := False; -- Write-only. Stop detection flag clear Writing 1 to this bit clears -- the STOPF flag in the I2C_ISR register. STOPCF : Boolean := False; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; -- Write-only. Bus error flag clear Writing 1 to this bit clears the -- BERRF flag in the I2C_ISR register. BERRCF : Boolean := False; -- Write-only. Arbitration Lost flag clear Writing 1 to this bit clears -- the ARLO flag in the I2C_ISR register. ARLOCF : Boolean := False; -- Write-only. Overrun/Underrun flag clear Writing 1 to this bit clears -- the OVR flag in the I2C_ISR register. OVRCF : Boolean := False; -- Write-only. PEC Error flag clear Writing 1 to this bit clears the -- PECERR flag in the I2C_ISR register. Note: If the SMBus feature is -- not supported, this bit is reserved and forced by hardware to 0. -- Please refer to Section25.3: I2C implementation. PECCF : Boolean := False; -- Write-only. Timeout detection flag clear Writing 1 to this bit clears -- the TIMEOUT flag in the I2C_ISR register. Note: If the SMBus feature -- is not supported, this bit is reserved and forced by hardware to 0. -- Please refer to Section25.3: I2C implementation. TIMOUTCF : Boolean := False; -- Write-only. Alert flag clear Writing 1 to this bit clears the ALERT -- flag in the I2C_ISR register. Note: If the SMBus feature is not -- supported, this bit is reserved and forced by hardware to 0. Please -- refer to Section25.3: I2C implementation. ALERTCF : Boolean := False; -- unspecified Reserved_14_31 : HAL.UInt18 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ICR_Register use record Reserved_0_2 at 0 range 0 .. 2; ADDRCF at 0 range 3 .. 3; NACKCF at 0 range 4 .. 4; STOPCF at 0 range 5 .. 5; Reserved_6_7 at 0 range 6 .. 7; BERRCF at 0 range 8 .. 8; ARLOCF at 0 range 9 .. 9; OVRCF at 0 range 10 .. 10; PECCF at 0 range 11 .. 11; TIMOUTCF at 0 range 12 .. 12; ALERTCF at 0 range 13 .. 13; Reserved_14_31 at 0 range 14 .. 31; end record; subtype PECR_PEC_Field is HAL.UInt8; -- Access: No wait states type PECR_Register is record -- Read-only. Packet error checking register This field contains the -- internal PEC when PECEN=1. The PEC is cleared by hardware when PE=0. PEC : PECR_PEC_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for PECR_Register use record PEC at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype RXDR_RXDATA_Field is HAL.UInt8; -- Access: No wait states type RXDR_Register is record -- Read-only. 8-bit receive data Data byte received from the I2C bus. RXDATA : RXDR_RXDATA_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for RXDR_Register use record RXDATA at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype TXDR_TXDATA_Field is HAL.UInt8; -- Access: No wait states type TXDR_Register is record -- 8-bit transmit data Data byte to be transmitted to the I2C bus. Note: -- These bits can be written only when TXE=1. TXDATA : TXDR_TXDATA_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for TXDR_Register use record TXDATA at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- I2C type I2C_Peripheral is record -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is -- completed. The latency of the second write access can be up to 2 x -- PCLK1 + 6 x I2CCLK. CR1 : aliased CR1_Register; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is -- completed. The latency of the second write access can be up to 2 x -- PCLK1 + 6 x I2CCLK. CR2 : aliased CR2_Register; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is -- completed. The latency of the second write access can be up to 2 x -- PCLK1 + 6 x I2CCLK. OAR1 : aliased OAR1_Register; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is -- completed. The latency of the second write access can be up to 2 x -- PCLK1 + 6 x I2CCLK. OAR2 : aliased OAR2_Register; -- Access: No wait states TIMINGR : aliased TIMINGR_Register; -- Access: No wait states, except if a write access occurs while a write -- access to this register is ongoing. In this case, wait states are -- inserted in the second write access until the previous one is -- completed. The latency of the second write access can be up to 2 x -- PCLK1 + 6 x I2CCLK. TIMEOUTR : aliased TIMEOUTR_Register; -- Access: No wait states ISR : aliased ISR_Register; -- Access: No wait states ICR : aliased ICR_Register; -- Access: No wait states PECR : aliased PECR_Register; -- Access: No wait states RXDR : aliased RXDR_Register; -- Access: No wait states TXDR : aliased TXDR_Register; end record with Volatile; for I2C_Peripheral use record CR1 at 16#0# range 0 .. 31; CR2 at 16#4# range 0 .. 31; OAR1 at 16#8# range 0 .. 31; OAR2 at 16#C# range 0 .. 31; TIMINGR at 16#10# range 0 .. 31; TIMEOUTR at 16#14# range 0 .. 31; ISR at 16#18# range 0 .. 31; ICR at 16#1C# range 0 .. 31; PECR at 16#20# range 0 .. 31; RXDR at 16#24# range 0 .. 31; TXDR at 16#28# range 0 .. 31; end record; -- I2C I2C1_Periph : aliased I2C_Peripheral with Import, Address => I2C1_Base; -- I2C I2C2_Periph : aliased I2C_Peripheral with Import, Address => I2C2_Base; -- I2C I2C3_Periph : aliased I2C_Peripheral with Import, Address => I2C3_Base; -- I2C I2C4_Periph : aliased I2C_Peripheral with Import, Address => I2C4_Base; end STM32_SVD.I2C;
pragma License (Unrestricted); -- implementation unit required by compiler with System.Storage_Pools.Standard_Pools; package System.Pool_Global is pragma Preelaborate; subtype Unbounded_No_Reclaim_Pool is Storage_Pools.Standard_Pools.Standard_Pool; pragma Suppress (All_Checks); -- for renaming -- required for default of 'Storage_Pool by compiler (s-pooglo.ads) Global_Pool_Object : Unbounded_No_Reclaim_Pool renames Storage_Pools.Standard_Pools.Standard_Storage_Pool.all; end System.Pool_Global;
package Pure with Pure is --@description A pure spec test package end Pure;
package Except is Test_Exception : exception; procedure Do_Something; procedure Do_Sth_2; end Except;
----------------------------------------------------------------------- -- gen-artifacts-distribs-libs -- Unix shared library extraction and distribution -- Copyright (C) 2012, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with Util.Beans.Objects; with Util.Files; with EL.Variables.Default; with EL.Contexts.Default; with Gen.Utils; package body Gen.Artifacts.Distribs.Libs is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Distribs.Exec"); -- ------------------------------ -- Create a distribution rule to extract the shared libraries used by an executable -- and copy a selected subset in the target directory. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is procedure Collect_Libraries (Rule : in out Libs_Rule'Class; Node : in DOM.Core.Node); -- ------------------------------ -- Collect the library patterns for the distribution rule. -- ------------------------------ procedure Collect_Libraries (Rule : in out Libs_Rule'Class; Node : in DOM.Core.Node) is Name : constant String := Gen.Utils.Get_Data_Content (Node); begin Rule.Libraries.Append (Name); end Collect_Libraries; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Libs_Rule'Class, Process => Collect_Libraries); Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Gen.Utils.Get_Data_Content (Node, "command"); Result : constant Libs_Rule_Access := new Libs_Rule; begin if Command = "" then Result.Command := EL.Expressions.Create_Expression ("ldd #{src}", Ctx); else Result.Command := EL.Expressions.Create_Expression (Command, Ctx); end if; Iterate (Result.all, Node, "library"); return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Libs_Rule) return String is pragma Unreferenced (Rule); begin return "libs"; end Get_Install_Name; -- ------------------------------ -- Get the target path associate with the given source file for the distribution rule. -- ------------------------------ overriding function Get_Target_Path (Rule : in Libs_Rule; Base : in String; File : in File_Record) return String is pragma Unreferenced (File); Dir : constant String := Ada.Strings.Unbounded.To_String (Rule.Dir); begin return Util.Files.Compose (Base, Dir); end Get_Target_Path; -- ------------------------------ -- Check if the library whose absolute path is defined in <b>Source</b> must be -- copied in the target directory and copy that library if needed. -- ------------------------------ procedure Copy (Rule : in Libs_Rule; Dir : in String; Source : in String) is Name : constant String := Ada.Directories.Simple_Name (Source); Path : constant String := Ada.Directories.Compose (Dir, Name); Iter : Util.Strings.Vectors.Cursor := Rule.Libraries.First; Found : Boolean := not Util.Strings.Vectors.Has_Element (Iter); begin Log.Debug ("Checking library {0}", Path); while not Found and then Util.Strings.Vectors.Has_Element (Iter) loop declare Lib : constant String := Util.Strings.Vectors.Element (Iter); Matcher : constant GNAT.Regpat.Pattern_Matcher := Make_Regexp (Lib); begin Found := GNAT.Regpat.Match (Matcher, Name); end; Util.Strings.Vectors.Next (Iter); end loop; if Found then Log.Info ("Copy {0} To {1}", Source, Path); -- Make sure the target directory exists. Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Source, Target_Name => Path, Form => "preserve=all_attributes, mode=overwrite"); end if; end Copy; overriding procedure Install (Rule : in Libs_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Source : constant String := Get_Source_Path (Files); begin if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info ("install {0} to {1}", Source, Path); end if; Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Rule.Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Reader : Util.Streams.Texts.Reader_Stream; begin -- Execute 'ldd' with the executable and read the output to extract the library path. -- Lines have the form: -- libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0xb758a000) -- and we extract the absolute path to make the copy. Pipe.Open (Command); Reader.Initialize (Pipe'Unchecked_Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Last : Natural; begin Reader.Read_Line (Line, True); Pos := Ada.Strings.Unbounded.Index (Line, "=> "); if Pos > 0 then Pos := Pos + 3; Last := Ada.Strings.Unbounded.Index (Line, " ", Pos); if Last = 0 then Last := Ada.Strings.Unbounded.Length (Line); else Last := Last - 1; end if; if Pos < Last then Rule.Copy (Path, Ada.Strings.Unbounded.Slice (Line, Pos, Last)); end if; end if; end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Context.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Install; end Gen.Artifacts.Distribs.Libs;
-- openapi_ipify -- OpenAPI client for ipify, a simple public IP address API -- -- OpenAPI spec version: 0.9.0 -- Contact: blah@cliffano.com -- -- NOTE: This package is auto generated by the swagger code generator 3.2.1-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. with Swagger.Streams; with Swagger.Servers.Operation; package body .Skeletons is package body Skeleton is package API_Get_Ip is new Swagger.Servers.Operation (Handler => Get_Ip, Method => Swagger.Servers.GET, URI => "/"); -- Get your public IP address procedure Get_Ip (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is Impl : Implementation_Type; Format : Swagger.Nullable_UString; Callback : Swagger.Nullable_UString; Result : Swagger.Object; begin Swagger.Servers.Get_Query_Parameter (Req, "format", Format); Swagger.Servers.Get_Query_Parameter (Req, "callback", Callback); Impl.Get_Ip (Format, Callback, Result, Context); if Context.Get_Status = 200 then Stream.Start_Document; .Models.Serialize (Stream, "", Result); Stream.End_Document; end if; end Get_Ip; procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is begin Swagger.Servers.Register (Server, API_Get_Ip.Definition); end Register; end Skeleton; package body Shared_Instance is -- Get your public IP address procedure Get_Ip (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is Format : Swagger.Nullable_UString; Callback : Swagger.Nullable_UString; Result : Swagger.Object; begin Swagger.Servers.Get_Query_Parameter (Req, "format", Format); Swagger.Servers.Get_Query_Parameter (Req, "callback", Callback); Server.Get_Ip (Format, Callback, Result, Context); if Context.Get_Status = 200 then Stream.Start_Document; .Models.Serialize (Stream, "", Result); Stream.End_Document; end if; end Get_Ip; package API_Get_Ip is new Swagger.Servers.Operation (Handler => Get_Ip, Method => Swagger.Servers.GET, URI => "/"); procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is begin Swagger.Servers.Register (Server, API_Get_Ip.Definition); end Register; protected body Server is -- Get your public IP address procedure Get_Ip (Format : in Swagger.Nullable_UString; Callback : in Swagger.Nullable_UString; Result : out Swagger.Object; Context : in out Swagger.Servers.Context_Type) is begin Impl.Get_Ip (Format, Callback, Result, Context); end Get_Ip; end Server; end Shared_Instance; end .Skeletons;
package GDB_Remote.Agent is subtype Address is Unsigned_64; type Instance (Buffer_Size : Buffer_Lenght_Type := 256) is abstract tagged limited private; subtype Class is Instance'Class; type Ptr is access all Class; procedure Send_To_Host (This : in out Instance; C : Character) is abstract; type Event_Kind is (None, Got_Packet, Got_Ack, Got_Nack, Got_An_Interrupt); type Event (Kind : Event_Kind := None) is record case Kind is when Got_Packet => P : Packet; when None | Got_Ack | Got_Nack | Got_An_Interrupt => null; end case; end record; function Received (This : in out Instance; C : Character) return Event; function Next_Field (This : in out Instance) return String; function Next_Data (This : in out Instance; Success : out Boolean) return Unsigned_8; -- Return the next octet of the binary data in a packet procedure Ack (This : in out Instance); procedure Nack (This : in out Instance); procedure Send_Packet (This : in out Instance; Data : String); procedure Start_Packet (This : in out Instance); procedure Push_Data (This : in out Instance; Data : String); generic type T is mod <>; procedure Push_Mod (This : in out Instance; Data : T); procedure End_Packet (This : in out Instance); private type State_Kind is (Waiting_For_Ack, Waiting_For_Start, Receiving_Packet, Checksum); type Instance (Buffer_Size : Buffer_Lenght_Type := 256) is abstract tagged limited record Buffer : String (1 .. Buffer_Size); Char_Count : Natural := 0; Field_Cursor : Natural := 0; Checksum : Unsigned_8; Checksum_Str : String (1 .. 2); Checksum_Str_Count : Natural := 0; State : State_Kind := Waiting_For_Ack; Data_Fmt : Data_Format := Binary; Tx_Checksum : Unsigned_8; end record; function Checksum_OK (This : Instance) return Boolean; end GDB_Remote.Agent;
-- { dg-do run } -- { dg-options "-O3 -flto" { target lto } } with Lto21_Pkg1; with Lto21_Pkg2; use Lto21_Pkg2; procedure Lto21 is begin Proc; end;
-- Copyright (c) 2015-2019 Marcel Schneider -- for details see License.txt with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Position; use Position; with Tokens; use Tokens; package TokenValue is type Object is record SourcePosition : Position.Object; TokenId : Token; Literal : Unbounded_String; Message : Unbounded_String; end record; end TokenValue;
with color_h; use color_h; package Libtcod.Color.Conversions is function To_TCOD_ColorRGB(color : RGB_Color) return TCOD_ColorRGB with Inline; function To_RGB_Color(color : TCOD_ColorRGB) return RGB_Color with Inline; private function To_TCOD_ColorRGB(color : RGB_Color) return TCOD_ColorRGB is (TCOD_ColorRGB(color)); function To_RGB_Color(color : TCOD_ColorRGB) return RGB_Color is (RGB_Color(color)); end Libtcod.Color.Conversions;
Int_Bits : constant Integer := Integer'size; Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element
with System; with STM32_SVD.SAU; use STM32_SVD.SAU; package STM32.SAU is type SAU_Regions is range 0 .. 7; procedure Add_Region (Region_Num : SAU_Regions; Addr : UInt32; Size : UInt32; NSC : Boolean); procedure Enable_SAU; procedure All_NS; end STM32.SAU;
with AUnit.Reporter.Text; with AUnit.Run; with Test_Suite; procedure Tests is procedure Run is new AUnit.Run.Test_Runner (Test_Suite.Create_Test_Suite); Reporter : AUnit.Reporter.Text.Text_Reporter; begin Run (Reporter); end Tests;
with Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; package Scape is function Decode (Str : String) return Unbounded_Wide_Wide_String; function Encode (Str : Unbounded_Wide_Wide_String) return Unbounded_String; end Scape;
with float_Math.Geometry.d3.Modeller.Forge; package body openGL.IO.lat_long_Radius is function to_Model (math_Model : access Geometry_3d.a_Model) return IO.Model is site_Count : constant long_Index_t := long_Index_t (math_Model.site_Count); coord_Count : constant long_Index_t := 0; --get_coord_Count; -- TODO: Add texturing. normal_Count : constant long_Index_t := 0; --collada_Normals'Length / 3; -- TODO: Add lighting. the_Sites : constant Sites_view := new many_Sites (1 .. site_Count); the_Normals : constant Normals_view := new many_Normals (1 .. normal_Count); the_Coords : Coords_view; the_Faces : IO.Faces_view := new IO.Faces (1 .. 50_000); face_Count : long_Index_t := 0; begin if coord_Count > 0 then the_Coords := new many_Coordinates_2D (1 .. coord_Count); end if; for i in 1 .. Integer (site_Count) loop the_Sites (long_Index_t (i)) := math_Model.Sites (i); end loop; -- Primitives -- declare the_Vertices : Vertices (1 .. long_Index_t (math_Model.tri_Count * 3)); Start : long_Index_t; the_Face : IO.Face; begin for i in math_Model.Triangles'Range loop Start := long_Index_t ((i - 1) * 3 + 1); the_Vertices (Start ) := (site_Id => long_Index_t (math_Model.Triangles (i) (1)), others => 0); the_Vertices (Start + 1) := (site_Id => long_Index_t (math_Model.Triangles (i) (2)), others => 0); the_Vertices (Start + 2) := (site_Id => long_Index_t (math_Model.Triangles (i) (3)), others => 0); the_Face := (Triangle, the_Vertices (Start .. Start + 2)); face_Count := face_Count + 1; the_Faces (face_Count) := the_Face; end loop; end; declare used_Faces : constant IO.Faces_view := new IO.Faces' (the_Faces (1 .. face_Count)); begin free (the_Faces); return (Sites => the_Sites, Coords => the_Coords, Normals => the_Normals, Weights => null, Faces => used_Faces); end; end to_Model; function to_Model (model_File : in String) return IO.Model is use float_Math.Geometry.d3.Modeller.Forge; the_math_Model : aliased Geometry_3d.a_Model := mesh_Model_from (Model => polar_Model_from (model_File)); begin return to_Model (the_math_Model'Access); end to_Model; end openGL.IO.lat_long_Radius;
with Ada.Text_IO; use Ada.Text_IO; with Interfaces.C; use Interfaces.C; --with termbox_h; use termbox_h; --with x86_64_linux_gnu_bits_stdint_uintn_h; use x86_64_linux_gnu_bits_stdint_uintn_h; with Termbox; procedure Demo is Init : Termbox.Return_Value; Evt : Termbox.Return_Value; Ev: access Termbox.Event := new Termbox.Event; W,H : Integer; TestCell : access Termbox.Cell := new Termbox.Cell'('B', Termbox.BLACK, Termbox.RED); subtype Color_Array_Idx_Type is Integer range 1..8; type Color_Array_Type is array(Color_Array_Idx_Type) of Termbox.Termbox_Constant; Colors : Color_Array_Type := ( Termbox.BLACK, Termbox.RED, Termbox.GREEN, Termbox.YELLOW, Termbox.BLUE, Termbox.MAGENTA, Termbox.CYAN, Termbox.WHITE ); FgIdx : Color_Array_Idx_Type := 1; begin Init := Termbox.Init; if Init /= 0 then Put_Line("Termbox Init failed with error code: " & Integer'Image(Init)); return; end if; W:= Termbox.Width; H:= Termbox.Height; --Termbox.Set_Clear_Attributes(Termbox.WHITE, Termbox.WHITE); Termbox.Clear; Termbox.Set_Cursor(0,10); Termbox.Put_Cell(0, 9, TestCell); loop Evt := Termbox.Peek_Event(Ev, 100); exit when Ev.key = Termbox.KEY_ESC; Termbox.Change_Cell(0, 0, 'H', Colors(FgIdx), 0); Termbox.Change_Cell(1, 0, 'E', Colors(FgIdx), 0); Termbox.Change_Cell(2, 0, 'L', Colors(FgIdx), 0); Termbox.Change_Cell(3, 0, 'L', Colors(FgIdx), 0); Termbox.Change_Cell(4, 0, 'O', Colors(FgIdx), 0); Termbox.Change_Cell(6, 0, 'W', Colors(FgIdx), 0); Termbox.Change_Cell(7, 0, 'O', Colors(FgIdx), 0); Termbox.Change_Cell(8, 0, 'R', Colors(FgIdx), 0); Termbox.Change_Cell(9, 0, 'L', Colors(FgIdx), 0); Termbox.Change_Cell(10, 0, 'D', Colors(FgIdx), 0); if FgIdx >= 8 then FgIdx :=1; else FgIdx := FgIdx + 1; end if; Termbox.Present; end loop; Termbox.Shutdown; Put_Line("Width/Height:" & Integer'Image(W) & Integer'Image(H)); end Demo;
-- Copyright 2019-2021 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. procedure Vla is type Array_Type is array (Natural range <>) of Integer; type Record_Type (L1, L2 : Natural) is record I1 : Integer; A1 : Array_Type (1 .. L1); I2 : Integer; A2 : Array_Type (1 .. L2); I3 : Integer; end record; -- Some versions of GCC emit the members in the incorrect order. -- Since this isn't relevant to the bug at hand, disable -- reordering to get consistent results. pragma No_Component_Reordering (Record_Type); procedure Process (R : Record_Type) is begin null; end Process; R00 : Record_Type := (L1 => 0, L2 => 0, I1 => 1, A1 => (others => 10), I2 => 2, A2 => (others => 20), I3 => 3); R01 : Record_Type := (L1 => 0, L2 => 1, I1 => 1, A1 => (others => 10), I2 => 2, A2 => (others => 20), I3 => 3); R10 : Record_Type := (L1 => 1, L2 => 0, I1 => 1, A1 => (others => 10), I2 => 2, A2 => (others => 20), I3 => 3); R22 : Record_Type := (L1 => 2, L2 => 2, I1 => 1, A1 => (others => 10), I2 => 2, A2 => (others => 20), I3 => 3); begin Process (R00); -- Set breakpoint here Process (R01); Process (R10); Process (R22); end Vla;
package openGL.Renderer -- -- Provides a base class for all renderers. -- is type Item is abstract tagged limited private; type View is access all Item'Class; -- Attributes -- procedure Background_is (Self : in out Item; Now : in openGL.lucid_Color); procedure Background_is (Self : in out Item; Now : in openGL.Color; Opacity : in unit_Interval := 1.0); -- Operations -- procedure clear_Frame (Self : in Item); private type Item is abstract tagged limited record Background : openGL.lucid_Color; end record; end openGL.Renderer;
-- SPDX-FileCopyrightText: 2022 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Regions.Contexts.Environments.Package_Nodes is type Entity_Cursor is new Regions.Entity_Cursor with record List_Cursor : Selected_Entity_Name_Lists.Cursor; end record; type Entity_Iterator (Env : not null Regions.Contexts.Environments.Environment_Node_Access) is new Regions.Entity_Iterator_Interfaces.Forward_Iterator with record List : Selected_Entity_Name_Lists.List; end record; overriding function First (Self : Entity_Iterator) return Regions.Entity_Cursor_Class; overriding function Next (Self : Entity_Iterator; Cursor : Regions.Entity_Cursor_Class) return Regions.Entity_Cursor_Class; --------------- -- Empty_Map -- --------------- function Empty_Map (Self : access Package_Node) return Name_List_Maps.Map is begin return Name_List_Maps.Empty_Map (Self.Version'Access); end Empty_Map; ----------- -- First -- ----------- overriding function First (Self : Entity_Iterator) return Regions.Entity_Cursor_Class is First : constant Selected_Entity_Name_Lists.Cursor := Self.List.Iterate.First; begin if Selected_Entity_Name_Lists.Has_Element (First) then return Entity_Cursor' (Entity => Self.Env.Get_Entity (Self.List (First)), List_Cursor => First, Left => Self.List.Length - 1); else return Entity_Cursor'(null, 0, Selected_Entity_Name_Lists.No_Element); end if; end First; ----------------------- -- Immediate_Visible -- ----------------------- overriding function Immediate_Visible (Self : Package_Entity; Symbol : Symbols.Symbol) return Regions.Entity_Iterator_Interfaces.Forward_Iterator'Class is (raise Program_Error); -------------------------------- -- Immediate_Visible_Backward -- -------------------------------- overriding function Immediate_Visible_Backward (Self : Package_Entity; Symbol : Symbols.Symbol) return Regions.Entity_Iterator_Interfaces.Forward_Iterator'Class is Node : Package_Node renames Package_Node (Self.Env.Nodes.Element (Self.Name).all); begin if Node.Names.Contains (Symbol) then declare List : constant Selected_Entity_Name_Lists.List := Node.Names.Element (Symbol); begin return Entity_Iterator'(Self.Env, List); end; else return Entity_Iterator' (Self.Env, Selected_Entity_Name_Lists.Empty_List); end if; end Immediate_Visible_Backward; ---------- -- Next -- ---------- overriding function Next (Self : Entity_Iterator; Cursor : Regions.Entity_Cursor_Class) return Regions.Entity_Cursor_Class is begin if Cursor.Left = 0 then return Entity_Cursor'(null, 0, Selected_Entity_Name_Lists.No_Element); else declare Value : Entity_Cursor renames Entity_Cursor (Cursor); Next : constant Selected_Entity_Name_Lists.Cursor := Self.List.Iterate.Next (Value.List_Cursor); begin return Entity_Cursor' (Entity => Self.Env.Get_Entity (Self.List (Next)), List_Cursor => Next, Left => Cursor.Left - 1); end; end if; end Next; end Regions.Contexts.Environments.Package_Nodes;
with Shader_Manager; package body Palet is G_Draw_State : Draw_State; function Background_Colour (Palet_Data : Colour_Palet) return Color is begin return Palet_Data.Background_Colour; end Background_Colour; -- ------------------------------------------------------------------------ function Background_Red (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (R); end Background_Red; -- ------------------------------------------------------------------------ function Background_Green (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (G); end Background_Green; -- ------------------------------------------------------------------------ function Background_Blue (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (B); end Background_Blue; -- ------------------------------------------------------------------------ function Current_Sphere return Geosphere.Geosphere is begin return G_Draw_State.M_Sphere; end Current_Sphere; -- ------------------------------------------------------------------------ function Foreground_Colour (Palet_Data : Colour_Palet) return Color is begin return Palet_Data.Foreground_Colour; end Foreground_Colour; -- ------------------------------------------------------------------------ function Foreground_Alpha (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Foreground_Colour (A); end Foreground_Alpha; -- ------------------------------------------------------------------------ function Foreground_Blue (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (B); end Foreground_Blue; -- ------------------------------------------------------------------------ function Foreground_Green (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (G); end Foreground_Green; -- ------------------------------------------------------------------------ function Foreground_Red (Palet_Data : Colour_Palet) return Single is begin return Palet_Data.Background_Colour (R); end Foreground_Red; -- ------------------------------------------------------------------------ function Get_Draw_Mode return Draw_Mode is begin return G_Draw_State.M_Draw_Mode; end Get_Draw_Mode; -- ------------------------------------------------------------------------ function Get_Plane_Size return Float is begin return G_Draw_State.Plane_Size; end Get_Plane_Size; -- ------------------------------------------------------------------------ function Is_Null return Colour_Palet is Null_Colour : constant Color := (0.0, 0.0, 0.0, 0.0); begin return (False, Null_Colour, Null_Colour, Null_Colour); end Is_Null; -- ------------------------------------------------------------------------ function Line_Length return Float is begin return G_Draw_State.Line_Length; end Line_Length; -- ------------------------------------------------------------------------ function Magnitude return Boolean is begin return G_Draw_State.M_Draw_Mode.Magnitude; end Magnitude; -- ------------------------------------------------------------------------ function Orientation return Boolean is begin return G_Draw_State.M_Draw_Mode.Orientation; end Orientation; -- ------------------------------------------------------------------------ function Outline_Colour (Palet_Data : Colour_Palet) return Color is begin return Palet_Data.Outline_Colour; end Outline_Colour; -- ------------------------------------------------------------------------ function Point_Size return Float is begin return G_Draw_State.Point_Size; end Point_Size; -- ------------------------------------------------------------------------ procedure Set_Background_Alpa (Palet_Data : in out Colour_Palet; Alpa : Float) is begin Palet_Data.Background_Colour (A) := GL.Types.Single (Alpa); end Set_Background_Alpa; -- ------------------------------------------------------------------------ procedure Set_Background_Colour (Palet_Data : in out Colour_Palet; Back_Colour : Color) is begin Palet_Data.Background_Colour := Back_Colour; end Set_Background_Colour; -- ------------------------------------------------------------------------ procedure Set_Background_Colour (Palet_Data : Colour_Palet) is Colour : constant Color := Background_Colour (Palet_Data); A_State : constant Single := Single (G_Draw_State.Ambient); D_State : constant Single := Single (G_Draw_State.Diffuse); Ambient_Colour : constant Color := (A_State * Colour (R), A_State * Colour (G), A_State * Colour (B), A_State * Colour (A)); Diffuse_Colour : constant Color := (D_State * Colour (R), D_State * Colour (G), D_State * Colour (B), D_State * Colour (A)); begin Shader_Manager.Set_Ambient_Colour ((Ambient_Colour (R), Ambient_Colour (G), Ambient_Colour (B), Ambient_Colour (A))); Shader_Manager.Set_Diffuse_Colour ((Diffuse_Colour (R), Diffuse_Colour (G),Diffuse_Colour (B), Diffuse_Colour (A))); end Set_Background_Colour; -- ------------------------------------------------------------------------ procedure Set_Current_Sphere (aSphere : Geosphere.Geosphere) is begin G_Draw_State.M_Sphere := aSphere; end Set_Current_Sphere; -- ------------------------------------------------------------------------ procedure Set_Draw_Mode_Off (Mode : Draw_Mode_Type) is begin case Mode is when OD_Shade => G_Draw_State.M_Draw_Mode.Shade := False; when OD_Wireframe => G_Draw_State.M_Draw_Mode.Wireframe := False; when OD_Magnitude => G_Draw_State.M_Draw_Mode.Magnitude := False; when OD_Orientation => G_Draw_State.M_Draw_Mode.Orientation := False; end case; end Set_Draw_Mode_Off; -- ------------------------------------------------------------------------ procedure Set_Draw_Mode_On (Mode : Draw_Mode_Type) is begin case Mode is when OD_Shade => G_Draw_State.M_Draw_Mode.Shade := True; when OD_Wireframe => G_Draw_State.M_Draw_Mode.Wireframe := True; when OD_Magnitude => G_Draw_State.M_Draw_Mode.Magnitude := True; when OD_Orientation => G_Draw_State.M_Draw_Mode.Orientation := True; end case; end Set_Draw_Mode_On; -- ------------------------------------------------------------------------ procedure Set_Foreground_Alpa (Palet_Data : in out Colour_Palet; Alpa : Float) is begin Palet_Data.Foreground_Colour (A) := GL.Types.Single (Alpa); end Set_Foreground_Alpa; -- ------------------------------------------------------------------------ procedure Set_Foreground_Colour (Palet_Data : Colour_Palet) is Colour : constant Color := Foreground_Colour (Palet_Data); A_State : constant Single := Single (G_Draw_State.Ambient); D_State : constant Single := Single (G_Draw_State.Diffuse); Ambient_Colour : constant Color := (A_State * Colour (R), A_State * Colour (G), A_State * Colour (B), A_State * Colour (A)); Diffuse_Colour : constant Color := (D_State * Colour (R), D_State * Colour (G), D_State * Colour (B), D_State * Colour (A)); begin Shader_Manager.Set_Ambient_Colour ((Ambient_Colour (R),Ambient_Colour (G), Ambient_Colour (B), Ambient_Colour (A))); Shader_Manager.Set_Diffuse_Colour ((Diffuse_Colour (R), Diffuse_Colour (G), Diffuse_Colour (B), Diffuse_Colour (A))); end Set_Foreground_Colour; -- ------------------------------------------------------------------------ procedure Set_Foreground_Colour (Palet_Data : in out Colour_Palet; Fore_Colour : Color) is begin Palet_Data.Foreground_Colour := Fore_Colour; end Set_Foreground_Colour; -- ------------------------------------------------------------------------ procedure Set_Outline_Alpa (Palet_Data : in out Colour_Palet; Alpa : Float) is begin Palet_Data.Outline_Colour (A) := GL.Types.Single (Alpa); end Set_Outline_Alpa; -- ------------------------------------------------------------------------ procedure Set_Outline_Colour (Palet_Data : in out Colour_Palet; Outline_Colour : Color) is begin Palet_Data.Outline_Colour := Outline_Colour; end Set_Outline_Colour; -- ------------------------------------------------------------------------ procedure Set_Outline_Colour (Palet_Data : Colour_Palet) is Colour : constant Color := Outline_Colour (Palet_Data); A_State : constant Single := Single (G_Draw_State.Ambient); D_State : constant Single := Single (G_Draw_State.Diffuse); Ambient_Colour : constant Color := (A_State * Colour (R), A_State * Colour (G), A_State * Colour (B), A_State * Colour (A)); Diffuse_Colour : constant Color := (D_State * Colour (R), D_State * Colour (G), D_State * Colour (B), D_State * Colour (A)); begin Shader_Manager.Set_Ambient_Colour ((Ambient_Colour (R), Ambient_Colour (G), Ambient_Colour (B), Ambient_Colour (A))); Shader_Manager.Set_Diffuse_Colour ((Diffuse_Colour (R), Diffuse_Colour (G), Diffuse_Colour (B), Diffuse_Colour (A))); end Set_Outline_Colour; -- ------------------------------------------------------------------------ procedure Set_Point_Size (Point_Size : Float) is begin G_Draw_State.Point_Size := Point_Size; end Set_Point_Size; -- ------------------------------------------------------------------------ function Shade return Boolean is begin return G_Draw_State.M_Draw_Mode.Shade; end Shade; -- ------------------------------------------------------------------------ function Wireframe return Boolean is begin return G_Draw_State.M_Draw_Mode.Wireframe; end Wireframe; -- ------------------------------------------------------------------------ end Palet;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015, 2017, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Strings; with Util.Properties; with Util.Beans.Objects; with Util.Files; with Util.Log.Loggers; with Util.Serialize.IO.XML; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Policies; with AWA.Events.Configs.Reader_Config; with AWA.Services.Contexts; package body AWA.Applications.Configs is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs"); type Wallet_Manager is limited new Util.Properties.Implementation.Manager with record Wallet : Keystore.Properties.Manager; Props : ASF.Applications.Config; Length : Positive; Prefix : String (1 .. MAX_PREFIX_LENGTH); end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Wallet_Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Wallet_Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access; package Shared_Manager is new Util.Properties.Implementation.Shared_Implementation (Wallet_Manager); subtype Property_Map is Shared_Manager.Manager; type Property_Map_Access is access all Property_Map; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then declare Value : constant String := From.Wallet.Get (Prefixed_Name); begin return Util.Beans.Objects.To_Object (Value); end; else return From.Props.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object) is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then From.Wallet.Set_Value (Prefixed_Name, Value); else From.Props.Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Wallet_Manager; Name : in String) return Boolean is begin return Self.Props.Exists (Name) or else Self.Wallet.Exists (Self.Prefix (1 .. Self.Length) & Name); end Exists; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Wallet_Manager; Name : in String) is Prefixed_Name : constant String := Self.Prefix (1 .. Self.Length) & Name; begin if Self.Wallet.Exists (Prefixed_Name) then Self.Wallet.Remove (Prefixed_Name); else Self.Props.Remove (Name); end if; end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is procedure Wallet_Filter (Name : in String; Item : in Util.Beans.Objects.Object); procedure Property_Filter (Name : in String; Item : in Util.Beans.Objects.Object); procedure Wallet_Filter (Name : in String; Item : in Util.Beans.Objects.Object) is begin if Util.Strings.Starts_With (Name, Self.Prefix (1 .. Self.Length)) then Log.Debug ("Use wallet property {0} as {1}", Name, Name (Name'First + Self.Length .. Name'Last)); Process (Name (Name'First + Self.Length .. Name'Last), Item); end if; end Wallet_Filter; procedure Property_Filter (Name : in String; Item : in Util.Beans.Objects.Object) is Prefixed_Name : constant String := Self.Prefix (1 .. Self.Length) & Name; begin if not Self.Wallet.Exists (Prefixed_Name) then Process (Name, Item); end if; end Property_Filter; begin Self.Props.Iterate (Property_Filter'Access); Self.Wallet.Iterate (Wallet_Filter'Access); end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Self.Length; Result.Wallet := Self.Wallet; Result.Props := Self.Props; Result.Prefix := Self.Prefix; return Result.all'Access; end Create_Copy; -- ------------------------------ -- Merge the configuration content and the keystore to a final configuration object. -- The keystore can be used to store sensitive information such as database connection, -- secret keys while the rest of the configuration remains in clear property files. -- The keystore must be unlocked to have access to its content. -- The prefix parameter is used to prefix names from the keystore so that the same -- keystore could be used by several applications. -- ------------------------------ procedure Merge (Into : in out ASF.Applications.Config; Config : in out ASF.Applications.Config; Wallet : in out Keystore.Properties.Manager; Prefix : in String) is function Allocate return Util.Properties.Implementation.Shared_Manager_Access; function Allocate return Util.Properties.Implementation.Shared_Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Prefix'Length; Result.Wallet := Wallet; Result.Props := Config; Result.Prefix (1 .. Result.Length) := Prefix; return Result.all'Access; end Allocate; procedure Setup is new Util.Properties.Implementation.Initialize (Allocate); begin Setup (Into); end Merge; -- ------------------------------ -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Mapper, App_Access, Context.all'Access, Override_Context); package Event_Config is new AWA.Events.Configs.Reader_Config (Mapper => Mapper, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Event_Config); begin Event_Config.Initialize; end Reader_Config; -- ------------------------------ -- Read the application configuration file and configure the application -- ------------------------------ procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean) is Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Ctx : AWA.Services.Contexts.Service_Context; Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context, Override_Context); pragma Warnings (Off, Config); begin Sec.Prepare_Config (Mapper); -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.Mappers.Dump (Mapper, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File, Mapper); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; -- ------------------------------ -- Get the configuration path for the application name. -- The configuration path is search from: -- o the current directory, -- o the 'config' directory, -- o the Dynamo installation directory in share/dynamo -- ------------------------------ function Get_Config_Path (Name : in String) return String is use Ada.Strings.Unbounded; use Ada.Directories; Command : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Command); Dir : constant String := Containing_Directory (Path); Paths : Ada.Strings.Unbounded.Unbounded_String; begin Append (Paths, ".;"); Append (Paths, Util.Files.Compose (Dir, "config")); Append (Paths, ";"); Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name)); return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths)); end Get_Config_Path; end AWA.Applications.Configs;