text
stringlengths
437
491k
meta
dict
-- -- Convert any image or animation file to BMP file(s). -- -- Middle-size test/demo for the GID (Generic Image Decoder) package. -- -- Supports: -- - Transparency (blends transparent or partially opaque areas with a -- background image, gid.gif, or a fixed, predefined colour) -- - Display orientation (JPEG EXIF informations from digital cameras) -- -- For a smaller and simpler example, look for mini.adb . -- with GID; with Ada.Calendar; with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Command_Line; use Ada.Command_Line; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Ada.Unchecked_Deallocation; with Interfaces; procedure To_BMP is default_bkg_name: constant String:= "gid.gif"; procedure Blurb is begin Put_Line(Standard_Error, "To_BMP * Converts any image file to a BMP file"); Put_Line(Standard_Error, "Simple test for the GID (Generic Image Decoder) package"); Put_Line(Standard_Error, "Package version " & GID.version & " dated " & GID.reference); Put_Line(Standard_Error, "URL: " & GID.web); New_Line(Standard_Error); Put_Line(Standard_Error, "Syntax:"); Put_Line(Standard_Error, "to_bmp [-] [-<background_image_name>] <image_1> [<image_2>...]"); New_Line(Standard_Error); Put_Line(Standard_Error, "Options:"); Put_Line(Standard_Error, " '-': don't output image (testing only)"); Put_Line(Standard_Error, " '-<background_image_name>':"); Put_Line(Standard_Error, " use specifed background to mix with transparent images"); Put_Line(Standard_Error, " (otherwise, trying with '"& default_bkg_name &"' or single color)"); New_Line(Standard_Error); Put_Line(Standard_Error, "Output: "".dib"" is added the full input name(s)"); Put_Line(Standard_Error, " Reason of "".dib"": unknown synonym of "".bmp"";"); Put_Line(Standard_Error, " just do ""del *.dib"" for cleanup"); New_Line(Standard_Error); end Blurb; -- Image used as background for displaying images having transparency background_image_name: Unbounded_String:= Null_Unbounded_String; use Interfaces; type Byte_Array is array(Integer range <>) of Unsigned_8; type p_Byte_Array is access Byte_Array; procedure Dispose is new Ada.Unchecked_Deallocation(Byte_Array, p_Byte_Array); forgive_errors: constant Boolean:= False; error: Boolean; img_buf, bkg_buf: p_Byte_Array:= null; bkg: GID.Image_descriptor; generic correct_orientation: GID.Orientation; -- Load image into a 24-bit truecolor BGR raw bitmap (for a BMP output) procedure Load_raw_image( image : in out GID.Image_descriptor; buffer: in out p_Byte_Array; next_frame: out Ada.Calendar.Day_Duration ); -- procedure Load_raw_image( image : in out GID.Image_descriptor; buffer: in out p_Byte_Array; next_frame: out Ada.Calendar.Day_Duration ) is subtype Primary_color_range is Unsigned_8; subtype U16 is Unsigned_16; image_width: constant Positive:= GID.Pixel_width(image); image_height: constant Positive:= GID.Pixel_height(image); padded_line_size_x: constant Positive:= 4 * Integer(Float'Ceiling(Float(image_width) * 3.0 / 4.0)); padded_line_size_y: constant Positive:= 4 * Integer(Float'Ceiling(Float(image_height) * 3.0 / 4.0)); -- (in bytes) idx: Integer; mem_x, mem_y: Natural; bkg_padded_line_size: Positive; bkg_width, bkg_height: Natural; -- procedure Set_X_Y (x, y: Natural) is pragma Inline(Set_X_Y); use GID; rev_x: constant Natural:= image_width - (x+1); rev_y: constant Natural:= image_height - (y+1); begin case correct_orientation is when Unchanged => idx:= 3 * x + padded_line_size_x * y; when Rotation_90 => idx:= 3 * rev_y + padded_line_size_y * x; when Rotation_180 => idx:= 3 * rev_x + padded_line_size_x * rev_y; when Rotation_270 => idx:= 3 * y + padded_line_size_y * rev_x; end case; mem_x:= x; mem_y:= y; end Set_X_Y; -- -- No background version of Put_Pixel -- procedure Put_Pixel_without_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_without_bkg); pragma Warnings(off, alpha); -- alpha is just ignored use GID; begin buffer(idx..idx+2):= (blue, green, red); -- GID requires us to look to next pixel for next time: case correct_orientation is when Unchanged => idx:= idx + 3; when Rotation_90 => idx:= idx + padded_line_size_y; when Rotation_180 => idx:= idx - 3; when Rotation_270 => idx:= idx - padded_line_size_y; end case; end Put_Pixel_without_bkg; -- -- Unicolor background version of Put_Pixel -- procedure Put_Pixel_with_unicolor_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_with_unicolor_bkg); u_red : constant:= 200; u_green: constant:= 133; u_blue : constant:= 32; begin if alpha = 255 then buffer(idx..idx+2):= (blue, green, red); else -- blend with bckground color buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * u_blue )/255); buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * u_green)/255); buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * u_red )/255); end if; idx:= idx + 3; -- ^ GID requires us to look to next pixel on the right for next time. end Put_Pixel_with_unicolor_bkg; -- -- Background image version of Put_Pixel -- procedure Put_Pixel_with_image_bkg ( red, green, blue : Primary_color_range; alpha : Primary_color_range ) is pragma Inline(Put_Pixel_with_image_bkg); b_red, b_green, b_blue : Primary_color_range; bkg_idx: Natural; begin if alpha = 255 then buffer(idx..idx+2):= (blue, green, red); else -- blend with background image bkg_idx:= 3 * (mem_x mod bkg_width) + bkg_padded_line_size * (mem_y mod bkg_height); b_blue := bkg_buf(bkg_idx); b_green:= bkg_buf(bkg_idx+1); b_red := bkg_buf(bkg_idx+2); buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * U16(b_blue) )/255); buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * U16(b_green))/255); buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * U16(b_red) )/255); end if; idx:= idx + 3; -- ^ GID requires us to look to next pixel on the right for next time. mem_x:= mem_x + 1; end Put_Pixel_with_image_bkg; stars: Natural:= 0; procedure Feedback(percents: Natural) is so_far: constant Natural:= percents / 5; begin for i in stars+1..so_far loop Put( Standard_Error, '*'); end loop; stars:= so_far; end Feedback; -- Here, the exciting thing: the instanciation of -- GID.Load_image_contents. In our case, we load the image -- into a 24-bit bitmap (because we provide a Put_Pixel -- that does that with the pixels), but we could do plenty -- of other things instead, like display the image live on a GUI. -- More exciting: for tuning performance, we have 3 different -- instances of GID.Load_image_contents (each of them with the full -- decoders for all formats, own specialized generic instances, inlines, -- etc.) depending on the transparency features. procedure BMP24_Load_without_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_without_bkg, Feedback, GID.fast ); procedure BMP24_Load_with_unicolor_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_with_unicolor_bkg, Feedback, GID.fast ); procedure BMP24_Load_with_image_bkg is new GID.Load_image_contents( Primary_color_range, Set_X_Y, Put_Pixel_with_image_bkg, Feedback, GID.fast ); begin error:= False; Dispose(buffer); case correct_orientation is when GID.Unchanged | GID.Rotation_180 => buffer:= new Byte_Array(0..padded_line_size_x * GID.Pixel_height(image) - 1); when GID.Rotation_90 | GID.Rotation_270 => buffer:= new Byte_Array(0..padded_line_size_y * GID.Pixel_width(image) - 1); end case; if GID.Expect_transparency(image) then if background_image_name = Null_Unbounded_String then BMP24_Load_with_unicolor_bkg(image, next_frame); else bkg_width:= GID.Pixel_width(bkg); bkg_height:= GID.Pixel_height(bkg); bkg_padded_line_size:= 4 * Integer(Float'Ceiling(Float(bkg_width) * 3.0 / 4.0)); BMP24_Load_with_image_bkg(image, next_frame); end if; else BMP24_Load_without_bkg(image, next_frame); end if; -- -- For testing: white rectangle with a red half-frame. -- buffer.all:= (others => 255); -- for x in 0..GID.Pixel_width(image)-1 loop -- Put_Pixel_with_unicolor_bkg(x,0,255,0,0,255); -- end loop; -- for y in 0..GID.Pixel_height(image)-1 loop -- Put_Pixel_with_unicolor_bkg(0,y,255,0,0,255); -- end loop; exception when others => if forgive_errors then error:= True; next_frame:= 0.0; else raise; end if; end Load_raw_image; procedure Load_raw_image_0 is new Load_raw_image(GID.Unchanged); procedure Load_raw_image_90 is new Load_raw_image(GID.Rotation_90); procedure Load_raw_image_180 is new Load_raw_image(GID.Rotation_180); procedure Load_raw_image_270 is new Load_raw_image(GID.Rotation_270); procedure Dump_BMP_24(name: String; i: GID.Image_descriptor) is f: Ada.Streams.Stream_IO.File_Type; type BITMAPFILEHEADER is record bfType : Unsigned_16; bfSize : Unsigned_32; bfReserved1: Unsigned_16:= 0; bfReserved2: Unsigned_16:= 0; bfOffBits : Unsigned_32; end record; -- ^ No packing needed BITMAPFILEHEADER_Bytes: constant:= 14; type BITMAPINFOHEADER is record biSize : Unsigned_32; biWidth : Unsigned_32; biHeight : Unsigned_32; biPlanes : Unsigned_16:= 1; biBitCount : Unsigned_16; biCompression : Unsigned_32:= 0; biSizeImage : Unsigned_32; biXPelsPerMeter: Unsigned_32:= 0; biYPelsPerMeter: Unsigned_32:= 0; biClrUsed : Unsigned_32:= 0; biClrImportant : Unsigned_32:= 0; end record; -- ^ No packing needed BITMAPINFOHEADER_Bytes: constant:= 40; FileInfo : BITMAPINFOHEADER; FileHeader: BITMAPFILEHEADER; -- generic type Number is mod <>; procedure Write_Intel_x86_number(n: in Number); procedure Write_Intel_x86_number(n: in Number) is m: Number:= n; bytes: constant Integer:= Number'Size/8; begin for i in 1..bytes loop Unsigned_8'Write(Stream(f), Unsigned_8(m and 255)); m:= m / 256; end loop; end Write_Intel_x86_number; procedure Write_Intel is new Write_Intel_x86_number( Unsigned_16 ); procedure Write_Intel is new Write_Intel_x86_number( Unsigned_32 ); begin FileHeader.bfType := 16#4D42#; -- 'BM' FileHeader.bfOffBits := BITMAPINFOHEADER_Bytes + BITMAPFILEHEADER_Bytes; FileInfo.biSize := BITMAPINFOHEADER_Bytes; case GID.Display_orientation(i) is when GID.Unchanged | GID.Rotation_180 => FileInfo.biWidth := Unsigned_32(GID.Pixel_width(i)); FileInfo.biHeight := Unsigned_32(GID.Pixel_height(i)); when GID.Rotation_90 | GID.Rotation_270 => FileInfo.biWidth := Unsigned_32(GID.Pixel_height(i)); FileInfo.biHeight := Unsigned_32(GID.Pixel_width(i)); end case; FileInfo.biBitCount := 24; FileInfo.biSizeImage := Unsigned_32(img_buf.all'Length); FileHeader.bfSize := FileHeader.bfOffBits + FileInfo.biSizeImage; Create(f, Out_File, name & ".dib"); -- BMP Header, endian-safe: Write_Intel(FileHeader.bfType); Write_Intel(FileHeader.bfSize); Write_Intel(FileHeader.bfReserved1); Write_Intel(FileHeader.bfReserved2); Write_Intel(FileHeader.bfOffBits); -- Write_Intel(FileInfo.biSize); Write_Intel(FileInfo.biWidth); Write_Intel(FileInfo.biHeight); Write_Intel(FileInfo.biPlanes); Write_Intel(FileInfo.biBitCount); Write_Intel(FileInfo.biCompression); Write_Intel(FileInfo.biSizeImage); Write_Intel(FileInfo.biXPelsPerMeter); Write_Intel(FileInfo.biYPelsPerMeter); Write_Intel(FileInfo.biClrUsed); Write_Intel(FileInfo.biClrImportant); -- BMP raw BGR image: declare -- Workaround for the severe xxx'Read xxx'Write performance -- problems in the GNAT and ObjectAda compilers (as in 2009) -- This is possible if and only if Byte = Stream_Element and -- arrays types are both packed the same way. -- subtype Size_test_a is Byte_Array(1..19); subtype Size_test_b is Ada.Streams.Stream_Element_Array(1..19); workaround_possible: constant Boolean:= Size_test_a'Size = Size_test_b'Size and then Size_test_a'Alignment = Size_test_b'Alignment; -- begin if workaround_possible then declare use Ada.Streams; SE_Buffer : Stream_Element_Array (0..Stream_Element_Offset(img_buf'Length-1)); for SE_Buffer'Address use img_buf.all'Address; pragma Import (Ada, SE_Buffer); begin Ada.Streams.Write(Stream(f).all, SE_Buffer(0..Stream_Element_Offset(img_buf'Length-1))); end; else Byte_Array'Write(Stream(f), img_buf.all); -- the workaround is about this line... end if; end; Close(f); end Dump_BMP_24; procedure Process(name: String; as_background, test_only: Boolean) is f: Ada.Streams.Stream_IO.File_Type; i: GID.Image_descriptor; up_name: constant String:= To_Upper(name); -- next_frame, current_frame: Ada.Calendar.Day_Duration:= 0.0; begin -- -- Load the image in its original format -- Open(f, In_File, name); Put_Line(Standard_Error, "Processing " & name & "..."); -- GID.Load_image_header( i, Stream(f).all, try_tga => name'Length >= 4 and then up_name(up_name'Last-3..up_name'Last) = ".TGA" ); Put_Line(Standard_Error, " Image format: " & GID.Image_format_type'Image(GID.Format(i)) ); Put_Line(Standard_Error, " Image detailed format: " & GID.Detailed_format(i) ); Put_Line(Standard_Error, " Image sub-format ID (if any): " & Integer'Image(GID.Subformat(i)) ); Put_Line(Standard_Error, " Dimensions in pixels: " & Integer'Image(GID.Pixel_width(i)) & " x" & Integer'Image(GID.Pixel_height(i)) ); Put_Line(Standard_Error, " Display orientation: " & GID.Orientation'Image(GID.Display_orientation(i)) ); Put(Standard_Error, " Color depth: " & Integer'Image(GID.Bits_per_pixel(i)) & " bits" ); if GID.Bits_per_pixel(i) <= 24 then Put_Line(Standard_Error, ',' & Integer'Image(2**GID.Bits_per_pixel(i)) & " colors" ); else New_Line(Standard_Error); end if; Put_Line(Standard_Error, " Palette: " & Boolean'Image(GID.Has_palette(i)) ); Put_Line(Standard_Error, " Greyscale: " & Boolean'Image(GID.Greyscale(i)) ); Put_Line(Standard_Error, " RLE encoding (if any): " & Boolean'Image(GID.RLE_encoded(i)) ); Put_Line(Standard_Error, " Interlaced (GIF: each frame's choice): " & Boolean'Image(GID.Interlaced(i)) ); Put_Line(Standard_Error, " Expect transparency: " & Boolean'Image(GID.Expect_transparency(i)) ); Put_Line(Standard_Error, "1........10........20"); Put_Line(Standard_Error, " | | "); -- if as_background then case GID.Display_orientation(i) is when GID.Unchanged => Load_raw_image_0(i, bkg_buf, next_frame); when GID.Rotation_90 => Load_raw_image_90(i, bkg_buf, next_frame); when GID.Rotation_180 => Load_raw_image_180(i, bkg_buf, next_frame); when GID.Rotation_270 => Load_raw_image_270(i, bkg_buf, next_frame); end case; bkg:= i; New_Line(Standard_Error); Close(f); return; end if; loop case GID.Display_orientation(i) is when GID.Unchanged => Load_raw_image_0(i, img_buf, next_frame); when GID.Rotation_90 => Load_raw_image_90(i, img_buf, next_frame); when GID.Rotation_180 => Load_raw_image_180(i, img_buf, next_frame); when GID.Rotation_270 => Load_raw_image_270(i, img_buf, next_frame); end case; if not test_only then Dump_BMP_24(name & Duration'Image(current_frame), i); end if; New_Line(Standard_Error); if error then Put_Line(Standard_Error, "Error!"); end if; exit when next_frame = 0.0; current_frame:= next_frame; end loop; Close(f); exception when GID.unknown_image_format => Put_Line(Standard_Error, " Image format is unknown!"); if Is_Open(f) then Close(f); end if; end Process; test_only: Boolean:= False; begin if Argument_Count=0 then Blurb; return; end if; Put_Line(Standard_Error, "To_BMP, using GID version " & GID.version & " dated " & GID.reference); begin Process(default_bkg_name, True, False); -- if success: background_image_name:= To_Unbounded_String(default_bkg_name); exception when Ada.Text_IO.Name_Error => null; -- nothing bad, just couldn't find default background end; for i in 1..Argument_Count loop declare arg: constant String:= Argument(i); begin if arg /= "" and then arg(arg'First)='-' then declare opt: constant String:= arg(arg'First+1..arg'Last); begin if opt = "" then test_only:= True; else Put_Line(Standard_Error, "Background image is " & opt); Process(opt, True, False); -- define this only after processing, otherwise -- a transparent background will try to use -- an undefined background background_image_name:= To_Unbounded_String(opt); end if; end; else Process(arg, False, test_only); end if; end; end loop; end To_BMP;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Handling; use Ada.Characters.Handling; with Agen; use Agen; with Argument_Stack; package body Actions.Init is procedure Help is begin Put_Line(" (new|init)"); Put_Line(" project <name> - create a project from a basic template"); Put_Line(" gpr <name> - create a GPR from a basic template"); end Help; function Try_Act return Boolean is begin if Argument_Stack.Is_Empty then goto Fail; end if; declare Action : constant String := Argument_Stack.Pop; begin if To_Upper(Action) /= "NEW" and To_Upper(Action) /= "INIT" then goto Fail; end if; end; if Argument_Stack.Is_Empty then Put_Line(Standard_Error, "Error: No target was specified"); goto Fail; end if; declare Target : constant String := Argument_Stack.Pop; begin if To_Upper(Target) = "PROJECT" then if Argument_Stack.Is_Empty then Put_Line(Standard_Error, "Error: No name was specifed"); goto Fail; end if; Agen.Create_Project(Argument_Stack.Pop); return True; elsif To_Upper(Target) = "GPR" then if Argument_Stack.Is_Empty then Put_Line(Standard_Error, "Error: No name was specified"); goto Fail; end if; Agen.Create_GPR(Argument_Stack.Pop); return True; else Put_Line(Standard_Error, "Error: """ & Target & """ was not an understood target"); goto Fail; end if; end; <<Fail>> Argument_Stack.Reset; return False; end Try_Act; end Actions.Init;
{ "source": "starcoderdata", "programming_language": "ada" }
-- if not, write to the Free Software Foundation, Inc., 59 Temple -- -- Place - Suite 330, Boston, MA 02111-1307, USA. -- ----------------------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Ada.Real_Time; use Ada.Real_Time; with Display; use Display; with Display.Basic; use Display.Basic; with Libm_Single; use Libm_Single; procedure Main is -- QUESTION 1 - Part 1 -- define type Bodies_Enum_T as an enumeration of Sun, Earth, Moon, Satellite -- define type Parameters_Enum_T as an enumeration of parameter X, Y, -- Radius, Speed, Distance, Angle -- define type Bodies_Array_T as an array of float indexed by bodies and -- parameters -- define type Colors_Array_T as an array of color (RGBA_T) indexed by bodies -- declare variable Bodies which is an instance of Bodies_Array_T -- declare variable Colors which is an instance of Colors_Array_T -- declare a variable Next of type Time to store the Next step time Next : Time; -- declare a constant Period of 40 milliseconds of type Time_Span defining -- the loop period Period : constant Time_Span := Milliseconds (40); -- reference to the application window Window : Window_ID; -- reference to the graphical canvas associated with the application window Canvas : Canvas_ID; begin -- Create a window 240x320 Window := Create_Window (Width => 240, Height => 320, Name => "Solar System"); -- Retrieve the graphical canvas from the window Canvas := Get_Canvas (Window); -- QUESTION 1 - Part 2 -- initialize Bodies variable with parameters for each body using an aggregate -- Sun Distance = 0.0, Angle = 0.0, Speed = 0.0, Radius = 20.0; -- Earth Distance = 50.0, Angle = 0.0, Speed = 0.02, Radius = 5.0; -- Moon Distance = 15.0, Angle = 0.0, Speed = 0.04, Radius = 2.0; -- Satellite Distance = 8.0, Angle = 0.0, Speed = 0.1, Radius = 1.0; -- QUESTION 1 - Part 3 -- initialize Colors variable with Sun is Yellow, Earth is Blue, Moon is -- White, Satellite is Red -- initialize the Next step time begin the current time (Clock) + the period Next := Clock + Period; while not Is_Killed loop -- QUESTION 2 - part 1 -- create a loop to update each body position and angles -- the position of an object around (0,0) at distance d with an angle a -- is (d*cos(a), d*sin(a)) -- update angle parameter of each body adding speed to the previous angle -- QUESTION 2 - part 2 -- create a loop to draw every objects -- use the Draw_Sphere procedure to do it -- update the screen using procedure Swap_Buffers Swap_Buffers (Window); -- wait until Next delay until Next; -- update the Next time adding the period for the next step Next := Next + Period; end loop; end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
with numbers; use numbers; with strings; use strings; package address is type pos_addr_t is tagged private; null_pos_addr : constant pos_addr_t; error_address_odd : exception; function create (value : word) return pos_addr_t; procedure set (pos_addr : in out pos_addr_t; value : word); function get (pos_addr : pos_addr_t) return word; function valid_value_for_pos_addr (value : word) return boolean; procedure inc (pos_addr : in out pos_addr_t); function inc (pos_addr : pos_addr_t) return pos_addr_t; procedure dec (pos_addr : in out pos_addr_t); function "<" (a, b : pos_addr_t) return boolean; function "<=" (a, b : pos_addr_t) return boolean; function ">" (a, b : pos_addr_t) return boolean; function ">=" (a, b : pos_addr_t) return boolean; function "-" (a, b : pos_addr_t) return pos_addr_t; function "+" (a, b : pos_addr_t) return pos_addr_t; function "*" (a, b : pos_addr_t) return pos_addr_t; function "/" (a, b : pos_addr_t) return pos_addr_t; function "+" (a: pos_addr_t; b : natural) return pos_addr_t; function "+" (a: pos_addr_t; b : word) return pos_addr_t; private use type word; type pos_addr_t is tagged record addr : word; end record; null_pos_addr : constant pos_addr_t := (addr => 16#ffff#); end address;
{ "source": "starcoderdata", "programming_language": "ada" }
-- { dg-do run } with GNAT.Time_Stamp; use GNAT.Time_Stamp; procedure test_time_stamp is S : constant String := Current_Time; function NN (S : String) return Boolean is begin for J in S'Range loop if S (J) not in '0' .. '9' then return True; end if; end loop; return False; end NN; begin if S'Length /= 22 or else S (5) /= '-' or else S (8) /= '-' or else S (11) /= ' ' or else S (14) /= ':' or else S (17) /= ':' or else S (20) /= '.' or else NN (S (1 .. 4)) or else NN (S (6 .. 7)) or else NN (S (9 .. 10)) or else NN (S (12 .. 13)) or else NN (S (15 .. 16)) or else NN (S (18 .. 19)) or else NN (S (21 .. 22)) then raise Program_Error; end if; end;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- -- @summary -- Version Trees -- -- @description -- The package provides Version and Version_Tree types. -- Nested generic package Versioned_Values provides Container type. -- package Incr.Version_Trees is type Version is private; -- Version identificator type Version_Tree is tagged limited private; -- Version_Tree keeps history of a document as sequence (actually tree) of -- Versions as they are created. One version (changing) is different, this -- is a version where current chages are performed. -- Only read-write version of the document is its changing version. type Version_Tree_Access is access all Version_Tree'Class; not overriding function Changing (Self : Version_Tree) return Version; -- Version where current chages are performed not overriding function Is_Changing (Self : Version_Tree; Value : Version) return Boolean; -- Check if given Value is changing version of a document. -- @param Value version under test not overriding function Parent (Self : Version_Tree; Value : Version) return Version; -- Provide origin of given Version. -- @param Value version under query not overriding procedure Start_Change (Self : in out Version_Tree; Parent : Version; Changing : out Version); -- Create new changing version by branching it from given Parent version. -- @param Parent version to branch new one from -- @param Changing return new version. It becames changing version of -- a document generic type Element is private; -- @private Disable indexing this type in gnatdoc package Versioned_Values is -- @summary -- Versioned Values -- -- @description -- The package provides Container to keep history of value changes -- over the time. type Container is private; -- Container to store history of value changes. procedure Initialize (Self : in out Container; Initial_Value : Element); -- Initialize container and place Initial_Value as current. -- @param Initial_Value value at the initial version of a document function Get (Self : Container; Time : Version) return Element; -- Retrieve a value from container corresponding to given version. -- @param Time provides requested version -- @return Value at given time/version procedure Set (Self : in out Container; Value : Element; Time : Version; Changes : in out Integer); -- Update container by given value. Version should be Is_Changing in -- the corresponding Version_Tree. The call returns Changes counter: -- * as +1 if Value becomes new value of the property -- * as -1 if Value is revereted to old value of the property -- * and 0 if Value has been changed already or match old value procedure Discard (Self : in out Container; Time : Version; Changes : out Integer); -- Update container by reverting its value. Version should be -- Is_Changing as in Set. See Set for description of Changes. private type Circle_Index is mod 8; type Element_Array is array (Circle_Index) of Element; type Version_Array is array (Circle_Index) of Version; type Container is record Elements : Element_Array; Versions : Version_Array; Index : Circle_Index := 0; end record; end Versioned_Values; private -- This is prototype implementation. It doesn't support branching -- and keeps history as linear sequence of versions. Only a few versions -- are kept and any older versions are dropped. type Version is mod 256; function "<" (Left, Right : Version) return Boolean; function ">=" (Left, Right : Version) return Boolean is (not (Left < Right)); function ">" (Left, Right : Version) return Boolean is (Right < Left); type Version_Tree is tagged limited record Changing : Version := 1; end record; end Incr.Version_Trees;
{ "source": "starcoderdata", "programming_language": "ada" }
with GDNative.Context; with GDNative.Console; with GDNative.Exceptions; with Adventure; package body Engine_Hooks is procedure On_GDNative_Init (p_options : access Thin.godot_gdnative_init_options) is begin Context.GDNative_Initialize (p_options); Console.Put ("GDNative Initialized!"); end; procedure On_GDNative_Terminate (p_options : access Thin.godot_gdnative_terminate_options) is begin Console.Put ("GDNative Finalized!"); Context.GDNative_Finalize (p_options); end; procedure On_Nativescript_Init (p_handle : Thin.Nativescript_Handle) is begin Console.Put ("Nativescript Initialzing"); Context.Nativescript_Initialize (p_handle); Adventure.Register_Classes; Console.Put ("Nativescript Initialized!"); exception when Error : others => Exceptions.Put_Error (Error); end; end;
{ "source": "starcoderdata", "programming_language": "ada" }
with TEXT_IO; with INFLECTIONS_PACKAGE; use INFLECTIONS_PACKAGE; with DICTIONARY_PACKAGE; use DICTIONARY_PACKAGE; with ADDONS_PACKAGE; use ADDONS_PACKAGE; with WORD_SUPPORT_PACKAGE; use WORD_SUPPORT_PACKAGE; package WORD_PACKAGE is LINE_NUMBER, WORD_NUMBER : INTEGER := 0; type STEM_ARRAY_TYPE is array (INTEGER range <>) of STEM_TYPE; subtype STEM_ARRAY is STEM_ARRAY_TYPE(0..MAX_STEM_SIZE); NOT_A_STEM : constant STEM_TYPE := (others => 'x'); NOT_A_STEM_ARRAY : STEM_ARRAY := (others => NOT_A_STEM); SA, SSA : STEM_ARRAY := NOT_A_STEM_ARRAY; SSA_MAX : INTEGER := 0; type PRUNED_DICTIONARY_ITEM is record DS : DICTIONARY_STEM; D_K : DICTIONARY_KIND := DEFAULT_DICTIONARY_KIND; end record; NULL_PRUNED_DICTIONARY_ITEM : PRUNED_DICTIONARY_ITEM; type PRUNED_DICTIONARY_LIST is array (1..80) of PRUNED_DICTIONARY_ITEM; -- Aug 96 QU_PRON max 42, PACK max 54 -- Jan 97 QU_PRON max 42, PACK max 74 -- Might reduce PDL : PRUNED_DICTIONARY_LIST := (others => NULL_PRUNED_DICTIONARY_ITEM); PDL_INDEX : INTEGER := 0; subtype SAL is PARSE_ARRAY(1..250); type DICT_RESTRICTION is (X, REGULAR, QU_PRON_ONLY, PACK_ONLY); XXX_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For TRICKS YYY_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For SYNCOPE NNN_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For Names RRR_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For Roman Numerals PPP_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For COMPOUNDED SCROLL_LINE_NUMBER : INTEGER := 0; OUTPUT_SCROLL_COUNT : INTEGER := 0; procedure PAUSE(OUTPUT : TEXT_IO.FILE_TYPE); function MIN(A, B : INTEGER) return INTEGER; function LTU(C, D : CHARACTER) return BOOLEAN; function EQU(C, D : CHARACTER) return BOOLEAN; function GTU(C, D : CHARACTER) return BOOLEAN; function LTU(S, T : STRING) return BOOLEAN; function GTU(S, T : STRING) return BOOLEAN; function EQU(S, T : STRING) return BOOLEAN; procedure RUN_INFLECTIONS(S : in STRING; SL : in out SAL; RESTRICTION : DICT_RESTRICTION := REGULAR); procedure SEARCH_DICTIONARIES(SSA : in STEM_ARRAY_TYPE; PREFIX : PREFIX_ITEM; SUFFIX : SUFFIX_ITEM; RESTRICTION : DICT_RESTRICTION := REGULAR); procedure WORD(RAW_WORD : in STRING; PA : in out PARSE_ARRAY; PA_LAST : in out INTEGER); procedure CHANGE_LANGUAGE(C : CHARACTER); procedure INITIALIZE_WORD_PACKAGE; end WORD_PACKAGE;
{ "source": "starcoderdata", "programming_language": "ada" }
-- * ISO C99: 7.18 Integer types <stdint.h> -- -- Exact integral types. -- Signed. -- There is some amount of overlap with <sys/types.h> as known by inet code -- Unsigned. subtype uint8_t is unsigned_char; -- stdint.h:48 subtype uint16_t is unsigned_short; -- stdint.h:49 subtype uint32_t is unsigned; -- stdint.h:51 subtype uint64_t is unsigned_long; -- stdint.h:55 -- Small types. -- Signed. subtype int_least8_t is signed_char; -- stdint.h:65 subtype int_least16_t is short; -- stdint.h:66 subtype int_least32_t is int; -- stdint.h:67 subtype int_least64_t is long; -- stdint.h:69 -- Unsigned. subtype uint_least8_t is unsigned_char; -- stdint.h:76 subtype uint_least16_t is unsigned_short; -- stdint.h:77 subtype uint_least32_t is unsigned; -- stdint.h:78 subtype uint_least64_t is unsigned_long; -- stdint.h:80 -- Fast types. -- Signed. subtype int_fast8_t is signed_char; -- stdint.h:90 subtype int_fast16_t is long; -- stdint.h:92 subtype int_fast32_t is long; -- stdint.h:93 subtype int_fast64_t is long; -- stdint.h:94 -- Unsigned. subtype uint_fast8_t is unsigned_char; -- stdint.h:103 subtype uint_fast16_t is unsigned_long; -- stdint.h:105 subtype uint_fast32_t is unsigned_long; -- stdint.h:106 subtype uint_fast64_t is unsigned_long; -- stdint.h:107 -- Types for `void *' pointers. subtype uintptr_t is unsigned_long; -- stdint.h:122 -- Largest integral types. subtype intmax_t is long; -- stdint.h:134 subtype uintmax_t is unsigned_long; -- stdint.h:135 -- Limits of integral types. -- Minimum of signed integral types. -- Maximum of signed integral types. -- Maximum of unsigned integral types. -- Minimum of signed integral types having a minimum size. -- Maximum of signed integral types having a minimum size. -- Maximum of unsigned integral types having a minimum size. -- Minimum of fast signed integral types having a minimum size. -- Maximum of fast signed integral types having a minimum size. -- Maximum of fast unsigned integral types having a minimum size. -- Values to test for integral types holding `void *' pointer. -- Minimum for largest signed integral type. -- Maximum for largest signed integral type. -- Maximum for largest unsigned integral type. -- Limits of other integer types. -- Limits of `ptrdiff_t' type. -- Limits of `sig_atomic_t'. -- Limit of `size_t' type. -- Limits of `wchar_t'. -- These constants might also be defined in <wchar.h>. -- Limits of `wint_t'. -- Signed. -- Unsigned. -- Maximal type. end CUPS.stdint_h;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_Io; with Ada.Integer_text_IO; procedure Call_Back_Example is -- Purpose: Apply a callback to an array -- Output: Prints the squares of an integer array to the console -- Define the callback procedure procedure Display(Location : Positive; Value : Integer) is begin Ada.Text_Io.Put("array("); Ada.Integer_Text_Io.Put(Item => Location, Width => 1); Ada.Text_Io.Put(") = "); Ada.Integer_Text_Io.Put(Item => Value * Value, Width => 1); Ada.Text_Io.New_Line; end Display; -- Define an access type matching the signature of the callback procedure type Call_Back_Access is access procedure(L : Positive; V : Integer); -- Define an unconstrained array type type Value_Array is array(Positive range <>) of Integer; -- Define the procedure performing the callback procedure Map(Values : Value_Array; Worker : Call_Back_Access) is begin for I in Values'range loop Worker(I, Values(I)); end loop; end Map; -- Define and initialize the actual array Sample : Value_Array := (5,4,3,2,1); begin Map(Sample, Display'access); end Call_Back_Example;
{ "source": "starcoderdata", "programming_language": "ada" }
with System.Storage_Elements; function Storage_Array_To_String(X : System.Storage_Elements.Storage_Array) return String is use System.Storage_Elements; begin -- This compile-time check is useful for GNAT, but in GNATprove it currently -- just generates a warning that it can not yet be proved correct. pragma Warnings (GNATprove, Off, "Compile_Time_Error"); pragma Compile_Time_Error ((Character'Size /= Storage_Element'Size), "Character and Storage_Element types are different sizes!"); pragma Warnings (GNATprove, On, "Compile_Time_Error"); return R : String(Integer(X'First) .. Integer(X'Last)) do for I in X'Range loop R(Integer(I)) := Character'Val(Storage_Element'Pos(X(I))); end loop; end return; end Storage_Array_To_String;
{ "source": "starcoderdata", "programming_language": "ada" }
package body Buffer_Package is procedure Enable_Undo (B : in out Buffer) is begin B.Can_Undo := True; end Enable_Undo; procedure Clear_Tag (B : in out Buffer; T : Tag_Type) is begin if T < TAG_MAX then declare Val : constant Integer := Tag_Type'Pos (T); begin B.Tags (Val).P1 := (NONE, NONE); B.Tags (Val).P2 := (NONE, NONE); end; end if; end Clear_Tag; procedure Set_Tag (B : out Buffer; T : Tag_Type; P1 : Pos; P2 : Pos; V : Integer) is begin if T < TAG_MAX and P1.L /= NONE and P1.C /= NONE and P2.L /= NONE and P2.C /= NONE then declare Val : constant Integer := Tag_Type'Pos (T); begin B.Tags (Val).P1 := P1; B.Tags (Val).P2 := P2; B.Tags (Val).V := V; end; end if; end Set_Tag; end Buffer_Package;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with Ada.Unchecked_Deallocation; package body Ahven.SList is procedure Remove (Ptr : Node_Access) is procedure Free is new Ada.Unchecked_Deallocation (Object => Node, Name => Node_Access); My_Ptr : Node_Access := Ptr; begin Ptr.Next := null; Free (My_Ptr); end Remove; procedure Append (Target : in out List; Node_Data : Element_Type) is New_Node : Node_Access := null; begin if Target.Size = Count_Type'Last then raise List_Full; end if; New_Node := new Node'(Data => Node_Data, Next => null); if Target.Last = null then Target.First := New_Node; else Target.Last.Next := New_Node; end if; Target.Last := New_Node; Target.Size := Target.Size + 1; end Append; procedure Clear (Target : in out List) is Current_Node : Node_Access := Target.First; Next_Node : Node_Access := null; begin while Current_Node /= null loop Next_Node := Current_Node.Next; Remove (Current_Node); Current_Node := Next_Node; end loop; Target.First := null; Target.Last := null; Target.Size := 0; end Clear; function First (Target : List) return Cursor is begin return Cursor (Target.First); end First; function Next (Position : Cursor) return Cursor is begin if Position = null then raise Invalid_Cursor; end if; return Cursor (Position.Next); end Next; function Data (Position : Cursor) return Element_Type is begin if Position = null then raise Invalid_Cursor; end if; return Position.Data; end Data; function Is_Valid (Position : Cursor) return Boolean is begin return Position /= null; end Is_Valid; function Length (Target : List) return Count_Type is begin return Target.Size; end Length; procedure For_Each (Target : List) is Current_Node : Node_Access := Target.First; begin while Current_Node /= null loop Action (Current_Node.Data); Current_Node := Current_Node.Next; end loop; end For_Each; procedure Initialize (Target : in out List) is begin Target.Last := null; Target.First := null; Target.Size := 0; end Initialize; procedure Finalize (Target : in out List) is begin Clear (Target); end Finalize; procedure Adjust (Target : in out List) is Target_Last : Node_Access := null; Target_First : Node_Access := null; Current : Node_Access := Target.First; New_Node : Node_Access; begin -- Recreate the list using the same data while Current /= null loop New_Node := new Node'(Data => Current.Data, Next => null); if Target_Last = null then Target_First := New_Node; else Target_Last.Next := New_Node; end if; Target_Last := New_Node; Current := Current.Next; end loop; Target.First := Target_First; Target.Last := Target_Last; -- No need to adjust size, it is same as before copying end Adjust; end Ahven.SList;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Util.Beans.Basic; package Util.Beans.Objects.Pairs is -- The <tt>Pair</tt> type is a bean that contains two values named first/key and -- second/value. type Pair is new Util.Beans.Basic.Bean with record First : Object; Second : Object; end record; type Pair_Access is access all Pair'Class; -- 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 Pair; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Pair; Name : in String; Value : in Util.Beans.Objects.Object); -- Return an object represented by the pair of two values. function To_Object (First, Second : in Object) return Object; end Util.Beans.Objects.Pairs;
{ "source": "starcoderdata", "programming_language": "ada" }
package body openGL.Model.sphere is --------- --- Forge -- procedure define (Self : out Item; Radius : Real) is begin Self.Radius := Radius; end define; -------------- --- Attributes -- overriding function Bounds (Self : in Item) return openGL.Bounds is begin return (Ball => Self.Radius, Box => (Lower => (-Self.Radius, -Self.Radius, -Self.Radius), Upper => ( Self.Radius, Self.Radius, Self.Radius))); end Bounds; end openGL.Model.sphere;
{ "source": "starcoderdata", "programming_language": "ada" }
--____________________________________________________________________-- -- -- This package provides an implementation of code sources consisting -- of several lines. The package defines an abstract base type Source. -- with Ada.Finalization; with Ada.Unchecked_Deallocation; with Parsers.Generic_Source; package Parsers.Multiline_Source is type Line_Number is new Natural; -- -- Position -- File postion -- type Position is record Line : Line_Number; Column : Integer; end record; function "<" (Left, Right : Position) return Boolean; -- -- Location -- File slice from First to previous to Next -- type Location is record First : Position; Next : Position; end record; type String_Ptr is access all String; -- -- Source -- The source containing a file -- -- Buffer - The source line buffer -- Line - The current source line number -- Length - The current line length -- Pointer - The second cursor -- Last - The first (backup) cursor -- -- The field Buffer points to a string, which is used to keep the -- current source line. The constructor allocates the buffer of some -- reasonable size. When a new line is requested the buffer can be -- replaced by a greater one if necessary. The destructor deallocates -- the buffer. -- type Source is abstract new Ada.Finalization.Limited_Controlled with record Buffer : String_Ptr; Line : Line_Number := 0; Length : Natural; Pointer : Integer; Last : Integer; end record; type Line_Ptr is access constant String; -- -- Finalize -- Destruction -- -- Code - The source code -- procedure Finalize (Code : in out Source); -- -- Initialize -- Construction -- -- Code - The source code -- procedure Initialize (Code : in out Source); -- -- Get_Line -- Read the next line into the buffer -- -- Code - The source code -- -- An implementation should read a complete next line into -- Code.Buffer.all. It may reallocate the buffer if necessary. After -- successful completion Code.Buffer should point to a buffer containing -- the line and Code.Length should be the line length. The rest of the -- buffer is ignored. -- -- Exceptions : -- -- End_Error - No more lines available -- Any other - I/O error etc -- procedure Get_Line (Code : in out Source) is abstract; -- -- Get_Location -- Of an error from an error message string -- -- Message - An error message -- Prefix - Introducing error location image -- -- This function searches for a location image in an error message -- string. The image is searched backwards for an appearance of Prefix. -- If an image does not follow Prefix search continues. The result is -- the location decoded according to the format used by Image. If no -- image found the result is ((0,0), (0,0). -- -- Returns : -- -- The rightmost location -- function Get_Location ( Message : String; Prefix : String := "at " ) return Location; -- -- Skip -- Advance source to the specified location -- -- Code - The source code -- Link - Location -- -- This procedure advances the source Code to the location Link, so that -- the result of Link (Code) would equal to the value of the parameter -- Link. Layout_Error is propagated when the source is beyond the first -- position of Link. It is also propagated when some parts of Link do -- not belong to the source Code. -- -- Exceptions : -- -- Layout_Error - Link is beyond the actual position -- Any other - I/O error etc -- procedure Skip (Code : in out Source'Class; Link : Location); -- -- Implementations of the Parsers.Generic_Source interface -- function "&" (Left, Right : Location) return Location; function End_Of (Code : Source'Class) return Boolean; function Get_Backup_Pointer (Code : Source'Class) return Integer; function Get_Line (Code : Source'Class) return String; procedure Get_Line ( Code : Source'Class; Line : out Line_Ptr; Pointer : out Integer; Last : out Integer ); function Get_Pointer (Code : Source'Class) return Integer; function Image (Link : Location) return String; function Link (Code : Source'Class) return Location; procedure Next_Line (Code : in out Source'Class); procedure Reset_Pointer (Code : in out Source'Class); procedure Set_Pointer ( Code : in out Source'Class; Pointer : Integer ); -- -- Code -- The implementation -- package Code is new Parsers.Generic_Source ( Location_Type => Location, Source_Type => Source'Class, Line_Ptr_Type => Line_Ptr ); private pragma Inline ("<"); pragma Inline (End_Of); pragma Inline (Get_Backup_Pointer); pragma Inline (Get_Line); pragma Inline (Get_Pointer); pragma Inline (Link); pragma Inline (Reset_Pointer); procedure Free is new Ada.Unchecked_Deallocation (String, String_Ptr); end Parsers.Multiline_Source;
{ "source": "starcoderdata", "programming_language": "ada" }
-- SOFTWARE. with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; with DG_Types; use DG_Types; package Simh_Tapes is -- tape image markers Mtr_Tmk : constant Dword_T := 0; Mtr_EOM : constant Dword_T := 16#ffff_ffff#; Mtr_Gap : constant Dword_T := 16#ffff_fffe#; Mtr_Max_Len : constant Dword_T := 16#00ff_ffff#; Mtr_Erf : constant Dword_T := 16#8000_0000#; -- status codes type Mt_Stat is (OK, Tmk, Unatt, IOerr, InvRec, InvFmt, BOT, EOM, RecErr, WrOnly); type Mt_Rec is array (Natural range <>) of Byte_T; procedure Read_Meta_Data (Img_Stream : in out Stream_Access; Meta_Data : out Dword_T); procedure Write_Meta_Data (Img_Stream : in out Stream_Access; Meta_Data : in Dword_T); procedure Read_Record_Data (Img_Stream : in out Stream_Access; Num_Bytes : in Natural; Rec : out Mt_Rec); procedure Write_Record_Data (Img_Stream : in out Stream_Access; Rec : in Mt_Rec); procedure Rewind (Img_File : in out File_Type); function Space_Forward (Img_Stream : in out Stream_Access; Num_Recs : in Integer) return Mt_Stat; function Scan_Image (Img_Filename : in String) return String; end Simh_Tapes;
{ "source": "starcoderdata", "programming_language": "ada" }
with impact.d3.Transform; with impact.d3.collision.point_Collector; with impact.d3.collision.Detector.discrete.gjk_pair; with impact.d3.collision.Detector.discrete; with impact.d3.Vector; -- #include "impact.d3.collision.convex_Raycast.gjk.h" -- #include "BulletCollision/CollisionShapes/impact.d3.Shape.convex.internal.sphere.h" -- #include "impact.d3.collision.Detector.discrete.gjk_pair.h" -- #include "impact.d3.collision.point_Collector.h" -- #include "LinearMath/impact.d3.TransformUtil.h" package body impact.d3.collision.convex_Raycast.gjk is ------------ --- Globals -- -- #ifdef BT_USE_DOUBLE_PRECISION MAX_ITERATIONS : constant := 64; -- #else -- #define MAX_ITERATIONS 32 -- #endif ---------- --- Forge -- function to_gjk_convex_Raycast (convexA, convexB : access impact.d3.Shape.convex.Item'Class; simplexSolver : access impact.d3.collision.simplex_Solver.Item'Class) return Item is Self : constant Item := (impact.d3.collision.convex_Raycast.item with m_simplexSolver => simplexSolver, m_convexA => convexA, m_convexB => convexB); begin return Self; end to_gjk_convex_Raycast; --------------- --- Attributes -- overriding function calcTimeOfImpact (Self : access Item; fromA, toA : in Transform_3d; fromB, toB : in Transform_3d; result : access impact.d3.collision.convex_Raycast.CastResult'Class) return Boolean is use impact.d3.Transform, math.Vectors; linVelA : constant math.Vector_3 := getOrigin (toA) - getOrigin (fromA); linVelB : constant math.Vector_3 := getOrigin (toB) - getOrigin (fromB); radius : math.Real := 0.001; lambda : math.Real := 0.0; v : math.vector_3 := (1.0, 0.0, 0.0); maxIter : constant Integer := MAX_ITERATIONS; n : math.Vector_3 := (0.0, 0.0, 0.0); hasResult : Boolean := False; c : math.Vector_3; r : constant math.Vector_3 := linVelA - linVelB; lastLambda : math.Real := lambda; -- impact.d3.Scalar epsilon = impact.d3.Scalar(0.001); numIter : Integer := 0; -- first solution, using GJK identityTrans : Transform_3d := getIdentity; pointCollector : impact.d3.collision.point_Collector.item; gjk : Detector.discrete.gjk_pair.item := Detector.discrete.gjk_pair.to_gjk_pair_Detector (Self.m_convexA, Self.m_convexB, Self.m_simplexSolver, null); -- m_penetrationDepthSolver); input : Detector.discrete.ClosestPointInput; dist : math.Real; begin Self.m_simplexSolver.reset; -- compute linear velocity for this interval, to interpolate -- assume no rotation/angular velocity, assert here? -- -- we don't use margins during CCD -- gjk.setIgnoreMargin(true); input.m_transformA := fromA; input.m_transformB := fromB; gjk.getClosestPoints (input, pointCollector, False); hasResult := pointCollector.m_hasResult; c := pointCollector.m_pointInWorld; if hasResult then dist := pointCollector.m_distance; n := pointCollector.m_normalOnBInWorld; -- not close enough -- while dist > radius loop numIter := numIter + 1; if numIter > maxIter then return False; -- todo: report a failure end if; declare use impact.d3.Vector; dLambda : math.Real := 0.0; projectedLinearVelocity : constant math.Real := dot (r, n); begin dLambda := dist / projectedLinearVelocity; lambda := lambda - dLambda; if lambda > 1.0 then return False; end if; if lambda < 0.0 then return False; end if; -- todo: next check with relative epsilon if lambda <= lastLambda then return False; -- n.setValue(0,0,0); -- exit; end if; lastLambda := lambda; -- interpolate to next lambda -- setInterpolate3 (getOrigin (input.m_transformA'Access).all, getOrigin (fromA), getOrigin (toA), lambda); setInterpolate3 (getOrigin (input.m_transformB'Access).all, getOrigin (fromB), getOrigin (toB), lambda); gjk.getClosestPoints (input, pointCollector, False); if pointCollector.m_hasResult then if pointCollector.m_distance < 0.0 then result.m_fraction := lastLambda; n := pointCollector.m_normalOnBInWorld; result.m_normal := n; result.m_hitPoint := pointCollector.m_pointInWorld; return True; end if; c := pointCollector.m_pointInWorld; n := pointCollector.m_normalOnBInWorld; dist := pointCollector.m_distance; else return False; -- ?? end if; end; end loop; -- is n normalized? -- don't report time of impact for motion away from the contact normal (or causes minor penetration) -- if impact.d3.Vector.dot (n, r) >= -result.m_allowedPenetration then return False; end if; result.m_fraction := lambda; result.m_normal := n; result.m_hitPoint := c; return True; end if; return False; end calcTimeOfImpact; end impact.d3.collision.convex_Raycast.gjk; -- -- -- -- bool impact.d3.collision.convex_Raycast.gjk::calcTimeOfImpact( -- const impact.d3.Transform& fromA, -- const impact.d3.Transform& toA, -- const impact.d3.Transform& fromB, -- const impact.d3.Transform& toB, -- CastResult& result) -- { -- -- -- m_simplexSolver->reset(); -- -- /// compute linear velocity for this interval, to interpolate -- //assume no rotation/angular velocity, assert here? -- impact.d3.Vector linVelA,linVelB; -- linVelA = toA.getOrigin()-fromA.getOrigin(); -- linVelB = toB.getOrigin()-fromB.getOrigin(); -- -- impact.d3.Scalar radius = impact.d3.Scalar(0.001); -- impact.d3.Scalar lambda = impact.d3.Scalar(0.); -- impact.d3.Vector v(1,0,0); -- -- int maxIter = MAX_ITERATIONS; -- -- impact.d3.Vector n; -- n.setValue(impact.d3.Scalar(0.),impact.d3.Scalar(0.),impact.d3.Scalar(0.)); -- bool hasResult = false; -- impact.d3.Vector c; -- impact.d3.Vector r = (linVelA-linVelB); -- -- impact.d3.Scalar lastLambda = lambda; -- //impact.d3.Scalar epsilon = impact.d3.Scalar(0.001); -- -- int numIter = 0; -- //first solution, using GJK -- -- -- impact.d3.Transform identityTrans; -- identityTrans.setIdentity(); -- -- -- // result.drawCoordSystem(sphereTr); -- -- impact.d3.collision.point_Collector pointCollector; -- -- -- impact.d3.collision.Detector.discrete.gjk_pair gjk(m_convexA,m_convexB,m_simplexSolver,0);//m_penetrationDepthSolver); -- impact.d3.collision.Detector.discrete.gjk_pair::ClosestPointInput input; -- -- //we don't use margins during CCD -- // gjk.setIgnoreMargin(true); -- -- input.m_transformA = fromA; -- input.m_transformB = fromB; -- gjk.getClosestPoints(input,pointCollector,0); -- -- hasResult = pointCollector.m_hasResult; -- c = pointCollector.m_pointInWorld; -- -- if (hasResult) -- { -- impact.d3.Scalar dist; -- dist = pointCollector.m_distance; -- n = pointCollector.m_normalOnBInWorld; -- -- -- -- //not close enough -- while (dist > radius) -- { -- numIter++; -- if (numIter > maxIter) -- { -- return false; //todo: report a failure -- } -- impact.d3.Scalar dLambda = impact.d3.Scalar(0.); -- -- impact.d3.Scalar projectedLinearVelocity = r.dot(n); -- -- dLambda = dist / (projectedLinearVelocity); -- -- lambda = lambda - dLambda; -- -- if (lambda > impact.d3.Scalar(1.)) -- return false; -- -- if (lambda < impact.d3.Scalar(0.)) -- return false; -- -- //todo: next check with relative epsilon -- if (lambda <= lastLambda) -- { -- return false; -- //n.setValue(0,0,0); -- break; -- } -- lastLambda = lambda; -- -- //interpolate to next lambda -- result.DebugDraw( lambda ); -- input.m_transformA.getOrigin().setInterpolate3(fromA.getOrigin(),toA.getOrigin(),lambda); -- input.m_transformB.getOrigin().setInterpolate3(fromB.getOrigin(),toB.getOrigin(),lambda); -- -- gjk.getClosestPoints(input,pointCollector,0); -- if (pointCollector.m_hasResult) -- { -- if (pointCollector.m_distance < impact.d3.Scalar(0.)) -- { -- result.m_fraction = lastLambda; -- n = pointCollector.m_normalOnBInWorld; -- result.m_normal=n; -- result.m_hitPoint = pointCollector.m_pointInWorld; -- return true; -- } -- c = pointCollector.m_pointInWorld; -- n = pointCollector.m_normalOnBInWorld; -- dist = pointCollector.m_distance; -- } else -- { -- //?? -- return false; -- } -- -- } -- -- //is n normalized? -- //don't report time of impact for motion away from the contact normal (or causes minor penetration) -- if (n.dot(r)>=-result.m_allowedPenetration) -- return false; -- -- result.m_fraction = lambda; -- result.m_normal = n; -- result.m_hitPoint = c; -- return true; -- } -- -- return false; -- -- -- }
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with LSE.Utils.Angle; with LSE.Model.Grammar.Symbol_Utils; with LSE.Model.L_System.Growth_Rule; use Ada.Containers; use LSE.Utils.Angle; use LSE.Model.Grammar.Symbol_Utils.P_List; use LSE.Model.Grammar.Symbol_Utils.Ptr; -- @description -- This package provides a factory for making a L-System. -- package LSE.Model.L_System.Factory is -- Make an axiom -- @param Value String to convert to a list of Symbol -- @return Return the list created function Make_Axiom (Value : String) return LSE.Model.Grammar.Symbol_Utils.P_List.List; -- Make an angle -- @param Value String to convert to an angle -- @return Return the angle created function Make_Angle (Value : String) return LSE.Utils.Angle.Angle; -- Make a growth rule -- @param Value String to convert to a growth rule -- @return Return the growth rule created function Make_Rule (Head : Character; Rule : String) return Growth_Rule.Instance; private -- Get hash of a character -- @param Key Character to get hash -- @return Return the hash corresponding to character function ID_Hashed (Key : Character) return Hash_Type; package Know_Symbol is new Ada.Containers.Hashed_Maps (Key_Type => Character, Element_Type => Holder, Hash => ID_Hashed, Equivalent_Keys => "="); -- List of static symbol (optimized to prevent RAM overflow) Symbol_List : Know_Symbol.Map; -- Get the symbol corresponding to the character -- @param Key Character used to get corresponding symbol -- @return Return a pointer to the corresponding symbol function Get_Symbol (Key : Character) return Holder; -- Create a list of symbol -- @param Value String to convert to symbol list -- @return Return the list of symbol created function Make_Symbol_List (Value : String) return LSE.Model.Grammar.Symbol_Utils.P_List.List; end LSE.Model.L_System.Factory;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Servlet.Parts; -- The <b>ASF.Parts</b> package is an Ada implementation of the Java servlet part -- (JSR 315 3. The Request) provided by the <tt>javax.servlet.http.Part</tt> class. package ASF.Parts is -- ------------------------------ -- Multi part content -- ------------------------------ -- The <b>Part</b> type describes a mime part received in a request. -- The content is stored in a file and several operations are provided -- to manage the content. subtype Part is Servlet.Parts.Part; end ASF.Parts;
{ "source": "starcoderdata", "programming_language": "ada" }
--------------------------------------------------------------------------- with Ada.Numerics; with Ada.Numerics.Generic_Elementary_Functions; with Givens_Rotation; package body Hessenberg is package math is new Ada.Numerics.Generic_Elementary_Functions (Real); use math; package Rotate is new Givens_Rotation (Real); use Rotate; Zero : constant Real := +0.0; One : constant Real := +1.0; Two : constant Real := +2.0; function Identity return A_Matrix is Q : A_Matrix; begin Q := (others => (others => Zero)); for c in C_Index loop Q(c, c) := One; end loop; return Q; end Identity; ---------------------- -- Upper_Hessenberg -- ---------------------- -- Operates only on square real blocks. -- -- Want to use similarity transforms to make A into H, -- upper Hessenberg. Let Qj be a 2x2 givens rotation matrix, -- and let Qj' be its transpose (and inverse). Then form -- -- A = -- -- (Q1*...*Qn) * (Qn'*...*Q1') * A * (Q1*...*Qn) * (Qn'*...*Q1') = -- -- Q * H * Q', -- -- where H = Q' * A * Q. -- -- To complete the decomposition of A to H, insert Qj * Qj' into -- Q * H * Q' to get Q * (Qj * Qj') * H * (Qj * Qj') * Q'. -- -- So to develop Q, we rotate columns of Q by multiplying on RHS with -- Qj. H gets multiplied on the LHS by Qj' (rotating rows to zero out -- the lower triangular region) and on the RHS by Qj. -- -- Wind up with the eigenvalue equation A = Q * H * Q' which becomes -- -- A * Q = Q * H. -- -- If H were diagonal, then the column vectors of Q would be the eigenvectors -- and the diagonal elements of H would be the eigenvalues. procedure Upper_Hessenberg (A : in out A_Matrix; Q : out A_Matrix; Starting_Col : in C_Index := C_Index'First; Final_Col : in C_Index := C_Index'Last; Initial_Q : in A_Matrix := Identity) is Final_Row : constant C_Index := Final_Col; Pivot_Row : R_Index; --------------------------------------- -- Rotate_to_Kill_Element_Lo_of_pCol -- --------------------------------------- -- Zero out A(Lo_Row, pCol) with a similarity transformation. In -- other words, multiply A on left by Q_tr and on right by Q: -- A_h = Q_transpose * A * Q procedure Rotate_to_Kill_Element_Lo_of_pCol (pCol : in C_Index; Hi_Row : in R_Index; Lo_Row : in R_Index) is sn, cs : Real; cs_minus_1 : Real; sn_minus_1 : Real; hypot : Real; P_bigger_than_L : Boolean; Skip_Rotation : Boolean; Pivot_Col : C_Index renames pCol; Pivot_Row : R_Index renames Hi_Row; Low_Row : R_Index renames Lo_Row; A_pvt, A_low, Q_pvt, Q_low : Real; P : constant Real := A(Pivot_Row, Pivot_Col); -- P is for Pivot L : constant Real := A(Low_Row, Pivot_Col); begin Get_Rotation_That_Zeros_Out_Low (P, L, sn, cs, cs_minus_1, sn_minus_1, hypot, P_bigger_than_L, Skip_Rotation); if Skip_Rotation then return; end if; -- Rotate rows. Multiply on LHS by givens rotation G. -- Want Q' A Q = H = upper hessenberg. -- Each step is: G A G' = partial H -- So the desired Q will be the product of the G' matrices -- which we obtain by repeatedly multiplying I on the RHS by G'. if P_bigger_than_L then -- |s| < |c| for c in Pivot_Col .. Final_Col loop A_pvt := A(Pivot_Row, c); A_low := A(Low_Row, c); A(Pivot_Row, c) := A_pvt + ( cs_minus_1*A_pvt + sn*A_low); A(Low_Row, c) := A_low + (-sn*A_pvt + cs_minus_1*A_low); end loop; else -- Abs_P <= Abs_L, so abs t := abs (P / L) <= 1 for c in Pivot_Col .. Final_Col loop A_pvt := A(Pivot_Row, c); A_low := A(Low_Row, c); A(Pivot_Row, c) := A_low + ( cs*A_pvt + sn_minus_1*A_low); A(Low_Row, c) :=-A_pvt + (-sn_minus_1*A_pvt + cs*A_low); end loop; end if; A(Pivot_Row, Pivot_Col) := Real'Copy_Sign (Hypot, A(Pivot_Row, Pivot_Col)); -- Rotate corresponding columns. Multiply on RHS by transpose -- of above givens matrix (second step of similarity transformation). -- (Low_Row is Lo visually, but its index is higher than Pivot's.) if P_bigger_than_L then -- |s| < |c| for r in Starting_Col .. Final_Col loop A_pvt := A(r, Pivot_Row); A_low := A(r, Low_Row); A(r, Pivot_Row) := A_pvt + ( cs_minus_1*A_pvt + sn*A_low); A(r, Low_Row) := A_low + (-sn*A_pvt + cs_minus_1*A_low); end loop; else -- Abs_P <= Abs_L, so abs t := abs (P / L) <= 1 for r in Starting_Col .. Final_Col loop A_pvt := A(r, Pivot_Row); A_low := A(r, Low_Row); A(r, Pivot_Row) := A_low + ( cs*A_pvt + sn_minus_1*A_low); A(r, Low_Row) :=-A_pvt + (-sn_minus_1*A_pvt + cs*A_low); end loop; end if; -- Rotate corresponding columns of Q. (Multiply on RHS by transpose -- of above givens matrix to accumulate full Q.) if P_bigger_than_L then -- |s| < |c| for r in Starting_Col .. Final_Col loop Q_pvt := Q(r, Pivot_Row); Q_low := Q(r, Low_Row); Q(r, Pivot_Row) := Q_pvt + ( cs_minus_1*Q_pvt + sn*Q_low); Q(r, Low_Row) := Q_low + (-sn*Q_pvt + cs_minus_1*Q_low); end loop; else -- Abs_P <= Abs_L, so abs t := abs (P / L) <= 1 for r in Starting_Col .. Final_Col loop Q_pvt := Q(r, Pivot_Row); Q_low := Q(r, Low_Row); Q(r, Pivot_Row) := Q_low + ( cs*Q_pvt + sn_minus_1*Q_low); Q(r, Low_Row) :=-Q_pvt + (-sn_minus_1*Q_pvt + cs*Q_low); end loop; end if; end Rotate_to_Kill_Element_Lo_of_pCol; type Column is array(R_Index) of Real; procedure Get_Sqrt_of_Sum_of_Sqrs_of_Col (Col_Id : in C_Index; Starting_Row : in R_Index; Ending_Row : in R_Index; Col_Sums : out Column) is Max : Real := Zero; Un_Scale, Scale : Real := Zero; Emin : constant Integer := Real'Machine_Emin; Emax : constant Integer := Real'Machine_Emax; Abs_A : Real := Zero; M_exp : Integer := 0; begin Max := Abs A(Starting_Row, Col_Id); if Ending_Row > Starting_Row then for i in Starting_Row+1 .. Ending_Row loop Abs_A := Abs A(i, Col_Id); if Abs_A > Max then Max := Abs_A; end if; end loop; end if; if Max < Two**Emin then Col_Sums := (others => Zero); return; end if; if Max < Two**(Emin / 2) or else Max > Two**(Emax / 4) then M_Exp := Real'Exponent (Max); Scale := Two ** (-M_Exp); Un_Scale := Two ** ( M_Exp); else Scale := One; Un_Scale := One; end if; Col_Sums(Starting_Row) := Abs A(Starting_Row, Col_Id); if Ending_Row > Starting_Row then Compensated_Sum: declare val, Sum_tmp, Err, Sum : Real := Zero; begin for r in Starting_Row .. Ending_Row loop Val := (Scale * A(r, Col_Id)) ** 2; Val := Val - Err; -- correction to Val, next term in sum. Sum_tmp := Sum + Val; -- now increment Sum Err := (Sum_tmp - Sum) - Val; Sum := Sum_tmp; Col_Sums(r) := Un_Scale * Sqrt (Sum); end loop; end Compensated_Sum; end if; end Get_Sqrt_of_Sum_of_Sqrs_of_Col; Col_Sums : Column := (others => Zero); begin Q := Initial_Q; if (Final_Col - Starting_Col) < 2 then return; end if; for Pivot_Col in Starting_Col .. Final_Col-2 loop Pivot_Row := Pivot_Col + 1; Get_Sqrt_of_Sum_of_Sqrs_of_Col -- version _2 Only takes Sqrt of full column sum (Col_id => Pivot_Col, Starting_Row => Pivot_Row, Ending_Row => Final_Row, Col_Sums => Col_Sums); for Low_Row in Pivot_Row+1 .. Final_Row loop Rotate_to_Kill_Element_Lo_of_pCol -- zero out A(Lo_Row, pCol) (pCol => Pivot_Col, Hi_Row => Pivot_Row, -- Hi = high to eye; its id is lower than Lo_Row. Lo_Row => Low_Row); A(Low_Row, Pivot_Col) := Zero; A(Pivot_Row, Pivot_Col) := Real'Copy_Sign (Col_Sums(Low_Row), A(Pivot_Row, Pivot_Col)); end loop; -- over Low_Row end loop; -- over Pivot_Col end Upper_Hessenberg; ---------------------- -- Lower_Hessenberg -- ---------------------- procedure Lower_Hessenberg (A : in out A_Matrix; Q : out A_Matrix; Starting_Col : in C_Index := C_Index'First; Final_Col : in C_Index := C_Index'Last; Initial_Q : in A_Matrix := Identity) is Starting_Row : constant C_Index := Starting_Col; Final_Row : constant C_Index := Final_Col; Pivot_Col : R_Index := Starting_Col; --------------------------------------- -- Rotate_to_Kill_Element_Hi_of_pRow -- --------------------------------------- -- Zero out A(Lo_Row, pCol) with a similarity transformation. In -- other words, multiply A on left by Q_tr and on right by Q: -- A_h = Q_transpose * A * Q -- Use enhanced precision rotations here. procedure Rotate_to_Kill_Element_Hi_of_pRow (pRow : in R_Index; Lo_Col : in R_Index; Hi_Col : in R_Index) is sn, cs : Real; cs_minus_1 : Real; sn_minus_1 : Real; hypot : Real; P_bigger_than_H : Boolean; Skip_Rotation : Boolean; Pivot_Row : R_Index renames pRow; Pivot_Col : C_Index renames Lo_Col; A_pvt, A_hi , Q_pvt, Q_hi : Real; P : constant Real := A(Pivot_Row, Pivot_Col); -- P is for Pivot H : constant Real := A(Pivot_Row, Hi_Col); pragma Assert(Pivot_Col = Pivot_Row+1); begin Get_Rotation_That_Zeros_Out_Low (P, H, sn, cs, cs_minus_1, sn_minus_1, hypot, P_bigger_than_H, Skip_Rotation); if Skip_Rotation then return; end if; -- Rotate columns. Multiply on RHS by transpose -- of above givens matrix (second step of similarity transformation). -- (Hi_Col is to the rt. visually, and its index is higher than Pivot's.) if P_bigger_than_H then -- |s| < |c| for r in Starting_Row .. Final_Row loop A_pvt := A(r, Pivot_Col); A_hi := A(r, Hi_Col); A(r, Pivot_Col) := A_pvt + ( cs_minus_1*A_pvt + sn*A_hi); A(r, Hi_Col) := A_hi + (-sn*A_pvt + cs_minus_1*A_hi); end loop; else -- Abs_P <= Abs_H, so abs t := abs (P / H) <= 1 for r in Pivot_Row .. Final_Row loop A_pvt := A(r, Pivot_Col); A_hi := A(r, Hi_Col); A(r, Pivot_Col) := A_hi + ( cs*A_pvt + sn_minus_1*A_hi); A(r, Hi_Col) :=-A_pvt + (-sn_minus_1*A_pvt + cs*A_hi); end loop; end if; -- Rotate corresponding columns of Q. (Multiply on RHS by transpose -- of above givens matrix to accumulate full Q.) if P_bigger_than_H then -- |s| < |c| for r in Starting_Col .. Final_Col loop Q_pvt := Q(r, Pivot_Col); Q_hi := Q(r, Hi_Col); Q(r, Pivot_Col) := Q_pvt + ( cs_minus_1*Q_pvt + sn*Q_hi); Q(r, Hi_Col) := Q_hi + (-sn*Q_pvt + cs_minus_1*Q_hi); end loop; else -- Abs_P <= Abs_H, so abs t := abs (P / H) <= 1 for r in Starting_Col .. Final_Col loop Q_pvt := Q(r, Pivot_Col); Q_hi := Q(r, Hi_Col); Q(r, Pivot_Col) := Q_hi + ( cs*Q_pvt + sn_minus_1*Q_hi); Q(r, Hi_Col) :=-Q_pvt + (-sn_minus_1*Q_pvt + cs*Q_hi); end loop; end if; -- Rotate rows. Multiply on LHS by givens rotation G. -- Want Q' A Q = H = upper hessenberg. -- Each step is: G A G' = partial H -- So the desired Q will be the product of the G' matrices -- which we obtain by repeatedly multiplying I on the RHS by G'. if P_bigger_than_H then -- |s| < |c| for c in Starting_Col .. Final_Col loop A_pvt := A(Pivot_Col, c); A_hi := A(Hi_Col, c); A(Pivot_Col, c) := A_pvt + ( cs_minus_1*A_pvt + sn*A_hi); A(Hi_Col, c) := A_hi + (-sn*A_pvt + cs_minus_1*A_hi); end loop; else -- Abs_P <= Abs_H, so abs t := abs (P / H) <= 1 for c in Starting_Col .. Final_Col loop A_pvt := A(Pivot_Col, c); A_hi := A(Hi_Col, c); A(Pivot_Col, c) := A_hi + ( cs*A_pvt + sn_minus_1*A_hi); A(Hi_Col, c) :=-A_pvt + (-sn_minus_1*A_pvt + cs*A_hi); end loop; end if; end Rotate_to_Kill_Element_Hi_of_pRow; begin Q := Initial_Q; if (Final_Col - Starting_Col) < 2 then return; end if; for Pivot_Row in Starting_Row .. Final_Row-2 loop Pivot_Col := Pivot_Row + 1; -- the lower off-diagonal for Hi_Col in Pivot_Col+1 .. Final_Col loop Rotate_to_Kill_Element_Hi_of_pRow -- zero out A(pRow, Hi_Col) (pRow => Pivot_Row, Lo_Col => Pivot_Col, Hi_Col => Hi_Col); A(Pivot_Row, Hi_Col) := Zero; end loop; -- over Low_Row end loop; -- over Pivot_Col end Lower_Hessenberg; end Hessenberg;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with Interfaces.C; use type Interfaces.C.long; package body HW.Time.Timer with Refined_State => (Timer_State => null, Abstract_Time => null) is CLOCK_MONOTONIC_RAW : constant := 4; subtype Clock_ID_T is Interfaces.C.int; subtype Time_T is Interfaces.C.long; type Struct_Timespec is record TV_Sec : aliased Time_T; TV_NSec : aliased Interfaces.C.long; end record; pragma Convention (C_Pass_By_Copy, Struct_Timespec); function Clock_Gettime (Clock_ID : Clock_ID_T; Timespec : access Struct_Timespec) return Interfaces.C.int; pragma Import (C, Clock_Gettime, "clock_gettime"); function Raw_Value_Min return T is Ignored : Interfaces.C.int; Timespec : aliased Struct_Timespec; begin Ignored := Clock_Gettime (CLOCK_MONOTONIC_RAW, Timespec'Access); return T (Timespec.TV_Sec * 1_000_000_000 + Timespec.TV_NSec); end Raw_Value_Min; function Raw_Value_Max return T is begin return Raw_Value_Min + 1; end Raw_Value_Max; function Hz return T is begin return 1_000_000_000; -- clock_gettime(2) is fixed to nanoseconds end Hz; end HW.Time.Timer;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with PrimeInstances; package body Problem_49 is package IO renames Ada.Text_IO; type Four_Digit is new Integer range 1_000 .. 9_999; package Positive_Primes renames PrimeInstances.Positive_Primes; procedure Solve is Is_Prime : Array (Four_Digit) of Boolean := (others => False); prime : Positive; type Permute_Array is Array(Positive range <>) of Four_Digit; function Permute(num : Four_Digit) return Permute_Array is type Digit_Count is Array(0 .. 9) of Natural; d : Digit_Count := (others => 0); count : Positive := 4*3*2; begin declare quotient : Natural := Natural(num); remainder : Natural := 0; function fact(num : Natural) return Positive is result : Positive := 1; begin for n in 1 .. num loop result := result * n; end loop; return result; end; begin while(quotient > 0) loop remainder := quotient mod 10; quotient := quotient / 10; d(remainder) := d(remainder) + 1; end loop; for digit in d'Range loop count := count / fact(d(digit)); end loop; if d(0) = 1 then count := count - count / 4; elsif d(0) = 2 then count := count / 2; elsif d(0) = 3 then count := count / 4; end if; end; declare result : Permute_Array(1 .. count); num_array : Array(1 .. 4) of Natural; index : Positive := 1; possible : Natural; function Combine return Natural is result : Natural := 0; begin for index in num_array'Range loop result := 10*result + num_array(index); end loop; return result; end Combine; begin for digit in d'Range loop while d(digit) > 0 loop num_array(index) := digit; index := index + 1; d(digit) := d(digit) - 1; end loop; end loop; possible := Combine; if possible > 1000 then result(1) := Four_Digit(possible); index := 2; else index := 1; end if; main_loop: loop declare k : Positive := num_array'Last - 1; l : Positive := num_array'Last; begin -- Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation. loop exit when num_array(k) < num_array(k + 1); exit main_loop when k = 1; k := k - 1; end loop; -- Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l. loop exit when num_array(k) < num_array(l); l := l - 1; end loop; -- Swap a[k] with a[l]. declare temp : Natural := num_array(k); begin num_array(k) := num_array(l); num_array(l) := temp; -- Reverse the sequence from a[k + 1] up to and including the final element a[n].; for index in 1 .. (num_array'Last - k) / 2 loop temp := num_array(k + index); num_array(k + index) := num_array(num_array'Last + 1 - index); num_array(num_array'Last + 1 - index) := temp; end loop; end; possible := Combine; if possible > 1000 then result(index) := Four_Digit(possible); exit when index = count; index := index + 1; end if; end; end loop main_loop; return result; end; end Permute; pragma Pure_Function(Permute); begin declare gen : Positive_Primes.Prime_Generator := Positive_Primes.Make_Generator(9_999); begin loop Positive_Primes.Next_Prime(gen, prime); exit when prime >= 1_000; end loop; while prime /= 1 loop Is_Prime(Four_Digit(prime)) := True; Positive_Primes.Next_Prime(gen, prime); end loop; end; Prime_Loop: for num in Four_Digit(1_000) .. 9_999 loop if not Is_Prime(num) or num = 1487 then goto Next_Prime; end if; declare rotations : Array (1 .. 24) of Four_Digit; permutations : constant Permute_Array := Permute(num); count : Natural := 0; begin for permute_index in permutations'Range loop declare permutation : constant Four_Digit := permutations(permute_index); begin if Is_Prime(permutation) then if permutation < num then goto Next_Prime; end if; count := count + 1; rotations(count) := permutation; end if; end; end loop; if count >= 3 then for base in 1 .. count - 2 loop for mid in base + 1.. count - 1 loop for top in mid + 1 .. count loop if rotations(base) + rotations(top) = 2*rotations(mid) then IO.Put_Line(Four_Digit'Image(rotations(base)) & Four_Digit'Image(rotations(mid)) & Four_Digit'Image(rotations(top))); exit Prime_Loop; end if; end loop; end loop; end loop; end if; end; <<Next_Prime>> null; end loop Prime_Loop; end Solve; end Problem_49;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- with System.Storage_Pools.Subpools; with Program.Compilation_Units; with Program.Cross_Reference_Updaters; with Program.Library_Environments; with Program.Visibility; private procedure Program.Resolve_Standard (Unit : not null Program.Compilation_Units.Compilation_Unit_Access; Context : aliased in out Program.Visibility.Context; Library : in out Program.Library_Environments.Library_Environment; Subpool : not null System.Storage_Pools.Subpools.Subpool_Handle; Setter : not null Program.Cross_Reference_Updaters.Cross_Reference_Updater_Access); -- Resolve names in predefined Standard package. -- This is simplified version of resolver that creates and polulates -- name table for Standard package. It uses some implementation defined -- tricks, because Standard package can't be expressed in Ada. pragma Preelaborate (Program.Resolve_Standard);
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with GNATCOLL.Projects; with GNATCOLL.VFS; with Langkit_Support.Slocs; with Libadalang.Analysis; with Libadalang.Common; with Libadalang.Project_Provider; procedure Main is package LAL renames Libadalang.Analysis; package LALCO renames Libadalang.Common; package Slocs renames Langkit_Support.Slocs; -- Context : constant LAL.Analysis_Context := LAL.Create_Context; Context : LAL.Analysis_Context; Provider : LAL.Unit_Provider_Reference; -- If Node is an object declaration, print its text. Always continue the -- traversal. function Process_Node (Node : LAL.Ada_Node'Class) return LALCO.Visit_Status is use type LALCO.Ada_Node_Kind_Type; begin -- if Node.Kind = LALCO.Ada_Object_Decl then Put_Line ("Line" & Slocs.Line_Number'Image (Node.Sloc_Range.Start_Line) & ": " & LALCO.Ada_Node_Kind_Type'Image (Node.kind) & ": " & Node.Debug_Text); -- end if; return LALCO.Into; end Process_Node; -- Load the project file designated by the first command-line argument function Load_Project return LAL.Unit_Provider_Reference is package GPR renames GNATCOLL.Projects; package LAL_GPR renames Libadalang.Project_Provider; use type GNATCOLL.VFS.Filesystem_String; Project_Filename : constant String := Ada.Command_Line.Argument (1); Project_File : constant GNATCOLL.VFS.Virtual_File := GNATCOLL.VFS.Create (+Project_Filename); Env : GPR.Project_Environment_Access; Project : constant GPR.Project_Tree_Access := new GPR.Project_Tree; begin GPR.Initialize (Env); -- Use procedures in GNATCOLL.Projects to set scenario -- variables (Change_Environment), to set the target -- and the runtime (Set_Target_And_Runtime), etc. Project.Load (Project_File, Env); return LAL_GPR.Create_Project_Unit_Provider (Tree => Project, Project => GPR.No_Project, Env => Env); end Load_Project; begin Context := LAL.Create_Context (Unit_Provider => Load_Project); -- Try to parse all source file given as arguments for I in 2 .. Ada.Command_Line.Argument_Count loop declare Filename : constant String := Ada.Command_Line.Argument (I); Unit : constant LAL.Analysis_Unit := Context.Get_From_File (Filename); begin Put_Line ("== " & Filename & " =="); -- Report parsing errors, if any if Unit.Has_Diagnostics then for D of Unit.Diagnostics loop Put_Line (Unit.Format_GNU_Diagnostic (D)); end loop; -- Otherwise, look for object declarations else Unit.Root.Traverse (Process_Node'Access); end if; New_Line; end; end loop; end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
-- implementation unit package Ada.Containers.Binary_Trees.Simple is pragma Preelaborate; Node_Size : constant := Standard'Address_Size * 3; type Node is new Binary_Trees.Node; for Node'Size use Node_Size; procedure Insert ( Container : in out Node_Access; Length : in out Count_Type; Before : Node_Access; New_Item : not null Node_Access); procedure Remove ( Container : in out Node_Access; Length : in out Count_Type; Position : not null Node_Access); procedure Copy ( Target : out Node_Access; Length : out Count_Type; Source : Node_Access; Copy : not null access procedure ( Target : out Node_Access; Source : not null Node_Access)); -- set operations procedure Merge is new Binary_Trees.Merge (Insert => Insert, Remove => Remove); procedure Copying_Merge is new Binary_Trees.Copying_Merge (Insert => Insert); end Ada.Containers.Binary_Trees.Simple;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Ada_2012; with Bits; with BitOperations.Search.Axiom; with BitOperations.Search.Axiom.Most_Significant_Bit; package body TLSF.Block.Types with SPARK_Mode, Pure, Preelaborate is package Bits_Size is new Bits(Size_Bits); use Bits_Size; function To_Size_Bits (S : Size) return Size_Bits is Result : constant Size_Bits := Size_Bits(S); begin pragma Assert (Natural(Size_Bits'Last) = Natural(Size'Last)); pragma Assert (Natural(S) in 0 .. Natural(Size_Bits'Last)); pragma Assert (Size(Result) = S); return Result; end To_Size_Bits; function To_Address_Bits (A : Address) return Address_Bits is Result : constant Address_Bits := Address_Bits(A); begin pragma Assert (Natural(Address_Bits'Last) = Natural(Address'Last)); pragma Assert (Natural(A) in 0 .. Natural(Address_Bits'Last)); pragma Assert (Address(Result) = A); return Result; end To_Address_Bits; generic type Value_Type is range <>; type Value_Type_Mod is mod <>; function Is_Aligned_Generic(Val : Value_Type_Mod) return Boolean with Pre => Integer(Value_Type_Mod'First) = Integer(Value_Type'First) and then Integer(Value_Type_Mod'Last) = Integer(Value_Type'Last) and then Integer(Val) in 0 .. Integer(Value_Type'Last), Contract_Cases => ( (Val and Align_Mask) = 0 => Is_Aligned_Generic'Result = True, (Val and Align_Mask) /= 0 => Is_Aligned_Generic'Result = False); function Is_Aligned_Generic(Val : Value_Type_Mod) return Boolean is Result : constant Boolean := (Val and Align_Mask) = 0; begin return Result; end Is_Aligned_Generic; function Is_Aligned(Val : Size) return Boolean is function Is_Aligned_Size is new Is_Aligned_Generic(Size, Size_Bits); begin return Is_Aligned_Size(Size_Bits(Val)); end Is_Aligned; function Is_Aligned(Val : Address) return Boolean is function Is_Aligned_Addr is new Is_Aligned_Generic(Address, Address_Bits); begin return Is_Aligned_Addr(Address_Bits(Val)); end Is_Aligned; ---------------- -- Round_Size -- ---------------- generic type Value_Type is range <>; type Value_Type_Mod is mod <>; with function Is_Aligned (Val : Value_Type_Mod) return Boolean; function Round_Generic (V : Value_Type) return Value_Type with Pre => V <= Value_Type'Last - Align_Mask and then Integer(Value_Type_Mod'First) = Integer(Value_Type'First) and then Integer(Value_Type_Mod'Last) = Integer(Value_Type'Last) and then Integer(V) in 0 .. Integer(Value_Type'Last), Post => Is_Aligned(Value_Type_Mod(Round_Generic'Result)) and then (Value_Type_Mod(Round_Generic'Result) and Align_Mask) = 0; function Round_Generic (V : Value_Type) return Value_Type is pragma Assert (V <= Value_Type'Last - Align_Mask); USize : constant Value_Type_Mod := Value_Type_Mod(V); pragma Assert (USize <= Value_Type_Mod(Size'Last - Align_Mask)); Adj_Size : constant Value_Type_Mod := USize + Align_Mask; Masked_Size : constant Value_Type_Mod := Adj_Size and (not Align_Mask); pragma Assert (Natural(Value_Type_Mod'Last) = Natural(Value_Type'Last)); Result_Size : constant Value_Type := Value_Type(Masked_Size); begin pragma Assert (Is_Aligned(Masked_Size)); return Result_Size; end Round_Generic; function Round_Size_Up (S : Size) return Aligned_Size is function Is_Aligned_Val is new Is_Aligned_Generic(Size, Size_Bits); function Round is new Round_Generic(Size, Size_Bits, Is_Aligned_Val); begin return Round(S); end Round_Size_Up; function Round_Address_Up (A : Address) return Aligned_Address is function Is_Aligned_Val is new Is_Aligned_Generic(Address, Address_Bits); function Round is new Round_Generic(Address, Address_Bits, Is_Aligned_Val); begin return Round(A); end Round_Address_Up; function "+" (A: Aligned_Address; S: Aligned_Size) return Aligned_Address is Addr : constant Natural := Natural(A) + Natural(S); pragma Assert (Addr in 0 .. Natural (Address'Last)); -- TODO add lemma: -- Aligned + Aligned = Aligned -- or more common case: preservation of aligment by +,-,* operations pragma Assume (Is_Aligned(Address(Addr))); Result : constant Aligned_Address := Address(Addr); begin return Result; end "+"; function "+" (L, R : Aligned_Size) return Aligned_Size is Sz : constant Natural := Natural (L) + Natural (R); pragma Assert (Sz in 0 .. Natural (Size'Last)); pragma Assume (Is_Aligned (Size (Sz))); Result : constant Aligned_Size := Size (Sz); begin return Result; end "+"; function "-" (To, From : Aligned_Address) return Aligned_Size is Sz : constant Natural := Natural(To) - Natural(From); pragma Assert (Sz in 0.. Natural(Size'Last)); -- TODO add lemma: -- Aligned + Aligned = Aligned -- or more common case: preservation of aligment by +,-,* operations pragma Assume (Is_Aligned(Size(Sz))); Result : constant Aligned_Size := Size(Sz); begin return Result; end "-"; function Calculate_Levels_Indices (S : Size_Bits) return Level_Index is package Search_Axiom_Pkg is new Bits_Size.Search.Axiom; package MSB_Axiom is new Search_Axiom_Pkg.Most_Significant_Bit; First_Bit : constant Bits_Size.Bit_Position := Bits_Size.Most_Significant_Bit(S); Second_Level_Bits : Size_Bits; MSB_Small_Block_Size : constant Bits_Size.Bit_Position := Bits_Size.Most_Significant_Bit(Small_Block_Size) with Ghost; Result : Level_Index; begin MSB_Axiom.Result_Is_Correct(S, First_Bit); MSB_Axiom.Result_Is_Correct(Small_Block_Size, MSB_Small_Block_Size); MSB_Axiom.Order_Preservation_Value_To_Index (Value1 => S, Value2 => Small_Block_Size, Index1 => First_Bit, Index2 => FL_Index_Shift); pragma Assert (First_Bit >= FL_Index_Shift); Second_Level_Bits := Bits_Size.Extract(S, First_Bit - SL_Index_Count_Log2, First_Bit - 1); Result.First_Level := First_Level_Index (First_Bit); Result.Second_Level := Second_Level_Index (Second_Level_Bits); return Result; end Calculate_Levels_Indices; function Is_Same_Size_Class(S1, S2: Size) return Boolean is (Calculate_Levels_Indices(Size_Bits(S1)) = Calculate_Levels_Indices(Size_Bits(S2))); end TLSF.Block.Types;
{ "source": "starcoderdata", "programming_language": "ada" }
-- Auteur: -- Gérer un stock de matériel informatique. package Stocks_Materiel is CAPACITE : constant Integer := 10; -- nombre maximum de matériels dans un stock type T_Nature is (UNITE_CENTRALE, DISQUE, ECRAN, CLAVIER, IMPRIMANTE); type T_Materiel is private; type T_Stock is limited private; -- Créer un stock vide. -- -- paramètres -- Stock : le stock à créer -- -- Assure -- Nb_Materiels (Stock) = 0 -- procedure Creer (Stock : out T_Stock) with Post => Nb_Materiels (Stock) = 0; -- Obtenir le nombre de matériels dans le stock Stock. -- -- Paramètres -- Stock : le stock dont ont veut obtenir la taille -- -- Nécessite -- Vrai -- -- Assure -- Résultat >= 0 Et Résultat <= CAPACITE -- function Nb_Materiels (Stock: in T_Stock) return Integer with Post => Nb_Materiels'Result >= 0 and Nb_Materiels'Result <= CAPACITE; -- Obtenir le nombre de matériels non fonctionnel dans le stock Stock. -- -- Paramètres -- Stock : le stock dont ont veut obtenir la taille -- -- Nécessite -- Vrai -- -- Assure -- Résultat >= 0 Et Résultat <= CAPACITE -- function Nb_Defectueux (Stock: in T_Stock) return Integer with Post => Nb_Defectueux'Result >= 0 and Nb_Defectueux'Result <= CAPACITE; -- Modifie l'état d'un matériel à l'aide de son numéro de série. -- -- Paramètres -- Stock : le stock à compléter -- Numero_Serie : le numéro de série du matériel -- Est_Fonctionnel : le nouveau état du matériel -- -- Nécessite -- Nb_Materiels (Stock) > 0 -- Un matériel de numéro de serie = Numero_Serie est déja présent. -- -- Assure -- Matériel de numéro de serie = Numero_Serie à bien l'état Est_Fonctionnel procedure Mettre_A_Jour ( Stock: in out T_Stock; Numero_Serie: in Integer; Est_Fonctionnel: in Boolean ) with Pre => Nb_Materiels(Stock) > 0 and Existe(Stock, Numero_Serie); -- Supprime un matériel du stock à l'aide de son numéro de série. -- -- Paramètres -- Stock : le stock à compléter -- Numero_Serie : le numéro de série du matériel -- -- Nécessite -- Nb_Materiels (Stock) > 0 -- Un matériel de numéro de serie = Numero_Serie est déja présent. -- -- Assure -- Nb_Materiels (Stock) = Nb_Materiels (Stock)'Avant - 1; procedure Supprimer ( Stock: in out T_Stock; Numero_Serie: in Integer ) with Pre => Nb_Materiels(Stock) > 0 and Existe(Stock, Numero_Serie), Post => Nb_Materiels (Stock) = Nb_Materiels (Stock)'Old - 1; -- Enregistrer un nouveau métériel dans le stock. Il est en -- fonctionnement. Le stock ne doit pas être plein. -- -- Paramètres -- Stock : le stock à compléter -- Numero_Serie : le numéro de série du nouveau matériel -- Nature : la nature du nouveau matériel -- Annee_Achat : l'année d'achat du nouveau matériel -- -- Nécessite -- Nb_Materiels (Stock) < CAPACITE -- -- Assure -- Nouveau matériel ajouté -- Nb_Materiels (Stock) = Nb_Materiels (Stock)'Avant + 1 procedure Enregistrer ( Stock : in out T_Stock; Numero_Serie : in Integer; Nature : in T_Nature; Annee_Achat : in Integer ) with Pre => Nb_Materiels (Stock) < CAPACITE, Post => Nb_Materiels (Stock) = Nb_Materiels (Stock)'Old + 1; -- Existence d'un matériel avec le numéro de serie donné. -- -- Paramètres -- Stock : le stock à compléter -- Numero_Serie : le numéro de série du matériel -- -- Nécessite -- Vrai -- -- Assure -- Vrai function Existe (Stock: in T_Stock; Numero_Serie: in Integer) return Boolean; -- Afficher le stock au terminal. -- -- Paramètres -- Stock : le stock à compléter -- -- Nécessite -- Vrai -- -- Assure -- Vrai procedure Afficher (Stock: in T_Stock); -- Supprimer tous les matériels qui ne sont pas en état de fonctionnement. -- -- Paramètres -- Stock : le stock à compléter -- -- Nécessite -- Vrai -- -- Assure -- Nb_Defectueux(Stock) = 0 et Nb_Materials(Stock) = Nb_Materials(Stock)'Avant - Nb_Defectueux(Stock)'Avant procedure Nettoyer (Stock: in out T_Stock) with Post => Nb_Defectueux(Stock) = 0 and Nb_Materiels(Stock) = Nb_Materiels(Stock)'Old - Nb_Defectueux(Stock)'Old; private type T_Materiel is record Numero_Serie: Integer; Nature: T_Nature; Annee_Achat: Integer; Est_Fonctionnel: Boolean; end record; type T_Materiels is array(1..CAPACITE) of T_Materiel; type T_Stock is record Materiels: T_Materiels; Nombre: Integer; end record; end Stocks_Materiel;
{ "source": "starcoderdata", "programming_language": "ada" }
with Yaml.Lexer.Buffering_Test; with Yaml.Lexer.Tokenization_Test; with Yaml.Parser.Event_Test; package body Yaml.Loading_Tests.Suite is Result : aliased AUnit.Test_Suites.Test_Suite; Buffering_TC : aliased Lexer.Buffering_Test.TC; Tokenization_TC : aliased Lexer.Tokenization_Test.TC; Event_TC : aliased Parser.Event_Test.TC; function Suite return AUnit.Test_Suites.Access_Test_Suite is begin AUnit.Test_Suites.Add_Test (Result'Access, Buffering_TC'Access); AUnit.Test_Suites.Add_Test (Result'Access, Tokenization_TC'Access); AUnit.Test_Suites.Add_Test (Result'Access, Event_TC'Access); return Result'Access; end Suite; end Yaml.Loading_Tests.Suite;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with EL.Contexts.Default; -- == EL TLS Context == -- The <tt>TLS_Context</tt> type defines an expression context that associates itself to -- a per-thread context information. By declaring a variable with this type, the expression -- context is associated with the current thread and it can be retrieved at any time by using the -- <tt>Current</tt> function. As soon as the variable is finalized, the current thread context -- is updated. -- -- The expression context may be declared as follows: -- -- Context : EL.Contexts.TLS.TLS_Context; -- -- And at any time, a function or procedure that needs to evaluate an expression can use it: -- -- Expr : EL.Expressions.Expression; -- ... -- Value : Util.Beans.Objects.Object := Expr.Get_Value (EL.Contexts.TLS.Current.all); -- package EL.Contexts.TLS is -- ------------------------------ -- TLS Context -- ------------------------------ -- Context information for expression evaluation. type TLS_Context is new EL.Contexts.Default.Default_Context with private; -- Get the current EL context associated with the current thread. function Current return EL.Contexts.ELContext_Access; private type TLS_Context is new EL.Contexts.Default.Default_Context with record Previous : EL.Contexts.ELContext_Access; end record; -- Initialize and setup a new per-thread EL context. overriding procedure Initialize (Obj : in out TLS_Context); -- Restore the previouse per-thread EL context. overriding procedure Finalize (Obj : in out TLS_Context); end EL.Contexts.TLS;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Strings, Ada.Strings.Bounded; with AUnit.Test_Suites; package BinToAsc_Suite is package Test_Vector_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length(Max => 16); use all type Test_Vector_Strings.Bounded_String; function TBS (Source : in String; Drop : in Ada.Strings.Truncation := Ada.Strings.Error) return Test_Vector_Strings.Bounded_String renames Test_Vector_Strings.To_Bounded_String; subtype Test_Vector_String is Test_Vector_Strings.Bounded_String; type Test_Vector is record Unencoded : Test_Vector_String; Encoded : Test_Vector_String; end record; type Test_Vector_Array is array (Natural range <>) of Test_Vector; function Suite return AUnit.Test_Suites.Access_Test_Suite; end BinToAsc_Suite;
{ "source": "starcoderdata", "programming_language": "ada" }
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with Ada.Real_Time; use Ada.Real_Time; with Ada.Text_IO; use Ada.Text_IO; with STM32GD.Board; use STM32GD.Board; with STM32GD.GPIO; use STM32GD.GPIO; with STM32GD.GPIO.Pin; with STM32GD.EXTI; with STM32_SVD.AFIO; with STM32_SVD.NVIC; with STM32_SVD.RCC; with Peripherals; use Peripherals; procedure Main is Next_Release : Time := Clock; Period : constant Time_Span := Milliseconds (1000); -- arbitrary begin Init; STM32_SVD.NVIC.NVIC_Periph.ISER0 := 2#00000000_10011000_00000000_00000000#; Put_Line ("Init"); USB_Re_Enumerate; USB.Init; LED2.Set; Put_Line ("Starting"); loop LED2.Toggle; Next_Release := Next_Release + Period; delay until Next_Release; end loop; end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with GNAT.Decode_UTF8_String; with Config; package body UTF8_Utils is Locale_To_UTF_8 : Iconv_T; UTF_8_To_Locale : Iconv_T; Latin1_To_UTF_8 : Iconv_T; UTF_8_To_UTF_32 : Iconv_T; Is_Opened : Boolean := False; procedure Open; -- Initialize internal data if not yet initialized ---------- -- Open -- ---------- procedure Open is begin if not Is_Opened then Locale_To_UTF_8 := Iconv_Open (To_Code => UTF8, From_Code => Config.Default_Charset); UTF_8_To_Locale := Iconv_Open (From_Code => UTF8, To_Code => Config.Default_Charset); Latin1_To_UTF_8 := Iconv_Open (From_Code => ISO_8859_1, To_Code => UTF8); UTF_8_To_UTF_32 := Iconv_Open (From_Code => UTF8, To_Code => UTF32); Is_Opened := True; end if; end Open; --------------------- -- Unknown_To_UTF8 -- --------------------- procedure Unknown_To_UTF8 (Input : String; Output : out GNAT.Strings.String_Access; Success : out Boolean) is begin Open; Output := null; Success := True; -- First check if the string is already UTF-8 if Validate (UTF_8_To_UTF_32, Input) then -- The string is UTF-8, nothing to do return; end if; -- The string is not valid UTF-8, assume it is encoded using the locale. if Validate (Locale_To_UTF_8, Input) then Output := new String'(Iconv (Locale_To_UTF_8, Input)); else Success := False; end if; end Unknown_To_UTF8; function Unknown_To_UTF8 (Input : String; Success : access Boolean) return UTF8_String is Output : GNAT.Strings.String_Access; begin Unknown_To_UTF8 (Input, Output, Success.all); if Success.all then if Output = null then return Input; else declare S : constant String := Output.all; begin Free (Output); return S; end; end if; else return ""; end if; end Unknown_To_UTF8; function Unknown_To_UTF8 (Input : String) return UTF8_String is Success : aliased Boolean; S : constant String := Unknown_To_UTF8 (Input, Success'Access); begin if Success then return S; else return "<could not convert to UTF8>"; end if; end Unknown_To_UTF8; -------------------- -- UTF8_To_Locale -- -------------------- function UTF8_To_Locale (Input : UTF8_String) return String is begin Open; return Iconv (UTF_8_To_Locale, Input); end UTF8_To_Locale; -------------------- -- Locale_To_UTF8 -- -------------------- function Locale_To_UTF8 (Input : String) return UTF8_String is begin Open; return Iconv (Locale_To_UTF_8, Input); end Locale_To_UTF8; ------------------- -- UTF8_Get_Char -- ------------------- function UTF8_Get_Char (Input : UTF8_String) return Wide_Wide_Character is Next : Positive := Input'First; Result : Wide_Wide_Character; begin GNAT.Decode_UTF8_String.Decode_Wide_Wide_Character (Input, Next, Result); return Result; end UTF8_Get_Char; -------------------- -- UTF8_Next_Char -- -------------------- function UTF8_Next_Char (Str : UTF8_String; Index : Positive) return Positive is Byte : constant Character := Str (Index); begin case Byte is when Character'Val (16#C0#) .. Character'Val (16#DF#) => return Index + 2; when Character'Val (16#E0#) .. Character'Val (16#EF#) => return Index + 3; when Character'Val (16#F0#) .. Character'Val (16#F7#) => return Index + 4; when Character'Val (16#F8#) .. Character'Val (16#FB#) => return Index + 5; when Character'Val (16#FC#) .. Character'Val (16#FD#) => return Index + 6; when others => return Index + 1; end case; end UTF8_Next_Char; -------------------- -- UTF8_Next_Char -- -------------------- function UTF8_Next_Char (Str : UTF8_Unbounded_String; Index : Positive) return Positive is Byte : constant Character := Element (Str, Index); begin case Byte is when Character'Val (16#C0#) .. Character'Val (16#DF#) => return Index + 2; when Character'Val (16#E0#) .. Character'Val (16#EF#) => return Index + 3; when Character'Val (16#F0#) .. Character'Val (16#F7#) => return Index + 4; when Character'Val (16#F8#) .. Character'Val (16#FB#) => return Index + 5; when Character'Val (16#FC#) .. Character'Val (16#FD#) => return Index + 6; when others => return Index + 1; end case; end UTF8_Next_Char; -------------------- -- UTF8_Prev_Char -- -------------------- function UTF8_Prev_Char (Str : UTF8_String; Index : Natural) return Natural is Result : Integer := Index - 1; begin if Index not in Str'Range then return Index; end if; while Result in Str'Range and then Str (Result) in Character'Val (16#80#) .. Character'Val (16#BF#) loop Result := Result - 1; end loop; return Result; end UTF8_Prev_Char; --------------------- -- Latin_1_To_UTF8 -- --------------------- function Latin_1_To_UTF8 (Input : String) return UTF8_String is begin Open; return Iconv (Latin1_To_UTF_8, Input); end Latin_1_To_UTF8; -------------- -- Validate -- -------------- function Validate (Object : Iconv_T; Input : Byte_Sequence) return Boolean is Output : Byte_Sequence (1 .. 4096); Input_Index : Positive := Input'First; Output_Index : Positive := Output'First; Result : Iconv_Result; begin if Input = "" then return True; end if; loop Iconv (Object, Input, Input_Index, Output, Output_Index, Result); case Result is when Invalid_Multibyte_Sequence | Incomplete_Multibyte_Sequence => return False; when Success => return True; when Full_Buffer => -- Continue convertion by rewriting output buffer Output_Index := Output'First; end case; end loop; end Validate; -------------------- -- Validate_UTF_8 -- -------------------- function Validate_UTF_8 (Input : Byte_Sequence) return Boolean is begin Open; return Validate (UTF_8_To_UTF_32, Input); end Validate_UTF_8; --------------------- -- Column_To_Index -- --------------------- function Column_To_Index (Buffer : UTF8_String; Column : Character_Offset_Type) return Natural is Result : Positive := Buffer'First; begin if Column <= 0 then return 0; end if; for J in 2 .. Column loop Result := UTF8_Next_Char (Buffer, Result); end loop; return Result; end Column_To_Index; ----------------- -- UTF8_Length -- ----------------- function UTF8_Length (Item : UTF8_String) return Natural is Result : Natural := 0; Index : Positive := Item'First; begin while Index <= Item'Last loop Result := Result + 1; Index := UTF8_Next_Char (Item, Index); end loop; return Result; end UTF8_Length; end UTF8_Utils;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with AcronymList; use AcronymList; with RASCAL.WimpTask; use RASCAL.WimpTask; with RASCAL.Utility; use RASCAL.Utility; with RASCAL.Variable; use RASCAL.Variable; with RASCAL.OS; use RASCAL.OS; package Main is -- Main_Task : ToolBox_Task_Class; main_objectid : Object_ID := -1; main_winid : Wimp_Handle_Type := -1; Data_Menu_Entries : natural := 0; x_pos : Integer := -1; y_pos : Integer := -1; -- Constants Not_Found_Message : UString; app_name : constant String := "Meaning"; Choices_Write : constant String := "<Choices$Write>." & app_name; Choices_Read : constant String := "Choices:" & app_name & ".Choices"; scrapdir : constant String := "<Wimp$ScrapDir>." & app_name; -- Acronym_List : AcronymList.ListPointer := new AcronymList.List; Untitled_String : Unbounded_String; -- procedure Main; procedure Discard_Acronyms; procedure Read_Acronyms; procedure Report_Error (Token : in String; Info : in String); -- end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
& ", Free Software Foundation, Inc."); end Output_Version; ------------------- -- GNATCmd_Usage -- ------------------- procedure GNATCmd_Usage is begin Output_Version; New_Line; Put_Line ("To list Ada build switches use " & Ada_Help_Switch); New_Line; Put_Line ("List of available commands"); New_Line; for C in Command_List'Range loop Put ("gnat "); Put (To_Lower (Command_List (C).Cname.all)); Set_Col (25); Put (Program_Name (Command_List (C).Unixcmd.all, "gnat").all); declare Sws : Argument_List_Access renames Command_List (C).Unixsws; begin if Sws /= null then for J in Sws'Range loop Put (' '); Put (Sws (J).all); end loop; end if; end; New_Line; end loop; New_Line; end GNATCmd_Usage; procedure Check_Version_And_Help is new Check_Version_And_Help_G (GNATCmd_Usage); -- Start of processing for GNATCmd begin -- All output from GNATCmd is debugging or error output: send to stderr Set_Standard_Error; -- Initializations Last_Switches.Init; Last_Switches.Set_Last (0); First_Switches.Init; First_Switches.Set_Last (0); -- Put the command line in environment variable GNAT_DRIVER_COMMAND_LINE, -- so that the spawned tool may know the way the GNAT driver was invoked. Name_Len := 0; Add_Str_To_Name_Buffer (Command_Name); for J in 1 .. Argument_Count loop Add_Char_To_Name_Buffer (' '); Add_Str_To_Name_Buffer (Argument (J)); end loop; Setenv ("GNAT_DRIVER_COMMAND_LINE", Name_Buffer (1 .. Name_Len)); -- Add the directory where the GNAT driver is invoked in front of the path, -- if the GNAT driver is invoked with directory information. declare Command : constant String := Command_Name; begin for Index in reverse Command'Range loop if Command (Index) = Directory_Separator then declare Absolute_Dir : constant String := Normalize_Pathname (Command (Command'First .. Index)); PATH : constant String := Absolute_Dir & Path_Separator & Getenv ("PATH").all; begin Setenv ("PATH", PATH); end; exit; end if; end loop; end; -- Scan the command line -- First, scan to detect --version and/or --help Check_Version_And_Help ("GNAT", "1996"); begin loop if Command_Arg <= Argument_Count and then Argument (Command_Arg) = "-v" then Verbose_Mode := True; Command_Arg := Command_Arg + 1; elsif Command_Arg <= Argument_Count and then Argument (Command_Arg) = "-dn" then Keep_Temporary_Files := True; Command_Arg := Command_Arg + 1; elsif Command_Arg <= Argument_Count and then Argument (Command_Arg) = Ada_Help_Switch then Usage; Exit_Program (E_Success); else exit; end if; end loop; -- If there is no command, just output the usage if Command_Arg > Argument_Count then GNATCmd_Usage; -- Add the following so that output is consistent with or without the -- --help flag. Write_Eol; Write_Line ("Report bugs to <EMAIL>"); return; end if; The_Command := Real_Command_Type'Value (Argument (Command_Arg)); exception when Constraint_Error => -- Check if it is an alternate command declare Alternate : Alternate_Command; begin Alternate := Alternate_Command'Value (Argument (Command_Arg)); The_Command := Corresponding_To (Alternate); exception when Constraint_Error => GNATCmd_Usage; Fail ("unknown command: " & Argument (Command_Arg)); end; end; -- Get the arguments from the command line and from the eventual -- argument file(s) specified on the command line. for Arg in Command_Arg + 1 .. Argument_Count loop declare The_Arg : constant String := Argument (Arg); begin -- Check if an argument file is specified if The_Arg'Length > 0 and then The_Arg (The_Arg'First) = '@' then declare Arg_File : Ada.Text_IO.File_Type; Line : String (1 .. 256); Last : Natural; begin -- Open the file and fail if the file cannot be found begin Open (Arg_File, In_File, The_Arg (The_Arg'First + 1 .. The_Arg'Last)); exception when others => Put (Standard_Error, "Cannot open argument file """); Put (Standard_Error, The_Arg (The_Arg'First + 1 .. The_Arg'Last)); Put_Line (Standard_Error, """"); raise Error_Exit; end; -- Read line by line and put the content of each non- -- empty line in the Last_Switches table. while not End_Of_File (Arg_File) loop Get_Line (Arg_File, Line, Last); if Last /= 0 then Last_Switches.Increment_Last; Last_Switches.Table (Last_Switches.Last) := new String'(Line (1 .. Last)); end if; end loop; Close (Arg_File); end; elsif The_Arg'Length > 0 then -- It is not an argument file; just put the argument in -- the Last_Switches table. Last_Switches.Increment_Last; Last_Switches.Table (Last_Switches.Last) := new String'(The_Arg); end if; end; end loop; declare Program : String_Access; Exec_Path : String_Access; Get_Target : Boolean := False; begin if The_Command = Stack then -- Never call gnatstack with a prefix Program := new String'(Command_List (The_Command).Unixcmd.all); else Program := Program_Name (Command_List (The_Command).Unixcmd.all, "gnat"); -- If we want to invoke gnatmake/gnatclean with -P, then check if -- gprbuild/gprclean is available; if it is, use gprbuild/gprclean -- instead of gnatmake/gnatclean. -- Ditto for gnatname -> gprname and gnatls -> gprls. if The_Command = Make or else The_Command = Compile or else The_Command = Bind or else The_Command = Link or else The_Command = Clean or else The_Command = Name or else The_Command = List then declare Switch : String_Access; Call_GPR_Tool : Boolean := False; begin for J in 1 .. Last_Switches.Last loop Switch := Last_Switches.Table (J); if Switch'Length >= 2 and then Switch (Switch'First .. Switch'First + 1) = "-P" then Call_GPR_Tool := True; exit; end if; end loop; if Call_GPR_Tool then case The_Command is when Bind | Compile | Link | Make => if Locate_Exec_On_Path (Gprbuild) /= null then Program := new String'(Gprbuild); Get_Target := True; if The_Command = Bind then First_Switches.Append (new String'("-b")); elsif The_Command = Link then First_Switches.Append (new String'("-l")); end if; elsif The_Command = Bind then Fail ("'gnat bind -P' is no longer supported;" & " use 'gprbuild -b' instead."); elsif The_Command = Link then Fail ("'gnat Link -P' is no longer supported;" & " use 'gprbuild -l' instead."); end if; when Clean => if Locate_Exec_On_Path (Gprclean) /= null then Program := new String'(Gprclean); Get_Target := True; end if; when Name => if Locate_Exec_On_Path (Gprname) /= null then Program := new String'(Gprname); Get_Target := True; end if; when List => if Locate_Exec_On_Path (Gprls) /= null then Program := new String'(Gprls); Get_Target := True; end if; when others => null; end case; if Get_Target then Find_Program_Name; if Name_Len > 5 then First_Switches.Append (new String' ("--target=" & Name_Buffer (1 .. Name_Len - 5))); end if; end if; end if; end; end if; end if; -- Locate the executable for the command Exec_Path := Locate_Exec_On_Path (Program.all); if Exec_Path = null then Put_Line (Standard_Error, "could not locate " & Program.all); raise Error_Exit; end if; -- If there are switches for the executable, put them as first switches if Command_List (The_Command).Unixsws /= null then for J in Command_List (The_Command).Unixsws'Range loop First_Switches.Increment_Last; First_Switches.Table (First_Switches.Last) := Command_List (The_Command).Unixsws (J); end loop; end if; -- For FIND and XREF, look for switch -P. If it is specified, then -- report an error indicating that the command is no longer supporting -- project files. if The_Command = Find or else The_Command = Xref then declare Argv : String_Access; begin for Arg_Num in 1 .. Last_Switches.Last loop Argv := Last_Switches.Table (Arg_Num); if Argv'Length >= 2 and then Argv (Argv'First .. Argv'First + 1) = "-P" then if The_Command = Find then Fail ("'gnat find -P' is no longer supported;"); else Fail ("'gnat xref -P' is no longer supported;"); end if; end if; end loop; end; end if; -- Gather all the arguments and invoke the executable declare The_Args : Argument_List (1 .. First_Switches.Last + Last_Switches.Last); Arg_Num : Natural := 0; begin for J in 1 .. First_Switches.Last loop Arg_Num := Arg_Num + 1; The_Args (Arg_Num) := First_Switches.Table (J); end loop; for J in 1 .. Last_Switches.Last loop Arg_Num := Arg_Num + 1; The_Args (Arg_Num) := Last_Switches.Table (J); end loop; if Verbose_Mode then Put (Exec_Path.all); for Arg in The_Args'Range loop Put (" " & The_Args (Arg).all); end loop; New_Line; end if; My_Exit_Status := Exit_Status (Spawn (Exec_Path.all, The_Args)); Set_Exit_Status (My_Exit_Status); end; end; exception when Error_Exit => Set_Exit_Status (Failure); end GNATCmd;
{ "source": "starcoderdata", "programming_language": "ada" }
-- Universitat Politecnica de Valencia -- -- July, 2020 - Version 1 -- -- February, 2021 - Version 2 -- -- -- -- This is free software in the ample sense: -- -- you can use it freely, provided you preserve -- -- this comment at the header of source files -- -- and you clearly indicate the changes made to -- -- the original file, if any. -- ------------------------------------------------------------ with Gnoga.Gui.Base; with Gnoga.Gui.Element.Common; with Gnoga.Gui.Element.Canvas.Context_2D; with Gnoga.Gui.View.Grid; package BB.GUI.View is -- Size of canvas to display animation and graph Canvas_X_Size : constant := 500; Canvas_Y_Size : constant := 400; type Default_View_Type is new Gnoga.Gui.View.Grid.Grid_View_Type with record BB_Anim_View : Gnoga.Gui.View.View_Type; BB_Anim_Canvas : Gnoga.Gui.Element.Canvas.Canvas_Type; BB_Animation : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type; BB_Graph_View : Gnoga.Gui.View.View_Type; BB_Graph_Canvas : Gnoga.Gui.Element.Canvas.Canvas_Type; BB_Pos_Graph : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type; Quit_Button : Gnoga.Gui.Element.Common.Button_Type; Pause_Button : Gnoga.Gui.Element.Common.Button_Type; end record; type Default_View_Access is access all Default_View_Type; type Pointer_to_Default_View_Class is access all Default_View_Type'Class; procedure Create (View : in out Default_View_Type; Parent : in out Gnoga.Gui.Base.Base_Type'Class; ID : in String := ""); end BB.GUI.View;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Pipes is -- ----------------------- -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ----------------------- procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String) is begin Util.Processes.Set_Shell (Stream.Proc, Shell); end Set_Shell; -- ----------------------- -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String) is begin Util.Processes.Set_Input_Stream (Stream.Proc, File); end Set_Input_Stream; -- ----------------------- -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Output_Stream (Stream.Proc, File, Append); end Set_Output_Stream; -- ----------------------- -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. -- ----------------------- procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False) is begin Util.Processes.Set_Error_Stream (Stream.Proc, File, Append); end Set_Error_Stream; -- ----------------------- -- Closes the given file descriptor in the child process before executing the command. -- ----------------------- procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type) is begin Util.Processes.Add_Close (Stream.Proc, Fd); end Add_Close; -- ----------------------- -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. -- ----------------------- procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String) is begin Util.Processes.Set_Working_Directory (Stream.Proc, Path); end Set_Working_Directory; -- ----------------------- -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. -- ----------------------- procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ) is begin Util.Processes.Spawn (Stream.Proc, Command, Mode); end Open; -- ----------------------- -- Close the pipe and wait for the external process to terminate. -- ----------------------- overriding procedure Close (Stream : in out Pipe_Stream) is begin Util.Processes.Wait (Stream.Proc); end Close; -- ----------------------- -- Get the process exit status. -- ----------------------- function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is begin return Util.Processes.Get_Exit_Status (Stream.Proc); end Get_Exit_Status; -- ----------------------- -- Returns True if the process is running. -- ----------------------- function Is_Running (Stream : in Pipe_Stream) return Boolean is begin return Util.Processes.Is_Running (Stream.Proc); end Is_Running; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc); begin if Output = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Output.Write (Buffer); end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc); begin if Input = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Input.Read (Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Pipe_Stream) is begin null; end Finalize; end Util.Streams.Pipes;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Interfaces; with ByteBauble; use ByteBauble; procedure api_test is -- Perform API operations. subtype uint16 is Interfaces.Unsigned_16; subtype uint32 is Interfaces.Unsigned_32; subtype uint64 is Interfaces.Unsigned_64; --subtype U128 is Interfaces.Unsigned_128; testValue16: uint16 := 16#0102#; testValue32: uint32 := 16#01010304#; --testValue64: uint64 := 16#01020304080A0B0C#; resVal: Integer; begin -- Default global: should return LE result. resVal := Integer(toGlobal(testValue32, BB_BE)); -- Assume it's BE. Put("[1] Result: "); Ada.Integer_Text_IO.Put(resVal, Base => 16); Put_Line("."); -- Set new global (BE), should return BE result. end api_test;
{ "source": "starcoderdata", "programming_language": "ada" }
--------------------------------------------------------------------------- package Ada.Environment_Variables is pragma Preelaborate (Environment_Variables); function Value (Name : in String) return String; function Value (Name : in String; Default : in String) return String; function Exists (Name : in String) return Boolean; procedure Set (Name : in String; Value : in String); procedure Clear (Name : in String); procedure Clear; procedure Iterate (Process : not null access procedure (Name : in String; Value : in String)); end Ada.Environment_Variables;
{ "source": "starcoderdata", "programming_language": "ada" }
-- ----------------------------------------------------------------- -- -- **************************************************************** -- -- This is an Ada binding to SDL ( Simple DirectMedia Layer from -- -- Sam Lantinga - www.libsld.org ) -- -- **************************************************************** -- -- In order to help the Ada programmer, the comments in this file -- -- are, in great extent, a direct copy of the original text in the -- -- SDL header files. -- -- **************************************************************** -- with System; with Interfaces.C.Strings; with Interfaces.C.Pointers; with Ada.Unchecked_Conversion; with Ada.Strings.Unbounded; with SDL.Types; use SDL.Types; with SDL.Mutex; with SDL.RWops; use type Interfaces.C.int; package SDL.Video is package CS renames Interfaces.C.Strings; package US renames Ada.Strings.Unbounded; -- Transparency definitions: These define -- alpha as the opacity of a surface. ALPHA_OPAQUE : constant := 255; ALPHA_TRANSPARENT : constant := 0; -- Useful data types type Rect is record x, y : Sint16; w, h : Uint16; end record; pragma Convention (C, Rect); type Rect_ptr is access all Rect; pragma Convention (C, Rect_ptr); type Rect_ptr_ptr is access all Rect_ptr; pragma Convention (C, Rect_ptr_ptr); -- type Rects_Array is array (Natural range <>) of aliased Rect; type Rects_Array is array (C.unsigned range <>) of aliased Rect; type Rects_Array_Access is access all Rects_Array; type Color is record r, g, b, unused : Uint8; end record; pragma Convention (C, Color); type Color_ptr is access all Color; pragma Convention (C, Color_ptr); Null_Color : Color := (0, 0, 0, 123); type Colors_Array is array (C.size_t range <>) of aliased Color; package Color_PtrOps is new C.Pointers ( Index => C.size_t, Element => Color, Element_Array => Colors_Array, Default_Terminator => Null_Color); -- You must do a "use Color_PtrOps" -- in your code type Palette is record ncolors : C.int; colors : Color_ptr; end record; pragma Convention (C, Palette); type Palette_ptr is access Palette; pragma Convention (C, Palette_ptr); -- Everything in the pixel format structure -- is read-only. In Ada this can be controled -- using "access constant". type PixelFormat is record palette : Palette_ptr; BitsPerPixel, BytesPerPixel, Rloss, Gloss, Bloss, Aloss, Rshift, Gshift, Bshift, Ashift : Uint8; Rmask, Gmask, Bmask, Amask : Uint32; -- RGB color key information colorkey : Uint32; -- Alpha value information (per-surface alpha) alpha : Uint8; end record; pragma Convention (C, PixelFormat); type PixelFormat_ptr is access constant PixelFormat; pragma Convention (C, PixelFormat_ptr); type private_hwdata_ptr is new System.Address; type BlitMap_ptr is new System.Address; type Surface_Flags is mod 2 ** 32; for Surface_Flags'Size use 32; -- This structure should be treated as read-only type Surface is record flags : Surface_Flags; -- Read-only format : PixelFormat_ptr; -- Read-only w, h : C.int; -- Read-only pitch : Uint16; -- Read-only pixels : System.Address; -- Read-write offset : C.int; -- Private -- Hardware-specific surface info hwdata : private_hwdata_ptr; -- Clipping information clip_rect : Rect; -- Read-only unused1 : Uint32; -- For binary compatibility -- Allow recursive locks locked : Uint32; -- Private -- Info for fast blit mapping to other surfaces map : BlitMap_ptr; -- Private -- Format version, bumped at every change to -- invalidate blit maps. format_version : C.unsigned; -- Private -- Reference count -- used when freeing surface refcount : C.int; -- Read-mostly end record; pragma Convention (C, Surface); type Surface_ptr is access all Surface; pragma Convention (C, Surface_ptr); null_Surface_ptr : constant Surface_ptr := null; -- These are the currently supported flags for -- the SDL_surface. -- ---------------------------------------------- -- Available for CreateRGBSurface or SetVideoMode. -- Surface is in system memory SWSURFACE : constant Surface_Flags := 16#00000000#; -- Surface is in video memory HWSURFACE : constant Surface_Flags := 16#00000001#; -- Use asynchronous blits if possible ASYNCBLIT : constant Surface_Flags := 16#00000004#; -- ---------------------------------------------- -- Available for SetVideoMode -- Allow any video depth/pixel-format ANYFORMAT : constant Surface_Flags := 16#10000000#; -- Surface has exclusive palette HWPALETTE : constant Surface_Flags := 16#20000000#; -- Set up double-buffered video mode DOUBLEBUF : constant Surface_Flags := 16#40000000#; -- Surface is a full screen display FULLSCREEN : constant Surface_Flags := 16#80000000#; -- Create an OpenGL rendering context OPENGL : constant Surface_Flags := 16#00000002#; -- Create an OpenGL rendering context and use if -- for blitting OPENGLBLIT : constant Surface_Flags := 16#0000000A#; -- This video mode may be resized RESIZABLE : constant Surface_Flags := 16#00000010#; -- No window caption or edge frame NOFRAME : constant Surface_Flags := 16#00000020#; -- ----------------------------------------------- -- Use internally (read-only -- Blit uses hardware acceleration HWACCEL : constant Surface_Flags := 16#00000100#; -- Blit uses a source color key SRCCOLORKEY : constant Surface_Flags := 16#00001000#; -- Private flag RLEACCELOK : constant Surface_Flags := 16#00002000#; -- Surface is RLE encoded RLEACCEL : constant Surface_Flags := 16#00004000#; -- Blit uses source alpha blending SRCALPHA : constant Surface_Flags := 16#00010000#; -- Surface uses preallocated memory PREALLOC : constant Surface_Flags := 16#01000000#; -- Evaluates to true if the surface needs to be locked -- before access. function MUSTLOCK (surface : Surface_ptr) return Boolean; pragma Inline (MUSTLOCK); -- Useful for determining the video hardware capabilities type VideoInfo is record hw_available : bits1; -- Flag: Can you create hardware surfaces? wm_available : bits1; -- Flag: Can you talk to a window manager? UnusedBits1 : bits6; UnusedBits2 : bits1; blit_hw : bits1; -- Flag: Accelerated blits HW --> HW blit_hw_CC : bits1; -- Flag: Accelerated blits with Colorkey blit_hw_A : bits1; -- Flag: Accelerated blits with Alpha blit_sw : bits1; -- Flag: Accelerated blits SW --> HW blit_sw_CC : bits1; -- Flag: Accelerated blits with Colorkey blit_sw_A : bits1; -- Flag: Accelerated blits with Alpha blit_fill : bits1; -- Flag: Accelerated color fill UnusedBits3 : bits16; video_mem : Uint32; -- The total amount of video memory (in K) -- Value: The format of the video surface vfmt : PixelFormat_ptr; end record; for VideoInfo use record hw_available at 0 range 0 .. 0; wm_available at 0 range 1 .. 1; UnusedBits1 at 0 range 2 .. 7; UnusedBits2 at 1 range 0 .. 0; blit_hw at 1 range 1 .. 1; blit_hw_CC at 1 range 2 .. 2; blit_hw_A at 1 range 3 .. 3; blit_sw at 1 range 4 .. 4; blit_sw_CC at 1 range 5 .. 5; blit_sw_A at 1 range 6 .. 6; blit_fill at 1 range 7 .. 7; UnusedBits3 at 2 range 0 .. 15; video_mem at 4 range 0 .. 31; vfmt at 8 range 0 .. 31; end record; pragma Convention (C, VideoInfo); type VideoInfo_ptr is access all VideoInfo; pragma Convention (C, VideoInfo_ptr); type VideoInfo_ConstPtr is access constant VideoInfo; pragma Convention (C, VideoInfo_ConstPtr); -- The most common video ovelay formats. -- For an explanation of this pixel formats, see: -- http://www.webartz.com/fourcc/indexyuv.htm -- For information on the relationship between color spaces, see -- http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html -- Planar mode: Y + V + U (3 planes) YV12_OVERLAY : constant := 16#32315659#; -- Planar mode: Y + U + V (3 planes) IYUV_OVERLAY : constant := 16#56555949#; -- Packed mode: Y0 + U0 + Y1 + V0 (1 plane) YUY2_OVERLAY : constant := 16#32595559#; -- Packed mode: U0 + Y0 + V0 + Y1 (1 plane) UYVY_OVERLAY : constant := 16#59565955#; -- Packed mode: Y0 + V0 + Y1 + U0 (1 plane) YVYU_OVERLAY : constant := 16#55595659#; type private_yuvhwfuncs_ptr is new System.Address; type private_yuvhwdata_ptr is new System.Address; -- The YUV hardware video overlay type Overlay is record format : Uint32; -- Read-only h, w : C.int; -- Read-only planes : C.int; -- Read-only pitches : Uint16_ptr; -- Read-only pixels : Uint8_ptr_ptr; -- Read-write -- Hardware-specific surface info hwfuncs : private_yuvhwfuncs_ptr; hwdata : private_yuvhwdata_ptr; -- Special flags hw_overlay : bits1; UnusedBits : bits31; end record; for Overlay use record format at 0 range 0 .. 31; h at 4 range 0 .. 31; w at 8 range 0 .. 31; planes at 12 range 0 .. 31; pitches at 16 range 0 .. 31; pixels at 20 range 0 .. 31; hwfuncs at 24 range 0 .. 31; hwdata at 28 range 0 .. 31; hw_overlay at 32 range 0 .. 0; UnusedBits at 32 range 1 .. 31; end record; pragma Convention (C, Overlay); type Overlay_ptr is access all Overlay; pragma Convention (C, Overlay_ptr); type GLattr is new C.int; GL_RED_SIZE : constant GLattr := 0; GL_GREEN_SIZE : constant GLattr := 1; GL_BLUE_SIZE : constant GLattr := 2; GL_ALPHA_SIZE : constant GLattr := 3; GL_BUFFER_SIZE : constant GLattr := 4; GL_DOUBLEBUFFER : constant GLattr := 5; GL_DEPTH_SIZE : constant GLattr := 6; GL_STENCIL_SIZE : constant GLattr := 7; GL_ACCUM_RED_SIZE : constant GLattr := 8; GL_ACCUM_GREEN_SIZE : constant GLattr := 9; GL_ACCUM_BLUE_SIZE : constant GLattr := 10; GL_ACCUM_ALPHA_SIZE : constant GLattr := 11; LOGPAL : constant := 16#01#; PHYSPAL : constant := 16#02#; --------------------------- -- Function prototypes -- --------------------------- -- These functions are used internally, and should -- not be used unless you have a specific need to specify -- the video driver you want to use. -- -- Binding note: I will not make this functions private -- because I wish to make them available just like the -- original C interface. -- -- VideoInit initializes the video subsystem -- -- sets up a connection to the window manager, etc, and -- determines the current video mode and pixel format, -- but does not initialize a window or graphics mode. -- Note that event handling is activated by this routine. -- -- If you use both sound and video in you application, you -- need to call Init before opening the sound device, -- otherwise under Win32 DirectX, you won't be able to set -- the full-screen display modes. function VideoInit ( namebuf : C.Strings.chars_ptr; maxlen : C.int) return C.Strings.chars_ptr; pragma Import (C, VideoInit, "SDL_VideoInit"); procedure VideoQuit; pragma Import (C, VideoQuit, "SDL_VideoQuit"); -- This function fills the given character buffer with the -- name of the video driver, and returns a pointer to it -- if the video driver has been initialized. It returns NULL -- if no driver has been initialized. function VideoDriverName ( namebuf : C.Strings.chars_ptr; maxlen : C.int) return C.Strings.chars_ptr; pragma Import (C, VideoDriverName, "SDL_VideoDriverName"); -- This function returns a pointer to the current display -- surface. If SDL is doing format conversion on the display -- surface, this function returns the publicly visible surface, -- not the real video surface. function GetVideoSurface return Surface_ptr; pragma Import (C, GetVideoSurface, "SDL_GetVideoSurface"); -- This function returns a Read-only pointer to information -- about the video hardware. If this is called before SetVideoMode, -- the 'vfmt' member of the returned structure will contain the -- pixel format of the "best" video mode. function GetVideoInfo return VideoInfo_ConstPtr; pragma Import (C, GetVideoInfo, "SDL_GetVideoInfo"); -- Check to see if a particular video mode is supported. -- It returns 0 if the requested video mode is not supported -- under any bit depth, or retuns the bits-per-pixel of the -- closest available mode with the given width and height. If -- this bits-per-pixel is different from the one used when -- setting the video mode, SetVideoMode will succeed, but -- will emulate the requested bits-per-pixel with a shadow -- surface. -- -- The arguments to VideoModeOK are the same ones you would -- pass to SetVideoMode. function VideoModeOK ( width : C.int; height : C.int; bpp : C.int; -- flags : Uint32) flags : Surface_Flags) return C.int; pragma Import (C, VideoModeOK, "SDL_VideoModeOK"); -- Return a pointer to an array of available screen dimensions -- for the given format and video flags, sorted largest to -- smallest. Returns NULL if there are no dimensions available -- for a particular format, or Rect_ptr_ptr(-1) if any dimension -- is okay for the given format. -- -- If 'format' is NULL, the mode list will be the format given -- by GetVideoInfo.all.vfmt function ListModes ( format : PixelFormat_ptr; flags : Surface_Flags) return Rect_ptr_ptr; pragma Import (C, ListModes, "SDL_ListModes"); -- Necessary to verify if ListModes returns -- a non-pointer value like 0 or -1. function RectPP_To_Int is new Ada.Unchecked_Conversion (Rect_ptr_ptr, C.int); -- Necessary to manipulate C pointer from Ada type Rect_ptr_Array is array (C.size_t range <>) of aliased Rect_ptr; package Rect_ptr_PtrOps is new C.Pointers ( Index => C.size_t, Element => Rect_ptr, Element_Array => Rect_ptr_Array, Default_Terminator => null); -- You must do a --> use Rect_ptr_Ptrs; in your code. -- The limit of 20 is arbitrary -- The array scan should stop before 20 when a null is found. -- type Modes_Array is array (0 .. 19) of Rect_ptr; -- function ListModes ( -- format : PixelFormat_ptr; -- flags : Surface_Flags) -- return Modes_Array; -- pragma Import (C, ListModes, "SDL_ListModes"); -- Set up a video mode with the specified width, height and -- and bits-per-pixel. -- -- If 'bpp' is 0, it is treated as the current display -- bits-per-pixel. -- -- If ANYFORMAT is set in 'flags', the SDL library will -- try to set the requestd bits-per-pixel, but will return -- whatever video pixel format is available. The default is -- to emulate the requested pixel format if it is not natively -- available. -- -- If HWSURFACE is set in 'flags', the video surface will be -- placed in video memory, if possible, and you may have to -- call LockSurface in order to access the raw buffer. Otherwise -- the video surface will be created in the system memory. -- -- If ASYNCBLIT is set in 'flags', SDL will try to perform -- rectangle updates asynchronously, but you must always lock -- before accessing pixels. SDL will wait for updates to -- complete before returning from the lock. -- -- If HWPALETTE is set in 'flags', the SDL library will -- garantee that the colors set by SetColors will be the -- colors you get. Otherwise, in 8-bit mode, SetColors my -- not be able to set all of the colors exactly the way -- they are requested, and you should look at the video -- surface structure to determine the actual palette. If -- SDL cannot garantee that the colors you request can be -- set, i.e. if the color map is shared, then the video -- surface my be created under emulation in system memory, -- overriding the HWSURFACE flag. -- -- If FULLSCREEN is set in 'flags', the SDL library will -- try to set a fullscreen video mode. The default is to -- create a windowed mode if the current graphics system -- has a window manager. -- If the SDL library is able to set a fullscreen mode, -- this flag will be set in the surface that is returned. -- -- If DOUBLEBUF is set in 'flags', the SDL library will -- try to set up two surfaces in video memory and swap -- between them when you call Flip. This is usually slower -- than the normal single-buffering scheme, but prevents -- "tearing" artifacts caused by modifying video memory -- while the monitor is refreshing. It should only be used -- by applications that redraw the entire screen on every -- update. -- -- This function returns the video buffer surface, or NULL -- if it fails. function SetVideoMode ( width : C.int; height : C.int; bpp : C.int; flags : Surface_Flags) return Surface_ptr; pragma Import (C, SetVideoMode, "SDL_SetVideoMode"); -- Makes sure the given list of rectangles is updated on the -- given screen. If 'x','y','w' and 'h' are all 0, UpdateRect -- will update the entire screen. -- These functions should not be called while 'screen' is locked. procedure UpdateRects ( screen : Surface_ptr; numrects : C.int; rects : Rect_ptr); procedure UpdateRects ( screen : Surface_ptr; numrects : C.int; rects : Rects_Array); pragma Import (C, UpdateRects, "SDL_UpdateRects"); procedure UpdateRect ( screen : Surface_ptr; x : Sint32; y : Sint32; w : Uint32; h : Uint32); pragma Import (C, UpdateRect, "SDL_UpdateRect"); procedure Update_Rect ( screen : Surface_ptr; the_rect : Rect); pragma Inline (Update_Rect); -- On hardware that supports double-buffering, this function sets up a flip -- and returns. The hardware will wait for vertical retrace, and then swap -- video buffers before the next video surface blit or lock will return. -- On hardware that doesn not support double-buffering, this is equivalent -- to calling UpdateRect (screen, 0, 0, 0, 0); -- The DOUBLEBUF flag must have been passed to SetVideoMode when -- setting the video mode for this function to perform hardware flipping. -- This function returns 0 if successful, or -1 if there was an error. function Flip (screen : Surface_ptr) return C.int; procedure Flip (screen : Surface_ptr); pragma Import (C, Flip, "SDL_Flip"); -- Set the gamma correction for each of the color channels. -- The gamma values range (approximately) between 0.1 and 10.0 -- -- If this function isn't supported directly by the hardware, it will -- be emulated using gamma ramps, if available. If successful, this -- function returns 0, otherwise it returns -1. function SetGamma ( red : C.C_float; green : C.C_float; blue : C.C_float) return C.int; procedure SetGamma ( red : C.C_float; green : C.C_float; blue : C.C_float); pragma Import (C, SetGamma, "SDL_SetGamma"); -- Set the gamma translation table for the red, green, and blue channels -- of the video hardware. Each table is an array of 256 16-bit quantities, -- representing a mapping between the input and output for that channel. -- The input is the index into the array, and the output is the 16-bit -- gamma value at that index, scaled to the output color precision. -- -- You may pass NULL for any of the channels to leave it unchanged. -- If the call succeeds, it will return 0. If the display driver or -- hardware does not support gamma translation, or otherwise fails, -- this function will return -1. function SetGammaRamp ( red : Uint16_ptr; green : Uint16_ptr; blue : Uint16_ptr) return C.int; type ramp_Array is array (Natural range 0 .. 255) of aliased Uint16; function SetGammaRamp ( red : ramp_Array; green : ramp_Array; blue : ramp_Array) return C.int; pragma Import (C, SetGammaRamp, "SDL_SetGammaRamp"); -- Retrieve the current values of the gamma translation tables. -- -- You must pass in valid pointers to arrays of 256 8-bit quantities. -- Any of the pointers may be NULL to ignore that channel. -- If the call succeeds, it will return 0. If the display driver or -- hardware does not support gamma translation, or otherwise fails, -- this function will return -1. function GetGammaRamp ( red : Uint16_ptr; green : Uint16_ptr; blue : Uint16_ptr) return C.int; pragma Import (C, GetGammaRamp, "SDL_GetGammaRamp"); -- Sets a portion of the colormap for the given 8-bit surface. If -- 'surface' is not a palettized surface, this function does nothing, -- returning 0. If all of the colors were set as passed to SetColors, -- it will return 1. If not all the color entries were set exactly as -- given, it will return 0, and you should look at the surface palette to -- determine the actual color palette. -- -- When 'surface' is the surface associated with the current display, the -- display colormap will be updated with the requested colors. If -- HWPALETTE was set in SetVideoMode flags, SetColors -- will always return 1, and the palette is guaranteed to be set the way -- you desire, even if the window colormap has to be warped or run under -- emulation. function SetColors ( surface : Surface_ptr; colors : Color_ptr; firstcolor : C.int; ncolor : C.int) return C.int; procedure SetColors ( surface : Surface_ptr; colors : Color_ptr; firstcolor : C.int; ncolor : C.int); function SetColors ( surface : Surface_ptr; colors : Colors_Array; firstcolor : C.int; ncolor : C.int) return C.int; procedure SetColors ( surface : Surface_ptr; colors : Colors_Array; firstcolor : C.int; ncolor : C.int); pragma Import (C, SetColors, "SDL_SetColors"); function Set_Colors ( surface : Surface_ptr; colors : Colors_Array) return C.int; procedure Set_Colors ( surface : Surface_ptr; colors : Colors_Array); -- Sets a portion of the colormap for a given 8-bit surface. -- 'flags' is one or both of: -- LOGPAL -- set logical palette, which controls how blits are mapped -- to/from the surface, -- PHYSPAL -- set physical palette, which controls how pixels look on -- the screen -- Only screens have physical palettes. Separate change of physical/logical -- palettes is only possible if the screen has HWPALETTE set. -- -- The return value is 1 if all colours could be set as requested, and 0 -- otherwise. -- -- SetColors is equivalent to calling this function with -- flags = (LOGPAL or PHYSPAL). function SetPalette ( surface : Surface_ptr; flags : C.int; Colors : Color_ptr; firstcolor : C.int; ncolors : C.int) return C.int; function SetPalette ( surface : Surface_ptr; flags : C.int; Colors : Colors_Array; firstcolor : C.int; ncolors : C.int) return C.int; procedure SetPalette ( surface : Surface_ptr; flags : C.int; Colors : Color_ptr; firstcolor : C.int; ncolors : C.int); procedure SetPalette ( surface : Surface_ptr; flags : C.int; Colors : Colors_Array; firstcolor : C.int; ncolors : C.int); pragma Import (C, SetPalette, "SDL_SetPalette"); -- Maps an RGB triple to an opaque pixel value for a given pixel format function MapRGB ( format : PixelFormat_ptr; r : Uint8; g : Uint8; b : Uint8) return Uint32; pragma Import (C, MapRGB, "SDL_MapRGB"); -- Maps an RGBA quadruple to a pixel value for a given pixel format function MapRGBA ( format : PixelFormat_ptr; r : Uint8; g : Uint8; b : Uint8; a : Uint8) return Uint32; pragma Import (C, MapRGBA, "SDL_MapRGBA"); -- Maps a pixel value into the RGB components for a given pixel format procedure GetRGB ( pixel : Uint32; fmt : PixelFormat_ptr; r : Uint8_ptr; g : Uint8_ptr; b : Uint8_ptr); pragma Import (C, GetRGB, "SDL_GetRGB"); -- Maps a pixel value into the RGBA components for a given pixel format procedure GetRGBA ( pixel : Uint32; fmt : PixelFormat_ptr; r : Uint8_ptr; g : Uint8_ptr; b : Uint8_ptr; a : Uint8_ptr); pragma Import (C, GetRGBA, "SDL_GetRGBA"); -- Allocate and free an RGB surface (must be called after SetVideoMode) -- If the depth is 4 or 8 bits, an empty palette is allocated for the -- surface. If the depth is greater than 8 bits, the pixel format is set -- using the flags '[RGB]mask'. -- If the function runs out of memory, it will return NULL. -- -- The 'flags' tell what kind of surface to create. -- SWSURFACE means that the surface should be created in system memory. -- HWSURFACE means that the surface should be created in video memory, -- with the same format as the display surface. This is useful for -- surfaces that will not change much, to take advantage of hardware -- acceleration when being blitted to the display surface. -- ASYNCBLIT means that SDL will try to perform asynchronous blits with -- this surface, but you must always lock it before accessing the pixels. -- SDL will wait for current blits to finish before returning from the -- lock. SRCCOLORKEY indicates that the surface will be used for colorkey -- blits. If the hardware supports acceleration of colorkey blits between -- two surfaces in video memory, SDL will try to place the surface in -- video memory. If this isn't possible or if there is no hardware -- acceleration available, the surface will be placed in system memory. -- SRCALPHA means that the surface will be used for alpha blits and -- if the hardware supports hardware acceleration of alpha blits between -- two surfaces in video memory, to place the surface in video memory -- if possible, otherwise it will be placed in system memory. -- If the surface is created in video memory, blits will be _much_ faster, -- but the surface format must be identical to the video surface format, -- and the only way to access the pixels member of the surface is to use -- the LockSurface and UnlockSurface calls. -- If the requested surface actually resides in video memory, HWSURFACE -- will be set in the flags member of the returned surface. If for some -- reason the surface could not be placed in video memory, it will not have -- the HWSURFACE flag set, and will be created in system memory instead. function CreateRGBSurface ( flags : Surface_Flags; width : C.int; height : C.int; depth : C.int; Rmask : Uint32; Gmask : Uint32; Bmask : Uint32; Amask : Uint32) return Surface_ptr; pragma Import (C, CreateRGBSurface, "SDL_CreateRGBSurface"); function CreateRGBSurfaceFrom ( pixels : void_ptr; width : C.int; height : C.int; depth : C.int; pitch : C.int; Rmask : Uint32; Gmask : Uint32; Bmask : Uint32; Amask : Uint32) return Surface_ptr; pragma Import (C, CreateRGBSurfaceFrom, "SDL_CreateRGBSurfaceFrom"); procedure FreeSurface (surface : Surface_ptr); pragma Import (C, FreeSurface, "SDL_FreeSurface"); function AllocSurface ( flags : Surface_Flags; width : C.int; height : C.int; depth : C.int; Rmask : Uint32; Gmask : Uint32; Bmask : Uint32; Amask : Uint32) return Surface_ptr renames CreateRGBSurface; -- LockSurface sets up a surface for directly accessing the pixels. -- Between calls to LockSurface/UnlockSurface, you can write -- to and read from 'the_surface_ptr.pixels', using the pixel format -- stored in 'the_surface_ptr.format'. Once you are done accessing -- the surface, you should use UnlockSurface to release it. -- -- Not all surfaces require locking. If MUSTLOCK(surface) evaluates -- to 0, then you can read and write to the surface at any time, and the -- pixel format of the surface will not change. In particular, if the -- HWSURFACE flag is not given when calling SetVideoMode, you -- will not need to lock the display surface before accessing it. -- -- No operating system or library calls should be made between lock/unlock -- pairs, as critical system locks may be held during this time. -- -- LockSurface returns 0, or -1 if the surface couldn't be locked. function LockSurface (surface : Surface_ptr) return C.int; pragma Import (C, LockSurface, "SDL_LockSurface"); procedure UnlockSurface (surface : Surface_ptr); pragma Import (C, UnlockSurface, "SDL_UnlockSurface"); -- Load a surface from a seekable SDL data source (memory or file.) -- If 'freesrc' is non-zero, the source will be closed after being read. -- Returns the new surface, or NULL if there was an error. -- The new surface should be freed with FreeSurface. function LoadBMP_RW ( src : SDL.RWops.RWops_ptr; freesrc : C.int) return Surface_ptr; pragma Import (C, LoadBMP_RW, "SDL_LoadBMP_RW"); -- Load a surface from a file. function LoadBMP (file : C.Strings.chars_ptr) return Surface_ptr; pragma Inline (LoadBMP); function LoadBMP (file : String) return Surface_ptr; pragma Inline (LoadBMP); function Load_BMP (file : String) return Surface_ptr renames LoadBMP; -- Save a surface to a seekable SDL data source (memory or file.) -- If 'freedst' is non-zero, the source will be closed after being written. -- Returns 0 if successful or -1 if there was an error. function SaveBMP_RW ( surface : Surface_ptr; dst : SDL.RWops.RWops_ptr; freedst : C.int) return C.int; pragma Import (C, SaveBMP_RW, "SDL_SaveBMP_RW"); -- Save a surface to a file function SaveBMP ( surface : Surface_ptr; file : C.Strings.chars_ptr) return C.int; pragma Inline (SaveBMP); procedure SaveBMP ( surface : Surface_ptr; file : C.Strings.chars_ptr); pragma Inline (SaveBMP); function Save_BMP ( surface : Surface_ptr; file : String) return C.int; pragma Inline (Save_BMP); procedure Save_BMP ( surface : Surface_ptr; file : String); pragma Inline (Save_BMP); -- Sets the color key (transparent pixel) in a blittable surface. -- If 'flag' is SRCCOLORKEY (optionally OR'd with RLEACCEL), -- 'key' will be the transparent pixel in the source image of a blit. -- RLEACCEL requests RLE acceleration for the surface if present, -- and removes RLE acceleration if absent. -- If 'flag' is 0, this function clears any current color key. -- This function returns 0, or -1 if there was an error. function SetColorKey ( surface : Surface_ptr; -- flag : Uint32; flag : Surface_Flags; key : Uint32) return C.int; procedure SetColorKey ( surface : Surface_ptr; -- flag : Uint32; flag : Surface_Flags; key : Uint32); pragma Import (C, SetColorKey, "SDL_SetColorKey"); -- This function sets the alpha value for the entire surface, as opposed to -- using the alpha component of each pixel. This value measures the range -- of transparency of the surface, 0 being completely transparent to 255 -- being completely opaque. An 'alpha' value of 255 causes blits to be -- opaque, the source pixels copied to the destination (the default). Note -- that per-surface alpha can be combined with colorkey transparency. -- -- If 'flag' is 0, alpha blending is disabled for the surface. -- If 'flag' is SRCALPHA, alpha blending is enabled for the surface. -- OR:ing the flag with RLEACCEL requests RLE acceleration for the -- surface; if RLEACCEL is not specified, the RLE accel will be removed. function SetAlpha ( surface : Surface_ptr; flag : Surface_Flags; alpha : Uint8) return C.int; procedure SetAlpha ( surface : Surface_ptr; flag : Surface_Flags; alpha : Uint8); pragma Import (C, SetAlpha, "SDL_SetAlpha"); -- Sets the clipping rectangle for the destination surface in a blit. -- -- If the clip rectangle is NULL, clipping will be disabled. -- If the clip rectangle doesn't intersect the surface, the function will -- return SDL_FALSE and blits will be completely clipped. Otherwise the -- function returns SDL_TRUE and blits to the surface will be clipped to -- the intersection of the surface area and the clipping rectangle. -- -- Note that blits are automatically clipped to the edges of the source -- and destination surfaces. function SetClipRect ( surface : Surface_ptr; rect : Rect_ptr) return C.int; -- The return must be SDL_true or SDL_false, function SetClipRect ( surface : Surface_ptr; the_rect : Rect) return C.int; -- The return must be SDL_true or SDL_false, procedure SetClipRect ( surface : Surface_ptr; rect : Rect_ptr); procedure SetClipRect ( surface : Surface_ptr; the_rect : Rect); pragma Import (C, SetClipRect, "SDL_SetClipRect"); procedure Disable_Clipping (surface : Surface_ptr); pragma Inline (Disable_Clipping); -- Gets the clipping rectangle for the destination surface in a blit. -- 'prect' must be a pointer to a valid rectangle which will be filled -- with the correct values. procedure GetClipRect ( surface : Surface_ptr; prect : access Rect); procedure GetClipRect ( surface : Surface_ptr; the_rect : Rect); pragma Import (C, GetClipRect, "SDL_GetClipRect"); -- Creates a new surface of the specified format, and then copies and maps -- the given surface to it so the blit of the converted surface will be as -- fast as possible. If this function fails, it returns NULL. -- -- The 'flags' parameter is passed to CreateRGBSurface and has those -- semantics. -- -- This function is used internally by SDL_DisplayFormat. function ConvertSurface ( src : Surface_ptr; fmt : PixelFormat_ptr; flags : Surface_Flags) return Surface_ptr; pragma Import (C, ConvertSurface, "SDL_ConvertSurface"); -- This performs a fast blit from the source surface to the destination -- surface. It assumes that the source and destination rectangles are -- the same size. If either 'srcrect' or 'dstrect' are NULL, the entire -- surface (src or dst) is copied. The final blit rectangles are saved -- in 'srcrect' and 'dstrect' after all clipping is performed. -- If the blit is successful, it returns 0, otherwise it returns -1. -- -- The blit function should not be called on a locked surface. -- -- The blit semantics for surfaces with and without alpha and colorkey -- are defined as follows: -- -- RGBA->RGB: -- SDL_SRCALPHA set: -- alpha-blend (using alpha-channel). -- SDL_SRCCOLORKEY ignored. -- SDL_SRCALPHA not set: -- copy RGB. -- if SDL_SRCCOLORKEY set, only copy the pixels matching the -- RGB values of the source colour key, ignoring alpha in the -- comparison. -- -- RGB->RGBA: -- SDL_SRCALPHA set: -- alpha-blend (using the source per-surface alpha value); -- set destination alpha to opaque. -- SDL_SRCALPHA not set: -- copy RGB, set destination alpha to opaque. -- both: -- if SDL_SRCCOLORKEY set, only copy the pixels matching the -- source colour key. -- -- RGBA->RGBA: -- SDL_SRCALPHA set: -- alpha-blend (using the source alpha channel) the RGB values; -- leave destination alpha untouched. [Note: is this correct?] -- SDL_SRCCOLORKEY ignored. -- SDL_SRCALPHA not set: -- copy all of RGBA to the destination. -- if SDL_SRCCOLORKEY set, only copy the pixels matching the -- RGB values of the source colour key, ignoring alpha in the -- comparison. -- -- RGB->RGB: -- SDL_SRCALPHA set: -- alpha-blend (using the source per-surface alpha value). -- SDL_SRCALPHA not set: -- copy RGB. -- both: -- if SDL_SRCCOLORKEY set, only copy the pixels matching the -- source colour key. -- If either of the surfaces were in video memory, and the blit returns -2, -- the video memory was lost, so it should be reloaded with artwork and -- re-blitted: -- while BlitSurface (image, imgrect, screen, dstrect) = -2 loop -- while SDL_LockSurface (image) < 0 loop -- Sleep(10); -- end loop; -- -- Write image pixels to image->pixels -- -- UnlockSurface (image); -- end loop; -- This happens under DirectX 5.0 when the system switches away from your -- fullscreen application. The lock will also fail until you have access -- to the video memory again. -- This is the public blit function, BlitSurface, and it performs -- rectangle validation and clipping before passing it to LowerBlit function UpperBlit ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect_ptr) return C.int; function UpperBlit ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect_ptr) return C.int; function UpperBlit ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect) return C.int; function UpperBlit ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect) return C.int; procedure UpperBlit ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect_ptr); procedure UpperBlit ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect_ptr); procedure UpperBlit ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect); procedure UpperBlit ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect); pragma Import (C, UpperBlit, "SDL_UpperBlit"); -- You should call BlitSurface unless you know exactly how SDL -- blitting works internally and how to use the other blit functions. function BlitSurface ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect_ptr) return C.int renames UpperBlit; function BlitSurface ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect_ptr) return C.int renames UpperBlit; function BlitSurface ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect) return C.int renames UpperBlit; function BlitSurface ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect) return C.int renames UpperBlit; procedure BlitSurface ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect_ptr) renames UpperBlit; procedure BlitSurface ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect_ptr) renames UpperBlit; procedure BlitSurface ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect) renames UpperBlit; procedure BlitSurface ( src : Surface_ptr; srcrect : Rect; dst : Surface_ptr; dstrect : Rect) renames UpperBlit; -- This is a semi-private blit function and it performs low-level surface -- blitting only. function LowerBlit ( src : Surface_ptr; srcrect : Rect_ptr; dst : Surface_ptr; dstrect : Rect_ptr) return C.int; pragma Import (C, LowerBlit, "SDL_LowerBlit"); -- This function performs a fast fill of the given rectangle with 'color' -- The given rectangle is clipped to the destination surface clip area -- and the final fill rectangle is saved in the passed in pointer. -- If 'dstrect' is NULL, the whole surface will be filled with 'color' -- The color should be a pixel of the format used by the surface, and -- can be generated by the MapRGB function. -- This function returns 0 on success, or -1 on error. function FillRect ( dst : Surface_ptr; dstrect : Rect_ptr; color : Uint32) return C.int; procedure FillRect ( dst : Surface_ptr; dstrect : Rect_ptr; color : Uint32); procedure FillRect ( dst : Surface_ptr; dstrect : in out Rect; -- Not really changed inside FillRect. color : Uint32); -- but used to avoid some Unchecked_Access pragma Import (C, FillRect, "SDL_FillRect"); -- This function takes a surface and copies it to a new surface of the -- pixel format and colors of the video framebuffer, suitable for fast -- blitting onto the display surface. It calls ConvertSurface -- -- If you want to take advantage of hardware colorkey or alpha blit -- acceleration, you should set the colorkey and alpha value before -- calling this function. -- -- If the conversion fails or runs out of memory, it returns NULL function DisplayFormat (surface : Surface_ptr) return Surface_ptr; pragma Import (C, DisplayFormat, "SDL_DisplayFormat"); -- This function takes a surface and copies it to a new surface of the -- pixel format and colors of the video framebuffer (if possible), -- suitable for fast alpha blitting onto the display surface. -- The new surface will always have an alpha channel. -- -- If you want to take advantage of hardware colorkey or alpha blit -- acceleration, you should set the colorkey and alpha value before -- calling this function. -- -- If the conversion fails or runs out of memory, it returns NULL function DisplayFormatAlpha (surface : Surface_ptr) return Surface_ptr; pragma Import (C, DisplayFormatAlpha, "SDL_DisplayFormatAlpha"); -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- * YUV video surface overlay functions * -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- This function creates a video output overlay -- Calling the returned surface an overlay is something of a misnomer -- because the contents of the display surface underneath the area where -- the overlay is shown is undefined - it may be overwritten with the -- converted YUV data. function CreateYUVOverlay ( width : C.int; height : C.int; format : Uint32; display : Surface_ptr) return Overlay_ptr; pragma Import (C, CreateYUVOverlay, "SDL_CreateYUVOverlay"); -- Lock an overlay for direct access, and unlock it when you are done function LockYUVOverlay (overlay : Overlay_ptr) return C.int; pragma Import (C, LockYUVOverlay, "SDL_LockYUVOverlay"); procedure UnlockYUVOverlay (overlay : Overlay_ptr); pragma Import (C, UnlockYUVOverlay, "SDL_UnlockYUVOverlay"); -- Blit a video overlay to the display surface. -- The contents of the video surface underneath the blit destination are -- not defined. -- The width and height of the destination rectangle may be different from -- that of the overlay, but currently only 2x scaling is supported. function DisplayYUVOverlay ( overlay : Overlay_ptr; dstrect : Rect_ptr) return C.int; pragma Import (C, DisplayYUVOverlay, "SDL_DisplayYUVOverlay"); -- Free a video overlay procedure FreeYUVOverlay (overlay : Overlay_ptr); pragma Import (C, FreeYUVOverlay, "SDL_FreeYUVOverlay"); -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- * OpenGL support functions. * -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- * -- * Dynamically load a GL driver, if SDL is built with dynamic GL. -- * -- * SDL links normally with the OpenGL library on your system by default, -- * but you can compile it to dynamically load the GL driver at runtime. -- * If you do this, you need to retrieve all of the GL functions used in -- * your program from the dynamic library using GL_GetProcAddress. -- * -- * This is disabled in default builds of SDL. function GL_LoadLibrary (path : C.Strings.chars_ptr) return C.int; pragma Import (C, GL_LoadLibrary, "SDL_GL_LoadLibrary"); -- Get the address of a GL function (for extension functions) function GL_GetProcAddress (proc : C.Strings.chars_ptr) return System.Address; pragma Import (C, GL_GetProcAddress, "SDL_GL_GetProcAddress"); -- Set an attribute of the OpenGL subsystem before intialization. function GL_SetAttribute ( attr : GLattr; value : C.int) return C.int; procedure GL_SetAttribute ( attr : GLattr; value : C.int); pragma Import (C, GL_SetAttribute, "SDL_GL_SetAttribute"); -- Get an attribute of the OpenGL subsystem from the windowing -- interface, such as glX. This is of course different from getting -- the values from SDL's internal OpenGL subsystem, which only -- stores the values you request before initialization. -- -- Developers should track the values they pass into GL_SetAttribute -- themselves if they want to retrieve these values. function GL_GetAttribute ( attr : GLattr; value : access C.int) return C.int; procedure GL_GetAttribute ( attr : GLattr; value : access C.int); procedure GL_GetAttribute ( attr : GLattr; value : out C.int); pragma Import (C, GL_GetAttribute, "SDL_GL_GetAttribute"); -- Swap the OpenGL buffers, if double-buffering is supported. procedure GL_SwapBuffers; pragma Import (C, GL_SwapBuffers, "SDL_GL_SwapBuffers"); -- ---------------------------------------------------- -- Internal functions that should not be called unless you have read -- and understood the source code for these functions. procedure GL_UpdateRects ( numrects : C.int; rects : Rect_ptr); pragma Import (C, GL_UpdateRects, "SDL_UpdateRects"); procedure GL_Lock; pragma Import (C, GL_Lock, "SDL_GL_Lock"); procedure GL_Unlock; pragma Import (C, GL_Unlock, "SDL_GL_Unlock"); -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- * These functions allow interaction with the window manager, if any. * -- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- * -- * Sets/Gets the title and icon text of the display window procedure WM_SetCaption ( title : C.Strings.chars_ptr; icon : C.Strings.chars_ptr); pragma Import (C, WM_SetCaption, "SDL_WM_SetCaption"); procedure WM_Set_Caption ( title : in String; icon : in String); pragma Inline (WM_Set_Caption); procedure WM_Set_Caption_Title (title : in String); pragma Inline (WM_Set_Caption_Title); procedure WM_Set_Caption_Icon (icon : in String); pragma Inline (WM_Set_Caption_Icon); procedure WM_GetCaption ( title : chars_ptr_ptr; icon : chars_ptr_ptr); pragma Import (C, WM_GetCaption, "SDL_WM_GetCaption"); procedure WM_Get_Caption ( title : out US.Unbounded_String; icon : out US.Unbounded_String); pragma Inline (WM_Get_Caption); procedure WM_Get_Caption_Title (title : out US.Unbounded_String); pragma Inline (WM_Get_Caption_Title); procedure WM_Get_Caption_Icon (icon : out US.Unbounded_String); pragma Inline (WM_Get_Caption_Icon); -- Sets the icon for the display window. -- This function must be called before the first call to SetVideoMode. -- It takes an icon surface, and a mask in MSB format. -- If 'mask' is NULL, the entire icon surface will be used as the icon. procedure WM_SetIcon ( icon : Surface_ptr; mask : Uint8_ptr); -- Allowing "null" type Icon_Mask_Array is array (Integer range <>) of Uint8; pragma Convention (C, Icon_Mask_Array); procedure WM_SetIcon ( icon : Surface_ptr; mask : in Icon_Mask_Array); pragma Import (C, WM_SetIcon, "SDL_WM_SetIcon"); -- This function iconifies the window, and returns 1 if it succeeded. -- If the function succeeds, it generates an APPACTIVE loss event. -- This function is a noop and returns 0 in non-windowed environments. function WM_IconifyWindow return C.int; procedure WM_IconifyWindow; pragma Import (C, WM_IconifyWindow, "SDL_WM_IconifyWindow"); -- Toggle fullscreen mode without changing the contents of the screen. -- If the display surface does not require locking before accessing -- the pixel information, then the memory pointers will not change. -- -- If this function was able to toggle fullscreen mode (change from -- running in a window to fullscreen, or vice-versa), it will return 1. -- If it is not implemented, or fails, it returns 0. -- -- The next call to SetVideoMode will set the mode fullscreen -- attribute based on the flags parameter - if SDL_FULLSCREEN is not -- set, then the display will be windowed by default where supported. -- -- This is currently only implemented in the X11 video driver. function WM_ToggleFullScreen (surface : Surface_ptr) return C.int; pragma Import (C, WM_ToggleFullScreen, "SDL_WM_ToggleFullScreen"); type GrabMode is new C.int; GRAB_QUERY : constant GrabMode := -1; GRAB_OFF : constant GrabMode := 0; GRAB_ON : constant GrabMode := 1; GRAB_FULLSCREEN : constant GrabMode := 2; -- Used internally -- This function allows you to set and query the input grab state of -- the application. It returns the new input grab state. -- Grabbing means that the mouse is confined to the application window, -- and nearly all keyboard input is passed directly to the application, -- and not interpreted by a window manager, if any. -- function WM_GrabInput ( -- mode : C.int -- Might be GRAB_QUERY, GRAB_OFF, or GRAB_FULLSCREEN -- ) return C.int; -- Might be GRAB_QUERY, GRAB_OFF, or GRAB_FULLSCREEN function WM_GrabInput (mode : GrabMode) return GrabMode; pragma Import (C, WM_GrabInput, "SDL_WM_GrabInput"); end SDL.Video;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Streams.Naked_Stream_IO.Standard_Files; package body Ada.Streams.Stream_IO.Standard_Files is Standard_Input_Object : aliased File_Type; Standard_Output_Object : aliased File_Type; Standard_Error_Object : aliased File_Type; -- implementation function Standard_Input return not null access constant File_Type is begin return Standard_Input_Object'Access; end Standard_Input; function Standard_Output return not null access constant File_Type is begin return Standard_Output_Object'Access; end Standard_Output; function Standard_Error return not null access constant File_Type is begin return Standard_Error_Object'Access; end Standard_Error; begin Controlled.Reference (Standard_Input_Object).all := Naked_Stream_IO.Standard_Files.Standard_Input; Controlled.Reference (Standard_Output_Object).all := Naked_Stream_IO.Standard_Files.Standard_Output; Controlled.Reference (Standard_Error_Object).all := Naked_Stream_IO.Standard_Files.Standard_Error; end Ada.Streams.Stream_IO.Standard_Files;
{ "source": "starcoderdata", "programming_language": "ada" }
procedure Hello is procedure example is begin meow := meow + meow; end example; procedure bark ( top, tip : INTEGER ; abc :STRING) is a,b,c : ARRAY (1..5) of INTEGER; begin a(1):= 5; end bark; function foo return INTEGER is begin return 1; end example; function hi (hello:STRING) return FLOAT is begin return 1.0; end example; buf : INTEGER; ch : character; begin bark(5,5); example; buf:=hi("hello"&"abc"); for Iter in 1..5 loop if min = max then buf:=hi("hello"&'a'); elsif min < max then null; else null; end if; ch := 's'; end loop; end Hello;
{ "source": "starcoderdata", "programming_language": "ada" }
package body Memory.Option is function Create_Option return Option_Pointer is result : constant Option_Pointer := new Option_Type; begin return result; end Create_Option; function Clone(mem : Option_Type) return Memory_Pointer is result : constant Option_Pointer := new Option_Type'(mem); begin return Memory_Pointer(result); end Clone; procedure Permute(mem : in out Option_Type; generator : in Distribution_Type; max_cost : in Cost_Type) is begin mem.index := Random(generator) mod (mem.memories.Last_Index + 1); end Permute; procedure Add_Memory(mem : in out Option_Type; other : access Memory_Type'Class) is begin mem.memories.Append(Memory_Pointer(other)); end Add_Memory; function Done(mem : Option_Type) return Boolean is begin return Done(mem.memories.Element(mem.index).all); end Done; procedure Reset(mem : in out Option_Type; context : in Natural) is begin for i in mem.memories.First_Index .. mem.memories.Last_Index loop Reset(mem.memories.Element(i).all, context); end loop; end Reset; procedure Set_Port(mem : in out Option_Type; port : in Natural; ready : out Boolean) is begin Set_Port(mem.memories.Element(mem.index).all, port, ready); end Set_Port; procedure Read(mem : in out Option_Type; address : in Address_Type; size : in Positive) is begin Read(mem.memories.Element(mem.index).all, address, size); end Read; procedure Write(mem : in out Option_Type; address : in Address_Type; size : in Positive) is begin Write(mem.memories.Element(mem.index).all, address, size); end Write; procedure Idle(mem : in out Option_Type; cycles : in Time_Type) is begin Idle(mem.memories.Element(mem.index).all, cycles); end Idle; function Get_Time(mem : Option_Type) return Time_Type is begin return Get_Time(mem.memories.Element(mem.index).all); end Get_Time; function Get_Writes(mem : Option_Type) return Long_Integer is begin return Get_Writes(mem.memories.Element(mem.index).all); end Get_Writes; function To_String(mem : Option_Type) return Unbounded_String is begin return To_String(mem.memories.Element(mem.index).all); end To_String; function Get_Cost(mem : Option_Type) return Cost_Type is begin return Get_Cost(mem.memories.Element(mem.index).all); end Get_Cost; function Get_Word_Size(mem : Option_Type) return Positive is begin return Get_Word_Size(mem.memories.Element(mem.index).all); end Get_Word_Size; procedure Generate(mem : in Option_Type; sigs : in out Unbounded_String; code : in out Unbounded_String) is begin Generate(mem.memories.Element(mem.index).all, sigs, code); end Generate; function Get_Ports(mem : Option_Type) return Port_Vector_Type is begin return Get_Ports(mem.memories.Element(mem.index).all); end Get_Ports; procedure Adjust(mem : in out Option_Type) is begin for i in mem.memories.First_Index .. mem.memories.Last_Index loop declare ptr : constant Memory_Pointer := mem.memories.Element(i); begin mem.memories.Replace_Element(i, Clone(ptr.all)); end; end loop; end Adjust; procedure Finalize(mem : in out Option_Type) is begin for i in mem.memories.First_Index .. mem.memories.Last_Index loop declare ptr : Memory_Pointer := mem.memories.Element(i); begin Destroy(ptr); end; end loop; end Finalize; end Memory.Option;
{ "source": "starcoderdata", "programming_language": "ada" }
Tok_Of, -- OF Eterm, Sterm Tok_Out, -- OUT Eterm, Sterm Tok_Renames, -- RENAMES Eterm, Sterm Tok_Reverse, -- REVERSE Eterm, Sterm Tok_Some, -- SOME Eterm, Sterm Tok_Tagged, -- TAGGED Eterm, Sterm Tok_Case, -- CASE Eterm, Sterm, After_SM Tok_Delay, -- DELAY Eterm, Sterm, After_SM Tok_Accept, -- ACCEPT Eterm, Sterm, After_SM Tok_Elsif, -- ELSIF Eterm, Sterm, After_SM Tok_End, -- END Eterm, Sterm, After_SM Tok_Exit, -- EXIT Eterm, Sterm, After_SM Tok_Goto, -- GOTO Eterm, Sterm, After_SM Tok_If, -- IF Eterm, Sterm, After_SM Tok_Pragma, -- PRAGMA Eterm, Sterm, After_SM Tok_Raise, -- RAISE Eterm, Sterm, After_SM Tok_Requeue, -- REQUEUE Eterm, Sterm, After_SM Tok_Return, -- RETURN Eterm, Sterm, After_SM Tok_Terminate, -- TERMINATE Eterm, Sterm, After_SM Tok_Until, -- UNTIL Eterm, Sterm, After_SM Tok_When, -- WHEN Eterm, Sterm, After_SM Tok_For, -- FOR Eterm, Sterm, After_SM, Labeled_Stmt Tok_While, -- WHILE Eterm, Sterm, After_SM, Labeled_Stmt Tok_Separate, -- SEPARATE Eterm, Sterm, Cunit, After_SM Tok_Entry, -- ENTRY Eterm, Sterm, Declk, Deckn, After_SM Tok_Protected, -- PROTECTED Eterm, Sterm, Declk, Deckn, After_SM Tok_Task, -- TASK Eterm, Sterm, Declk, Deckn, After_SM Tok_Type, -- TYPE Eterm, Sterm, Declk, Deckn, After_SM Tok_Subtype, -- SUBTYPE Eterm, Sterm, Declk, Deckn, After_SM Tok_Overriding, -- OVERRIDING Eterm, Sterm, Declk, Declk, After_SM Tok_Synchronized, -- SYNCHRONIZED Eterm, Sterm, Declk, Deckn, After_SM Tok_Use, -- USE Eterm, Sterm, Declk, Deckn, After_SM Tok_Generic, -- GENERIC Eterm, Sterm, Cunit, Declk, After_SM Tok_Function, -- FUNCTION Eterm, Sterm, Cunit, Declk, After_SM Tok_Package, -- PACKAGE Eterm, Sterm, Cunit, Declk, After_SM Tok_Procedure, -- PROCEDURE Eterm, Sterm, Cunit, Declk, After_SM Tok_Do, -- DO Eterm, Sterm Tok_Is, -- IS Eterm, Sterm Tok_Interface, -- INTERFACE Eterm, Sterm Tok_Record, -- RECORD Eterm, Sterm Tok_Then, -- THEN Eterm, Sterm Tok_Abort, -- ABORT Eterm, Sterm, After_SM Tok_Else, -- ELSE Eterm, Sterm, After_SM Tok_Exception, -- EXCEPTION Eterm, Sterm, After_SM Tok_Select, -- SELECT Eterm, Sterm, After_SM Tok_Begin, -- BEGIN Eterm, Sterm, After_SM, Labeled_Stmt Tok_Declare, -- DECLARE Eterm, Sterm, After_SM, Labeled_Stmt Tok_Loop, -- LOOP Eterm, Sterm, After_SM, Labeled_Stmt Tok_Private, -- PRIVATE Eterm, Sterm, Cunit, After_SM Tok_With, -- WITH Eterm, Sterm, Cunit, After_SM Tok_Semicolon, -- ; Eterm, Sterm, Cterm Tok_Left_Paren, -- ( Namext, Consk Tok_Ampersand, -- & Binary_Addop Tok_Vertical_Bar, -- | Cterm, Sterm, Chtok Tok_Less_Less, -- << Eterm, Sterm, After_SM Tok_Greater_Greater, -- >> Eterm, Sterm Tok_Pound, -- # sign, used by the preprocessor Tok_Left_Square_Bracket, -- '[' used in wide character encoding Tok_Right_Square_Bracket, -- ']' used in wide character encoding Tok_Colon, -- : Eterm, Sterm Tok_Arrow, -- => Sterm, Cterm, Chtok Tok_Dot_Dot, -- .. Sterm, Chtok No_Token); -- No_Token is used for initializing Token values to indicate that -- no value has been set yet. type Token_Set is array (Token_Type) of Boolean; pragma Pack (Token_Set); subtype Reserved_Token_Type is Token_Type range Tok_Abstract .. Tok_With; subtype Token_Class_Literal is Token_Type range Tok_Integer_Literal .. Tok_Operator_Symbol; -- Literal subtype Token_Class_Declk is Token_Type range Tok_Entry .. Tok_Procedure; -- Keywords which start a declaration subtype Token_Class_No_Cont is Token_Type range Tok_Generic .. Tok_Colon; -- Do not allow a following continuation line Is_Operator : constant Token_Set := (Tok_Double_Asterisk | Tok_Minus | Tok_Plus | Tok_Asterisk | Tok_Slash | Tok_Less | Tok_Equal | Tok_Greater | Tok_Not_Equal | Tok_Greater_Equal | Tok_Less_Equal | Tok_Ampersand => True, others => False); Is_Extended_Operator : constant Token_Set := (Tok_Double_Asterisk .. Tok_Slash | Tok_Comma .. Tok_Colon_Equal | Tok_Semicolon | Tok_Ampersand .. Tok_Greater_Greater | Tok_Colon .. Tok_Dot_Dot => True, others => False); Max_Identifier : constant := 256; -- Maximum length of an identifier type Variable_Kind_Type is (Unknown_Kind, Parameter_Kind, Discriminant_Kind); type Extended_Token is record Token : Token_Type := No_Token; -- Enclosing token In_Declaration : Boolean := False; -- Are we inside a declarative part ? In_Entity_Profile : Boolean := True; -- Are we in a definition? -- (e.g. [procedure bla] is -- [type T is record] null; end record; -- etc... Extra_Indent : Boolean := False; -- Used for various kinds of constructs, when detecting different -- ways of indenting code (only used internally). -- For a Tok_Record, set to True if the keyword "record" was found on -- its own line. -- For a Tok_Case, set to True if 'when' constructs should be indented -- an extra level, as for the RM style. Type_Declaration : Boolean := False; -- Is it a type declaration ? Package_Declaration : Boolean := False; -- Is it a package declaration ? Protected_Declaration : Boolean := False; -- Is this a protected declaration ? -- ??? It would be nice to merge the fields Declaration, -- Type_Declaration and Package_Declaration at some point. Identifier : String (1 .. Max_Identifier); -- Name of the enclosing token -- The actual name is Identifier (1 .. Ident_Len) Ident_Len : Natural := 0; -- Actual length of Indentifier Profile_Start : Natural := 0; -- Position in the buffer where the profile of the current subprogram -- starts. Profile_End : Natural := 0; -- Position in the buffer where the profile of the current subprogram -- ends. Align_Colon : Natural := 0; -- The column on which to align declarations Colon_Col : Natural := 0; -- The column where the last ':' was found. -- Only relevant for Tok_Colon tokens Sloc : Source_Location; -- Source location for this entity Sloc_Name : Source_Location; -- Source location for the name of this entity, if relevant Visibility : Construct_Visibility := Visibility_Public; -- Is the token public or private ? Visibility_Section : Construct_Visibility := Visibility_Public; -- Are we on the public or on the private section of the token ? Variable_Kind : Variable_Kind_Type := Unknown_Kind; -- If the token is a variable, hold wether this is actually a variable, -- a discriminant or a parameter Type_Definition_Section : Boolean := False; -- Are we currently processing the type definition of the token ? Is_In_Type_Definition : Boolean := False; -- Is this token found in the type definition section of its parent ? Attributes : Construct_Attribute_Map := No_Attribute; -- Defines the attributes that have been found for the given token Is_Generic_Param : Boolean := False; -- Is this token a generic parameter? end record; -- Extended information for a token package Token_Stack is new Generic_Stack (Extended_Token); use Token_Stack; type Construct_Type is (Conditional, Type_Declaration, Function_Call, Aggregate); -- Type used to differentiate different constructs to refine indentation package Construct_Stack is new Generic_Stack (Construct_Type); use Construct_Stack; ---------------------- -- Local procedures -- ---------------------- function Get_Token (Str : String; Prev_Token : Token_Type) return Token_Type; -- Return a token_Type given a string. -- For efficiency, S is assumed to start at index 1. -- Prev_Token is the previous token scanned, if any. This is needed -- to e.g. differenciate pragma Interface vs interface keyword. function Is_Library_Level (Stack : Token_Stack.Simple_Stack) return Boolean; -- Return True if the current scope in Stack is a library level package --------------- -- Get_Token -- --------------- function Get_Token (Str : String; Prev_Token : Token_Type) return Token_Type is S : String (Str'Range); begin pragma Assert (S'First = 1); -- First convert Str to lower case for the token parser below for K in Str'Range loop S (K) := To_Lower (Str (K)); end loop; if S'Length = 0 then return No_Token; elsif S'Length = 1 then if Is_Control (S (S'First)) then return No_Token; else return Tok_Identifier; end if; end if; -- Use a case statement instead of a loop for efficiency case S (1) is when 'a' => case S (2) is when 'b' => if S (3 .. S'Last) = "ort" then return Tok_Abort; elsif S (3 .. S'Last) = "s" then return Tok_Abs; elsif S (3 .. S'Last) = "stract" then return Tok_Abstract; end if; when 'c' => if S (3 .. S'Last) = "cept" then return Tok_Accept; elsif S (3 .. S'Last) = "cess" then return Tok_Access; end if; when 'l' => if S (3 .. S'Last) = "l" then return Tok_All; elsif S (3 .. S'Last) = "iased" then return Tok_Aliased; end if; when 'n' => if S (3 .. S'Last) = "d" then return Tok_And; end if; when 'r' => if S (3 .. S'Last) = "ray" then return Tok_Array; end if; when 't' => if S'Length = 2 then return Tok_At; end if; when others => return Tok_Identifier; end case; when 'b' => if S (2 .. S'Last) = "egin" then return Tok_Begin; elsif S (2 .. S'Last) = "ody" then return Tok_Body; end if; when 'c' => if S (2 .. S'Last) = "ase" then return Tok_Case; elsif S (2 .. S'Last) = "onstant" then return Tok_Constant; end if; when 'd' => if S (2) = 'e' then if S (3 .. S'Last) = "clare" then return Tok_Declare; elsif S (3 .. S'Last) = "lay" then return Tok_Delay; elsif S (3 .. S'Last) = "lta" then return Tok_Delta; end if; elsif S (2 .. S'Last) = "igits" then return Tok_Digits; elsif S (2 .. S'Last) = "o" then return Tok_Do; end if; when 'e' => if S (2 .. S'Last) = "lse" then return Tok_Else; elsif S (2 .. S'Last) = "lsif" then return Tok_Elsif; elsif S (2 .. S'Last) = "nd" then return Tok_End; elsif S (2 .. S'Last) = "ntry" then return Tok_Entry; elsif S (2 .. S'Last) = "xception" then return Tok_Exception; elsif S (2 .. S'Last) = "xit" then return Tok_Exit; end if; when 'f' => if S (2 .. S'Last) = "or" then return Tok_For; elsif S (2 .. S'Last) = "unction" then return Tok_Function; end if; when 'g' => if S (2 .. S'Last) = "eneric" then return Tok_Generic; elsif S (2 .. S'Last) = "oto" then return Tok_Goto; end if; when 'i' => if S (2 .. S'Last) = "f" then return Tok_If; elsif S (2 .. S'Last) = "n" then return Tok_In; elsif S (2 .. S'Last) = "nterface" then if Prev_Token = Tok_Pragma then return Tok_Identifier; else return Tok_Interface; end if; elsif S (2 .. S'Last) = "s" then return Tok_Is; end if; when 'l' => if S (2 .. S'Last) = "imited" then return Tok_Limited; elsif S (2 .. S'Last) = "oop" then return Tok_Loop; end if; when 'm' => if S (2 .. S'Last) = "od" then return Tok_Mod; end if; when 'n' => if S (2 .. S'Last) = "ew" then return Tok_New; elsif S (2 .. S'Last) = "ot" then return Tok_Not; elsif S (2 .. S'Last) = "ull" then return Tok_Null; end if; when 'o' => if S (2 .. S'Last) = "thers" then return Tok_Others; elsif S (2 .. S'Last) = "ut" then return Tok_Out; elsif S (2 .. S'Last) = "f" then return Tok_Of; elsif S (2 .. S'Last) = "r" then return Tok_Or; elsif S (2 .. S'Last) = "verriding" then return Tok_Overriding; end if; when 'p' => if S (2) = 'r' then if S (3 .. S'Last) = "agma" then return Tok_Pragma; elsif S (3 .. S'Last) = "ivate" then return Tok_Private; elsif S (3 .. S'Last) = "ocedure" then return Tok_Procedure; elsif S (3 .. S'Last) = "otected" then return Tok_Protected; end if; elsif S (2 .. S'Last) = "ackage" then return Tok_Package; end if; when 'r' => if S (2) = 'a' then if S (3 .. S'Last) = "ise" then return Tok_Raise; elsif S (3 .. S'Last) = "nge" then return Tok_Range; end if; elsif S (2) = 'e' then if S (3 .. S'Last) = "cord" then return Tok_Record; elsif S (3 .. S'Last) = "m" then return Tok_Rem; elsif S (3 .. S'Last) = "names" then return Tok_Renames; elsif S (3 .. S'Last) = "queue" then return Tok_Requeue; elsif S (3 .. S'Last) = "turn" then return Tok_Return; elsif S (3 .. S'Last) = "verse" then return Tok_Reverse; end if; end if; when 's' => if S (2 .. S'Last) = "elect" then return Tok_Select; elsif S (2 .. S'Last) = "eparate" then return Tok_Separate; elsif S (2 .. S'Last) = "ome" then if Prev_Token = Tok_For then return Tok_Some; else return Tok_Identifier; end if; elsif S (2 .. S'Last) = "ubtype" then return Tok_Subtype; elsif S (2 .. S'Last) = "ynchronized" then return Tok_Synchronized; end if; when 't' => if S (2 .. S'Last) = "agged" then return Tok_Tagged; elsif S (2 .. S'Last) = "ask" then return Tok_Task; elsif S (2 .. S'Last) = "erminate" then return Tok_Terminate; elsif S (2 .. S'Last) = "hen" then return Tok_Then; elsif S (2 .. S'Last) = "ype" then return Tok_Type; end if; when 'u' => if S (2 .. S'Last) = "ntil" then return Tok_Until; elsif S (2 .. S'Last) = "se" then return Tok_Use; end if; when 'w' => if S (2 .. S'Last) = "hen" then return Tok_When; elsif S (2 .. S'Last) = "hile" then return Tok_While; elsif S (2 .. S'Last) = "ith" then return Tok_With; end if; when 'x' => if S (2 .. S'Last) = "or" then return Tok_Xor; end if; when others => return Tok_Identifier; end case; return Tok_Identifier; end Get_Token; ---------------------- -- Is_Library_Level -- ---------------------- function Is_Library_Level (Stack : Token_Stack.Simple_Stack) return Boolean is Result : Boolean := True; function Check_Token (Token : Extended_Token) return Boolean; function Check_Token (Token : Extended_Token) return Boolean is begin if Token.Token /= No_Token and then Token.Token /= Tok_Package and then Token.Token /= Tok_Generic then Result := False; return False; end if; return True; end Check_Token; begin Traverse_Stack (Stack, Check_Token'Access); return Result; end Is_Library_Level; ------------------------ -- Analyze_Ada_Source -- ------------------------ SPARK_Keywords : constant Pattern_Matcher := Compile ("^(a(bs|ll|nd|ss(ert|ume))|check|derives|e(lse|nd)|" & "f(or|rom|unction)|global|" & "h(ide|old)|i(n|s)|in(herit|itializes|variant)|" & "main_program|n(ot|ull)|o(r|wn|thers)|post|pre|some|" & "a(ccept|re_interchangeable|s|ssume)|const|div|" & "element|fi(nish|rst)|for_(all|some)|goal|" & "last|may_be_(deduced|deduced_from|" & "replaced_by)|no(n(first|last)|t_in)|o(dd|ut)|" & "p(ending|red|roof)|r(ange|e(al|quires|turn|m))|s(ave|" & "e(quence|t)|ome|qr|t(art|rict_subset_of)|" & "u(bset_of|cc))|t(hen|ype)|update|var|where|xor|" & "fld_.*|upf_.*)$"); -- Regular expression for SPARK keywords procedure Analyze_Ada_Source (Buffer : UTF8_String; Symbols : GNATCOLL.Symbols.Symbol_Table_Access; Indent_Params : Indent_Parameters; Format : Boolean := True; From, To : Natural := 0; Replace : Replace_Text_Callback := null; Constructs : Construct_List_Access := null; Callback : Entity_Callback := null; Indent_Offset : Natural := 0; Case_Exceptions : Casing_Exceptions := No_Casing_Exception; Is_Optional_Keyword : access function (S : String) return Boolean := null) is --------------- -- Constants -- --------------- None : constant := -1; Default_Extended : Extended_Token; pragma Warnings (Off, Default_Extended); -- Use default values to initialize this pseudo constant Indent_Level : Natural renames Indent_Params.Indent_Level; Indent_Continue : Natural renames Indent_Params.Indent_Continue; Indent_Decl : Natural renames Indent_Params.Indent_Decl; Indent_With : constant := 5; Indent_Use : constant := 4; Indent_When : constant := 5; Indent_Comments : Boolean renames Indent_Params.Indent_Comments; Stick_Comments : Boolean renames Indent_Params.Stick_Comments; Stop_On_Blank_Line : constant Boolean := True; Indent_Record : Natural renames Indent_Params.Indent_Record; Indent_Case_Extra : Indent_Style renames Indent_Params.Indent_Case_Extra; Indent_Conditional : Natural renames Indent_Params.Indent_Conditional; Reserved_Casing : Casing_Type renames Indent_Params.Reserved_Casing; Ident_Casing : Casing_Type renames Indent_Params.Ident_Casing; Use_Tabs : Boolean renames Indent_Params.Use_Tabs; Format_Operators : constant Boolean := Format and then Indent_Params.Format_Operators; Align_On_Colons : constant Boolean := Format and then Indent_Params.Align_On_Colons; Align_On_Arrows : constant Boolean := Format and then Indent_Params.Align_On_Arrows; Align_Decl_On_Colon : constant Boolean := Format and then Indent_Params.Align_Decl_On_Colon; Buffer_Last : constant Natural := Buffer'Last; --------------- -- Variables -- --------------- Line_Count : Integer := 1; Str : String (1 .. 1024); Str_Len : Natural := 0; Current : Natural; Prec : Natural := Buffer'First; Start_Of_Line : Natural; Prev_Line : Natural; Num_Spaces : Integer := 0; Continuation_Val : Integer := 0; Indent_Done : Boolean := False; Num_Parens : Integer := 0; Index_Ident : Natural; In_Generic : Boolean := False; Aspect_Clause : Boolean := False; -- True when the current construct is an Ada 2012 aspect clause -- Consider merging with Subprogram_Aspect ??? Aspect_Clause_Sloc : Source_Location; -- source location of start of the current aspect clause, when -- Aspect_Clause is True. type In_Declaration_Kind is (No_Decl, Subprogram_Decl, Subprogram_Aspect, Type_Decl); In_Declaration : In_Declaration_Kind := No_Decl; -- Identifies when we are in a declaration Syntax_Error : Boolean := False; -- Not used for now, but may be useful in the future pragma Unreferenced (Syntax_Error); Comments_Skipped : Boolean := False; Token : Token_Type; Prev_Token : Token_Type := No_Token; Prev_Prev_Token : Token_Type := No_Token; Tokens : Token_Stack.Simple_Stack; Paren_Stack : Construct_Stack.Simple_Stack; Indents : Indent_Stack.Stack.Simple_Stack; Top_Token : Token_Stack.Generic_Type_Access; Casing : Casing_Type := Unchanged; Terminated : Boolean := False; End_Reached : Boolean := False; Last_Replace_Line : Natural := 0; Padding : Integer := 0; Paren_In_Middle : Boolean := False; Is_Parameter : Boolean := False; -- This variable is true if the identifiers picked are parameters, false -- otherwise. Is_Discriminant : Boolean := False; -- This variable is true if the identifiers picked are parameters, false -- otherwise. Right_Assignment : Boolean := False; -- When this is true, we are in a left assignment section procedure Handle_Word_Token (Reserved : Token_Type; Temp : out Extended_Token; Do_Pop : out Integer; Do_Push : out Boolean; Finish : out Boolean); -- Handle a reserved word and computes a token out of it. Results -- reads as follows: -- Temp - the token created -- Do_Pop - number of tokens to be popped out of the token list after -- intendation -- Do_Push - does temp needs to be pushed to the token list after -- indentation? -- Finish - should the analysis be terminated? procedure Handle_Word_Indent (Reserved : Token_Type; Temp : in out Extended_Token); -- Performs indentation after a call to Handle_Word_Token, and before -- tokens are pushed or popped. procedure Finish_Aspect_Clause (P, Line : Natural; Done : out Boolean); -- We are at the end of an aspect clause, so pop the stack, -- call corresponding callbacks. -- Done is set to True if processing should stop after this call. -- P points to the first character in Buffer after the aspect clause. -- Line is the current line. procedure Next_Word (P : in out Natural; L : in out Natural; Terminated : out Boolean; End_Reached : out Boolean); -- Starting at Buffer (P), find the location of the next word -- and set P accordingly. -- Formatting of operators is performed by this procedure. -- The following variables are accessed read-only: -- Buffer, Tokens, Num_Spaces, Indent_Continue -- The following variables are read and modified: -- New_Buffer, Num_Parens, Line_Count, Indents, Indent_Done, -- Prev_Token. -- If the end of the buffer has been reached, set End_Reached to True. -- If parsing should be terminated, set Terminated to True. function End_Of_Word (P : Natural) return Natural; -- Return the end of the word pointed by P function End_Of_Identifier (P : Natural) return Natural; -- Starting from P, scan for the end of the identifier. -- P should be at the first non word character, which means that -- if the identifier does not contain any dot, P - 1 will be returned. procedure Look_For_End_Of_Data_Declaration (Sloc : in out Source_Location); -- Search the first ; character, or the first closing parenthesis, -- skipping nested ones. Intended to go at the end of a variable or -- parameter declaration. procedure Look_For (Sloc : in out Source_Location; Char : Character); -- Search Char in Buffer starting from Sloc. -- Sloc is updated to the first occurrence of Char in Buffer, or -- Buffer_Last if not found. function Look_For (Index : Natural; S : String) return Boolean; -- Return True if Buffer (Index) contains the word S procedure New_Line (Count : in out Natural); pragma Inline (New_Line); -- Increment Count and poll if needed (e.g for graphic events) procedure Do_Indent (Prec : Natural; Line_Count : Natural; Num_Spaces : Integer; Continuation : Boolean := False); -- Perform indentation by inserting spaces in the buffer. -- If Continuation is True, Indent_Continue extra spaces are added. procedure Indent_Function_Return (Prec : Natural); -- Perform special indentation for function return/rename statements function Is_Continuation_Line (Token : Token_Type; Prev_Token : Token_Type; Prev_Prev_Token : Token_Type) return Boolean; -- Return True if we are indenting a continuation line procedure Compute_Indentation (Token : Token_Type; Prev_Token : Token_Type; Prev_Prev_Token : Token_Type; Prec : Natural; Line_Count : Natural; Num_Spaces : Integer); -- Compute proper indentation, taking into account various cases -- of simple/continuation/declaration/... lines. function Next_Char (P : Natural) return Natural; -- Return the next char in buffer. P is the current character pragma Inline (Next_Char); function Prev_Char (P : Natural) return Natural; -- Return the previous char in buffer. P is the current character pragma Inline (Prev_Char); function Compute_Alignment (P : Natural; Stop_On_Blank_Line : Boolean := False; Skip_First_Line : Boolean := True; Align_On : Token_Type := Tok_Colon) return Natural; -- Compute the column number for an alignment on Align_On, starting at P -- Align_On can take one of the following values: -- - Tok_Colon -- - Tok_Arrow -- - Tok_Colon_Equal (not supported yet) procedure Replace_Text (First : Natural; Last : Natural; Line : Natural; Str : String); -- Wrapper for Replace.all, taking (From, To) into account function Call_Callback (Entity : Language_Entity; Sloc_Start : Source_Location; Sloc_End : Source_Location; Partial_Entity : Boolean) return Boolean; -- Call Callback and take into account Aspect_Clause/Aspect_Clause_Sloc -- if needed. -------------------- -- Stack Routines -- -------------------- procedure Pop (Stack : in out Token_Stack.Simple_Stack; Value : out Extended_Token); -- Pop Value on top of Stack procedure Pop (Stack : in out Token_Stack.Simple_Stack); -- Pop Value on top of Stack. Ignore returned value --------------- -- Next_Char -- --------------- function Next_Char (P : Natural) return Natural is begin return UTF8_Next_Char (Buffer, P); end Next_Char; --------------- -- Prev_Char -- --------------- function Prev_Char (P : Natural) return Natural is begin return UTF8_Prev_Char (Buffer, P); end Prev_Char; --------------- -- Do_Indent -- --------------- procedure Do_Indent (Prec : Natural; Line_Count : Natural; Num_Spaces : Integer; Continuation : Boolean := False) is Start : Natural; Indentation : Integer; Index : Natural; begin if Indent_Done or not Format then return; end if; Paren_In_Middle := False; if Prec > Buffer_Last then -- In this case, we've parsed the entire buffer, so just compute -- from the last offset Start := Line_Start (Buffer, Buffer'Last); else Start := Line_Start (Buffer, Prec); end if; Index := Start; loop -- Manual unrolling for efficiency exit when Buffer (Index) /= ' ' and then Buffer (Index) /= ASCII.HT; Index := Index + 1; exit when Buffer (Index) /= ' ' and then Buffer (Index) /= ASCII.HT; Index := Index + 1; exit when Buffer (Index) /= ' ' and then Buffer (Index) /= ASCII.HT; Index := Index + 1; end loop; if Top (Indents).Level = None then Indentation := Num_Spaces + Indent_Offset; else Indentation := Top (Indents).Level; end if; if Continuation then Continuation_Val := Continuation_Val + Indent_Continue; Indentation := Indentation + Continuation_Val; else Continuation_Val := 0; end if; Replace_Text (Start, Index, Line_Count, Blank_Slice (Indentation, Use_Tabs, Tab_Width)); Indent_Done := True; end Do_Indent; ---------------------------- -- Indent_Function_Return -- ---------------------------- procedure Indent_Function_Return (Prec : Natural) is Top_Token : constant Token_Stack.Generic_Type_Access := Top (Tokens); begin -- function A -- return B; -- from Indent_Continue -- function A (....) -- return B; -- function A -- (...) -- return B; if Top_Token.Profile_Start = 0 then Do_Indent (Prec, Line_Count, Num_Spaces + Indent_Continue); else Do_Indent (Prec, Line_Count, Top_Token.Profile_Start - Line_Start (Buffer, Top_Token.Profile_Start) + 1); end if; end Indent_Function_Return; ----------------------- -- Compute_Alignment -- ----------------------- function Compute_Alignment (P : Natural; Stop_On_Blank_Line : Boolean := False; Skip_First_Line : Boolean := True; Align_On : Token_Type := Tok_Colon) return Natural is Alignment : Natural := 0; New_Align : Natural; Found_Align : Boolean := False; J : Natural; Non_Blank : Natural := 0; Length_Ident : Natural := 0; Local_Num_Parens : Natural := 0; begin if Align_On /= Tok_Colon and then Align_On /= Tok_Arrow -- and then Align_On /= Tok_Colon_Equal ??? not supported yet then return 0; end if; if Skip_First_Line then J := Next_Line (Buffer, P); else J := P; end if; Main_Loop : loop exit Main_Loop when J >= Buffer'Last; if Non_Blank = 0 then if not Is_Blank (Buffer (J)) then Non_Blank := J; Length_Ident := 1; end if; else Length_Ident := Length_Ident + 1; end if; exit Main_Loop when Look_For (J, "begin") or else Look_For (J, "case") or else Look_For (J, "end") or else Look_For (J, "package") or else Look_For (J, "protected") or else Look_For (J, "task") or else Look_For (J, "type"); case Buffer (J) is when '"' => if Buffer (J - 1) /= ''' then J := J + 1; Skip_To_Char (Buffer, J, '"'); end if; when '-' => if Buffer (J + 1) = '-' then -- Skip comment J := Next_Line (Buffer, J) - 1; Found_Align := False; Non_Blank := 0; end if; when '(' => if Buffer (J - 1) /= ''' or else Buffer (J + 1) /= ''' then Local_Num_Parens := Local_Num_Parens + 1; end if; when ')' => if Buffer (J - 1) /= ''' then exit Main_Loop when Local_Num_Parens = 0; Local_Num_Parens := Local_Num_Parens - 1; end if; when ':' => if Align_On = Tok_Colon and then Local_Num_Parens = 0 and then Buffer (J - 1) /= ''' and then not Found_Align then Found_Align := True; New_Align := Length_Ident; if Format_Operators and then not Is_Blank (Buffer (J - 1)) then New_Align := New_Align + 1; end if; Alignment := Natural'Max (Alignment, New_Align); end if; when '=' => if Align_On = Tok_Arrow and then Buffer (J + 1) = '>' and then Local_Num_Parens = 0 and then not Found_Align then Found_Align := True; New_Align := Length_Ident + 1; if Format_Operators and then not Is_Blank (Buffer (J - 1)) then -- ??? Format_Operators may add more than a single -- blank inside the expression. New_Align := New_Align + 1; end if; Alignment := Natural'Max (Alignment, New_Align); end if; when ASCII.LF => exit Main_Loop when Stop_On_Blank_Line and then Non_Blank = 0; Found_Align := False; Non_Blank := 0; when others => null; end case; J := Next_Char (J); end loop Main_Loop; return Alignment; end Compute_Alignment; -------------------------- -- Is_Continuation_Line -- -------------------------- function Is_Continuation_Line (Token : Token_Type; Prev_Token : Token_Type; Prev_Prev_Token : Token_Type) return Boolean is Top_Tok : constant Token_Type := Top (Tokens).Token; begin if Aspect_Clause then return True; end if; if Prev_Token = Tok_Is and then In_Generic then return True; end if; if Top_Tok = No_Token then return False; end if; -- Special case for variable (Tok_Colon) or type (only case when -- Tok_Is is passed to this subprogram) declarations. -- In these cases, and if the Indent_Decl preference is set to 0 -- then this is not a continuation line, e.g: -- Var -- : Integer; -- type T -- is new Integer; -- Note that we reuse Indent_Decl for now to avoid introducing -- a new preference. if (Top_Tok = Tok_Colon and then Token = Tok_Colon) or else Token = Tok_Is then return Indent_Decl /= 0; end if; return (Token not in Reserved_Token_Type and then Prev_Token not in Token_Class_No_Cont and then (Prev_Token /= Tok_Arrow or else (not Top (Tokens).In_Declaration and then Top_Tok not in Tok_Case | Tok_When | Tok_Select | Tok_Exception))) or else (Prev_Token = Tok_Is and then (Token in Tok_New | Tok_Access | Tok_Separate | Tok_Abstract or else (Top_Tok = Tok_Subtype and then Token /= Tok_Subtype))) or else Token in Tok_Array | Tok_Of or else (Token = Tok_Not and then (Prev_Token in Tok_And | Tok_Or | Tok_Then | Tok_Else)) or else (Prev_Token = Tok_With and then (Token = Tok_String_Literal or else Token = Tok_Private or else Top_Tok = Tok_Procedure or else Top_Tok = Tok_Function)) or else Prev_Token in Tok_Colon_Equal | Tok_Access | Tok_Of or else (Prev_Token = Tok_Protected and then Prev_Prev_Token = Tok_Access) or else (Prev_Token = Tok_When and then Token = Tok_Others) or else (Prev_Token = Tok_Exit and then Token = Tok_When) or else (Prev_Token = Tok_Null and then Token = Tok_Record) or else (Prev_Prev_Token = Tok_And and then Prev_Token = Tok_Then and then Num_Parens = 0) or else (Prev_Prev_Token = Tok_Or and then Prev_Token = Tok_Else and then Num_Parens = 0) or else (Token = Tok_With and then (Prev_Prev_Token = Tok_Raise or else Top_Tok = Tok_Colon)) or else (Top_Tok = Tok_Type and then (Token = Tok_Null or else Token = Tok_Tagged)) or else (Token = Tok_When and then Top_Tok = Tok_Entry); end Is_Continuation_Line; ------------------------- -- Compute_Indentation -- ------------------------- procedure Compute_Indentation (Token : Token_Type; Prev_Token : Token_Type; Prev_Prev_Token : Token_Type; Prec : Natural; Line_Count : Natural; Num_Spaces : Integer) is Top_Tok : constant Token_Type := Top (Tokens).Token; begin if Indent_Done or not Format then return; end if; if (Prev_Token = Tok_Vertical_Bar or else Prev_Token = Tok_Or) and then Top_Tok = Tok_When then -- Indent multiple-line when statements specially: -- case Foo is -- when A | -- B => -- from Indent_When Do_Indent (Prec, Line_Count, Num_Spaces - Indent_Level + Indent_When); elsif Prev_Token = Tok_Comma and then (Num_Parens = 0 or else Token /= Tok_When) then if Top_Tok = Tok_Declare or else Top_Tok = Tok_Identifier or else Top_Tok = Tok_Record or else Top_Tok = Tok_Case or else Top_Tok = Tok_When then -- Inside a declare block, indent broken lines specially -- declare -- A, -- B : Integer; -- from Indent_Decl Do_Indent (Prec, Line_Count, Num_Spaces + Indent_Decl); elsif Top_Tok = Tok_With then -- Indent continuation lines in with clauses: -- with Package1, -- Package2; -- from Indent_With Do_Indent (Prec, Line_Count, Num_Spaces + Indent_With); elsif Top_Tok = Tok_Use then -- Ditto for use clauses: -- use Package1, -- Package2; -- from Indent_Use Do_Indent (Prec, Line_Count, Num_Spaces + Indent_Use); elsif Num_Parens = 0 then if Continuation_Val > 0 then declare Tmp_Index : Natural := Prec + 1; begin Skip_Blanks (Buffer, Tmp_Index); if Look_For (Tmp_Index, "=>") then -- May happen with aspects: -- procedure G with -- Pre => F, -- Post => F; Continuation_Val := Continuation_Val - Indent_Continue; end if; end; end if; Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); else -- Default case, simply use Num_Spaces Do_Indent (Prec, Line_Count, Num_Spaces); end if; elsif Top (Tokens).Colon_Col /= 0 and then Continuation_Val = 0 and then Num_Parens = 0 and then (Prev_Token = Tok_Colon_Equal or else Prev_Token = Tok_Renames or else Is_Operator (Prev_Token) or else Is_Operator (Token)) then Continuation_Val := Top (Tokens).Colon_Col + 4 - Indent_Continue; Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); elsif Prev_Token = Tok_Ampersand or else Token = Tok_Ampersand then if Continuation_Val > 0 then Continuation_Val := Continuation_Val - Indent_Continue; end if; Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); Continuation_Val := 0; elsif Is_Continuation_Line (Token, Prev_Token, Prev_Prev_Token) then Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); if Is_Operator (Token) then Continuation_Val := 0; end if; elsif Num_Parens > 0 and then (Token in Tok_When | Tok_Vertical_Bar or else Prev_Token = Tok_Arrow or else (Prev_Token = Tok_Then and then Prev_Prev_Token /= Tok_And) or else (Prev_Token = Tok_Else and then Prev_Prev_Token /= Tok_Or)) then -- Handle a bit better Ada 2012 conditional expressions if Token in Tok_When | Tok_Vertical_Bar then Continuation_Val := Indent_Level - Indent_Continue; else Continuation_Val := Continuation_Val + Indent_Level - Indent_Continue; end if; Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); else Do_Indent (Prec, Line_Count, Num_Spaces); end if; end Compute_Indentation; ----------------- -- End_Of_Word -- ----------------- function End_Of_Word (P : Natural) return Natural is Cur : Natural; begin if P >= Buffer_Last then return Buffer_Last; end if; Cur := Next_Char (P); while Cur <= Buffer_Last and then Is_Entity_Letter (UTF8_Get_Char (Buffer (Cur .. Buffer_Last))) loop Cur := Next_Char (Cur); end loop; if Cur > Buffer_Last then return Buffer_Last; else return Cur - 1; end if; end End_Of_Word; ----------------------- -- End_Of_Identifier -- ----------------------- function End_Of_Identifier (P : Natural) return Natural is Tmp : Natural := P; Prev : Natural := P - 1; Start : Natural; New_Lines : Natural; Last_Dot : Natural; begin -- Do not try to go past '.' and line breaks when reformatting, -- this is causing too much trouble for no gain. -- Getting full identifiers is only useful when parsing, not -- when reformatting. if Format then return P - 1; end if; loop New_Lines := 0; while Tmp < Buffer_Last and then Is_Blank (Buffer (Tmp)) loop if Buffer (Tmp) = ASCII.LF then New_Lines := New_Lines + 1; end if; Tmp := Tmp + 1; end loop; if Tmp >= Buffer_Last or else Buffer (Tmp) /= '.' or else Buffer (Tmp + 1) = '.' then return Prev; end if; Last_Dot := Tmp; while Tmp < Buffer_Last loop Tmp := Tmp + 1; if Buffer (Tmp) = ASCII.LF then Compute_Indentation (Token, Prev_Token, Prev_Prev_Token, Tmp - 1, Line_Count, Num_Spaces); New_Lines := New_Lines + 1; end if; exit when not Is_Blank (Buffer (Tmp)); end loop; if Buffer (Tmp) = '"' then -- Case of an operator, e.g System."=", will be handled -- separately for proper highlighting. return Prev; elsif not Is_Entity_Letter (UTF8_Get_Char (Buffer (Tmp .. Buffer_Last))) then return Last_Dot; else Start := Tmp; Tmp := End_Of_Word (Tmp); if Buffer (Start .. Tmp) = "all" -- constructions like sth.procedure often reflect incomplete -- statements, e.g.: -- -- use Ada. -- procedure P is -- -- retreiving these here improve the general tree balance in -- case of incomplete constructs. or else Buffer (Start .. Tmp) = "procedure" or else Buffer (Start .. Tmp) = "function" or else Buffer (Start .. Tmp) = "package" then return Prev; end if; end if; Line_Count := Line_Count + New_Lines; Prev := Tmp; Tmp := Tmp + 1; end loop; end End_Of_Identifier; -------------------------------------- -- Look_For_End_Of_Data_Declaration -- -------------------------------------- procedure Look_For_End_Of_Data_Declaration (Sloc : in out Source_Location) is C : Character; In_Comments : Boolean := False; Paren_Depth : Integer := 0; begin for J in Sloc.Index .. Buffer_Last loop C := Buffer (J); if not In_Comments and then Paren_Depth = 0 and then (C = ';' or else C = ')') then Sloc.Index := J; return; elsif C = '-' and then Buffer (J - 1) = '-' then In_Comments := True; elsif C = ASCII.LF then In_Comments := False; Sloc.Line := Sloc.Line + 1; Sloc.Column := 1; elsif C = '(' then Paren_Depth := Paren_Depth + 1; Sloc.Column := Sloc.Column + 1; elsif C = ')' then Paren_Depth := Paren_Depth - 1; Sloc.Column := Sloc.Column + 1; elsif C /= ASCII.CR then Sloc.Column := Sloc.Column + 1; end if; end loop; end Look_For_End_Of_Data_Declaration; -------------- -- Look_For -- -------------- procedure Look_For (Sloc : in out Source_Location; Char : Character) is C : Character; In_Comments : Boolean := False; begin for J in Sloc.Index .. Buffer_Last loop C := Buffer (J); if not In_Comments and then C = Char then Sloc.Index := J; return; elsif C = '-' and then Buffer (J - 1) = '-' then In_Comments := True; elsif C = ASCII.LF then In_Comments := False; Sloc.Line := Sloc.Line + 1; Sloc.Column := 1; elsif C /= ASCII.CR then Sloc.Column := Sloc.Column + 1; end if; end loop; end Look_For; function Look_For (Index : Natural; S : String) return Boolean is begin return Is_Blank (Buffer (Index - 1)) and then Index + S'Length < Buffer'Last and then To_Lower (Buffer (Index .. Index + S'Length - 1)) = S and then (Buffer (Index + S'Length) = ';' or else Buffer (Index + S'Length) = '-' or else Is_Blank (Buffer (Index + S'Length))); end Look_For; -------------- -- New_Line -- -------------- procedure New_Line (Count : in out Natural) is begin Count := Count + 1; end New_Line; --------- -- Pop -- --------- procedure Pop (Stack : in out Token_Stack.Simple_Stack; Value : out Extended_Token) is Column : Natural; Info : Construct_Access; begin -- Never pop the initial value if Top (Stack).Token = No_Token then Value := Top (Stack).all; return; end if; Token_Stack.Pop (Stack, Value); Top_Token := Token_Stack.Top (Stack); -- Tok_Record will be taken into account by Tok_Type if needed. -- Build next entry of Constructs if Value.Token = Tok_Colon and then Constructs /= null then -- If we are on a Tok_Colon, then we want to assign attibutes to -- all the data that are related to this declaration. declare Current : Construct_Access := Constructs.Current; begin while Current /= null and then Current.Category in Data_Category and then Current.Sloc_Start.Index <= Prec and then Current.Sloc_End.Index >= Prec loop Current.Attributes := Value.Attributes; Current := Current.Prev; end loop; end; elsif Value.Token /= Tok_Record and then Value.Token /= Tok_When and then Value.Token /= Tok_Generic and then Constructs /= null then Column := Prec - Line_Start (Buffer, Prec) + 1; Info := Constructs.Current; Constructs.Current := new Construct_Information; if Constructs.First = null then Constructs.First := Constructs.Current; else Constructs.Current.Prev := Info; Constructs.Current.Next := Info.Next; Info.Next := Constructs.Current; end if; Constructs.Last := Constructs.Current; Constructs.Size := Constructs.Size + 1; Constructs.Current.Visibility := Value.Visibility; Constructs.Current.Attributes := Value.Attributes; Constructs.Current.Is_Generic_Spec := Value.Is_Generic_Param; if Value.Attributes (Ada_Tagged_Attribute) then Constructs.Current.Category := Cat_Class; elsif Value.Attributes (Ada_Record_Attribute) then if Value.Token = Tok_Case then -- A case statement inside a record Constructs.Current.Category := Cat_Case_Inside_Record; else Constructs.Current.Category := Cat_Structure; end if; else case Value.Token is when Tok_Package => Constructs.Current.Category := Cat_Package; when Tok_Procedure => Constructs.Current.Category := Cat_Procedure; when Tok_Function => Constructs.Current.Category := Cat_Function; when Tok_Task => Constructs.Current.Category := Cat_Task; when Tok_Protected => Constructs.Current.Category := Cat_Protected; when Tok_Entry => Constructs.Current.Category := Cat_Entry; when Tok_Type => Constructs.Current.Category := Cat_Type; when Tok_Subtype => Constructs.Current.Category := Cat_Subtype; when Tok_For => Constructs.Current.Category := Cat_Representation_Clause; when Tok_Identifier => if Is_Library_Level (Stack) then Constructs.Current.Category := Cat_Variable; elsif Value.Variable_Kind = Parameter_Kind then Constructs.Current.Category := Cat_Parameter; elsif Value.Variable_Kind = Discriminant_Kind then Constructs.Current.Category := Cat_Discriminant; elsif Value.Is_In_Type_Definition then if Top (Stack).Type_Declaration or else Top (Stack).Protected_Declaration or else Top (Stack).Attributes (Ada_Record_Attribute) then Constructs.Current.Category := Cat_Field; else Constructs.Current.Category := Cat_Literal; end if; else Constructs.Current.Category := Cat_Local_Variable; end if; when Tok_With => Constructs.Current.Category := Cat_With; when Tok_Use => Constructs.Current.Category := Cat_Use; when Tok_Loop => Constructs.Current.Category := Cat_Loop_Statement; when Tok_Then => Constructs.Current.Category := Cat_If_Statement; when Tok_Case => Constructs.Current.Category := Cat_Case_Statement; when Tok_Select => Constructs.Current.Category := Cat_Select_Statement; when Tok_Accept | Tok_Do => Constructs.Current.Category := Cat_Accept_Statement; when Tok_Declare => Constructs.Current.Category := Cat_Declare_Block; when Tok_Begin => Constructs.Current.Category := Cat_Simple_Block; when Tok_Return => Constructs.Current.Category := Cat_Return_Block; when Tok_Exception => Constructs.Current.Category := Cat_Exception_Handler; when Tok_Pragma => Constructs.Current.Category := Cat_Pragma; when Tok_Arrow => Constructs.Current.Category := Cat_Aspect; when others => Constructs.Current.Category := Cat_Unknown; end case; end if; if Value.Ident_Len > 0 then Constructs.Current.Name := Symbols.Find (Value.Identifier (1 .. Value.Ident_Len)); Constructs.Current.Sloc_Entity := Value.Sloc_Name; end if; if Value.Profile_Start /= 0 then Constructs.Current.Profile := new String' (Buffer (Value.Profile_Start .. Value.Profile_End)); end if; Constructs.Current.Sloc_Start := Value.Sloc; if Comments_Skipped then Constructs.Current.Sloc_End := (Prev_Line, Column, Prec); else Constructs.Current.Sloc_End := (Line_Count, Column, Prec); end if; case Constructs.Current.Category is when Cat_Parameter | Cat_Discriminant => -- Adjust the Sloc_End to the next semicolon for enclosing -- entities and variable declarations, or next closing -- parenthesis Look_For_End_Of_Data_Declaration (Constructs.Current.Sloc_End); when Cat_Variable | Cat_Local_Variable | Cat_Field | Cat_Declare_Block | Cat_Simple_Block | Cat_Type | Cat_Subtype | Namespace_Category | Subprogram_Category | Cat_Pragma => -- Adjust the Sloc_End to the next semicolon for enclosing -- entities and variable declarations. In case if loops, -- adjust the end of the source location to the end of the -- identifier. if Prev_Token /= Tok_For then Look_For (Constructs.Current.Sloc_End, ';'); else Constructs.Current.Sloc_End.Column := Constructs.Current.Sloc_End.Column + Value.Ident_Len - 1; Constructs.Current.Sloc_End.Index := Constructs.Current.Sloc_End.Index + Value.Ident_Len - 1; end if; when others => null; end case; Constructs.Current.Is_Declaration := In_Declaration in Subprogram_Decl .. Subprogram_Aspect or else Value.Type_Declaration or else Value.Package_Declaration or else Value.Protected_Declaration; end if; end Pop; procedure Pop (Stack : in out Token_Stack.Simple_Stack) is Value : Extended_Token; begin Pop (Stack, Value); end Pop; -------------------------- -- Finish_Aspect_Clause -- -------------------------- procedure Finish_Aspect_Clause (P, Line : Natural; Done : out Boolean) is Prec_Saved : constant Natural := Prec; begin Aspect_Clause := False; Done := False; -- Pop aspect clause -- Set Prec so that Pop will use the proper index/column Prec := Prev_Char (P); Pop (Tokens); if Callback /= null then Start_Of_Line := Line_Start (Buffer, Prec); Done := Callback (Aspect_Text, Aspect_Clause_Sloc, (Line, Prec - Start_Of_Line + 1, Prec), False); end if; Prec := Prec_Saved; end Finish_Aspect_Clause; ----------------------- -- Handle_Word_Token -- ----------------------- procedure Handle_Word_Token (Reserved : Token_Type; Temp : out Extended_Token; Do_Pop : out Integer; Do_Push : out Boolean; Finish : out Boolean) is Top_Token : Token_Stack.Generic_Type_Access; Start_Of_Line : Natural; Index_Next : Natural; Tmp_Index : Natural; procedure Adjust_Block_Column; -- Adjust status column of declare block to take into -- account a label at start of the line by using the first -- non blank character on the line. ------------------------- -- Adjust_Block_Column -- ------------------------- procedure Adjust_Block_Column is begin if Prev_Token = Tok_Colon then Tmp_Index := Start_Of_Line; Skip_Blanks (Buffer, Tmp_Index); Temp.Sloc.Column := Tmp_Index - Start_Of_Line + 1; Temp.Sloc.Index := Tmp_Index; end if; end Adjust_Block_Column; begin Do_Push := False; Do_Pop := 0; Finish := False; if Reserved = Tok_Is and then Aspect_Clause then Finish_Aspect_Clause (Prec, Line_Count, Done => Finish); if Finish then return; end if; end if; Top_Token := Top (Tokens); Temp := (others => <>); Temp.Token := Reserved; Start_Of_Line := Line_Start (Buffer, Prec); Temp.Sloc.Line := Line_Count; Temp.Sloc.Column := Prec - Start_Of_Line + 1; Temp.Sloc.Index := Prec; Temp.Visibility := Top_Token.Visibility_Section; if Callback /= null then Finish := Call_Callback (Keyword_Text, Temp.Sloc, (Line_Count, Current - Start_Of_Line + 1, Current), False); if Finish then return; end if; end if; -- Computes Tok_Token.Type_Att if not Right_Assignment then case Reserved is when Tok_Abstract => Top_Token.Attributes (Ada_Abstract_Attribute) := True; when Tok_Access => Top_Token.Attributes (Ada_Access_Attribute) := True; when Tok_Aliased => Top_Token.Attributes (Ada_Aliased_Attribute) := True; when Tok_Array => Top_Token.Attributes (Ada_Array_Attribute) := True; when Tok_Colon_Equal => Top_Token.Attributes (Ada_Assign_Attribute) := True; when Tok_Constant => Top_Token.Attributes (Ada_Constant_Attribute) := True; when Tok_Delta => Top_Token.Attributes (Ada_Delta_Attribute) := True; when Tok_Digits => Top_Token.Attributes (Ada_Digits_Attribute) := True; when Tok_Range => Top_Token.Attributes (Ada_Range_Attribute) := True; when Tok_Mod => Top_Token.Attributes (Ada_Mod_Attribute) := True; when Tok_New => Top_Token.Attributes (Ada_New_Attribute) := True; when Tok_Not => Top_Token.Attributes (Ada_Not_Attribute) := True; when Tok_Null => Top_Token.Attributes (Ada_Null_Attribute) := True; when Tok_Out => Top_Token.Attributes (Ada_Out_Attribute) := True; when Tok_Tagged => Top_Token.Attributes (Ada_Tagged_Attribute) := True; when Tok_In => Top_Token.Attributes (Ada_In_Attribute) := True; when Tok_Interface => Top_Token.Attributes (Ada_Interface_Attribute) := True; when Tok_Record => if Prev_Token /= Tok_Null or else Prev_Prev_Token = Tok_Is then -- Do not take aggregates like (null record) as a record -- definition but we still want "is null record" to be -- properly reported as record type. Top_Token.Attributes (Ada_Record_Attribute) := True; end if; when Tok_Renames => Top_Token.Attributes (Ada_Renames_Attribute) := True; when others => null; end case; end if; -- Computes the end of the profile case Top_Token.Token is when Tok_Procedure | Tok_Function | Tok_Entry => if Reserved = Tok_Is then Top_Token.In_Entity_Profile := False; end if; when Tok_Type => if Reserved = Tok_Record then Top_Token.In_Entity_Profile := False; -- type N is new O with record ... -- type N is new O with null record ... if Prev_Token = Tok_With or (Prev_Prev_Token = Tok_With and Prev_Token = Tok_Null) then Top_Token.Attributes (Ada_Tagged_Attribute) := True; end if; -- type N is new O with private; elsif Prev_Token = Tok_With and Reserved = Tok_Private then Top_Token.Attributes (Ada_Tagged_Attribute) := True; end if; when others => null; end case; -- Note: the order of the following conditions is important if Reserved = Tok_Body then if Top_Token.Token = Tok_Package then Top_Token.Package_Declaration := False; elsif Top_Token.Token = Tok_Protected then Top_Token.Protected_Declaration := False; end if; elsif Prev_Token /= Tok_End and then Reserved = Tok_Case and then Num_Parens = 0 then Temp.Visibility_Section := Top_Token.Visibility_Section; -- If the case is in a type declaration (e.g. protected), then -- mark itself as a type declaration so we will extract the -- corresponding fields. if Top_Token.Type_Declaration then Temp.Type_Declaration := True; end if; -- If the case is in a record, then mark itself as a record so we -- will extract the corresponding fields. if Top_Token.Attributes (Ada_Record_Attribute) then Temp.Attributes (Ada_Record_Attribute) := True; end if; Do_Push := True; elsif Prev_Token /= Tok_End and then ((Reserved = Tok_If and then Num_Parens = 0) or else Reserved = Tok_For or else Reserved = Tok_While or else Reserved = Tok_Accept) then Do_Push := True; elsif Reserved = Tok_Renames then if not Top_Token.In_Declaration and then (Top_Token.Token = Tok_Function or else Top_Token.Token = Tok_Procedure or else Top_Token.Token = Tok_Package) then -- Terminate current subprogram declaration, e.g: -- procedure ... renames ...; Do_Pop := Do_Pop + 1; end if; elsif Prev_Token = Tok_Is and then Top_Token.Token /= Tok_Type and then (Top_Token.Token not in Tok_Task | Tok_Protected or else Reserved = Tok_Separate) and then Top_Token.Token /= Tok_Subtype and then (Reserved = Tok_New or else Reserved = Tok_In or else Reserved = Tok_Abstract or else Reserved = Tok_Separate or else (Reserved = Tok_Null and then not In_Generic and then Top_Token.Token = Tok_Procedure)) then In_Declaration := Subprogram_Decl; elsif Reserved = Tok_Pragma then Num_Parens := 0; Do_Push := True; elsif Reserved = Tok_Function or else Reserved = Tok_Procedure or else Reserved = Tok_Package or else Reserved = Tok_Task or else Reserved = Tok_Protected or else Reserved = Tok_Entry then if not In_Generic and then (Top_Token.Token = Tok_With or else Top_Token.Token = Tok_Use) then -- In this case, we're probably parsing code in the process -- of being written, and the use or with clause is not finished -- yet. Close the construct anyway, so that the tree stays -- correctly balanced. Do_Pop := Do_Pop + 1; end if; if Reserved = Tok_Package then Temp.Package_Declaration := True; elsif Reserved = Tok_Protected then Temp.Protected_Declaration := True; elsif (Top_Token.Token = Tok_Type and then (Prev_Token /= Tok_Access or else Prev_Prev_Token = Tok_Is)) or else (Prev_Token /= Tok_Access and then Prev_Token /= Tok_Protected and then Prev_Token /= Tok_Constant) then -- take into account the following: -- type P is access procedure; -- -- and ignore the following cases: -- type P is array () of access procedure; -- procedure P (X : access procedure); In_Declaration := Subprogram_Decl; Num_Parens := 0; end if; if Prev_Token = Tok_Overriding or else (Token = Tok_Package and then Prev_Token = Tok_Private) or else (Token in Tok_Procedure | Tok_Function and then Prev_Token = Tok_With) then -- Adjust column of subprogram to take into account possible -- [not] overriding at start of the line by using the -- first non blank character on the line. -- Ditto for "private package xxx is" and "with procedure xx" Tmp_Index := Start_Of_Line; Skip_Blanks (Buffer, Tmp_Index); Temp.Sloc.Column := Tmp_Index - Start_Of_Line + 1; Temp.Sloc.Index := Tmp_Index; end if; if Prev_Token = Tok_Access or else Prev_Token = Tok_Protected then -- Ada 2005 anonymous access subprogram parameter: -- procedure P (F : access [protected] procedure); null; elsif Top_Token.Token = Tok_Type then null; else if not Top_Token.In_Declaration and then (Top_Token.Token = Tok_Function or else Top_Token.Token = Tok_Procedure) then -- There was a function declaration, e.g: -- -- procedure xxx (); -- procedure ... Do_Pop := Do_Pop + 1; end if; if Top_Token.Token = Tok_Generic and then Prev_Token /= Tok_With then -- Pops the temporary generic token and replace it by -- the actual subprogram or package Temp.Sloc := Top_Token.Sloc; Temp.Attributes (Ada_Generic_Attribute) := True; Do_Pop := Do_Pop + 1; end if; Do_Push := True; end if; elsif Reserved = Tok_End or else (Reserved = Tok_Elsif and then Num_Parens = 0) or else (Reserved = Tok_Null and then Prev_Token = Tok_Is and then not In_Generic and then Top_Token.Token = Tok_Procedure) then -- unindent after end of elsif, e.g: -- -- if xxx then -- xxx -- elsif xxx then -- xxx -- end if; if Reserved = Tok_End then case Top_Token.Token is when Tok_When | Tok_Exception => -- End of subprogram Do_Pop := Do_Pop + 1; when others => null; end case; Do_Pop := Do_Pop + 1; elsif Top_Token.Token = Tok_Then and then Reserved = Tok_Elsif then Top_Token.Token := Tok_If; end if; elsif Reserved = Tok_With then if not In_Generic then if Top_Token.Token = Tok_With or else Top_Token.Token = Tok_Use then -- Incomplete clause, pops to preserve tree balance Do_Pop := Do_Pop + 1; end if; if Top_Token.Token = No_Token then Do_Push := True; end if; end if; if Prev_Prev_Token not in Tok_Raise | Tok_Left_Paren -- Exclude Tok_Raise: raise CE with "string"; -- Ditto for Tok_Left_Paren: X := (Parent with Field => null); and then ((Top_Token.Token in Tok_Type | Tok_Subtype | Tok_Function | Tok_Procedure | Tok_Colon and then Num_Parens = 0) or else (Top_Token.Token in Tok_Task | Tok_Protected and then (Prev_Prev_Token in Tok_Protected | Tok_Task | Tok_Type or else Prev_Token = Tok_Right_Paren)) or else (Top_Token.Token = No_Token and then Prev_Token not in Tok_Semicolon | Tok_Limited | Tok_Private | No_Token)) then -- Recognize aspect clauses, even in the case of a partial -- buffer. But do not confuse with a 'with' clause. Tmp_Index := Current + 1; Skip_Blanks (Buffer, Tmp_Index); if not Look_For (Tmp_Index, "record") and then not Look_For (Tmp_Index, "null") and then not Look_For (Tmp_Index, "private") then Aspect_Clause := True; Aspect_Clause_Sloc := (Line_Count, Current + 1 - Start_Of_Line + 1, Current + 1); Do_Push := True; Temp.Token := Tok_Arrow; -- Arrow is used for aspects Temp.Sloc := Aspect_Clause_Sloc; end if; end if; elsif Reserved = Tok_Use and then (Top_Token.Token = No_Token or else (Top_Token.Token /= Tok_For and then Top_Token.Token /= Tok_Record)) then if Top_Token.Token = Tok_With or else Top_Token.Token = Tok_Use then -- Incomplete clause, pops to preserve tree balance Do_Pop := Do_Pop + 1; end if; Do_Push := True; elsif Reserved = Tok_Is or else Reserved = Tok_Declare or else Reserved = Tok_Begin or else Reserved = Tok_Do or else (Prev_Token /= Tok_Or and then Reserved = Tok_Else and then Num_Parens = 0) or else (Prev_Token /= Tok_And and then Reserved = Tok_Then and then Num_Parens = 0) or else (Prev_Token /= Tok_End and then Reserved = Tok_Select) or else (Reserved = Tok_Or and then (Top_Token.Token = Tok_Select or else Top_Token.Token = Tok_When)) or else (Prev_Token /= Tok_End and then Reserved = Tok_Loop) or else (Prev_Token /= Tok_End and then Prev_Token /= Tok_Null and then Reserved = Tok_Record) or else ((Top_Token.Token = Tok_Exception or else Top_Token.Token = Tok_Case or else Top_Token.Token = Tok_Select) and then Reserved = Tok_When and then Prev_Token /= Tok_Exit and then Prev_Prev_Token /= Tok_Exit) or else (Top_Token.In_Declaration and then Reserved = Tok_Private and then (Prev_Token /= Tok_Is or else Top_Token.Token = Tok_Package) and then Prev_Token /= Tok_Limited and then Prev_Token /= Tok_With) then if Reserved = Tok_Do then if Top_Token.Token = Tok_Accept then Top_Token.Token := Tok_Do; else -- Extended return statement: -- return X : xxx do -- ... -- end; Temp.Token := Tok_Return; Do_Push := True; end if; end if; if Reserved = Tok_Select then Do_Push := True; elsif Top_Token.Token = Tok_If and then Reserved = Tok_Then then -- Notify that we're past the 'if' condition Top_Token.Token := Tok_Then; elsif Reserved = Tok_Loop then if Top_Token.Token = Tok_While or else Top_Token.Token = Tok_For then -- Replace token since this is a loop construct -- but keep the original source location. Top_Token.Token := Tok_Loop; else Do_Push := True; end if; elsif Reserved = Tok_Declare then if Align_On_Colons then Temp.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; Temp.In_Declaration := True; Adjust_Block_Column; Do_Push := True; elsif Reserved = Tok_Is then case Top_Token.Token is when Tok_Case | Tok_When | Tok_Type | Tok_Subtype => Top_Token.Type_Definition_Section := True; when Tok_Task | Tok_Protected => if Top_Token.Token = Tok_Protected then Top_Token.Type_Definition_Section := True; end if; if Align_On_Colons then Top_Token.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; Top_Token.In_Declaration := True; when others => if Top_Token.Token = Tok_Function then Index_Next := Current + 1; -- Skip blanks on current line while Index_Next < Buffer'Last and then Buffer (Index_Next) /= ASCII.LF and then (Buffer (Index_Next) = ' ' or else Buffer (Index_Next) = ASCII.HT) loop Index_Next := Index_Next + 1; end loop; end if; if Align_On_Colons then Top_Token.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; Top_Token.In_Declaration := True; end case; elsif Reserved = Tok_Begin then if Top_Token.In_Declaration then Num_Spaces := Num_Spaces - Indent_Level; Top_Token.Align_Colon := 0; Top_Token.In_Declaration := False; else Adjust_Block_Column; Do_Push := True; end if; elsif Reserved = Tok_Record then -- Is "record" the first keyword on the line ? -- If True, we are in a case like: -- type A is -- record -- from Indent_Record -- null; -- end record; if Top_Token.Token = Tok_Type then Top_Token.Attributes (Ada_Record_Attribute) := True; Temp.Attributes (Ada_Record_Attribute) := True; Temp.Type_Definition_Section := Top_Token.Type_Definition_Section; end if; Do_Push := True; elsif Reserved = Tok_Else or else (Top_Token.Token = Tok_Select and then Reserved = Tok_Then) or else (Reserved = Tok_When and then Num_Parens = 0) or else Reserved = Tok_Or or else Reserved = Tok_Private then if (Reserved = Tok_Or or else Reserved = Tok_Else) and then Top_Token.Token = Tok_When then Do_Pop := Do_Pop + 1; Top_Token := Top (Tokens); end if; if Reserved = Tok_Private then Top_Token.Visibility_Section := Visibility_Private; end if; if Reserved = Tok_When then Do_Push := True; end if; end if; elsif (Reserved = Tok_Type and then Prev_Token /= Tok_With -- with type and then Prev_Token /= Tok_Use -- use type and then (Prev_Prev_Token /= Tok_Use or Prev_Token /= Tok_All)) -- use all type or else Reserved = Tok_Subtype then -- Entering a type declaration/definition if Prev_Token = Tok_Task -- task type or else Prev_Token = Tok_Protected -- protected type then Top_Token.Type_Declaration := True; else Do_Push := True; end if; In_Declaration := Type_Decl; elsif Reserved = Tok_Exception then if Top_Token.Token /= Tok_Colon then Do_Push := True; end if; elsif Reserved = Tok_Generic then Temp.In_Declaration := True; Do_Push := True; end if; exception when Token_Stack.Stack_Empty => Syntax_Error := True; end Handle_Word_Token; ------------------------ -- Handle_Word_Indent -- ------------------------ procedure Handle_Word_Indent (Reserved : Token_Type; Temp : in out Extended_Token) is Top_Token : Token_Stack.Generic_Type_Access := Top (Tokens); Start_Of_Line : Natural; Index_Next : Natural; Tmp_Index : Natural; begin Top_Token := Top (Tokens); Start_Of_Line := Line_Start (Buffer, Prec); -- Note: the order of the following conditions is important if Prev_Token /= Tok_End and then Reserved = Tok_Case then if Align_On_Colons and then Top_Token.Token = Tok_Record then Temp.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; Do_Indent (Prec, Line_Count, Num_Spaces); if Prev_Token /= Tok_Left_Paren and then Indent_Case_Extra = RM_Style then Temp.Extra_Indent := True; Num_Spaces := Num_Spaces + Indent_Level; end if; elsif Reserved = Tok_Abort then if Top_Token.Token = Tok_Select and then Prev_Token = Tok_Then then -- Temporarily unindent if we have a 'then abort' construct, -- with 'abort' on its own line, e.g: -- select -- Foo; -- then -- abort -- Bar; Do_Indent (Prec, Line_Count, Num_Spaces - Indent_Level, Continuation => True); end if; elsif Reserved = Tok_Renames then if In_Declaration = Subprogram_Decl then -- function A (....) -- renames B; Indent_Function_Return (Prec); end if; elsif Prev_Token = Tok_Is and then not In_Generic and then Top_Token.Token /= Tok_Type and then (Top_Token.Token not in Tok_Task | Tok_Protected or else Reserved = Tok_Separate) and then Top_Token.Token /= Tok_Subtype and then (Reserved = Tok_New or else Reserved = Tok_In or else Reserved = Tok_Abstract or else Reserved = Tok_Separate or else (Reserved = Tok_Null and then not In_Generic and then Top_Token.Token = Tok_Procedure)) then -- Handle indentation of e.g. -- -- function Abstract_Func -- return String -- is abstract; if Top_Token.Token = Tok_Function and then Reserved /= Tok_New and then (Reserved = Tok_Abstract or else Reserved = Tok_Separate or else Start_Of_Line /= Line_Start (Buffer, Top_Token.Sloc.Index)) then Indent_Function_Return (Prec); Num_Spaces := Num_Spaces + Indent_Level; end if; -- Unindent since this is a declaration, e.g: -- package ... is new ...; -- function ... is abstract; -- function ... is separate; -- procedure ... is null; -- Or a Gnatdist main procedure declaration : -- procedure ... is in ...; Num_Spaces := Num_Spaces - Indent_Level; if Num_Spaces < 0 then Num_Spaces := 0; Syntax_Error := True; end if; elsif (Reserved in Tok_Function | Tok_Procedure | Tok_Protected and then Top_Token.Token /= Tok_Type) or else (Reserved in Tok_Package | Tok_Task | Tok_Entry and then Prev_Token /= Tok_Is) then if In_Generic and then Prev_Token not in Tok_With | Tok_Access then -- unindent after a generic declaration, e.g: -- -- generic -- with procedure xxx; -- with function xxx; -- with package xxx; -- package xxx is Num_Spaces := Num_Spaces - Indent_Level; if Num_Spaces < 0 then Num_Spaces := 0; Syntax_Error := True; end if; end if; elsif Reserved = Tok_Return and then In_Declaration = Subprogram_Decl then Indent_Function_Return (Prec); elsif Reserved = Tok_End or else (Reserved = Tok_Elsif and then Num_Parens = 0) or else (Reserved = Tok_Null and then not In_Generic and then Prev_Token = Tok_Is and then Top_Token.Token = Tok_Procedure) then -- unindent after end of elsif, e.g: -- -- if xxx then -- xxx -- elsif xxx then -- xxx -- end if; if Reserved = Tok_End then case Top_Token.Token is when Tok_When | Tok_Exception => -- Undo additional level of indentation, as in: -- ... -- exception -- when others => -- null; -- end; Num_Spaces := Num_Spaces - Indent_Level; when Tok_Case => if Top_Token.Extra_Indent then Num_Spaces := Num_Spaces - Indent_Level; end if; when Tok_Record => -- If the "record" keyword was on its own line if Top_Token.Extra_Indent then Do_Indent (Prec, Line_Count, Num_Spaces - Indent_Level); Num_Spaces := Num_Spaces - Indent_Record; end if; when others => null; end case; end if; Num_Spaces := Num_Spaces - Indent_Level; if Num_Spaces < 0 then Num_Spaces := 0; Syntax_Error := True; end if; elsif (Reserved = Tok_Is and then Num_Parens = 0 and then not In_Generic) or else Reserved in Tok_Declare | Tok_Begin | Tok_Do or else (Prev_Token /= Tok_Or and then Reserved = Tok_Else and then Num_Parens = 0) or else (Prev_Token /= Tok_And and then Reserved = Tok_Then and then Num_Parens = 0) or else (Prev_Token /= Tok_End and then Reserved = Tok_Select) or else (Reserved = Tok_Or and then (Top_Token.Token = Tok_Select or else Top_Token.Token = Tok_When)) or else (Prev_Token /= Tok_End and then Reserved = Tok_Loop) or else (Prev_Token /= Tok_End and then Prev_Token /= Tok_Null and then Reserved = Tok_Record) or else ((Top_Token.Token = Tok_Exception or else Top_Token.Token = Tok_Case or else Top_Token.Token = Tok_Select) and then Reserved = Tok_When and then Prev_Token /= Tok_Exit and then Prev_Prev_Token /= Tok_Exit) or else (Top_Token.In_Declaration and then Reserved = Tok_Private and then (Prev_Token /= Tok_Is or else Top_Token.Token = Tok_Package) and then Prev_Token /= Tok_Limited and then Prev_Token /= Tok_With) then -- unindent for this reserved word, and then indent again, e.g: -- -- procedure xxx is -- ... -- begin <-- -- ... if Reserved = Tok_Declare then if Align_On_Colons then Temp.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; if Prev_Token = Tok_Colon then -- Adjust status column of declare block to take into -- account a label at start of the line by using the first -- non blank character on the line. Tmp_Index := Start_Of_Line; Skip_Blanks (Buffer, Tmp_Index); Temp.Sloc.Column := Tmp_Index - Start_Of_Line + 1; Temp.Sloc.Index := Tmp_Index; end if; elsif Reserved = Tok_Is then if not In_Generic then case Top_Token.Token is when Tok_Case | Tok_When | Tok_Type | Tok_Subtype => null; when Tok_Task | Tok_Protected => if Align_On_Colons then Top_Token.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; when others => if Top_Token.Token = Tok_Function then Index_Next := Current + 1; -- Skip blanks on current line while Index_Next < Buffer'Last and then Buffer (Index_Next) /= ASCII.LF and then (Buffer (Index_Next) = ' ' or else Buffer (Index_Next) = ASCII.HT) loop Index_Next := Index_Next + 1; end loop; end if; if Align_On_Colons then Top_Token.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; end case; end if; elsif Reserved = Tok_Begin then if Top_Token.In_Declaration then Num_Spaces := Num_Spaces - Indent_Level; Top_Token.Align_Colon := 0; Top_Token.In_Declaration := False; end if; elsif Reserved = Tok_Record then -- Is "record" the first keyword on the line ? -- If True, we are in a case like: -- type A is -- record -- from Indent_Record -- null; -- end record; if not Indent_Done then Temp.Extra_Indent := True; Num_Spaces := Num_Spaces + Indent_Record; Do_Indent (Prec, Line_Count, Num_Spaces); end if; if Top_Token.Token = Tok_Type then Num_Spaces := Num_Spaces + Indent_Level; if Align_On_Colons then Temp.Align_Colon := Compute_Alignment (Prec, Stop_On_Blank_Line => Stop_On_Blank_Line); end if; end if; elsif Reserved = Tok_Else or else (Top_Token.Token = Tok_Select and then Reserved = Tok_Then) or else (Reserved = Tok_When and then Num_Parens = 0) or else Reserved = Tok_Or or else Reserved = Tok_Private then if (Reserved = Tok_Or or else Reserved = Tok_Else) and then Top_Token.Token = Tok_When and then (Next (Tokens) = null or else Next (Tokens).Token /= Tok_Case) then Num_Spaces := Num_Spaces - Indent_Level; end if; if Reserved /= Tok_When or else Top_Token.Token /= Tok_Select then Num_Spaces := Num_Spaces - Indent_Level; end if; if Reserved = Tok_When then if Top_Token.Token = Tok_Case then if Indent_Case_Extra = Automatic and then not Top_Token.Extra_Indent and then Prec - Start_Of_Line > Num_Spaces then Top_Token.Extra_Indent := True; Num_Spaces := Num_Spaces + Indent_Level; end if; end if; end if; end if; if Num_Spaces < 0 then Num_Spaces := 0; Syntax_Error := True; end if; if Top_Token.Token /= Tok_Type and then Top_Token.Token /= Tok_Subtype and then (Token /= Tok_Is or else In_Generic or else Top_Token.Token /= Tok_Function or else not (Look_For (Index_Next, "abstract") or else Look_For (Index_Next, "separate"))) -- 'is abstract|separate' will be indented when handling -- 'abstract|separate' for functions then Do_Indent (Prec, Line_Count, Num_Spaces); Num_Spaces := Num_Spaces + Indent_Level; end if; elsif Reserved = Tok_Or or else Reserved = Tok_And or else Reserved = Tok_Xor then -- "and then", "or else", "and", "or" and "xor" should get an -- extra indentation on line start, e.g: -- if ... -- and then ... if Top (Indents).Level = None then if Continuation_Val > 0 then if Top (Tokens).Colon_Col = 0 then Continuation_Val := Continuation_Val - Indent_Continue; else Continuation_Val := Continuation_Val + Indent_Continue; end if; end if; Do_Indent (Prec, Line_Count, Num_Spaces, Continuation => True); else Do_Indent (Prec, Line_Count, Num_Spaces); end if; elsif Reserved = Tok_Generic then -- Indent before a generic entity, e.g: -- -- generic -- type ...; Do_Indent (Prec, Line_Count, Num_Spaces); Num_Spaces := Num_Spaces + Indent_Level; elsif Reserved = Tok_Exception then if Top_Token.Token /= Tok_Colon then Num_Spaces := Num_Spaces - Indent_Level; Do_Indent (Prec, Line_Count, Num_Spaces); Num_Spaces := Num_Spaces + 2 * Indent_Level; end if; end if; exception when Token_Stack.Stack_Empty => Syntax_Error := True; end Handle_Word_Indent; --------------- -- Next_Word -- --------------- procedure Next_Word (P : in out Natural; L : in out Natural; Terminated : out Boolean; End_Reached : out Boolean) is Comma : String := ", "; Spaces : String := " "; End_Of_Line : Natural; Start_Of_Line : Natural; Long : Natural; First : Natural; Last : Natural; Offs : Natural; Align : Natural; Adjust : Natural; Insert_Spaces : Boolean; Char : Character; Prev_Prev_Token : Token_Type := No_Token; Prev3_Token : Token_Type; Local_Top_Token : Token_Stack.Generic_Type_Access; Tmp : Boolean; Token_Found : Boolean; Recompute_Align : Boolean; procedure Close_Parenthesis; -- Current buffer contents is a closed parenthesis, -- reset stacks and states accordingly. procedure Handle_Arrow; -- Current buffer contents is an arrow colon, handle it. -- In particular, align arrows in statements. procedure Handle_Colon; -- Current buffer contents is a colon, handle it. -- In particular, align colons in declarations. procedure Handle_Two_Chars (Second_Char : Character); -- Handle a two char operator, whose second char is Second_Char procedure Preprocessor_Directive; -- Handle preprocessor directive. -- Assume that Buffer (P) = '#' procedure Skip_Blank_Lines; -- Skip empty lines procedure Skip_Comments; -- Skip comment & blank lines procedure Pop_And_Set_Local (Stack : in out Token_Stack.Simple_Stack); -- Pops the last element of the stack and set Local_Top_Token -- to the top element, null if the stack is empty. ----------------------- -- Close_Parenthesis -- ----------------------- procedure Close_Parenthesis is begin if not Is_Empty (Paren_Stack) then Pop (Paren_Stack); end if; if Is_Empty (Indents) or else Top (Indents).Level = None then -- Syntax error null; else if not Indent_Done then -- Adjust indentation level for closing parenthesis at the -- beginning of a line, e.g: -- -- (x, -- y -- ); <- Top (Indents).Level := Top (Indents).Level - 1; Do_Indent (P, L, Num_Spaces); Continuation_Val := Top (Indents).Continuation_Val; end if; Num_Parens := Num_Parens - 1; Pop (Indents); Local_Top_Token := Top (Tokens); if Num_Parens = 0 then Is_Parameter := False; Is_Discriminant := False; Right_Assignment := False; Paren_In_Middle := False; if Local_Top_Token.Token in Token_Class_Declk and then Local_Top_Token.Profile_End = 0 and then In_Declaration = Subprogram_Decl then Local_Top_Token.Profile_End := P; Local_Top_Token.Align_Colon := 0; end if; end if; end if; end Close_Parenthesis; ------------------ -- Handle_Colon -- ------------------ procedure Handle_Colon is Align_Colon : Natural := 0; Non_Blank : Natural; Offset_Align : Natural; First_Paren : Natural; Colon_Token : Token_Stack.Generic_Type_Access; Char : Character; begin Prev_Token := Tok_Colon; Non_Blank := Start_Of_Line; Is_Parameter := False; Is_Discriminant := False; if Format then Skip_Blanks (Buffer, Non_Blank); end if; if Local_Top_Token.In_Declaration and then Local_Top_Token.Token = Tok_Identifier then Pop_And_Set_Local (Tokens); declare Val : Extended_Token; begin -- Create a dummy token to separate variables -- declaration from their type. Val.Token := Tok_Colon; case In_Declaration is when Subprogram_Decl => Val.Variable_Kind := Parameter_Kind; when Type_Decl => Val.Variable_Kind := Discriminant_Kind; when others => null; end case; if Align_Decl_On_Colon then Val.Colon_Col := P - Non_Blank; end if; Push (Tokens, Val); Colon_Token := Top (Tokens); end; end if; if P > Buffer'First and then P < Buffer'Last and then Buffer (Prev_Char (P)) in '0' .. '9' then Char := Buffer (Next_Char (P)); if Char in '0' .. '9' or else Char = ';' then -- Special case 16:12: obsolete format (equivalent to -- 16#12#), e.g: -- X : Integer := 16:12:; Insert_Spaces := False; end if; end if; -- Auto align colons in declarations (parameters, variables, ...) if Local_Top_Token.Align_Colon = 0 or else Num_Parens > 1 then return; end if; Align_Colon := Local_Top_Token.Align_Colon; if Format_Operators then if Buffer (Next_Char (P)) = ' ' or else Last - 1 = End_Of_Line then Long := 2; else Long := 3; end if; if Buffer (Prev_Char (P)) = ' ' then Offs := 2; Long := Long - 1; else Align_Colon := Align_Colon - 1; end if; else Offs := 2; Long := 1; end if; if Num_Parens /= 0 then -- Handle properly alignment of first parameter in the -- following case: -- -- procedure F (X : Integer; <-- -- Foo : Integer); First_Paren := Non_Blank; while First_Paren < P and then Buffer (First_Paren) /= '(' loop First_Paren := First_Paren + 1; end loop; if Buffer (First_Paren) = '(' then Align_Colon := Align_Colon + First_Paren - Non_Blank + 1; end if; end if; -- In case Align_Colon is too small, avoid truncating non blank -- characters by never using a negative offset. Offset_Align := Integer'Max (0, Align_Colon - (P - Non_Blank + 1)); if Align_Decl_On_Colon and then Colon_Token /= null then Colon_Token.Colon_Col := Colon_Token.Colon_Col + Offset_Align; end if; Replace_Text (First, Last, L, (1 .. Offset_Align => ' ') & Spaces (Offs .. Offs + Long - 1)); Insert_Spaces := False; end Handle_Colon; ------------------ -- Handle_Arrow -- ------------------ procedure Handle_Arrow is Align_Arrow : Natural := Top (Indents).Align_Arrow; Non_Blank : Natural; Offset_Align : Natural; J : Natural; First_Paren : Natural; Next_Tok : Token_Stack.Generic_Type_Access; begin if Num_Parens > 0 and then Analyze_Ada_Source.Prev_Prev_Token in Tok_When | Tok_Dot_Dot then -- Handle case expression: -- (case X is -- when 1 -- => Compute_Indentation (Tok_Arrow, Prev_Token, Prev_Prev_Token, P, L, Num_Spaces); else Do_Indent (P, L, Num_Spaces); end if; Prev_Token := Tok_Arrow; Next_Tok := Next (Tokens); if (Local_Top_Token.Token = Tok_When and then (Next_Tok = null or else Next_Tok.Token /= Tok_Select)) or else Local_Top_Token.Token = Tok_For then Pop_And_Set_Local (Tokens); end if; Handle_Two_Chars ('>'); if Align_Arrow = 0 then return; end if; if not Is_Blank (Buffer (P - 2)) then Align_Arrow := Align_Arrow - 1; end if; Non_Blank := Start_Of_Line; Skip_Blanks (Buffer, Non_Blank); -- Handle properly alignment of first parameter in the -- following case: -- -- Foo (X => 1, <-- -- Foo => 2); First_Paren := 0; J := Non_Blank; while J < P - 1 loop if Buffer (J) = '(' and then (Buffer (J - 1) /= ''' or else Buffer (J + 1) /= ''') and then First_Paren = 0 then First_Paren := J; end if; if Buffer (J) = ')' and then (Buffer (J - 1) /= ''' or else Buffer (J + 1) /= ''') then First_Paren := 0; end if; J := J + 1; end loop; if First_Paren /= 0 and then Buffer (First_Paren) = '(' then Align_Arrow := Align_Arrow + First_Paren - Non_Blank + 1; end if; -- In case Align_Arrow is too small, avoid truncating non blank -- characters by never using a negative offset. Offset_Align := Integer'Max (0, Align_Arrow - (P - Non_Blank + 1)); Replace_Text (First, Last, L, (1 .. Offset_Align => ' ') & Spaces (Offs .. Offs + Long - 1)); Insert_Spaces := False; end Handle_Arrow; ---------------------- -- Handle_Two_Chars -- ---------------------- procedure Handle_Two_Chars (Second_Char : Character) is Prev_Tmp : constant Integer := Prev_Char (P); begin Last := P + 2; if Prev_Tmp < Buffer'First or else Is_Blank (Buffer (Prev_Tmp)) then Offs := 2; Long := 2; else Long := 3; end if; P := Next_Char (P); if P < Buffer_Last and then not Is_Blank (Buffer (Next_Char (P))) then Long := Long + 1; end if; Spaces (3) := Second_Char; end Handle_Two_Chars; ---------------------- -- Skip_Blank_Lines -- ---------------------- procedure Skip_Blank_Lines is begin if P > Buffer_Last or else (Buffer (P) /= ASCII.LF and then Buffer (P) /= ASCII.CR) then return; end if; while P < Buffer_Last and then (Buffer (P) = ASCII.LF or else Buffer (P) = ASCII.CR) loop if Buffer (P) = ASCII.LF then New_Line (L); Indent_Done := False; end if; P := Next_Char (P); end loop; if P < Buffer_Last then Start_Of_Line := P; End_Of_Line := Line_End (Buffer, Start_Of_Line); end if; end Skip_Blank_Lines; ------------------- -- Skip_Comments -- ------------------- procedure Skip_Comments is Prev_Start_Line : Natural; Last : Natural; Ref_Indent : Natural; Success : Boolean; Entity : Language_Entity; First_Indent : Boolean := True; begin Ref_Indent := Integer'Max (Num_Spaces, 0); if not Indent_Done and then Stick_Comments and then (Prev_Token = Tok_Is or else Prev_Token = Tok_Record) and then Start_Of_Line > Buffer'First + 2 and then Buffer (Start_Of_Line - 2) /= ASCII.LF then Ref_Indent := Integer'Max (Ref_Indent - Indent_Level, 0); end if; while P < Buffer_Last and then Buffer (P) = '-' and then Buffer (P + 1) = '-' loop Prev_Start_Line := Start_Of_Line; Prev_Line := L; First := P; Comments_Skipped := True; -- If we do not indent here, then automatic indentation -- won't work for comments right after 'is' and 'begin', -- e.g: -- procedure Foo is -- begin -- -- comment if Indent_Comments then if First_Indent and then not Indent_Done and then ((Prev_Token in Reserved_Token_Type and then Prev_Token not in Token_Class_No_Cont) or else (Prev_Token = Tok_Right_Paren and then Top (Tokens).Token /= No_Token) or else (Num_Parens > 0 and then Continuation_Val /= 0)) then -- Add simple handling of comment and continuation lines if Num_Parens > 0 then Continuation_Val := Continuation_Val - Indent_Continue; end if; Do_Indent (P, L, Ref_Indent, Continuation => True); Ref_Indent := Integer'Max (Ref_Indent + Continuation_Val, 0); Continuation_Val := 0; else Do_Indent (P, L, Ref_Indent); end if; First_Indent := False; end if; -- Keep track of the indentation of the first comment line, -- in case we're doing incremental reformatting: in this case, -- we want to follow the indentation (possibly manual) of this -- first line. if Ref_Indent = Num_Spaces and then To /= 0 and then L not in From .. To then Ref_Indent := Integer'Max (P - Start_Of_Line - Indent_Offset, 0); end if; Next_Line (Buffer, P + 1, P, Success); Last := P; if Success then New_Line (L); Last := Prev_Char (Last); Indent_Done := False; end if; loop -- Skip blank lines -- ??? need to handle ASCII.CR as well, although we now -- only use LF separators internally in GPS. while P < Buffer_Last and then Buffer (P) = ASCII.LF loop Ref_Indent := Integer'Max (Num_Spaces, 0); New_Line (L); P := P + 1; end loop; Start_Of_Line := P; if P /= Buffer_Last then while Buffer (P) = ' ' or else Buffer (P) = ASCII.HT loop P := P + 1; if P = Buffer_Last then exit; end if; end loop; end if; exit when P = Buffer_Last or else Buffer (P) /= ASCII.LF; end loop; End_Of_Line := Line_End (Buffer, P); Padding := 0; if Indent_Comments and then Buffer (P) = ASCII.LF then -- Indent last buffer line before exiting, to position -- the cursor at the right location pragma Assert (P = Buffer_Last); Do_Indent (P, L, Ref_Indent); end if; if Callback /= null then if First + 2 <= Buffer_Last and then Buffer (First + 2) = '#' then Entity := Annotated_Comment_Text; else Entity := Comment_Text; end if; if Entity = Annotated_Comment_Text and then Replace = null then -- Recognize and handle SPARK reserved words when parsing -- constructs. declare Prev_Sloc : Source_Location; Line : constant Natural := Prev_Line - 1; Col : constant Natural := First + 2 - Prev_Start_Line + 1; function Is_SPARK_Keyword (S : String) return Boolean; -- Callback for Analyze_Ada_Source to recognize SPARK -- keywords. function Local_Callback (Entity : Language_Entity; Sloc_Start : Source_Location; Sloc_End : Source_Location; Partial_Entity : Boolean) return Boolean; -- Wrapper around Callback function Adjust (Loc : Source_Location) return Source_Location; -- Adjust Loc taking Line, Col and Offset into account ---------------------- -- Is_SPARK_Keyword -- ---------------------- function Is_SPARK_Keyword (S : String) return Boolean is begin return Match (SPARK_Keywords, S); end Is_SPARK_Keyword; ------------ -- Adjust -- ------------ function Adjust (Loc : Source_Location) return Source_Location is begin return (Loc.Line + Line, Loc.Column + Col, Loc.Index); end Adjust; -------------------- -- Local_Callback -- -------------------- function Local_Callback (Entity : Language_Entity; Sloc_Start : Source_Location; Sloc_End : Source_Location; Partial_Entity : Boolean) return Boolean is Ignore : Boolean; pragma Unreferenced (Ignore); Sloc1 : constant Source_Location := Adjust (Sloc_Start); Sloc2 : constant Source_Location := Adjust (Sloc_End); begin if Entity = Keyword_Text and then Is_SPARK_Keyword (Buffer (Sloc_Start.Index .. Sloc_End.Index)) then Ignore := Callback (Annotated_Comment_Text, Prev_Sloc, (Sloc1.Line, Sloc1.Column - 1, Sloc1.Index - 1), Partial_Entity); Prev_Sloc := (Sloc2.Line, Sloc2.Column + 1, Sloc2.Index + 1); return Callback (Annotated_Keyword_Text, Sloc1, Sloc2, Partial_Entity); else return False; end if; end Local_Callback; begin Prev_Sloc := (Prev_Line, First - Prev_Start_Line + 1, First); -- Call Analyze_Ada_Source recursively on the SPARK -- annotations to highlight keywords. Analyze_Ada_Source (Buffer (First + 3 .. Last - 1), Symbols, Indent_Params => Indent_Params, Format => Format, Replace => null, Constructs => null, Callback => Local_Callback'Unrestricted_Access, Indent_Offset => Indent_Offset, Case_Exceptions => Case_Exceptions, Is_Optional_Keyword => Is_SPARK_Keyword'Access); if Prev_Sloc.Index <= Last then if Callback (Entity, Prev_Sloc, (Prev_Line, Last - Prev_Start_Line + 1, Last), False) then Terminated := True; return; end if; end if; end; else if Call_Callback (Entity, (Prev_Line, First - Prev_Start_Line + 1, First), (Prev_Line, Last - Prev_Start_Line + 1, Last), False) then Terminated := True; return; end if; end if; end if; if P = Buffer_Last then -- In this case, the comment goes until the end of the -- buffer. There's nothing more to be analyzed, so -- put P beyond the last analyzed element. P := P + 1; end if; end loop; if P > Buffer_Last then End_Reached := True; end if; end Skip_Comments; ---------------------------- -- Preprocessor_Directive -- ---------------------------- procedure Preprocessor_Directive is begin -- Skip line while P < Buffer'Last and then Buffer (P + 1) /= ASCII.LF loop P := P + 1; end loop; -- Mark this line as indented, so that the current indentation is -- kept. Indent_Done := True; end Preprocessor_Directive; ----------------------- -- Pop_And_Set_Local -- ----------------------- procedure Pop_And_Set_Local (Stack : in out Token_Stack.Simple_Stack) is begin Pop (Stack); if not Is_Empty (Stack) then Local_Top_Token := Top (Stack); else Local_Top_Token := null; end if; end Pop_And_Set_Local; begin -- Next_Word Start_Of_Line := Line_Start (Buffer, P); End_Of_Line := Line_End (Buffer, Start_Of_Line); Terminated := False; End_Reached := False; loop declare L1, L2 : Natural; begin L1 := L; Skip_Blank_Lines; Skip_Comments; L2 := L; -- If we have blank lines and/or comment line we need to -- recompute the alignment for the next block of code. Recompute_Align := L2 > L1 + 1; end; if (End_Reached and then Buffer (Buffer_Last) /= ASCII.LF) or else Terminated then return; end if; exit when P > Buffer_Last or else Is_Entity_Letter (UTF8_Get_Char (Buffer (P .. Buffer_Last))); -- WARNING: any call to Pop (Token) during the case statement -- below should be followed by a recomputation of Top_Token. -- See e.g. Handle_Arrow where this is done. -- Only if Top_Token is not accessed further down this procedure -- can the recomputation be omitted. Local_Top_Token := Top (Tokens); if Align_On_Colons and then Recompute_Align then Local_Top_Token.Align_Colon := Compute_Alignment (P, Stop_On_Blank_Line => True, Skip_First_Line => False); end if; Prev3_Token := Prev_Prev_Token; Prev_Prev_Token := Prev_Token; Token_Found := True; case Buffer (P) is when '#' => First := P; Prev_Token := Tok_Pound; if (P = Buffer'First or else not Is_Alphanumeric (Buffer (P - 1))) and then P < Buffer'Last and then (Is_Letter (Buffer (P + 1)) or else Buffer (P + 1) = ' ') then Preprocessor_Directive; end if; when '[' => First := P; Prev_Token := Tok_Left_Square_Bracket; when ']' => First := P; Prev_Token := Tok_Right_Square_Bracket; when '(' => First := P; Prev_Token := Tok_Left_Paren; if Num_Parens = 0 then if In_Declaration = Subprogram_Decl and then (Top_Token = null or else not Top_Token.Attributes (Ada_New_Attribute)) then Is_Parameter := True; elsif In_Declaration = Type_Decl then Is_Discriminant := True; elsif Prev_Prev_Token = Tok_Is and then Local_Top_Token.Token = Tok_Function then -- This is an expression function so we won't have -- and 'end function', unindent accordingly. Num_Spaces := Num_Spaces - Indent_Level; -- ??? The code below is not quite right: ideally we -- want to register the end of the expression function -- at the semicolon. Pop_And_Set_Local (Tokens); end if; end if; if not Is_Empty (Paren_Stack) then Push (Paren_Stack, Top (Paren_Stack).all); elsif Local_Top_Token.Token = Tok_Type then Push (Paren_Stack, Type_Declaration); elsif Prev_Prev_Token = Tok_Return then Push (Paren_Stack, Aggregate); elsif Prev_Prev_Token in Reserved_Token_Type then Push (Paren_Stack, Conditional); elsif Prev_Prev_Token = Tok_Identifier then Push (Paren_Stack, Function_Call); else Push (Paren_Stack, Aggregate); end if; if Continuation_Val > Indent_Continue and then Top (Indents).Level /= None then Continuation_Val := 0; end if; if P > Buffer'First then Char := Buffer (Prev_Char (P)); else Char := ' '; end if; if Indent_Done then Adjust := Indent_Continue + Continuation_Val; Paren_In_Middle := True; -- If Prev_Prev_Token is an operator, it means that -- spaces have already been inserted. if Format_Operators and then not Is_Blank (Char) and then Char /= '(' and then Char /= ''' and then not Is_Extended_Operator (Prev_Prev_Token) then Spaces (2) := Buffer (P); Replace_Text (P, P + 1, L, Spaces (1 .. 2)); end if; else -- Indent with extra spaces if the '(' is the first -- non blank character on the line if Prev_Prev_Token = Tok_Comma then Adjust := 1; else Adjust := Indent_Continue + 1; end if; if Prev_Prev_Token = Tok_Comma or else Prev_Prev_Token = Tok_Ampersand then Do_Indent (P, L, Num_Spaces); else if Prev_Prev_Token = Tok_Colon_Equal and then Local_Top_Token.Colon_Col /= 0 and then Continuation_Val = 0 then Continuation_Val := Top (Tokens).Colon_Col + 4 - Indent_Continue; end if; Adjust := Adjust + Continuation_Val; Tmp := Paren_In_Middle; Do_Indent (P, L, Num_Spaces, Continuation => Prev_Prev_Token = Tok_Apostrophe or else Prev_Prev_Token = Tok_Arrow or else not Paren_In_Middle or else Prev_Prev_Token in Reserved_Token_Type); Paren_In_Middle := Tmp; end if; end if; Num_Parens := Num_Parens + 1; Align := 0; if Num_Parens = 1 and then Local_Top_Token.Token in Token_Class_Declk and then Local_Top_Token.Profile_Start = 0 and then not Local_Top_Token.Attributes (Ada_New_Attribute) then if In_Declaration = Subprogram_Decl then Local_Top_Token.Profile_Start := P; end if; if Align_On_Colons then Local_Top_Token.Align_Colon := Compute_Alignment (P + 1, Skip_First_Line => False); end if; else if Align_On_Arrows then Align := Compute_Alignment (P + 1, Skip_First_Line => False, Align_On => Tok_Arrow); end if; end if; -- Indent on the left parenthesis for subprogram & type -- declarations, and for subprogram calls/aggregates with no -- nested parenthesis except on the same line and for -- arrows+paren as in: -- X := (Foo => (Y, -- Z)); -- In other cases (complex subprogram call), -- indent as for continuation lines. declare Level, Tmp_Index, Val : Integer; begin if Top (Paren_Stack).all = Conditional then Level := P - Start_Of_Line + Padding + Indent_Conditional; else -- ../test/ada-gps/ada_gps_bug_006.adb -- The_TV := E (Query, (Def_Restriction.Traffic_Volume, Tmp_Index := P + 1; while Tmp_Index <= Buffer'Last and then Buffer (Tmp_Index) = ' ' loop Tmp_Index := Tmp_Index + 1; end loop; Level := Tmp_Index - Start_Of_Line + Padding; end if; Val := Top (Indents).Continuation_Val; Push (Indents, (Level, Align, L, Continuation_Val)); -- If Align_Decl_On_Colon is set and Colon_Col is set -- then ignore Val and continue indenting based on -- the current Continuation_Val since the saved value -- does not take Colon_Col into account. if Local_Top_Token.Colon_Col /= 0 then if Continuation_Val > 0 then Continuation_Val := Continuation_Val - Indent_Continue; end if; else Continuation_Val := Val; end if; end; when ')' => if (Local_Top_Token.Token = Tok_Colon or else Local_Top_Token.Token = Tok_Identifier) and then (Local_Top_Token.Variable_Kind in Parameter_Kind .. Discriminant_Kind or else (Local_Top_Token.Is_In_Type_Definition and then not Local_Top_Token.Attributes (Ada_Record_Attribute) and then not Local_Top_Token.Type_Declaration)) then if Local_Top_Token.Token = Tok_Identifier and then not (Local_Top_Token.Is_In_Type_Definition and then not Local_Top_Token.Attributes (Ada_Record_Attribute) and then not Local_Top_Token.Type_Declaration) then -- This handles cases where we have a family entry. -- For example: -- entry E (Integer); -- here Integer is a type, so we don't want it in the -- constructs. But is has already been pushed. The -- code below disactivate its addition to the -- constructs Local_Top_Token.Token := Tok_Colon; end if; Pop_And_Set_Local (Tokens); end if; First := P; Prev_Token := Tok_Right_Paren; Close_Parenthesis; when '"' => declare Len : Natural; Entity : Language_Entity; begin First := P; while P < End_Of_Line loop P := Next_Char (P); exit when Buffer (P) = '"'; end loop; if Buffer (P) /= '"' then -- Syntax error: the string was not terminated -- Try to recover properly, and in particular, try -- to reset the parentheses stack. if Num_Parens > 0 then Close_Parenthesis; end if; end if; if (Local_Top_Token.Token in Token_Class_Declk and then Local_Top_Token.Ident_Len = 0) or else Prev_Token in Tok_End | Tok_Dot or else Local_Top_Token.Token = Tok_With then -- This is an operator symbol, e.g function ">=" (...) -- Or we're parsing a GNAT Project file and this is -- a dependency declaration (with "bla.gpr") if Prev_Token not in Tok_End | Tok_Dot then Len := P - First + 1; Local_Top_Token.Identifier (1 .. Len) := Buffer (First .. P); Local_Top_Token.Ident_Len := Len; Local_Top_Token.Sloc_Name.Line := L; Local_Top_Token.Sloc_Name.Column := First - Start_Of_Line + 1; Local_Top_Token.Sloc_Name.Index := First; end if; Prev_Token := Tok_Operator_Symbol; Entity := Block_Text; else Prev_Token := Tok_String_Literal; Entity := String_Text; end if; Compute_Indentation (Prev_Token, Prev_Prev_Token, Prev3_Token, P, L, Num_Spaces); if Callback /= null then if Call_Callback (Entity, (L, First - Start_Of_Line + 1, First), (L, P - Start_Of_Line + 1, P), False) then Terminated := True; return; end if; end if; end; when '&' | '+' | '-' | '*' | '/' | ':' | '<' | '>' | '=' | '|' | '.' => Spaces (2) := Buffer (P); Spaces (3) := ' '; First := P; Last := P + 1; Offs := 1; case Buffer (P) is when '+' | '-' => if Buffer (P) = '-' then Prev_Token := Tok_Minus; else Prev_Token := Tok_Plus; end if; if Prev_Prev_Token = Tok_Identifier and then (P <= Buffer'First + 1 or else To_Upper (Buffer (P - 1)) /= 'E' or else (Buffer (P - 2) /= '#' and then Buffer (P - 2) not in '0' .. '9')) and then (P = Buffer'Last or else (Buffer (P + 1) /= '"' and then Buffer (P + 1) /= '(')) then Insert_Spaces := True; else Insert_Spaces := False; end if; when '&' | '|' => if Buffer (P) = '&' then Prev_Token := Tok_Ampersand; else Prev_Token := Tok_Vertical_Bar; end if; Insert_Spaces := True; when '/' | ':' => Insert_Spaces := True; if P < Buffer'Last and then Buffer (P + 1) = '=' then if Buffer (P) = ':' and then Local_Top_Token.Token = Tok_Colon then Right_Assignment := True; Local_Top_Token.Attributes (Ada_Assign_Attribute) := True; if Local_Top_Token.Variable_Kind in Parameter_Kind .. Discriminant_Kind then Pop_And_Set_Local (Tokens); end if; end if; Handle_Two_Chars ('='); if Buffer (P) = '/' then Prev_Token := Tok_Not_Equal; else Prev_Token := Tok_Colon_Equal; end if; elsif Buffer (P) = '/' then Prev_Token := Tok_Slash; else Handle_Colon; end if; when '*' => declare Prev_Tmp : constant Integer := Prev_Char (P); begin Insert_Spaces := Prev_Tmp >= Buffer'First and then Buffer (Prev_Tmp) /= '*'; end; if P < Buffer'Last and then Buffer (Next_Char (P)) = '*' then Handle_Two_Chars ('*'); Prev_Token := Tok_Double_Asterisk; else Prev_Token := Tok_Asterisk; end if; when '.' => declare Next_Tmp : constant Natural := Next_Char (P); begin Insert_Spaces := Next_Tmp <= Buffer'Last and then Buffer (Next_Tmp) = '.'; end; if Insert_Spaces then Handle_Two_Chars ('.'); Prev_Token := Tok_Dot_Dot; else Prev_Token := Tok_Dot; end if; when '<' => declare Next_Tmp : constant Natural := Next_Char (P); begin if Next_Tmp <= Buffer'Last then case Buffer (Next_Tmp) is when '=' => Insert_Spaces := True; Prev_Token := Tok_Less_Equal; Handle_Two_Chars ('='); when '<' => Prev_Token := Tok_Less_Less; Insert_Spaces := False; Handle_Two_Chars ('<'); when '>' => Prev_Token := Tok_Box; Insert_Spaces := False; Handle_Two_Chars ('>'); when others => Prev_Token := Tok_Less; Insert_Spaces := True; end case; else Prev_Token := Tok_Less; Insert_Spaces := True; end if; end; when '>' => declare Next_Tmp : constant Natural := Next_Char (P); begin if Next_Tmp <= Buffer'Last then case Buffer (Next_Tmp) is when '=' => Insert_Spaces := True; Prev_Token := Tok_Greater_Equal; Handle_Two_Chars ('='); when '>' => Prev_Token := Tok_Greater_Greater; Insert_Spaces := False; Handle_Two_Chars ('>'); when others => Prev_Token := Tok_Greater; Insert_Spaces := True; end case; else Prev_Token := Tok_Greater; Insert_Spaces := True; end if; end; when '=' => Insert_Spaces := True; if P + 1 <= Buffer'Last and then Buffer (P + 1) = '>' then Handle_Arrow; else Prev_Token := Tok_Equal; end if; when others => null; end case; if Spaces (3) = ' ' then if P + 1 > Buffer'Last or else Is_Blank (Buffer (P + 1)) or else Last - 1 = End_Of_Line then Long := 2; else Long := 3; end if; end if; if P > Buffer'First and then Is_Blank (Buffer (P - 1)) then Offs := 2; Long := Long - 1; end if; if (Num_Parens = 0 or else Prev_Token in Tok_Ampersand | Tok_Vertical_Bar or else Prev_Prev_Token in Tok_Arrow | Tok_Then | Tok_Else) and then Local_Top_Token.Token /= Tok_When then -- If we're not inside parens or if we're in a -- conditional expression, then handle continuation -- lines here. Otherwise, continuation lines are already -- handled separately. Compute_Indentation (Prev_Token, Prev_Prev_Token, Prev3_Token, P, L, Num_Spaces); else Do_Indent (P, L, Num_Spaces); end if; if Format_Operators and then Insert_Spaces then Replace_Text (First, Last, L, Spaces (Offs .. Offs + Long - 1)); end if; when ',' | ';' => First := P; if Buffer (P) = ';' then Prev_Token := Tok_Semicolon; Right_Assignment := False; if Aspect_Clause then Finish_Aspect_Clause (P, L, Done => Terminated); Local_Top_Token := Top (Tokens); if Terminated then return; end if; end if; if Local_Top_Token.Token = Tok_Colon then Pop_And_Set_Local (Tokens); elsif Num_Parens = 0 then if In_Declaration /= No_Decl or else (Local_Top_Token.Token = Tok_Task and then In_Declaration = Type_Decl) or else Local_Top_Token.Token = Tok_Subtype or else Local_Top_Token.Token = Tok_For then -- subprogram spec or type decl or repr. clause, -- e.g: -- procedure xxx (...); -- type ... is ...; -- for ... use ...; Pop_And_Set_Local (Tokens); In_Declaration := No_Decl; elsif Local_Top_Token.Token = Tok_With or else Local_Top_Token.Token = Tok_Use or else Local_Top_Token.Token = Tok_Identifier or else Local_Top_Token.Token = Tok_Type or else Local_Top_Token.Token = Tok_Accept or else Local_Top_Token.Token = Tok_Pragma then Pop_And_Set_Local (Tokens); end if; end if; if In_Declaration = Subprogram_Decl and then not (Top_Token /= null and then Top_Token.Attributes (Ada_New_Attribute)) then Is_Parameter := True; elsif In_Declaration = Type_Decl then Is_Discriminant := True; end if; else Prev_Token := Tok_Comma; if Local_Top_Token.In_Declaration and then Local_Top_Token.Token = Tok_Identifier then Pop_And_Set_Local (Tokens); elsif Local_Top_Token.Token = Tok_With or else Local_Top_Token.Token = Tok_Use then declare Val : Extended_Token; begin -- Create a separate entry for each with clause: -- with a, b; -- will get two entries: one for a, one for b. Val.Token := Local_Top_Token.Token; Pop_And_Set_Local (Tokens); Val.Sloc.Line := L; Val.Sloc.Column := Prec - Line_Start (Buffer, Prec) + 2; Val.Sloc.Index := Prec + 1; Val.Ident_Len := 0; Push (Tokens, Val); end; end if; end if; if Format_Operators and then P /= End_Of_Line then Char := Buffer (P + 1); if Char /= ' ' then Do_Indent (P, L, Num_Spaces); Comma (1) := Buffer (P); Replace_Text (P, P + 1, L, Comma (1 .. 2)); end if; end if; when ''' => -- Apostrophe. This can either be the start of a character -- literal, an isolated apostrophe used in a qualified -- expression or an attribute. We treat it as a character -- literal if it does not follow a right parenthesis, -- identifier, the keyword ALL or a literal. This means that -- we correctly treat constructs like: -- A := Character'('A'); First := P; if Prev_Token = Tok_Identifier or else Prev_Token = Tok_Right_Paren or else Prev_Token = Tok_All or else Prev_Token in Token_Class_Literal or else P = End_Of_Line then Prev_Token := Tok_Apostrophe; else if P = End_Of_Line - 1 then P := P + 1; else P := P + 2; end if; while P < End_Of_Line and then Buffer (P) /= ''' loop P := Next_Char (P); end loop; Prev_Token := Tok_Char_Literal; if Callback /= null then if Call_Callback (Character_Text, (L, First - Start_Of_Line + 1, First), (L, P - Start_Of_Line + 1, P), False) then Terminated := True; Comments_Skipped := False; return; end if; end if; end if; when others => Token_Found := False; end case; if Buffer (P) /= ' ' and then not Is_Control (Buffer (P)) then Comments_Skipped := False; end if; if Token_Found and then (Prev_Token in Tok_Double_Asterisk .. Tok_Colon_Equal or else Prev_Token in Tok_Semicolon .. Tok_Dot_Dot) then if Callback /= null then if Call_Callback (Operator_Text, (L, First - Start_Of_Line + 1, First), (L, P - Start_Of_Line + 1, P), False) then Terminated := True; Comments_Skipped := False; return; end if; end if; end if; P := Next_Char (P); end loop; Comments_Skipped := False; Terminated := False; end Next_Word; ------------------ -- Replace_Text -- ------------------ procedure Replace_Text (First : Natural; Last : Natural; Line : Natural; Str : String) is Start : Natural; begin if Replace /= null and then (To = 0 or else Line in From .. To) then if Last_Replace_Line /= Line then Last_Replace_Line := Line; Padding := 0; end if; Start := Line_Start (Buffer, First); Replace (Line, Padding + First - Start + 1, Padding + Last - Start + 1, Str); Padding := Padding + Str'Length - (Last - First); end if; end Replace_Text; ------------------- -- Call_Callback -- ------------------- function Call_Callback (Entity : Language_Entity; Sloc_Start : Source_Location; Sloc_End : Source_Location; Partial_Entity : Boolean) return Boolean is Ignore : Boolean; pragma Unreferenced (Ignore); Ent : Language_Entity := Entity; begin if Aspect_Clause then case Entity is when Keyword_Text => Ent := Aspect_Keyword_Text; when Comment_Text | Annotated_Comment_Text => Ent := Aspect_Comment_Text; when others => -- Highlight everything else with Aspect_Text, -- which will be done next time Call_Callback is called. return False; end case; Ignore := Callback (Aspect_Text, Aspect_Clause_Sloc, (Sloc_Start.Line, Sloc_Start.Column - 1, Sloc_Start.Index - 1), Partial_Entity); Aspect_Clause_Sloc := (Sloc_End.Line, Sloc_End.Column + 1, Sloc_End.Index + 1); end if; return Callback (Ent, Sloc_Start, Sloc_End, Partial_Entity); end Call_Callback; begin -- Analyze_Ada_Source if Buffer'Length = 0 then return; end if; -- Push a dummy token so that stack will never be empty Push (Tokens, Default_Extended); -- Push a dummy indentation so that stack will never be empty Push (Indents, (None, 0, 0, 0)); Next_Word (Prec, Line_Count, Terminated, End_Reached); -- If there is only one character in the buffer and the end of the -- buffer has been reached, enter the main loop anyway. Otherwise, -- the on-the-fly auto-casing will not work when adding a space after -- single character identifier. if (End_Reached and then Buffer_Last > 1 and then Buffer (Buffer_Last) /= ASCII.LF) or else Terminated then Clear (Paren_Stack); Clear (Tokens); Clear (Indents); return; end if; Current := End_Of_Word (Prec); Main_Loop : loop Str_Len := Current - Prec + 1; Str (1 .. Str_Len) := Buffer (Prec .. Current); Token := Get_Token (Str (1 .. Str_Len), Prev_Token); if Token = Tok_Identifier then -- Handle dotted names, e.g Foo.Bar.X Prev_Line := Line_Count; if Current < Buffer_Last then Index_Ident := End_Of_Identifier (Current + 1); if Index_Ident /= Current then -- We have a dotted name, update indexes Str_Len := Index_Ident - Prec + 1; Str (Current - Prec + 2 .. Index_Ident - Prec + 1) := Buffer (Current + 1 .. Index_Ident); Current := Index_Ident; end if; end if; Top_Token := Top (Tokens); Start_Of_Line := Line_Start (Buffer, Prec); if Top_Token.Ident_Len = 0 and then (Top_Token.Token in Token_Class_Declk or else Top_Token.Token = Tok_With or else Top_Token.Token = Tok_Pragma) then -- Store enclosing entity name Top_Token.Identifier (1 .. Str_Len) := Buffer (Prec .. Current); Top_Token.Ident_Len := Str_Len; Top_Token.Sloc_Name.Line := Prev_Line; Top_Token.Sloc_Name.Column := Prec - Start_Of_Line + 1; Top_Token.Sloc_Name.Index := Prec; end if; if (Top_Token.In_Declaration or else (Top_Token.Token = Tok_For and then Prev_Token = Tok_For) or else Top_Token.Type_Declaration or else (Top_Token.Attributes (Ada_Record_Attribute) and then (Top_Token.Token = Tok_Case or else Prev_Token /= Tok_Arrow)) or else Is_Parameter or else Is_Discriminant or else (Top_Token.Type_Definition_Section and then Top_Token.Token = Tok_Type and then Top_Token.Attributes = No_Attribute)) and then (Num_Parens = 0 or else Is_Parameter or else Is_Discriminant or else Top_Token.Type_Definition_Section) and then (Prev_Token not in Reserved_Token_Type or else Prev_Token = Tok_Declare or else Prev_Token = Tok_Private or else Prev_Token = Tok_Record or else Prev_Token = Tok_Generic or else Prev_Token = Tok_For or else (Prev_Token = Tok_Is and then not In_Generic)) and then Prev_Token /= Tok_Dot and then Prev_Token /= Tok_Apostrophe and then not Aspect_Clause then -- This is a variable, a field declaration or a enumeration -- literal declare Val : Extended_Token; begin Val.Token := Tok_Identifier; Val.Sloc.Line := Prev_Line; Val.Sloc.Column := Prec - Start_Of_Line + 1; Val.Sloc.Index := Prec; Val.Identifier (1 .. Str_Len) := Str (1 .. Str_Len); Val.Ident_Len := Str_Len; Val.Sloc_Name := Val.Sloc; Val.In_Declaration := True; Val.Visibility := Top_Token.Visibility_Section; if Is_Parameter then Val.Variable_Kind := Parameter_Kind; elsif Is_Discriminant then Val.Variable_Kind := Discriminant_Kind; end if; Val.Is_In_Type_Definition := Top_Token.Type_Definition_Section; Val.Is_Generic_Param := In_Generic; Push (Tokens, Val); if Prev_Token = Tok_For then Pop (Tokens); end if; end; end if; declare Entity : Language_Entity; begin Entity := Identifier_Text; Casing := Ident_Casing; if Is_Digit (Str (1)) or else (Prev_Token = Tok_Pound and then Is_Hexadecimal_Digit (Str (1))) then -- Recognize simple cases of numeric values -- ??? recognizing more cases would require changing -- Next_Word parsing. Entity := Number_Text; elsif Is_Optional_Keyword /= null and then Is_Optional_Keyword (Str (1 .. Str_Len)) then Entity := Keyword_Text; Casing := Reserved_Casing; -- Try to differentiate type identifiers and block identifiers -- from others in declarations. elsif ((Prev_Token = Tok_In or else Prev_Token = Tok_Access or else Prev_Token = Tok_Aliased or else Prev_Token = Tok_Constant) and then (Prev_Prev_Token = Tok_Colon or else Prev_Prev_Token = Tok_Null or else Prev_Prev_Token = Tok_Is)) or else (Prev_Token = Tok_All and then Prev_Prev_Token = Tok_Access) or else (Prev_Token = Tok_Is and then Prev_Prev_Token = Tok_Identifier and then Top_Token.Type_Declaration) or else (Prev_Token = Tok_Out and then (Prev_Prev_Token = Tok_Colon or else Prev_Prev_Token = Tok_In)) or else Prev_Token = Tok_Colon or else (In_Declaration = Subprogram_Decl and then Prev_Token = Tok_Return) then Entity := Type_Text; elsif (Prev_Token = Tok_Type and then Prev_Prev_Token /= Tok_Use) or else Prev_Token = Tok_Subtype or else Prev_Token = Tok_End or else Prev_Token = Tok_Procedure or else Prev_Token = Tok_Function or else Prev_Token = Tok_Task or else Prev_Token = Tok_Body or else Prev_Token = Tok_Entry or else Prev_Token = Tok_Accept or else Prev_Token = Tok_Package or else (Prev_Token = Tok_Renames and then Prev_Prev_Token = Tok_Right_Paren) or else (Current + 8 <= Buffer_Last and then Buffer (Current + 2) = ':' and then (Look_For (Current + 4, "begin") or else Look_For (Current + 4, "declare"))) then Entity := Block_Text; end if; if Prev_Token = Tok_Apostrophe and then To_Upper (Str (1 .. Str_Len)) = "CLASS" and then Top_Token.In_Entity_Profile then Top_Token.Attributes (Ada_Class_Attribute) := True; end if; if Callback /= null then exit Main_Loop when Call_Callback (Entity, (Prev_Line, Prec - Start_Of_Line + 1, Prec), (Line_Count, Current - Line_Start (Buffer, Current) + 1, Current), False); end if; end; elsif Prev_Token = Tok_Apostrophe and then (Token = Tok_Delta or else Token = Tok_Digits or else Token = Tok_Mod or else Token = Tok_Range or else Token = Tok_Access) then -- This token should not be considered as a reserved word Casing := Ident_Casing; if Callback /= null then Start_Of_Line := Line_Start (Buffer, Prec); exit Main_Loop when Call_Callback (Identifier_Text, (Line_Count, Prec - Start_Of_Line + 1, Prec), (Line_Count, Current - Start_Of_Line + 1, Current), False); end if; elsif Token = No_Token then Casing := Unchanged; else -- We have a reserved word Casing := Reserved_Casing; declare Temp : aliased Extended_Token; Do_Push : Boolean; Do_Pop : Integer; Do_Finish : Boolean; begin Handle_Word_Token (Token, Temp, Do_Pop, Do_Push, Do_Finish); exit Main_Loop when Do_Finish; Handle_Word_Indent (Token, Temp); for J in 1 .. Do_Pop loop Pop (Tokens); end loop; -- Handles In_Generic if not In_Generic and then Token = Tok_Generic then In_Generic := True; elsif In_Generic and then Prev_Token not in Tok_With | Tok_Access | Tok_Protected and then Token in Tok_Function | Tok_Procedure | Tok_Package then In_Generic := False; end if; if Do_Push then Temp.Is_Generic_Param := In_Generic; Push (Tokens, Temp); else null; end if; -- Computes In_Declaration -- ??? There is still some computation of this done in -- Handle_Word_Token. It would be nice to have all of it here. if Token = Tok_Body or else Token = Tok_Renames or else (Token = Tok_Is and then not In_Generic) then In_Declaration := No_Decl; elsif In_Declaration = Subprogram_Decl and then Token = Tok_With then In_Declaration := Subprogram_Aspect; end if; end; end if; if Indent_Params.Casing_Policy /= Disabled and then Prev_Token /= Tok_Pound -- Disable casing for based literal (so if a word is preceded by -- a pound sign). then case Casing is when Unchanged => null; when Upper | Lower | Mixed | Smart_Mixed => -- We do not want to case some as this is a new keyword in -- Ada 2012 but for upward compatibility issue GNAT does not -- forbid some as identifier. Without context it is not -- possible to determine if some is used as identifier or as -- keyword, so to avoid upsetting users we never change -- casing of some. if To_Lower (Str (1 .. Str_Len)) /= "some" then Replace_Text (Prec, Current + 1, Line_Count, Set_Case (Case_Exceptions, Str (1 .. Str_Len), Casing)); end if; end case; end if; -- 'is' is handled specially, so nothing is needed here except -- for type declarations, e.g: -- type T -- is ... if Token /= Tok_Is or else (Top_Token /= null and then Top_Token.Token = Tok_Type) then Compute_Indentation (Token, Prev_Token, Prev_Prev_Token, Current, Line_Count, Num_Spaces); end if; Prec := Current + 1; Prev_Prev_Token := Prev_Token; Prev_Token := Token; exit Main_Loop when Prec > Buffer_Last; Next_Word (Prec, Line_Count, Terminated, End_Reached); exit Main_Loop when Terminated or else (End_Reached and then Buffer (Buffer_Last) /= ASCII.LF); Current := End_Of_Word (Prec); end loop Main_Loop; -- Try to register partial constructs, friendlier Prec := Integer'Min (Prec, Buffer'Last); if Constructs /= null then while Top (Tokens).Token /= No_Token loop Pop (Tokens); end loop; end if; Clear (Paren_Stack); Clear (Tokens); Clear (Indents); exception when E : others => Trace (Me, E); raise; end Analyze_Ada_Source; end Ada_Analyzer;
{ "source": "starcoderdata", "programming_language": "ada" }
package body UxAS.Comms.Transport.ZeroMQ_Socket_Configurations is ---------- -- Make -- ---------- function Make (Network_Name : String; Socket_Address : String; Is_Receive : Boolean; Zmq_Socket_Type : ZMQ.Sockets.Socket_Type; Number_Of_IO_Threads : Positive; Is_Server_Bind : Boolean; Receive_High_Water_Mark : Int32; Send_High_Water_Mark : Int32) return ZeroMq_Socket_Configuration is Result : ZeroMq_Socket_Configuration; begin Result.Is_Receive := Is_Receive; Copy (Network_Name, To => Result.Network_Name); Copy (Socket_Address, To => Result.Socket_Address); Result.Zmq_Socket_Type := Zmq_Socket_Type; Result.Number_Of_IO_Threads := Number_Of_IO_Threads; Result.Is_Server_Bind := Is_Server_Bind; Result.Receive_High_Water_Mark := Receive_High_Water_Mark; Result.Send_High_Water_Mark := Send_High_Water_Mark; return Result; end Make; end UxAS.Comms.Transport.ZeroMQ_Socket_Configurations;
{ "source": "starcoderdata", "programming_language": "ada" }
package body Equilibrium is function Get_Indices (From : Array_Type) return Index_Vectors.Vector is Result : Index_Vectors.Vector; Right_Sum, Left_Sum : Element_Type := Zero; begin for Index in Index_Type'Range loop Right_Sum := Right_Sum + Element (From, Index); end loop; for Index in Index_Type'Range loop Right_Sum := Right_Sum - Element (From, Index); if Left_Sum = Right_Sum then Index_Vectors.Append (Result, Index); end if; Left_Sum := Left_Sum + Element (From, Index); end loop; return Result; end Get_Indices; end Equilibrium;
{ "source": "starcoderdata", "programming_language": "ada" }
Lines_Table => null, Lines_Table_Max => 1, Logical_Lines_Table => null, Num_SRef_Pragmas => 0, Reference_Name => N, Sloc_Adjust => 0, Source_Checksum => 0, Source_First => Lo, Source_Last => Hi, Source_Text => Src, Template => No_Source_File, Unit => No_Unit, Time_Stamp => Osint.Current_Source_File_Stamp); Alloc_Line_Tables (S, Opt.Table_Factor * Alloc.Lines_Initial); S.Lines_Table (1) := Lo; end; -- Preprocess the source if it needs to be preprocessed if Preprocessing_Needed then -- Temporarily set the Source_File_Index_Table entries for the -- source, to avoid crash when reporting an error. Set_Source_File_Index_Table (X); if Opt.List_Preprocessing_Symbols then Get_Name_String (N); declare Foreword : String (1 .. Foreword_Start'Length + Name_Len + Foreword_End'Length); begin Foreword (1 .. Foreword_Start'Length) := Foreword_Start; Foreword (Foreword_Start'Length + 1 .. Foreword_Start'Length + Name_Len) := Name_Buffer (1 .. Name_Len); Foreword (Foreword'Last - Foreword_End'Length + 1 .. Foreword'Last) := Foreword_End; Prep.List_Symbols (Foreword); end; end if; declare T : constant Nat := Total_Errors_Detected; -- Used to check if there were errors during preprocessing Save_Style_Check : Boolean; -- Saved state of the Style_Check flag (which needs to be -- temporarily set to False during preprocessing, see below). Modified : Boolean; begin -- If this is the first time we preprocess a source, allocate -- the preprocessing buffer. if Prep_Buffer = null then Prep_Buffer := new Text_Buffer (1 .. Initial_Size_Of_Prep_Buffer); end if; -- Make sure the preprocessing buffer is empty Prep_Buffer_Last := 0; -- Initialize the preprocessor hooks Prep.Setup_Hooks (Error_Msg => Errout.Error_Msg'Access, Scan => Scn.Scanner.Scan'Access, Set_Ignore_Errors => Errout.Set_Ignore_Errors'Access, Put_Char => Put_Char_In_Prep_Buffer'Access, New_EOL => New_EOL_In_Prep_Buffer'Access); -- Initialize scanner and set its behavior for preprocessing, -- then preprocess. Also disable style checks, since some of -- them are done in the scanner (specifically, those dealing -- with line length and line termination), and cannot be done -- during preprocessing (because the source file index table -- has not been set yet). Scn.Scanner.Initialize_Scanner (X); Scn.Scanner.Set_Special_Character ('#'); Scn.Scanner.Set_Special_Character ('$'); Scn.Scanner.Set_End_Of_Line_As_Token (True); Save_Style_Check := Opt.Style_Check; Opt.Style_Check := False; -- The actual preprocessing step Preprocess (Modified); -- Reset the scanner to its standard behavior, and restore the -- Style_Checks flag. Scn.Scanner.Reset_Special_Characters; Scn.Scanner.Set_End_Of_Line_As_Token (False); Opt.Style_Check := Save_Style_Check; -- If there were errors during preprocessing, record an error -- at the start of the file, and do not change the source -- buffer. if T /= Total_Errors_Detected then Errout.Error_Msg ("file could not be successfully preprocessed", Lo); return No_Source_File; else -- Output the result of the preprocessing, if requested and -- the source has been modified by the preprocessing. Only -- do that for the main unit (spec, body and subunits). if Generate_Processed_File and then Modified and then ((Compiler_State = Parsing and then Parsing_Main_Extended_Source) or else (Compiler_State = Analyzing and then Analysing_Subunit_Of_Main)) then declare FD : File_Descriptor; NB : Integer; Status : Boolean; begin Get_Name_String (N); Add_Str_To_Name_Buffer (Prep_Suffix); Delete_File (Name_Buffer (1 .. Name_Len), Status); FD := Create_New_File (Name_Buffer (1 .. Name_Len), Text); Status := FD /= Invalid_FD; if Status then NB := Write (FD, Prep_Buffer (1)'Address, Integer (Prep_Buffer_Last)); Status := NB = Integer (Prep_Buffer_Last); end if; if Status then Close (FD, Status); end if; if not Status then Errout.Error_Msg ("??could not write processed file """ & Name_Buffer (1 .. Name_Len) & '"', Lo); end if; end; end if; -- Set the new value of Hi Hi := Lo + Source_Ptr (Prep_Buffer_Last); -- Create the new source buffer declare subtype Actual_Source_Buffer is Source_Buffer (Lo .. Hi); -- Physical buffer allocated type Actual_Source_Ptr is access Actual_Source_Buffer; -- Pointer type for the physical buffer allocated Actual_Ptr : constant Actual_Source_Ptr := new Actual_Source_Buffer; -- Actual physical buffer begin Actual_Ptr (Lo .. Hi - 1) := Prep_Buffer (1 .. Prep_Buffer_Last); Actual_Ptr (Hi) := EOF; -- Now we need to work out the proper virtual origin -- pointer to return. This is Actual_Ptr (0)'Address, but -- we have to be careful to suppress checks to compute -- this address. declare pragma Suppress (All_Checks); pragma Warnings (Off); -- This unchecked conversion is aliasing safe, since -- it is never used to create improperly aliased -- pointer values. function To_Source_Buffer_Ptr is new Unchecked_Conversion (Address, Source_Buffer_Ptr); pragma Warnings (On); begin Src := To_Source_Buffer_Ptr (Actual_Ptr (0)'Address); -- Record in the table the new source buffer and the -- new value of Hi. Source_File.Table (X).Source_Text := Src; Source_File.Table (X).Source_Last := Hi; -- Reset Last_Line to 1, because the lines do not -- have necessarily the same starts and lengths. Source_File.Table (X).Last_Source_Line := 1; end; end; end if; end; end if; Set_Source_File_Index_Table (X); return X; end if; end Load_File; ---------------------------------- -- Load_Preprocessing_Data_File -- ---------------------------------- function Load_Preprocessing_Data_File (N : File_Name_Type) return Source_File_Index is begin return Load_File (N, Osint.Preprocessing_Data); end Load_Preprocessing_Data_File; ---------------------- -- Load_Source_File -- ---------------------- function Load_Source_File (N : File_Name_Type) return Source_File_Index is begin return Load_File (N, Osint.Source); end Load_Source_File; ---------------------------- -- New_EOL_In_Prep_Buffer -- ---------------------------- procedure New_EOL_In_Prep_Buffer is begin Put_Char_In_Prep_Buffer (ASCII.LF); end New_EOL_In_Prep_Buffer; ----------------------------- -- Put_Char_In_Prep_Buffer -- ----------------------------- procedure Put_Char_In_Prep_Buffer (C : Character) is begin -- If preprocessing buffer is not large enough, double it if Prep_Buffer_Last = Prep_Buffer'Last then declare New_Prep_Buffer : constant Text_Buffer_Ptr := new Text_Buffer (1 .. 2 * Prep_Buffer_Last); begin New_Prep_Buffer (Prep_Buffer'Range) := Prep_Buffer.all; Free (Prep_Buffer); Prep_Buffer := New_Prep_Buffer; end; end if; Prep_Buffer_Last := Prep_Buffer_Last + 1; Prep_Buffer (Prep_Buffer_Last) := C; end Put_Char_In_Prep_Buffer; ------------------------- -- Source_File_Is_Body -- ------------------------- function Source_File_Is_Body (X : Source_File_Index) return Boolean is Pcount : Natural; begin Initialize_Scanner (No_Unit, X); -- Loop to look for subprogram or package body loop case Token is -- PRAGMA, WITH, USE (which can appear before a body) when Tok_Pragma | Tok_Use | Tok_With => -- We just want to skip any of these, do it by skipping to a -- semicolon, but check for EOF, in case we have bad syntax. loop if Token = Tok_Semicolon then Scan; exit; elsif Token = Tok_EOF then return False; else Scan; end if; end loop; -- PACKAGE when Tok_Package => Scan; -- Past PACKAGE -- We have a body if and only if BODY follows return Token = Tok_Body; -- FUNCTION or PROCEDURE when Tok_Function | Tok_Procedure => Pcount := 0; -- Loop through tokens following PROCEDURE or FUNCTION loop Scan; case Token is -- For parens, count paren level (note that paren level -- can get greater than 1 if we have default parameters). when Tok_Left_Paren => Pcount := Pcount + 1; when Tok_Right_Paren => Pcount := Pcount - 1; -- EOF means something weird, probably no body when Tok_EOF => return False; -- BEGIN or IS or END definitely means body is present when Tok_Begin | Tok_End | Tok_Is => return True; -- Semicolon means no body present if at outside any -- parens. If within parens, ignore, since it could be -- a parameter separator. when Tok_Semicolon => if Pcount = 0 then return False; end if; -- Skip anything else when others => null; end case; end loop; -- Anything else in main scan means we don't have a body when others => return False; end case; end loop; end Source_File_Is_Body; ---------------------------- -- Source_File_Is_No_Body -- ---------------------------- function Source_File_Is_No_Body (X : Source_File_Index) return Boolean is begin Initialize_Scanner (No_Unit, X); if Token /= Tok_Pragma then return False; end if; Scan; -- past pragma if Token /= Tok_Identifier or else Chars (Token_Node) /= Name_No_Body then return False; end if; Scan; -- past No_Body if Token /= Tok_Semicolon then return False; end if; Scan; -- past semicolon return Token = Tok_EOF; end Source_File_Is_No_Body; end Sinput.L;
{ "source": "starcoderdata", "programming_language": "ada" }
with impact.d3.Space; package impact.d3.Action is type Item is abstract tagged limited record null; end record; procedure updateAction (Self : in Item; collisionWorld : access impact.d3.Space.item'Class; deltaTimeStep : in math.Real ) is abstract; -- procedure destruct (Self : in out Item) is null; -- procedure DebugDraw (Self : in Item; -- debugDrawer : access btDebugDraw.item'Class) is abstract; end impact.d3.Action; -- #ifndef _BT_ACTION_INTERFACE_H -- #define _BT_ACTION_INTERFACE_H -- class btIDebugDraw; -- class impact.d3.Space; -- #include "LinearMath/impact.d3.Scalar.h" -- #include "impact.d3.Object.rigid.h" -- ///Basic interface to allow actions such as vehicles and characters to be updated inside a impact.d3.Space.dynamic -- class impact.d3.Action -- { -- protected: -- static impact.d3.Object.rigid& getFixedBody(); -- public: -- virtual ~impact.d3.Action() -- { -- } -- virtual void updateAction( impact.d3.Space* collisionWorld, impact.d3.Scalar deltaTimeStep)=0; -- virtual void debugDraw(btIDebugDraw* debugDrawer) = 0; -- }; -- #endif //_BT_ACTION_INTERFACE_H
{ "source": "starcoderdata", "programming_language": "ada" }
with AdaM.Entity, Ada.Containers.Vectors, Ada.Streams; package AdaM.a_Pragma is type Item is new Entity.item with private; -- View -- type View is access all Item'Class; procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : in View); procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : out View); for View'write use View_write; for View'read use View_read; -- Vector -- package Vectors is new ada.Containers.Vectors (Positive, View); subtype Vector is Vectors.Vector; -- Forge -- function new_Pragma (Name : in String := "") return a_Pragma.view; procedure free (Self : in out a_Pragma.view); procedure destruct (Self : in out a_Pragma.item); -- Attributes -- overriding function Id (Self : access Item) return AdaM.Id; overriding function Name (Self : in Item) return Identifier; procedure Name_is (Self : in out Item; Now : in String); procedure add_Argument (Self : in out Item; Now : in String); function Arguments (Self : in Item) return text_Lines; overriding function to_Source (Self : in Item) return text_Vectors.Vector; type Kind is (all_calls_remote, assert, assertion_policy, asynchronous, atomic, atomic_components, attach_handler, convention, cpu, default_storage_pool, detect_blocking, discard_names, dispatching_domain, elaborate, elaborate_all, elaborate_body, export, import, independent, independent_components, inline, inspection_point, interrupt_handler, interrupt_priority, linker_options, list, locking_policy, no_return, normalize_scalars, optimize, pack, page, partition_elaboration_policy, preelaborable_initialization, preelaborate, priority, priority_specific_dispatching, profile, pure, queuing_policy, relative_deadline, remote_call_interface, remote_types, restrictions, reviewable, shared_passive, storage_size, suppress, task_dispatching_policy, unchecked_union, unsuppress, volatile, volatile_components, assertion_policy_2); private type Item is new Entity.item with record Name : Text; Arguments : text_Lines; end record; end AdaM.a_Pragma;
{ "source": "starcoderdata", "programming_language": "ada" }
with Yaml.Events.Context; package body Yaml.Transformator.Annotation.Vars is procedure Put (Object : in out Instance; E : Event) is begin Object.State.all (Object, E); end Put; function Has_Next (Object : Instance) return Boolean is (False); function Next (Object : in out Instance) return Event is begin raise Constraint_Error with "no event available"; return (others => <>); end Next; function New_Vars (Pool : Text.Pool.Reference; Node_Context : Node_Context_Type; Processor_Context : Events.Context.Reference; Swallows_Previous : out Boolean) return not null Pointer is pragma Unreferenced (Pool); begin if Node_Context /= Document_Root then raise Annotation_Error with "@@vars may only be applied to a document's root node"; end if; Swallows_Previous := True; return new Instance'(Transformator.Instance with Context => Processor_Context, others => <>); end New_Vars; procedure Initial (Object : in out Instance; E : Event) is begin if E.Kind /= Annotation_Start then raise Stream_Error with "unexpected token (expected annotation start): " & E.Kind'Img; end if; Object.State := After_Annotation_Start'Access; end Initial; procedure After_Annotation_Start (Object : in out Instance; E : Event) is begin if E.Kind /= Annotation_End then raise Annotation_Error with "@@vars does not take any parameters."; end if; Object.State := After_Annotation_End'Access; end After_Annotation_Start; procedure After_Annotation_End (Object : in out Instance; E : Event) is begin if E.Kind /= Mapping_Start then raise Annotation_Error with "@@vars must be applied on a mapping."; end if; Object.State := At_Mapping_Level'Access; end After_Annotation_End; procedure At_Mapping_Level (Object : in out Instance; E : Event) is begin case E.Kind is when Scalar => Object.Cur_Name := E.Content; Object.State := Inside_Value'Access; when Mapping_End => Object.State := After_Mapping_End'Access; when others => raise Annotation_Error with "mapping annotated with @@vars must only have scalar keys"; end case; end At_Mapping_Level; procedure Inside_Value (Object : in out Instance; E : Event) is use type Events.Context.Location_Type; use type Text.Reference; begin if Object.Depth = 0 then declare Modified_Event : Event := E; begin case E.Kind is when Scalar => Modified_Event.Scalar_Properties.Anchor := Object.Cur_Name; when Mapping_Start | Sequence_Start => Modified_Event.Collection_Properties.Anchor := Object.Cur_Name; when Alias => declare Pos : constant Events.Context.Cursor := Events.Context.Position (Object.Context, E.Target); begin if Events.Context.Location (Pos) = Events.Context.None then raise Annotation_Error with "unresolvable alias: *" & E.Target; end if; declare Referenced_Events : constant Events.Store.Stream_Reference := Events.Context.Retrieve (Pos); Depth : Natural := 0; begin Modified_Event := Referenced_Events.Value.Next; case Modified_Event.Kind is when Mapping_Start | Sequence_Start => Modified_Event.Collection_Properties.Anchor := Object.Cur_Name; when Scalar => Modified_Event.Scalar_Properties.Anchor := Object.Cur_Name; when others => raise Program_Error with "alias referenced " & Modified_Event.Kind'Img; end case; loop Object.Context.Stream_Store.Memorize (Modified_Event); case Modified_Event.Kind is when Mapping_Start | Sequence_Start => Depth := Depth + 1; when Mapping_End | Sequence_End => Depth := Depth - 1; when others => null; end case; exit when Depth = 0; Modified_Event := Referenced_Events.Value.Next; end loop; end; end; Object.State := At_Mapping_Level'Access; return; when others => raise Stream_Error with "Unexpected event (expected node start): " & E.Kind'Img; end case; Object.Cur_Queue.Append (Modified_Event); end; elsif E.Kind = Alias then declare Pos : constant Events.Context.Cursor := Events.Context.Position (Object.Context, E.Target); begin if Events.Context.Location (Pos) = Events.Context.None then raise Annotation_Error with "unresolvable alias: *" & E.Target; end if; declare Referenced_Events : constant Events.Store.Stream_Reference := Events.Context.Retrieve (Pos); Depth : Natural := 0; Cur_Event : Event := Referenced_Events.Value.Next; begin loop Object.Cur_Queue.Append (Cur_Event); case Cur_Event.Kind is when Mapping_Start | Sequence_Start => Depth := Depth + 1; when Mapping_End | Sequence_End => Depth := Depth - 1; when others => null; end case; exit when Depth = 0; Cur_Event := Referenced_Events.Value.Next; end loop; end; end; else Object.Cur_Queue.Append (E); end if; case E.Kind is when Mapping_Start | Sequence_Start => Object.Depth := Object.Depth + 1; return; when Mapping_End | Sequence_End => Object.Depth := Object.Depth - 1; when others => null; end case; if Object.Depth = 0 then loop Object.Context.Stream_Store.Memorize (Object.Cur_Queue.First); Object.Cur_Queue.Dequeue; exit when Object.Cur_Queue.Length = 0; end loop; Object.State := At_Mapping_Level'Access; end if; end Inside_Value; procedure After_Mapping_End (Object : in out Instance; E : Event) is begin raise Constraint_Error with "unexpected input to @@vars (already finished)"; end After_Mapping_End; begin Map.Include ("vars", New_Vars'Access); end Yaml.Transformator.Annotation.Vars;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with AWA.Tests; with Jason.Applications; with Jason.Projects.Tests; with Jason.Tickets.Tests; package body Jason.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is begin Jason.Projects.Tests.Add_Tests (Tests'Access); Jason.Tickets.Tests.Add_Tests (Tests'Access); return Tests'Access; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is App : constant Jason.Applications.Application_Access := Jason.Applications.Create; begin -- Jason.Applications.Initialize (App); -- ASF.Server.Tests.Set_Context (App.all'Access); AWA.Tests.Initialize (App.all'Access, Props, True); end Initialize; end Jason.Testsuite;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Ada_2012; pragma Style_Checks (Off); pragma Warnings ("U"); with Interfaces.C; use Interfaces.C; with sys_ustdint_h; with arm_math_types_h; package bayes_functions_h is type arm_gaussian_naive_bayes_instance_f32 is record vectorDimension : aliased sys_ustdint_h.uint32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:59 numberOfClasses : aliased sys_ustdint_h.uint32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:60 theta : access arm_math_types_h.float32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:61 sigma : access arm_math_types_h.float32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:62 classPriors : access arm_math_types_h.float32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:63 epsilon : aliased arm_math_types_h.float32_t; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:64 end record with Convention => C_Pass_By_Copy; -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:65 function arm_gaussian_naive_bayes_predict_f32 (S : access constant arm_gaussian_naive_bayes_instance_f32; c_in : access arm_math_types_h.float32_t; pOutputProbabilities : access arm_math_types_h.float32_t; pBufferB : access arm_math_types_h.float32_t) return sys_ustdint_h.uint32_t -- ../CMSIS_5/CMSIS/DSP/Include/dsp/bayes_functions.h:79 with Import => True, Convention => C, External_Name => "arm_gaussian_naive_bayes_predict_f32"; end bayes_functions_h;
{ "source": "starcoderdata", "programming_language": "ada" }
package physics.Joint.hinge -- -- An interface to a hinge joint. -- is type Item is limited interface and Joint.item; type View is access all Item'Class; procedure Limits_are (Self : in out Item; Low, High : in Real; Softness : in Real := 0.9; biasFactor : in Real := 0.3; relaxationFactor : in Real := 1.0) is abstract; function lower_Limit (Self : in Item) return Real is abstract; function upper_Limit (Self : in Item) return Real is abstract; function Angle (Self : in Item) return Real is abstract; end physics.Joint.hinge;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; with Randomise; use Randomise; procedure Main is C : Character; S : R_String.Bounded_String; Are_Inside_Tag : Boolean := False; begin while not End_Of_File loop Get_Immediate(C); if Are_Inside_Tag then if C in '<'|'"' then Are_Inside_Tag := False; Randomise_String(S); Put(R_String.To_String(S)); S := R_String.To_Bounded_String(""); Put(C); else R_String.Append(S, C); end if; elsif C in '>'|'"' then Are_Inside_Tag := True; S := R_String.To_Bounded_String(""); Put(C); else Put(C); end if; end loop; end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
-- ------------------------------------------------------------------------ ------------------------------------------------------------------------ -- -- Ada support for leveled logs. Based on Google's glog -- ------------------------------------------------------------------------ with GNAT.Source_Info; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; package Alog is package ASU renames Ada.Strings.Unbounded; -- Four levels of loggging. type Level is ( INFO, WARN, ERROR, FATAL ); -- Type representing where things are logged to. type LogTo is ( NONE, STDOUT, FILE, BOTH ); --------------------------------------------------------------------- -- Logging --------------------------------------------------------------------- -- Methods for each log message level. procedure Info (Msg : String); procedure Warn (Msg : String); procedure Error (Msg : String); procedure Fatal (Msg : String); procedure Vlog (Lvl : Natural; Msg : String; Source : String := GNAT.Source_Info.Source_Location); --------------------------------------------------------------------- -- Configuration --------------------------------------------------------------------- -- Set where the logs saved. By default set to BOTH. procedure Set_LogTo (Output : LogTo); -- Helper method to you can pass a String representation of LogTo. procedure Set_LogTo (Output : String); -- Set what the threshold level of stdout will be. procedure Set_Stdout_Threshold (Lvl : Level); -- Helper method to you can pass a String representation of Level. procedure Set_Stdout_Threshold (Lvl : String); -- Set where the log files shoudl be saved. procedure Set_File_Path (Path : String); -- Set the Vlog Threshold. procedure Set_Vlog_Threshold (Lvl : Natural); -- blah procedure Set_Vlog_Modules (Mods : String); --------------------------------------------------------------------- -- Statistics --------------------------------------------------------------------- -- Return the number of lines written to a specified log file. function Lines (Lvl : Level) return Natural; private -- Record of statistics about the log levels. type Level_Stats is record Lines : Natural := 0; end record; -- Array of level stats for each log level. type Log_Stats is array (Level) of Level_Stats; Stats : Log_Stats; function Program_Name (Cmd : String) return String; function Program_Time (Time : String) return String; function Format_Module (Source : String) return String; procedure Vmodule_Setup (Mods : String); Files_Created : Boolean := False; Files_Location_Set : Boolean := False; function Equivalent_Strings (Left, Right : ASU.Unbounded_String) return Boolean; package Module is new Ada.Containers.Hashed_Maps (Key_Type => ASU.Unbounded_String, Element_Type => Natural, Hash => ASU.Hash, Equivalent_Keys => Equivalent_Strings); Modules_Map : Module.Map; end Alog;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; procedure Count_The_Coins is type Counter_Type is range 0 .. 2**63-1; -- works with gnat type Coin_List is array(Positive range <>) of Positive; function Count(Goal: Natural; Coins: Coin_List) return Counter_Type is Cnt: array(0 .. Goal) of Counter_Type := (0 => 1, others => 0); -- 0 => we already know one way to choose (no) coins that sum up to zero -- 1 .. Goal => we do not (yet) other ways to choose coins begin for C in Coins'Range loop for Amount in 1 .. Cnt'Last loop if Coins(C) <= Amount then Cnt(Amount) := Cnt(Amount) + Cnt(Amount-Coins(C)); -- Amount-Coins(C) plus Coins(C) sums up to Amount; end if; end loop; end loop; return Cnt(Goal); end Count; procedure Print(C: Counter_Type) is begin Ada.Text_IO.Put_Line(Counter_Type'Image(C)); end Print; begin Print(Count( 1_00, (25, 10, 5, 1))); Print(Count(1000_00, (100, 50, 25, 10, 5, 1))); end Count_The_Coins;
{ "source": "starcoderdata", "programming_language": "ada" }
package body GDB_Remote is -------------- -- From_Hex -- -------------- function From_Hex (Str : String) return Unsigned_64 is Res : Unsigned_64 := 0; begin for C of Str loop Res := Shift_Left (Res, 4); Res := Res + Unsigned_64 (From_Hex (C)); end loop; return Res; end From_Hex; ------------------ -- Parse_Packet -- ------------------ function Parse_Packet (Str : String; Cursor : out Natural) return Packet is begin Cursor := Str'First + 1; case Str (Str'First) is when 'c' => return Parse_Continue (Str, Cursor); when 'D' => return (Kind => Detach); when 's' => return Parse_Single_Step (Str, Cursor); when 'q' => return Parse_General_Query (Str, Cursor); when 'v' => return Parse_v_Packet (Str, Cursor); when 'H' => return Parse_Set_Thread (Str, Cursor); when '?' => return (Kind => Question_Halt); when 'g' => return (Kind => Read_General_Registers); when 'p' => return Parse_Read_Register (Str, Cursor); when 'm' => return Parse_Read_Memory (Str, Cursor); when 'M' => return Parse_Write_Memory (Str, Cursor, Hexadecimal); when 'X' => return Parse_Write_Memory (Str, Cursor, Binary); when 'z' => return Parse_Breakpoint (Str, Cursor, Insert => False); when 'Z' => return Parse_Breakpoint (Str, Cursor, Insert => True); when others => return (Kind => Unknown_Packet); end case; end Parse_Packet; ------------------------- -- Parse_General_Query -- ------------------------- function Parse_General_Query (Str : String; Cursor : in out Natural) return Packet is Topic_Str : constant String := Next_Field (Str, Cursor); Topic : General_Query_Topic := Unknown_General_Query; begin if Topic_Str = "Supported" then Topic := Supported; elsif Topic_Str = "TStatus" then Topic := TStatus; elsif Topic_Str = "Attached" then Topic := Attached; elsif Topic_Str = "fThreadInfo" then Topic := Thread_Info_Start; elsif Topic_Str = "sThreadInfo" then Topic := Thread_Info_Cont; end if; return (Kind => General_Query, Q_Topic => Topic); end Parse_General_Query; ------------------- -- Parse_v_Query -- ------------------- function Parse_v_Packet (Str : String; Cursor : in out Natural) return Packet is Id_Str : constant String := Next_Field (Str, Cursor); begin Cursor := Str'Last + 1; if Id_Str = "MustReplyEmpty" then return (Kind => Must_Reply_Empty); elsif Id_Str = "Cont?" then return (Kind => Query_Supported_Continue); else return (Kind => Unknown_Packet); end if; end Parse_v_Packet; ---------------------- -- Parse_Set_Thread -- ---------------------- function Parse_Set_Thread (Str : String; Cursor : in out Natural) return Packet is Res : Packet := (Kind => Set_Thread, others => <>); begin if Str'Length < 3 then return (Kind => Bad_Packet); end if; Res.Op := Str (Cursor); Res.Thread_ID := To_Int (Str (Cursor + 1 .. Str'Last)); Cursor := Str'Last + 1; return Res; end Parse_Set_Thread; ------------------------- -- Parse_Read_Register -- ------------------------- function Parse_Read_Register (Str : String; Cursor : in out Natural) return Packet is Res : Packet := (Kind => Read_Register, others => <>); begin if Str'Length < 2 then return (Kind => Bad_Packet); end if; Res.Register_Id := To_Int (Str (Cursor .. Str'Last)); Cursor := Str'Last + 1; return Res; end Parse_Read_Register; ----------------------- -- Parse_Read_Memory -- ----------------------- function Parse_Read_Memory (Str : String; Cursor : in out Natural) return Packet is Res : Packet := (Kind => Read_Memory, others => <>); Addr_Str : constant String := Next_Field (Str, Cursor); Size_Str : constant String := Next_Field (Str, Cursor); begin Res.M_Address := From_Hex (Addr_Str); Res.M_Size := From_Hex (Size_Str); return Res; end Parse_Read_Memory; ------------------------ -- Parse_Write_Memory -- ------------------------ function Parse_Write_Memory (Str : String; Cursor : in out Natural; Fmt : Data_Format) return Packet is Res : Packet := (Kind => Write_Memory, others => <>); Addr_Str : constant String := Next_Field (Str, Cursor); Size_Str : constant String := Next_Field (Str, Cursor); begin Res.M_Address := From_Hex (Addr_Str); Res.M_Size := From_Hex (Size_Str); Res.M_Data_Fmt := Fmt; return Res; end Parse_Write_Memory; -------------------- -- Parse_Continue -- -------------------- function Parse_Continue (Str : String; Cursor : in out Natural) return Packet is Addr : Integer; begin if Str'Length > 1 then Addr := To_Int (Str (Cursor .. Str'Last)); Cursor := Str'Last + 1; return (Kind => Continue_Addr, C_Address => Unsigned_64 (Addr)); else return (Kind => Continue); end if; end Parse_Continue; ----------------------- -- Parse_Single_Step -- ----------------------- function Parse_Single_Step (Str : String; Cursor : in out Natural) return Packet is Addr : Integer; begin if Str'Length > 1 then Addr := To_Int (Str (Cursor .. Str'Last)); Cursor := Str'Last + 1; return (Kind => Single_Step_Addr, C_Address => Unsigned_64 (Addr)); else return (Kind => Single_Step); end if; end Parse_Single_Step; ---------------------- -- Parse_Breakpoint -- ---------------------- function Parse_Breakpoint (Str : String; Cursor : in out Natural; Insert : Boolean) return Packet is Type_Str : constant String := Next_Field (Str, Cursor); Addr_Str : constant String := Next_Field (Str, Cursor); Kind_Str : constant String := Next_Field (Str, Cursor); B_Type : Breakpoint_Type; B_Kind : Natural; B_Addr : Unsigned_64; begin if Type_Str'Length /= 1 then return (Kind => Bad_Packet); end if; case Type_Str (Type_Str'First) is when '0' => B_Type := Software_Breakpoint; when '1' => B_Type := Hardware_Breakpoint; when '2' => B_Type := Write_Watchpoint; when '3' => B_Type := Read_Watchpoint; when '4' => B_Type := Access_Watchpoint; when others => return (Kind => Bad_Packet); end case; B_Addr := From_Hex (Addr_Str); B_Kind := Natural (From_Hex (Kind_Str)); if Insert then return (Kind => Insert_Breakpoint, B_Type => B_Type, B_Addr => B_Addr, B_Kind => B_Kind); else return (Kind => Remove_Breakpoint, B_Type => B_Type, B_Addr => B_Addr, B_Kind => B_Kind); end if; end Parse_Breakpoint; ---------------- -- Next_Field -- ---------------- function Next_Field (P : String; Cursor : in out Natural) return String is From : constant Natural := Cursor; To : Natural; begin while Cursor in P'First .. P'Last and then P (Cursor) not in ':' | ';' | ',' loop Cursor := Cursor + 1; end loop; To := Cursor - 1; Cursor := Cursor + 1; return P (From .. To); end Next_Field; --------------- -- Next_Data -- --------------- function Next_Data (P : String; Cursor : in out Natural; Fmt : Data_Format; Success : out Boolean) return Unsigned_8 is Res : Unsigned_8; begin case Fmt is when Hexadecimal => if Cursor in P'First .. P'Last - 1 then Success := True; return Unsigned_8 (From_Hex (P (Cursor .. Cursor + 1))); end if; when Binary => if Cursor in P'First .. P'Last then if P (Cursor) = '}' then -- Escape character Cursor := Cursor + 1; if Cursor <= P'Last then Res := Unsigned_8 (P (Cursor)'Enum_Rep) xor 16#20#; Cursor := Cursor + 1; Success := True; return Res; end if; else Res := Unsigned_8 (P (Cursor)'Enum_Rep); Cursor := Cursor + 1; Success := True; return Res; end if; end if; end case; Success := False; return 0; end Next_Data; ------------ -- To_Int -- ------------ function To_Int (Str : String) return Integer is Res : Integer := 0; Cursor : Natural; begin if Str (Str'First) = '-' then Cursor := Str'First + 1; else Cursor := Str'First; end if; while Cursor <= Str'Last loop Res := Res * 16 + Integer (From_Hex (Str (Cursor))); Cursor := Cursor + 1; end loop; if Str (Str'First) = '-' then return -Res; else return Res; end if; end To_Int; end GDB_Remote;
{ "source": "starcoderdata", "programming_language": "ada" }
-------------------------------------------------------------------------------- -- An Ada implementation of the Advent Of Code 2018 -- -- -- -- Day 2: Inventory Management System -- -- -- -- The following is an MCW example (outside of data) for day 2 of AOC 2018. -- -- See: <https://adventofcode.com/2018> for the whole event. -- -------------------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; procedure Day02 is package ASU renames Ada.Strings.Unbounded; -- for convenience purpose type US_Array is array(Positive range <>) of ASU.Unbounded_String; -- The IDs in the input data are all the same length, so we could use a -- fixed-length String array, but it would not be very generic, and it would -- not be suited for examples either. type Natural_Couple is array(1..2) of Natural; -- This data structure will be used to store two things: -- * IDs that have exactly 2 of any letter and exactly 3 of any letter; -- * the absolute count of IDs for the previous item. -- I could/should use a record for that, but meh, later maybe. type Character_Count is array(Character range 'a' .. 'z') of Natural; -- An array indexed on characters that will be used to count occurrences. -- This is not very generic (cough), but it will do for the input. -- Creates the "String" array from the file name function Read_Input(file_name : in String) return US_Array is -- Tail-call recursion to create the final array. function Read_Input_Rec(input : in Ada.Text_IO.File_Type; acc : in US_Array) return US_Array is begin if Ada.Text_IO.End_Of_File(input) then return acc; else return Read_Input_Rec ( input, acc & (1 => ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(input))) ); end if; end Read_Input_Rec; F : Ada.Text_IO.File_Type; acc : US_Array(1 .. 0); begin Ada.Text_IO.Open ( File => F, Mode => Ada.Text_IO.In_File, Name => file_name ); declare result : US_Array := Read_Input_Rec(F, acc); begin Ada.Text_IO.Close(F); return result; end; end Read_Input; -- the number that have an ID containing exactly two of any letter and then -- separately counting those with exactly three of any letter. -- You can multiply those two counts together to get a rudimentary checksum. function Checksum(nc : Natural_Couple) return Natural is begin return nc(1) * nc(2); end Checksum; function Common_Part(left, right : in String) return String is function Common_Part_Rec(li, ri : in Positive; acc : in String) return String is begin if li > left'Last then return acc; else return Common_Part_Rec ( li+1, ri+1, acc & (if left(li) = right(ri) then (1 => left(li)) else "") ); end if; end Common_Part_Rec; begin return Common_Part_Rec(left'First, right'First, ""); end Common_Part; function Part_1(input : in US_Array) return Natural is total_count : Natural_Couple := (0, 0); begin for ID of input loop declare counts : Character_Count := (others => 0); current_count : Natural_Couple := (0, 0); begin for C of ASU.To_String(ID) loop counts(C) := counts(C) + 1; end loop; for count of counts loop if count = 2 then current_count(1) := 1; elsif count = 3 then current_count(2) := 1; end if; exit when current_count = (1, 1); end loop; total_count(1) := total_count(1) + current_count(1); total_count(2) := total_count(2) + current_count(2); end; end loop; return Checksum(total_count); end Part_1; function Part_2(input : in US_Array) return String is begin for I in input'Range loop for J in I+1 .. input'Last loop declare common : constant String := Common_Part ( ASU.To_String(input(I)), ASU.To_String(input(J)) ); begin if common'Length = ASU.Length(input(I)) - 1 then return common; end if; end; end loop; end loop; return ""; end Part_2; input : constant US_Array := Read_Input("input/day02.txt"); begin Ada.Text_IO.Put_Line("What is the checksum for your list of box IDs?"); Ada.Text_IO.Put_Line(Natural'Image(Part_1(input))); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line("What letters are common between the two correct box IDs?"); Ada.Text_IO.Put_Line(Part_2(input)); end Day02;
{ "source": "starcoderdata", "programming_language": "ada" }
generic package SipHash.Entropy with SPARK_Mode => On is Entropy_Unavailable : exception; -- This function indicates whether the program has been compiled with the -- possibility to set the SipHash key from system entropy. Note that even -- if this returns true it is still possible for Set_Key_From_System_Entropy -- to fail, for example if there is an IO error or the system declines to -- provide enough entropy. function System_Entropy_Source return Boolean; -- This procedure will set the SipHash key from a system entropy source, -- unless System_Entropy_Source is False or the system returns insufficient -- data, in which case it will raise No_Entropy_Available. procedure Set_Key_From_System_Entropy with Global => (Output => Initial_Hash_State); -- This procedure will set the SipHash key from a system entropy source, -- returning a boolean to indicate if it was successful. Failure can be -- caused by having no entropy source compiled into the library, or by an -- inability to retrieve sufficient data from the system. -- It would be nice to make this a function, but functions with side effects -- are not permitted by SPARK. procedure Set_Key_From_System_Entropy (Success : out Boolean) with Global => (Output => Initial_Hash_State); end SipHash.Entropy;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- -- For more information please go to http://www.gnoga.com -- ------------------------------------------------------------------------------ with Ada.Strings.Unbounded; with Ada.Exceptions; with Ada_GUI.Gnoga.Server.Connection; package body Ada_GUI.Gnoga.Gui.Element.Canvas is -------------- -- Finalize -- -------------- overriding procedure Finalize (Object : in out Context_Type) is begin Gnoga.Server.Connection.Execute_Script (Object.Connection_ID, "delete gnoga['" & Ada.Strings.Unbounded.To_String (Object.Context_ID) & "'];"); exception when E : Gnoga.Server.Connection.Connection_Error => Log ("Connection" & Object.Connection_ID'Img & " error during delete object " & Ada.Strings.Unbounded.To_String (Object.Context_ID)); Log (Ada.Exceptions.Exception_Information (E)); end Finalize; ------------ -- Create -- ------------ procedure Create (Canvas : in out Canvas_Type; Parent : in out Gnoga.Gui.Base_Type'Class; Width : in Integer; Height : in Integer; ID : in String := "") is begin Canvas.Create_From_HTML (Parent, "<canvas width=" & Width'Img & " height =" & Height'Img & ">", ID); end Create; ------------------- -- Connection_ID -- ------------------- function Connection_ID (Context : Context_Type) return Gnoga.Connection_ID is begin return Context.Connection_ID; end Connection_ID; -------- -- ID -- -------- function ID (Context : Context_Type) return String is use Ada.Strings.Unbounded; begin return To_String (Context.Context_ID); end ID; -------------- -- Property -- -------------- procedure Property (Context : in out Context_Type; Name : in String; Value : in String) is begin Context.Execute (Name & "='" & Escape_Quotes (Value) & "';"); end Property; procedure Property (Context : in out Context_Type; Name : in String; Value : in Integer) is begin Context.Execute (Name & "=" & Value'Img & ";"); end Property; procedure Property (Context : in out Context_Type; Name : in String; Value : in Boolean) is begin Context.Execute (Name & "=" & Value'Img & ";"); end Property; procedure Property (Context : in out Context_Type; Name : in String; Value : in Float) is begin Context.Execute (Name & "=" & Value'Img & ";"); end Property; function Property (Context : Context_Type; Name : String) return String is begin return Context.Execute (Name); end Property; function Property (Context : Context_Type; Name : String) return Integer is begin return Integer'Value (Context.Property (Name)); exception when E : others => Log ("Error Property converting to Integer (forced to 0)."); Log (Ada.Exceptions.Exception_Information (E)); return 0; end Property; function Property (Context : Context_Type; Name : String) return Boolean is begin return Boolean'Value (Context.Property (Name)); exception when E : others => Log ("Error Property converting to Boolean (forced to False)."); Log (Ada.Exceptions.Exception_Information (E)); return False; end Property; function Property (Context : Context_Type; Name : String) return Float is begin return Float'Value (Context.Property (Name)); exception when E : others => Log ("Error Property converting to Float (forced to 0.0)."); Log (Ada.Exceptions.Exception_Information (E)); return 0.0; end Property; ------------- -- Execute -- ------------- procedure Execute (Context : in out Context_Type; Method : String) is begin Gnoga.Server.Connection.Execute_Script (ID => Context.Connection_ID, Script => "gnoga['" & Context.ID & "']." & Method); end Execute; function Execute (Context : Context_Type; Method : String) return String is begin return Gnoga.Server.Connection.Execute_Script (ID => Context.Connection_ID, Script => "gnoga['" & Context.ID & "']." & Method); end Execute; end Ada_GUI.Gnoga.Gui.Element.Canvas;
{ "source": "starcoderdata", "programming_language": "ada" }
--____________________________________________________________________-- with System; use System; package body Object.Handle is procedure Adjust (Reference : in out Handle) is begin if Reference.Ptr /= null then Increment_Count (Reference.Ptr.all); end if; end Adjust; procedure Finalize (Reference : in out Handle) is begin Release (Reference.Ptr); Reference.Ptr := null; end Finalize; procedure Invalidate (Reference : in out Handle) is begin if Reference.Ptr /= null then Release (Reference.Ptr); Reference.Ptr := null; end if; end Invalidate; function Is_Valid (Reference : Handle) return Boolean is begin return Reference.Ptr /= null; end Is_Valid; function Ptr (Reference : Handle) return Object_Type_Ptr is begin return Reference.Ptr; end Ptr; function Ref (Thing : Object_Type_Ptr) return Handle is begin if Thing /= null then Increment_Count (Thing.all); end if; return Handle'(Ada.Finalization.Controlled with Thing); end Ref; procedure Release (Ptr : in out Object_Type_Ptr) is begin if Ptr /= null then declare -- -- We have to use an unchecked access here, because -- otherwise accessibility check might fail when -- Object_Type_Ptr is a local access type. -- Pointer : Entity_Ptr := Ptr.all'Unchecked_Access; begin Release (Pointer); if Pointer = null then Ptr := null; end if; end; end if; end Release; procedure Set (Reference : in out Handle; Thing : Object_Type_Ptr) is begin if Reference.Ptr /= Thing then if Reference.Ptr /= null then Release (Reference.Ptr); Reference.Ptr := null; end if; if Thing /= null then Increment_Count (Thing.all); Reference.Ptr := Thing; end if; end if; end Set; function "<" (Left, Right : Handle) return Boolean is begin return Less (Left.Ptr.all, Right.Ptr.all); end "<"; function "<=" (Left, Right : Handle) return Boolean is begin return ( Equal (Left.Ptr.all, Right.Ptr.all) or else Less (Left.Ptr.all, Right.Ptr.all) ); end "<="; function "=" (Left, Right : Handle) return Boolean is begin if Left.Ptr = null then if Right.Ptr = null then return True; else return False; end if; else if Right.Ptr = null then return False; else return Equal (Left.Ptr.all, Right.Ptr.all); end if; end if; end "="; function ">=" (Left, Right : Handle) return Boolean is begin return not Less (Left.Ptr.all, Right.Ptr.all); end ">="; function ">" (Left, Right : Handle) return Boolean is begin return not ( Equal (Left.Ptr.all, Right.Ptr.all) or else Less (Left.Ptr.all, Right.Ptr.all) ); end ">"; function "=" (Left : Handle; Right : access Object_Type'Class) return Boolean is begin return ( Left.Ptr /= null and then Left.Ptr.all'Address = Right.all'Address ); end "="; function "=" (Left : access Object_Type'Class; Right : Handle) return Boolean is begin return ( Right.Ptr /= null and then Right.Ptr.all'Address = Left.all'Address ); end "="; end Object.Handle;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- Ada version by yt -- This file is encoded as Latin-1 -- with Ada.Text_IO; with Ada.Unchecked_Conversion; with System; with C.stdio; with C.stdlib; with C.string; with C.libxml.encoding; with C.libxml.xmlwriter; with C.libxml.globals; with C.libxml.parser; with C.libxml.tree; with C.libxml.xmlmemory; with C.libxml.xmlstring; with C.libxml.xmlversion; --pragma Compile_Time_Error ( -- not C.libxml.xmlversion.LIBXML_WRITER_ENABLED -- or else not C.libxml.xmlversion.LIBXML_OUTPUT_ENABLED, -- "Writer or output support not compiled in"); procedure test_writer is pragma Linker_Options ("-lxml2"); use type C.char; use type C.char_array; use type C.signed_int; use type C.size_t; use type C.libxml.encoding.xmlCharEncodingHandlerPtr; use type C.libxml.tree.xmlBufferPtr; use type C.libxml.tree.xmlDocPtr; use type C.libxml.tree.xmlNodePtr; use type C.libxml.xmlstring.xmlChar_ptr; use type C.libxml.xmlwriter.xmlTextWriterPtr; function To_void_ptr is new Ada.Unchecked_Conversion ( C.libxml.xmlstring.xmlChar_ptr, C.void_ptr); function To_char_const_ptr is new Ada.Unchecked_Conversion ( C.libxml.xmlstring.xmlChar_ptr, C.char_const_ptr); function To_unsigned_char_const_ptr is new Ada.Unchecked_Conversion ( C.char_const_ptr, C.unsigned_char_const_ptr); function To_xmlChar_ptr is new Ada.Unchecked_Conversion ( C.void_ptr, C.libxml.xmlstring.xmlChar_ptr); function To_xmlChar_const_ptr is new Ada.Unchecked_Conversion ( C.char_const_ptr, C.libxml.xmlstring.xmlChar_ptr); MY_ENCODING : constant C.char_array := "ISO-8859-1" & C.char'Val (0); -- ConvertInput: -- @in: string in a given encoding -- @encoding: the encoding used -- -- Converts @in into UTF-8 for processing with libxml2 APIs -- -- Returns the converted UTF-8 string, or NULL in case of error. function ConvertInput (A_in : C.char_array; encoding : C.char_array) return C.libxml.xmlstring.xmlChar_ptr is pragma Assert (A_in'Length > 0 and then A_in (A_in'Last) = C.char'Val (0)); pragma Assert ( encoding'Length > 0 and then encoding (encoding'Last) = C.char'Val (0)); L_out : C.libxml.xmlstring.xmlChar_ptr; ret : C.signed_int; size : C.signed_int; out_size : aliased C.signed_int; temp : aliased C.signed_int; handler : C.libxml.encoding.xmlCharEncodingHandlerPtr; begin handler := C.libxml.encoding.xmlFindCharEncodingHandler ( encoding (encoding'First)'Access); if handler = null then declare encoding_String : String (1 .. encoding'Length - 1); for encoding_String'Address use encoding'Address; begin raise Program_Error with "ConvertInput: no encoding handler found for '" & encoding_String & "'"; end; end if; size := C.signed_int (C.string.strlen (A_in (A_in'First)'Access)) + 1; out_size := size * 2 - 1; L_out := To_xmlChar_ptr (C.libxml.globals.xmlMalloc (C.size_t (out_size))); if L_out /= null then temp := size - 1; ret := handler.input ( L_out, out_size'Access, To_unsigned_char_const_ptr (A_in (A_in'First)'Unchecked_Access), temp'Access); if ret < 0 or else temp - size + 1 /= 0 then C.libxml.globals.xmlFree (To_void_ptr (L_out)); L_out := null; if ret < 0 then raise Program_Error with "ConvertInput: conversion wasn't successful."; else raise Program_Error with "ConvertInput: conversion wasn't successful. converted:" & C.signed_int'Image (temp) & " octets."; end if; else L_out := To_xmlChar_ptr ( C.libxml.globals.xmlRealloc (To_void_ptr (L_out), C.size_t (out_size) + 1)); declare out_Array : array (0 .. C.size_t (out_size)) of C.libxml.xmlstring.xmlChar with Convention => C; for out_Array'Address use System.Address (To_void_ptr (L_out)); begin out_Array (C.size_t (out_size)) := C.libxml.xmlstring.xmlChar'Val (0); -- null terminating out end; end if; else raise Program_Error with "ConvertInput: no mem"; end if; return L_out; end ConvertInput; -- shared procedure Write_Sample_XML (writer : C.libxml.xmlwriter.xmlTextWriterPtr) is rc : C.signed_int; tmp : C.libxml.xmlstring.xmlChar_ptr; begin -- Write a comment as child of EXAMPLE. -- Please observe, that the input to the xmlTextWriter functions -- HAS to be in UTF-8, even if the output XML is encoded -- in iso-8859-1 tmp := ConvertInput ( "This is a comment with special chars: <" & C.char'Val (16#E4#) & C.char'Val (16#F6#) & C.char'Val (16#FC#) & ">" & C.char'Val (0), MY_ENCODING); rc := C.libxml.xmlwriter.xmlTextWriterWriteComment (writer, tmp); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteComment"; end if; if tmp /= null then C.libxml.globals.xmlFree (To_void_ptr (tmp)); end if; -- Start an element named "ORDER" as child of EXAMPLE. declare Name : constant C.char_array := "ORDER" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Add an attribute with name "version" and value "1.0" to ORDER. declare Name : constant C.char_array := "version" & C.char'Val (0); Format : constant C.char_array := "1.0" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteAttribute ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteAttribute"; end if; -- Add an attribute with name "xml:lang" and value "de" to ORDER. declare Name : constant C.char_array := "xml:lang" & C.char'Val (0); Format : constant C.char_array := "de" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteAttribute ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteAttribute"; end if; -- Write a comment as child of ORDER tmp := ConvertInput ( "<" & C.char'Val (16#E4#) & C.char'Val (16#F6#) & C.char'Val (16#FC#) & ">" & C.char'Val (0), MY_ENCODING); declare Format : constant C.char_array := "This is another comment with special chars: " & C.char'Val (0); Value : C.char_array (0 .. 255); Dummy_char_ptr : C.char_ptr; begin Dummy_char_ptr := C.string.strcpy ( Value (Value'First)'Access, Format (Format'First)'Access); Dummy_char_ptr := C.string.strcat ( Value (Value'First)'Access, To_char_const_ptr (tmp)); rc := C.libxml.xmlwriter.xmlTextWriterWriteComment ( writer, To_xmlChar_const_ptr (Value (Value'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteFormatComment"; end if; if tmp /= null then C.libxml.globals.xmlFree (To_void_ptr (tmp)); end if; -- Start an element named "HEADER" as child of ORDER. declare Name : constant C.char_array := "HEADER" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Write an element named "X_ORDER_ID" as child of HEADER. declare Name : constant C.char_array := "X_ORDER_ID" & C.char'Val (0); Format : constant C.char_array := "0000053535" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteFormatElement"; end if; -- Write an element named "CUSTOMER_ID" as child of HEADER. declare Name : constant C.char_array := "CUSTOMER_ID" & C.char'Val (0); Format : constant C.char_array := "1010" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteFormatElement"; end if; -- Write an element named "NAME_1" as child of HEADER. tmp := ConvertInput ( "M" & C.char'Val (16#FC#) & "ller" & C.char'Val (0), MY_ENCODING); declare Name : constant C.char_array := "NAME_1" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), tmp); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteElement"; end if; if tmp /= null then C.libxml.globals.xmlFree (To_void_ptr (tmp)); end if; -- Write an element named "NAME_2" as child of HEADER. tmp := ConvertInput ( "J" & C.char'Val (16#F6#) & "rg" & C.char'Val (0), MY_ENCODING); declare Name : constant C.char_array := "NAME_2" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), tmp); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteElement"; end if; if tmp /= null then C.libxml.globals.xmlFree (To_void_ptr (tmp)); end if; -- Close the element named HEADER. rc := C.libxml.xmlwriter.xmlTextWriterEndElement (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndElement"; end if; -- Start an element named "ENTRIES" as child of ORDER. declare Name : constant C.char_array := "ENTRIES" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Start an element named "ENTRY" as child of ENTRIES. declare Name : constant C.char_array := "ENTRY" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Write an element named "ARTICLE" as child of ENTRY. declare Name : constant C.char_array := "ARTICLE" & C.char'Val (0); Format : constant C.char_array := "<Test>" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteElement"; end if; -- Write an element named "ENTRY_NO" as child of ENTRY. declare Name : constant C.char_array := "ENTRY_NO" & C.char'Val (0); Format : constant C.char_array := "10" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteFormatElement"; end if; -- Close the element named ENTRY. rc := C.libxml.xmlwriter.xmlTextWriterEndElement (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndElement"; end if; -- Start an element named "ENTRY" as child of ENTRIES. declare Name : constant C.char_array := "ENTRY" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Write an element named "ARTICLE" as child of ENTRY. declare Name : constant C.char_array := "ARTICLE" & C.char'Val (0); Format : constant C.char_array := "<Test 2>" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteElement"; end if; -- Write an element named "ENTRY_NO" as child of ENTRY. declare Name : constant C.char_array := "ENTRY_NO" & C.char'Val (0); Format : constant C.char_array := "20" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteFormatElement"; end if; -- Close the element named ENTRY. rc := C.libxml.xmlwriter.xmlTextWriterEndElement (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndElement"; end if; -- Close the element named ENTRIES. rc := C.libxml.xmlwriter.xmlTextWriterEndElement (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndElement"; end if; -- Start an element named "FOOTER" as child of ORDER. declare Name : constant C.char_array := "FOOTER" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; -- Write an element named "TEXT" as child of FOOTER. declare Name : constant C.char_array := "TEXT" & C.char'Val (0); Format : constant C.char_array := "This is a text." & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterWriteElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), To_xmlChar_const_ptr (Format (Format'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterWriteElement"; end if; -- Close the element named FOOTER. rc := C.libxml.xmlwriter.xmlTextWriterEndElement (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndElement"; end if; end Write_Sample_XML; -- testXmlwriterFilename: -- @uri: the output URI -- -- test the xmlWriter interface when writing to a new file procedure testXmlwriterFilename (uri : not null access constant C.char) is rc : C.signed_int; writer : C.libxml.xmlwriter.xmlTextWriterPtr; begin -- Create a new XmlWriter for uri, with no compression. writer := C.libxml.xmlwriter.xmlNewTextWriterFilename (uri, 0); if writer = null then raise Program_Error with "testXmlwriterFilename: Error creating the xml writer"; end if; -- Start the document with the xml default for the version, -- encoding ISO 8859-1 and the default for the standalone -- declaration. rc := C.libxml.xmlwriter.xmlTextWriterStartDocument ( writer, null, MY_ENCODING (MY_ENCODING'First)'Access, null); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartDocument"; end if; -- Start an element named "EXAMPLE". Since thist is the first -- element, this will be the root element of the document. declare Name : constant C.char_array := "EXAMPLE" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; Writing : begin Write_Sample_XML (writer); end Writing; -- Here we could close the elements ORDER and EXAMPLE using the -- function xmlTextWriterEndElement, but since we do not want to -- write any other elements, we simply call xmlTextWriterEndDocument, -- which will do all the work. rc := C.libxml.xmlwriter.xmlTextWriterEndDocument (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndDocument"; end if; C.libxml.xmlwriter.xmlFreeTextWriter (writer); end testXmlwriterFilename; -- testXmlwriterMemory: -- @file: the output file -- -- test the xmlWriter interface when writing to memory procedure testXmlwriterMemory (file : not null access constant C.char) is rc : C.signed_int; writer : C.libxml.xmlwriter.xmlTextWriterPtr; buf : C.libxml.tree.xmlBufferPtr; fp : access C.stdio.FILE; Dummy_signed_int : C.signed_int; begin -- Create a new XML buffer, to which the XML document will be written buf := C.libxml.tree.xmlBufferCreate; if buf = null then raise Program_Error with "testXmlwriterMemory: Error creating the xml buffer"; end if; -- Create a new XmlWriter for memory, with no compression. -- Remark: there is no compression for this kind of xmlTextWriter writer := C.libxml.xmlwriter.xmlNewTextWriterMemory (buf, 0); if writer = null then raise Program_Error with "testXmlwriterMemory: Error creating the xml writer"; end if; -- Start the document with the xml default for the version, -- encoding ISO 8859-1 and the default for the standalone -- declaration. rc := C.libxml.xmlwriter.xmlTextWriterStartDocument ( writer, null, MY_ENCODING (MY_ENCODING'First)'Access, null); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartDocument"; end if; -- Start an element named "EXAMPLE". Since thist is the first -- element, this will be the root element of the document. declare Name : constant C.char_array := "EXAMPLE" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; Writing : begin Write_Sample_XML (writer); end Writing; -- Here we could close the elements ORDER and EXAMPLE using the -- function xmlTextWriterEndElement, but since we do not want to -- write any other elements, we simply call xmlTextWriterEndDocument, -- which will do all the work. rc := C.libxml.xmlwriter.xmlTextWriterEndDocument (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndDocument"; end if; C.libxml.xmlwriter.xmlFreeTextWriter (writer); declare Mode : constant C.char_array := "w" & C.char'Val (0); begin fp := C.stdio.fopen (file, Mode (Mode'First)'Access); end; if fp = null then raise Program_Error with "testXmlwriterMemory: Error at fopen"; end if; Dummy_signed_int := C.stdio.fputs (To_char_const_ptr (buf.content), fp); Dummy_signed_int := C.stdio.fclose (fp); C.libxml.tree.xmlBufferFree (buf); end testXmlwriterMemory; -- testXmlwriterDoc: -- @file: the output file -- -- test the xmlWriter interface when creating a new document procedure testXmlwriterDoc (file : not null access constant C.char) is rc : C.signed_int; writer : C.libxml.xmlwriter.xmlTextWriterPtr; doc : aliased C.libxml.tree.xmlDocPtr; Dummy_signed_int : C.signed_int; begin -- Create a new XmlWriter for DOM, with no compression. writer := C.libxml.xmlwriter.xmlNewTextWriterDoc (doc'Access, 0); if writer = null then raise Program_Error with "testXmlwriterDoc: Error creating the xml writer"; end if; -- Start the document with the xml default for the version, -- encoding ISO 8859-1 and the default for the standalone -- declaration. rc := C.libxml.xmlwriter.xmlTextWriterStartDocument ( writer, null, MY_ENCODING (MY_ENCODING'First)'Access, null); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartDocument"; end if; -- Start an element named "EXAMPLE". Since thist is the first -- element, this will be the root element of the document. declare Name : constant C.char_array := "EXAMPLE" & C.char'Val (0); begin rc := C.libxml.xmlwriter.xmlTextWriterStartElement ( writer, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access)); end; if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartElement"; end if; Writing : begin Write_Sample_XML (writer); end Writing; -- Here we could close the elements ORDER and EXAMPLE using the -- function xmlTextWriterEndElement, but since we do not want to -- write any other elements, we simply call xmlTextWriterEndDocument, -- which will do all the work. rc := C.libxml.xmlwriter.xmlTextWriterEndDocument (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndDocument"; end if; C.libxml.xmlwriter.xmlFreeTextWriter (writer); Dummy_signed_int := C.libxml.tree.xmlSaveFileEnc ( file, doc, MY_ENCODING (MY_ENCODING'First)'Access); C.libxml.tree.xmlFreeDoc (doc); end testXmlwriterDoc; -- testXmlwriterTree: -- @file: the output file -- -- test the xmlWriter interface when writing to a subtree procedure testXmlwriterTree (file : not null access constant C.char) is rc : C.signed_int; writer : C.libxml.xmlwriter.xmlTextWriterPtr; doc : C.libxml.tree.xmlDocPtr; node : C.libxml.tree.xmlNodePtr; Dummy_xmlNodePtr : C.libxml.tree.xmlNodePtr; Dummy_signed_int : C.signed_int; begin -- Create a new XML DOM tree, to which the XML document will be written doc := C.libxml.tree.xmlNewDoc ( To_xmlChar_const_ptr ( C.libxml.parser.XML_DEFAULT_VERSION ( C.libxml.parser.XML_DEFAULT_VERSION'First)'Access)); if doc = null then raise Program_Error with "testXmlwriterTree: Error creating the xml document tree"; end if; -- Create a new XML node, to which the XML document will be appended declare Name : constant C.char_array := "EXAMPLE" & C.char'Val (0); begin node := C.libxml.tree.xmlNewDocNode ( doc, null, To_xmlChar_const_ptr (Name (Name'First)'Unchecked_Access), null); end; if node = null then raise Program_Error with "testXmlwriterTree: Error creating the xml node"; end if; -- Make ELEMENT the root node of the tree Dummy_xmlNodePtr := C.libxml.tree.xmlDocSetRootElement (doc, node); -- Create a new XmlWriter for DOM tree, with no compression. writer := C.libxml.xmlwriter.xmlNewTextWriterTree (doc, node, 0); if writer = null then raise Program_Error with "testXmlwriterTree: Error creating the xml writer"; end if; -- Start the document with the xml default for the version, -- encoding ISO 8859-1 and the default for the standalone -- declaration. rc := C.libxml.xmlwriter.xmlTextWriterStartDocument ( writer, null, MY_ENCODING (MY_ENCODING'First)'Access, null); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterStartDocument"; end if; Writing : begin Write_Sample_XML (writer); end Writing; -- Here we could close the elements ORDER and EXAMPLE using the -- function xmlTextWriterEndElement, but since we do not want to -- write any other elements, we simply call xmlTextWriterEndDocument, -- which will do all the work. rc := C.libxml.xmlwriter.xmlTextWriterEndDocument (writer); if rc < 0 then raise Program_Error with "testXmlwriterTree: Error at xmlTextWriterEndDocument"; end if; C.libxml.xmlwriter.xmlFreeTextWriter (writer); Dummy_signed_int := C.libxml.tree.xmlSaveFileEnc ( file, doc, MY_ENCODING (MY_ENCODING'First)'Access); C.libxml.tree.xmlFreeDoc (doc); end testXmlwriterTree; begin -- this initialize the library and check potential ABI mismatches -- between the version it was compiled for and the actual shared -- library used. C.libxml.xmlversion.xmlCheckVersion (C.libxml.xmlversion.LIBXML_VERSION); declare Default_Temp : constant C.char_array (0 .. 4) := "/tmp" & C.char'Val (0); function Get_Temp return access constant C.char is TMPDIR : constant C.char_array (0 .. 6) := "TMPDIR" & C.char'Val (0); Temp : access constant C.char := C.stdlib.getenv (TMPDIR (0)'Access); begin if Temp = null or else Temp.all = C.char'Val (0) then Temp := Default_Temp (0)'Access; end if; return Temp; end Get_Temp; Temp : constant not null access constant C.char := Get_Temp; Dummy_char_ptr : C.char_ptr; begin -- first, the file version declare uri_Name : constant C.char_array := "/writer1.res" & C.char'Val (0); uri : aliased C.char_array (0 .. C.string.strlen (Temp) + 256); begin Dummy_char_ptr := C.string.strcpy (uri (0)'Access, Temp); Dummy_char_ptr := C.string.strcat (uri (0)'Access, uri_Name (0)'Access); testXmlwriterFilename (uri => uri (0)'Access); end; -- next, the memory version declare file_Name : constant C.char_array := "/writer2.res" & C.char'Val (0); file : aliased C.char_array (0 .. C.string.strlen (Temp) + 256); begin Dummy_char_ptr := C.string.strcpy (file (0)'Access, Temp); Dummy_char_ptr := C.string.strcat (file (0)'Access, file_Name (0)'Access); testXmlwriterMemory (file => file (0)'Access); end; -- next, the DOM version declare file_Name : constant C.char_array := "/writer3.res" & C.char'Val (0); file : aliased C.char_array (0 .. C.string.strlen (Temp) + 256); begin Dummy_char_ptr := C.string.strcpy (file (0)'Access, Temp); Dummy_char_ptr := C.string.strcat (file (0)'Access, file_Name (0)'Access); testXmlwriterDoc (file => file (0)'Access); end; -- next, the tree version declare file_Name : constant C.char_array := "/writer4.res" & C.char'Val (0); file : aliased C.char_array (0 .. C.string.strlen (Temp) + 256); begin Dummy_char_ptr := C.string.strcpy (file (0)'Access, Temp); Dummy_char_ptr := C.string.strcat (file (0)'Access, file_Name (0)'Access); testXmlwriterTree (file => file (0)'Access); end; end; -- Cleanup function for the XML library. C.libxml.parser.xmlCleanupParser; -- this is to debug memory for regression tests C.libxml.xmlmemory.xmlMemoryDump; -- finish Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error.all, "ok"); end test_writer;
{ "source": "starcoderdata", "programming_language": "ada" }
with Apsepp.Test_Node_Class.Generic_Assert; use Apsepp.Test_Node_Class; with Apsepp.Abstract_Test_Case; use Apsepp.Abstract_Test_Case; package Apsepp_Scope_Bound_Locks_Test_Case is type Apsepp_Scope_Bound_Locks_T_C is limited new Test_Case with null record; overriding procedure Setup_Routine (Obj : Apsepp_Scope_Bound_Locks_T_C); overriding function Routine_Array (Obj : Apsepp_Scope_Bound_Locks_T_C) return Test_Routine_Array; overriding procedure Run (Obj : in out Apsepp_Scope_Bound_Locks_T_C; Outcome : out Test_Outcome; Kind : Run_Kind := Assert_Cond_And_Run_Test); private procedure Assert is new Apsepp.Test_Node_Class.Generic_Assert (Test_Node_Tag => Apsepp_Scope_Bound_Locks_T_C'Tag); end Apsepp_Scope_Bound_Locks_Test_Case;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.Text_IO; with Glib; with Gtk.Frame; with Gtk.Tree_Model; with Gtk.Tree_Store; with Gtk.Cell_Renderer_Text; with Gtk.Tree_View; with Gtk.Scrolled_Window; package MAT.Consoles.Gtkmat is type Console_Type is new MAT.Consoles.Console_Type with private; type Console_Type_Access is access all Console_Type'Class; -- Initialize the console to display the result in the Gtk frame. procedure Initialize (Console : in out Console_Type; Frame : in Gtk.Frame.Gtk_Frame); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Column_Type is record Field : Field_Type; Title : Ada.Strings.Unbounded.Unbounded_String; end record; type Column_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Column_Type; type Field_Index_Array is array (Field_Type) of Glib.Gint; type Console_Type is new MAT.Consoles.Console_Type with record Frame : Gtk.Frame.Gtk_Frame; Scrolled : Gtk.Scrolled_Window.Gtk_Scrolled_Window; List : Gtk.Tree_Store.Gtk_Tree_Store; Current_Row : Gtk.Tree_Model.Gtk_Tree_Iter; File : Ada.Text_IO.File_Type; Indexes : Field_Index_Array; Columns : Column_Array; Tree : Gtk.Tree_View.Gtk_Tree_View; Col_Text : Gtk.Cell_Renderer_Text.Gtk_Cell_renderer_Text; end record; end MAT.Consoles.Gtkmat;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------- with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with Keccak.Types; with Test_Vectors; use Test_Vectors; package body CSHAKE_Runner is procedure Free is new Ada.Unchecked_Deallocation (Object => Keccak.Types.Byte_Array, Name => Byte_Array_Access); procedure Run_Tests (File_Name : in String; Num_Passed : out Natural; Num_Failed : out Natural) is use type Keccak.Types.Byte_Array; package Integer_IO is new Ada.Text_IO.Integer_IO(Integer); N_Key : constant Unbounded_String := To_Unbounded_String("N"); S_Key : constant Unbounded_String := To_Unbounded_String("S"); InLen_Key : constant Unbounded_String := To_Unbounded_String("InLen"); In_Key : constant Unbounded_String := To_Unbounded_String("In"); OutLen_Key : constant Unbounded_String := To_Unbounded_String("OutLen"); Out_Key : constant Unbounded_String := To_Unbounded_String("Out"); Schema : Test_Vectors.Schema_Maps.Map; Tests : Test_Vectors.Lists.List; Ctx : CSHAKE.Context; Output : Byte_Array_Access; OutLen : Natural; begin Num_Passed := 0; Num_Failed := 0; -- Setup schema Schema.Insert (Key => N_Key, New_Item => Schema_Entry'(VType => String_Type, Required => True, Is_List => False)); Schema.Insert (Key => S_Key, New_Item => Schema_Entry'(VType => String_Type, Required => True, Is_List => False)); Schema.Insert (Key => InLen_Key, New_Item => Schema_Entry'(VType => Integer_Type, Required => True, Is_List => False)); Schema.Insert (Key => In_Key, New_Item => Schema_Entry'(VType => Hex_Array_Type, Required => True, Is_List => False)); Schema.Insert (Key => OutLen_Key, New_Item => Schema_Entry'(VType => Integer_Type, Required => True, Is_List => False)); Schema.Insert (Key => Out_Key, New_Item => Schema_Entry'(VType => Hex_Array_Type, Required => True, Is_List => False)); -- Load the test file using the file name given on the command line Ada.Text_IO.Put_Line("Loading file: " & File_Name); Test_Vectors.Load (File_Name => File_Name, Schema => Schema, Vectors_List => Tests); Ada.Text_IO.Put ("Running "); Integer_IO.Put (Integer (Tests.Length), Width => 0); Ada.Text_IO.Put_Line (" tests ..."); -- Run each test. for C of Tests loop CSHAKE.Init (Ctx => Ctx, Customization => To_String (C.Element (S_Key).First_Element.Str), Function_Name => To_String (C.Element (N_Key).First_Element.Str)); CSHAKE.Update(Ctx => Ctx, Message => C.Element (In_Key).First_Element.Hex.all, Bit_Length => C.Element (InLen_Key).First_Element.Int); Output := new Keccak.Types.Byte_Array (C.Element (Out_Key).First_Element.Hex.all'Range); CSHAKE.Extract (Ctx, Output.all); -- Mask any unused bits from the output. OutLen := C.Element (OutLen_Key).First_Element.Int; if OutLen mod 8 /= 0 then Output.all(Output.all'Last) := Output.all(Output.all'Last) and Keccak.Types.Byte((2**(OutLen mod 8)) - 1); end if; -- Check output if Output.all = C.Element(Out_Key).First_Element.Hex.all then Num_Passed := Num_Passed + 1; else Num_Failed := Num_Failed + 1; -- Display a message on failure to help with debugging. Ada.Text_IO.Put("FAILURE (Input bit-len: "); Integer_IO.Put(C.Element (InLen_Key).First_Element.Int, Width => 0); Ada.Text_IO.Put_Line(")"); Ada.Text_IO.Put(" Expected MD: "); Ada.Text_IO.Put(Byte_Array_To_String (C.Element(Out_Key).First_Element.Hex.all)); Ada.Text_IO.New_Line; Ada.Text_IO.Put(" Actual MD: "); Ada.Text_IO.Put(Byte_Array_To_String(Output.all)); Ada.Text_IO.New_Line; end if; Free (Output); end loop; end Run_Tests; end CSHAKE_Runner;
{ "source": "starcoderdata", "programming_language": "ada" }
with GNAT.Strings; package body WisiToken.Lexer is procedure Finalize (Object : in out Source) is begin case Object.Label is when String_Label => if not Object.User_Buffer then Ada.Strings.Unbounded.Free (Object.Buffer); end if; when File_Label => GNATCOLL.Mmap.Free (Object.Region); GNATCOLL.Mmap.Close (Object.File); end case; end Finalize; function Buffer (Source : in Lexer.Source) return GNATCOLL.Mmap.Str_Access is use GNATCOLL.Mmap; begin case Source.Label is when String_Label => return Short.To_Str_Access (GNAT.Strings.String_Access (Source.Buffer)); when File_Label => return Data (Source.Region); end case; end Buffer; function File_Name (Source : in Lexer.Source) return String is begin return -Source.File_Name; end File_Name; function To_Char_Pos (Source : in Lexer.Source; Lexer_Char_Pos : in Integer) return Base_Buffer_Pos is begin return Base_Buffer_Pos (Lexer_Char_Pos) + Source.Buffer_Nominal_First_Char - Buffer_Pos'First; end To_Char_Pos; end WisiToken.Lexer;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.Directories; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Files; with Util.Strings; with Util.Log.Loggers; with Are.Utils; with Are.Installer.Copies; with Are.Installer.Exec; with Are.Installer.Concat; with Are.Installer.Bundles; with Are.Installer.Merges; with Sax.Readers; with Input_Sources.File; with DOM.Core.Documents; with DOM.Readers; package body Are.Installer is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Are.Installer"); -- ------------------------------ -- Create a resource rule identified by `Kind`. -- The resource rule is configured according to the DOM tree whose node is `Node`. -- ------------------------------ function Create_Rule (Kind : in String; Node : in DOM.Core.Node) return Distrib_Rule_Access is begin Log.Debug ("Creating resource rule {0}", Kind); if Kind = "copy" or Kind = "" then return Are.Installer.Copies.Create_Rule (False); elsif Kind = "copy-first" then return Are.Installer.Copies.Create_Rule (True); elsif Kind = "exec" then return Are.Installer.Exec.Create_Rule (Node, False); elsif Kind = "copy-exec" then return Are.Installer.Exec.Create_Rule (Node, True); elsif Kind = "concat" then return Are.Installer.Concat.Create_Rule (Node); elsif Kind = "bundle" then return Are.Installer.Bundles.Create_Rule (Node); elsif Kind = "webmerge" then return Are.Installer.Merges.Create_Rule (Node); else return null; end if; end Create_Rule; -- ------------------------------ -- Add a simple rule to copy the files matching the pattern on the resource. -- ------------------------------ procedure Add_Rule (Installer : in out Installer_Type; Resource : in Are.Resource_Access; Pattern : in String) is Rule : constant Distrib_Rule_Access := Copies.Create_Rule (Copy_First_File => True); Match : Match_Rule; begin Rule.Resource := Resource; Installer.Rules.Append (Rule); Match.Match := Ada.Strings.Unbounded.To_Unbounded_String (Pattern); Rule.Matches.Append (Match); end Add_Rule; -- ------------------------------ -- Read the XML package file that describes the resources and build the list -- of rules to collect and build those resources. -- ------------------------------ procedure Read_Package (Installer : in out Installer_Type; File : in String; Context : in out Context_Type'Class) is use Ada.Strings.Maps; procedure Register_Rule (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node); procedure Register_Resource (List : in out Are.Resource_List; Node : in DOM.Core.Node); procedure Register_Resources (List : in out Are.Resource_List; Node : in DOM.Core.Node); procedure Register_Line_Separator (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node); procedure Register_Line_Filter (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node); -- ------------------------------ -- Register a new type mapping. -- ------------------------------ procedure Register_Rule (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node) is -- Collect the include definitions for the distribution rule. procedure Collect_Includes (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node); -- Collect the exclude definitions for the distribution rule. procedure Collect_Excludes (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node); -- Collect the fileset definitions for the distribution rule. procedure Collect_Filesets (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node); use Ada.Strings.Unbounded; Dir : constant UString := Are.Utils.Get_Attribute (Node, "dir"); Mode : constant String := To_String (Are.Utils.Get_Attribute (Node, "mode")); Level : constant String := To_String (Are.Utils.Get_Attribute (Node, "log")); Match : Match_Rule; -- ------------------------------ -- Collect the include definitions for the distribution rule. -- ------------------------------ procedure Collect_Includes (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node) is Name : constant UString := Are.Utils.Get_Attribute (Node, "name"); begin if Name = "" then Context.Error ("{0}: empty include name in '<include>' definition", File); return; end if; Match.Match := Name; Rule.Matches.Append (Match); end Collect_Includes; -- ------------------------------ -- Collect the exclude definitions for the distribution rule. -- ------------------------------ procedure Collect_Excludes (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node) is Name : constant UString := Are.Utils.Get_Attribute (Node, "name"); begin if Name = "" then Context.Error ("{0}: empty exclude name in '<exclude>' definition", File); return; end if; Match.Match := Name; Rule.Excludes.Append (Match); end Collect_Excludes; procedure Iterate is new Are.Utils.Iterate_Nodes (T => Distrib_Rule_Access, Process => Collect_Includes); procedure Iterate_Excludes is new Are.Utils.Iterate_Nodes (T => Distrib_Rule_Access, Process => Collect_Excludes); -- ------------------------------ -- Collect the include definitions for the distribution rule. -- ------------------------------ procedure Collect_Filesets (Rule : in out Distrib_Rule_Access; Node : in DOM.Core.Node) is Dir : constant UString := Are.Utils.Get_Attribute (Node, "dir"); begin if Dir /= "." then Match.Base_Dir := Dir; end if; Iterate (Rule, Node, "include"); Iterate_Excludes (Rule, Node, "exclude", False); end Collect_Filesets; procedure Iterate_Filesets is new Are.Utils.Iterate_Nodes (T => Distrib_Rule_Access, Process => Collect_Filesets); Rule : Distrib_Rule_Access := Create_Rule (Kind => Mode, Node => Node); begin Log.Debug ("Install {0} in {1}", Dir, To_String (Resource.Name)); if Rule = null then Context.Error ("{0}: rule '" & Mode & "' is not recognized", File); return; end if; Rule.Resource := Resource; Rule.Dir := Dir; if Level = "info" then Rule.Level := Util.Log.INFO_LEVEL; elsif Level = "debug" then Rule.Level := Util.Log.DEBUG_LEVEL; else Rule.Level := Util.Log.WARN_LEVEL; end if; Rule.Source_Timestamp := Are.Utils.Get_Attribute (Node, "source-timestamp"); Rule.Strip_Extension := Are.Utils.Get_Attribute (Node, "strip-extension"); Installer.Rules.Append (Rule); Iterate (Rule, Node, "include", False); Iterate_Excludes (Rule, Node, "exclude", False); Iterate_Filesets (Rule, Node, "fileset"); if Rule.Matches.Is_Empty then Context.Error ("{0}: empty fileset definition", File); end if; end Register_Rule; -- ------------------------------ -- Register a new line separator. -- ------------------------------ procedure Register_Line_Separator (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node) is Separator : constant String := Are.Utils.Get_Data_Content (Node); begin if Separator'Length = 0 then return; end if; if Separator'Length = 1 then Resource.Separators := Resource.Separators or To_Set (Separator); elsif Separator = "\n" then Resource.Separators := Resource.Separators or To_Set (ASCII.LF); elsif Separator = "\r" then Resource.Separators := Resource.Separators or To_Set (ASCII.CR); elsif Separator = "\t" then Resource.Separators := Resource.Separators or To_Set (ASCII.HT); else Resource.Separators := Resource.Separators or To_Set (Separator); end if; end Register_Line_Separator; -- ------------------------------ -- Register a new line filter. -- ------------------------------ procedure Register_Line_Filter (Resource : in out Are.Resource_Access; Node : in DOM.Core.Node) is Pattern : constant String := Are.Utils.Get_Data_Content (Node); Replace : constant String := Are.Utils.Get_Attribute (Node, "replace"); begin Resource.Add_Line_Filter (Pattern, Replace); exception when GNAT.Regpat.Expression_Error => Context.Error ("{0}: invalid pattern '{1}'", File, Pattern); end Register_Line_Filter; -- ------------------------------ -- Register the resource definition. -- ------------------------------ procedure Register_Resource (List : in out Are.Resource_List; Node : in DOM.Core.Node) is function Get_Format (Name : in String) return Are.Format_Type; procedure Iterate is new Are.Utils.Iterate_Nodes (T => Are.Resource_Access, Process => Register_Rule); procedure Iterate_Line_Separator is new Are.Utils.Iterate_Nodes (T => Are.Resource_Access, Process => Register_Line_Separator); procedure Iterate_Line_Filter is new Are.Utils.Iterate_Nodes (T => Are.Resource_Access, Process => Register_Line_Filter); function Get_Format (Name : in String) return Are.Format_Type is begin if Name = "binary" then return R_BINARY; elsif Name = "string" then return R_STRING; elsif Name = "lines" then return R_LINES; else Context.Error ("{0}: invalid resource format '{1}'", File, Name); return R_BINARY; end if; end Get_Format; Name : constant String := Are.Utils.Get_Attribute (Node, "name"); Resource : Are.Resource_Access; begin Are.Create_Resource (List, Name, Resource); Resource.Type_Name := Are.Utils.Get_Attribute (Node, "type", ""); Resource.Format := Get_Format (Are.Utils.Get_Attribute (Node, "format", "binary")); Resource.Function_Name := Are.Utils.Get_Attribute (Node, "function-name", ""); Resource.Member_Content_Name := Are.Utils.Get_Attribute (Node, "member-content", ""); Resource.Member_Modtime_Name := Are.Utils.Get_Attribute (Node, "member-time", ""); Resource.Member_Length_Name := Are.Utils.Get_Attribute (Node, "member-length", ""); Resource.Member_Format_Name := Are.Utils.Get_Attribute (Node, "member-format", ""); Iterate_Line_Separator (Resource, Node, "line-separator"); Iterate_Line_Filter (Resource, Node, "line-filter"); Iterate (Resource, Node, "install"); if Resource.Format = R_LINES and then Resource.Separators = Null_Set then Context.Error ("{0}: missing 'line-separator' for resource '{1}'", File, Name); end if; end Register_Resource; -- ------------------------------ -- Register a resource description -- ------------------------------ procedure Register_Resources (List : in out Are.Resource_List; Node : in DOM.Core.Node) is procedure Iterate is new Are.Utils.Iterate_Nodes (T => Are.Resource_List, Process => Register_Resource); begin Iterate (List, Node, "resource"); end Register_Resources; procedure Iterate is new Are.Utils.Iterate_Nodes (T => Are.Resource_List, Process => Register_Resources); Read : Input_Sources.File.File_Input; My_Tree_Reader : DOM.Readers.Tree_Reader; Name_Start : Natural; begin Log.Info ("Reading package file '{0}'", File); -- Base file name should be used as the public Id Name_Start := File'Last; while Name_Start >= File'First and then File (Name_Start) /= '/' loop Name_Start := Name_Start - 1; end loop; Input_Sources.File.Open (File, Read); -- Full name is used as the system id Input_Sources.File.Set_System_Id (Read, File); Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last)); DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False); DOM.Readers.Parse (My_Tree_Reader, Read); Input_Sources.File.Close (Read); declare Doc : constant DOM.Core.Document := DOM.Readers.Get_Tree (My_Tree_Reader); Root : constant DOM.Core.Element := DOM.Core.Documents.Get_Element (Doc); begin Iterate (Context.Resources, Root, "package"); end; DOM.Readers.Free (My_Tree_Reader); Log.Info ("Loaded {0} rules for {1} resources", Util.Strings.Image (Natural (Installer.Rules.Length)), Util.Strings.Image (Are.Length (Context.Resources))); exception when Ada.IO_Exceptions.Name_Error => Context.Error ("package file {0} does not exist", File); when E : Sax.Readers.XML_Fatal_Error => Context.Error ("{0}", Ada.Exceptions.Exception_Message (E)); end Read_Package; -- ------------------------------ -- Scan the directory collecting the files that must be taken into account and -- processed by the distribution rules. -- ------------------------------ procedure Scan_Directory (Installer : in out Installer_Type; Path : in String; Context : in out Context_Type'Class) is pragma Unreferenced (Context); Tree : constant Directory_List_Access := new Directory_List '(Length => 1, Name => ".", Rel_Pos => Path'Length + 2, Path_Length => Path'Length, Path => Path, others => <>); begin Log.Debug ("Scanning directory: {0}", Path); Installer.Trees.Append (Tree); Scan (Path, ".", Tree); Log.Info ("Scanning directory: {0} found {1} files in {2} directories", Path, Util.Strings.Image (Natural (Tree.Files.Length)), Util.Strings.Image (Natural (Tree.Directories.Length))); end Scan_Directory; -- ------------------------------ -- Execute the installation rules and collect the resources to be written -- in the context. -- ------------------------------ procedure Execute (Installer : in out Installer_Type; Context : in out Context_Type'Class) is procedure Scan_Rule (Pos : in Distrib_Rule_Vectors.Cursor); procedure Execute_Rule (Pos : in Distrib_Rule_Vectors.Cursor); -- ------------------------------ -- Process the rule by scaning the directory tree and detecting files that are concerned. -- ------------------------------ procedure Scan_Rule (Pos : in Distrib_Rule_Vectors.Cursor) is Rule : constant Distrib_Rule_Access := Distrib_Rule_Vectors.Element (Pos); Iter : Directory_List_Vector.Cursor := Installer.Trees.First; begin Log.Debug ("Scanning rule"); while Directory_List_Vector.Has_Element (Iter) loop Rule.Scan (Directory_List_Vector.Element (Iter).all); Directory_List_Vector.Next (Iter); end loop; end Scan_Rule; -- ------------------------------ -- Execute the rules. -- ------------------------------ procedure Execute_Rule (Pos : in Distrib_Rule_Vectors.Cursor) is Rule : constant Distrib_Rule_Access := Distrib_Rule_Vectors.Element (Pos); begin Log.Debug ("Process rule"); Rule.Execute (Context); end Execute_Rule; begin Log.Info ("Executing {0} rules on {1} directory tree", Util.Strings.Image (Natural (Installer.Rules.Length)), Util.Strings.Image (Natural (Installer.Trees.Length))); Installer.Rules.Iterate (Process => Scan_Rule'Access); Installer.Rules.Iterate (Process => Execute_Rule'Access); end Execute; -- ------------------------------ -- Get the relative path of the directory. -- ------------------------------ function Get_Relative_Path (Dir : in Directory_List) return String is begin return Dir.Path (Dir.Rel_Pos .. Dir.Path'Last); end Get_Relative_Path; -- ------------------------------ -- Get the first source path from the list. -- ------------------------------ function Get_Source_Path (From : in File_Vector; Use_First_File : in Boolean := False) return String is use type Ada.Containers.Count_Type; begin if From.Length = 0 then return ""; elsif Use_First_File then declare File : constant File_Record := From.Element (1); begin return Util.Files.Compose (File.Dir.Path, File.Name); end; else declare File : constant File_Record := From.Element (From.Last_Index); begin return Util.Files.Compose (File.Dir.Path, File.Name); end; end if; end Get_Source_Path; -- ------------------------------ -- Build a regular expression pattern from a pattern string. -- ------------------------------ function Make_Regexp (Pattern : in String) return String is Result : String (1 .. Pattern'Length * 2 + 2); Pos : Natural := 1; begin Result (1) := '^'; for I in Pattern'Range loop if Pattern (I) = '*' then Pos := Pos + 1; Result (Pos) := '.'; elsif Pattern (I) = '.' or Pattern (I) = '$' or Pattern (I) = '^' then Pos := Pos + 1; Result (Pos) := '\'; end if; Pos := Pos + 1; Result (Pos) := Pattern (I); end loop; Pos := Pos + 1; Result (Pos) := '$'; return Result (1 .. Pos); end Make_Regexp; -- ------------------------------ -- Build a regular expression pattern from a pattern string. -- ------------------------------ function Make_Regexp (Pattern : in String) return GNAT.Regpat.Pattern_Matcher is Expr : constant String := Make_Regexp (Pattern); begin return GNAT.Regpat.Compile (Expr); end Make_Regexp; -- ------------------------------ -- Scan the directory whose root path is <b>Path</b> and with the relative path -- <b>Rel_Path</b> and build in <b>Dir</b> the list of files and directories. -- ------------------------------ procedure Scan (Path : in String; Rel_Path : in String; Dir : in Directory_List_Access) is use Ada.Directories; Full_Path : constant String := Util.Files.Compose (Path, Rel_Path); Filter : constant Filter_Type := (Ordinary_File => True, Directory => True, others => False); Ent : Ada.Directories.Directory_Entry_Type; Search : Search_Type; begin Log.Debug ("Scanning {0}", Full_Path); Start_Search (Search, Directory => Full_Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); File_Path : constant String := Util.Files.Compose (Rel_Path, Name); Full_Path : constant String := Ada.Directories.Full_Name (Ent); begin if Are.Utils.Is_File_Ignored (Name) then Log.Debug ("Ignoring {0}", Name); -- If this is a directory, recursively scan it and collect its files. elsif Ada.Directories.Kind (Full_Path) = Ada.Directories.Directory then declare Sub_Dir : constant Directory_List_Access := new Directory_List '(Length => Name'Length, Path_Length => Full_Path'Length, Rel_Pos => Full_Path'Length - File_Path'Length + 1, Name => Name, Path => Full_Path, others => <>); begin Dir.Directories.Append (Sub_Dir); Scan (Path, File_Path, Sub_Dir); end; else Log.Debug ("Collect {0}", File_Path); Dir.Files.Append (File_Record '(Length => Name'Length, Name => Name, Dir => Dir)); end if; end; end loop; end Scan; procedure Execute (Rule : in out Distrib_Rule; Context : in out Context_Type'Class) is use Ada.Containers; procedure Process (Key : in String; Files : in out File_Vector); procedure Process (Key : in String; Files : in out File_Vector) is begin Distrib_Rule'Class (Rule).Install (Key, Files, Context); exception when Ex : others => Context.Error ("install of {0} failed: {1}", Key, Ada.Exceptions.Exception_Message (Ex)); end Process; Iter : File_Tree.Cursor := Rule.Files.First; Count : constant Count_Type := Rule.Files.Length; Name : constant String := Distrib_Rule'Class (Rule).Get_Install_Name; begin if Count = 0 or else Rule.Resource = null then return; elsif Count = 1 then Log.Info ("Installing 1 file with {0} in {1}", Name, Ada.Strings.Unbounded.To_String (Rule.Resource.Name)); else Log.Info ("Installing{0} files with {1} in {2}", Count_Type'Image (Count), Name, Ada.Strings.Unbounded.To_String (Rule.Resource.Name)); end if; while File_Tree.Has_Element (Iter) loop Rule.Files.Update_Element (Iter, Process'Access); File_Tree.Next (Iter); end loop; end Execute; -- ------------------------------ -- Strip the base part of the path -- ------------------------------ function Get_Strip_Path (Base : in String; Path : in String) return String is begin if Base /= "." and then Path'Length >= Base'Length and then Path (Path'First .. Path'First + Base'Length - 1) = Base then return Path (Path'First + Base'Length + 1 .. Path'Last); else return Path; end if; end Get_Strip_Path; -- ------------------------------ -- Get the target path associate with the given source file for the distribution rule. -- ------------------------------ function Get_Target_Path (Rule : in Distrib_Rule; Base : in String; File : in File_Record) return String is Rel_Path : constant String := Get_Relative_Path (File.Dir.all); Path : constant String := Get_Strip_Path (Base, Rel_Path); begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Rule.Dir), Util.Files.Compose (Path, File.Name)); end Get_Target_Path; -- ------------------------------ -- Get the source path of the file. -- ------------------------------ function Get_Source_Path (Rule : in Distrib_Rule; File : in File_Record) return String is pragma Unreferenced (Rule); begin return Util.Files.Compose (File.Dir.Path, File.Name); end Get_Source_Path; -- ------------------------------ -- Get the path that must be exported by the rule. -- ------------------------------ function Get_Export_Path (Rule : in Distrib_Rule; Path : in String) return String is begin if not Rule.Strip_Extension then return Path; end if; declare Pos : constant Natural := Util.Strings.Rindex (Path, '.'); begin if Pos = 0 then return Path; else return Path (Path'First .. Pos - 1); end if; end; end Get_Export_Path; -- ------------------------------ -- Add the file to be processed by the distribution rule. The file has a relative -- path represented by <b>Path</b>. The path is relative from the base directory -- specified in <b>Base_Dir</b>. -- ------------------------------ procedure Add_Source_File (Rule : in out Distrib_Rule; Path : in String; File : in File_Record) is procedure Add_File (Key : in String; Info : in out File_Vector); procedure Add_File (Key : in String; Info : in out File_Vector) is pragma Unreferenced (Key); begin Info.Append (File); end Add_File; Target_Path : constant String := Distrib_Rule'Class (Rule).Get_Target_Path (Path, File); Pos : constant File_Tree.Cursor := Rule.Files.Find (Target_Path); begin Log.Debug ("Adding {0} - {1}", Path, Target_Path); if File_Tree.Has_Element (Pos) then Rule.Files.Update_Element (Pos, Add_File'Access); else declare Info : File_Vector; begin Info.Append (File); Rule.Files.Insert (Target_Path, Info); end; end if; end Add_Source_File; -- ------------------------------ -- Remove the file to be processed by the distribution rule. This is the opposite of -- <tt>Add_Source_File</tt> and used for the <exclude name="xxx"/> rules. -- ------------------------------ procedure Remove_Source_File (Rule : in out Distrib_Rule; Path : in String; File : in File_Record) is procedure Remove_File (Key : in String; Info : in out File_Vector); Target_Path : constant String := Distrib_Rule'Class (Rule).Get_Target_Path (Path, File); Need_Remove : Boolean := False; procedure Remove_File (Key : in String; Info : in out File_Vector) is pragma Unreferenced (Key); Pos : File_Cursor := Info.Find (File); begin if File_Record_Vectors.Has_Element (Pos) then Log.Debug ("Excluding {0} - {1}", Path, Target_Path); Info.Delete (Pos); Need_Remove := Info.Is_Empty; end if; end Remove_File; Pos : File_Tree.Cursor := Rule.Files.Find (Target_Path); begin if File_Tree.Has_Element (Pos) then Rule.Files.Update_Element (Pos, Remove_File'Access); if Need_Remove then Rule.Files.Delete (Pos); end if; end if; end Remove_Source_File; -- ------------------------------ -- Load and add the file in the resource library. -- ------------------------------ procedure Add_File (Rule : in Distrib_Rule; Name : in String; Path : in String; Modtime : in Ada.Calendar.Time; Override : in Boolean := False) is Export_Path : constant String := Rule.Get_Export_Path (Name); begin if Rule.Source_Timestamp then Rule.Resource.Add_File (Export_Path, Path, Modtime, Override); else Rule.Resource.Add_File (Export_Path, Path, Override); end if; end Add_File; -- ------------------------------ -- Scan the directory tree whose root is defined by <b>Dir</b> and find the files -- that match the current rule. -- ------------------------------ procedure Scan (Rule : in out Distrib_Rule; Dir : in Directory_List) is procedure Scan_Pattern (Pos : in Match_Rule_Vector.Cursor); Exclude : Boolean; procedure Scan_Pattern (Pos : in Match_Rule_Vector.Cursor) is Match : constant Match_Rule := Match_Rule_Vector.Element (Pos); Base : constant String := Ada.Strings.Unbounded.To_String (Match.Base_Dir); Pattern : constant String := Ada.Strings.Unbounded.To_String (Match.Match); begin Log.Debug ("Scan pattern base {0} - pat {1}", Base, Pattern); if Base = "" then Rule.Scan (Dir, ".", Pattern, Exclude); return; end if; declare Iter : Directory_List_Vector.Cursor := Dir.Directories.First; D : Directory_List_Access; P : Natural := Base'First; N : Natural; begin while P < Base'Last loop N := Util.Strings.Index (Base, '/', P); if N = 0 then N := Base'Last; else N := N - 1; end if; while Directory_List_Vector.Has_Element (Iter) loop D := Directory_List_Vector.Element (Iter); if D.Name = Base (P .. N) then if N = Base'Last then Log.Debug ("Scanning from sub directory at {0}", Base); Rule.Scan (D.all, Base, Pattern, Exclude); return; end if; Iter := D.Directories.First; exit; end if; Directory_List_Vector.Next (Iter); end loop; P := N + 2; end loop; end; end Scan_Pattern; begin Exclude := False; Rule.Matches.Iterate (Scan_Pattern'Access); Exclude := True; Rule.Excludes.Iterate (Scan_Pattern'Access); end Scan; procedure Scan (Rule : in out Distrib_Rule; Dir : in Directory_List; Base_Dir : in String; Pattern : in String; Exclude : in Boolean) is procedure Collect_Subdirs (Name_Pattern : in String); procedure Collect_Files (Name_Pattern : in String); -- **/*.xhtml -- bin/** -- bin/**/test.bin N : constant Natural := Util.Strings.Index (Pattern, '/'); Pos : Natural := Pattern'First; procedure Collect_Files (Name_Pattern : in String) is use GNAT.Regpat; procedure Collect_File (File : in File_Record); Matcher : constant Pattern_Matcher := Make_Regexp (Name_Pattern); procedure Collect_File (File : in File_Record) is begin Log.Debug ("Check {0} - {1}", Base_Dir, File.Name); if Match (Matcher, File.Name) then if Exclude then Rule.Remove_Source_File (Base_Dir, File); else Rule.Add_Source_File (Base_Dir, File); end if; end if; end Collect_File; Iter : File_Record_Vectors.Cursor := Dir.Files.First; begin while File_Record_Vectors.Has_Element (Iter) loop File_Record_Vectors.Query_Element (Iter, Collect_File'Access); File_Record_Vectors.Next (Iter); end loop; end Collect_Files; procedure Collect_Subdirs (Name_Pattern : in String) is procedure Collect_Dir (Sub_Dir : in Directory_List_Access); procedure Collect_Dir (Sub_Dir : in Directory_List_Access) is begin if Name_Pattern = Sub_Dir.Name or else Name_Pattern = "*" then Rule.Scan (Sub_Dir.all, Base_Dir, Pattern (Pos .. Pattern'Last), Exclude); end if; end Collect_Dir; Iter : Directory_List_Vector.Cursor := Dir.Directories.First; begin while Directory_List_Vector.Has_Element (Iter) loop Directory_List_Vector.Query_Element (Iter, Collect_Dir'Access); Directory_List_Vector.Next (Iter); end loop; end Collect_Subdirs; Next : Natural; begin Log.Debug ("Scan {0}/{1} for pattern {2}", Base_Dir, Dir.Name, Pattern); if N > 0 then if Pattern = "**" then Collect_Subdirs (Name_Pattern => "**"); Collect_Files (Name_Pattern => "*"); return; elsif Pattern (Pattern'First .. N) = "*/" then Pos := N + 1; Collect_Subdirs (Name_Pattern => "*"); elsif Pattern (Pattern'First .. N) = "**/" then Collect_Subdirs (Name_Pattern => "*"); else Pos := N + 1; Collect_Subdirs (Name_Pattern => Pattern (Pattern'First .. N - 1)); return; end if; Next := Util.Strings.Index (Pattern, '/', N + 1); if Next = 0 then Collect_Files (Name_Pattern => Pattern (N + 1 .. Pattern'Last)); end if; end if; if N = 0 then -- No more directory Collect_Files (Name_Pattern => Pattern); end if; end Scan; procedure Delete (Directory : in out Directory_List_Access) is procedure Free is new Ada.Unchecked_Deallocation (Object => Directory_List, Name => Directory_List_Access); begin while not Directory.Directories.Is_Empty loop declare Child : Directory_List_Access := Directory.Directories.First_Element; begin Directory.Directories.Delete_First; Delete (Child); end; end loop; Free (Directory); end Delete; -- ------------------------------ -- Clear the rules and files that have been loaded. -- ------------------------------ procedure Clear (Installer : in out Installer_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Distrib_Rule'Class, Name => Distrib_Rule_Access); begin -- Release the rules until the list becomes empty. while not Installer.Rules.Is_Empty loop declare Rule : Distrib_Rule_Access := Installer.Rules.First_Element; begin Installer.Rules.Delete_First; Free (Rule); end; end loop; -- Likewise for directories. while not Installer.Trees.Is_Empty loop declare Dir : Directory_List_Access := Installer.Trees.First_Element; begin Installer.Trees.Delete_First; Delete (Dir); end; end loop; end Clear; overriding procedure Finalize (Installer : in out Installer_Type) is begin Installer.Clear; end Finalize; end Are.Installer;
{ "source": "starcoderdata", "programming_language": "ada" }
-------------------------------------------------------------------------------- with CL.Enumerations; with CL.Helpers; with CL.API.CL_GL; package body CL.Memory.Images.CL_GL is package body Constructors is function Create_Image2D (Context : Contexts.CL_GL.Context'Class; Mode : Access_Kind; Texture_Target : Targets.Texture_2D_Target.Fillable_Target'Class; Mipmap_Level : GL.Objects.Textures.Mipmap_Level; Texture : GL.Objects.Textures.Texture'Class) return Image2D is Flags : constant Memory_Flags := Create_Flags (Mode); Raw_Object : System.Address; Error : aliased Enumerations.Error_Code; begin Raw_Object := API.CL_GL.Create_From_GL_Texture_2D (CL_Object (Context).Location, To_Bitfield (Flags), Texture_Target.Raw_Kind, Mipmap_Level, Texture.Raw_Id, Error'Unchecked_Access); Helpers.Error_Handler (Error); return Image2D'(Ada.Finalization.Controlled with Location => Raw_Object); end Create_Image2D; function Create_Image2D (Context : Contexts.CL_GL.Context'Class; Mode : Access_Kind; Texture_Target : Targets.Cube_Map_Side_Target.Fillable_Target'Class; Mipmap_Level : GL.Objects.Textures.Mipmap_Level; Texture : GL.Objects.Textures.Texture'Class) return Image2D is Flags : constant Memory_Flags := Create_Flags (Mode); Raw_Object : System.Address; Error : aliased Enumerations.Error_Code; begin Raw_Object := API.CL_GL.Create_From_GL_Texture_2D (CL_Object (Context).Location, To_Bitfield (Flags), Texture_Target.Raw_Kind, Mipmap_Level, Texture.Raw_Id, Error'Unchecked_Access); Helpers.Error_Handler (Error); return Image2D'(Ada.Finalization.Controlled with Location => Raw_Object); end Create_Image2D; function Create_Image2D (Context : Contexts.CL_GL.Context'Class; Mode : Access_Kind; Renderbuffer : GL.Objects.Renderbuffers.Renderbuffer_Target) return Image2D is Flags : constant Memory_Flags := Create_Flags (Mode); Raw_Object : System.Address; Error : aliased Enumerations.Error_Code; begin Raw_Object := API.CL_GL.Create_From_GL_Renderbuffer (CL_Object (Context).Location, To_Bitfield (Flags), Renderbuffer.Raw_Kind, Error'Unchecked_Access); Helpers.Error_Handler (Error); return Image2D'(Ada.Finalization.Controlled with Location => Raw_Object); end Create_Image2D; function Create_Image3D (Context : Contexts.CL_GL.Context'Class; Mode : Access_Kind; Texture_Target : Targets.Texture_3D_Target.Fillable_Target'Class; Mipmap_Level : GL.Objects.Textures.Mipmap_Level; Texture : GL.Objects.Textures.Texture'Class) return Image3D is Flags : constant Memory_Flags := Create_Flags (Mode); Raw_Object : System.Address; Error : aliased Enumerations.Error_Code; begin Raw_Object := API.CL_GL.Create_From_GL_Texture_3D (CL_Object (Context).Location, To_Bitfield (Flags), Texture_Target.Raw_Kind, Mipmap_Level, Texture.Raw_Id, Error'Unchecked_Access); Helpers.Error_Handler (Error); return Image3D'(Ada.Finalization.Controlled with Location => Raw_Object); end Create_Image3D; end Constructors; end CL.Memory.Images.CL_GL;
{ "source": "starcoderdata", "programming_language": "ada" }
-- @brief Example program using GNAT.sockets to get the date from a RFC 868 TCP protocol server -- @details The output as seconds since the Linux epoch can be verified by running: -- $ date -d @`./get_rdate sandy-ubuntu` -- Sun 7 Jul 19:42:14 BST 2019 with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Command_Line; with Ada.Strings.Fixed; with Interfaces; use Interfaces; with GNAT.Sockets; procedure Get_RDate is Rdate_Client : GNAT.Sockets.Socket_Type; Address : GNAT.Sockets.Sock_Addr_Type; Channel : GNAT.Sockets.Stream_Access; Rdate_Port : GNAT.Sockets.Port_Type := 37; -- Define am array to receive the rdate time as a big-endian 32-bit number of seconds -- since the epoch of 00:00 (midnight) 1 January 1900 GMT type Rdate_Time_Packet is Array (0..3) of Interfaces.Unsigned_8; Raw_Time : Rdate_Time_Packet; Host_Rdate_Time : Interfaces.Unsigned_32; -- From RFC 868 Rdate_To_Linux_Epoch_Seconds : constant := 2208988800; Time_Since_Linux_Epoch : Interfaces.Unsigned_32; begin if Ada.Command_Line.Argument_Count /= 1 then Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & "get_rdate <rdate_server>"); return; end if; declare Rdate_Server : constant String := Ada.Command_Line.Argument (1); begin -- Connect to the specified rdate server and retrieve a packet with the time GNAT.Sockets.Initialize; GNAT.Sockets.Create_Socket (Rdate_Client); Address.Addr := GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (Rdate_Server)); Address.Port := Rdate_Port; GNAT.Sockets.Connect_Socket (Rdate_Client, Address); Channel := GNAT.Sockets.Stream (Rdate_Client); Rdate_Time_Packet'Read (Channel, Raw_Time); GNAT.Sockets.Close_Socket (Rdate_Client); -- Convert the big-endian received rdate Host_Rdate_Time := Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(0)), 24) + Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(1)), 16) + Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(2)), 8) + Interfaces.Unsigned_32 (Raw_Time(3)); -- Display the time as the number of seconds since the Linux epoch. Time_Since_Linux_Epoch := Host_Rdate_Time - Rdate_To_Linux_Epoch_Seconds; declare Raw_Image : constant String := Interfaces.Unsigned_32'Image (Time_Since_Linux_Epoch); begin Ada.Text_Io.Put (Ada.Strings.Fixed.Trim (Raw_Image, Ada.Strings.Left)); end; end; end Get_Rdate;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------------------------ with Ada.Directories; with Ada.Environment_Variables; private with XDG.Defaults; package body XDG is ---------------------------------------------------------------------------- package EV renames Ada.Environment_Variables; -- Directory separator is different for Windows and UNIX so use appropriate -- one. Sep: constant Character := XDG.Defaults.Separator; ---------------------------------------------------------------------------- generic Variable: String; Default : String; function Get_Home return String; function Get_Home return String is Home: constant String := EV.Value ("HOME"); begin if EV.Exists (Variable) then declare Value: constant String := EV.Value (Variable); begin if Value (Value'Last) = Sep then return Value; else return Value & Sep; end if; end; else if Home (Home'Last) = Sep then return Home & Default; else return Home & Sep & Default; end if; end if; end Get_Home; function Get_Data_Home is new Get_Home ("XDG_DATA_HOME", XDG.Defaults.Home); function Get_Config_Home is new Get_Home ("XDG_CONFIG_HOME", XDG.Defaults.Config); function Get_Cache_Home is new Get_Home ("XDG_CACHE_HOME", XDG.Defaults.Cache); function Data_Home return String renames Get_Data_Home; function Config_Home return String renames Get_Config_Home; function Cache_Home return String renames Get_Cache_Home; function Runtime_Dir return String is begin if EV.Exists ("XDG_RUNTIME_DIR") then declare Value: constant String := EV.Value ("XDG_RUNTIME_DIR"); begin if Value (Value'Last) = Sep then return Value; else return Value & Sep; end if; end; else return ""; end if; end Runtime_Dir; function Data_Dirs return String is begin if EV.Exists ("XDG_DATA_DIRS") then return EV.Value ("XDG_DATA_DIRS"); else return XDG.Defaults.Data_Dirs; end if; end Data_Dirs; function Config_Dirs return String is begin if EV.Exists ("XDG_CONFIG_DIRS") then return EV.Value ("XDG_CONFIG_DIRS"); else return XDG.Defaults.Config_Dirs; end if; end Config_Dirs; ---------------------------------------------------------------------------- generic with function XDG_Path return String; function XDG_Home (Directory: in String) return String; function XDG_Home (Directory: in String) return String is Path: constant String := XDG_Path; begin if Path (Path'Last) = Sep then if Directory (Directory'Last) = Sep then return Path & Directory; else return Path & Directory & Sep; end if; else if Directory (Directory'Last) = Sep then return Path & Sep & Directory; else return Path & Sep & Directory & Sep; end if; end if; end XDG_Home; function Data_Home_Path is new XDG_Home (Data_Home); function Config_Home_Path is new XDG_Home (Config_Home); function Cache_Home_Path is new XDG_Home (Cache_Home); function Data_Home (Directory: in String) return String renames Data_Home_Path; function Config_Home (Directory: in String) return String renames Config_Home_Path; function Cache_Home (Directory: in String) return String renames Cache_Home_Path; function Runtime_Dir (Directory: in String) return String is Path: constant String := Runtime_Dir; begin if Path'Length = 0 then raise No_Runtime_Dir; elsif Directory (Directory'Last) = Sep then return Path & Directory; else return Path & Directory & Sep; end if; end Runtime_Dir; ---------------------------------------------------------------------------- generic with function XDG_Path (Directory: in String) return String; procedure Create_Home (Directory: in String); procedure Create_Home (Directory: in String) is package AD renames Ada.Directories; Path: constant String := XDG_Path (Directory); begin AD.Create_Path (Path); end Create_Home; procedure Create_Data is new Create_Home (Data_Home); procedure Create_Config is new Create_Home (Config_Home); procedure Create_Cache is new Create_Home (Cache_Home); procedure Create_Runtime is new Create_Home (Runtime_Dir); procedure Create_Data_Home (Directory: in String) renames Create_Data; procedure Create_Config_Home (Directory: in String) renames Create_Config; procedure Create_Cache_Home (Directory: in String) renames Create_Cache; procedure Create_Runtime_Dir (Directory: in String) renames Create_Runtime; ---------------------------------------------------------------------------- generic with function XDG_Path (Directory: in String) return String; procedure Delete_Home (Directory: in String; Empty_Only: in Boolean := True); procedure Delete_Home (Directory: in String; Empty_Only: in Boolean := True) is package AD renames Ada.Directories; Path: constant String := XDG_Path (Directory); begin if Empty_Only then AD.Delete_Directory (Path); else AD.Delete_Tree (Path); end if; end Delete_Home; procedure Delete_Data is new Delete_Home (Data_Home); procedure Delete_Config is new Delete_Home (Config_Home); procedure Delete_Cache is new Delete_Home (Cache_Home); procedure Delete_Runtime is new Delete_Home (Runtime_Dir); procedure Delete_Data_Home ( Directory : in String; Empty_Only: in Boolean := True ) renames Delete_Data; procedure Delete_Config_Home ( Directory : in String; Empty_Only: in Boolean := True ) renames Delete_Config; procedure Delete_Cache_Home ( Directory : in String; Empty_Only: in Boolean := True ) renames Delete_Cache; procedure Delete_Runtime_Dir ( Directory : in String; Empty_Only: in Boolean := True ) renames Delete_Runtime; ---------------------------------------------------------------------------- generic with function XDG_Home (Directory: in String) return String; function Check_Home (Directory: in String) return Boolean; function Check_Home (Directory: in String) return Boolean is package AD renames Ada.Directories; use type AD.File_Kind; Path: constant String := XDG_Home (Directory); begin if AD.Exists (Path) and then AD.Kind (Path) /= AD.Directory then return False; else return True; end if; end Check_Home; function Check_Data_Home is new Check_Home (Data_Home); function Check_Config_Home is new Check_Home (Config_Home); function Check_Cache_Home is new Check_Home (Cache_Home); function Check_Runtime_Dir is new Check_Home (Runtime_Dir); function Is_Valid_Data_Home (Directory: in String) return Boolean renames Check_Data_Home; function Is_Valid_Config_Home (Directory: in String) return Boolean renames Check_Config_Home; function Is_Valid_Cache_Home (Directory: in String) return Boolean renames Check_Cache_Home; function Is_Valid_Runtime_Dir (Directory: in String) return Boolean renames Check_Runtime_Dir; ---------------------------------------------------------------------------- end XDG;
{ "source": "starcoderdata", "programming_language": "ada" }
-- { dg-do run } with Init8; use Init8; with Text_IO; use Text_IO; with Dump; procedure S8 is A1 : R1 := My_R1; A2 : R2 := My_R2; N1 : Nested1; N2 : Nested2; C1 : Integer; C2 : Integer; C3 : Integer; begin Put ("A1 :"); Dump (A1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A1 : 78 56 34 12 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Put ("A2 :"); Dump (A2'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A2 : 12 34 56 78 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } N1 := A1.N; C1 := N1.C1; C2 := N1.C2; C3 := N1.C3; Put_Line("C1 :" & C1'Img); -- { dg-output "C1 : 11206674.*\n" } Put_Line("C2 :" & C2'Img); -- { dg-output "C2 : 13434932.*\n" } Put_Line("C3 :" & C3'Img); -- { dg-output "C3 : 15663190.*\n" } N1.C1 := C1; N1.C2 := C2; N1.C3 := C3; A1.N := N1; N2 := A2.N; C1 := N2.C1; C2 := N2.C2; C3 := N2.C3; Put_Line("C1 :" & C1'Img); -- { dg-output "C1 : 11206674.*\n" } Put_Line("C2 :" & C2'Img); -- { dg-output "C2 : 13434932.*\n" } Put_Line("C3 :" & C3'Img); -- { dg-output "C3 : 15663190.*\n" } N2.C1 := C1; N2.C2 := C2; N2.C3 := C3; A2.N := N2; Put ("A1 :"); Dump (A1'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A1 : 78 56 34 12 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Put ("A2 :"); Dump (A2'Address, R1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "A2 : 12 34 56 78 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } end;
{ "source": "starcoderdata", "programming_language": "ada" }
-- Implemented from the specification included in the Intel C++ Compiler -- User Guide and Reference, version 9.0. -- We need type definitions from the MMX header file. -- Get _mm_malloc () and _mm_free (). -- Constants for use with _mm_prefetch. subtype u_mm_hint is unsigned; u_MM_HINT_ET0 : constant unsigned := 7; u_MM_HINT_ET1 : constant unsigned := 6; u_MM_HINT_T0 : constant unsigned := 3; u_MM_HINT_T1 : constant unsigned := 2; u_MM_HINT_T2 : constant unsigned := 1; u_MM_HINT_NTA : constant unsigned := 0; -- d:\install\gpl2018\lib\gcc\x86_64-pc-mingw32\7.3.1\include\xmmintrin.h:37 -- _MM_HINT_ET is _MM_HINT_T with set 3rd bit. -- Loads one cache line from address P to a location "closer" to the -- processor. The selector I specifies the type of prefetch operation. -- The Intel API is flexible enough that we must allow aliasing with other -- vector types, and their scalar components. subtype uu_m128 is <vector>; -- d:\install\gpl2018\lib\gcc\x86_64-pc-mingw32\7.3.1\include\xmmintrin.h:69 -- Unaligned version of the same type. subtype uu_m128_u is <vector>; -- d:\install\gpl2018\lib\gcc\x86_64-pc-mingw32\7.3.1\include\xmmintrin.h:72 -- Internal data types for implementing the intrinsics. subtype uu_v4sf is <vector>; -- d:\install\gpl2018\lib\gcc\x86_64-pc-mingw32\7.3.1\include\xmmintrin.h:75 -- Create a selector for use with the SHUFPS instruction. -- Bits in the MXCSR. -- Create an undefined vector. -- skipped func _mm_undefined_ps -- Create a vector of zeros. -- skipped func _mm_setzero_ps -- Perform the respective operation on the lower SPFP (single-precision -- floating-point) values of A and B; the upper three SPFP values are -- passed through from A. -- skipped func _mm_add_ss -- skipped func _mm_sub_ss -- skipped func _mm_mul_ss -- skipped func _mm_div_ss -- skipped func _mm_sqrt_ss -- skipped func _mm_rcp_ss -- skipped func _mm_rsqrt_ss -- skipped func _mm_min_ss -- skipped func _mm_max_ss -- Perform the respective operation on the four SPFP values in A and B. -- skipped func _mm_add_ps -- skipped func _mm_sub_ps -- skipped func _mm_mul_ps -- skipped func _mm_div_ps -- skipped func _mm_sqrt_ps -- skipped func _mm_rcp_ps -- skipped func _mm_rsqrt_ps -- skipped func _mm_min_ps -- skipped func _mm_max_ps -- Perform logical bit-wise operations on 128-bit values. -- skipped func _mm_and_ps -- skipped func _mm_andnot_ps -- skipped func _mm_or_ps -- skipped func _mm_xor_ps -- Perform a comparison on the lower SPFP values of A and B. If the -- comparison is true, place a mask of all ones in the result, otherwise a -- mask of zeros. The upper three SPFP values are passed through from A. -- skipped func _mm_cmpeq_ss -- skipped func _mm_cmplt_ss -- skipped func _mm_cmple_ss -- skipped func _mm_cmpgt_ss -- skipped func _mm_cmpge_ss -- skipped func _mm_cmpneq_ss -- skipped func _mm_cmpnlt_ss -- skipped func _mm_cmpnle_ss -- skipped func _mm_cmpngt_ss -- skipped func _mm_cmpnge_ss -- skipped func _mm_cmpord_ss -- skipped func _mm_cmpunord_ss -- Perform a comparison on the four SPFP values of A and B. For each -- element, if the comparison is true, place a mask of all ones in the -- result, otherwise a mask of zeros. -- skipped func _mm_cmpeq_ps -- skipped func _mm_cmplt_ps -- skipped func _mm_cmple_ps -- skipped func _mm_cmpgt_ps -- skipped func _mm_cmpge_ps -- skipped func _mm_cmpneq_ps -- skipped func _mm_cmpnlt_ps -- skipped func _mm_cmpnle_ps -- skipped func _mm_cmpngt_ps -- skipped func _mm_cmpnge_ps -- skipped func _mm_cmpord_ps -- skipped func _mm_cmpunord_ps -- Compare the lower SPFP values of A and B and return 1 if true -- and 0 if false. -- skipped func _mm_comieq_ss -- skipped func _mm_comilt_ss -- skipped func _mm_comile_ss -- skipped func _mm_comigt_ss -- skipped func _mm_comige_ss -- skipped func _mm_comineq_ss -- skipped func _mm_ucomieq_ss -- skipped func _mm_ucomilt_ss -- skipped func _mm_ucomile_ss -- skipped func _mm_ucomigt_ss -- skipped func _mm_ucomige_ss -- skipped func _mm_ucomineq_ss -- Convert the lower SPFP value to a 32-bit integer according to the current -- rounding mode. -- skipped func _mm_cvtss_si32 -- skipped func _mm_cvt_ss2si -- Convert the lower SPFP value to a 32-bit integer according to the -- current rounding mode. -- Intel intrinsic. -- skipped func _mm_cvtss_si64 -- Microsoft intrinsic. -- skipped func _mm_cvtss_si64x -- Convert the two lower SPFP values to 32-bit integers according to the -- current rounding mode. Return the integers in packed form. -- skipped func _mm_cvtps_pi32 -- skipped func _mm_cvt_ps2pi -- Truncate the lower SPFP value to a 32-bit integer. -- skipped func _mm_cvttss_si32 -- skipped func _mm_cvtt_ss2si -- Truncate the lower SPFP value to a 32-bit integer. -- Intel intrinsic. -- skipped func _mm_cvttss_si64 -- Microsoft intrinsic. -- skipped func _mm_cvttss_si64x -- Truncate the two lower SPFP values to 32-bit integers. Return the -- integers in packed form. -- skipped func _mm_cvttps_pi32 -- skipped func _mm_cvtt_ps2pi -- Convert B to a SPFP value and insert it as element zero in A. -- skipped func _mm_cvtsi32_ss -- skipped func _mm_cvt_si2ss -- Convert B to a SPFP value and insert it as element zero in A. -- Intel intrinsic. -- skipped func _mm_cvtsi64_ss -- Microsoft intrinsic. -- skipped func _mm_cvtsi64x_ss -- Convert the two 32-bit values in B to SPFP form and insert them -- as the two lower elements in A. -- skipped func _mm_cvtpi32_ps -- skipped func _mm_cvt_pi2ps -- Convert the four signed 16-bit values in A to SPFP form. -- skipped func _mm_cvtpi16_ps -- This comparison against zero gives us a mask that can be used to -- fill in the missing sign bits in the unpack operations below, so -- that we get signed values after unpacking. -- Convert the four words to doublewords. -- Convert the doublewords to floating point two at a time. -- Convert the four unsigned 16-bit values in A to SPFP form. -- skipped func _mm_cvtpu16_ps -- Convert the four words to doublewords. -- Convert the doublewords to floating point two at a time. -- Convert the low four signed 8-bit values in A to SPFP form. -- skipped func _mm_cvtpi8_ps -- This comparison against zero gives us a mask that can be used to -- fill in the missing sign bits in the unpack operations below, so -- that we get signed values after unpacking. -- Convert the four low bytes to words. -- Convert the low four unsigned 8-bit values in A to SPFP form. -- skipped func _mm_cvtpu8_ps -- Convert the four signed 32-bit values in A and B to SPFP form. -- skipped func _mm_cvtpi32x2_ps -- Convert the four SPFP values in A to four signed 16-bit integers. -- skipped func _mm_cvtps_pi16 -- Convert the four SPFP values in A to four signed 8-bit integers. -- skipped func _mm_cvtps_pi8 -- Selects four specific SPFP values from A and B based on MASK. -- Selects and interleaves the upper two SPFP values from A and B. -- skipped func _mm_unpackhi_ps -- Selects and interleaves the lower two SPFP values from A and B. -- skipped func _mm_unpacklo_ps -- Sets the upper two SPFP values with 64-bits of data loaded from P; -- the lower two values are passed through from A. -- skipped func _mm_loadh_pi -- Stores the upper two SPFP values of A into P. -- skipped func _mm_storeh_pi -- Moves the upper two values of B into the lower two values of A. -- skipped func _mm_movehl_ps -- Moves the lower two values of B into the upper two values of A. -- skipped func _mm_movelh_ps -- Sets the lower two SPFP values with 64-bits of data loaded from P; -- the upper two values are passed through from A. -- skipped func _mm_loadl_pi -- Stores the lower two SPFP values of A into P. -- skipped func _mm_storel_pi -- Creates a 4-bit mask from the most significant bits of the SPFP values. -- skipped func _mm_movemask_ps -- Return the contents of the control register. -- skipped func _mm_getcsr -- Read exception bits from the control register. -- skipped func _MM_GET_EXCEPTION_STATE -- skipped func _MM_GET_EXCEPTION_MASK -- skipped func _MM_GET_ROUNDING_MODE -- skipped func _MM_GET_FLUSH_ZERO_MODE -- Set the control register to I. -- skipped func _mm_setcsr -- Set exception bits in the control register. -- skipped func _MM_SET_EXCEPTION_STATE -- skipped func _MM_SET_EXCEPTION_MASK -- skipped func _MM_SET_ROUNDING_MODE -- skipped func _MM_SET_FLUSH_ZERO_MODE -- Create a vector with element 0 as F and the rest zero. -- skipped func _mm_set_ss -- Create a vector with all four elements equal to F. -- skipped func _mm_set1_ps -- skipped func _mm_set_ps1 -- Create a vector with element 0 as *P and the rest zero. -- skipped func _mm_load_ss -- Create a vector with all four elements equal to *P. -- skipped func _mm_load1_ps -- skipped func _mm_load_ps1 -- Load four SPFP values from P. The address must be 16-byte aligned. -- skipped func _mm_load_ps -- Load four SPFP values from P. The address need not be 16-byte aligned. -- skipped func _mm_loadu_ps -- Load four SPFP values in reverse order. The address must be aligned. -- skipped func _mm_loadr_ps -- Create the vector [Z Y X W]. -- skipped func _mm_set_ps -- Create the vector [W X Y Z]. -- skipped func _mm_setr_ps -- Stores the lower SPFP value. -- skipped func _mm_store_ss -- skipped func _mm_cvtss_f32 -- Store four SPFP values. The address must be 16-byte aligned. -- skipped func _mm_store_ps -- Store four SPFP values. The address need not be 16-byte aligned. -- skipped func _mm_storeu_ps -- Store the lower SPFP value across four words. -- skipped func _mm_store1_ps -- skipped func _mm_store_ps1 -- Store four SPFP values in reverse order. The address must be aligned. -- skipped func _mm_storer_ps -- Sets the low SPFP value of A from the low value of B. -- skipped func _mm_move_ss -- Extracts one of the four words of A. The selector N must be immediate. -- Inserts word D into one of four words of A. The selector N must be -- immediate. -- Compute the element-wise maximum of signed 16-bit values. -- skipped func _mm_max_pi16 -- skipped func _m_pmaxsw -- Compute the element-wise maximum of unsigned 8-bit values. -- skipped func _mm_max_pu8 -- skipped func _m_pmaxub -- Compute the element-wise minimum of signed 16-bit values. -- skipped func _mm_min_pi16 -- skipped func _m_pminsw -- Compute the element-wise minimum of unsigned 8-bit values. -- skipped func _mm_min_pu8 -- skipped func _m_pminub -- Create an 8-bit mask of the signs of 8-bit values. -- skipped func _mm_movemask_pi8 -- skipped func _m_pmovmskb -- Multiply four unsigned 16-bit values in A by four unsigned 16-bit values -- in B and produce the high 16 bits of the 32-bit results. -- skipped func _mm_mulhi_pu16 -- skipped func _m_pmulhuw -- Return a combination of the four 16-bit values in A. The selector -- must be an immediate. -- Conditionally store byte elements of A into P. The high bit of each -- byte in the selector N determines whether the corresponding byte from -- A is stored. -- skipped func _mm_maskmove_si64 -- skipped func _m_maskmovq -- Compute the rounded averages of the unsigned 8-bit values in A and B. -- skipped func _mm_avg_pu8 -- skipped func _m_pavgb -- Compute the rounded averages of the unsigned 16-bit values in A and B. -- skipped func _mm_avg_pu16 -- skipped func _m_pavgw -- Compute the sum of the absolute differences of the unsigned 8-bit -- values in A and B. Return the value in the lower 16-bit word; the -- upper words are cleared. -- skipped func _mm_sad_pu8 -- skipped func _m_psadbw -- Stores the data in A to the address P without polluting the caches. -- skipped func _mm_stream_pi -- Likewise. The address must be 16-byte aligned. -- skipped func _mm_stream_ps -- Guarantees that every preceding store is globally visible before -- any subsequent store. -- skipped func _mm_sfence -- Transpose the 4x4 matrix composed of row[0-3]. -- For backward source compatibility. -- The execution of the next instruction is delayed by an implementation -- specific amount of time. The instruction does not modify the -- architectural state. This is after the pop_options pragma because -- it does not require SSE support in the processor--the encoding is a -- nop on processors that do not support it. -- skipped func _mm_pause end xmmintrin_h;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with Ada.Strings.Fixed.Hash; with Ada.Strings.Unbounded.Hash; with Ada.Containers; with Util.Test_Caller; with Util.Strings.Transforms; with Util.Strings.Maps; with Util.Perfect_Hash; with Util.Strings.Tokenizers; with Ada.Streams; with Util.Measures; package body Util.Strings.Tests is use Ada.Strings.Unbounded; use Util.Tests; use Util.Strings.Transforms; package Caller is new Util.Test_Caller (Test, "Strings"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Javascript", Test_Escape_Javascript'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Escape_Xml", Test_Escape_Xml'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Unescape_Xml", Test_Unescape_Xml'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.Capitalize", Test_Capitalize'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Upper_Case", Test_To_Upper_Case'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Lower_Case", Test_To_Lower_Case'Access); Caller.Add_Test (Suite, "Test Util.Strings.Transforms.To_Hex", Test_To_Hex'Access); Caller.Add_Test (Suite, "Test Measure", Test_Measure_Copy'Access); Caller.Add_Test (Suite, "Test Util.Strings.Index", Test_Index'Access); Caller.Add_Test (Suite, "Test Util.Strings.Rindex", Test_Rindex'Access); Caller.Add_Test (Suite, "Test Util.Strings.Benchmark", Test_Measure_Hash'Access); Caller.Add_Test (Suite, "Test Util.Strings.String_Ref", Test_String_Ref'Access); Caller.Add_Test (Suite, "Test perfect hash", Test_Perfect_Hash'Access); Caller.Add_Test (Suite, "Test Util.Strings.Tokenizers.Iterate_Token", Test_Iterate_Token'Access); end Add_Tests; procedure Test_Escape_Javascript (T : in out Test) is Result : Unbounded_String; begin Escape_Javascript (Content => ASCII.LF & " ""a string"" a 'single quote'", Into => Result); Assert_Equals (T, "\n \""a string\"" a \'single quote\'", Result); Result := To_Unbounded_String (""); Escape_Javascript (Content => ASCII.ESC & "[m " & Character'Val (255), Into => Result); Assert_Equals (T, "\u001B[m " & Character'Val (255), Result); end Test_Escape_Javascript; procedure Test_Escape_Xml (T : in out Test) is Result : Unbounded_String; begin Escape_Xml (Content => ASCII.LF & " < ""a string"" a 'single quote' >& ", Into => Result); Assert_Equals (T, ASCII.LF & " &lt; ""a string"" a &apos;single quote&apos; &gt;&amp; ", Result); Result := To_Unbounded_String (""); Escape_Xml (Content => ASCII.ESC & "[m " & Character'Val (255), Into => Result); Assert_Equals (T, ASCII.ESC & "[m &#255;", Result); end Test_Escape_Xml; procedure Test_Unescape_Xml (T : in out Test) is Result : Unbounded_String; begin Unescape_Xml (Content => "&lt;&gt;&amp;&quot; &apos; &#x41;", Translator => Util.Strings.Transforms.TR.Translate_Xml_Entity'Access, Into => Result); Util.Tests.Assert_Equals (T, "<>&"" ' A", Result, "Invalid unescape"); Set_Unbounded_String (Result, ""); Unescape_Xml (Content => "Test &#65;&#111;&#126; end", Translator => Util.Strings.Transforms.TR.Translate_Xml_Entity'Access, Into => Result); Util.Tests.Assert_Equals (T, "Test Ao~ end", Result, "Invalid decimal unescape"); Set_Unbounded_String (Result, ""); Unescape_Xml (Content => "Test &#x65;&#xc0;&#x111;&#x126;&#xcb; end", Translator => Util.Strings.Transforms.TR.Translate_Xml_Entity'Access, Into => Result); Util.Tests.Assert_Equals (T, "Test eÀđĦË end", Result, "Invalid Decimal Unescape"); Unescape_Xml (Content => "&;&#qsf;&qsd;&#12121212121212121212;; &#41", Translator => Util.Strings.Transforms.TR.Translate_Xml_Entity'Access, Into => Result); end Test_Unescape_Xml; procedure Test_Capitalize (T : in out Test) is Result : Unbounded_String; begin Assert_Equals (T, "Capitalize_A_String", Capitalize ("capITalIZe_a_strING")); Capitalize ("CapAS_String", Result); Assert_Equals (T, "Capas_String", Result); end Test_Capitalize; procedure Test_To_Upper_Case (T : in out Test) is begin Assert_Equals (T, "UPPERCASE_0123_STR", To_Upper_Case ("upperCase_0123_str")); end Test_To_Upper_Case; procedure Test_To_Lower_Case (T : in out Test) is begin Assert_Equals (T, "lowercase_0123_str", To_Lower_Case ("LowERCase_0123_STR")); end Test_To_Lower_Case; procedure Test_To_Hex (T : in out Test) is Result : Unbounded_String; begin To_Hex (Result, Character'Val (23)); Assert_Equals (T, "\u0017", Result); To_Hex (Result, Character'Val (31)); Assert_Equals (T, "\u0017\u001F", Result); To_Hex (Result, Character'Val (255)); Assert_Equals (T, "\u0017\u001F\u00FF", Result); end Test_To_Hex; procedure Test_Measure_Copy (T : in out Test) is pragma Unreferenced (T); Buf : constant Ada.Streams.Stream_Element_Array (1 .. 10_024) := (others => 23); pragma Suppress (All_Checks, Buf); begin declare T : Util.Measures.Stamp; R : Ada.Strings.Unbounded.Unbounded_String; begin for I in Buf'Range loop Append (R, Character'Val (Buf (I))); end loop; Util.Measures.Report (T, "Stream transform using Append (1024 bytes)"); end; declare T : Util.Measures.Stamp; R : Ada.Strings.Unbounded.Unbounded_String; S : String (1 .. 10_024); pragma Suppress (All_Checks, S); begin for I in Buf'Range loop S (Natural (I)) := Character'Val (Buf (I)); end loop; Append (R, S); Util.Measures.Report (T, "Stream transform using temporary string (1024 bytes)"); end; -- declare -- T : Util.Measures.Stamp; -- R : Ada.Strings.Unbounded.Unbounded_String; -- P : constant Ptr := new String (1 .. Buf'Length); -- -- pragma Suppress (All_Checks, P); -- begin -- for I in P'Range loop -- P (I) := Character'Val (Buf (Ada.Streams.Stream_Element_Offset (I))); -- end loop; -- Ada.Strings.Unbounded.Aux.Set_String (R, P.all'Access); -- Util.Measures.Report (T, "Stream transform using Aux string (1024 bytes)"); -- end; declare T : Util.Measures.Stamp; H : Ada.Containers.Hash_Type; pragma Unreferenced (H); begin for I in 1 .. 1_000 loop H := Ada.Strings.Fixed.Hash ("http://code.google.com/p/ada-awa/jsf:wiki"); end loop; Util.Measures.Report (T, "Ada.Strings.Fixed.Hash"); end; declare T : Util.Measures.Stamp; H : Ada.Containers.Hash_Type; pragma Unreferenced (H); begin for I in 1 .. 1_000 loop H := Ada.Strings.Fixed.Hash ("http://code.google.com/p/ada-awa/jsf:wiki"); end loop; Util.Measures.Report (T, "Ada.Strings.Fixed.Hash"); end; end Test_Measure_Copy; -- Test the Index operation procedure Test_Index (T : in out Test) is Str : constant String := "0123456789abcdefghijklmnopq"; begin declare St : Util.Measures.Stamp; Pos : Integer; begin for I in 1 .. 10 loop Pos := Index (Str, 'q'); end loop; Util.Measures.Report (St, "Util.Strings.Index"); Assert_Equals (T, 27, Pos, "Invalid index position"); end; declare St : Util.Measures.Stamp; Pos : Integer; begin for I in 1 .. 10 loop Pos := Ada.Strings.Fixed.Index (Str, "q"); end loop; Util.Measures.Report (St, "Ada.Strings.Fixed.Index"); Assert_Equals (T, 27, Pos, "Invalid index position"); end; end Test_Index; -- Test the Rindex operation procedure Test_Rindex (T : in out Test) is Str : constant String := "0123456789abcdefghijklmnopq"; begin declare St : Util.Measures.Stamp; Pos : Natural; begin for I in 1 .. 10 loop Pos := Rindex (Str, '0'); end loop; Util.Measures.Report (St, "Util.Strings.Rindex"); Assert_Equals (T, 1, Pos, "Invalid rindex position"); end; declare St : Util.Measures.Stamp; Pos : Natural; begin for I in 1 .. 10 loop Pos := Ada.Strings.Fixed.Index (Str, "0", Ada.Strings.Backward); end loop; Util.Measures.Report (St, "Ada.Strings.Fixed.Rindex"); Assert_Equals (T, 1, Pos, "Invalid rindex position"); end; end Test_Rindex; package String_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Unbounded_String, Hash => Hash, Equivalent_Keys => "="); package String_Ref_Map is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => String_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test) is KEY : aliased constant String := "testing"; Str_Map : Util.Strings.Maps.Map; Ptr_Map : Util.Strings.String_Access_Map.Map; Ref_Map : String_Ref_Map.Map; Unb_Map : String_Map.Map; Name : String_Access := new String '(KEY); Ref : constant String_Ref := To_String_Ref (KEY); begin Str_Map.Insert (Name.all, Name.all); Ptr_Map.Insert (Name.all'Access, Name.all'Access); Unb_Map.Insert (To_Unbounded_String (KEY), To_Unbounded_String (KEY)); Ref_Map.Insert (Ref, Ref); declare T : Util.Measures.Stamp; H : Ada.Containers.Hash_Type; pragma Unreferenced (H); begin for I in 1 .. 1_000 loop H := Ada.Strings.Fixed.Hash ("http://code.google.com/p/ada-awa/jsf:wiki"); end loop; Util.Measures.Report (T, "Ada.Strings.Fixed.Hash (1000 calls)"); end; -- Performance of Hashed_Map Name_Access -> Name_Access -- (the fastest hash) declare St : Util.Measures.Stamp; Pos : constant Strings.String_Access_Map.Cursor := Ptr_Map.Find (KEY'Unchecked_Access); Val : constant Name_Access := Util.Strings.String_Access_Map.Element (Pos); begin Util.Measures.Report (St, "Util.Strings.String_Access_Maps.Find+Element"); Assert_Equals (T, "testing", Val.all, "Invalid value returned"); end; -- Performance of Hashed_Map String_Ref -> String_Ref -- (almost same performance as Hashed_Map Name_Access -> Name_Access) declare St : Util.Measures.Stamp; Pos : constant String_Ref_Map.Cursor := Ref_Map.Find (Ref); Val : constant String_Ref := String_Ref_Map.Element (Pos); begin Util.Measures.Report (St, "Util.Strings.String_Ref_Maps.Find+Element"); Assert_Equals (T, "testing", String '(To_String (Val)), "Invalid value returned"); end; -- Performance of Hashed_Map Unbounded_String -> Unbounded_String -- (little overhead due to String copy made by Unbounded_String) declare St : Util.Measures.Stamp; Pos : constant String_Map.Cursor := Unb_Map.Find (To_Unbounded_String (KEY)); Val : constant Unbounded_String := String_Map.Element (Pos); begin Util.Measures.Report (St, "Hashed_Maps<Unbounded,Unbounded..Find+Element"); Assert_Equals (T, "testing", Val, "Invalid value returned"); end; -- Performance for Indefinite_Hashed_Map String -> String -- (the slowest hash, string copy to get the result, pointer to key and element -- in the hash map implementation) declare St : Util.Measures.Stamp; Pos : constant Util.Strings.Maps.Cursor := Str_Map.Find (KEY); Val : constant String := Util.Strings.Maps.Element (Pos); begin Util.Measures.Report (St, "Util.Strings.Maps.Find+Element"); Assert_Equals (T, "testing", Val, "Invalid value returned"); end; Free (Name); end Test_Measure_Hash; -- ------------------------------ -- Test String_Ref creation -- ------------------------------ procedure Test_String_Ref (T : in out Test) is R1 : String_Ref := To_String_Ref ("testing a string"); begin for I in 1 .. 1_000 loop declare S : constant String (1 .. I) := (others => 'x'); R2 : constant String_Ref := To_String_Ref (S); begin Assert_Equals (T, S, To_String (R2), "Invalid String_Ref"); T.Assert (R2 = S, "Invalid comparison"); Assert_Equals (T, I, Length (R2), "Invalid length"); R1 := R2; T.Assert (R1 = R2, "Invalid String_Ref copy"); end; end loop; end Test_String_Ref; -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test) is begin for I in Util.Perfect_Hash.Keywords'Range loop declare K : constant String := Util.Perfect_Hash.Keywords (I).all; begin Assert_Equals (T, I, Util.Perfect_Hash.Hash (K), "Invalid hash"); Assert_Equals (T, I, Util.Perfect_Hash.Hash (To_Lower_Case (K)), "Invalid hash"); Assert (T, Util.Perfect_Hash.Is_Keyword (K), "Keyword " & K & " is not a keyword"); Assert (T, Util.Perfect_Hash.Is_Keyword (To_Lower_Case (K)), "Keyword " & K & " is not a keyword"); end; end loop; end Test_Perfect_Hash; -- ------------------------------ -- Test the token iteration. -- ------------------------------ procedure Test_Iterate_Token (T : in out Test) is procedure Process_Token (Token : in String; Done : out Boolean); Called : Natural := 0; procedure Process_Token (Token : in String; Done : out Boolean) is begin T.Assert (Token = "one" or Token = "two" or Token = "three" or Token = "four five" or Token = "six seven", "Invalid token: [" & Token & "]"); Called := Called + 1; Done := False; end Process_Token; begin Util.Strings.Tokenizers.Iterate_Tokens (Content => "one two three", Pattern => " ", Process => Process_Token'Access); Util.Tests.Assert_Equals (T, 3, Called, "Iterate_Tokens calls Process incorrectly"); Util.Strings.Tokenizers.Iterate_Tokens (Content => "one two three", Pattern => " ", Process => Process_Token'Access, Going => Ada.Strings.Backward); Util.Tests.Assert_Equals (T, 6, Called, "Iterate_Tokens calls Process incorrectly"); Util.Strings.Tokenizers.Iterate_Tokens (Content => "four five blob six seven", Pattern => " blob ", Process => Process_Token'Access); Util.Tests.Assert_Equals (T, 8, Called, "Iterate_Tokens calls Process incorrectly"); end Test_Iterate_Token; end Util.Strings.Tests;
{ "source": "starcoderdata", "programming_language": "ada" }
--* -- CHECK THAT CONSTRAINT_ERROR IS RAISED FOR THE DECLARATION OF A NULL -- ARRAY OBJECT IF THE INITIAL VALUE IS NOT A NULL ARRAY. -- RJW 7/20/86 -- GMT 7/01/87 ADDED CODE TO PREVENT DEAD VARIABLE OPTIMIZATION. -- CHANGED THE RANGE VALUES OF A FEW DIMENSIONS. WITH REPORT; USE REPORT; PROCEDURE C32112B IS TYPE ARR1 IS ARRAY (NATURAL RANGE <>) OF INTEGER; SUBTYPE NARR1 IS ARR1 (IDENT_INT (2) .. IDENT_INT (1)); TYPE ARR2 IS ARRAY (NATURAL RANGE <>, NATURAL RANGE <>) OF INTEGER; SUBTYPE NARR2 IS ARR2 (IDENT_INT (1) .. IDENT_INT (2), IDENT_INT (1) .. IDENT_INT (0)); BEGIN TEST ("C32112B", "CHECK THAT CONSTRAINT_ERROR IS RAISED FOR " & "THE DECLARATION OF A NULL ARRAY OBJECT IF " & "THE INITIAL VALUE IS NOT A NULL ARRAY"); BEGIN DECLARE A : ARR1 (IDENT_INT(1) .. IDENT_INT(2)); N1A : NARR1 := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1A'"); A(1) := IDENT_INT(N1A(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1A'"); END; BEGIN DECLARE A : ARR1 (IDENT_INT (1) .. IDENT_INT (2)); N1B : CONSTANT NARR1 := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1B'"); A(1) := IDENT_INT(N1B(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1B'"); END; BEGIN DECLARE A : ARR1 (IDENT_INT (1) .. IDENT_INT (1)); N1C : CONSTANT NARR1 := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1C'"); A(1) := IDENT_INT(N1C(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1C'"); END; BEGIN DECLARE A : ARR1 (IDENT_INT (1) .. IDENT_INT (1)); N1D : NARR1 := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1D'"); A(1) := IDENT_INT(N1D(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1D'"); END; BEGIN DECLARE A : ARR1 (IDENT_INT (0) .. IDENT_INT (1)); N1E : ARR1 (IDENT_INT (1) .. IDENT_INT (0)) := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1E'"); A(1) := IDENT_INT(N1E(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N1E'"); END; BEGIN DECLARE A : ARR1 (IDENT_INT (0) .. IDENT_INT (1)); N1F : CONSTANT ARR1 (IDENT_INT (1) .. IDENT_INT (0)) := (A'RANGE => 0); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1F'"); A(1) := IDENT_INT(N1F(1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N1F'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (2), IDENT_INT (0) .. IDENT_INT (1)); N2A : CONSTANT NARR2 := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2'"); A(1,1) := IDENT_INT(N2A(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2A'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (2), IDENT_INT (0) .. IDENT_INT (1)); N2B : NARR2 := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2B'"); A(1,1) := IDENT_INT(N2B(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2B'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (3), IDENT_INT (1) .. IDENT_INT (1)); N2C : CONSTANT NARR2 := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2C'"); A(1,1) := IDENT_INT(N2C(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2C'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (3), IDENT_INT (1) .. IDENT_INT (1)); N2D : NARR2 := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2D'"); A(1,1) := IDENT_INT(N2D(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2D'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (1), IDENT_INT (1) .. IDENT_INT (1)); N2E : CONSTANT ARR2 (IDENT_INT (2) .. IDENT_INT (1), IDENT_INT (1) .. IDENT_INT (1)) := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2E'"); A(1,1) := IDENT_INT(N2E(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'N2E'"); END; BEGIN DECLARE A : ARR2 (IDENT_INT (1) .. IDENT_INT (1), IDENT_INT (1) .. IDENT_INT (1)); N2F : ARR2 (IDENT_INT (2) .. IDENT_INT (1), IDENT_INT (1) .. IDENT_INT (1)) := (A'RANGE => (A'RANGE (2) =>0)); BEGIN FAILED ("NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2F'"); A(1,1) := IDENT_INT(N2F(1,1)); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'N2F'"); END; RESULT; END C32112B;
{ "source": "starcoderdata", "programming_language": "ada" }
-- ----------------------------------------------------------------- -- with gl_h; use gl_h; package AdaGL is function glGetString (Chars_Ref : GLenum) return String; type Three_GLfloat_Vector is array (0 .. 2) of GLfloat; pragma Convention (C, Three_GLFloat_Vector); type Four_GLfloat_Vector is array (0 .. 3) of GLfloat; pragma Convention (C, Four_GLFloat_Vector); type Three_GLint_Vector is array (0 .. 2) of GLint; pragma Convention (C, Three_GLint_Vector); type Four_GLint_Vector is array (0 .. 3) of GLint; pragma Convention (C, Four_GLint_Vector); procedure glVertex3fv (v : Three_GLFloat_Vector); pragma Import (C, glVertex3fv, "glVertex3fv"); procedure glColor3fv (v : Three_GLFloat_Vector); pragma Import (C, glColor3fv, "glColor3fv"); -- To be used with pname receiving one of: -- GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_POSITION procedure glLightfv (light : GLenum; pname : GLenum; params : Three_GLFloat_Vector); -- To be used with pname receiving GL_SPOT_DIRECTION: procedure glLightfv (light : GLenum; pname : GLenum; params : Four_GLFloat_Vector); -- To be used with pname receiving: -- GL_SPOT_EXPONENT, GL_SPOT_CUTOFF, GL_CONSTANT_ATTENUATION, -- GL_LINEAR_ATTENUATION, GL_QUADRATIC_ATTENUATION procedure glLightfv (light : GLenum; pname : GLenum; params : in out GLFloat); -- pseudo in pragma Import (C, glLightfv, "glLightfv"); -- To be used with pname receiving one of: -- GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_POSITION procedure glLightiv (light : GLenum; pname : GLenum; params : Three_GLint_Vector); -- To be used with pname receiving GL_SPOT_DIRECTION: procedure glLightiv (light : GLenum; pname : GLenum; params : Four_GLint_Vector); -- To be used with pname receiving: -- GL_SPOT_EXPONENT, GL_SPOT_CUTOFF, GL_CONSTANT_ATTENUATION, -- GL_LINEAR_ATTENUATION, GL_QUADRATIC_ATTENUATION procedure glLightiv (light : GLenum; pname : GLenum; params : in out GLint); -- pseudo in pragma Import (C, glLightiv, "glLightiv"); -- To be used with pname receiving: -- GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_EMISSION -- GL_AMBIENT_AND_DIFFUSE procedure glMaterialfv (face : GLenum; pname : GLenum; params : Four_GLfloat_Vector); -- To be used with pname receiving: -- GL_COLOR_INDEXES procedure glMaterialfv (face : GLenum; pname : GLenum; params : Three_GLfloat_Vector); -- To be used with pname receiving: -- GL_SHININESS procedure glMaterialfv (face : GLenum; pname : GLenum; params : in out GLfloat); -- pseudo in pragma Import (C, glMaterialfv, "glMaterialfv"); -- To be used with pname receiving: -- GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_EMISSION -- GL_AMBIENT_AND_DIFFUSE procedure glMaterialiv (face : GLenum; pname : GLenum; params : Four_GLint_Vector); -- To be used with pname receiving: -- GL_COLOR_INDEXES procedure glMaterialiv (face : GLenum; pname : GLenum; params : Three_GLint_Vector); -- To be used with pname receiving: -- GL_SHININESS procedure glMaterialiv (face : GLenum; pname : GLenum; params : in out GLint); -- pseudo in pragma Import (C, glMaterialiv, "glMaterialiv"); type GLubyte_Array is array (Integer range <>) of GLubyte; -- type_Id = GL_UNSIGNED_BYTE procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLubyte_Array); type GLbyte_Array is array (Integer range <>) of GLbyte; -- type_Id = GL_BYTE procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLbyte_Array); type GLushort_Array is array (Integer range <>) of GLushort; -- type_Id = GL_UNSIGNED_SHORT procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLushort_Array); type GLshort_Array is array (Integer range <>) of GLshort; -- type_Id = GL_SHORT procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLshort_Array); type GLuint_Array is array (Integer range <>) of GLuint; -- type_Id = GL_UNSIGNED_INT procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLuint_Array); type GLint_Array is array (Integer range <>) of GLint; -- type_Id = GL_INT; procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLint_Array); type GLfloat_Array is array (Integer range <>) of GLfloat; -- type_Id = GL_FLOAT procedure glTexImage1D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLfloat_Array); pragma Import (C, glTexImage1D, "glTexImage1D"); -- type_Id = GL_UNSIGNED_BYTE procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLubyte_Array); -- type_Id = GL_BYTE procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLbyte_Array); -- type_Id = GL_UNSIGNED_SHORT procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLushort_Array); -- type_Id = GL_SHORT procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLshort_Array); -- type_Id = GL_UNSIGNED_INT procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLuint_Array); -- type_Id = GL_INT procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLint_Array); -- type_Id = GL_FLOAT procedure glTexImage2D (target : GLenum; level : GLint; internalFormat : GLint; width : GLsizei; height : GLsizei; border : GLint; format : GLenum; type_Id : GLenum; pixels : GLfloat_Array); pragma Import (C, glTexImage2D, "glTexImage2D"); -- type_Id = GL_UNSIGNED_BYTE procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLubyte_Array); -- type_Id = GL_BYTE procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLbyte_Array); -- type_Id = GL_UNSIGNED_SHORT procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLushort_Array); -- type_Id = GL_SHORT procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLshort_Array); -- type_Id = GL_UNSIGNED_INT procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLuint_Array); -- type_Id = GL_INT procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLint_Array); -- type_Id = GL_FLOAT procedure glDrawPixels (width : GLsizei; height : GLsizei; format : GLenum; type_Id : GLenum; pixels : GLfloat_Array); pragma Import (C, glDrawPixels, "glDrawPixels"); end AdaGL;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; use Ada.Text_IO; with Ada.Command_Line; use Ada.Command_Line; with Gnat.Command_Line; use Gnat.Command_Line; with Ada.Environment_Variables; with Ada.Directories; use Ada.Directories; with GNAT.OS_Lib; use GNAT.OS_Lib; with Ada.Containers; use Ada.Containers; with Ada.Containers.Indefinite_Ordered_Maps; with Ada; use Ada; with Ada.Command_Line.Environment; procedure Xclock is -- Ada_Launch is the default name, but is meant to be renamed -- to the executable or app name that this executable launches package Env renames Ada.Environment_Variables; package CL renames Ada.Command_Line; package CLenv renames Ada.Command_Line.Environment; package Files renames Ada.Directories; -- Env, CL, and CLenv are just abbreviations for: -- Environment_Variables, Command_Line, and Command_Line.Environment -- xterm -bg black -fg white +sb +sm -fn 10x20 -sl 4000 -cr yellow Launch_Name : String := Locate_Exec_On_Path ("/usr/bin/xclock").all; package Associative_Array is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => String); Xrms : Associative_Array.Map; -- Xterm_ScrollBar : Boolean := False, -- Xterm_SessionManagementCallbacks : Boolean := False; -- Xterm_LoginShell : Boolean := False; -- Xterm_Font : String := "fixed"; -- Xterm_LinesHistory : String := "4000"; -- Xterm_CursorColor : String := "yellow"; Launch_Num_Of_Arguments : Integer := 13; Env_Display : String := Env.Value ("DISPLAY", ":0"); --Launch_Name : String := "/bin/" & Simple_Name (Command_Name); -- The file name to execute/launch Launch_Arguments : GNAT.OS_Lib.Argument_List (1 .. Argument_Count + Launch_Num_Of_Arguments); -- The arguments to give the executable Launch_Status : Boolean; -- The return status of the command + arguments begin Xrms ("Background") := "darkgreen"; Env.Clear; Env.Set ("DISPLAY", Env_Display); Launch_Arguments (1) := new String'("-bg"); Launch_Arguments (2) := new String'(Xterm_Background); Launch_Arguments (3) := new String'("-fg"); Launch_Arguments (4) := new String'(Xterm_Foreground); if Xterm_ScrollBar then Launch_Arguments (5) := new String'("-sb"); else Launch_Arguments (5) := new String'("+sb"); end if; if Xterm_SessionManagementCallbacks then Launch_Arguments (6) := new String'("-sm"); else Launch_Arguments (6) := new String'("+sm"); end if; if Xterm_LoginShell then Launch_Arguments (7) := new String'("-ls"); else Launch_Arguments (7) := new String'("+ls"); end if; Launch_Arguments (8) := new String'("-fn"); Launch_Arguments (9) := new String'(Xterm_Font); Launch_Arguments (10) := new String'("-sl"); Launch_Arguments (11) := new String'(Xterm_LinesHistory); Launch_Arguments (12) := new String'("-cr"); Launch_Arguments (13) := new String'(Xterm_CursorColor); for N in 1 .. Argument_Count loop Launch_Arguments (N + Launch_Num_Of_Arguments) := new String'(Argument (N)); end loop; -- Simply copy/convey all arguments to the new command launch. --Put_Line (Launch_Name); -- DEBUG ACTION - remove this statement when the performance is sufficient. if Files.Exists (Launch_Name) then Spawn (Launch_Name, ( new String'("-digital"), new String'("-xrm"), new String'("*fontColor: lightgreen"), new String'("-xrm"), new String'("*foreground: lightgreen"), new String'("-xrm"), new String'("*XClock.twentyfour: True") ) & Launch_Arguments, Launch_Status); -- Launch the new process with conveyed arguments and capture general -- return status as Success or Failure. A number may be used in the future. else Launch_Status := False; end if; if not Launch_Status then Set_Exit_Status (Failure); else Set_Exit_Status (Success); end if; --Give return status back to calling os/environment. end Xclock;
{ "source": "starcoderdata", "programming_language": "ada" }
----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Applications.Main; with ASF.Components.Root; with ASF.Responses; with Util.Log.Loggers; -- The <b>ASF.Lifecycles.Response</b> package defines the behavior -- of the response phase. package body ASF.Lifecycles.Response is use Ada.Exceptions; use Util.Log; use ASF.Applications; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Lifecycles.Response"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Response_Controller; App : access ASF.Applications.Main.Application'Class) is begin Controller.View_Handler := App.Get_View_Handler; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Response_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : constant Components.Root.UIViewRoot := Context.Get_View_Root; begin if Components.Root.Get_Root (View) = null then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; else Controller.View_Handler.Render_View (Context, View); end if; exception when E : others => Log.Error ("Error when displaying view {0}: {1}: {2}", "?", Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Response;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- with Program.Element_Vectors; with Program.Elements.Declarations; with Program.Elements.Defining_Identifiers; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Discriminant_Specifications is pragma Pure (Program.Elements.Discriminant_Specifications); type Discriminant_Specification is limited interface and Program.Elements.Declarations.Declaration; type Discriminant_Specification_Access is access all Discriminant_Specification'Class with Storage_Size => 0; not overriding function Names (Self : Discriminant_Specification) return not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access is abstract; not overriding function Object_Subtype (Self : Discriminant_Specification) return not null Program.Elements.Element_Access is abstract; not overriding function Default_Expression (Self : Discriminant_Specification) return Program.Elements.Expressions.Expression_Access is abstract; not overriding function Has_Not_Null (Self : Discriminant_Specification) return Boolean is abstract; type Discriminant_Specification_Text is limited interface; type Discriminant_Specification_Text_Access is access all Discriminant_Specification_Text'Class with Storage_Size => 0; not overriding function To_Discriminant_Specification_Text (Self : aliased in out Discriminant_Specification) return Discriminant_Specification_Text_Access is abstract; not overriding function Colon_Token (Self : Discriminant_Specification_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Not_Token (Self : Discriminant_Specification_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Null_Token (Self : Discriminant_Specification_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Assignment_Token (Self : Discriminant_Specification_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Semicolon_Token (Self : Discriminant_Specification_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; type Discriminant_Specification_Vector is limited interface and Program.Element_Vectors.Element_Vector; type Discriminant_Specification_Vector_Access is access all Discriminant_Specification_Vector'Class with Storage_Size => 0; overriding function Element (Self : Discriminant_Specification_Vector; Index : Positive) return not null Program.Elements.Element_Access is abstract with Post'Class => Element'Result.Is_Discriminant_Specification; function To_Discriminant_Specification (Self : Discriminant_Specification_Vector'Class; Index : Positive) return not null Discriminant_Specification_Access is (Self.Element (Index).To_Discriminant_Specification); end Program.Elements.Discriminant_Specifications;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with Ada.Numerics.Float_Random; procedure Rock_Paper_Scissors is package Rand renames Ada.Numerics.Float_Random; Gen: Rand.Generator; type Choice is (Rock, Paper, Scissors); Cnt: array (Choice) of Natural := (1, 1, 1); -- for the initialization: pretend that each of Rock, Paper, -- and Scissors, has been played once by the human -- else the first computer choice would be deterministic function Computer_Choice return Choice is Random_Number: Natural := Integer(Rand.Random(Gen) * (Float(Cnt(Rock)) + Float(Cnt(Paper)) + Float(Cnt(Scissors)))); begin if Random_Number < Cnt(Rock) then -- guess the human will choose Rock return Paper; elsif Random_Number - Cnt(Rock) < Cnt(Paper) then -- guess the human will choose Paper return Scissors; else -- guess the human will choose Scissors return Rock; end if; end Computer_Choice; Finish_The_Game: exception; function Human_Choice return Choice is Done: Boolean := False; T: constant String := "enter ""r"" for Rock, ""p"" for Paper, or ""s"" for Scissors""!"; U: constant String := "or enter ""q"" to Quit the game"; Result: Choice; begin Ada.Text_IO.Put_Line(T); Ada.Text_IO.Put_Line(U); while not Done loop Done := True; declare S: String := Ada.Text_IO.Get_Line; begin if S="r" or S="R" then Result := Rock; elsif S="p" or S = "P" then Result := Paper; elsif S="s" or S="S" then Result := Scissors; elsif S="q" or S="Q" then raise Finish_The_Game; else Done := False; end if; end; end loop; return Result; end Human_Choice; type Result is (Human_Wins, Draw, Computer_Wins); function "<" (X, Y: Choice) return Boolean is -- X < Y if X looses against Y begin case X is when Rock => return (Y = Paper); when Paper => return (Y = Scissors); when Scissors => return (Y = Rock); end case; end "<"; Score: array(Result) of Natural := (0, 0, 0); C,H: Choice; Res: Result; begin -- play the game loop C := Computer_Choice; -- the computer makes its choice first H := Human_Choice; -- now ask the player for his/her choice Cnt(H) := Cnt(H) + 1; -- update the counts for the AI if C < H then Res := Human_Wins; elsif H < C then Res := Computer_Wins; else Res := Draw; end if; Ada.Text_IO.Put_Line("COMPUTER'S CHOICE: " & Choice'Image(C) & " RESULT: " & Result'Image(Res)); Ada.Text_IO.New_Line; Score(Res) := Score(Res) + 1; end loop; exception when Finish_The_Game => Ada.Text_IO.New_Line; for R in Score'Range loop Ada.Text_IO.Put_Line(Result'Image(R) & Natural'Image(Score(R))); end loop; end Rock_Paper_Scissors;
{ "source": "starcoderdata", "programming_language": "ada" }
--____________________________________________________________________-- -- -- The package provides stream interface to string. A string can be -- read and written using stream I/O attributes. -- with Ada.Streams; use Ada.Streams; with System.Storage_Elements; package Strings_Edit.Streams is -- -- String_Stream -- A string stream, when read, Data (Position..Length) -- is amount of data available to read/write. Note that -- before reading from the stream is must be initialized using Set. -- Otherwise the result of reading will be the unitialized contents of -- the Data field. -- type String_Stream (Length : Natural) is new Root_Stream_Type with record Position : Positive := 1; Data : String (1..Length); end record; -- -- Get -- Written contents of the stream -- -- Stream - The stream object -- -- Get is an operation inverse to T'Write. -- -- Returns : -- -- String written -- function Get (Stream : String_Stream) return String; -- -- Get_Size -- Number of stream elements available to write or to read -- -- Stream - The stream object -- function Get_Size (Stream : String_Stream) return Stream_Element_Count; -- -- Read -- Overrides Ada.Streams... -- procedure Read ( Stream : in out String_Stream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset ); -- -- Rewind -- The stream -- -- Stream - The stream object -- -- This procedure moves Stream.Position to the beginning. This undoes -- all reading/writing actions. -- procedure Rewind (Stream : in out String_Stream); -- -- Set -- Contents -- -- Stream - The stream object -- Content - String to read -- -- The stream is changed to contain Content. The next read operation -- will yield the first character of Content. Set is an operation -- inverse to T'Read. -- -- Exceptions : -- -- Contraint_Error - no room in Stream -- procedure Set (Stream : in out String_Stream; Content : String); -- -- Write -- Overrides Ada.Streams... -- -- Exceptions : -- -- End_Error - No room in the string -- procedure Write ( Stream : in out String_Stream; Item : Stream_Element_Array ); private use System.Storage_Elements; pragma Inline (Get_Size); -- -- Char_Count -- Number of characters per string elements -- Char_Count : constant := Stream_Element'Size / Character'Size; -- -- Stream_Element'Size must be a multiple of Character'Size and the -- later be a multiple of Storage_Element'Size. -- subtype Confirmed is Boolean range True..True; Assert : constant Confirmed := ( Char_Count * Character'Size = Stream_Element'Size and then Character'Size mod Storage_Element'Size = 0 ); end Strings_Edit.Streams;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- with Program.Elements.Definitions; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Real_Range_Specifications is pragma Pure (Program.Elements.Real_Range_Specifications); type Real_Range_Specification is limited interface and Program.Elements.Definitions.Definition; type Real_Range_Specification_Access is access all Real_Range_Specification'Class with Storage_Size => 0; not overriding function Lower_Bound (Self : Real_Range_Specification) return not null Program.Elements.Expressions.Expression_Access is abstract; not overriding function Upper_Bound (Self : Real_Range_Specification) return not null Program.Elements.Expressions.Expression_Access is abstract; type Real_Range_Specification_Text is limited interface; type Real_Range_Specification_Text_Access is access all Real_Range_Specification_Text'Class with Storage_Size => 0; not overriding function To_Real_Range_Specification_Text (Self : aliased in out Real_Range_Specification) return Real_Range_Specification_Text_Access is abstract; not overriding function Range_Token (Self : Real_Range_Specification_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Double_Dot_Token (Self : Real_Range_Specification_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Real_Range_Specifications;
{ "source": "starcoderdata", "programming_language": "ada" }
--* -- OBJECTIVE: -- CHECK THAT AN ADDRESS CLAUSE CAN BE GIVEN IN THE PRIVATE PART -- OF A GENERIC PACKAGE SPECIFICATION FOR A VARIABLE OF A FORMAL -- ARRAY TYPE, WHERE THE VARIABLE IS DECLARED IN THE VISIBLE PART -- OF THE SPECIFICATION. -- HISTORY: -- BCB 10/08/87 CREATED ORIGINAL TEST. -- PWB 05/11/89 CHANGED EXTENSION FROM '.DEP' TO '.ADA'. WITH SYSTEM; USE SYSTEM; WITH SPPRT13; USE SPPRT13; WITH REPORT; USE REPORT; WITH TEXT_IO; USE TEXT_IO; PROCEDURE CD5014X IS BEGIN TEST ("CD5014X", " AN ADDRESS CLAUSE CAN BE GIVEN " & "IN THE PRIVATE PART OF A GENERIC PACKAGE " & "SPECIFICATION FOR A VARIABLE OF A FORMAL " & "ARRAY TYPE, WHERE THE VARIABLE IS DECLARED " & "IN THE VISIBLE PART OF THE SPECIFICATION"); DECLARE TYPE COLOR IS (RED,BLUE,GREEN); TYPE COLOR_TABLE IS ARRAY (COLOR) OF INTEGER; GENERIC TYPE INDEX IS (<>); TYPE FORM_ARRAY_TYPE IS ARRAY (INDEX) OF INTEGER; PACKAGE PKG IS FORM_ARRAY_OBJ1 : FORM_ARRAY_TYPE := (1,2,3); PRIVATE FOR FORM_ARRAY_OBJ1 USE AT VARIABLE_ADDRESS; END PKG; PACKAGE BODY PKG IS BEGIN IF EQUAL(3,3) THEN FORM_ARRAY_OBJ1 := (10,20,30); END IF; IF FORM_ARRAY_OBJ1 /= (10,20,30) THEN FAILED ("INCORRECT VALUE FOR FORMAL ARRAY VARIABLE"); END IF; IF FORM_ARRAY_OBJ1'ADDRESS /= VARIABLE_ADDRESS THEN FAILED ("INCORRECT ADDRESS FOR FORMAL ARRAY " & "VARIABLE"); END IF; END PKG; PACKAGE PACK IS NEW PKG(INDEX => COLOR, FORM_ARRAY_TYPE => COLOR_TABLE); BEGIN NULL; END; RESULT; END CD5014X;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; use Ada.Text_IO; procedure Euler10 Is function Sum_Prime_Under(N: Integer) return Long_Long_Integer is Is_Prime : array (2 .. N - 1) of Boolean := (others => True); Sum : Long_Long_Integer := 0; begin for I in Is_Prime'Range loop if Is_Prime(I) then Sum := Sum + Long_Long_Integer(I); declare J : Integer := I * 2; begin while J <= Is_Prime'Last loop Is_Prime(J) := False; J := J + I; end loop; end; end if; end loop; return Sum; end; begin Put_Line(Long_Long_Integer'Image(Sum_Prime_Under(2_000_000))); end;
{ "source": "starcoderdata", "programming_language": "ada" }
-- with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Calendar; with Rails; use Rails; package Trains is package Calendar renames Ada.Calendar; type Train (Route_Length: Integer) is record Id : Integer; Name : SU.Unbounded_String; Speed : Integer; Capacity : Integer; Route : Route_Array(1 .. Route_Length); Index : Integer; Att : Track_Ptr; end record; type Train_Ptr is access Train; procedure Connection(Self: Train_Ptr; From, To : out Track_Ptr); function Move_To(Self: Train_Ptr; T : Track_Ptr) return Float; function As_String(Self: Train_Ptr) return String; function As_Verbose_String(Self: Train_Ptr) return String; type Trains_Array is array(Integer range<>) of Train_Ptr; type Trains_Ptr is access Trains_Array; function New_Train ( Id : Integer; Name : SU.Unbounded_String; Speed : Integer; Capacity : Integer; Route : Route_Array) return Train_Ptr; task type Simulation is entry Init(S : Calendar.Time; SPH : Integer; H : Integer; M : Integer; V : Boolean); entry Simulate(T : in Train_Ptr; C : in Connections_Ptr); end Simulation; type Simulation_Ptr is access Simulation; type Time_Component_Type is delta 1.0 digits 2 range 0.0 .. 60.0; end Trains;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with Ada.Command_Line; procedure Main is generator: Natural; prime : Natural; alicePrivateKey : Natural; bobPrivateKey : Natural; --------------------- -- DecimalToBinary -- --------------------- function DecimalToBinary (N : Natural) return String is ret : Ada.Strings.Unbounded.Unbounded_String; begin if N < 2 then return "1"; else Ada.Strings.Unbounded.Append(ret, Ada.Strings.Unbounded.To_Unbounded_String(decimalToBinary (N / 2))); Ada.Strings.Unbounded.Append(ret, Ada.Strings.Fixed.Trim(Integer'Image(N mod 2), Ada.Strings.Left)); end if; return Ada.Strings.Unbounded.To_String(ret); end decimalToBinary; ------------------------------- -- FastModularExponentiation -- ------------------------------- function FastModularExponentiation (b, exp, m : Natural) return Integer is x : Integer := 1; power : Integer; str : String := DecimalToBinary (exp); begin power := b mod m; for i in 0 .. (str'Length - 1) loop if str(str'Last - i) = '1' then x := (x * power) mod m; end if; power := (power*power) mod m; end loop; return x; end FastModularExponentiation; ----------- -- Power -- ----------- function Power (privateKey, g, n : Integer) return Integer is begin if privateKey = 1 then return 1; end if; return FastModularExponentiation (g, privateKey, n); end Power; ------------------- -- IsPrimeNumber -- ------------------- function IsPrimeNumber (N : Natural) return Boolean is isPrime : Boolean := true; begin if N = 0 or N = 1 then return false; end if; for i in 1 .. N / 2 loop if (N mod (i + 1)) = 0 then isPrime := false; exit; end if; end loop; return isPrime; end IsPrimeNumber; begin Ada.Integer_Text_IO.Default_Width := 0; if Ada.Command_Line.Argument_Count < 1 then Ada.Text_IO.Put_Line("You forgot to pass in all the arguments! Try --help."); return; end if; if Ada.Command_Line.Argument(1) = "--help" then Ada.Text_IO.Put_Line("Argument order: Alice, Bob, Generator, Prime"); return; end if; if Ada.Command_Line.Argument_Count < 4 then Ada.Text_IO.Put_Line("You forgot to pass in all the arguments! Try --help."); return; end if; alicePrivateKey := Integer'Value(Ada.Command_Line.Argument(1)); bobPrivateKey := Integer'Value(Ada.Command_Line.Argument(2)); generator := Integer'Value(Ada.Command_Line.Argument(3)); prime := Integer'Value(Ada.Command_Line.Argument(4)); if not IsPrimeNumber (prime) then Ada.Integer_Text_IO.Put (prime); Ada.Text_IO.Put_Line(" is not a prime number."); return; end if; Ada.Text_IO.Put ("Generator: "); Ada.Integer_Text_IO.Put (generator); Ada.Text_IO.New_Line; Ada.Text_IO.Put ("Prime Number: "); Ada.Integer_Text_IO.Put (prime); Ada.Text_IO.New_Line; Ada.Text_IO.Put ("Alice's Private Key: "); Ada.Integer_Text_IO.Put (alicePrivateKey); Ada.Text_IO.New_Line; Ada.Text_IO.Put ("Bob's Private Key: "); Ada.Integer_Text_IO.Put (bobPrivateKey); Ada.Text_IO.New_Line; Ada.Text_IO.Put ("Alice sends the message "); Ada.Integer_Text_IO.Put (Power(alicePrivateKey, generator, prime)); Ada.Text_IO.Put_Line (" to Bob."); Ada.Text_IO.Put ("Bob sends the message "); Ada.Integer_Text_IO.Put (Power(bobPrivateKey, generator, prime)); Ada.Text_IO.Put_Line (" to Alice."); Ada.Text_IO.Put ("Alice gets the secret key "); Ada.Integer_Text_IO.Put (Power(alicePrivateKey, Power(bobPrivateKey, generator, prime), prime)); Ada.Text_IO.New_Line; Ada.Text_IO.Put ("Bob gets the secret key "); Ada.Integer_Text_IO.Put (Power(bobPrivateKey, Power(alicePrivateKey, generator, prime), prime)); Ada.Text_IO.New_Line; null; end Main;
{ "source": "starcoderdata", "programming_language": "ada" }
-- -- * Type definitions; takes common type definitions that must be used -- * in multiple header files due to [XSI], removes them from the system -- * space, and puts them in the implementation space. -- -- total blocks subtype uu_darwin_blkcnt_t is i386_utypes_h.uu_int64_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:55 -- preferred block size subtype uu_darwin_blksize_t is i386_utypes_h.uu_int32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:56 -- dev_t subtype uu_darwin_dev_t is i386_utypes_h.uu_int32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:57 -- Used by statvfs and fstatvfs subtype uu_darwin_fsblkcnt_t is unsigned; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:58 -- Used by statvfs and fstatvfs subtype uu_darwin_fsfilcnt_t is unsigned; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:59 -- [???] process and group IDs subtype uu_darwin_gid_t is i386_utypes_h.uu_uint32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:60 -- [XSI] pid_t, uid_t, or gid_t subtype uu_darwin_id_t is i386_utypes_h.uu_uint32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:61 -- [???] Used for 64 bit inodes subtype uu_darwin_ino64_t is i386_utypes_h.uu_uint64_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:62 -- [???] Used for inodes subtype uu_darwin_ino_t is uu_darwin_ino64_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:64 -- [???] Used for inodes -- Used by mach subtype uu_darwin_mach_port_name_t is i386_utypes_h.uu_darwin_natural_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:68 -- Used by mach subtype uu_darwin_mach_port_t is uu_darwin_mach_port_name_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:69 -- [???] Some file attributes subtype uu_darwin_mode_t is i386_utypes_h.uu_uint16_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:70 -- [???] Used for file sizes subtype uu_darwin_off_t is i386_utypes_h.uu_int64_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:71 -- [???] process and group IDs subtype uu_darwin_pid_t is i386_utypes_h.uu_int32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:72 -- [???] signal set subtype uu_darwin_sigset_t is i386_utypes_h.uu_uint32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:73 -- [???] microseconds subtype uu_darwin_suseconds_t is i386_utypes_h.uu_int32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:74 -- [???] user IDs subtype uu_darwin_uid_t is i386_utypes_h.uu_uint32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:75 -- [???] microseconds subtype uu_darwin_useconds_t is i386_utypes_h.uu_uint32_t; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:76 type uu_darwin_uuid_t is array (0 .. 15) of aliased unsigned_char; -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:77 subtype uu_darwin_uuid_string_t is Interfaces.C.char_array (0 .. 36); -- /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys/_types.h:78 end sys_utypes_h;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Task_Identification; -- use Ada.Task_Identification; generic type Attribute is private; Initial_Value : Attribute; package Ada.Task_Attributes is type Attribute_Handle is access all Attribute; function Value ( T : Task_Identification.Task_Id := Task_Identification.Current_Task) return Attribute; function Reference ( T : Task_Identification.Task_Id := Task_Identification.Current_Task) return not null Attribute_Handle; procedure Set_Value ( Val : Attribute; T : Task_Identification.Task_Id := Task_Identification.Current_Task); procedure Reinitialize ( T : Task_Identification.Task_Id := Task_Identification.Current_Task); end Ada.Task_Attributes;
{ "source": "starcoderdata", "programming_language": "ada" }
-- { dg-do compile } -- { dg-options "-g" } with Debug2_Pkg; use Debug2_Pkg; package body Debug2 is procedure Proc is function F return String_List_Ptr is begin return new String_List'(Singleton); end; A : String_List_Ptr := F; begin null; end; function Get return Integer is begin return 0; end; Failed : exception; A: String_Ptr; begin declare Server_Args : Integer; begin Server_Args := Get; exception when X : Failed => A := To_Heap; end; end Debug2;
{ "source": "starcoderdata", "programming_language": "ada" }
procedure A043 is use Ada.Long_Integer_Text_IO; Main_Num : String (1 .. 10) := "0123456789"; Temp_Char : String (1 .. 1); Pandigital_Num_List : array (Integer range 1 .. 100) of Long_Integer := (others => 0); Sum : Long_Integer := 0; Count_Val : Integer := 1; Duplicate_Found : Boolean; begin for I in 1 .. 10 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Main_Num (5 .. 5); Main_Num (5 .. 5) := Main_Num (4 .. 4); Main_Num (4 .. 4) := Main_Num (3 .. 3); Main_Num (3 .. 3) := Main_Num (2 .. 2); Main_Num (2 .. 2) := Main_Num (1 .. 1); Main_Num (1 .. 1) := Temp_Char; for J in 1 .. 9 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Main_Num (5 .. 5); Main_Num (5 .. 5) := Main_Num (4 .. 4); Main_Num (4 .. 4) := Main_Num (3 .. 3); Main_Num (3 .. 3) := Main_Num (2 .. 2); Main_Num (2 .. 2) := Temp_Char; for K in 1 .. 8 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Main_Num (5 .. 5); Main_Num (5 .. 5) := Main_Num (4 .. 4); Main_Num (4 .. 4) := Main_Num (3 .. 3); Main_Num (3 .. 3) := Temp_Char; for L in 1 .. 7 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Main_Num (5 .. 5); Main_Num (5 .. 5) := Main_Num (4 .. 4); Main_Num (4 .. 4) := Temp_Char; for M in 1 .. 6 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Main_Num (5 .. 5); Main_Num (5 .. 5) := Temp_Char; for N in 1 .. 5 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Main_Num (6 .. 6); Main_Num (6 .. 6) := Temp_Char; for O in 1 .. 4 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Main_Num (7 .. 7); Main_Num (7 .. 7) := Temp_Char; for P in 1 .. 3 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Main_Num (8 .. 8); Main_Num (8 .. 8) := Temp_Char; for Q in 1 .. 2 loop Temp_Char := Main_Num (10 .. 10); Main_Num (10 .. 10) := Main_Num (9 .. 9); Main_Num (9 .. 9) := Temp_Char; if Main_Num (6 .. 6) /= "5" and Main_Num (6 .. 6) /= "0" then goto Continue; end if; if Integer'Value (Main_Num (4 .. 4)) mod 2 /= 0 then goto Continue; end if; if (Integer'Value (Main_Num (3 .. 3)) + Integer'Value (Main_Num (4 .. 4)) + Integer'Value (Main_Num (5 .. 5))) mod 3 /= 0 then goto Continue; end if; if Integer'Value (Main_Num (5 .. 7)) mod 7 /= 0 then goto Continue; end if; if Integer'Value (Main_Num (6 .. 8)) mod 11 /= 0 then goto Continue; end if; if Integer'Value (Main_Num (7 .. 9)) mod 13 /= 0 then goto Continue; end if; if Integer'Value (Main_Num (8 .. 10)) mod 17 /= 0 then goto Continue; end if; Duplicate_Found := False; for R in 1 .. Count_Val loop if Pandigital_Num_List (R) = Long_Integer'Value (Main_Num) then Duplicate_Found := True; exit; end if; end loop; if not Duplicate_Found then Pandigital_Num_List (Count_Val) := Long_Integer'Value (Main_Num); Sum := Sum + Long_Integer'Value (Main_Num); Count_Val := Count_Val + 1; end if; <<Continue>> end loop; end loop; end loop; end loop; end loop; end loop; end loop; end loop; end loop; Put (Sum, Width => 0); end A043;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Exception_Identification.From_Here; with Ada.Exceptions.Finally; with Ada.Unchecked_Conversion; with System.Address_To_Named_Access_Conversions; with System.Storage_Map; with System.System_Allocators; with System.Zero_Terminated_WStrings; with C.string; with C.winternl; package body System.Native_IO.Names is use Ada.Exception_Identification.From_Here; use type Storage_Elements.Storage_Offset; use type C.char_array; use type C.size_t; use type C.winternl.NTSTATUS; use type C.winnt.LPWSTR; -- Name_Pointer use type C.winnt.WCHAR; -- Name_Character use type C.winnt.WCHAR_array; -- Name_String package Name_Pointer_Conv is new Address_To_Named_Access_Conversions ( Name_Character, Name_Pointer); package POBJECT_NAME_INFORMATION_Conv is new Address_To_Named_Access_Conversions ( C.winternl.struct_OBJECT_NAME_INFORMATION, C.winternl.POBJECT_NAME_INFORMATION); function "+" (Left : Name_Pointer; Right : C.ptrdiff_t) return Name_Pointer with Convention => Intrinsic; pragma Inline_Always ("+"); function "+" (Left : Name_Pointer; Right : C.ptrdiff_t) return Name_Pointer is begin return Name_Pointer_Conv.To_Pointer ( Name_Pointer_Conv.To_Address (Left) + Storage_Elements.Storage_Offset (Right) * (Name_Character'Size / Standard'Storage_Unit)); end "+"; type NtQueryObject_Type is access function ( Handle : C.winnt.HANDLE; ObjectInformationClass : C.winternl.OBJECT_INFORMATION_CLASS; ObjectInformation : C.winnt.PVOID; ObjectInformationLength : C.windef.ULONG; ReturnLength : access C.windef.ULONG) return C.winternl.NTSTATUS with Convention => WINAPI; NtQueryObject_Name : constant C.char_array (0 .. 13) := "NtQueryObject" & C.char'Val (0); function To_NtQueryObject_Type is new Ada.Unchecked_Conversion (C.windef.FARPROC, NtQueryObject_Type); -- implementation procedure Open_Ordinary ( Method : Open_Method; Handle : aliased out Handle_Type; Mode : File_Mode; Name : String; Out_Name : aliased out Name_Pointer; Form : Packed_Form) is C_Name : aliased Name_String ( 0 .. Name'Length * Zero_Terminated_WStrings.Expanding); begin Zero_Terminated_WStrings.To_C (Name, C_Name (0)'Access); Open_Ordinary (Method, Handle, Mode, C_Name (0)'Unchecked_Access, Form); Out_Name := null; end Open_Ordinary; procedure Get_Full_Name ( Handle : Handle_Type; Has_Full_Name : in out Boolean; Name : in out Name_Pointer; Is_Standard : Boolean; Raise_On_Error : Boolean) is procedure Finally (X : in out C.winnt.PVOID); procedure Finally (X : in out C.winnt.PVOID) is begin System_Allocators.Free (Address (X)); end Finally; package Holder is new Ada.Exceptions.Finally.Scoped_Holder (C.winnt.PVOID, Finally); NtQueryObject : constant NtQueryObject_Type := To_NtQueryObject_Type ( C.winbase.GetProcAddress ( Storage_Map.NTDLL, NtQueryObject_Name (0)'Access)); Info : aliased C.winnt.PVOID := C.void_ptr (Null_Address); ReturnLength : aliased C.windef.ULONG; Unicode_Name : C.winternl.PUNICODE_STRING; New_Name : Name_Pointer; Drives : aliased Name_String (0 .. 3 * 26); -- (A to Z) * "X:\" Drive : Name_String (0 .. 2); -- "X:" New_Name_Length : C.size_t; Relative_Index : C.size_t; Skip_Length : C.size_t; begin if NtQueryObject = null then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then raise Program_Error; -- ?? end if; return; -- error end if; -- Get ObjectNameInformation. Holder.Assign (Info); Info := C.winnt.PVOID (System_Allocators.Allocate (4096)); if Address (Info) = Null_Address then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then raise Storage_Error; end if; return; -- error end if; if NtQueryObject ( Handle, C.winternl.ObjectNameInformation, Info, 4096, ReturnLength'Access) /= 0 -- STATUS_SUCCESS then declare New_Info : constant C.winnt.PVOID := C.winnt.PVOID ( System_Allocators.Reallocate ( Address (Info), Storage_Elements.Storage_Offset (ReturnLength))); begin if Address (New_Info) = Null_Address then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then raise Storage_Error; end if; return; -- error end if; Info := New_Info; end; if NtQueryObject ( Handle, C.winternl.ObjectNameInformation, Info, ReturnLength, null) /= 0 -- STATUS_SUCCESS then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then Raise_Exception (Use_Error'Identity); end if; return; -- error end if; end if; Unicode_Name := POBJECT_NAME_INFORMATION_Conv.To_Pointer (Address (Info)).Name'Access; -- To DOS name. if C.winbase.GetLogicalDriveStrings (Drives'Length, Drives (0)'Access) >= Drives'Length then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then Raise_Exception (Use_Error'Identity); end if; return; -- error end if; Drive (1) := Name_Character'Val (Character'Pos (':')); Drive (2) := Name_Character'Val (0); Skip_Length := 0; Relative_Index := 0; New_Name_Length := C.size_t (Unicode_Name.Length); declare Unicode_Name_All : Name_String ( 0 .. C.size_t (Unicode_Name.Length) - 1); for Unicode_Name_All'Address use Name_Pointer_Conv.To_Address (Unicode_Name.Buffer); P : Name_Pointer := Drives (0)'Unchecked_Access; begin while P.all /= Name_Character'Val (0) loop declare Length : constant C.size_t := C.string.wcslen (P); Long_Name : aliased Name_String (0 .. C.windef.MAX_PATH - 1); begin if Length > 0 then Drive (0) := P.all; -- drop trailing '\' if C.winbase.QueryDosDevice ( Drive (0)'Access, Long_Name (0)'Access, C.windef.MAX_PATH) /= 0 then declare Long_Name_Length : C.size_t := 0; begin while Long_Name (Long_Name_Length) /= Name_Character'Val (0) loop if Long_Name (Long_Name_Length) = Name_Character'Val (Character'Pos (';')) then -- Skip ";X:\" (Is it a bug of VirtualBox?) Long_Name ( Long_Name_Length .. Long_Name'Last - 4) := Long_Name ( Long_Name_Length + 4 .. Long_Name'Last); end if; Long_Name_Length := Long_Name_Length + 1; end loop; if Long_Name (0 .. Long_Name_Length - 1) = Unicode_Name_All (0 .. Long_Name_Length - 1) and then Unicode_Name_All (Long_Name_Length) = Name_Character'Val (Character'Pos ('\')) then Skip_Length := Long_Name_Length; Relative_Index := 2; New_Name_Length := New_Name_Length - Skip_Length + 2; exit; end if; end; end if; end if; P := P + C.ptrdiff_t (Length); end; P := P + 1; -- skip NUL end loop; if Relative_Index = 0 and then Unicode_Name_All (1) /= Name_Character'Val (Character'Pos (':')) and then ( Unicode_Name_All (0) /= Name_Character'Val (Character'Pos ('\')) or else Unicode_Name_All (1) /= Name_Character'Val (Character'Pos ('\'))) then -- For example, a pipe's name is like "pipe:[N]". Drive (0) := Name_Character'Val (Character'Pos ('*')); Relative_Index := 1; New_Name_Length := New_Name_Length + 1; end if; end; -- Copy a name. New_Name := Name_Pointer_Conv.To_Pointer ( System_Allocators.Allocate ( (Storage_Elements.Storage_Offset (New_Name_Length) + 1) * (Name_Character'Size / Standard'Storage_Unit))); if New_Name = null then -- Failed, keep Has_Full_Name and Name. if Raise_On_Error then raise Storage_Error; end if; return; -- error end if; declare Unicode_Name_All : Name_String ( 0 .. C.size_t (Unicode_Name.Length) - 1); for Unicode_Name_All'Address use Name_Pointer_Conv.To_Address (Unicode_Name.Buffer); New_Name_All : Name_String (0 .. New_Name_Length); -- NUL for New_Name_All'Address use Name_Pointer_Conv.To_Address (New_Name); begin if Relative_Index > 0 then New_Name_All (0 .. Relative_Index - 1) := Drive (0 .. Relative_Index - 1); end if; New_Name_All (Relative_Index .. New_Name_Length - 1) := Unicode_Name_All ( Skip_Length .. C.size_t (Unicode_Name.Length) - 1); New_Name_All (New_Name_Length) := Name_Character'Val (0); end; -- Succeeded. if not Is_Standard then Free (Name); -- External or External_No_Close end if; Name := New_Name; Has_Full_Name := True; end Get_Full_Name; end System.Native_IO.Names;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Text_IO; with Ada.Directories; with Init_Project; with Blueprint; use Blueprint; package body Commands.Init is package IO renames Ada.Text_IO; package TT renames CLIC.TTY; ------------- -- Execute -- ------------- overriding procedure Execute ( Cmd : in out Command; Args : AAA.Strings.Vector) is ToDo : Action := Write; begin if Cmd.Dry_Run then IO.Put_Line(TT.Emph("You specified the dry-run flag, so no changes will be written.")); ToDo := DryRun; end if; Init_Project.Init(Ada.Directories.Current_Directory,ToDo); end Execute; -------------------- -- Setup_Switches -- -------------------- overriding procedure Setup_Switches (Cmd : in out Command; Config : in out CLIC.Subcommand.Switches_Configuration) is use CLIC.Subcommand; begin Define_Switch (Config, Cmd.Dry_Run'Access, "", "-dry-run", "Dry-run"); end Setup_Switches; end Commands.Init;
{ "source": "starcoderdata", "programming_language": "ada" }
with System; with TLSF.Config; use TLSF.Config; with TLSF.Block.Types; use TLSF.Block.Types; with TLSF.Block.Proof; package TLSF.Block.Operations_Old with SPARK_Mode is package Proof renames TLSF.Block.Proof; function Get_Block_At_Address(Base : System.Address; Addr : Aligned_Address) return Block_Header with Pre => (Addr /= Address_Null and then Proof.Block_Present_At_Address(Addr)), Post => Get_Block_At_Address'Result = Proof.Block_At_Address(Addr); procedure Set_Block_At_Address(Base : System.Address; Addr : Aligned_Address; Header : Block_Header) with Pre => (Addr /= Address_Null and then not Proof.Block_Present_At_Address(Addr)), Post => (Proof.Block_Present_At_Address(Addr) and then Proof.Block_At_Address(Addr) = Header); procedure Remove_Block_At_Address(Base : System.Address; Addr : Aligned_Address) with Pre => (Addr /= Address_Null and then Proof.Block_Present_At_Address(Addr)), Post => not Proof.Block_Present_At_Address(Addr); -- Work with free lists function Check_Blocks_Linked_Correctly (Block_Left, Block_Right : Block_Header; Block_Left_Address, Block_Right_Address : Aligned_Address) return Boolean is (Is_Block_Free(Block_Left) and then Is_Block_Free(Block_Right) and then Block_Left.Free_List.Next_Address = Block_Right_Address and then Block_Right.Free_List.Prev_Address = Block_Left_Address); function Check_Free_List_Correctness_After_Unlinking (Base : System.Address; Block : Block_Header) return Boolean is -- properly linked in free list block cannot have zero links -- because free list is circular double linked list (Check_Blocks_Linked_Correctly (Block_Left => Get_Block_At_Address(Base, Block.Free_List.Prev_Address), Block_Right => Get_Block_At_Address(Base, Block.Free_List.Next_Address), Block_Left_Address => Block.Free_List.Prev_Address, Block_Right_Address => Block.Free_List.Next_Address)) with Pre => Is_Block_Free(Block) and then Proof.Block_Present_At_Address(Block.Free_List.Prev_Address) and then Proof.Block_Present_At_Address(Block.Free_List.Next_Address); function Is_Block_Physically_Present_At_Address_And_In_Free_List_For_Specific_Size (Base : System.Address; Address : Aligned_Address; Size : Aligned_Size; Block : Block_Header) return Boolean is (Is_Block_Free(Block) and then Proof.Specific_Block_Present_At_Address(Address, Block) and then Is_Block_Linked_To_Free_List(Block) and then Proof.Is_Block_In_Free_List_For_Size (Size, Address)) with Ghost; procedure Unlink_From_Free_List (Base : System.Address; Address : Aligned_Address; Block : in out Block_Header; Free_List : in out Free_Blocks_List) with Pre => -- TODO: think about storing meta info about Free_Lists, -- ie add extra structure for Free_Blocks_List for size Is_Block_Free(Block) and then -- Free List is not empty not Is_Free_List_Empty(Free_List) and then -- presence in free lists Is_Block_Physically_Present_At_Address_And_In_Free_List_For_Specific_Size (Base => Base, Address => Address, Size => Block.Size, Block => Block) and then -- is neighbors from free list are free blocks to (like inductive case) -- left heighbor Proof.Block_Present_At_Address(Block.Free_List.Prev_Address) and then Is_Block_Physically_Present_At_Address_And_In_Free_List_For_Specific_Size (Base => Base, Address => Block.Free_List.Prev_Address, Size => Block.Size, Block => Get_Block_At_Address(Base, Block.Free_List.Prev_Address)) and then -- right heighbor Proof.Block_Present_At_Address(Block.Free_List.Next_Address) and then Is_Block_Physically_Present_At_Address_And_In_Free_List_For_Specific_Size (Base => Base, Address => Block.Free_List.Next_Address, Size => Block.Size, Block => Get_Block_At_Address(Base, Block.Free_List.Next_Address)) and then -- Last block is in correct state regarding linking (if Is_Block_Last_In_Free_List(Block) then (Block.Free_List = Free_List and then Block.Free_List.Prev_Address = Block.Free_List.Next_Address and then Block.Free_List.Prev_Address = Address)), Post => -- physycal presence same block (modulo free list links) at same address Proof.Specific_Block_Present_At_Address(Address, Block) and then -- removed from free lists (to do may be : for all free_lists: ... ?) not Proof.Is_Block_In_Free_List_For_Size (Block.Size, Address) and then not Is_Block_Linked_To_Free_List(Block) and then -- everything the same, except free list links Changed_Only_Links_For_Free_List(Block, Block'Old) and then -- check that list in correct state ; Check_Free_List_Correctness_After_Unlinking (Base => Base, Block => Block'Old) and then -- Check correst update of Free_List if it is was last block in it (if Block'Old.Free_List = Free_List'Old then Is_Free_List_Empty(Free_List)); -- function Is_Free_Block_Splitable(Block : Block_Header) -- return Boolean -- with -- Pre => -- Is_Block_Free(Block) and then -- Block.Size >= Small_Block_Size * 2, -- -- Contract_Cases => -- ( Block.Size >= 2*Small_Block_Size -- => Is_Free_Block_Splitable'Result = True, -- others -- => Is_Free_Block_Splitable'Result = False); -- -- -- NB: we can split only unlinked block -- -- this approach will be helpful for multithread version, -- -- because we can unlink fast, using fast lock or even move to lockless -- -- double-linked-lists -- procedure Split_Free_Block (Base : System.Address; -- Addr : Aligned_Address; -- Block : Block_Header; -- Left_Size, Right_Size : Aligned_Size; -- Block_Left, Block_Right : out Block_Header) -- with -- Pre => -- -- -- physical presence -- Proof.Specific_Block_Present_At_Address(Addr, Block) and then -- -- -- Block already should be unlinked from free lists (TODO: all lists?) -- not Is_Block_Linked_To_Free_List(Block) and then -- not Proof.Is_Block_In_Free_List_For_Size(Block.Size, Addr) and then -- -- -- splittable -- Is_Free_Block_Splitable(Block) and then -- -- -- Sizes preservation -- Block.Size = Left_Size + Right_Size, -- -- Post => -- -- -- physical presence : original block is nowhere -- not Proof.Specific_Block_Present_At_Address(Addr, Block) and then -- -- -- check once again that it is not included into any free lists -- not Is_Block_Linked_To_Free_List(Block) and then -- -- TODO: no free list contains blocks, ie we removed it from everywhere -- not Proof.Is_Block_In_Free_List_For_Size(Block.Size, Addr) and then -- -- -- Correctnes of sizes -- Block_Left.Size = Left_Size and then -- Block_Right.Size = Right_Size and then -- -- -- Check properties of the Left block: -- -- -- check if type is correct -- Is_Block_Free(Block_Left) and then -- -- -- physical presense -- Proof.Specific_Block_Present_At_Address(Addr, Block_Left) and then -- -- -- not yet linked into free lists -- not Is_Block_Linked_To_Free_List(Block_Left) and then -- not Proof.Is_Block_In_Free_List_For_Size(Block_Left.Size, Addr) and then -- -- -- TODO: add neighbors check -- -- -- The same for the right block -- Is_Block_Free(Block_Right) and then -- -- Proof.Specific_Block_Present_At_Address(Addr + Left_Size, Block_Right) and then -- -- not Is_Block_Linked_To_Free_List(Block_Right) and then -- not Proof.Is_Block_In_Free_List_For_Size(Block_Right.Size, Addr); -- -- -- procedure Link_To_Free_List_For_Size(Base : System.Address; -- Addr : Aligned_Address; -- Block : in out Block_Header; -- Free_List : in out Free_Blocks_List) -- with -- Pre => -- -- type check -- Is_Block_Free(Block) and then -- -- -- physical presense -- Proof.Specific_Block_Present_At_Address(Addr, Block) and then -- -- -- not linked to free lists yet (TODO: all free lists?) -- not Proof.Is_Block_In_Free_List_For_Size(Block.Size, Addr) and then -- not Is_Block_Linked_To_Free_List(Block), -- -- Post => -- -- type check -- Is_Block_Free(Block) and then -- -- -- physical presense -- Proof.Specific_Block_Present_At_Address(Addr, Block) and then -- -- -- linked to specific free list -- Is_Block_Linked_To_Free_List(Block) and then -- Proof.Is_Block_Present_In_Exactly_One_Free_List_For_Size(Block.Size, Addr) and then -- -- -- everything the same, except free list links -- Changed_Only_Links_For_Free_List(Block, Block'Old); end TLSF.Block.Operations_Old;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Containers.Hashed_Maps; with Ada.Containers.Ordered_Sets; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Text_IO; with GNAT.String_Split; package body AOC.AOC_2019.Day06 is type Planet is new String (1..3); function Orbit_Maps_Hash (Key : Planet) return Ada.Containers.Hash_Type is begin return Ada.Strings.Hash (String (Key)); end; package Planets is new Ada.Containers.Ordered_Sets (Element_Type => Planet); package Orbit_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Planet, Element_Type => Planets.Set, Hash => Orbit_Maps_Hash, Equivalent_Keys => "=", "=" => Planets."="); Orbits : Orbit_Maps.Map; package Orbit_Paths is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Planet); package Orbit_Processings is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Orbit_Paths.Vector, "=" => Orbit_Paths."="); Orbit_Processing : Orbit_Processings.Vector; Total_Orbits : Natural := 0; You_Path : Orbit_Paths.Vector; San_Path : Orbit_Paths.Vector; procedure Init (D : in out Day_06; Root : String) is use Ada.Text_IO; File : File_Type; begin Open (File => File, Mode => In_File, Name => Root & "/input/2019/day06.txt"); while not End_Of_File (File) loop declare use GNAT; Orbit_Line : String := Get_Line (File); Orbit_Set : String_Split.Slice_Set; begin String_Split.Create (S => Orbit_Set, From => Orbit_Line, Separators => ")", Mode => String_Split.Single); declare Key : Planet := Planet (String_Split.Slice (Orbit_Set, 1)); Value : Planet := Planet (String_Split.Slice (Orbit_Set, 2)); begin if Orbits.Contains (Key) then Orbits (Key).Insert (Value); else declare Planets_Set : Planets.Set; begin Planets_Set.Insert (Value); Orbits.Include (Key, Planets_Set); end; end if; end; end; end loop; declare Com_Path : Orbit_Paths.Vector; begin Com_Path.Append ("COM"); Orbit_Processing.Append (Com_Path); end; while not Orbit_Processing.Is_Empty loop declare Path : Orbit_Paths.Vector := Orbit_Processing.First_Element; Orbiter : Planet := Path.Last_Element; begin Total_Orbits := Total_Orbits + Natural (Path.Length) - 1; Orbit_Processing.Delete_First; if Orbits.Contains (Orbiter) then for P of Orbits (Orbiter) loop declare New_Path : Orbit_Paths.Vector := Path; begin New_Path.Append (P); Orbit_Processing.Append (New_Path); end; end loop; elsif Orbiter = "YOU" then You_Path := Path; elsif Orbiter = "SAN" then San_Path := Path; end if; end; end loop; end Init; function Part_1 (D : Day_06) return String is begin return Total_Orbits'Image; end Part_1; function Part_2 (D : Day_06) return String is Common_Orbit_Count : Natural := Natural'First; begin while You_Path (Common_Orbit_Count) = San_Path (Common_Orbit_Count) loop Common_Orbit_Count := Common_Orbit_Count + 1; end loop; return Natural'Image (Natural (You_Path.Length) + Natural (San_Path.Length) - (Common_Orbit_Count + 1)*2); end Part_2; end AOC.AOC_2019.Day06;
{ "source": "starcoderdata", "programming_language": "ada" }
with Extraction.Node_Edge_Types; with Extraction.Utilities; package body Extraction.Bodies_For_Entries is use type LALCO.Ada_Node_Kind_Type; procedure Extract_Edges (Node : LAL.Ada_Node'Class; Graph : Graph_Operations.Graph_Context) is begin if Node.Kind = LALCO.Ada_Entry_Body then declare Entry_Body : constant LAL.Entry_Body := Node.As_Entry_Body; Entry_Decl : constant LAL.Basic_Decl := Entry_Body.P_Decl_Part; begin Graph.Write_Edge(Entry_Decl, Entry_Body, Node_Edge_Types.Edge_Type_Is_Implemented_By); end; elsif Node.Kind in LALCO.Ada_Accept_Stmt_Range then declare Accept_Stmt : constant LAL.Accept_Stmt := Node.As_Accept_Stmt; Task_Body : constant LAL.Basic_Decl := Utilities.Get_Parent_Basic_Decl(Accept_Stmt); Entry_Decl : constant LAL.Basic_Decl := Utilities.Get_Referenced_Decl(Accept_Stmt.F_Name); begin Graph.Write_Edge(Entry_Decl, Task_Body, Node_Edge_Types.Edge_Type_Is_Implemented_By); end; end if; end Extract_Edges; end Extraction.Bodies_For_Entries;
{ "source": "starcoderdata", "programming_language": "ada" }
pragma Ada_2012; with AUnit.Assertions; use AUnit.Assertions; with AUnit.Test_Caller; with Ada.Streams; use Ada.Streams; with HMAC; use HMAC.HMAC_SHA_1; package body HMAC_SHA1_Streams_Tests is package Caller is new AUnit.Test_Caller (Fixture); Test_Suite : aliased AUnit.Test_Suites.Test_Suite; function Suite return AUnit.Test_Suites.Access_Test_Suite is Name : constant String := "[HMAC_SHA1 - Ada.Streams] "; begin Test_Suite.Add_Test (Caller.Create (Name & "HMAC_SHA1() - RFC 2202 test vectors", HMAC_SHA1_RFC2202_Test'Access)); return Test_Suite'Access; end Suite; procedure HMAC_SHA1_RFC2202_Test (Object : in out Fixture) is function HMAC (Key, Message : String) return Stream_Element_Array renames HMAC.HMAC_SHA_1.HMAC; begin declare Ctx : Context := Initialize (Stream_Element_Array' (16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#, 16#0b#)); begin Update (Ctx, "Hi There"); Assert (Finalize (Ctx) = Stream_Element_Array' (16#b6#, 16#17#, 16#31#, 16#86#, 16#55#, 16#05#, 16#72#, 16#64#, 16#e2#, 16#8b#, 16#c0#, 16#b6#, 16#fb#, 16#37#, 16#8c#, 16#8e#, 16#f1#, 16#46#, 16#be#, 16#00#), "test case no. 1"); end; Assert (HMAC (Key => "Jefe", Message => "what do ya want for nothing?") = Stream_Element_Array' (16#ef#, 16#fc#, 16#df#, 16#6a#, 16#e5#, 16#eb#, 16#2f#, 16#a2#, 16#d2#, 16#74#, 16#16#, 16#d5#, 16#f1#, 16#84#, 16#df#, 16#9c#, 16#25#, 16#9a#, 16#7c#, 16#79#), "test case no. 2"); declare Ctx : Context := Initialize (Stream_Element_Array'(1 .. 20 => 16#aa#)); begin Update (Ctx, Stream_Element_Array'(1 .. 50 => 16#dd#)); Assert (Finalize (Ctx) = Stream_Element_Array' (16#12#, 16#5d#, 16#73#, 16#42#, 16#b9#, 16#ac#, 16#11#, 16#cd#, 16#91#, 16#a3#, 16#9a#, 16#f4#, 16#8a#, 16#a1#, 16#7b#, 16#4f#, 16#63#, 16#f1#, 16#75#, 16#d3#), "test case no. 3"); end; declare Ctx : Context := Initialize (Stream_Element_Array' (16#01#, 16#02#, 16#03#, 16#04#, 16#05#, 16#06#, 16#07#, 16#08#, 16#09#, 16#0a#, 16#0b#, 16#0c#, 16#0d#, 16#0e#, 16#0f#, 16#10#, 16#11#, 16#12#, 16#13#, 16#14#, 16#15#, 16#16#, 16#17#, 16#18#, 16#19#)); begin Update (Ctx, Stream_Element_Array'(1 .. 50 => 16#cd#)); Assert (Finalize (Ctx) = Stream_Element_Array' (16#4c#, 16#90#, 16#07#, 16#f4#, 16#02#, 16#62#, 16#50#, 16#c6#, 16#bc#, 16#84#, 16#14#, 16#f9#, 16#bf#, 16#50#, 16#c8#, 16#6c#, 16#2d#, 16#72#, 16#35#, 16#da#), "test case no. 4"); end; declare Ctx : Context := Initialize (Stream_Element_Array'(1 .. 20 => 16#0c#)); begin Update (Ctx, "Test With Truncation"); Assert (Finalize (Ctx) = Stream_Element_Array' (16#4c#, 16#1a#, 16#03#, 16#42#, 16#4b#, 16#55#, 16#e0#, 16#7f#, 16#e7#, 16#f2#, 16#7b#, 16#e1#, 16#d5#, 16#8b#, 16#b9#, 16#32#, 16#4a#, 16#9a#, 16#5a#, 16#04#), "test case no. 5"); end; declare Ctx : Context := Initialize (Stream_Element_Array'(1 .. 80 => 16#aa#)); begin Update (Ctx, "Test Using Larger Than Block-Size Key - Hash Key First"); Assert (Finalize (Ctx) = Stream_Element_Array' (16#aa#, 16#4a#, 16#e5#, 16#e1#, 16#52#, 16#72#, 16#d0#, 16#0e#, 16#95#, 16#70#, 16#56#, 16#37#, 16#ce#, 16#8a#, 16#3b#, 16#55#, 16#ed#, 16#40#, 16#21#, 16#12#), "test case no. 6"); end; declare Ctx : Context := Initialize (Stream_Element_Array'(1 .. 80 => 16#aa#)); begin Update (Ctx, "Test Using Larger Than Block-Size Key and" & " Larger Than One Block-Size Data"); Assert (Finalize (Ctx) = Stream_Element_Array' (16#e8#, 16#e9#, 16#9d#, 16#0f#, 16#45#, 16#23#, 16#7d#, 16#78#, 16#6d#, 16#6b#, 16#ba#, 16#a7#, 16#96#, 16#5c#, 16#78#, 16#08#, 16#bb#, 16#ff#, 16#1a#, 16#91#), "test case no. 7"); end; end HMAC_SHA1_RFC2202_Test; end HMAC_SHA1_Streams_Tests;
{ "source": "starcoderdata", "programming_language": "ada" }
---------------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Fixed; with Ada.Strings.Unbounded; package body Symbolic_Expressions is -- Set to True to enable few debug prints Verbose : constant Boolean := False; pragma Unreferenced (Verbose); --------- -- "+" -- --------- function "+" (L : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Unary_Plus, Term => Duplicate (L.Expr))); end "+"; --------- -- "-" -- --------- function "-" (L : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Unary_Minus, Term => Duplicate (L.Expr))); end "-"; --------- -- "+" -- --------- function "+" (L, R : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Sum, Left => Duplicate (L.Expr), Right => Duplicate (R.Expr))); end "+"; --------- -- "-" -- --------- function "-" (L, R : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Sub, Left => Duplicate (L.Expr), Right => Duplicate (R.Expr))); end "-"; --------- -- "*" -- --------- function "*" (L, R : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Mult, Left => Duplicate (L.Expr), Right => Duplicate (R.Expr))); end "*"; --------- -- "/" -- --------- function "/" (L, R : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Div, Left => Duplicate (L.Expr), Right => Duplicate (R.Expr))); end "/"; --------- -- "+" -- --------- function "+" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression is begin return L + To_Expr (R); end "+"; --------- -- "-" -- --------- function "-" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression is begin return L - To_Expr (R); end "-"; --------- -- "*" -- --------- function "*" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression is begin return L * To_Expr (R); end "*"; --------- -- "/" -- --------- function "/" (L : Symbolic_Expression; R : Scalar_Type) return Symbolic_Expression is begin return L / To_Expr (R); end "/"; --------- -- "+" -- --------- function "+" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression is begin return To_Expr (L) + R; end "+"; --------- -- "-" -- --------- function "-" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression is begin return To_Expr (L) - R; end "-"; --------- -- "*" -- --------- function "*" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression is begin return To_Expr (L) * R; end "*"; --------- -- "/" -- --------- function "/" (L : Scalar_Type; R : Symbolic_Expression) return Symbolic_Expression is begin return To_Expr (L) / R; end "/"; ----------------- -- Is_Constant -- ----------------- function Is_Constant (X : Node_Access) return Boolean is begin case X.Class is when Unary_Plus | Unary_Minus => return Is_Constant (X.Term); when Sum | Sub | Mult | Div => return Is_Constant (X.Left) and Is_Constant (X.Right); when Fun_Call => for I in 1 .. X.N_Params loop if not Is_Constant (X.Parameters (I)) then return False; end if; end loop; return True; when Var => return False; when Const => return True; end case; end Is_Constant; function Is_Constant (X : Symbolic_Expression) return Boolean is begin return Is_Constant (X.Expr); end Is_Constant; ------------------- -- Constant_Expr -- ------------------- function To_Expr (X : Scalar_Type) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => new Node_Type'(Class => Const, Value => X)); end To_Expr; --------------- -- To_Scalar -- --------------- function To_Scalar (X : Node_Access) return Scalar_Type is begin case X.Class is when Unary_Plus => return + To_Scalar (X.Term); when Unary_Minus => return - To_Scalar (X.Term); when Sum => return To_Scalar (X.Left) + To_Scalar (X.Right); when Sub => return To_Scalar (X.Left) - To_Scalar (X.Right); when Mult => return To_Scalar (X.Left) * To_Scalar (X.Right); when Div => return To_Scalar (X.Left) / To_Scalar (X.Right); when Fun_Call => declare Param : Scalar_Array (1 .. X.N_Params); begin for I in Param'Range loop Param (I) := To_Scalar (X.Parameters (I)); end loop; return Call (Identifier(X.Fun_Name), Param); end; when Var => raise Not_A_Scalar; when Const => return X.Value; end case; end To_Scalar; function Eval (X : Symbolic_Expression) return Scalar_Type is begin return To_Scalar (X.Expr); end Eval; ------------------- -- Function_Call -- ------------------- function Function_Call (Name : Function_Name; Parameters : Expression_Array) return Symbolic_Expression is Node : constant Node_Access := new Node_Type'(Class => Fun_Call, Fun_Name => Name, N_Params => Parameters'Length, Parameters => <>); begin for I in Parameters'Range loop Node.Parameters (I) := Duplicate (Parameters (I).Expr); end loop; return Symbolic_Expression'(Controlled with Expr => Node); end Function_Call; -------------- -- Variable -- -------------- function Variable (Name : Variable_Name) return Symbolic_Expression is begin return Symbolic_Expression'(Controlled with Expr => new Node_Type'(Class => Var, Var_Name => Name)); end Variable; function Replace (Item : Node_Access; Var_Name : Variable_Name; Value : Node_Access) return Node_Access is function Result_Class (Item : Node_Access; Var_Name : Variable_Name) return Node_Class is begin if Item.Class = Var and then Item.Var_Name = Var_Name then return Const; else return Item.Class; end if; end Result_Class; pragma Unreferenced (Result_Class); Result : Node_Access; begin -- Ada.Text_IO.Put_Line ("Bibi" & Item.Class'img); case Item.Class is when Unary_Plus | Unary_Minus => Result := new Node_Type (Item.Class); Result.Term := Replace (Item.Term, Var_Name, Value); pragma Assert (Result.Class = Item.Class); when Sum | Sub | Mult | Div => Result := new Node_Type (Item.Class); Result.Left := Replace (Item.Left, Var_Name, Value); Result.Right := Replace (Item.Right, Var_Name, Value); pragma Assert (Result.Class = Item.Class); when Fun_Call => Result := new Node_Type (Item.Class); Result.Fun_Name := Item.Fun_Name; Result.N_Params := Item.N_Params; for I in 1 .. Result.N_Params loop Result.Parameters (I) := Replace (Item.Parameters (I), Var_Name, Value); end loop; pragma Assert (Result.Class = Fun_Call); when Var => -- Ada.Text_Io.Put_Line ("'" & To_String (Var_Name) & "' '" -- & To_String (Item.Var_Name) & "'"); if Item.Var_Name = Var_Name then Result := Duplicate (Value); else Result := Duplicate (Item); end if; when Const => Result := Duplicate (Item); end case; -- Ada.Text_IO.Put_Line ("Bobo" & Item.Class'img); return Result; end Replace; ------------- -- Replace -- ------------- function Replace (Item : Symbolic_Expression; Var_Name : Variable_Name; Value : Symbolic_Expression) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => Replace (Item => Item.Expr, Var_Name => Var_Name, Value => Value.Expr)); end Replace; function Replace (Item : Symbolic_Expression; Table : Variable_Tables.Map) return Symbolic_Expression is Result : Symbolic_Expression := Item; procedure Process (Name : Variable_Name) is use Variable_Tables; Pos : constant Cursor := Table.Find (Name); begin if Pos = No_Element then return; else Result := Replace (Item => Result, Var_Name => Name, Value => Element (Pos)); end if; end Process; begin Iterate_On_Vars (Item, Process'Access); return Result; end Replace; function Replace (Item : Symbolic_Expression; Var_Name : Variable_Name; Value : Scalar_Type) return Symbolic_Expression is begin return Symbolic_Expression' (Controlled with Expr => Replace (Item.Expr, Var_Name, To_Expr(Value).Expr)); end Replace; function Free_Variables (Item : Symbolic_Expression) return Variable_Sets.Set is procedure Fill_List (Item : Node_Access; Names : in out Variable_Sets.Set) is begin case Item.Class is when Unary_Plus | Unary_Minus => Fill_List (Item.Term, Names); when Sum | Sub | Mult | Div => Fill_List (Item.Left, Names); Fill_List (Item.Right, Names); when Fun_Call => for I in 1 .. Item.N_Params loop Fill_List (Item.Parameters (I), Names); end loop; when Var => Names.Include (Item.Var_Name); when Const => null; end case; end Fill_List; Result : Variable_Sets.Set; begin Fill_List (Item.Expr, Result); return Result; end Free_Variables; --------------------- -- Iterate_On_Vars -- --------------------- procedure Iterate_On_Vars (Item : Symbolic_Expression; Process : access procedure (Var_Name : Variable_Name)) is use Variable_Sets; -- Variables : Var_Lists.Set := procedure Call (Pos : Cursor) is begin Process (Element (Pos)); end Call; begin Free_Variables (Item).Iterate (Call'Access); end Iterate_On_Vars; --------------- -- Normalize -- --------------- -- procedure Normalize (Item : in out Symbolic_Expression) is -- pragma Unreferenced (Item); -- begin -- -- Generated stub: replace with real body! -- pragma Compile_Time_Warning (Standard.False, "Normalize unimplemented"); -- raise Program_Error with "Unimplemented procedure Normalize"; -- end Normalize; function Duplicate (Item : Node_Access) return Node_Access is Result : constant Node_Access := new Node_Type (Item.Class); begin if Item = null then return null; end if; case Item.Class is when Unary_Plus | Unary_Minus => Result.Term := Duplicate (Item.Term); when Sum | Sub | Mult | Div => Result.Left := Duplicate (Item.Left); Result.Right := Duplicate (Item.Right); when Fun_Call => Result.Fun_Name := Item.Fun_Name; Result.N_Params := Item.N_Params; for I in 1 .. Result.N_Params loop Result.Parameters (I) := Duplicate (Item.Parameters (I)); end loop; when Var => Result.Var_Name := Item.Var_Name; when Const => Result.Value := Item.Value; end case; return Result; end Duplicate; procedure Free (Item : in out Node_Access) is procedure Dealloc is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Access); begin if Item = null then return; end if; pragma Assert (Item /= null); case Item.Class is when Unary_Plus | Unary_Minus => Free (Item.Term); when Sum | Sub | Mult | Div => Free (Item.Left); Free (Item.Right); when Fun_Call => for I in 1 .. Item.N_Params loop Free (Item.Parameters (I)); end loop; when Var => null; when Const => null; end case; Dealloc (Item); end Free; function Dump (Item : Node_Access; Level : Natural) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; function Head (X : String) return Unbounded_String is begin return To_Unbounded_String (((Level * 3) * " ") & X); end Head; CRLF : constant String := Character'Val (13) & Character'Val (10); Result : Unbounded_String; begin case Item.Class is when Unary_Plus => Result := Head ("@+") & CRLF & Dump (Item.Term, Level + 1); when Unary_Minus => Result := Head ("@-") & CRLF & Dump (Item.Term, Level + 1); when Sum => Result := Head ("+") & CRLF & Dump (Item.Left, Level + 1) & CRLF & Dump (Item.Right, Level + 1); when Sub => Result := Head ("-") & CRLF & Dump (Item.Left, Level + 1) & CRLF & Dump (Item.Right, Level + 1); when Mult => Result := Head ("*") & CRLF & Dump (Item.Left, Level + 1) & CRLF & Dump (Item.Right, Level + 1); when Div => Result := Head ("/") & CRLF & Dump (Item.Left, Level + 1) & CRLF & Dump (Item.Right, Level + 1); when Fun_Call => Result := Head ("Call " & ID_Image (Item.Fun_Name)); for I in 1 .. Item.N_Params loop Result := Result & CRLF & Dump (Item.Parameters (I), Level + 1); end loop; when Var => Result := Head ("Var ") & "(" & ID_Image (Item.Var_Name) & ")"; when Const => Result := Head ("Const ") & Image (Item.Value); end case; return To_String (Result); end Dump; function Dump (Item : Symbolic_Expression) return String is begin return Dump (Item.Expr, 0); end Dump; overriding procedure Initialize (Item : in out Symbolic_Expression) is begin Item.Expr := null; end Initialize; overriding procedure Finalize (Item : in out Symbolic_Expression) is begin if Item.Expr /= null then Free (Item.Expr); end if; end Finalize; overriding procedure Adjust (Item : in out Symbolic_Expression) is begin if Item.Expr /= null then Item.Expr := Duplicate (Item.Expr); end if; end Adjust; end Symbolic_Expressions;
{ "source": "starcoderdata", "programming_language": "ada" }
with Ada.Directories; with Ada.Real_Time; with Ada.Strings.Fixed; with Ada.Text_IO; package body WisiToken.Generate is function Error_Message (File_Name : in String; File_Line : in Line_Number_Type; Message : in String) return String is use Ada.Directories; use Ada.Strings.Fixed; use Ada.Strings; begin return Simple_Name (File_Name) & ":" & Trim (Line_Number_Type'Image (File_Line), Left) & ":0: " & Message; end Error_Message; procedure Put_Error (Message : in String) is begin Error := True; Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, Message); end Put_Error; procedure Check_Consistent (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; Source_File_Name : in String) is begin if Descriptor.Accept_ID /= Descriptor.First_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Descriptor.Accept_ID /= Descriptor.First_Nonterminal")); end if; if Grammar.First_Index /= Descriptor.First_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar.First_Index /= Descriptor.First_Nonterminal")); end if; if Grammar.Last_Index /= Descriptor.Last_Nonterminal then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar.Last_Index /= Descriptor.Last_Nonterminal")); end if; for Nonterm in Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal loop if Grammar (Nonterm).LHS /= Nonterm then Put_Error (Error_Message (Source_File_Name, Line_Number_Type'First, "Grammar (" & Image (Nonterm, Descriptor) & ").LHS = " & Image (Grammar (Nonterm).LHS, Descriptor) & " /= " & Image (Nonterm, Descriptor))); end if; end loop; end Check_Consistent; function Check_Unused_Tokens (Descriptor : in WisiToken.Descriptor; Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Boolean is subtype Terminals is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; subtype Nonterminals is Token_ID range Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal; Used_Tokens : Token_ID_Set := (Descriptor.First_Terminal .. Descriptor.Last_Nonterminal => False); Changed : Boolean := False; Abort_Generate : Boolean := False; Unused_Tokens : Boolean := False; begin Used_Tokens (Descriptor.Accept_ID) := True; -- First mark all nonterminals that occur in used nonterminals as -- used. loop for Prod of Grammar loop if Used_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for J of RHS.Tokens loop if J in Nonterminals then Changed := Changed or else not Used_Tokens (J); Used_Tokens (J) := True; end if; end loop; end loop; end if; end loop; exit when not Changed; Changed := False; end loop; -- Now mark terminals used in used nonterminals for Prod of Grammar loop if Used_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for J of RHS.Tokens loop if not (J in Used_Tokens'Range) then WisiToken.Generate.Put_Error ("non-grammar token " & Image (J, Descriptor) & " used in grammar"); -- This causes lots of problems with token_id not in terminal or -- nonterminal range, so abort early. Abort_Generate := True; end if; if J in Terminals then Used_Tokens (J) := True; end if; end loop; end loop; end if; end loop; for I in Used_Tokens'Range loop if not Used_Tokens (I) then if not Unused_Tokens then WisiToken.Generate.Put_Error ("Unused tokens:"); Unused_Tokens := True; end if; WisiToken.Generate.Put_Error (Image (I, Descriptor)); end if; end loop; if Abort_Generate then raise Grammar_Error; end if; return Unused_Tokens; end Check_Unused_Tokens; function Nullable (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_Array_Production_ID is use all type Ada.Containers.Count_Type; subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Result : Token_Array_Production_ID := (Nonterminal => Invalid_Production_ID); Changed : Boolean := True; begin loop exit when not Changed; Changed := False; for Prod of Grammar loop if Result (Prod.LHS) = Invalid_Production_ID then for RHS_Index in Prod.RHSs.First_Index .. Prod.RHSs.Last_Index loop declare RHS : WisiToken.Productions.Right_Hand_Side renames Prod.RHSs (RHS_Index); begin if RHS.Tokens.Length = 0 or else (RHS.Tokens (1) in Nonterminal and then Result (RHS.Tokens (1)) /= Invalid_Production_ID) then Result (Prod.LHS) := (Prod.LHS, RHS_Index); Changed := True; end if; end; end loop; end if; end loop; end loop; return Result; end Nullable; function Has_Empty_Production (Nullable : in Token_Array_Production_ID) return Token_ID_Set is begin return Result : Token_ID_Set := (Nullable'First .. Nullable'Last => False) do for I in Result'Range loop Result (I) := Nullable (I) /= Invalid_Production_ID; end loop; end return; end Has_Empty_Production; function Has_Empty_Production (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Token_ID_Set is use all type Ada.Containers.Count_Type; subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Result : Token_ID_Set := (Nonterminal => False); Changed : Boolean := True; begin loop exit when not Changed; Changed := False; for Prod of Grammar loop for RHS of Prod.RHSs loop if (RHS.Tokens.Length = 0 or else (RHS.Tokens (1) in Nonterminal and then Result (RHS.Tokens (1)))) and not Result (Prod.LHS) then Result (Prod.LHS) := True; Changed := True; end if; end loop; end loop; end loop; return Result; end Has_Empty_Production; function First (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Has_Empty_Production : in Token_ID_Set; First_Terminal : in Token_ID; Non_Terminal : in Token_ID) return Token_ID_Set is Search_Tokens : Token_ID_Set := (Grammar.First_Index .. Grammar.Last_Index => False); begin Search_Tokens (Non_Terminal) := True; return Derivations : Token_ID_Set := (First_Terminal .. Grammar.Last_Index => False) do while Any (Search_Tokens) loop declare Added_Tokens : Token_ID_Set := (First_Terminal .. Grammar.Last_Index => False); Added_Nonterms : Token_ID_Set := (Grammar.First_Index .. Grammar.Last_Index => False); begin for Prod of Grammar loop if Search_Tokens (Prod.LHS) then for RHS of Prod.RHSs loop for Derived_Token of RHS.Tokens loop if not Derivations (Derived_Token) then Added_Tokens (Derived_Token) := True; if Derived_Token in Added_Nonterms'Range then Added_Nonterms (Derived_Token) := True; end if; end if; if Derived_Token in Has_Empty_Production'Range and then Has_Empty_Production (Derived_Token) then null; else exit; end if; end loop; end loop; end if; end loop; Derivations := Derivations or Added_Tokens; Search_Tokens := Added_Nonterms; end; end loop; end return; end First; function First (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Has_Empty_Production : in Token_ID_Set; First_Terminal : in Token_ID) return Token_Array_Token_Set is Matrix : Token_Array_Token_Set := (Grammar.First_Index .. Grammar.Last_Index => (First_Terminal .. Grammar.Last_Index => False)); procedure Set_Slice (Matrix : in out Token_Array_Token_Set; I : Token_ID; Value : in Token_ID_Set) is begin for J in Matrix'Range (2) loop Matrix (I, J) := Value (J); end loop; end Set_Slice; begin for NT_Index in Matrix'Range loop Set_Slice (Matrix, NT_Index, First (Grammar, Has_Empty_Production, First_Terminal, NT_Index)); end loop; return Matrix; end First; function To_Terminal_Sequence_Array (First : in Token_Array_Token_Set; Descriptor : in WisiToken.Descriptor) return Token_Sequence_Arrays.Vector is subtype Terminal is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; begin return Result : Token_Sequence_Arrays.Vector do Result.Set_First_Last (First'First (1), First'Last (1)); for I in First'Range (1) loop declare Row : Token_ID_Arrays.Vector renames Result (I); begin for J in First'Range (2) loop if First (I, J) and then J in Terminal then Row.Append (J); end if; end loop; end; end loop; end return; end To_Terminal_Sequence_Array; function Follow (Grammar : in WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor; First : in Token_Array_Token_Set; Has_Empty_Production : in Token_ID_Set) return Token_Array_Token_Set is subtype Terminal is Token_ID range Descriptor.First_Terminal .. Descriptor.Last_Terminal; subtype Nonterminal is Token_ID range Descriptor.First_Nonterminal .. Descriptor.Last_Nonterminal; Prev_Result : Token_Array_Token_Set := (Nonterminal => (Terminal => False)); Result : Token_Array_Token_Set := (Nonterminal => (Terminal => False)); ID : Token_ID; begin -- [dragon] pgp 189: -- -- Rule 1 Follow (S, EOF) = True; EOF is explicit in the -- start symbol production, so this is covered by Rule 2. -- -- Rule 2: If A => alpha B Beta, add First (Beta) to Follow (B) -- -- Rule 3; if A => alpha B, or A -> alpha B Beta and Beta -- can be null, add Follow (A) to Follow (B) -- -- We don't assume any order in the productions list, so we -- have to keep applying rule 3 until nothing changes. for B in Nonterminal loop for Prod of Grammar loop for A of Prod.RHSs loop for I in A.Tokens.First_Index .. A.Tokens.Last_Index loop if A.Tokens (I) = B then if I < A.Tokens.Last_Index then -- Rule 1 ID := A.Tokens (1 + I); if ID in Terminal then Result (B, ID) := True; else Or_Slice (Result, B, Slice (First, ID)); end if; end if; end if; end loop; end loop; end loop; end loop; Prev_Result := Result; loop for B in Nonterminal loop for Prod of Grammar loop for A of Prod.RHSs loop for I in A.Tokens.First_Index .. A.Tokens.Last_Index loop if A.Tokens (I) = B then if I = A.Tokens.Last_Index or else (A.Tokens (1 + I) in Nonterminal and then Has_Empty_Production (A.Tokens (1 + I))) then -- rule 3 Or_Slice (Result, B, Slice (Result, Prod.LHS)); end if; end if; end loop; end loop; end loop; end loop; exit when Prev_Result = Result; Prev_Result := Result; end loop; return Result; end Follow; function To_Graph (Grammar : in WisiToken.Productions.Prod_Arrays.Vector) return Grammar_Graphs.Graph is subtype Nonterminals is Token_ID range Grammar.First_Index .. Grammar.Last_Index; Graph : Grammar_Graphs.Graph; J : Integer := 1; begin if Trace_Generate_Minimal_Complete > Outline then Ada.Text_IO.Put_Line ("grammar graph:"); end if; for LHS in Grammar.First_Index .. Grammar.Last_Index loop declare Prod : WisiToken.Productions.Instance renames Grammar (LHS); begin for RHS in Prod.RHSs.First_Index .. Prod.RHSs.Last_Index loop declare Tokens : Token_ID_Arrays.Vector renames Prod.RHSs (RHS).Tokens; begin for I in Tokens.First_Index .. Tokens.Last_Index loop if Tokens (I) in Nonterminals then if Trace_Generate_Minimal_Complete > Detail then Ada.Text_IO.Put_Line ("(" & Trimmed_Image (LHS) & ", " & Trimmed_Image (Tokens (I)) & "," & J'Image & ")"); J := J + 1; end if; Graph.Add_Edge (LHS, Tokens (I), (RHS, I)); end if; end loop; end; end loop; end; end loop; if Trace_Generate_Minimal_Complete > Outline then Ada.Text_IO.Put_Line ("..." & Graph.Count_Nodes'Image & " nodes" & Graph.Count_Edges'Image & " edges."); end if; return Graph; end To_Graph; function Recursion (LHS : in Token_ID; Token_Index : in Positive; Tokens : in Token_ID_Arrays.Vector) return Recursion_Class is begin return (if Token_Index = Tokens.First_Index then (if LHS = Tokens (Tokens.First_Index) then Direct_Left else Other_Left) elsif Token_Index = Tokens.Last_Index then (if LHS = Tokens (Tokens.Last_Index) then Direct_Right else Other_Right) else Other); end Recursion; procedure Set_Grammar_Recursions (Recursions : in WisiToken.Generate.Recursions; Grammar : in out WisiToken.Productions.Prod_Arrays.Vector) is begin for LHS of Grammar loop for RHS of LHS.RHSs loop RHS.Recursion.Set_First_Last (RHS.Tokens.First_Index, RHS.Tokens.Last_Index); end loop; end loop; for Path of Recursions.Recursions loop declare use WisiToken.Productions; Previous_Item_LHS : Token_ID := (if Recursions.Full then Path (Path'Last).Vertex else Token_ID'Last); begin for Item of Path loop for Edge of Item.Edges loop declare LHS : constant Token_ID := (if Recursions.Full then Previous_Item_LHS else Item.Vertex); RHS : Right_Hand_Side renames Grammar (LHS).RHSs (Edge.Data.RHS); begin RHS.Recursion (Edge.Data.Token_Index) := Recursion (LHS => LHS, Token_Index => Edge.Data.Token_Index, Tokens => RHS.Tokens); end; end loop; Previous_Item_LHS := Item.Vertex; end loop; end; end loop; end Set_Grammar_Recursions; function Compute_Full_Recursion (Grammar : in out WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return Recursions is Time_Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Graph : constant Grammar_Graphs.Graph := To_Graph (Grammar); begin return Result : Recursions := (Full => True, Recursions => Graph.Find_Cycles) do Grammar_Graphs.Sort_Paths.Sort (Result.Recursions); Set_Grammar_Recursions (Result, Grammar); if Trace_Time then declare use Ada.Real_Time; Time_End : constant Time := Clock; begin Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "compute partial recursion time:" & Duration'Image (To_Duration (Time_End - Time_Start))); end; end if; if Trace_Generate_Minimal_Complete > Extra then Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Productions:"); WisiToken.Productions.Put (Grammar, Descriptor); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("full recursions:"); for I in Result.Recursions.First_Index .. Result.Recursions.Last_Index loop Ada.Text_IO.Put_Line (Trimmed_Image (I) & " => " & Grammar_Graphs.Image (Result.Recursions (I))); end loop; end if; end return; end Compute_Full_Recursion; function Compute_Partial_Recursion (Grammar : in out WisiToken.Productions.Prod_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return Recursions is use Grammar_Graphs; Time_Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Graph : constant Grammar_Graphs.Graph := To_Graph (Grammar); Components : constant Component_Lists.List := Strongly_Connected_Components (To_Adjancency (Graph), Non_Trivial_Only => True); Loops : constant Vertex_Lists.List := Graph.Loops; begin return Result : Recursions do Result.Full := False; for Comp of Components loop declare Path : Recursion_Cycle (1 .. Integer (Comp.Length)); Last : Integer := Path'First - 1; begin for V of Comp loop Last := Last + 1; Path (Last) := (V, Graph.Edges (V)); end loop; Result.Recursions.Append (Path); end; end loop; declare Path : Recursion_Cycle (1 .. Integer (Loops.Length)); Last : Integer := Path'First - 1; begin for V of Loops loop Last := Last + 1; Path (Last) := (V, Graph.Edges (V)); end loop; Result.Recursions.Append (Path); end; Set_Grammar_Recursions (Result, Grammar); if Trace_Time then declare use Ada.Real_Time; Time_End : constant Time := Clock; begin Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "compute full recursion time:" & Duration'Image (To_Duration (Time_End - Time_Start))); end; end if; if Trace_Generate_Minimal_Complete > Extra then Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Productions:"); WisiToken.Productions.Put (Grammar, Descriptor); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("partial recursions:"); for I in Result.Recursions.First_Index .. Result.Recursions.Last_Index loop Ada.Text_IO.Put_Line (Trimmed_Image (I) & " => " & Grammar_Graphs.Image (Result.Recursions (I))); end loop; end if; end return; end Compute_Partial_Recursion; ---------- -- Indented text output procedure Indent_Line (Text : in String) is use Ada.Text_IO; begin Set_Col (Indent); Put_Line (Text); Line_Count := Line_Count + 1; end Indent_Line; procedure Indent_Start (Text : in String) is use Ada.Text_IO; begin Set_Col (Indent); Put (Text); end Indent_Start; procedure Indent_Wrap (Text : in String) is use all type Ada.Text_IO.Count; use Ada.Strings; use Ada.Strings.Fixed; I : Natural; First : Integer := Text'First; begin if Text'Length + Indent <= Max_Line_Length then Indent_Line (Text); else loop I := Text'Last; loop I := Index (Text (First .. Text'Last), " ", From => I, Going => Backward); exit when I - First + Integer (Indent) <= Max_Line_Length; I := I - 1; end loop; Indent_Line (Trim (Text (First .. I - 1), Right)); First := I + 1; exit when Text'Last - First + Integer (Indent) <= Max_Line_Length; end loop; Indent_Line (Text (First .. Text'Last)); end if; end Indent_Wrap; procedure Indent_Wrap_Comment (Text : in String; Comment_Syntax : in String) is use all type Ada.Text_IO.Count; use Ada.Strings; use Ada.Strings.Fixed; Prefix : constant String := Comment_Syntax & " "; I : Natural; First : Integer := Text'First; begin if Text'Length + Indent <= Max_Line_Length - 4 then Indent_Line (Prefix & Text); else loop I := Text'Last; loop I := Index (Text (First .. Text'Last), " ", From => I, Going => Backward); exit when I - First + Integer (Indent) <= Max_Line_Length - 4; I := I - 1; end loop; Indent_Line (Prefix & Text (First .. I - 1)); First := I + 1; exit when Text'Last - First + Integer (Indent) <= Max_Line_Length - 4; end loop; Indent_Line (Prefix & Text (First .. Text'Last)); end if; end Indent_Wrap_Comment; end WisiToken.Generate;
{ "source": "starcoderdata", "programming_language": "ada" }
------------------------------------------------------------- package body Program.Lexical_Elements is ----------- -- First -- ----------- function First (Self : Lexical_Element_Vector'Class) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Element (Self.First_Index); end First; ---------- -- Last -- ---------- function Last (Self : Lexical_Element_Vector'Class) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Element (Self.Last_Index); end Last; end Program.Lexical_Elements;
{ "source": "starcoderdata", "programming_language": "ada" }
with openGL.Errors, openGL.Buffer, openGL.Tasks, GL.Binding, ada.unchecked_Deallocation; package body openGL.Primitive.long_indexed is --------- --- Forge -- procedure define (Self : in out Item; Kind : in facet_Kind; Indices : in long_Indices) is use Buffer.long_indices.Forge; buffer_Indices : aliased long_Indices := (Indices'Range => <>); begin for Each in buffer_Indices'Range loop buffer_Indices (Each) := Indices (Each) - 1; -- Adjust indices to zero-based-indexing for GL. end loop; Self.facet_Kind := Kind; Self.Indices := new Buffer.long_indices.Object' (to_Buffer (buffer_Indices'Access, usage => Buffer.static_Draw)); end define; function new_Primitive (Kind : in facet_Kind; Indices : in long_Indices) return Primitive.long_indexed.view is Self : constant View := new Item; begin define (Self.all, Kind, Indices); return Self; end new_Primitive; overriding procedure destroy (Self : in out Item) is procedure free is new ada.unchecked_Deallocation (Buffer.long_indices.Object'Class, Buffer.long_indices.view); begin Buffer.destroy (Self.Indices.all); free (Self.Indices); end destroy; -------------- -- Attributes -- procedure Indices_are (Self : in out Item; Now : in long_Indices) is use Buffer.long_indices; buffer_Indices : aliased long_Indices := (Now'Range => <>); begin for Each in buffer_Indices'Range loop buffer_Indices (Each) := Now (Each) - 1; -- Adjust indices to zero-based-indexing for GL. end loop; Self.Indices.set (to => buffer_Indices); end Indices_are; -------------- -- Operations -- overriding procedure render (Self : in out Item) is use GL, GL.Binding; begin Tasks.check; openGL.Primitive.item (Self).render; -- Do base class render. Self.Indices.enable; glDrawElements (Thin (Self.facet_Kind), gl.GLint (Self.Indices.Length), GL_UNSIGNED_INT, null); Errors.log; end render; end openGL.Primitive.long_indexed;
{ "source": "starcoderdata", "programming_language": "ada" }
with Server; with Templates_Parser; with Ada.Text_IO; use Ada.Text_IO; with Generator; with Ada.Directories; with Ada.Calendar; with GNAT.Command_Line; use GNAT.Command_Line; with Ada.Wide_Wide_Text_IO; with Ada.Wide_Wide_Text_IO.Text_Streams; with Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with CLIC.Subcommand; with Commands; with CLIC.TTY; procedure Websitegenerator is use Ada.Calendar; use Ada.Wide_Wide_Text_IO.Text_Streams; use Generator.aString; use Templates_Parser; Start_Processing, End_Processing : Time; How_Long : Duration; S : constant Stream_Access := Stream (Ada.Wide_Wide_Text_IO.Current_Output); begin Ada.Text_IO.New_Line; Start_Processing := Clock; Commands.Execute; End_Processing := Clock; How_Long := (End_Processing - Start_Processing) * 1_000; Character'Write (S, ASCII.LF); String'Write (S, "Website generated in "); Wide_Wide_String'Write (S, How_Long'Wide_Wide_Image); String'Write (S, "ms!"); Character'Write (S, ASCII.LF); exception when E : others => Ada.Text_IO.Put_Line (Exception_Message (E)); end Websitegenerator;
{ "source": "starcoderdata", "programming_language": "ada" }