content
stringlengths
23
1.05M
generic type elem is private; package dcola is type cola is limited private; mal_uso: exception; espacio_desbordado: exception; procedure cvacia(qu: out cola); procedure poner (qu: in out cola; x: in elem); procedure borrar_primero (qu: in out cola); function coger_primero(qu: in cola) return elem; function esta_vacia(qu: in cola) return boolean; function is_last_item (qu: in cola) return boolean; private type nodo; type pnodo is access nodo; type nodo is record x: elem; sig: pnodo; end record; type cola is record p, q: pnodo; -- q inicio cola (consulta), p final cola (insercion) end record; end dcola;
-- ----------------------------------------------------------------- -- -- AdaSDL -- -- Thin binding to Simple Direct Media Layer -- -- Copyright (C) 2000-2012 A.M.F.Vargas -- -- Antonio M. M. Ferreira Vargas -- -- Manhente - Barcelos - Portugal -- -- http://adasdl.sourceforge.net -- -- E-mail: amfvargas@gmail.com -- -- ----------------------------------------------------------------- -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public -- -- License as published by the Free Software Foundation; either -- -- version 2 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from -- -- this unit, or you link this unit with other files to produce an -- -- executable, this unit does not by itself cause the resulting -- -- executable to be covered by the GNU General Public License. This -- -- exception does not however invalidate any other reasons why the -- -- executable file might be covered by the GNU Public License. -- -- Modified for SDL2 by R.H.I. Veenker -- (c) RNLA/JIVC/SATS -- ----------------------------------------------------------------- -- -- **************************************************************** -- -- 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 SDL.Types; use SDL.Types; with SDL.RWops; package SDL.Audio is pragma Elaborate_Body; package C renames Interfaces.C; use type Interfaces.C.int; SDL_AUDIO_ALLOW_FREQUENCY_CHANGE : constant C.int := 16#00000001#; SDL_AUDIO_ALLOW_FORMAT_CHANGE : constant C.int := 16#00000002#; SDL_AUDIO_ALLOW_CHANNELS_CHANGE : constant C.int := 16#00000004#; SDL_AUDIO_ALLOW_ANY_CHANGE : constant C.int := (SDL_AUDIO_ALLOW_FREQUENCY_CHANGE + SDL_AUDIO_ALLOW_FORMAT_CHANGE + SDL_AUDIO_ALLOW_CHANNELS_CHANGE); -- This function is called when the audio device needs more data. -- -- \param userdata An application-specific parameter saved in -- the SDL_AudioSpec structure -- \param stream A pointer to the audio data buffer. -- \param len The length of that buffer in bytes. -- -- Once the callback returns, the buffer will no longer be valid. -- Stereo samples are stored in a LRLRLR ordering. -- -- You can choose to avoid callbacks and use SDL_QueueAudio() instead, if -- you like. Just open your audio device with a NULL callback. type Callback_ptr_Type is access procedure ( userdata : void_ptr; stream : Uint8_ptr; len : C.int); pragma Convention (C, Callback_ptr_Type); -- The calculated values in this structure are calculated by SDL_OpenAudio(). -- -- For multi-channel audio, the default SDL channel mapping is: -- 2: FL FR (stereo) -- 3: FL FR LFE (2.1 surround) -- 4: FL FR BL BR (quad) -- 5: FL FR FC BL BR (quad + center) -- 6: FL FR FC LFE SL SR (5.1 surround - last two can also be BL BR) -- 7: FL FR FC LFE BC SL SR (6.1 surround) -- 8: FL FR FC LFE BL BR SL SR (7.1 surround) type AudioSpec is record freq : C.int; -- DSP frequency -- samples per second format : Uint16; -- Audio data format channels : Uint8; -- Number of channels: 1 mono, 2 stereo silence : Uint8; -- Audio buffer silence value (calculated) samples : Uint16; -- Audio buffer size in samples padding : Uint16; -- Necessary for some compile environments size : Uint32; -- Audio buffer size in bytes (calculated) -- This function is called when the audio device needs more data. -- 'stream' is a pointer to the audio data buffer -- 'len' is the length of that buffer in bytes. -- Once the callback returns, the buffer will no longer be valid. -- Stereo samples are stored in a LRLRLR ordering. callback : Callback_ptr_Type; userdata : void_ptr; end record; pragma Convention (C, AudioSpec); type AudioSpec_ptr is access all AudioSpec; pragma Convention (C, AudioSpec_ptr); type Format_Flag is mod 2 ** 16; pragma Convention (C, Format_Flag); type Format_Flag_ptr is access Format_Flag; pragma Convention (C, Format_Flag_ptr); -- Audio format flags (defaults to LSB byte order) -- Unsigned 8-bit samples AUDIO_U8 : constant Format_Flag := 16#0008#; -- Signed 8-bit samples AUDIO_S8 : constant Format_Flag := 16#8008#; -- Unsigned 16-bit samples AUDIO_U16LSB : constant Format_Flag := 16#0010#; -- Signed 16-bit samples AUDIO_S16LSB : constant Format_Flag := 16#8010#; -- As above, but big-endian byte order AUDIO_U16MSB : constant Format_Flag := 16#1010#; -- As above, but big-endian byte order AUDIO_S16MSB : constant Format_Flag := 16#9010#; AUDIO_U16 : constant Format_Flag := AUDIO_U16LSB; AUDIO_S16 : constant Format_Flag := AUDIO_S16LSB; function Get_Audio_U16_Sys return Format_Flag; function Get_Audio_S16_Sys return Format_Flag; SDL_AUDIOCVT_MAX_FILTERS : constant := 9; -- \brief A structure to hold a set of audio conversion filters and buffers. -- -- Note that various parts of the conversion pipeline can take advantage -- of SIMD operations (like SSE2, for example). SDL_AudioCVT doesn't require -- you to pass it aligned data, but can possibly run much faster if you -- set both its (buf) field to a pointer that is aligned to 16 bytes, and its -- (len) field to something that's a multiple of 16, if possible. -- This structure is 84 bytes on 32-bit architectures, make sure GCC doesn't -- pad it out to 88 bytes to guarantee ABI compatibility between compilers. -- vvv -- The next time we rev the ABI, make sure to size the ints and add padding. type AudioCVT; type AudioCVT_ptr is access all AudioCVT; pragma Convention (C, AudioCVT_ptr); type filter_ptr is access procedure ( cvt : AudioCVT_ptr; format : Uint16); pragma Convention (C, filter_ptr); type filters_array is array (0 .. 9) of filter_ptr; pragma Convention (C, filters_array); type AudioCVT is record needed : C.int; -- Set to 1 if conversion possible src_format : Uint16; -- Source audio format dst_format : Uint16; -- Target audio format rate_incr : C.double; -- Rate conversion increment buf : Uint8_ptr; -- Buffer to hold entire audio data len : C.int; -- Length of original audio buffer len_cvt : C.int; -- Length of converted audio buffer len_mult : C.int; -- buffer must be len*len_mult big len_ratio : C.double; -- Given len, final size is len*len_ratio filters : filters_array; filter_index : C.int; -- Current audio conversion function end record; pragma Convention (C, AudioCVT); -- ------------------- -- Function prototypes -- ------------------- -- These functions return the list of built in audio drivers, in the -- order that they are normally initialized by default. function SDL_GetNumAudioDrivers return C.int; pragma Import (C, SDL_GetNumAudioDrivers, "SDL_GetNumAudioDrivers"); function SDL_GetAudioDriver ( index : C.int) return C.Strings.chars_ptr; pragma Import (C, SDL_GetAudioDriver, "SDL_GetAudioDriver"); -- These function and procedure are used internally, and should not -- be used unless you have a specific need to specify the audio driver -- you want to use.You should normally use Init or InitSubSystem. function SDL_AudioInit (driver_name : C.Strings.chars_ptr) return C.int; pragma Import (C, SDL_AudioInit, "SDL_AudioInit"); procedure SDL_AudioQuit; pragma Import (C, SDL_AudioQuit, "SDL_AudioQuit"); -- This function returns the name of the current audio driver, or NULL -- if no driver has been initialized. function SDL_GetCurrentAudioDriver ( namebuf : C.Strings.chars_ptr; maslen : C.int) return C.Strings.chars_ptr; pragma Import (C, SDL_GetCurrentAudioDriver, "SDL_GetCurrentAudioDriver"); -- This function opens the audio device with the desired parameters, and -- returns 0 if successful, placing the actual hardware parameters in the -- structure pointed to by \c obtained. If \c obtained is NULL, the audio -- data passed to the callback function will be guaranteed to be in the -- requested format, and will be automatically converted to the hardware -- audio format if necessary. This function returns -1 if it failed -- to open the audio device, or couldn't set up the audio thread. -- -- When filling in the desired audio spec structure, -- - \c desired->freq should be the desired audio frequency in samples-per- -- second. -- - \c desired->format should be the desired audio format. -- - \c desired->samples is the desired size of the audio buffer, in -- samples. This number should be a power of two, and may be adjusted by -- the audio driver to a value more suitable for the hardware. Good values -- seem to range between 512 and 8096 inclusive, depending on the -- application and CPU speed. Smaller values yield faster response time, -- but can lead to underflow if the application is doing heavy processing -- and cannot fill the audio buffer in time. A stereo sample consists of -- both right and left channels in LR ordering. -- Note that the number of samples is directly related to time by the -- following formula: \code ms = (samples*1000)/freq \endcode -- - \c desired->size is the size in bytes of the audio buffer, and is -- calculated by SDL_OpenAudio(). -- - \c desired->silence is the value used to set the buffer to silence, -- and is calculated by SDL_OpenAudio(). -- - \c desired->callback should be set to a function that will be called -- when the audio device is ready for more data. It is passed a pointer -- to the audio buffer, and the length in bytes of the audio buffer. -- This function usually runs in a separate thread, and so you should -- protect data structures that it accesses by calling SDL_LockAudio() -- and SDL_UnlockAudio() in your code. Alternately, you may pass a NULL -- pointer here, and call SDL_QueueAudio() with some frequency, to queue -- more audio samples to be played (or for capture devices, call -- SDL_DequeueAudio() with some frequency, to obtain audio samples). -- - \c desired->userdata is passed as the first parameter to your callback -- function. If you passed a NULL callback, this value is ignored. -- -- The audio device starts out playing silence when it's opened, and should -- be enabled for playing by calling \c SDL_PauseAudio(0) when you are ready -- for your audio callback function to be called. Since the audio driver -- may modify the requested size of the audio buffer, you should allocate -- any local mixing buffers after you open the audio device. function SDL_OpenAudio ( desired : AudioSpec_ptr; obtained : AudioSpec_ptr) return C.int; pragma Import (C, SDL_OpenAudio, "SDL_OpenAudio"); -- ========================================================================== -- SDL Audio Device IDs: -- A successful call to SDL_OpenAudio() is always device id 1, and legacy -- SDL audio APIs assume you want this device ID. SDL_OpenAudioDevice() calls -- always returns devices >= 2 on success. The legacy calls are good both -- for backwards compatibility and when you don't care about multiple, -- specific, or capture devices. -- ========================================================================== -- Get the number of available devices exposed by the current driver. -- Only valid after a successfully initializing the audio subsystem. -- Returns -1 if an explicit list of devices can't be determined; this is -- not an error. For example, if SDL is set up to talk to a remote audio -- server, it can't list every one available on the Internet, but it will -- still allow a specific host to be specified to SDL_OpenAudioDevice(). -- -- In many common cases, when this function returns a value <= 0, it can still -- successfully open the default device (NULL for first argument of -- SDL_OpenAudioDevice()). function SDL_GetNumAudioDevices ( iscapture : C.int) return C.int; pragma Import (C, SDL_GetNumAudioDevices, "SDL_GetNumAudioDevices"); -- Get the human-readable name of a specific audio device. -- Must be a value between 0 and (number of audio devices-1). -- Only valid after a successfully initializing the audio subsystem. -- The values returned by this function reflect the latest call to -- SDL_GetNumAudioDevices(); recall that function to redetect available -- hardware. -- -- The string returned by this function is UTF-8 encoded, read-only, and -- managed internally. You are not to free it. If you need to keep the -- string for any length of time, you should make your own copy of it, as it -- will be invalid next time any of several other SDL functions is called. function SDL_GetAudioDeviceName ( index : C.int; iscapture : C.int) return C.Strings.chars_ptr; pragma Import (C, SDL_GetAudioDeviceName, "SDL_GetAudioDeviceName"); -- Open a specific audio device. Passing in a device name of NULL requests -- the most reasonable default (and is equivalent to calling SDL_OpenAudio()). -- -- The device name is a UTF-8 string reported by SDL_GetAudioDeviceName(), but -- some drivers allow arbitrary and driver-specific strings, such as a -- hostname/IP address for a remote audio server, or a filename in the -- diskaudio driver. -- -- \return 0 on error, a valid device ID that is >= 2 on success. -- -- SDL_OpenAudio(), unlike this function, always acts on device ID 1. function SDL_OpenAudioDevice ( device : C.Strings.chars_ptr; iscapture : C.int; desired : AudioSpec_ptr; obtained : AudioSpec_ptr; allowed_changes : C.int) return C.int; pragma Import (C, SDL_OpenAudioDevice, "SDL_OpenAudioDevice"); -- Get the current audio state: type audiostatus is new C.int; AUDIO_STOPED : constant := 0; AUDIO_PLAYING : constant := 1; AUDIO_PAUSED : constant := 2; function SDL_GetAudioStatus return audiostatus; pragma Import (C, SDL_GetAudioStatus, "SDL_GetAudioStatus"); function SDL_GetAudioDeviceStatus (dev : C.int) return audiostatus; pragma Import (C, SDL_GetAudioDeviceStatus, "SDL_GetAudioDeviceStatus"); -- These functions pause and unpause the audio callback processing. -- They should be called with a parameter of 0 after opening the audio -- device to start playing sound. This is so you can safely initialize -- data for your callback function after opening the audio device. -- Silence will be written to the audio device during the pause. procedure SDL_PauseAudio (pause_on : C.int); pragma Import (C, SDL_PauseAudio, "SDL_PauseAudio"); procedure SDL_PauseAudioDevice (device : C.int; pause_on : C.int); pragma Import (C, SDL_PauseAudioDevice, "SDL_PauseAudioDevice"); -- This function loads a WAVE from the data source, automatically freeing -- that source if \c freesrc is non-zero. For example, to load a WAVE file, -- you could do: -- \code -- SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...); -- \endcode -- -- If this function succeeds, it returns the given SDL_AudioSpec, -- filled with the audio data format of the wave data, and sets -- \c --audio_buf to a malloc()'d buffer containing the audio data, -- and sets \c --audio_len to the length of that audio buffer, in bytes. -- You need to free the audio buffer with SDL_FreeWAV() when you are -- done with it. -- -- This function returns NULL and sets the SDL error message if the -- wave file cannot be opened, uses an unknown data format, or is -- corrupt. Currently raw and MS-ADPCM WAVE files are supported. function SDL_LoadWAV_RW ( src : SDL.RWops.RWops; freesrc : C.int; spec : AudioSpec_ptr; audio_buf : Uint8_ptr_ptr; audio_len : Uint32_ptr) return AudioSpec_ptr; pragma Import (C, SDL_LoadWAV_RW, "SDL_LoadWAV_RW"); -- Loads a WAV from a file. -- Compatibility convenience function. function SDL_LoadWAV ( file : C.Strings.chars_ptr; spec : AudioSpec_ptr; audio_buf : Uint8_ptr_ptr; audio_len : Uint32_ptr) return AudioSpec_ptr; pragma Inline (SDL_LoadWAV); -- This function frees data previously allocated with SDL_LoadWAV_RW() procedure SDL_FreeWAV (audio_buf : Uint8_ptr); pragma Import (C, SDL_FreeWAV, "SDL_FreeWAV"); -- This function takes a source format and rate and a destination format -- and rate, and initializes the \c cvt structure with information needed -- by SDL_ConvertAudio() to convert a buffer of audio data from one format -- to the other. An unsupported format causes an error and -1 will be returned. -- -- \return 0 if no conversion is needed, 1 if the audio filter is set up, -- or -1 on error. function SDL_BuildAudioCVT ( cvt : AudioCVT_ptr; src_format : Uint16; src_channels : Uint8; src_rate : C.int; dst_format : Uint16; dst_channels : Uint8; dst_rate : C.int) return C.int; pragma Import (C, SDL_BuildAudioCVT, "SDL_BuildAudioCVT"); -- Once you have initialized the 'cvt' structure using BuildAudioCVT, -- created an audio buffer cvt.buf, and filled it with cvt.len bytes of -- audio data in the source format, this function will convert it in-place -- to the desired format. -- The data conversion may expand the size of the audio data, so the buffer -- cvt.buf should be allocated after the cvt structure is initialized by -- BuildAudioCVT, and should be cvt.len * cvt.len_mult bytes long. function SDL_ConvertAudio (cvt : AudioCVT_ptr) return C.int; pragma Import (C, SDL_ConvertAudio, "SDL_ConvertAudio"); -- ========================================================================= -- Incomplete: -- Needs mixer support -- Test: -- This takes two audio buffers of the playing audio format and mixes -- them, performing addition, volume adjustment, and overflow clipping. -- The volume ranges from 0 - 128, and should be set to _MIX_MAXVOLUME -- for full audio volume. Note this does not change hardware volume. -- This is provided for convenience -- you can mix your own audio data. MIX_MAXVOLUME : constant := 128; procedure MixAudio ( dst : Uint8_ptr; src : Uint8_ptr; len : Uint32; volume : C.int); pragma Import (c, MixAudio, "SDL_MixAudio"); -- ========================================================================= -- Queue more audio on non-callback devices. -- -- (If you are looking to retrieve queued audio from a non-callback capture -- device, you want SDL_DequeueAudio() instead. This will return -1 to -- signify an error if you use it with capture devices.) -- -- SDL offers two ways to feed audio to the device: you can either supply a -- callback that SDL triggers with some frequency to obtain more audio -- (pull method), or you can supply no callback, and then SDL will expect -- you to supply data at regular intervals (push method) with this function. -- -- There are no limits on the amount of data you can queue, short of -- exhaustion of address space. Queued data will drain to the device as -- necessary without further intervention from you. If the device needs -- audio but there is not enough queued, it will play silence to make up -- the difference. This means you will have skips in your audio playback -- if you aren't routinely queueing sufficient data. -- -- This function copies the supplied data, so you are safe to free it when -- the function returns. This function is thread-safe, but queueing to the -- same device from two threads at once does not promise which buffer will -- be queued first. -- -- You may not queue audio on a device that is using an application-supplied -- callback; doing so returns an error. You have to use the audio callback -- or queue audio with this function, but not both. -- -- You should not call SDL_LockAudio() on the device before queueing; SDL -- handles locking internally for this function. -- -- \param dev The device ID to which we will queue audio. -- \param data The data to queue to the device for later playback. -- \param len The number of bytes (not samples!) to which (data) points. -- \return 0 on success, or -1 on error. -- -- \sa SDL_GetQueuedAudioSize -- \sa SDL_ClearQueuedAudio function SDL_QueueAudio (device : C.int; data : Uint8_ptr; len : Uint32) return C.int; pragma Import (C, SDL_QueueAudio, "SDL_QueueAudio"); -- Dequeue more audio on non-callback devices. -- -- (If you are looking to queue audio for output on a non-callback playback -- device, you want SDL_QueueAudio() instead. This will always return 0 -- if you use it with playback devices.) -- -- SDL offers two ways to retrieve audio from a capture device: you can -- either supply a callback that SDL triggers with some frequency as the -- device records more audio data, (push method), or you can supply no -- callback, and then SDL will expect you to retrieve data at regular -- intervals (pull method) with this function. -- -- There are no limits on the amount of data you can queue, short of -- exhaustion of address space. Data from the device will keep queuing as -- necessary without further intervention from you. This means you will -- eventually run out of memory if you aren't routinely dequeueing data. -- -- Capture devices will not queue data when paused; if you are expecting -- to not need captured audio for some length of time, use -- SDL_PauseAudioDevice() to stop the capture device from queueing more -- data. This can be useful during, say, level loading times. When -- unpaused, capture devices will start queueing data from that point, -- having flushed any capturable data available while paused. -- -- This function is thread-safe, but dequeueing from the same device from -- two threads at once does not promise which thread will dequeued data -- first. -- -- You may not dequeue audio from a device that is using an -- application-supplied callback; doing so returns an error. You have to use -- the audio callback, or dequeue audio with this function, but not both. -- -- You should not call SDL_LockAudio() on the device before queueing; SDL -- handles locking internally for this function. -- -- \param dev The device ID from which we will dequeue audio. -- \param data A pointer into where audio data should be copied. -- \param len The number of bytes (not samples!) to which (data) points. -- \return number of bytes dequeued, which could be less than requested. -- -- \sa SDL_GetQueuedAudioSize -- \sa SDL_ClearQueuedAudio function SDL_DequeueAudio (device : C.int; data : Uint8_ptr; len : Uint32) return Uint32; pragma Import (C, SDL_DequeueAudio, "SDL_DequeueAudio"); -- Get the number of bytes of still-queued audio. -- -- For playback device: -- -- This is the number of bytes that have been queued for playback with -- SDL_QueueAudio(), but have not yet been sent to the hardware. This -- number may shrink at any time, so this only informs of pending data. -- -- Once we've sent it to the hardware, this function can not decide the -- exact byte boundary of what has been played. It's possible that we just -- gave the hardware several kilobytes right before you called this -- function, but it hasn't played any of it yet, or maybe half of it, etc. -- -- For capture devices: -- -- This is the number of bytes that have been captured by the device and -- are waiting for you to dequeue. This number may grow at any time, so -- this only informs of the lower-bound of available data. -- -- You may not queue audio on a device that is using an application-supplied -- callback; calling this function on such a device always returns 0. -- You have to queue audio with SDL_QueueAudio()/SDL_DequeueAudio(), or use -- the audio callback, but not both. -- -- You should not call SDL_LockAudio() on the device before querying; SDL -- handles locking internally for this function. -- -- \param dev The device ID of which we will query queued audio size. -- \return Number of bytes (not samples!) of queued audio. -- -- \sa SDL_QueueAudio -- \sa SDL_ClearQueuedAudio function SDL_GetQueuedAudioSize (device : C.int) return Uint32; pragma Import (C, SDL_GetQueuedAudioSize, "SDL_GetQueuedAudioSize"); -- Drop any queued audio data. For playback devices, this is any queued data -- still waiting to be submitted to the hardware. For capture devices, this -- is any data that was queued by the device that hasn't yet been dequeued by -- the application. -- -- Immediately after this call, SDL_GetQueuedAudioSize() will return 0. For -- playback devices, the hardware will start playing silence if more audio -- isn't queued. Unpaused capture devices will start filling the queue again -- as soon as they have more data available (which, depending on the state -- of the hardware and the thread, could be before this function call -- returns!). -- -- This will not prevent playback of queued audio that's already been sent -- to the hardware, as we can not undo that, so expect there to be some -- fraction of a second of audio that might still be heard. This can be -- useful if you want to, say, drop any pending music during a level change -- in your game. -- -- You may not queue audio on a device that is using an application-supplied -- callback; calling this function on such a device is always a no-op. -- You have to queue audio with SDL_QueueAudio()/SDL_DequeueAudio(), or use -- the audio callback, but not both. -- -- You should not call SDL_LockAudio() on the device before clearing the -- queue; SDL handles locking internally for this function. -- -- This function always succeeds and thus returns void. -- -- \param dev The device ID of which to clear the audio queue. -- -- \sa SDL_QueueAudio -- \sa SDL_GetQueuedAudioSize procedure SDL_ClearQueuedAudio (device : C.int); pragma Import (C, SDL_ClearQueuedAudio, "SDL_ClearQueuedAudio"); -- The lock manipulated by these functions protects the callback function. -- During a SDL_LockAudio()/SDL_UnlockAudio() pair, you can be guaranteed that -- the callback function is not running. Do not call these from the callback -- function or you will cause deadlock. procedure LockAudio; pragma Import (C, LockAudio, "SDL_LockAudio"); procedure SDL_LockAudioDevice (dev : C.int); pragma Import (C, SDL_LockAudioDevice, "SDL_LockAudioDevice"); procedure UnlockAudio; pragma Import (C, UnlockAudio, "SDL_UnlockAudio"); procedure SDL_UnlockAudioDevice (dev : C.int); pragma Import (C, SDL_UnlockAudioDevice, "SDL_UnlockAudioDevice"); -- This procedure shuts down audio processing and closes the audio device. procedure CloseAudio; pragma Import (C, CloseAudio, "SDL_CloseAudio"); procedure SDL_CloseAudioDevice (dev : C.int); pragma Import (C, SDL_CloseAudioDevice, "SDL_CloseAudioDevice"); end SDL.Audio;
with Ada.Unchecked_Deallocation; package body GNAT.Sockets is procedure Free is new Ada.Unchecked_Deallocation ( Ada.Streams.Stream_IO.File_Type, Socket_Type); function Addresses (E : Host_Entry_Type; N : Positive := 1) return Inet_Addr_Type is pragma Unreferenced (N); begin return ( Family => Family_Inet, Host_Name => Ada.Strings.Unbounded_Strings.To_Unbounded_String (String (E))); end Addresses; function Get_Host_By_Name (Name : String) return Host_Entry_Type is begin return Host_Entry_Type (Name); end Get_Host_By_Name; procedure Create_Socket ( Socket : out Socket_Type; Family : Family_Type := Family_Inet; Mode : Mode_Type := Socket_Stream) is pragma Unreferenced (Family); pragma Unreferenced (Mode); begin Socket := new Ada.Streams.Stream_IO.File_Type; end Create_Socket; procedure Close_Socket (Socket : in out Socket_Type) is begin Ada.Streams.Stream_IO.Close (Socket.all); Free (Socket); end Close_Socket; procedure Connect_Socket ( Socket : Socket_Type; Server : in out Sock_Addr_Type) is End_Point : constant Ada.Streams.Stream_IO.Sockets.End_Point := Ada.Streams.Stream_IO.Sockets.Resolve ( Ada.Strings.Unbounded_Strings.Constant_Reference ( Server.Addr.Host_Name).Element.all, Server.Port); begin Ada.Streams.Stream_IO.Sockets.Connect (Socket.all, End_Point); end Connect_Socket; procedure Receive_Socket ( Socket : Socket_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Flags : Request_Flag_Type := No_Request_Flag) is pragma Unreferenced (Flags); begin Ada.Streams.Stream_IO.Read (Socket.all, Item, Last); end Receive_Socket; function Stream (Socket : Socket_Type) return Stream_Access is begin return Ada.Streams.Stream_IO.Stream (Socket.all); end Stream; end GNAT.Sockets;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- L I B . W R I T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the routines for writing the library information package Lib.Writ is ----------------------------------- -- Format of Library Information -- ----------------------------------- -- This section describes the format of the library information that is -- associated with object files. The exact method of this association is -- potentially implementation dependent and is described and implemented in -- package ali. From the point of view of the description here, all we need -- to know is that the information is represented as a string of characters -- that is somehow associated with an object file, and can be retrieved. If -- no library information exists for a given object file, then we take this -- as equivalent to the non-existence of the object file, as if source file -- has not been previously compiled. -- The library information is written as a series of lines of the form: -- Key_Character parameter parameter ... -- The following sections describe the format of these lines in detail -------------------------------------- -- Making Changes to the ALI Format -- -------------------------------------- -- A number of tools use ali.adb to parse ali files. This means that -- changes to this format can cause old versions of these tools to be -- incompatible with new versions of the compiler. Any changes to ali file -- formats must be carefully evaluated to understand any such possible -- conflicts, and in particular, it is very undesirable to create conflicts -- between older versions of GNAT Studio and newer versions of the -- compiler. -- If the following guidelines are respected, downward compatibility -- problems (old tools reading new ali files) should be minimized: -- The basic key character format must be kept -- The V line must be the first line, this is checked by ali.adb even in -- Ignore_Errors mode, and is used to verify that the file at hand is -- indeed likely intended to be an ali file. -- The P line must be present, though may be modified in contents -- according to remaining guidelines. Again, ali.adb assumes the P -- line is present even in Ignore_Errors mode. -- New modifiers can generally be added (in particular adding new two -- letter modifiers to the P or U lines is always safe) -- Adding entirely new lines (with a new key letter) to the ali file is -- always safe, at any point (other than before the V line), since such -- lines will be ignored. -- Following the guidelines in this section should ensure that this problem -- is minimized and that old tools will be able to deal successfully with -- new ali formats. Note that this does not apply to the compiler itself, -- which always requires consistency between the ali files and the binder. -- That is because one of the main functions of the binder is to ensure -- consistency of the partition, and this can be compromised if the ali -- files are inconsistent. ------------------ -- Header Lines -- ------------------ -- The initial header lines in the file give information about the -- compilation environment, and identify other special information such as -- main program parameters. -- ---------------- -- -- V Version -- -- ---------------- -- V "xxxxxxxxxxxxxxxx" -- -- This line indicates the library output version, as defined in -- Gnatvsn. It ensures that separate object modules of a program are -- consistent. It has to be changed if anything changes which would -- affect successful binding of separately compiled modules. Examples -- of such changes are modifications in the format of the library info -- described in this package, or modifications to calling sequences, or -- to the way that data is represented. -- Note: the V line absolutely must be the first line, and no change -- to the ALI format should change this, since even in Ignore_Errors -- mode, Scan_ALI insists on finding a V line. -- --------------------- -- -- M Main Program -- -- --------------------- -- M type [priority] [T=time-slice] [C=cpu] W=? -- This line appears only if the main unit for this file is suitable -- for use as a main program. The parameters are: -- type -- P for a parameterless procedure -- F for a function returning a value of integral type -- (used for writing a main program returning an exit status) -- priority -- Present only if there was a valid pragma Priority in the -- corresponding unit to set the main task priority. It is an -- unsigned decimal integer. -- T=time-slice -- Present only if there was a valid pragma Time_Slice in the -- corresponding unit. It is an unsigned decimal integer in the -- range 0 .. 10**9 giving the time slice value in units of -- milliseconds. The actual significance of this parameter is -- target dependent. -- C=cpu -- Present only if there was a valid pragma CPU in the -- corresponding unit to set the main task affinity. It is an -- unsigned decimal integer. -- W=? -- This parameter indicates the wide character encoding method used -- when compiling the main program file. The ? character is the -- single character used in the -gnatW? switch. This is used to -- provide the default wide-character encoding for Wide_Text_IO -- files. -- ----------------- -- -- A Argument -- -- ----------------- -- A argument -- One of these lines appears for each of the arguments present in the -- call to the gnat1 program. This can be used if it is necessary to -- reconstruct this call (e.g. for fix and continue). -- ------------------- -- -- P Parameters -- -- ------------------- -- P <<parameters>> -- Indicates various information that applies to the compilation of the -- corresponding source file. Parameters is a sequence of zero or more -- two letter codes that indicate configuration pragmas and other -- parameters that apply: -- The arguments are as follows: -- CE Compilation errors. If this is present it means that the ali -- file resulted from a compilation with the -gnatQ switch set, -- and illegalities were detected. The ali file contents may -- not be completely reliable, but the format will be correct -- and complete. Note that NO is always present if CE is -- present. -- DB Detect_Blocking pragma is in effect for all units in this -- file. -- Ex A valid Partition_Elaboration_Policy pragma applies to all -- the units in this file, where x is the first character -- (upper case) of the policy name (e.g. 'C' for Concurrent). -- FX Units in this file use front-end exceptions, with explicit -- handlers to trigger AT-END actions on exception paths. -- GP Set if this compilation was done in GNATprove mode, either -- from direct use of GNATprove, or from use of -gnatdF. -- Lx A valid Locking_Policy pragma applies to all the units in -- this file, where x is the first character (upper case) of -- the policy name (e.g. 'C' for Ceiling_Locking). -- NO No object. This flag indicates that the units in this file -- were not compiled to produce an object. This can occur as a -- result of the use of -gnatc, or if no object can be produced -- (e.g. when a package spec is compiled instead of the body, -- or a subunit on its own). Note that in GNATprove mode, we -- do produce an object. The object is not suitable for binding -- and linking, but we do not set NO, instead we set GP. -- NR No_Run_Time. Indicates that a pragma No_Run_Time applies -- to all units in the file. -- NS Normalize_Scalars pragma in effect for all units in -- this file. -- OH Pragma Default_Scalar_Storage_Order (High_Order_First) is -- present in a configuration pragma file that applies. -- OL Pragma Default_Scalar_Storage_Order (Low_Order_First) is -- present in a configuration pragma file that applies. -- Qx A valid Queueing_Policy pragma applies to all the units -- in this file, where x is the first character (upper case) -- of the policy name (e.g. 'P' for Priority_Queueing). -- SL Indicates that the unit is an Interface to a Standalone -- Library. Note that this indication is never given by the -- compiler, but is added by the Project Manager in gnatmake -- when an Interface ALI file is copied to the library -- directory. -- SS This unit references System.Secondary_Stack (that is, -- the unit makes use of the secondary stack facilities). -- Tx A valid Task_Dispatching_Policy pragma applies to all -- the units in this file, where x is the first character -- (upper case) of the corresponding policy name (e.g. 'F' -- for FIFO_Within_Priorities). -- UA Unreserve_All_Interrupts pragma was processed in one or -- more units in this file -- ZX Units in this file use zero-cost exceptions and have -- generated exception tables. If ZX is not present, the -- longjmp/setjmp exception scheme is in use. -- Note that language defined units never output policy (Lx, Tx, Qx) -- parameters. Language defined units must correctly handle all -- possible cases. These values are checked for consistency by the -- binder and then copied to the generated binder output file. -- Note: The P line must be present. Even in Ignore_Errors mode, Scan_ALI -- insists on finding a P line. So if changes are made to the ALI format, -- they should not include removing the P line. -- --------------------- -- -- R Restrictions -- -- --------------------- -- There are two forms for R lines, positional and named. The positional -- notation is now considered obsolescent, it is not generated by the most -- recent versions of the compiler except under control of the debug switch -- -gnatdR, but is still recognized by the binder. -- The recognition by the binder is to ease the transition, and better deal -- with some cases of inconsistent builds using incompatible versions of -- the compiler and binder. The named notation is the current preferred -- approach. -- Note that R lines are generated using the information in unit Rident, -- and intepreted by the binder using the information in System.Rident. -- Normally these two units should be effectively identical. However in -- some cases of inconsistent builds, they may be different. This may lead -- to binder diagnostics, which can be suppressed using the -C switch for -- the binder, which results in ignoring unrecognized restrictions in the -- ali files. -- --------------------------------------- -- -- R Restrictions (Positional Form) -- -- --------------------------------------- -- The first R line records the status of restrictions generated by pragma -- Restrictions encountered, as well as information on what the compiler -- has been able to determine with respect to restrictions violations. -- The format is: -- R <<restriction-characters>> <<restriction-param-id-entries>> -- The first parameter is a string of characters that records -- information regarding restrictions that do not take parameter not -- take parameter values. It is a string of characters, one character -- for each value (in order) in All_Boolean_Restrictions. There are -- three possible settings for each restriction: -- r Restricted. Unit was compiled under control of a pragma -- Restrictions for the corresponding restriction. In this case -- the unit certainly does not violate the Restriction, since -- this would have been detected by the compiler. -- n Not used. The unit was not compiled under control of a pragma -- Restrictions for the corresponding restriction, and does not -- make any use of the referenced feature. -- v Violated. The unit was not compiled under control of a pragma -- Restrictions for the corresponding restriction, and it does -- indeed use the referenced feature. -- This information is used in the binder to check consistency, i.e. to -- detect cases where one unit has "r" and another unit has "v", which -- is not permitted, since these restrictions are partition-wide. -- The second parameter, which immediately follows the first (with no -- separating space) gives restriction information for identifiers for -- which a parameter is given. -- The parameter is a string of entries, one for each value in -- Restrict.All_Parameter_Restrictions. Each entry has two components -- in sequence, the first indicating whether or not there is a -- restriction, and the second indicating whether or not the compiler -- detected violations. In the boolean case it is not necessary to -- separate these, since if a restriction is set, and violated, that is -- an error. But in the parameter case, this is not true. For example, -- we can have a unit with a pragma Restrictions (Max_Tasks => 4), -- where the compiler can detect that there are exactly three tasks -- declared. Both of these pieces of information must be passed to the -- binder. The parameter of 4 is important in case the total number of -- tasks in the partition is greater than 4. The parameter of 3 is -- important in case some other unit has a restrictions pragma with -- Max_Tasks=>2. -- The component for the presence of restriction has one of two -- possible forms: -- n No pragma for this restriction is present in the set of units -- for this ali file. -- rN At least one pragma for this restriction is present in the -- set of units for this ali file. The value N is the minimum -- parameter value encountered in any such pragma. N is in the -- range of Integer (a value larger than N'Last causes the -- pragma to be ignored). -- The component for the violation detection has one of three -- possible forms: -- n No violations were detected by the compiler -- vN A violation was detected. N is either the maximum or total -- count of violations (depending on the checking type) in all -- the units represented by the ali file). Note that this -- setting is only allowed for restrictions that are in -- Checked_[Max|Sum]_Parameter_Restrictions. The value here is -- known to be exact by the compiler and is in the range of -- Natural. -- vN+ A violation was detected. The compiler cannot determine -- the exact count of violations, but it is at least N. -- There are no spaces within the parameter string, so the entry -- described above in the header of this section for Max_Tasks would -- appear as the string r4v3. -- Note: The restrictions line is required to be present. Even in -- Ignore_Errors mode, Scan_ALI expects to find an R line and will -- signal a fatal error if it is missing. This means that future -- changes to the ALI file format must retain the R line. -- ---------------------------------- -- -- R Restrictions (Named Form) -- -- ---------------------------------- -- The first R line for named form announces that named notation will be -- used, and also assures that there is at least one R line present, which -- makes parsing of ali files simpler. A blank line preceds the RN line. -- RN -- In named notation, the restrictions are given as a series of lines, -- one per restrictions that is specified or violated (no information is -- present for restrictions that are not specified or violated). In the -- following name is the name of the restriction in all upper case. -- For boolean restrictions, we have only two possibilities. A restrictions -- pragma is present, or a violation is detected: -- RR name -- A restriction pragma is present for the named boolean restriction. -- No violations were detected by the compiler (or the unit in question -- would have been found to be illegal). -- RV name -- No restriction pragma is present for the named boolean restriction. -- However, the compiler did detect one or more violations of this -- restriction, which may require a binder consistency check. Note that -- one case of a violation is the use of a Restriction_Set attribute for -- the restriction that yielded False. -- For the case of restrictions that take a parameter, we need both the -- information from pragma if present, and the actual information about -- what possible violations occur. For example, we can have a unit with -- a pragma Restrictions (Max_Tasks => 4), where the compiler can detect -- that there are exactly three tasks declared. Both of these pieces -- of information must be passed to the binder. The parameter of 4 is -- important in case the total number of tasks in the partition is greater -- than 4. The parameter of 3 is important in case some other unit has a -- restrictions pragma with Max_Tasks=>2. -- RR name=N -- A restriction pragma is present for the named restriction which is -- one of the restrictions taking a parameter. The value N (a decimal -- integer) is the value given in the restriction pragma. -- RV name=N -- A restriction pragma may or may not be present for the restriction -- given by name (one of the restrictions taking a parameter). But in -- either case, the compiler detected possible violations. N (a decimal -- integer) is the maximum or total count of violations (depending -- on the checking type) in all the units represented by the ali file). -- The value here is known to be exact by the compiler and is in the -- range of Natural. Note that if an RR line is present for the same -- restriction, then the value in the RV line cannot exceed the value -- in the RR line (since otherwise the compiler would have detected a -- violation of the restriction). -- RV name=N+ -- Similar to the above, but the compiler cannot determine the exact -- count of violations, but it is at least N. -- ------------------------------------------------- -- -- R Restrictions (No_Dependence Information) -- -- ------------------------------------------------- -- Subsequent R lines are present only if pragma Restriction No_Dependence -- is used. There is one such line for each such pragma appearing in the -- extended main unit. The format is: -- R unit_name -- Here the unit name is in all lower case. The components of the unit -- name are separated by periods. The names themselves are in encoded -- form, as documented in Namet. -- ------------------------- -- -- I Interrupt States -- -- ------------------------- -- I interrupt-number interrupt-state line-number -- This line records information from an Interrupt_State pragma. There -- is one line for each separate pragma, and if no such pragmas are -- used, then no I lines are present. -- The interrupt-number is an unsigned positive integer giving the -- value of the interrupt as defined in Ada.Interrupts.Names. -- The interrupt-state is one of r/s/u for Runtime/System/User -- The line number is an unsigned decimal integer giving the line -- number of the corresponding Interrupt_State pragma. This is used -- in consistency messages. -- -------------------------------------- -- -- S Priority Specific Dispatching -- -- -------------------------------------- -- S policy_identifier first_priority last_priority line-number -- This line records information from a Priority_Specific_Dispatching -- pragma. There is one line for each separate pragma, and if no such -- pragmas are used, then no S lines are present. -- The policy_identifier is the first character (upper case) of the -- corresponding policy name (e.g. 'F' for FIFO_Within_Priorities). -- The first_priority and last_priority fields define the range of -- priorities to which the specified dispatching policy apply. -- The line number is an unsigned decimal integer giving the line -- number of the corresponding Priority_Specific_Dispatching pragma. -- This is used in consistency messages. ---------------------------- -- Compilation Unit Lines -- ---------------------------- -- Following these header lines, a set of information lines appears for -- each compilation unit that appears in the corresponding object file. In -- particular, when a package body or subprogram body is compiled, there -- will be two sets of information, one for the spec and one for the body, -- with the entry for the body appearing first. This is the only case in -- which a single ALI file contains more than one unit (in particular note -- that subunits do *not* count as compilation units for this purpose, and -- generate no library information, since they are inlined). -- -------------------- -- -- U Unit Header -- -- -------------------- -- The lines for each compilation unit have the following form -- U unit-name source-name version <<attributes>> -- This line identifies the unit to which this section of the library -- information file applies. The first three parameters are the unit -- name in internal format, as described in package Uname, and the name -- of the source file containing the unit. -- Version is the version given as eight hexadecimal characters with -- upper case letters. This value is the exclusive or of the source -- checksums of the unit and all its semantically dependent units. -- The <<attributes>> are a series of two letter codes indicating -- information about the unit: -- BD Unit does not have pragma Elaborate_Body, but the elaboration -- circuit has determined that it would be a good idea if this -- pragma were present, since the body of the package contains -- elaboration code that modifies one or more variables in the -- visible part of the package. The binder will try, but does -- not promise, to keep the elaboration of the body close to -- the elaboration of the spec. -- DE Dynamic Elaboration. This unit was compiled with the dynamic -- elaboration model, as set by either the -gnatE switch or -- pragma Elaboration_Checks (Dynamic). -- -- EB Unit has pragma Elaborate_Body, or is a generic instance that -- has a body. Set for instances because RM 12.3(20) requires -- that the body be immediately elaborated after the spec (we -- would normally do that anyway, because elaborate spec and -- body together whenever possible, and for an instance it is -- always possible; however setting EB ensures that this is done -- even when using the -p gnatbind switch). -- EE Elaboration entity is present which must be set true when -- the unit is elaborated. The name of the elaboration entity is -- formed from the unit name in the usual way. If EE is present, -- then this boolean must be set True as part of the elaboration -- processing routine generated by the binder. Note that EE can -- be set even if NE is set. This happens when the boolean is -- needed solely for checking for the case of access before -- elaboration. -- GE Unit is a generic declaration, or corresponding body -- -- IL Unit source uses a style with identifiers in all lower-case -- IU (IL) or all upper case (IU). If the standard mixed-case usage -- is detected, or the compiler cannot determine the style, then -- no I parameter will appear. -- IS Initialize_Scalars pragma applies to this unit, or else there -- is at least one use of the Invalid_Value attribute. -- KM Unit source uses a style with keywords in mixed case (KM) -- KU or all upper case (KU). If the standard lower-case usage is -- is detected, or the compiler cannot determine the style, then -- no K parameter will appear. -- NE Unit has no elaboration routine. All subprogram bodies and -- specs are in this category. Package bodies and specs may or -- may not have NE set, depending on whether or not elaboration -- code is required. Set if N_Compilation_Unit node has flag -- Has_No_Elaboration_Code set. -- OL The units in this file are compiled with a local pragma -- Optimize_Alignment, so no consistency requirement applies -- to these units. All internal units have this status since -- they have an automatic default of Optimize_Alignment (Off). -- -- OO Optimize_Alignment (Off) is the default setting for all -- units in this file. All files in the partition that specify -- a default must specify the same default. -- OS Optimize_Alignment (Space) is the default setting for all -- units in this file. All files in the partition that specify -- a default must specify the same default. -- OT Optimize_Alignment (Time) is the default setting for all -- units in this file. All files in the partition that specify -- a default must specify the same default. -- PF The unit has a library-level (package) finalizer -- PK Unit is package, rather than a subprogram -- PU Unit has pragma Pure -- PR Unit has pragma Preelaborate -- RA Unit declares a Remote Access to Class-Wide (RACW) type -- RC Unit has pragma Remote_Call_Interface -- RT Unit has pragma Remote_Types -- SE Compilation of unit encountered one or more serious errors. -- Normally the generation of an ALI file is suppressed if there -- is a serious error, but this can be overridden with -gnatQ. -- SP Unit has pragma Shared_Passive -- SU Unit is a subprogram, rather than a package -- The attributes may appear in any order, separated by spaces -- ----------------------------- -- -- W, Y and Z Withed Units -- -- ----------------------------- -- Following each U line, is a series of lines of the form -- W unit-name [source-name lib-name] [E] [EA] [ED] [AD] -- or -- Y unit-name [source-name lib-name] [E] [EA] [ED] [AD] -- or -- Z unit-name [source-name lib-name] [E] [EA] [ED] [AD] -- One W line is present for each unit that is mentioned in an explicit -- nonlimited with clause by the current unit. One Y line is present -- for each unit that is mentioned in an explicit limited with clause -- by the current unit. One Z line is present for each unit that is -- only implicitly withed by the current unit. The first parameter is -- the unit name in internal format. The second parameter is the file -- name of the file that must be compiled to compile this unit. It is -- usually the file for the body, except for packages which have no -- body. For units that need a body, if the source file for the body -- cannot be found, the file name of the spec is used instead. The -- third parameter is the file name of the library information file -- that contains the results of compiling this unit. The optional -- modifiers are used as follows: -- E pragma Elaborate applies to this unit -- EA pragma Elaborate_All applies to this unit -- ED Elaborate_Desirable set for this unit, which means that there -- is no Elaborate, but the analysis suggests that Program_Error -- may be raised if the Elaborate conditions cannot be satisfied. -- The binder will attempt to treat ED as E if it can. -- AD Elaborate_All_Desirable set for this unit, which means that -- there is no Elaborate_All, but the analysis suggests that -- Program_Error may be raised if the Elaborate_All conditions -- cannot be satisfied. The binder will attempt to treat AD as -- EA if it can. -- The parameter source-name and lib-name are omitted for the case of a -- generic unit compiled with earlier versions of GNAT which did not -- generate object or ali files for generics. For compatibility in the -- bootstrap path we continue to omit these entries for predefined -- generic units, even though we do now generate object and ali files. -- However, in SPARK mode, we always generate source-name and lib-name -- parameters. Bootstrap issues do not apply there, and we need this -- information to properly compute frame conditions of subprograms. -- The parameter source-name and lib-name are also omitted for the W -- lines that result from use of a Restriction_Set attribute which gets -- a result of False from a No_Dependence check, in the case where the -- unit is not in the semantic closure. In such a case, the bare W -- line is generated, but no D (dependency) line. This will make the -- binder do the consistency check, but not include the unit in the -- partition closure (unless it is properly With'ed somewhere). -- -------------------- -- -- T Task Stacks -- -- -------------------- -- Following the W lines (if any, or the U line if not), is an optional -- line that identifies the number of default-sized primary and secondary -- stacks that the binder needs to create for the tasks declared within the -- unit. For each compilation unit, a line is present in the form: -- T primary-stack-quantity secondary-stack-quantity -- The first parameter of T defines the number of task objects declared -- in the unit that have no Storage_Size specified. The second parameter -- defines the number of task objects declared in the unit that have no -- Secondary_Stack_Size specified. These values are non-zero only if -- the restrictions No_Implicit_Heap_Allocations or -- No_Implicit_Task_Allocations are active. -- ----------------------- -- -- L Linker_Options -- -- ----------------------- -- Following the T and W lines (if any, or the U line if not), are -- an optional series of lines that indicates the usage of the pragma -- Linker_Options in the associated unit. For each appearance of a pragma -- Linker_Options (or Link_With) in the unit, a line is present with the -- form: -- L "string" -- where string is the string from the unit line enclosed in quotes. -- Within the quotes the following can occur: -- c graphic characters in range 20-7E other than " or { -- "" indicating a single " character -- {hh} indicating a character whose code is hex hh (0-9,A-F) -- {00} [ASCII.NUL] is used as a separator character -- to separate multiple arguments of a single -- Linker_Options pragma. -- For further details, see Stringt.Write_String_Table_Entry. Note that -- wide characters in the form {hhhh} cannot be produced, since pragma -- Linker_Option accepts only String, not Wide_String. -- The L lines are required to appear in the same order as the -- corresponding Linker_Options (or Link_With) pragmas appear in the -- source file, so that this order is preserved by the binder in -- constructing the set of linker arguments. -- Note: Linker_Options lines never appear in the ALI file generated for -- a predefined generic unit, and there is cicuitry in Sem_Prag to enforce -- this restriction, which is needed because of not generating source name -- and lib name parameters on the with lines for such files, as explained -- above in the section on with lines. -- -------------- -- -- N Notes -- -- -------------- -- The final section of unit-specific lines contains notes which record -- annotations inserted in source code for processing by external tools -- using pragmas. For each occurrence of any of these pragmas, a line is -- generated with the following syntax: -- N x<sloc> [<arg_id>:]<arg> ... -- x is one of: -- A pragma Annotate -- C pragma Comment -- I pragma Ident -- T pragma Title -- S pragma Subtitle -- <sloc> is the source location of the pragma in line:col[:filename] -- format. The file name is omitted if it is the same as the current -- unit (it therefore appears explicitly in the case of pragmas -- occurring in subunits, which do not have U sections of their own). -- Successive entries record the pragma_argument_associations. -- If a pragma argument identifier is present, the entry is prefixed -- with the pragma argument identifier <arg_id> followed by a colon. -- <arg> represents the pragma argument, and has the following -- conventions: -- - identifiers are output verbatim -- - static string expressions are output as literals encoded as -- for L lines -- - static integer expressions are output as decimal literals -- - any other expression is replaced by the placeholder "<expr>" --------------------- -- Reference Lines -- --------------------- -- The reference lines contain information about references from any of the -- units in the compilation (including body version and version attributes, -- linker options pragmas and source dependencies). -- ------------------------------------ -- -- E External Version References -- -- ------------------------------------ -- One of these lines is present for each use of 'Body_Version or 'Version -- in any of the units of the compilation. These are used by the linker to -- determine which version symbols must be output. The format is simply: -- E name -- where name is the external name, i.e. the unit name with either a S or a -- B for spec or body version referenced (Body_Version always references -- the body, Version references the Spec, except in the case of a reference -- to a subprogram with no separate spec). Upper half and wide character -- codes are encoded using the same method as in Namet (Uhh for upper half, -- Whhhh for wide character, where hh are hex digits). -- --------------------- -- -- D Dependencies -- -- --------------------- -- The dependency lines indicate the source files on which the compiled -- units depend. This is used by the binder for consistency checking. -- These lines are also referenced by the cross-reference information. -- D source-name time-stamp checksum (sub)unit-name line:file-name -- source-name also includes preprocessing data file and preprocessing -- definition file. These preprocessing files may be given as full -- path names instead of simple file names. If a full path name -- includes a directory with spaces, the path name is quoted (quote -- characters (") added at start and end, and any internal quotes are -- doubled). -- The time-stamp field contains the time stamp of the corresponding -- source file. See types.ads for details on time stamp representation. -- The checksum is an 8-hex digit representation of the source file -- checksum, with letters given in lower case. -- If the unit is not a subunit, the (sub)unit name is the unit name in -- internal format, as described in package Uname. If the unit is a -- subunit, the (sub)unit name is the fully qualified name of the -- subunit in all lower case letters. -- The line:file-name entry is present only if a Source_Reference -- pragma appeared in the source file identified by source-name. In -- this case, it gives the information from this pragma. Note that this -- allows cross-reference information to be related back to the -- original file. Note: the reason the line number comes first is that -- a leading digit immediately identifies this as a Source_Reference -- entry, rather than a subunit-name. -- A line number of zero for line: in this entry indicates that there -- is more than one source reference pragma. In this case, the line -- numbers in the cross-reference are correct, and refer to the -- original line number, but there is no information that allows a -- reader of the ALI file to determine the exact mapping of physical -- line numbers back to the original source. -- Files with a zero checksum and a non-zero time stamp are in general -- files on which the compilation depends but which are not Ada files -- with further dependencies. This includes preprocessor data files -- and preprocessor definition files. -- Note: blank lines are ignored when the library information is read, -- and separate sections of the file are separated by blank lines to -- ease readability. Blanks between fields are also ignored. -- For entries corresponding to files that were not present (and thus -- resulted in error messages), or for files that are not part of the -- dependency set, both the time stamp and checksum are set to all zero -- characters. These dummy entries are ignored by the binder in -- dependency checking, but must be present for proper interpretation -- of the cross-reference data. -- ------------------------- -- -- G Invocation Graph -- -- ------------------------- -- An invocation graph line has the following format: -- -- G line-kind line-attributes -- -- Attribute line-kind is a Character which denotes the nature of the -- line. Table ALI.Invocation_Graph_Line_Codes lists all legal values. -- -- Attribute line-attributes depends on the value of line-kind, and is -- contents are described further below. -- -- An invocation signature uniquely identifies an invocation construct in -- the ALI file namespace, and has the following format: -- -- [ name scope line column (locations | "none") ] -- -- Attribute name is a String which denotes the name of the construct -- -- Attribute scope is a String which denotes the qualified name of the -- scope where the construct is declared. -- -- Attribute line is a Positive which denotes the line number where the -- initial declaration of the construct appears. -- -- Attribute column is a Positive which denotes the column number where -- the initial declaration of the construct appears. -- -- Attribute locations is a String which denotes the line and column -- locations of all instances where the initial declaration of the -- construct appears. -- -- When the line-kind denotes invocation graph attributes, line-attributes -- are set as follows: -- -- encoding-kind -- -- Attribute encoding-kind is a Character which specifies the encoding -- kind used when collecting invocation constructs and relations. Table -- ALI.Invocation_Graph_Encoding_Codes lists all legal values. -- -- When the line-kind denotes an invocation construct, line-attributes are -- set as follows: -- -- construct-kind construct-spec-placement construct-body-placement -- construct-signature -- -- Attribute construct-kind is a Character which denotes the nature of -- the construct. Table ALI.Invocation_Construct_Codes lists all legal -- values. -- -- Attribute construct-spec-placement is a Character which denotes the -- placement of the construct's spec within the unit. All legal values -- are listed in table ALI.Spec_And_Body_Placement_Codes. -- -- Attribute construct-body-placement is a Character which denotes the -- placement of the construct's body within the unit. All legal values -- are listed in table ALI.Spec_And_Body_Placement_Codes. -- -- Attribute construct-signature is the invocation signature of the -- construct. -- -- When the line-kind denotes an invocation relation, line-attributes are -- set as follows: -- -- relation-kind (extra-name | "none") invoker-signature -- target-signature -- -- Attribute relation-kind is a Character which denotes the nature of -- the relation. All legal values are listed in ALI.Invocation_Codes. -- -- Attribute extra-name is a String which denotes the name of an extra -- entity used for error diagnostics. The value of extra-name depends -- on the relation-kind as follows: -- -- Accept_Alternative - related entry -- Access_Taken - related subprogram -- Call - not present -- Controlled_Adjustment - related controlled type -- Controlled_Finalization - related controlled type -- Controlled_Initialization - related controlled type -- Default_Initial_Condition_Verification - related private type -- Initial_Condition_Verification - not present -- Instantiation - not present -- Internal_Controlled_Adjustment - related controlled type -- Internal_Controlled_Finalization - related controlled type -- Internal_Controlled_Initialization - related controlled type -- Invariant_Verification - related private type -- Postcondition_Verification - related routine -- Protected_Entry_Call - not present -- Protected_Subprogram_Call - not present -- Task_Activation - not present -- Task_Entry_Call - not present -- Type_Initialization - related type -- -- Attribute invoker-signature is the invocation signature of the -- invoker. -- -- Attribute target-signature is the invocation signature of the target -------------------------- -- Cross-Reference Data -- -------------------------- -- The cross-reference data follows the dependency lines. See the spec of -- Lib.Xref in file lib-xref.ads for details on the format of this data. --------------------------------- -- Source Coverage Obligations -- --------------------------------- -- The Source Coverage Obligation (SCO) information follows the cross- -- reference data. See the spec of Par_SCO in file par_sco.ads for full -- details of the format. --------------------------------------- -- SPARK Cross-Reference Information -- --------------------------------------- -- The SPARK cross-reference information follows the SCO information. See -- the spec of SPARK_Xrefs in file spark_xrefs.ads for full details of the -- format. ------------------------------- -- ALI File Generation for C -- ------------------------------- -- The C compiler can also generate ALI files for use by the IDE's in -- providing navigation services in C. These ALI files are a subset of -- the specification above, lacking all Ada-specific output. Primarily -- the IDE uses the cross-reference sections of such files. ---------------------- -- Global Variables -- ---------------------- -- The table defined here stores one entry for each Interrupt_State pragma -- encountered either in the main source or in an ancillary with'ed source. -- Since interrupt state values have to be consistent across all units in a -- partition, we detect inconsistencies at compile time when we can. type Interrupt_State_Entry is record Interrupt_Number : Pos; -- Interrupt number value Interrupt_State : Character; -- Set to r/s/u for Runtime/System/User Pragma_Loc : Source_Ptr; -- Location of pragma setting this value in place end record; package Interrupt_States is new Table.Table ( Table_Component_Type => Interrupt_State_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 30, Table_Increment => 200, Table_Name => "Name_Interrupt_States"); -- The table structure defined here stores one entry for each -- Priority_Specific_Dispatching pragma encountered either in the main -- source or in an ancillary with'ed source. Since have to be consistent -- across all units in a partition, we may as well detect inconsistencies -- at compile time when we can. type Specific_Dispatching_Entry is record Dispatching_Policy : Character; -- First character (upper case) of the corresponding policy name First_Priority : Nat; -- Lower bound of the priority range to which the specified dispatching -- policy applies. Last_Priority : Nat; -- Upper bound of the priority range to which the specified dispatching -- policy applies. Pragma_Loc : Source_Ptr; -- Location of pragma setting this value in place end record; package Specific_Dispatching is new Table.Table ( Table_Component_Type => Specific_Dispatching_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => 10, Table_Increment => 100, Table_Name => "Name_Priority_Specific_Dispatching"); ----------------- -- Subprograms -- ----------------- procedure Ensure_System_Dependency; -- This procedure ensures that a dependency is created on system.ads. Even -- if there is no semantic dependency, Targparm has read the file to -- acquire target parameters, so we need a source dependency. procedure Write_ALI (Object : Boolean); -- This procedure writes the library information for the current main unit -- The Object parameter is true if an object file is created, and false -- otherwise. Note that the pseudo-object file generated in GNATprove mode -- does count as an object file from this point of view. -- -- Note: in the case where we are not generating code (-gnatc mode), this -- routine only writes an ALI file if it cannot find an existing up to -- date ALI file. If it *can* find an existing up to date ALI file, then -- it reads this file and sets the Lib.Compilation_Arguments table from -- the A lines in this file. procedure Add_Preprocessing_Dependency (S : Source_File_Index); -- Indicate that there is a dependency to be added on a preprocessing data -- file or on a preprocessing definition file. end Lib.Writ;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . E X C E P T I O N _ T A B L E -- -- -- -- B o d y -- -- -- -- Copyright (C) 1996-2005 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System.HTable; with System.Soft_Links; use System.Soft_Links; package body System.Exception_Table is use System.Standard_Library; type HTable_Headers is range 1 .. 37; procedure Set_HT_Link (T : Exception_Data_Ptr; Next : Exception_Data_Ptr); function Get_HT_Link (T : Exception_Data_Ptr) return Exception_Data_Ptr; function Hash (F : System.Address) return HTable_Headers; function Equal (A, B : System.Address) return Boolean; function Get_Key (T : Exception_Data_Ptr) return System.Address; package Exception_HTable is new System.HTable.Static_HTable ( Header_Num => HTable_Headers, Element => Exception_Data, Elmt_Ptr => Exception_Data_Ptr, Null_Ptr => null, Set_Next => Set_HT_Link, Next => Get_HT_Link, Key => System.Address, Get_Key => Get_Key, Hash => Hash, Equal => Equal); ----------- -- Equal -- ----------- function Equal (A, B : System.Address) return Boolean is S1 : constant Big_String_Ptr := To_Ptr (A); S2 : constant Big_String_Ptr := To_Ptr (B); J : Integer := 1; begin loop if S1 (J) /= S2 (J) then return False; elsif S1 (J) = ASCII.NUL then return True; else J := J + 1; end if; end loop; end Equal; ----------------- -- Get_HT_Link -- ----------------- function Get_HT_Link (T : Exception_Data_Ptr) return Exception_Data_Ptr is begin return T.HTable_Ptr; end Get_HT_Link; ------------- -- Get_Key -- ------------- function Get_Key (T : Exception_Data_Ptr) return System.Address is begin return T.Full_Name; end Get_Key; ------------------------------- -- Get_Registered_Exceptions -- ------------------------------- procedure Get_Registered_Exceptions (List : out Exception_Data_Array; Last : out Integer) is Data : Exception_Data_Ptr := Exception_HTable.Get_First; begin Lock_Task.all; Last := List'First - 1; while Last < List'Last and then Data /= null loop Last := Last + 1; List (Last) := Data; Data := Exception_HTable.Get_Next; end loop; Unlock_Task.all; end Get_Registered_Exceptions; ---------- -- Hash -- ---------- function Hash (F : System.Address) return HTable_Headers is type S is mod 2**8; Str : constant Big_String_Ptr := To_Ptr (F); Size : constant S := S (HTable_Headers'Last - HTable_Headers'First + 1); Tmp : S := 0; J : Positive; begin J := 1; loop if Str (J) = ASCII.NUL then return HTable_Headers'First + HTable_Headers'Base (Tmp mod Size); else Tmp := Tmp xor S (Character'Pos (Str (J))); end if; J := J + 1; end loop; end Hash; ------------------------ -- Internal_Exception -- ------------------------ function Internal_Exception (X : String; Create_If_Not_Exist : Boolean := True) return Exception_Data_Ptr is type String_Ptr is access all String; Copy : aliased String (X'First .. X'Last + 1); Res : Exception_Data_Ptr; Dyn_Copy : String_Ptr; begin Copy (X'Range) := X; Copy (Copy'Last) := ASCII.NUL; Res := Exception_HTable.Get (Copy'Address); -- If unknown exception, create it on the heap. This is a legitimate -- situation in the distributed case when an exception is defined only -- in a partition if Res = null and then Create_If_Not_Exist then Dyn_Copy := new String'(Copy); Res := new Exception_Data' (Not_Handled_By_Others => False, Lang => 'A', Name_Length => Copy'Length, Full_Name => Dyn_Copy.all'Address, HTable_Ptr => null, Import_Code => 0, Raise_Hook => null); Register_Exception (Res); end if; return Res; end Internal_Exception; ------------------------ -- Register_Exception -- ------------------------ procedure Register_Exception (X : Exception_Data_Ptr) is begin Exception_HTable.Set (X); end Register_Exception; --------------------------------- -- Registered_Exceptions_Count -- --------------------------------- function Registered_Exceptions_Count return Natural is Count : Natural := 0; Data : Exception_Data_Ptr := Exception_HTable.Get_First; begin -- We need to lock the runtime in the meantime, to avoid concurrent -- access since we have only one iterator. Lock_Task.all; while Data /= null loop Count := Count + 1; Data := Exception_HTable.Get_Next; end loop; Unlock_Task.all; return Count; end Registered_Exceptions_Count; ----------------- -- Set_HT_Link -- ----------------- procedure Set_HT_Link (T : Exception_Data_Ptr; Next : Exception_Data_Ptr) is begin T.HTable_Ptr := Next; end Set_HT_Link; -- Register the standard exceptions at elaboration time begin Register_Exception (Abort_Signal_Def'Access); Register_Exception (Tasking_Error_Def'Access); Register_Exception (Storage_Error_Def'Access); Register_Exception (Program_Error_Def'Access); Register_Exception (Numeric_Error_Def'Access); Register_Exception (Constraint_Error_Def'Access); end System.Exception_Table;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Sessions; with ADO.Model; with ADO.Objects; with ADO.SQL; package body ADO.Sequences.Hilo is use Util.Log; use ADO.Sessions; use ADO.Model; Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo"); type HiLoGenerator_Access is access all HiLoGenerator'Class; -- ------------------------------ -- Create a high low sequence generator -- ------------------------------ function Create_HiLo_Generator (Sess_Factory : in Session_Factory_Access) return Generator_Access is Result : constant HiLoGenerator_Access := new HiLoGenerator; begin Result.Factory := Sess_Factory; return Result.all'Access; end Create_HiLo_Generator; -- ------------------------------ -- Allocate an identifier using the generator. -- The generator allocates blocks of sequences by using a sequence -- table stored in the database. One database access is necessary -- every N allocations. -- ------------------------------ procedure Allocate (Gen : in out HiLoGenerator; Id : in out Objects.Object_Record'Class) is begin -- Get a new sequence range if Gen.Next_Id >= Gen.Last_Id then Allocate_Sequence (Gen); end if; Id.Set_Key_Value (Gen.Next_Id); Gen.Next_Id := Gen.Next_Id + 1; end Allocate; -- ------------------------------ -- Allocate a new sequence block. -- ------------------------------ procedure Allocate_Sequence (Gen : in out HiLoGenerator) is Name : constant String := Get_Sequence_Name (Gen); Value : Identifier; Seq_Block : Sequence_Ref; DB : Master_Session'Class := Gen.Get_Session; begin for Retry in 1 .. 10 loop -- Allocate a new sequence within a transaction. declare Query : ADO.SQL.Query; Found : Boolean; begin Log.Info ("Allocate sequence range for {0}", Name); DB.Begin_Transaction; Query.Set_Filter ("name = ?"); Query.Bind_Param (Position => 1, Value => Name); Seq_Block.Find (Session => DB, Query => Query, Found => Found); begin if Found then Value := Seq_Block.Get_Value; Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size); Seq_Block.Save (DB); else Value := 1; Seq_Block.Set_Name (Name); Seq_Block.Set_Block_Size (Gen.Block_Size); Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size); Seq_Block.Create (DB); end if; DB.Commit; Gen.Next_Id := Value; Gen.Last_Id := Seq_Block.Get_Value; return; exception when ADO.Objects.LAZY_LOCK => Log.Info ("Sequence table modified, retrying {0}/100", Util.Strings.Image (Retry)); DB.Rollback; delay 0.01 * Retry; end; exception when E : others => Log.Error ("Cannot allocate sequence range", E); raise; end; end loop; Log.Error ("Cannot allocate sequence range"); raise Allocate_Error with "Cannot allocate unique identifier"; end Allocate_Sequence; end ADO.Sequences.Hilo;
package Pythagorean_Means is type Set is array (Positive range <>) of Float; function Arithmetic_Mean (Data : Set) return Float; function Geometric_Mean (Data : Set) return Float; function Harmonic_Mean (Data : Set) return Float; end Pythagorean_Means;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Assertions; use Ada.Assertions; with Ada.Unchecked_Deallocation; with Ada.Numerics.Generic_Elementary_Functions; with Memory.Cache; use Memory.Cache; with Memory.SPM; use Memory.SPM; with Memory.Transform; use Memory.Transform; with Memory.Transform.Flip; use Memory.Transform.Flip; with Memory.Transform.Offset; use Memory.Transform.Offset; with Memory.Transform.Shift; use Memory.Transform.Shift; with Memory.Transform.EOR; use Memory.Transform.EOR; with Memory.Prefetch; use Memory.Prefetch; with Memory.Split; use Memory.Split; with Memory.Join; use Memory.Join; with Memory.Register; use Memory.Register; with Memory.Option; use Memory.Option; with Applicative; use Applicative; with Simplify_Memory; with Variance; package body Memory.Super is package LF_Math is new Ada.Numerics.Generic_Elementary_Functions(Long_Float); function Create_Memory(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer; function Create_Split(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer; function Create_Transform(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer; function Create_Memory(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer is tcost : constant Cost_Type := cost + Get_Cost(next.all); result : Memory_Pointer := null; begin case Random(mem.generator.all) mod 8 is when 0 => result := Create_Transform(mem, next, cost, in_bank); when 1 => if mem.has_idle then result := Random_Prefetch(next, mem.generator.all, tcost); else result := Create_Memory(mem, next, cost, in_bank); end if; when 2 => result := Random_SPM(next, mem.generator.all, tcost); when 3 => result := Random_Cache(next, mem.generator.all, tcost); when 4 => result := Create_Split(mem, next, cost, in_bank); when others => result := Create_Memory(mem, next, cost, in_bank); end case; Assert(result /= null, "Memory.Super.Create_Memory returning null"); return result; end Create_Memory; function Create_Split(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer is result : Split_Pointer; join0 : Join_Pointer; join1 : Join_Pointer; begin result := Split_Pointer(Random_Split(next, mem.generator.all, cost)); join0 := Create_Join(result, 0); join1 := Create_Join(result, 1); Set_Bank(result.all, 0, join0); Set_Bank(result.all, 1, join1); return Memory_Pointer(result); end Create_Split; function Create_Transform(mem : Super_Type; next : access Memory_Type'Class; cost : Cost_Type; in_bank : Boolean) return Memory_Pointer is result : Memory_Pointer; trans : Transform_Pointer; join : Join_Pointer; begin case Random(mem.generator.all) mod 4 is when 0 => result := Random_Flip(next, mem.generator.all, cost); when 1 => result := Random_Offset(next, mem.generator.all, cost); when 2 => result := Random_EOR(next, mem.generator.all, cost); when others => result := Random_Shift(next, mem.generator.all, cost); end case; trans := Transform_Pointer(result); if in_bank or else (Random(mem.generator.all) mod 2) = 0 then join := Create_Join(trans, 0); Set_Bank(trans.all, join); end if; return result; end Create_Transform; function Clone(mem : Super_Type) return Memory_Pointer is result : constant Super_Pointer := new Super_Type'(mem); begin return Memory_Pointer(result); end Clone; function Done(mem : Super_Type) return Boolean is begin return mem.iteration >= mem.max_iterations; end Done; function Count_Memories(ptr : Memory_Pointer) return Natural is begin if ptr /= null then if ptr.all in Split_Type'Class then declare sp : constant Split_Pointer := Split_Pointer(ptr); a : constant Memory_Pointer := Get_Bank(sp.all, 0); ac : constant Natural := Count_Memories(a); b : constant Memory_Pointer := Get_Bank(sp.all, 1); bc : constant Natural := Count_Memories(b); n : constant Memory_Pointer := Get_Memory(sp.all); nc : constant Natural := Count_Memories(n); begin return 1 + ac + bc + nc; end; elsif ptr.all in Transform_Type'Class then declare tp : constant Transform_Pointer := Transform_Pointer(ptr); bp : constant Memory_Pointer := Get_Bank(tp.all); bc : constant Natural := Count_Memories(bp); np : constant Memory_Pointer := Get_Memory(tp.all); nc : constant Natural := Count_Memories(np); begin return 1 + bc + nc; end; elsif ptr.all in Container_Type'Class then declare cp : constant Container_Pointer := Container_Pointer(ptr); begin return 1 + Count_Memories(Get_Memory(cp.all)); end; elsif ptr.all in Join_Type'Class then return 1; elsif ptr.all in Option_Type'Class then return 1; end if; end if; return 0; end Count_Memories; procedure Reset(mem : in out Super_Type; context : in Natural) is begin for i in Natural(mem.contexts.Length) .. context loop declare cp : constant Context_Pointer := new Context_Type; begin cp.index := i; mem.contexts.Append(cp); end; end loop; mem.current_length := 0; mem.context := mem.contexts.Element(context); Reset(Container_Type(mem), context); end Reset; procedure Read(mem : in out Super_Type; address : in Address_Type; size : in Positive) is begin mem.current_length := mem.current_length + 1; Read(Container_Type(mem), address, size); if mem.total = 0 then Insert(mem.generator.all, address, size); elsif Get_Value(mem'Access) >= mem.best_value * 2 then if mem.current_length > mem.context.total_length / 4 then if mem.contexts.Length = 1 then raise Prune_Error; end if; end if; end if; end Read; procedure Write(mem : in out Super_Type; address : in Address_Type; size : in Positive) is begin mem.current_length := mem.current_length + 1; Write(Container_Type(mem), address, size); if mem.total = 0 then Insert(mem.generator.all, address, size); elsif Get_Value(mem'Access) >= mem.best_value * 2 then if mem.current_length > mem.context.total_length / 4 then if mem.contexts.Length = 1 then raise Prune_Error; end if; end if; end if; end Write; procedure Idle(mem : in out Super_Type; cycles : in Time_Type) is begin if cycles > 0 then mem.has_idle := True; Idle(Container_Type(mem), cycles); end if; end Idle; procedure Remove_Memory(ptr : in out Memory_Pointer; index : in Natural; updated : out Boolean) is begin Assert(ptr /= null, "null ptr in Remove_Memory"); if index = 0 then if ptr.all in Split_Type'Class then declare sp : constant Split_Pointer := Split_Pointer(ptr); b0 : constant Memory_Pointer := Get_Bank(sp.all, 0); b1 : constant Memory_Pointer := Get_Bank(sp.all, 1); next : constant Memory_Pointer := Get_Memory(sp.all); begin if b0.all in Join_Type'Class and b1.all in Join_Type'Class then Set_Memory(sp.all, null); Destroy(ptr); ptr := next; updated := True; else updated := False; end if; end; elsif ptr.all in Container_Type'Class then declare cp : constant Container_Pointer := Container_Pointer(ptr); next : constant Memory_Pointer := Get_Memory(cp.all); begin Set_Memory(cp.all, null); Destroy(ptr); ptr := next; updated := True; end; elsif ptr.all in Join_Type'Class then updated := False; elsif ptr.all in Option_Type'Class then updated := False; else Destroy(ptr); ptr := null; updated := True; end if; elsif ptr.all in Split_Type'Class then declare sp : constant Split_Pointer := Split_Pointer(ptr); a : Memory_Pointer := Get_Bank(sp.all, 0); ac : constant Natural := Count_Memories(a); b : Memory_Pointer := Get_Bank(sp.all, 1); bc : constant Natural := Count_Memories(b); n : Memory_Pointer := Get_Memory(sp.all); begin if 1 + ac > index then Remove_Memory(a, index - 1, updated); Set_Bank(sp.all, 0, a); elsif 1 + ac + bc > index then Remove_Memory(b, index - ac - 1, updated); Set_Bank(sp.all, 1, b); else Remove_Memory(n, index - ac - bc - 1, updated); Set_Memory(sp.all, n); end if; end; elsif ptr.all in Transform_Type'Class then declare tp : constant Transform_Pointer := Transform_Pointer(ptr); bank : Memory_Pointer := Get_Bank(tp.all); count : constant Natural := Count_Memories(bank); next : Memory_Pointer := Get_Memory(tp.all); begin if 1 + count > index then Remove_Memory(bank, index - 1, updated); Set_Bank(tp.all, bank); else Remove_Memory(next, index - count - 1, updated); Set_Memory(tp.all, next); end if; end; elsif ptr.all in Container_Type'Class then declare cp : constant Container_Pointer := Container_Pointer(ptr); n : Memory_Pointer := Get_Memory(cp.all); begin Remove_Memory(n, index - 1, updated); Set_Memory(cp.all, n); end; else updated := False; end if; end Remove_Memory; procedure Insert_Memory(mem : in Super_Type; ptr : in out Memory_Pointer; index : in Natural; cost : in Cost_Type; in_bank : in Boolean) is begin Assert(ptr /= null, "null ptr in Insert_Memory"); if index = 0 then -- Insert other before ptr. ptr := Create_Memory(mem, ptr, cost, in_bank); elsif ptr.all in Split_Type'Class then declare sp : constant Split_Pointer := Split_Pointer(ptr); a : Memory_Pointer := Get_Bank(sp.all, 0); ac : constant Natural := Count_Memories(a); b : Memory_Pointer := Get_Bank(sp.all, 1); bc : constant Natural := Count_Memories(b); n : Memory_Pointer := Get_Memory(sp.all); begin if 1 + ac > index then -- Insert to the first bank. Push_Limit(mem.generator.all, 0, Get_Offset(sp.all)); Insert_Memory(mem, a, index - 1, cost, True); Pop_Limit(mem.generator.all); Set_Bank(sp.all, 0, a); elsif 1 + ac + bc > index then -- Insert to the second bank. Push_Limit(mem.generator.all, Get_Offset(sp.all), Address_Type'Last); Insert_Memory(mem, b, index - ac - 1, cost, True); Pop_Limit(mem.generator.all); Set_Bank(sp.all, 1, b); else -- Insert after the split. Insert_Memory(mem, n, index - ac - bc - 1, cost, in_bank); Set_Memory(sp.all, n); end if; end; elsif ptr.all in Transform_Type'Class then declare tp : constant Transform_Pointer := Transform_Pointer(ptr); bank : Memory_Pointer := Get_Bank(tp.all); count : constant Natural := Count_Memories(bank); next : Memory_Pointer := Get_Memory(tp.all); begin if 1 + count > index then -- Insert to the bank. Push_Transform(mem.generator.all, Applicative_Pointer(tp)); Insert_Memory(mem, bank, index - 1, cost, True); Pop_Transform(mem.generator.all); Set_Bank(tp.all, bank); else -- Insert after the transform. if Get_Bank(tp.all) = null then Push_Transform(mem.generator.all, Applicative_Pointer(tp)); Insert_Memory(mem, next, index - count - 1, cost, in_bank); Pop_Transform(mem.generator.all); else Insert_Memory(mem, next, index - count - 1, cost, in_bank); end if; Set_Memory(tp.all, next); end if; end; elsif ptr.all in Container_Type'Class then declare cp : constant Container_Pointer := Container_Pointer(ptr); n : Memory_Pointer := Get_Memory(cp.all); begin Insert_Memory(mem, n, index - 1, cost, in_bank); Set_Memory(cp.all, n); end; end if; end Insert_Memory; function Permute_Memory(mem : in Super_Type; ptr : in Memory_Pointer; index : in Natural; cost : in Cost_Type) return Boolean is begin Assert(ptr /= null, "null ptr in Permute_Memory"); if index = 0 then Permute(ptr.all, mem.generator.all, cost + Get_Cost(ptr.all)); return ptr.all not in Join_Type'Class; elsif ptr.all in Split_Type'Class then declare sp : constant Split_Pointer := Split_Pointer(ptr); a : constant Memory_Pointer := Get_Bank(sp.all, 0); ac : constant Natural := Count_Memories(a); b : constant Memory_Pointer := Get_Bank(sp.all, 1); bc : constant Natural := Count_Memories(b); n : constant Memory_Pointer := Get_Memory(sp.all); rc : Boolean; begin if 1 + ac > index then Push_Limit(mem.generator.all, 0, Get_Offset(sp.all)); rc := Permute_Memory(mem, a, index - 1, cost); Pop_Limit(mem.generator.all); elsif 1 + ac + bc > index then Push_Limit(mem.generator.all, Get_Offset(sp.all), Address_Type'Last); rc := Permute_Memory(mem, b, index - ac - 1, cost); Pop_Limit(mem.generator.all); else rc := Permute_Memory(mem, n, index - ac - bc - 1, cost); end if; return rc; end; elsif ptr.all in Transform_Type'Class then declare tp : constant Transform_Pointer := Transform_Pointer(ptr); bank : constant Memory_Pointer := Get_Bank(tp.all); count : constant Natural := Count_Memories(bank); next : constant Memory_Pointer := Get_Memory(tp.all); rc : Boolean; begin if 1 + count > index then Push_Transform(mem.generator.all, Applicative_Pointer(tp)); rc := Permute_Memory(mem, bank, index - 1, cost); Pop_Transform(mem.generator.all); else if Get_Bank(tp.all) = null then Push_Transform(mem.generator.all, Applicative_Pointer(tp)); rc := Permute_Memory(mem, next, index - count - 1, cost); Pop_Transform(mem.generator.all); else rc := Permute_Memory(mem, next, index - count - 1, cost); end if; end if; return rc; end; elsif ptr.all in Container_Type'Class then declare cp : constant Container_Pointer := Container_Pointer(ptr); n : constant Memory_Pointer := Get_Memory(cp.all); begin return Permute_Memory(mem, n, index - 1, cost); end; else Assert(False, "invalid type in Permute_Memory"); return False; end if; end Permute_Memory; procedure Randomize(mem : in Super_Type; ptr : in out Memory_Pointer) is len : constant Natural := Count_Memories(ptr); pos : Natural; rc : Boolean; cost : constant Cost_Type := Get_Cost(ptr.all); left : constant Cost_Type := mem.max_cost - cost; begin -- Select an action to take. -- Here we give extra weight to modifying an existing subsystem -- rather than adding or removing components. if mem.permute_only then loop pos := Random(mem.generator.all) mod len; if Permute_Memory(mem, ptr, pos, left) then exit when Get_Cost(ptr.all) <= mem.max_cost; end if; end loop; else case Random(mem.generator.all) mod 32 is when 0 => -- Insert a component. pos := Random(mem.generator.all) mod (len + 1); Insert_Memory(mem, ptr, pos, left, False); when 1 | 2 => -- Remove a component. if len = 0 then Insert_Memory(mem, ptr, 0, left, False); else for i in 1 .. 10 loop pos := Random(mem.generator.all) mod len; Remove_Memory(ptr, pos, rc); exit when rc; end loop; end if; when others => -- Modify a component. if len = 0 then Insert_Memory(mem, ptr, 0, left, False); else loop pos := Random(mem.generator.all) mod len; if Permute_Memory(mem, ptr, pos, left) then exit when Get_Cost(ptr.all) <= mem.max_cost; end if; end loop; end if; end case; end if; Assert(Get_Cost(mem) <= mem.max_cost, "Invalid randomize"); end Randomize; function Create_Super(mem : not null access Memory_Type'Class; max_cost : Cost_Type; seed : Integer; max_iterations : Long_Integer; permute_only : Boolean) return Super_Pointer is result : Super_Pointer; begin if Get_Cost(mem.all) > max_cost then return null; end if; result := new Super_Type; result.max_cost := max_cost; result.max_iterations := max_iterations; result.last := Memory_Pointer(mem); result.current := Clone(mem.all); result.generator := new Distribution_Type; result.permute_only := False; Set_Seed(result.generator.all, seed); Set_Memory(result.all, Clone(mem.all)); return result; end Create_Super; procedure Update_Memory(mem : in out Super_Type; result : in Result_Type) is eold : constant Long_Integer := Long_Integer(mem.last_value); enew : constant Long_Integer := Long_Integer(result.value); diff : constant Long_Integer := enew - eold; temp : Memory_Pointer; begin if mem.steps = 0 then mem.threshold := 1024; end if; if diff <= mem.threshold then -- Keep the current memory. for i in mem.contexts.First_Index .. mem.contexts.Last_Index loop declare cp : constant Context_Pointer := mem.contexts.Element(i); begin cp.last_value := result.context_values.Element(i); end; end loop; mem.last_value := result.value; Destroy(mem.last); mem.last := Clone(mem.current.all); -- Decrease the threshold. mem.threshold := mem.threshold - (mem.threshold + 1023) / 1024; mem.age := 0; else -- Revert to the previous memory. Destroy(mem.current); mem.current := Clone(mem.last.all); -- Increase the threshold. mem.threshold := mem.threshold + (mem.age * mem.threshold) / 2048; mem.threshold := mem.threshold + 1; mem.age := mem.age + 1; end if; mem.steps := mem.steps + 1; temp := Get_Memory(mem); Destroy(temp); Set_Memory(mem, null); Randomize(mem, mem.current); temp := Simplify_Memory(Clone(mem.current.all)); Insert_Registers(temp); Set_Memory(mem, temp); end Update_Memory; procedure Track_Best(mem : in out Super_Type; cost : in Cost_Type; value : in Value_Type) is simp_mem : Memory_Pointer; simp_cost : Cost_Type; simp_name : Unbounded_String; begin -- Value can't change from simplification, so we check it first. if value > mem.best_value then return; end if; -- Value is at least as good. -- The current memory being used is the simplified memory with -- registers inserted, so we use that. simp_mem := Get_Memory(mem); simp_cost := Get_Cost(simp_mem.all); -- If the value is the same, we will only accept the memory if -- the cost is at least as good. if value = mem.best_value and cost > mem.best_cost then return; end if; -- Get the name of the simplified memory. simp_name := To_String(simp_mem.all); -- If the cost and value are the same, we accept the memory -- only if the name is shorter. if value = mem.best_value and then cost = mem.best_cost and then Length(simp_name) > Length(mem.best_name) then return; end if; -- If we get here, we have a better memory subsystem. if mem.best_value < Value_Type'Last then -- Don't reset our count unless we are able to get at least -- 0.1% better since the last reset. mem.improvement := mem.improvement + mem.best_value - value; if mem.improvement > value / 1000 then mem.iteration := 0; mem.improvement := 0; end if; end if; mem.best_value := value; mem.best_cost := simp_cost; mem.best_name := simp_name; end Track_Best; procedure Cache_Result(mem : in out Super_Type; result : in Result_Type) is simp_mem : Memory_Pointer; simp_name : Unbounded_String; begin simp_mem := Simplify_Memory(Clone(mem.current.all)); simp_name := To_String(simp_mem.all); mem.table.Insert(simp_name, result); Destroy(simp_mem); end Cache_Result; function Check_Cache(mem : Super_Type) return Result_Type is simp_mem : Memory_Pointer; simp_name : Unbounded_String; cursor : Value_Maps.Cursor; begin simp_mem := Simplify_Memory(Clone(mem.current.all)); simp_name := To_String(simp_mem.all); Destroy(simp_mem); cursor := mem.table.Find(simp_name); if Value_Maps."="(cursor, Value_Maps.No_Element) then declare result : Result_Type; begin result.value := 0; return result; end; else return Value_Maps.Element(cursor); end if; end Check_Cache; package LF_Variance is new Variance(Long_Float); procedure Finish_Run(mem : in out Super_Type) is context : constant Context_Pointer := mem.context; cost : constant Cost_Type := Get_Cost(mem); value : Value_Type := Get_Value(mem'Access); sum : Long_Float; count : Long_Float; total : Long_Integer; var : LF_Variance.Variance_Type; result : Result_Type; begin -- Scale the result if necessary. if mem.current_length > context.total_length then context.total_length := mem.current_length; end if; if mem.current_length /= context.total_length then Put_Line("Prune"); declare mult : constant Long_Float := Long_Float(context.total_length) / Long_Float(mem.current_length); fval : constant Long_Float := Long_Float(value) * mult; begin if fval >= Long_Float(Value_Type'Last) then value := Value_Type'Last; else value := Value_Type(fval); end if; end; if value < mem.best_value then Put_Line("Prune overflow"); value := mem.best_value + 1; end if; end if; context.value := value; -- Return early if there are more contexts to process. if context.index > 0 then return; end if; -- We now have data for all benchmarks. -- Determine the average value (geometric mean). count := 0.0; sum := 0.0; total := 0; for i in mem.contexts.First_Index .. mem.contexts.Last_Index loop declare cp : constant Context_Pointer := mem.contexts.Element(i); diff : Long_Float := 0.0; pdiff : Long_Float := 0.0; begin if cp.last_value /= Value_Type'Last then diff := Long_Float(cp.value) - Long_Float(cp.last_value); pdiff := diff / Long_Float(cp.total_length); LF_Variance.Update(var, pdiff); Put_Line(To_String(i) & ": " & Value_Type'Image(cp.value) & " (delta: " & To_String(pdiff) & ")"); end if; sum := sum + LF_Math.Log(Long_Float(cp.value)); count := count + 1.0; total := total + cp.total_length; end; end loop; value := Value_Type(LF_Math.Exp(sum / count)); -- Report the average. if mem.last_value /= Value_Type'Last then declare diff : constant Long_Float := Long_Float(value) - Long_Float(mem.last_value); pdiff : constant Long_Float := diff / Long_Float(total); v : constant Long_Float := LF_Variance.Get_Variance(var); begin Put_Line("Average:" & Value_Type'Image(value) & " (delta: " & To_String(pdiff) & ")"); Put_Line("Variance: " & To_String(v)); end; else Put_Line("Average:" & Value_Type'Image(value)); end if; Put_Line("Cost:" & Cost_Type'Image(cost)); -- Keep track of the best memory. Track_Best(mem, cost, value); Put_Line("Best Memory: " & To_String(mem.best_name)); Put_Line("Best Value: " & Value_Type'Image(mem.best_value)); Put_Line("Best Cost: " & Cost_Type'Image(mem.best_cost)); -- Keep track of the result of running with this memory. for i in mem.contexts.First_Index .. mem.contexts.Last_Index loop result.context_values.Append(mem.contexts.Element(i).value); end loop; result.value := value; Cache_Result(mem, result); -- Keep track of the number of iterations. mem.iteration := mem.iteration + 1; mem.total := mem.total + 1; if not Done(mem) then Put_Line("Iteration:" & Long_Integer'Image(mem.iteration + 1) & " (evaluation " & To_String(mem.total + 1) & ", steps " & To_String(mem.steps + 1) & ", threshold " & To_String(mem.threshold) & ", age " & To_String(mem.age) & ")"); -- Generate new memories until we find a new one. loop Update_Memory(mem, result); result := Check_Cache(mem); value := result.value; exit when value = 0; end loop; Put_Line(To_String(To_String(mem))); end if; end Finish_Run; procedure Show_Stats(mem : in out Super_Type) is begin Show_Access_Stats(mem); end Show_Stats; procedure Show_Access_Stats(mem : in out Super_Type) is begin Finish_Run(mem); end Show_Access_Stats; procedure Adjust(mem : in out Super_Type) is begin Adjust(Container_Type(mem)); mem.generator := new Distribution_Type; mem.last := null; mem.current := null; end Adjust; procedure Destroy is new Ada.Unchecked_Deallocation(Distribution_Type, Distribution_Pointer); procedure Destroy is new Ada.Unchecked_Deallocation(Context_Type, Context_Pointer); procedure Finalize(mem : in out Super_Type) is begin for i in mem.contexts.First_Index .. mem.contexts.Last_Index loop declare cp : Context_Pointer := mem.contexts.Element(i); begin Destroy(cp); end; end loop; Destroy(mem.generator); Destroy(mem.last); Destroy(mem.current); Finalize(Container_Type(mem)); end Finalize; end Memory.Super;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. ------------------------------------------------------------------------- -- This file contains the key routine `List_Stems`; this currently uses too -- much state; ideally it should be a pure function, and making it so is -- an important step in simplifying WORDS and exposing its engine to other -- interfaces. -- -- `List_Stems` contains a *lot* of duplicated code that could be factored -- out, to be marked with "FACTOR OUT". with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Exceptions; use Ada.Exceptions; with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package; with Latin_Utils.Latin_File_Names; use Latin_Utils.Latin_File_Names; with Support_Utils.Word_Parameters; use Support_Utils.Word_Parameters; with Support_Utils.Addons_Package; use Support_Utils.Addons_Package; with Support_Utils.Uniques_Package; use Support_Utils.Uniques_Package; with Support_Utils.Word_Support_Package; use Support_Utils.Word_Support_Package; with Support_Utils.Developer_Parameters; use Support_Utils.Developer_Parameters; with Words_Engine.Word_Package; use Words_Engine.Word_Package; with Support_Utils.Char_Utils; with Support_Utils.Dictionary_Form; with Words_Engine.Put_Example_Line; with Words_Engine.List_Sweep; with Words_Engine.Put_Stat; with Words_Engine.Pearse_Code; use Words_Engine.Pearse_Code; use Latin_Utils; package body Words_Engine.List_Package is subtype Xons is Part_Of_Speech_Type range Tackon .. Suffix; Null_Dictionary_MNPC_Record : constant Dictionary_MNPC_Record := (X, Null_MNPC, Null_Dictionary_Entry); Null_Stem_Inflection_Record : constant Stem_Inflection_Record := (Stem => Null_Stem_Type, Ir => Null_Inflection_Record); Null_Sra : constant Stem_Inflection_Array (1 .. Stem_Inflection_Array_Size) := (others => (Null_Stem_Type, Null_Inflection_Record)); Null_Sraa : constant Stem_Inflection_Array_Array (1 .. Stem_Inflection_Array_Array_Size) := (others => Null_Sra); Null_Dma : constant Dictionary_MNPC_Array := (others => Null_Dictionary_MNPC_Record); Max_Meaning_Print_Size : constant := 79; Inflection_Frequency : constant array (Frequency_Type) of String (1 .. 8) := (" ", -- X "mostfreq", -- A "sometime", -- B "uncommon", -- C "infreq ", -- D "rare ", -- E "veryrare", -- F "inscript", -- I " ", -- Not used " "); Inflection_Age : constant array (Age_Type) of String (1 .. 8) := ("Always ", -- X "Archaic ", -- A "Early ", -- B "Classic ", -- C "Late ", -- D "Later ", -- E "Medieval", -- F "Scholar ", -- G "Modern "); -- H Dictionary_Frequency : constant array (Frequency_Type) of String (1 .. 8) := (" ", -- X "veryfreq", -- A "frequent", -- B "common ", -- C "lesser ", -- D "uncommon", -- E "veryrare", -- F "inscript", -- I "graffiti", -- J "Pliny "); -- N Dictionary_Age : constant array (Age_Type) of String (1 .. 8) := (" ", -- X "Archaic ", -- A "Early ", -- B "Classic ", -- C "Late ", -- D "Later ", -- E "Medieval", -- F "NeoLatin", -- G "Modern "); -- H subtype Meaning_Cache_Type is Dictionary_Kind range Xxx .. Ppp; type Meaning_Cache is array (Meaning_Cache_Type) of Boolean; function Get_Max_Meaning_Size (Output : Ada.Text_IO.File_Type) return Integer is begin if Ada.Text_IO.Name (Output) = Ada.Text_IO.Name (Ada.Text_IO.Standard_Output) then -- to keep from overflowing screen line or even adding blank line return Max_Meaning_Print_Size; else return Max_Meaning_Size; end if; end Get_Max_Meaning_Size; procedure Put_Pearse_Code (Output : Ada.Text_IO.File_Type; Code : Symbol) is begin if Words_Mdev (Do_Pearse_Codes) then Ada.Text_IO.Put (Output, Format (Code)); end if; end Put_Pearse_Code; procedure Put_Dictionary_Flags (Output : Ada.Text_IO.File_Type; De : Dictionary_Entry; Hit : out Boolean) is begin Hit := False; if Words_Mode (Show_Age) or (Trim (Dictionary_Age (De.Tran.Age))'Length /= 0) -- Not X then Ada.Text_IO.Put (Output, " " & Trim (Dictionary_Age (De.Tran.Age))); Hit := True; end if; if (Words_Mode (Show_Frequency) or (De.Tran.Freq >= D)) and (Trim (Dictionary_Frequency (De.Tran.Freq))'Length /= 0) then Ada.Text_IO.Put (Output, " " & Trim (Dictionary_Frequency (De.Tran.Freq))); Hit := True; end if; end Put_Dictionary_Flags; procedure Put_Dictionary_Form (Output : Ada.Text_IO.File_Type; D_K : Dictionary_Kind; MNPC : Dict_IO.Count; De : Dictionary_Entry) is Chit, Dhit, Ehit, Fhit, Lhit : Boolean := False; -- Things on this line? Dictionary_Line_Number : constant Integer := Integer (MNPC); begin -- PUT_DICTIONARY_FORM if Words_Mode (Do_Dictionary_Forms) then Put_Pearse_Code (Output, Citation_Form); if Words_Mdev (Do_Pearse_Codes) then Dhit := True; end if; if Support_Utils.Dictionary_Form (De)'Length /= 0 then Ada.Text_IO.Put (Output, Support_Utils.Dictionary_Form (De) & " "); Dhit := True; end if; end if; if Words_Mdev (Show_Dictionary_Codes) and then De.Part.Pofs not in Xons then Ada.Text_IO.Put (Output, " ["); -- FIXME: Why noy Translation_Record_IO.Put ? Age_Type_IO.Put (Output, De.Tran.Age); Area_Type_IO.Put (Output, De.Tran.Area); Geo_Type_IO.Put (Output, De.Tran.Geo); Frequency_Type_IO.Put (Output, De.Tran.Freq); Source_Type_IO.Put (Output, De.Tran.Source); Ada.Text_IO.Put (Output, "] "); Chit := True; end if; if Words_Mdev (Show_Dictionary) then Ada.Text_IO.Put (Output, Ext (D_K) & ">"); Ehit := True; end if; if Words_Mdev (Show_Dictionary_Line) then if Dictionary_Line_Number > 0 then Ada.Text_IO.Put (Output, "(" & Trim (Integer'Image (Dictionary_Line_Number)) & ")"); Lhit := True; end if; end if; Put_Dictionary_Flags (Output, De, Fhit); if Chit or Dhit or Ehit or Fhit or Lhit then Ada.Text_IO.New_Line (Output); end if; --end if; end Put_Dictionary_Form; function Constructed_Meaning (Sr : Stem_Inflection_Record; Dm : Dictionary_MNPC_Record) return String is -- Constructs the meaning for NUM from NUM.SORT and NUM_VALUE S : constant String (1 .. Max_Meaning_Size) := Null_Meaning_Type; N : Integer := 0; begin if Dm.De.Part.Pofs /= Num then return S; end if; N := Dm.De.Part.Num.Value; if Sr.Ir.Qual.Pofs /= Num then -- there is fix so POFS is not NUM return Head ("Number " & Integer'Image (N), Max_Meaning_Size); end if; -- Normal parse case Sr.Ir.Qual.Num.Sort is when Card => return Head (Integer'Image (N) & " - (CARD answers 'how many');", Max_Meaning_Size); when Ord => return Head (Integer'Image (N) & "th - (ORD, 'in series'); (a/the)" & Integer'Image (N) & "th (part) (fract w/pars?);", Max_Meaning_Size); when Dist => return Head (Integer'Image (N) & " each/apiece/times/fold/together/at a time" & " - 'how many each'; by " & Integer'Image (N) & "s; ", Max_Meaning_Size); when Adverb => return Head (Integer'Image (N) & " times, on" & Integer'Image (N) & " occasions - (ADVERB answers 'how often');", Max_Meaning_Size); when others => return S; end case; end Constructed_Meaning; function Trim_Bar (S : String) return String is -- Takes vertical bars from begining of MEAN and TRIMs begin return Trim (Ada.Strings.Fixed.Trim (S, Ada.Strings.Maps.To_Set ('|'), Ada.Strings.Maps.Null_Set)); end Trim_Bar; procedure Put_Meaning_Line (Output : Ada.Text_IO.File_Type; Sr : Stem_Inflection_Record; Dm : Dictionary_MNPC_Record; Mm : Integer; Xp : in Explanations; Used_Meanings : in out Meaning_Cache) is procedure Put_Meaning (Output : Ada.Text_IO.File_Type; Raw_Meaning : String) is -- Handles the MM screen line limit and TRIM_BAR, then TRIMs begin Ada.Text_IO.Put (Output, Trim (Head (Trim_Bar (Raw_Meaning), Mm))); Ada.Text_IO.New_Line (Output); end Put_Meaning; procedure Put_Word_Meaning (Meaning : in Meaning_Type; Code : in Symbol) is begin if not Used_Meanings (Dm.D_K) then Put_Pearse_Code (Output, Code); Put_Meaning (Output, Meaning); Used_Meanings (Dm.D_K) := True; end if; end Put_Word_Meaning; begin case Dm.D_K is when Rrr => Put_Word_Meaning (Xp.Rrr_Meaning, Gloss); -- Roman Numeral when Nnn => Put_Word_Meaning (Xp.Nnn_Meaning, Trick); -- Unknown Name when Xxx => Put_Word_Meaning (Xp.Xxx_Meaning, Trick); -- TRICKS when Yyy => Put_Word_Meaning (Xp.Yyy_Meaning, Trick); -- Syncope when Ppp => Put_Word_Meaning (Xp.Ppp_Meaning, Trick); -- Compounds when Addons => Put_Pearse_Code (Output, Trick); Put_Meaning (Output, Means (Integer (Dm.MNPC))); when others => Put_Pearse_Code (Output, Words_Engine.Pearse_Code.Gloss); if Dm.De.Part.Pofs = Num and then Dm.De.Part.Num.Value > 0 then Ada.Text_IO.Put_Line (Output, Constructed_Meaning (Sr, Dm)); -- Constructed MEANING elsif Dm.D_K = Unique then Put_Meaning (Output, Uniques_De (Dm.MNPC).Mean); else Put_Meaning (Output, Trim_Bar (Dm.De.Mean)); end if; end case; end Put_Meaning_Line; -- Convert from PARSE_RECORDs to DICTIONARY_MNPC_RECORD -- and STEM_INFLECTION_RECORD procedure Cycle_Over_Pa (Pa : in Parse_Array; Pa_Last : in Integer; Sraa : out Stem_Inflection_Array_Array; Dma : out Dictionary_MNPC_Array; I_Is_Pa_Last : out Boolean; Raw_Word, W : in String) is use Dict_IO; I : Integer := 1; J : Integer range 0 .. Stem_Inflection_Array_Array_Size := 0; K : Integer := 0; Dm : Dictionary_MNPC_Record := Null_Dictionary_MNPC_Record; Odm : Dictionary_MNPC_Record := Null_Dictionary_MNPC_Record; Dea : Dictionary_Entry := Null_Dictionary_Entry; begin while I <= Pa_Last loop -- I cycles over full PA array Odm := Null_Dictionary_MNPC_Record; if Pa (I).D_K = Unique then J := J + 1; Sraa (J)(1) := (Pa (I).Stem, Pa (I).IR); Dm := Null_Dictionary_MNPC_Record; Dm.D_K := Unique; Dm.MNPC := Pa (I).MNPC; Dm.De := Uniques_De (Pa (I).MNPC); Dma (J) := Dm; I := I + 1; else declare procedure Handle_Parse_Record is begin K := 1; -- K indexes within the MNPCA array -- Initialise J := J + 1; -- J indexes the number of MNPCA arrays - Next MNPCA Sraa (J)(K) := (Pa (I).Stem, Pa (I).IR); Dm := (Pa (I).D_K, Pa (I).MNPC, Dea); Dma (J) := Dm; Odm := Dm; end Handle_Parse_Record; pofs : constant Part_Of_Speech_Type := Pa (I).IR.Qual.Pofs; begin while I <= Pa_Last and Pa (I).IR.Qual.Pofs = pofs loop case pofs is when N | Pron | Pack | Adj | Num => if (pofs = Num) and (Pa (I).D_K = Rrr) then -- Roman numeral Dea := Null_Dictionary_Entry; Handle_Parse_Record; elsif Pa (I).MNPC /= Odm.MNPC then Dict_IO.Set_Index (Dict_File (Pa (I).D_K), Pa (I).MNPC); Dict_IO.Read (Dict_File (Pa (I).D_K), Dea); Handle_Parse_Record; else K := K + 1; -- K indexes within the MNPCA array -- Next MNPC Sraa (J)(K) := (Pa (I).Stem, Pa (I).IR); end if; when V | Vpar | Supine => if (Pa (I).MNPC /= Odm.MNPC) and (Pa (I).D_K /= Ppp) then -- Encountering new MNPC if Pa (I).D_K /= Ppp then Dict_IO.Set_Index (Dict_File (Pa (I).D_K), Pa (I).MNPC); Dict_IO.Read (Dict_File (Pa (I).D_K), Dea); end if; -- use previous DEA Handle_Parse_Record; else K := K + 1; -- K indexes within the MNPCA array - Next MNPC Sraa (J)(K) := (Pa (I).Stem, Pa (I).IR); end if; when others => --TEXT_IO.PUT_LINE ("Others"); if (Odm.D_K /= Pa (I).D_K) or (Odm.MNPC /= Pa (I).MNPC) then -- Encountering new single (K only 1) if Pa (I).MNPC /= Null_MNPC then if Pa (I).D_K = Addons then Dea := Null_Dictionary_Entry; -- Fix for ADDONS in MEANS, not DICT_IO else Dict_IO.Set_Index (Dict_File (Pa (I).D_K), Pa (I).MNPC); Dict_IO.Read (Dict_File (Pa (I).D_K), Dea); end if; else -- Has no dictionary to read Dea := Null_Dictionary_Entry; end if; Handle_Parse_Record; --else -- K := K + 1; -- K indexes within the MNPCA array - Next MNPC -- SRAA (J)(K) := (PA (I).STEM, PA (I).IR); end if; I := I + 1; -- I cycles over full PA array exit; -- Since Other is only one, don't loop end case; I := I + 1; -- I cycles over full PA array end loop; end; end if; end loop; if I = Pa_Last then I_Is_Pa_Last := True; else I_Is_Pa_Last := False; end if; exception when others => Ada.Text_IO.Put_Line ("Unexpected exception in CYCLE_OVER_PA processing " & Raw_Word); Put_Stat ("EXCEPTION LS at " & Head (Integer'Image (Line_Number), 8) & Head (Integer'Image (Word_Number), 4) & " " & Head (W, 20) & " " & Pa (I).Stem); raise; end Cycle_Over_Pa; procedure Put_Inflection (Configuration : Configuration_Type; Output : Ada.Text_IO.File_Type; Sr : Stem_Inflection_Record; Dm : Dictionary_MNPC_Record) is -- Handles Putting ONLY_MEAN, PEARSE_CODES, CAPS, QUAL, V_KIND, FLAGS procedure Put_Inflection_Flags is begin if (Words_Mode (Show_Age) or (Sr.Ir.Age /= X)) and -- Warn even if not to show AGE Trim (Inflection_Age (Sr.Ir.Age))'Length /= 0 then Ada.Text_IO.Put (Output, " " & Inflection_Age (Sr.Ir.Age)); end if; if (Words_Mode (Show_Frequency) or (Sr.Ir.Freq >= C)) and -- Warn regardless Trim (Inflection_Frequency (Sr.Ir.Freq))'Length /= 0 then Ada.Text_IO.Put (Output, " " & Inflection_Frequency (Sr.Ir.Freq)); end if; end Put_Inflection_Flags; begin --TEXT_IO.PUT_LINE ("PUT_INFLECTION "); if Words_Mode (Do_Only_Meanings) or (Configuration = Only_Meanings) then return; end if; Ada.Text_IO.Set_Col (Output, 1); if Dm.D_K = Addons then Put_Pearse_Code (Output, Affix); elsif Dm.D_K in Xxx .. Yyy then Put_Pearse_Code (Output, Trick); else Put_Pearse_Code (Output, Inflection); end if; --TEXT_IO.PUT (OUTPUT, CAP_STEM (TRIM (SR.STEM))); Ada.Text_IO.Put (Output, (Trim (Sr.Stem))); if Sr.Ir.Ending.Size > 0 then Ada.Text_IO.Put (Output, "."); --TEXT_IO.PUT (OUTPUT, TRIM (CAP_ENDING (SR.IR.ENDING.SUF))); Ada.Text_IO.Put (Output, Trim ((Sr.Ir.Ending.Suf))); end if; if Words_Mdev (Do_Pearse_Codes) then Ada.Text_IO.Set_Col (Output, 25); else Ada.Text_IO.Set_Col (Output, 22); end if; if Sr.Ir /= Null_Inflection_Record then Print_Modified_Qual : declare Out_String : String (1 .. Quality_Record_IO.Default_Width); Passive_Start : constant Integer := Part_Of_Speech_Type_IO.Default_Width + 1 + Decn_Record_IO.Default_Width + 1 + Tense_Type_IO.Default_Width + 1; Passive_Finish : constant Integer := Passive_Start + Voice_Type_IO.Default_Width; Ppl_Start : constant Integer := Part_Of_Speech_Type_IO.Default_Width + 1 + Decn_Record_IO.Default_Width + 1 + Case_Type_IO.Default_Width + 1 + Number_Type_IO.Default_Width + 1 + Gender_Type_IO.Default_Width + 1 + Tense_Type_IO.Default_Width + 1; Ppl_Finish : constant Integer := Ppl_Start + Voice_Type_IO.Default_Width; Passive_Blank : constant String (1 .. Voice_Type_IO.Default_Width) := (others => ' '); begin Quality_Record_IO.Put (Out_String, Sr.Ir.Qual); if Dm.D_K in General .. Local then -- UNIQUES has no DE if (Sr.Ir.Qual.Pofs = V) and then (Dm.De.Part.V.Kind = Dep) and then (Sr.Ir.Qual.Verb.Tense_Voice_Mood.Mood in Ind .. Inf) then --TEXT_IO.PUT_LINE ("START PRINT MODIFIED QUAL V"); Out_String (Passive_Start + 1 .. Passive_Finish) := Passive_Blank; elsif (Sr.Ir.Qual.Pofs = Vpar) and then (Dm.De.Part.V.Kind = Dep) and then (Sr.Ir.Qual.Vpar.Tense_Voice_Mood.Mood = Ppl) then --TEXT_IO.PUT_LINE ("START PRINT MODIFIED QUAL VPAR"); Out_String (Ppl_Start + 1 .. Ppl_Finish) := Passive_Blank; end if; end if; Ada.Text_IO.Put (Output, Out_String); --TEXT_IO.PUT_LINE ("PRINT MODIFIED QUAL 4"); end Print_Modified_Qual; -- if ((SR.IR.QUAL.POFS = NUM) and -- -- Don't want on inflection -- (DM.D_K in GENERAL .. UNIQUE)) and then -- (DM.DE.KIND.NUM_VALUE > 0) then -- TEXT_IO.PUT (OUTPUT, " "); -- INFLECTIONS_PACKAGE.INTEGER_IO.PUT -- (OUTPUT, DM.DE.KIND.NUM_VALUE); -- end if; Put_Inflection_Flags; Ada.Text_IO.New_Line (Output); Put_Example_Line (Configuration, Output, Sr.Ir, Dm.De); -- Only full when DO_EXAMPLES else Ada.Text_IO.New_Line (Output); end if; end Put_Inflection; -- Handles PEARSE_CODES and DICTIONARY_FORM (which has FLAGS) and D_K -- The Pearse 02 is handled in PUT_DICTIONARY_FORM procedure Put_Form (Output : Ada.Text_IO.File_Type; Sr : Stem_Inflection_Record; Dm : Dictionary_MNPC_Record) is begin if (Sr.Ir.Qual.Pofs not in Xons) and (Dm.D_K in General .. Unique) then --DICTIONARY_ENTRY_IO.PUT (DM.DE); Put_Dictionary_Form (Output, Dm.D_K, Dm.MNPC, Dm.De); end if; end Put_Form; procedure Do_Pause (Output : Ada.Text_IO.File_Type; I_Is_Pa_Last : in Boolean) is begin if I_Is_Pa_Last then Ada.Text_IO.New_Line (Output); elsif Integer (Ada.Text_IO.Line (Output)) > Scroll_Line_Number + Output_Screen_Size then Pause (Output); Scroll_Line_Number := Integer (Ada.Text_IO.Line (Output)); end if; end Do_Pause; -- output the details of a word or group of words -- -- this might handle a group of words, e.g., "factus est" procedure Put_Parse_Details (Configuration : Configuration_Type; Output : Ada.Text_IO.File_Type; WA : Word_Analysis) is Mm : constant Integer := Get_Max_Meaning_Size (Output); Osra : Stem_Inflection_Array (1 .. Stem_Inflection_Array_Size) := Null_Sra; Used_Meanings : Meaning_Cache := (others => False); begin pragma Assert (WA.Dict'First = WA.Stem_IAA'First); pragma Assert (WA.Dict'Last = WA.Stem_IAA'Last); for J in WA.Dict'Range loop declare Sra : constant Stem_Inflection_Array := WA.Stem_IAA (J); DER : constant Dictionary_MNPC_Record := WA.Dict (J); begin -- hack to work around static/dynamic schizophrenia if DER = Null_Dictionary_MNPC_Record then return; end if; -- Skips one identical SRA no matter what comes next if Sra /= Osra then Put_Inflection_Array_J : for K in Sra'Range loop exit Put_Inflection_Array_J when Sra (K) = Null_Stem_Inflection_Record; Put_Inflection (Configuration, Output, Sra (K), DER); if Sra (K).Stem (1 .. 3) = "PPL" then Ada.Text_IO.Put_Line (Output, Head (WA.Xp.Ppp_Meaning, Mm)); end if; end loop Put_Inflection_Array_J; Osra := Sra; end if; Putting_Form : begin if J = WA.Dict'First or else Support_Utils.Dictionary_Form (DER.De) /= Support_Utils.Dictionary_Form (WA.Dict (J - 1).De) then -- Put at first chance, skip duplicates Put_Form (Output, Sra (1), DER); end if; end Putting_Form; Putting_Meaning : begin if DER.D_K not in General .. Unique or else ( J + 1 > WA.Dict'Last or else DER.De.Mean /= WA.Dict (J + 1).De.Mean) then -- Handle simple multiple MEAN with same IR and FORM -- by anticipating duplicates and waiting until change Put_Meaning_Line (Output, Sra (1), DER, Mm, WA.Xp, Used_Meanings); end if; end Putting_Meaning; Do_Pause (Output, WA.I_Is_Pa_Last); end; end loop; end Put_Parse_Details; procedure Fix_Adverb (Pa : in out Parse_Array; Pa_Last : in out Integer; Xp : in out Explanations) is J1, J2 : Integer := 0; J : Integer := 0; begin --TEXT_IO.PUT_LINE ("In the ADJ -> ADV kludge There is no ADV"); for I in reverse Pa'First .. Pa_Last loop if Pa (I).IR.Qual.Pofs = Adj and then (Pa (I).IR.Qual.Adj = ((1, 1), Voc, S, M, Pos) or ((Pa (I).IR.Qual.Adj.Of_Case = Voc) and (Pa (I).IR.Qual.Adj.Number = S) and (Pa (I).IR.Qual.Adj.Gender = M) and (Pa (I).IR.Qual.Adj.Comparison = Super))) then J := I; while J >= Pa'First loop --Back through other ADJ cases if Pa (J).IR.Qual.Pofs /= Adj then J2 := J; -- J2 is first (reverse) that is not ADJ exit; end if; J := J - 1; end loop; while J >= Pa'First loop -- Sweep up associated fixes if Pa (J).IR.Qual.Pofs not in Xons then J1 := J; -- J1 is first (reverse) that is not XONS exit; end if; J := J - 1; end loop; for J in J1 + 1 .. J2 loop Pa (Pa_Last + J - J1 + 1) := Pa (J); end loop; Pa_Last := Pa_Last + J2 - J1 + 1; Pa (Pa_Last) := Pa (J2 + 1); Pa (Pa_Last) := ("e ", ((Suffix, Null_Suffix_Record), 0, Null_Ending_Record, X, B), Ppp, Null_MNPC); --PARSE_RECORD_IO.PUT (PA (PA_LAST)); TEXT_IO.NEW_LINE; Pa_Last := Pa_Last + 1; declare procedure Handle_Degree (E : Ending_Record; Caption : String) is begin Pa (Pa_Last) := (Pa (J2 + 1).Stem, ((Pofs => Adv, Adv => (Comparison => Pa (J2 + 1).IR.Qual.Adj.Comparison)), Key => 0, Ending => E, Age => X, Freq => B), Pa (J2 + 1).D_K, Pa (J2 + 1).MNPC); Xp.Ppp_Meaning := Head (Caption, Max_Meaning_Size); end Handle_Degree; begin if Pa (J2 + 1).IR.Qual.Adj.Comparison = Pos then Handle_Degree ((1, "e "), "-ly; -ily; Converting ADJ to ADV"); elsif Pa (J2 + 1).IR.Qual.Adj.Comparison = Super then Handle_Degree ((2, "me "), "-estly; -estily; most -ly, very -ly" & " Converting ADJ to ADV"); end if; end; end if; -- PA (I).IR.QUAL.POFS = ADJ end loop; end Fix_Adverb; -- update local dictionary, and handling of caps, temporarily disabled procedure List_Unknowns (Input_Line : String; Raw_Word : String) is use Ada.Text_IO; begin if Words_Mode (Write_Output_To_File) then Put_Pearse_Code (Output, Unknowns_2); Ada.Text_IO.Put (Output, Raw_Word); Ada.Text_IO.Set_Col (Output, 30); Inflections_Package.Integer_IO.Put (Output, Line_Number, 7); Inflections_Package.Integer_IO.Put (Output, Word_Number, 7); Ada.Text_IO.Put_Line (Output, " ======== UNKNOWN "); else -- Just screen Output if Words_Mdev (Do_Pearse_Codes) then Ada.Text_IO.Put ("04 "); end if; Ada.Text_IO.Put (Raw_Word); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put_Line (" ======== UNKNOWN "); end if; if Words_Mode (Write_Unknowns_To_File) then if Words_Mdev (Include_Unknown_Context) or Words_Mdev (Do_Only_Initial_Word) then Ada.Text_IO.Put_Line (Input_Line); Ada.Text_IO.Put_Line (Unknowns, Input_Line); end if; Put_Pearse_Code (Unknowns, Unknowns_2); Ada.Text_IO.Put (Unknowns, Raw_Word); Ada.Text_IO.Set_Col (Unknowns, 30); Inflections_Package.Integer_IO.Put (Unknowns, Line_Number, 7); Inflections_Package.Integer_IO.Put (Unknowns, Word_Number, 7); Ada.Text_IO.Put_Line (Unknowns, " ======== UNKNOWN "); end if; if Words_Mode (Do_Stems_For_Unknown) then if Words_Mode (Write_Output_To_File) and then not Words_Mode (Write_Unknowns_To_File) then List_Neighborhood (Output, Raw_Word); elsif Words_Mode (Write_Output_To_File) and then Words_Mode (Write_Unknowns_To_File) then List_Neighborhood (Output, Raw_Word); List_Neighborhood (Unknowns, Raw_Word); elsif Name (Current_Input) = Name (Standard_Input) then List_Neighborhood (Output, Raw_Word); end if; end if; end List_Unknowns; procedure Write_Addons_Stats (W : String; Pa : Parse_Array; Pa_Last : Integer) is begin if not Words_Mdev (Write_Statistics_File) then return; end if; -- Omit rest of Output for I in 1 .. Pa_Last loop -- Just to PUT_STAT if Pa (I).D_K = Addons then declare procedure Put_Addon_Info (Caption : String) is begin Put_Stat ("ADDON " & Caption & " at " & Head (Integer'Image (Line_Number), 8) & Head (Integer'Image (Word_Number), 4) & " " & Head (W, 20) & " " & Pa (I).Stem & " " & Integer'Image (Integer (Pa (I).MNPC))); end Put_Addon_Info; begin case Pa (I).IR.Qual.Pofs is when Prefix => Put_Addon_Info ("PREFIX"); when Suffix => Put_Addon_Info ("SUFFIX"); when Tackon => Put_Addon_Info ("TACKON"); when others => null; end case; end; end if; end loop; end Write_Addons_Stats; procedure Handle_Adverb (Pa : in out Parse_Array; Pa_Last : in out Integer; Xp : in out Explanations) is There_Is_An_Adverb : Boolean := False; begin ------- The gimick of adding an ADV if there is only ADJ VOC ---- --TEXT_IO.PUT_LINE ("About to do the ADJ -> ADV kludge"); for I in Pa'First .. Pa_Last loop if Pa (I).IR.Qual.Pofs = Adv then There_Is_An_Adverb := True; exit; end if; end loop; if (not There_Is_An_Adverb) and (Words_Mode (Do_Fixes)) then Fix_Adverb (Pa, Pa_Last, Xp); end if; end Handle_Adverb; function Analyse_Word (Pa : Parse_Array; Pa_Last : Integer; Raw_Word : String; Xp : Explanations) return Word_Analysis is Var_Pa : Parse_Array := Pa; Var_Pa_Last : Integer := Pa_Last; Var_Xp : Explanations := Xp; W : constant String := Raw_Word; Sraa : Stem_Inflection_Array_Array (1 .. Stem_Inflection_Array_Array_Size) := Null_Sraa; Dma : Dictionary_MNPC_Array := Null_Dma; I_Is_Pa_Last : Boolean := False; WA : Word_Analysis; begin -- Since this procedure weeds out possible parses, if it weeds out all -- (or all of a class) it must fix up the rest of the parse array, -- e.g., it must clean out dangling prefixes and suffixes Trimmed := False; Handle_Adverb (Var_Pa, Var_Pa_Last, Var_Xp); List_Sweep (Var_Pa (1 .. Var_Pa_Last), Var_Pa_Last); Write_Addons_Stats (W, Var_Pa, Var_Pa_Last); Cycle_Over_Pa (Var_Pa, Var_Pa_Last, Sraa, Dma, I_Is_Pa_Last, Raw_Word, W); WA := (Stem_IAA => Sraa, Dict => Dma, I_Is_Pa_Last => I_Is_Pa_Last, Unknowns => Var_Pa_Last = 0, The_Word => To_Unbounded_String (Raw_Word), Was_Trimmed => Trimmed, Xp => Var_Xp); return WA; end Analyse_Word; -- The main WORD processing has been to produce an array of PARSE_RECORD -- as defined in Latin_Utils.Dictionary_Package. -- This has involved STEMFILE and INFLECTS, no DICTFILE -- PARSE_RECORD is put through the LIST_SWEEP procedure that does TRIMing -- Then, for processing for Output, the data is converted to arrays of -- type STEM_INFLECTION_RECORD, defined above, and -- type DICTIONARY_MNPC_RECORD, -- containing the same data plus the DICTFILE data DICTIONARY_ENTRY -- but breaking it into two arrays allows different manipulation -- These are only within this routine, used to clean up the Output procedure List_Stems (Configuration : Configuration_Type; Output : Ada.Text_IO.File_Type; WA : Word_Analysis; Input_Line : String) is Raw_Word : constant String := To_String (WA.The_Word); begin -- Sets + if capitalized -- Strangely enough, it may enter LIST_STEMS with PA_LAST /= 0 -- but be weeded and end up with no parse after -- LIST_SWEEP - PA_LAST = 0 if WA.Unknowns then -- WORD failed List_Unknowns (Input_Line, Raw_Word); end if; -- Exit if UNKNOWNS ONLY (but had to do STATS above) if Words_Mode (Do_Unknowns_Only) then return; -- Omit rest of output end if; Put_Parse_Details (Configuration, Output, WA); if WA.Was_Trimmed then Ada.Text_IO.Put (Output, '*'); end if; Ada.Text_IO.New_Line (Output); exception when Error : others => Ada.Text_IO.Put_Line ("Unexpected exception in LIST_STEMS processing " & Raw_Word); Ada.Text_IO.Put_Line (Exception_Information (Error)); Put_Stat ("EXCEPTION LS at " & Head (Integer'Image (Line_Number), 8) & Head (Integer'Image (Word_Number), 4) & " " & Head (Raw_Word, 20)); raise; end List_Stems; procedure List_Entry (Output : Ada.Text_IO.File_Type; D_K : Dictionary_Kind; Mn : Dict_IO.Count; Mm : Integer) is De : Dictionary_Entry; begin Dict_IO.Read (Dict_File (D_K), De, Mn); Ada.Text_IO.Put (Output, "=> "); --TEXT_IO.PUT_LINE (OUTPUT, DICTIONARY_FORM (DE)); Put_Dictionary_Form (Output, D_K, Mn, De); Ada.Text_IO.Put_Line (Output, Trim (Head (De.Mean, Mm))); -- so it wont line wrap/Put CR end List_Entry; procedure Unknown_Search (Unknown : in String; Unknown_Count : out Dict_IO.Count) is use Stem_Io; D_K : constant Dictionary_Kind := General; J, J1, J2, Jj : Stem_Io.Count := 0; Index_On : constant String := Unknown; Index_First, Index_Last : Stem_Io.Count := 0; Ds : Dictionary_Stem; First_Try, Second_Try : Boolean := True; function First_Two (W : String) return String is -- 'v' could be represented by 'u' -- like the new Oxford Latin Dictionary -- Fixes the first two letters of a word/stem which can be done right S : constant String := Lower_Case (W); Ss : String (W'Range) := W; begin if S'Length = 1 then Ss (S'First) := Support_Utils.Char_Utils.V_To_U_And_J_To_I (W (S'First)); else Ss (S'First) := Support_Utils.Char_Utils.V_To_U_And_J_To_I (W (S'First)); Ss (S'First + 1) := Support_Utils.Char_Utils.V_To_U_And_J_To_I (W (S'First + 1)); end if; return Ss; end First_Two; begin if Dictionary_Available (D_K) then if not Is_Open (Stem_File (D_K)) then Open (Stem_File (D_K), Stem_Io.In_File, Add_File_Name_Extension (Stem_File_Name, Dictionary_Kind'Image (D_K))); end if; Index_First := First_Index (First_Two (Index_On), D_K); Index_Last := Last_Index (First_Two (Index_On), D_K); if Index_First > 0 and then Index_First <= Index_Last then J1 := Index_First; --###################### J2 := Index_Last; First_Try := True; Second_Try := True; J := (J1 + J2) / 2; Binary_Search : loop if (J1 = J2 - 1) or (J1 = J2) then if First_Try then J := J1; First_Try := False; elsif Second_Try then J := J2; Second_Try := False; else Jj := J; exit Binary_Search; end if; end if; Set_Index (Stem_File (D_K), J); Read (Stem_File (D_K), Ds); if Ltu (Lower_Case (Ds.Stem), Unknown) then J1 := J; J := (J1 + J2) / 2; elsif Gtu (Lower_Case (Ds.Stem), Unknown) then J2 := J; J := (J1 + J2) / 2; else for I in reverse J1 .. J loop Set_Index (Stem_File (D_K), Stem_Io.Count (I)); Read (Stem_File (D_K), Ds); if Equ (Lower_Case (Ds.Stem), Unknown) then Jj := I; else exit; end if; end loop; for I in J + 1 .. J2 loop Set_Index (Stem_File (D_K), Stem_Io.Count (I)); Read (Stem_File (D_K), Ds); if Equ (Lower_Case (Ds.Stem), Unknown) then Jj := I; else exit Binary_Search; end if; end loop; exit Binary_Search; end if; end loop Binary_Search; J1 := Jj; J2 := Index_Last; end if; Unknown_Count := Ds.MNPC; Close (Stem_File (D_K)); --?????? end if; --TEXT_IO.PUT_LINE ("Leaving LIST_NEIGHBORHOOD UNKNOWN_SEARCH"); end Unknown_Search; procedure List_Neighborhood (Output : Ada.Text_IO.File_Type; Input_Word : String) is D_K : constant Dictionary_Kind := General; Unk_MNPC : Dict_IO.Count; Mm : constant Integer := Get_Max_Meaning_Size (Output); begin Unknown_Search (Head (Input_Word, Max_Stem_Size), Unk_MNPC); --TEXT_IO.PUT_LINE ("UNK_MNPC = " & INTEGER'IMAGE (INTEGER (UNK_MNPC))); if Integer (Unk_MNPC) > 0 then Ada.Text_IO.Put_Line (Output, "---------- " & "Entries in GENEAL Dictionary around the UNKNOWN" & " ----------"); Pause (Output); for Mn in Dict_IO.Count (Integer (Unk_MNPC) - 5) .. Dict_IO.Count (Integer (Unk_MNPC) + 3) loop List_Entry (Output, D_K, Mn, Mm); end loop; end if; --TEXT_IO.PUT_LINE ("Leaving LIST_NEIGHBORHOOD"); end List_Neighborhood; end Words_Engine.List_Package;
type Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance;
with Ada.Text_IO; -- Tell compiler to use i/o library use Ada.Text_IO; -- Use library routines w/o fully qualified names procedure hello is begin --put("Hello World!\n"); Ada.Text_IO.Put_Line ("Hello world in Ada!"); end hello;
package body OpenGL.Vertex_Array is procedure Enable_Attribute_Array (Index : in Attribute_Index_t) is begin Thin.Enable_Vertex_Attrib_Array (Thin.Unsigned_Integer_t (Index)); end Enable_Attribute_Array; procedure Disable_Attribute_Array (Index : in Attribute_Index_t) is begin Thin.Disable_Vertex_Attrib_Array (Thin.Unsigned_Integer_t (Index)); end Disable_Attribute_Array; procedure Generate_Arrays (Arrays : in out Array_Index_Array_t) is begin Thin.Gen_Vertex_Arrays (Size => Arrays'Length, Arrays => Arrays (Arrays'First)'Address); end Generate_Arrays; procedure Delete_Arrays (Arrays : in Array_Index_Array_t) is begin Thin.Delete_Vertex_Arrays (Size => Arrays'Length, Arrays => Arrays (Arrays'First)'Address); end Delete_Arrays; procedure Draw_Arrays (Mode : in OpenGL.Vertex.Primitive_Type_t; First : in Attribute_Index_t; Count : in Attribute_Count_t) is begin Thin.Draw_Arrays (Mode => Vertex.Primitive_Type_To_Constant (Mode), First => Thin.Integer_t (First), Count => Thin.Size_t (Count)); end Draw_Arrays; -- -- Bind_Array -- procedure Bind_Array (Index : in Array_Index_t) is begin Thin.Bind_Vertex_Array (Thin.Unsigned_Integer_t (Index)); end Bind_Array; -- -- Pointer -- procedure Pointer_Integer (Data : in Vertex_Array_t; Coords_Per_Vertex : in Coords_Per_Vertex_t; Stride : in Natural) is Data_Type : Thin.Enumeration_t; begin case Vertex_Type is when Integer => Data_Type := Thin.GL_INT; when Short => Data_Type := Thin.GL_SHORT; end case; Thin.Vertex_Pointer (Size => Thin.Integer_t (Coords_Per_Vertex), Data_Type => Data_Type, Stride => Thin.Size_t (Stride), Pointer => Data (Data'First)'Address); end Pointer_Integer; procedure Pointer_Float (Data : in Vertex_Array_t; Coords_Per_Vertex : in Coords_Per_Vertex_t; Stride : in Natural) is Data_Type : Thin.Enumeration_t; begin case Vertex_Type is when Float => Data_Type := Thin.GL_FLOAT; when Double => Data_Type := Thin.GL_DOUBLE; end case; Thin.Vertex_Pointer (Size => Thin.Integer_t (Coords_Per_Vertex), Data_Type => Data_Type, Stride => Thin.Size_t (Stride), Pointer => Data (Data'First)'Address); end Pointer_Float; end OpenGL.Vertex_Array;
------------------------------------------------------------------------------- with Text_IO; package body Formatter is -- Instantiated Input-Output packages package IO is new Text_io.Integer_io(Integer); package FIO is new Text_io.Float_io(Float); package DFIO is new Text_io.Float_io(Dp_float); -- Overloaded Data Type to Variant Record conversion functions function F (Data : in Integer) return Contents is begin return Contents'(Class => Integer_Type, Integer_Value => Data); exception when others => return Contents'(Class => Unknown_Type); end F; function F (Data : in Enumerated) return Contents is Data_String : constant String := Enumerated'Image(Data); begin return Contents'(Class => String_Type, String_Value => (The_String => new String'(Data_String), The_Length => Data_String'Length)); exception when others => return Contents'(Class => Unknown_Type); end F; function F (Data : in Float) return Contents is begin return Contents'(Class => Float_Type, Float_Value => Data); exception when others => return Contents'(Class => Unknown_Type); end F; function F (Data : in Dp_Float) return Contents is begin return Contents'(Class => Dp_Float_Type, Dp_Float_Value => Data); exception when others => return Contents'(Class => Unknown_Type); end F; function F (Data : in String) return Contents is begin return Contents'(Class => String_Type, String_Value => (The_String => new String'(Data), The_Length => Data'Length)); exception when others => return Contents'(Class => Unknown_Type); end F; function F (Data : in Character) return Contents is begin return Contents'(Class => Character_Type, Character_Value => Data); exception when others => return Contents'(Class => Unknown_Type); end F; -- Overloaded Print Formatted Value procedures procedure Put(Format : in String; Value : in Values) is begin -- Write formatted string returned by Formatter.Get Text_Io.Put(Get(Format, Value)); end Put; procedure PutS(retStr : in out String; Format : in String; Value : in Values) is begin -- Write formatted string returned by Formatter.Get retStr := Get(Format, Value); end PutS; function SPut(Format : in String; Value : in Values) return String is begin -- Write formatted string returned by Formatter.Get return Get(Format, Value); end SPut; function SPut(Format : in String; Value : in Contents) return String is Value_List : Values(1..1) := (1 => Value); begin return SPut(Format => Format, Value => Value_List); end SPut; procedure Put(Format : in String) is Value_List : Values (1..0); begin Put(Format => Format, Value => Value_List); end Put; procedure Put(Format : in String; Value : in Contents) is Value_List : Values(1..1) := (1 => Value); begin Put(Format => Format, Value => Value_List); end Put; -- Overloaded Formatted Value String functions function Get(Format : in String; Value : in Values) return String is separate; function Get(Format : in String) return String is Value_List : Values (1..0); begin return Get(Format => Format, Value => Value_List); end Get; function Get(Format : in String; Value : in Contents) return String is Value_List : Values(1..1) := (1 => Value); begin return Get(Format => Format, Value => Value_List); end Get; end Formatter; -- separate(FORMATTER)
procedure Goto_Loop is begin <<Start>> null; goto Start; end Goto_Loop;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. package body Apsepp.Generic_Shared_Instance.Creator is ---------------------------------------------------------------------------- Locker : SB_L_Locker (Lock'Access); ---------------------------------------------------------------------------- function Has_Actually_Created return Boolean is (Locker.Has_Actually_Locked); ---------------------------------------------------------------------------- begin if not Just_Pretend and then Locker.Has_Actually_Locked then Deallocation_Needed := True; Instance_Access := Allocate; CB; end if; end Apsepp.Generic_Shared_Instance.Creator;
pragma License (Unrestricted); package Ada.Real_Time.Timing_Events is type Timing_Event is tagged limited private; type Timing_Event_Handler is access protected procedure (Event : in out Timing_Event); -- procedure Set_Handler ( -- Event : in out Timing_Event; -- At_Time : Time; -- Handler : Timing_Event_Handler); -- procedure Set_Handler ( -- Event : in out Timing_Event; -- In_Time : Time_Span; -- Handler : Timing_Event_Handler); -- function Current_Handler (Event : Timing_Event) -- return Timing_Event_Handler; -- procedure Cancel_Handler ( -- Event : in out Timing_Event; -- Cancelled : out Boolean); -- function Time_Of_Event (Event : Timing_Event) return Time; private type Timing_Event is tagged limited null record; end Ada.Real_Time.Timing_Events;
-- generic_example_options -- An example of the use of parse_args with generic option types -- Copyright (c) 2015, James Humphry -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. with Ada.Unchecked_Deallocation; with Parse_Args; use Parse_Args; with Parse_Args.Generic_Discrete_Options; with Parse_Args.Generic_Options; with Parse_Args.Generic_Indefinite_Options; with Parse_Args.Split_CSV; package Generic_Example_Options is type Compass is (North, South, East, West); package Compass_Option is new Generic_Discrete_Options(Element => Compass, Fallback_Default => North); procedure Is_Even(Arg : in Integer; Result : in out Boolean); package Even_Option is new Generic_Discrete_Options(Element => Natural, Fallback_Default => 0, Valid => Is_Even); package Float_Option is new Generic_Options(Element => Float, Fallback_Default => 0.0, Value => Float'Value, Image => Float'Image); type Float_Array is array (Integer range <>) of Float; type Float_Array_Access is access Float_Array; procedure Free_Float_Array is new Ada.Unchecked_Deallocation(Object => Float_Array, Name => Float_Array_Access); function Split_Float_Array is new Split_CSV(Element => Float, Element_Array => Float_Array, Element_Array_Access => Float_Array_Access, Value => Float'Value); function Float_Array_Image(Arg : Float_Array_Access) return String is ("<Float array of length: " & Integer'Image(Arg.all'Length) & ">"); package Float_Array_Option is new Generic_Indefinite_Options(Element => Float_Array, Element_Access => Float_Array_Access, Value => Split_Float_Array, Image => Float_Array_Image, Free_Element => Free_Float_Array); end Generic_Example_Options;
with Ada.Text_IO, Ada.Integer_Text_IO, display, stats, player, inventory_list, Game_Map; use Ada.Text_IO, Ada.Integer_Text_IO, display, stats, player, inventory_list, Game_Map; procedure test is User : Character := 'o'; Level_3 : Coords(1..30, 1..50); Position : Room_Ptr; Map_1 : Map_Type := (1..10 => (1..10 => (Others => Character'Val(178)))); Map_2 : Map_Type := (1..20 => (1..30 => (Others => Character'Val(178)))); Map_3 : Map_Type := (1..30 => (1..50 => (Others => Character'Val(178)))); Destroyed: Integer := 0; My_Player : Player_Type; Room_ID : Integer; begin Initialize(50, 30); -- Mark's Display System (Opposite My Coords) Instantiate; clearCharacter(My_Player); Initialize(Level_3, Position); Link(Level_3, Position, map_3); WipeScreen; Show_Screen(Position, map_3); while (User /= 'q') loop Get_Immediate(User); If (User = 'w') then Move_North(Position, map_3, My_Player, Room_ID); elsif (User = 'a') then Move_West(Position, map_3, My_Player, Room_ID); elsif (User = 's') then Move_South(Position, map_3, My_Player, Room_ID); elsif (User = 'd') then Move_East(Position, map_3, My_Player, Room_ID); end if; If (Empty(Position)) then Show_Screen(Position, map_3); Print(Position, map_3); Else Put_Line("Map has been deleted!"); End If; end loop; end test;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S W I T C H -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package scans switches. Note that the body of Usage must be -- coordinated with the switches that are recognized by this package. -- The Usage package also acts as the official documentation for the -- switches that are recognized. In addition, package Debug documents -- the otherwise undocumented debug switches that are also recognized. package Switch is -- Note: The default switch character is indicated by Switch_Character, -- but regardless of what it is, a hyphen is always allowed as an -- (alternative) switch character. -- Note: In GNAT, the case of switches is not significant if -- Switches_Case_Sensitive is False. If this is the case, switch -- characters, or letters appearing in the parameter to a switch, may be -- either upper case or lower case. ----------------- -- Subprograms -- ----------------- function Is_Switch (Switch_Chars : String) return Boolean; -- Returns True iff Switch_Chars is at least two characters long, -- and the first character indicates it is a switch. function Is_Front_End_Switch (Switch_Chars : String) return Boolean; -- Returns True iff Switch_Chars represents a front-end switch, -- ie. it starts with -I or -gnat. procedure Scan_Front_End_Switches (Switch_Chars : String); procedure Scan_Binder_Switches (Switch_Chars : String); procedure Scan_Make_Switches (Switch_Chars : String); -- Procedures to scan out switches stored in the given string. The first -- character is known to be a valid switch character, and there are no -- blanks or other switch terminator characters in the string, so the -- entire string should consist of valid switch characters, except that -- an optional terminating NUL character is allowed. A bad switch causes -- a fatal error exit and control does not return. The call also sets -- Usage_Requested to True if a ? switch is encountered. end Switch;
with Ada.Calendar; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones; with Ada.Text_Io; use Ada.Text_Io; procedure System_Time is Now : Time := Clock; begin Put_line(Image(Date => Now, Time_Zone => -7*60)); end System_Time;
with Ada.Directories; with Generic_Logging; package body Lal_Adapter.Tool is ------------ -- EXPORTED: ------------ -- LEAKS (only intended to be called once per program execution): procedure Process (This : in out Class; Project_File_Name : in String; Input_File_Name : in String; Output_Dir_Name : in String := Use_Current_Dir; Process_Predefined_Units : in Boolean; Process_Implementation_Units : in Boolean; Debug : in Boolean) is Parent_Name : constant String := Module_Name; Module_Name : constant String := Parent_Name & ".Process"; package Logging is new Generic_Logging (Module_Name); use Logging; Auto : Logging.Auto_Logger; -- Logs BEGIN and END package AD renames Ada.Directories; Full_Input_File_Name : constant String := AD.Full_Name (Input_File_Name); Source_File_Dir : constant String := AD.Containing_Directory (Full_Input_File_Name); Simple_File_Name : aliased String := AD.Simple_Name (Full_Input_File_Name); Full_Output_Dir_Name : constant String := (if Output_Dir_Name = Use_Current_Dir then AD.Current_Directory else AD.Full_Name (Output_Dir_Name)); -- Unit_Options : Unit.Options_Record; -- Initialized begin -- Process Lal_Adapter.Trace_On := Debug; Log ("Project_File_Name => """ & Project_File_Name & """"); Log ("Input_File_Name => """ & Input_File_Name & """"); Log ("Output_Dir_Name => """ & Output_Dir_Name & """"); Log ("Current directory => """ & Ada.Directories.Current_Directory & """"); Log ("Full_Input_File_Name => """ & Full_Input_File_Name & """"); Log ("Full_Output_Dir_Name => """ & Full_Output_Dir_Name & """"); if Input_File_Name = "" then raise Usage_Error with "Input_File_Name must be provided, was empty."; end if; -- Unit_Options.Process_If_Origin_Is (Lal.A_Predefined_Unit) := -- Process_Predefined_Units; -- Unit_Options.Process_If_Origin_Is (Lal.An_Implementation_Unit) := -- Process_Implementation_Units; This.Outputs.Text := new Indented_Text.Class; This.Outputs.Graph := Dot.Graphs.Create (Is_Digraph => True, Is_Strict => False); This.Outputs.A_Nodes := new A_Nodes.Class; -- This.My_Context.Process (Unit_Options => Unit_Options, -- Outputs => This.Outputs); This.My_Context.Process (Input_File_Name => Input_File_Name, Project_File_Name => Project_File_Name, Outputs => This.Outputs); This.Outputs.Graph.Write_File (Full_Output_Dir_Name & '/' & Simple_File_Name); This.Outputs.A_Nodes.Print_Stats; exception when X : External_Error | Internal_Error | Usage_Error => raise; when X: others => Logging.Log_Exception (X); Logging.Log ("No handler for this exception. Raising Internal_Error"); raise Internal_Error; end Process; ------------ -- EXPORTED: ------------ function Get_Nodes (This : in out Class) return a_nodes_h.Nodes_Struct is Parent_Name : constant String := Module_Name; Module_Name : constant String := Parent_Name & ".Get_Nodes"; package Logging is new Generic_Logging (Module_Name); use Logging; begin return This.Outputs.A_Nodes.Get_Nodes; exception when X : External_Error | Internal_Error | Usage_Error => raise; when X: others => Logging.Log_Exception (X); Logging.Log ("No handler for this exception. Raising Internal_Error"); raise Internal_Error; end Get_Nodes; end Lal_Adapter.Tool;
with Ada.Containers.Indefinite_Vectors; package Protypo.Api.Engine_Values.Engine_Value_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Engine_Value); -- package Engine_Value_Vectors is -- subtype Engine_Value_Array is Engine_Value_Vectors.Vector; -- -- No_Value : constant Engine_Value_Array := Engine_Value_Vectors.Empty_Vector; -- -- end Protypo.Api.Engine_Values.Value_Arrays;
-- Copyright 2012-2015 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. procedure Foo is type Discriminants_Record (A : Integer; B : Boolean) is record C : Float; end record; -- The following variable is unused on purpose, and might be -- optimized out by the compiler. Z : Discriminants_Record := (A => 1, B => False, C => 2.0); begin null; end Foo;
with Pig; with Ada.Text_IO; with Ada.Command_Line; procedure automatic_Pig is use Pig; type Robot is new Actor with record Bound: Natural := 20; Final_Run: Natural := 0; end record; function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean; function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean is ((Self.All_Recent < A.Bound) or else (Opponent.Score-100 > A.Final_Run)); function Arg(Position: Positive; Default: Natural) return Natural is package ACL renames Ada.Command_Line; begin return Natural'Value(ACL.Argument(Position)); exception when Constraint_Error => return Default; end Arg; T: Robot := (Bound => Arg(2, 35), Final_Run => Arg(3, 0)); F: Robot := (Bound => Arg(4, 20), Final_Run => Arg(5, 30)); T_Wins: Boolean; Win_Count: array(Boolean) of Natural := (True=> 0, False => 0); begin for I in 1 .. Arg(1, 1000) loop Play(T, F, T_Wins); Win_Count(T_Wins) := Win_Count(T_Wins) + 1; end loop; Ada.Text_IO.Put_Line(Natural'Image(Win_Count(True)) & Natural'Image(Win_Count(False))); end Automatic_Pig;
with STM32.Board; use STM32.Board; with HAL; use HAL; with STM32.GPIO; use STM32.GPIO; with STM32.Device; use STM32.Device; with Ada.Real_Time; use Ada.Real_Time; with STM32.Timers; use STM32.Timers; with STM32.PWM; use STM32.PWM; package control is Selected_Timer : STM32.Timers.Timer renames Timer_4; Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; Servo_Channel : constant Timer_Channel := Channel_1; Motor_Channel : constant Timer_Channel := Channel_2; Seed_Channel : constant Timer_Channel := Channel_3; Soil_Channel : constant Timer_Channel := Channel_4; LED_For : constant array (Timer_Channel) of User_LED := (Channel_1 => Green_LED, Channel_2 => Orange_LED, Channel_3 => Red_LED, Channel_4 => Blue_LED); Requested_Frequency : constant Hertz := 50; -- arbitrary Servo_Control : PWM_Modulator; Motor_Control : PWM_Modulator; Soil_Control : PWM_Modulator; Seed_Control : PWM_Modulator; procedure Intialize_Controls; procedure right; procedure left; procedure forward; procedure backward; procedure front; procedure stop; procedure Drop_Seed; procedure Measure; end control;
----------------------------------------------------------------------- -- util-properties-tests -- Tests for properties -- Copyright (C) 2009, 2010, 2011, 2014, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Text_IO; with Util.Properties; with Util.Properties.Basic; package body Util.Properties.Tests is use Ada.Text_IO; use type Ada.Containers.Count_Type; use Util.Properties.Basic; -- Test -- Properties.Set -- Properties.Exists -- Properties.Get procedure Test_Property (T : in out Test) is Props : Properties.Manager; begin T.Assert (Exists (Props, "test") = False, "Invalid properties"); T.Assert (Exists (Props, +("test")) = False, "Invalid properties"); T.Assert (Props.Is_Empty, "Property manager should be empty"); Props.Set ("test", "toto"); T.Assert (Exists (Props, "test"), "Property was not inserted"); declare V : constant String := Props.Get ("test"); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; declare V : constant Unbounded_String := Props.Get (+("test")); begin T.Assert (V = "toto", "Property was not set correctly"); end; end Test_Property; -- Test basic properties -- Get -- Set procedure Test_Integer_Property (T : in out Test) is Props : Properties.Manager; V : Integer := 23; begin Integer_Property.Set (Props, "test-integer", V); T.Assert (Props.Exists ("test-integer"), "Invalid properties"); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 23, "Property was not inserted"); Integer_Property.Set (Props, "test-integer", 24); V := Integer_Property.Get (Props, "test-integer"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Props, "unknown", 25); T.Assert (V = 25, "Default value must be returned for a Get"); end Test_Integer_Property; -- Test loading of property files procedure Test_Load_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 30, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("root.dir")) = ".", "Invalid property 'root.dir'"); T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar", "Invalid property 'console.lib'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Property; -- ------------------------------ -- Test loading of property files -- ------------------------------ procedure Test_Load_Strip_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin -- Load, filter and strip properties Open (F, In_File, "regtests/test.properties"); Load_Properties (Props, F, "tomcat.", True); Close (F); declare Names : Util.Strings.Vectors.Vector; begin Props.Get_Names (Names); T.Assert (Names.Length > 3, "Loading the test properties returned too few properties"); T.Assert (To_String (Props.Get ("version")) = "0.6", "Invalid property 'root.dir'"); end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties"); raise; end Test_Load_Strip_Property; -- ------------------------------ -- Test copy of properties -- ------------------------------ procedure Test_Copy_Property (T : in out Test) is Props : Properties.Manager; begin Props.Set ("prefix.one", "1"); Props.Set ("prefix.two", "2"); Props.Set ("prefix", "Not copied"); Props.Set ("prefix.", "Copied"); declare Copy : Properties.Manager; begin Copy.Copy (From => Props); T.Assert (Copy.Exists ("prefix.one"), "Property one not found"); T.Assert (Copy.Exists ("prefix.two"), "Property two not found"); T.Assert (Copy.Exists ("prefix"), "Property '' does not exist."); T.Assert (Copy.Exists ("prefix."), "Property '' does not exist."); end; declare Copy : Properties.Manager; begin Copy.Copy (From => Props, Prefix => "prefix.", Strip => True); T.Assert (Copy.Exists ("one"), "Property one not found"); T.Assert (Copy.Exists ("two"), "Property two not found"); T.Assert (Copy.Exists (""), "Property '' does not exist."); end; end Test_Copy_Property; procedure Test_Set_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a"); Props1.Set ("a", "d"); Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")), "Wrong property a in props1"); Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2 := Props1; Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")), "Wrong property a in props2"); Props2.Set ("e", "f"); Props2.Set ("c", "g"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment"); T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment"); Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")), "Wrong property c in props1"); end Test_Set_Preserve_Original; procedure Test_Remove_Preserve_Original (T : in out Test) is Props1 : Properties.Manager; begin Props1.Set ("a", "b"); Props1.Set ("c", "d"); declare Props2 : Properties.Manager; begin Props2 := Props1; T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment"); T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment"); Props1.Remove ("a"); T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1"); T.Assert (Props2.Exists ("a"), "Property a was removed from props2"); Props1 := Props2; -- Release Props2 but the property manager is internally shared so the Props1 is -- not changed. end; Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")), "Wrong property a in props1"); end Test_Remove_Preserve_Original; procedure Test_Missing_Property (T : in out Test) is Props : Properties.Manager; V : Unbounded_String; begin for Pass in 1 .. 2 loop T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; begin V := Props.Get (+("missing")); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted"); -- Check exception on Get returning a String. begin declare S : constant String := Props.Get ("missing"); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; -- Check exception on Get returning a String. begin declare S : constant String := Props.Get (+("missing")); pragma Unreferenced (S); begin T.Fail ("Exception NO_PROPERTY was not raised"); end; exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")), "The Get_Value operation must return a null object"); begin V := Props.Get ("missing"); T.Fail ("Exception NO_PROPERTY was not raised"); exception when NO_PROPERTY => null; end; Props.Set ("c", "d"); end loop; end Test_Missing_Property; procedure Test_Load_Ini_Property (T : in out Test) is Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); declare V : Util.Properties.Value; P : Properties.Manager; begin V := Props.Get_Value ("mysqld"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager; begin P := Props.Get ("mysqld"); T.Assert (P.Exists ("user"), "The [mysqld] property manager should contain a 'user' property"); P := Props.Get ("mysqld_safe"); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare P : Properties.Manager with Unreferenced; begin P := Props.Get ("bad"); T.Fail ("No exception raised for Get()"); exception when NO_PROPERTY => null; end; exception when Ada.Text_IO.Name_Error => Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf"); raise; end Test_Load_Ini_Property; procedure Test_Save_Properties (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("save-props.properties"); begin declare Props : Properties.Manager; F : File_Type; begin Open (F, In_File, "regtests/files/my.cnf"); Load_Properties (Props, F); Close (F); Props.Set ("New-Property", "Some-Value"); Props.Remove ("mysqld"); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed"); Props.Save_Properties (Path); end; declare Props : Properties.Manager; V : Util.Properties.Value; P : Properties.Manager; begin Props.Load_Properties (Path => Path); T.Assert (not Props.Exists ("mysqld"), "mysqld property was not removed (2)"); T.Assert (Props.Exists ("New-Property"), "Invalid Save_Properties"); V := Props.Get_Value ("mysqld_safe"); T.Assert (Util.Properties.Is_Manager (V), "Value 'mysqld_safe' must be a property manager"); P := Util.Properties.To_Manager (V); T.Assert (P.Exists ("socket"), "The [mysqld] property manager should contain a 'socket' property"); end; declare V : Util.Properties.Value; P : Properties.Manager with Unreferenced; begin P := Util.Properties.To_Manager (V); T.Fail ("No exception raised by To_Manager"); exception when Util.Beans.Objects.Conversion_Error => null; end; end Test_Save_Properties; procedure Test_Remove_Property (T : in out Test) is Props : Properties.Manager; begin begin Props.Remove ("missing"); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; begin Props.Remove (+("missing")); T.Fail ("Remove should raise exception"); exception when NO_PROPERTY => null; end; Props.Set ("a", "b"); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove ("a"); T.Assert (not Props.Exists ("a"), "Property not removed"); Props.Set ("a", +("b")); T.Assert (Props.Exists ("a"), "Property not inserted"); Props.Remove (+("a")); T.Assert (not Props.Exists ("a"), "Property not removed"); end Test_Remove_Property; package Caller is new Util.Test_Caller (Test, "Properties.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Set", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Exists", Test_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Remove", Test_Remove_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)", Test_Missing_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set", Test_Integer_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties", Test_Load_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)", Test_Load_Ini_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties", Test_Load_Strip_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Copy", Test_Copy_Property'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign", Test_Set_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove", Test_Remove_Preserve_Original'Access); Caller.Add_Test (Suite, "Test Util.Properties.Save_Properties", Test_Save_Properties'Access); end Add_Tests; end Util.Properties.Tests;
-- C45210A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT AN ENUMERATION IMPOSING AN "UNNATURAL" ORDER ON ALPHABETIC -- CHARACTERS CORRECTLY EVALUATES THE ORDERING OPERATORS. -- RM 15 OCTOBER 1980 -- JWC 7/8/85 RENAMED TO -AB WITH REPORT ; PROCEDURE C45210A IS USE REPORT; TYPE T IS ( 'S' , 'P' , 'M' , 'R' ); MVAR : T := T'('M') ; PVAR : T := T'('P') ; RVAR : T := T'('R') ; SVAR : T := T'('S') ; ERROR_COUNT : INTEGER := 0 ; -- INITIAL VALUE ESSENTIAL PROCEDURE BUMP IS BEGIN ERROR_COUNT := ERROR_COUNT +1 ; END BUMP ; BEGIN TEST( "C45210A" , "CHECK THAT AN ENUMERATION IMPOSING" & " AN ""UNNATURAL"" ORDER ON ALPHABETIC" & " CHARACTERS CORRECTLY EVALUATES THE " & " ORDERING OPERATORS" ) ; -- 256 CASES ( 4 * 4 ORDERED PAIRS OF OPERAND VALUES, -- 4 ORDERING OPERATORS: '<' , '<=' , '>' , '>=' -- (IN THE TABLE: A , B , C , D ) -- 4 VARIABLE/LITERAL FOR LEFT OPERAND, -- VARIABLE/LITERAL FOR RIGHT OPERAND, -- (IN THE TABLE: VV = ALPHA , -- VL = BETA , -- LV = GAMMA , -- LL = DELTA ) RANDOMIZED -- INTO 16 (ONE FOR EACH PAIR OF VALUES) ACCORDING TO THE FOL- -- LOWING GRAECO-LATIN SQUARE (WITH ADDITIONAL PROPERTIES): -- RIGHT OPERAND: 'S' 'P' 'M' 'R' -- LEFT -- OPERAND: -- 'S' A-ALPHA B-BETA C-GAMMA D-DELTA -- 'P' C-DELTA D-GAMMA A-BETA B-ALPHA -- 'M' D-BETA C-ALPHA B-DELTA A-GAMMA -- 'R' B-GAMMA A-DELTA D-ALPHA C-BETA -- (BOTH THE LATIN DIAGONAL AND THE GREEK DIAGONAL CONTAIN 4 -- DISTINCT LETTERS, NON-TRIVIALLY PERMUTED.) -- THE ABOVE DESCRIBES PART 1 OF THE TEST. PART 2 PERFORMS AN -- EXHAUSTIVE VERIFICATION OF THE 'VARIABLE VS. VARIABLE' CASE -- ( VV , ALPHA ) FOR ALL 4 OPERATORS. ----------------------------------------------------------------- -- PART 1 -- 'BUMP' MEANS 'BUMP THE ERROR COUNT' IF T'(SVAR) < T'(SVAR) THEN BUMP ; END IF; IF T'(SVAR) <= T'('P' ) THEN NULL; ELSE BUMP ; END IF; IF T'('S' ) > T'(MVAR) THEN BUMP ; END IF; IF T'('S' ) >= T'('R' ) THEN BUMP ; END IF; IF T'('P' ) > T'('S' ) THEN NULL; ELSE BUMP ; END IF; IF T'('P' ) >= T'(PVAR) THEN NULL; ELSE BUMP ; END IF; IF T'(PVAR) < T'('M' ) THEN NULL; ELSE BUMP ; END IF; IF T'(PVAR) <= T'(RVAR) THEN NULL; ELSE BUMP ; END IF; IF T'(MVAR) >= T'('S' ) THEN NULL; ELSE BUMP ; END IF; IF T'(MVAR) > T'(PVAR) THEN NULL; ELSE BUMP ; END IF; IF T'('M' ) <= T'('M' ) THEN NULL; ELSE BUMP ; END IF; IF T'('M' ) < T'(RVAR) THEN NULL; ELSE BUMP ; END IF; IF T'('R' ) <= T'(SVAR) THEN BUMP ; END IF; IF T'('R' ) < T'('P' ) THEN BUMP ; END IF; IF T'(RVAR) >= T'(MVAR) THEN NULL; ELSE BUMP ; END IF; IF T'(RVAR) > T'('R' ) THEN BUMP ; END IF; IF ERROR_COUNT /= 0 THEN FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE1" ); END IF; ----------------------------------------------------------------- -- PART 2 -- 'BUMP' MEANS 'INCREASE THE COUNT FOR THE NUMBER OF <TRUE>S' ERROR_COUNT := 0 ; FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES IF AVAR < BVAR THEN BUMP ; END IF; -- COUNT +:= 1 END LOOP; END LOOP; IF ERROR_COUNT /= 1 THEN -- THIS IS A PLAIN COUNT, NOT AN -- ERROR COUNT FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE2" ); END IF; ERROR_COUNT := 0 ; FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES IF AVAR <= BVAR THEN BUMP ; END IF; -- COUNT +:= 3 END LOOP; END LOOP; IF ERROR_COUNT /= 3 THEN -- THIS IS A PLAIN COUNT, NOT AN -- ERROR COUNT FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE3" ); END IF; ERROR_COUNT := 0 ; FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES IF AVAR > BVAR THEN BUMP ; END IF; -- COUNT +:= 5 END LOOP; END LOOP; IF ERROR_COUNT /= 5 THEN -- THIS IS A PLAIN COUNT, NOT AN -- ERROR COUNT FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE4" ); END IF; ERROR_COUNT := 0 ; FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES IF AVAR >= BVAR THEN BUMP ; END IF; -- COUNT +:= 7 END LOOP; END LOOP; IF ERROR_COUNT /= 7 THEN -- THIS IS A PLAIN COUNT, NOT AN -- ERROR COUNT FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE5" ); END IF; RESULT; END C45210A;
-- This file is generated by SWIG. Please do *not* modify by hand. -- with speech_tools_c.Pointers; with interfaces.C; package speech_tools_c.pointer_Pointers is -- EST_Wave_Pointer_Pointer -- type EST_Wave_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Wave_Pointer; -- EST_String_Pointer_Pointer -- type EST_String_Pointer_Pointer is access all speech_tools_c.Pointers.EST_String_Pointer; -- EST_Item_featfunc_Pointer_Pointer -- type EST_Item_featfunc_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Item_featfunc_Pointer; -- EST_Item_Pointer_Pointer -- type EST_Item_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Item_Pointer; -- EST_Val_Pointer_Pointer -- type EST_Val_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Val_Pointer; -- LISP_Pointer_Pointer -- type LISP_Pointer_Pointer is access all speech_tools_c.Pointers.LISP_Pointer; -- EST_Ngrammar_Pointer_Pointer -- type EST_Ngrammar_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Ngrammar_Pointer; -- EST_WFST_Pointer_Pointer -- type EST_WFST_Pointer_Pointer is access all speech_tools_c.Pointers.EST_WFST_Pointer; -- EST_Utterance_Pointer_Pointer -- type EST_Utterance_Pointer_Pointer is access all speech_tools_c.Pointers.EST_Utterance_Pointer; -- UnitDatabase_Pointer_Pointer -- type UnitDatabase_Pointer_Pointer is access all speech_tools_c.Pointers.UnitDatabase_Pointer; end speech_tools_c.pointer_Pointers;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; package body Bosch_BNO055 is subtype Register_Address is UInt8; function Value_At (This : in out BNO055_9DOF_IMU; MSB, LSB : Register_Address) return UInt16 with Inline; -- MSB and LSB are the *register addresses* from which to get the values, -- not the values themselves function Value_At (This : in out BNO055_9DOF_IMU; MSB, LSB : Register_Address) return Integer_16 with Inline; -- MSB and LSB are the *register addresses* from which to get the values, -- not the values themselves function To_Integer_16 (LSB, MSB : UInt8) return Integer_16 with Inline; -- returns a signed value, possibly negative based on high-order bit of MSB function As_Self_Test_Results is new Ada.Unchecked_Conversion (Source => UInt8, Target => Self_Test_Results); procedure Set_Units_Register (This : in out BNO055_9DOF_IMU; New_Value : UInt8; Units_Mask : UInt8); -- An internal utility routine. Sets the units bits within the UNIT_SEL -- register to the New_Value. Other bits are not altered. ----------- -- Reset -- ----------- procedure Reset (This : in out BNO055_9DOF_IMU) is Reset_Bit : constant UInt8 := 16#20#; begin Write (This.Port, BNO055_SYS_TRIGGER_ADDR, Value => Reset_Bit); Delay_Milliseconds (650); end Reset; --------------- -- Configure -- --------------- procedure Configure (This : in out BNO055_9DOF_IMU; Operating_Mode : Operating_Modes := Operating_Mode_NDOF; Power_Mode : Power_Modes := Power_Mode_Normal; Use_External_Crystal : Boolean := True) is begin Set_Mode (This, Operating_Mode_Config); -- select register map page zero Write (This.Port, BNO055_PAGE_ID_ADDR, 0); Delay_Milliseconds (10); Write (This.Port, BNO055_PWR_MODE_ADDR, Power_Mode'Enum_Rep); Delay_Milliseconds (10); -- clear interrupt, self-test, and reset bits, conditionally set -- external oscillator bit if Use_External_Crystal then Write (This.Port, BNO055_SYS_TRIGGER_ADDR, Value => 16#80#); else Write (This.Port, BNO055_SYS_TRIGGER_ADDR, Value => 0); end if; Delay_Milliseconds (10); Set_Mode (This, Operating_Mode); -- Note that Set_Mode automatically does a delay at the end so we don't -- need to do it here end Configure; ---------------------------- -- Set_Acceleration_Units -- ---------------------------- procedure Set_Acceleration_Units (This : in out BNO055_9DOF_IMU; Units : Acceleration_Units) is begin Set_Units_Register (This, Units'Enum_Rep, Acceleration_Units_Mask); end Set_Acceleration_Units; ---------------------------- -- Set_Angular_Rate_Units -- ---------------------------- procedure Set_Angular_Rate_Units (This : in out BNO055_9DOF_IMU; Units : Angular_Rate_Units) is begin Set_Units_Register (This, Units'Enum_Rep, Angular_Rate_Units_Mask); end Set_Angular_Rate_Units; --------------------------- -- Set_Euler_Angle_Units -- --------------------------- procedure Set_Euler_Angle_Units (This : in out BNO055_9DOF_IMU; Units : Euler_Angle_Units) is begin Set_Units_Register (This, Units'Enum_Rep, Euler_Angle_Units_Mask); end Set_Euler_Angle_Units; --------------------------- -- Set_Temperature_Units -- --------------------------- procedure Set_Temperature_Units (This : in out BNO055_9DOF_IMU; Units : Temperature_Units) is begin Set_Units_Register (This, Units'Enum_Rep, Temperature_Units_Mask); end Set_Temperature_Units; ------------------------ -- Set_Pitch_Rotation -- ------------------------ procedure Set_Pitch_Rotation (This : in out BNO055_9DOF_IMU; Convention : Pitch_Rotation_Conventions) is begin Set_Units_Register (This, Convention'Enum_Rep, Pitch_Rotation_Convention_Mask); end Set_Pitch_Rotation; -------------------------- -- Selected_Euler_Units -- -------------------------- function Selected_Euler_Units (This : in out BNO055_9DOF_IMU) return Euler_Angle_Units is Value : UInt8; begin Read (This.Port, BNO055_UNIT_SEL_ADDR, Value); if (Value and Euler_Angle_Units_Mask) = Degrees'Enum_Rep then return Degrees; else return Radians; end if; end Selected_Euler_Units; --------------------------------- -- Selected_Acceleration_Units -- --------------------------------- function Selected_Acceleration_Units (This : in out BNO055_9DOF_IMU) return Acceleration_Units is Value : UInt8; begin Read (This.Port, BNO055_UNIT_SEL_ADDR, Value); if (Value and Acceleration_Units_Mask) = Meters_Second_Squared'Enum_Rep then return Meters_Second_Squared; else return Milligravity; end if; end Selected_Acceleration_Units; -------------------------------- -- Selected_Temperature_Units -- -------------------------------- function Selected_Temperature_Units (This : in out BNO055_9DOF_IMU) return Temperature_Units is Value : UInt8; begin Read (This.Port, BNO055_UNIT_SEL_ADDR, Value); if (Value and Temperature_Units_Mask) = Fahrenheit'Enum_Rep then return Fahrenheit; else return Celsius; end if; end Selected_Temperature_Units; --------------- -- Device_Id -- --------------- function Device_Id (This : in out BNO055_9DOF_IMU) return UInt8 is Result : UInt8; begin Read (This.Port, BNO055_CHIP_ID_ADDR, Value => Result); return Result; end Device_Id; -------------- -- Set_Mode -- -------------- procedure Set_Mode (This : in out BNO055_9DOF_IMU; Mode : Operating_Modes) is -- Table 3-6 of the datasheet + 1ms as margin Switching_From_Config_Mode : constant := 8; -- milliseconds Switching_To_Config_Mode : constant := 20; -- milliseconds begin if This.Mode = Operating_Mode_Config then Write (This.Port, BNO055_OPR_MODE_ADDR, Value => Mode'Enum_Rep); Delay_Milliseconds (Switching_From_Config_Mode); else Write (This.Port, BNO055_OPR_MODE_ADDR, Value => Operating_Mode_Config'Enum_Rep); Delay_Milliseconds (Switching_To_Config_Mode); Write (This.Port, BNO055_OPR_MODE_ADDR, Value => Mode'Enum_Rep); Delay_Milliseconds (Switching_From_Config_Mode); end if; This.Mode := Mode; end Set_Mode; ------------------ -- Current_Mode -- ------------------ function Current_Mode (This : in out BNO055_9DOF_IMU) return Operating_Modes is Result : UInt8 := 0; begin Write (This.Port, BNO055_PAGE_ID_ADDR, 0); -- x7, x0 Delay_Milliseconds (10); Read (This.Port, BNO055_OPR_MODE_ADDR, Value => Result); return Operating_Modes'Val (Result and Operating_Mode_Mask); end Current_Mode; ----------------------- -- Get_Revision_Info -- ----------------------- procedure Get_Revision_Info (This : in out BNO055_9DOF_IMU; Info : out Revision_Information) is begin Read (This.Port, BNO055_ACCEL_REV_ID_ADDR, Info.Accelerometer); Read (This.Port, BNO055_MAG_REV_ID_ADDR, Info.Magnetometer); Read (This.Port, BNO055_GYRO_REV_ID_ADDR, Info.Gyroscope); Read (This.Port, BNO055_BL_REV_ID_ADDR, Info.Bootloader); Info.Software := Value_At (This, MSB => BNO055_SW_REV_ID_MSB_ADDR, LSB => BNO055_SW_REV_ID_LSB_ADDR); end Get_Revision_Info; ---------------- -- Get_Status -- ---------------- procedure Get_Status (This : in out BNO055_9DOF_IMU; System_Status : out System_Status_Values; Self_Test : out Self_Test_Results; System_Error : out System_Error_Values) is Value : UInt8; begin Read (This.Port, BNO055_SYS_STAT_ADDR, Value); System_Status := System_Status_Values'Val (Value); Read (This.Port, BNO055_SELFTEST_RESULT_ADDR, Value); Self_Test := As_Self_Test_Results (Value); Read (This.Port, BNO055_SYS_ERR_ADDR, Value); System_Error := System_Error_Values'Val (Value); end Get_Status; ------------------------ -- Sensor_Calibration -- ------------------------ function Sensor_Calibration (This : in out BNO055_9DOF_IMU) return Calibration_States is Data : UInt8; Mask : constant := 2#00000011#; Result : Calibration_States; begin Read (This.Port, BNO055_CALIB_STAT_ADDR, Data); Result.Platform := Shift_Right (Data, 6) and Mask; Result.Gyroscope := Shift_Right (Data, 4) and Mask; Result.Accelerometer := Shift_Right (Data, 2) and Mask; Result.Magnetometer := Data and Mask; return Result; end Sensor_Calibration; -------------------------- -- Calibration_Complete -- -------------------------- function Calibration_Complete (This : in out BNO055_9DOF_IMU; Selection : Sensors_Selection := All_Sensors) return Boolean is States : constant Calibration_States := Sensor_Calibration (This); begin for Sensor of Selection loop case Sensor is when Gyroscope => if States.Gyroscope not in Fully_Calibrated then return False; end if; when Accelerometer => if States.Accelerometer not in Fully_Calibrated then return False; end if; when Magnetometer => if States.Magnetometer not in Fully_Calibrated then return False; end if; end case; end loop; return True; end Calibration_Complete; ---------- -- Data -- ---------- function Output (This : in out BNO055_9DOF_IMU; Kind : Sensor_Data_Kinds) return Sensor_Data is Result : Sensor_Data; Buffer : Sensor_Data_Buffer (0 .. 5); New_X : Integer_16; New_Y : Integer_16; New_Z : Integer_16; LSB : Float; Source : Register_Address; begin case Kind is when Accelerometer_Data => Source := BNO055_ACCEL_DATA_X_LSB_ADDR; when Magnetometer_Data => Source := BNO055_MAG_DATA_X_LSB_ADDR; when Gyroscope_Data => Source := BNO055_GYRO_DATA_X_LSB_ADDR; when Euler_Orientation => Source := BNO055_EULER_H_LSB_ADDR; when Linear_Acceleration_Data => Source := BNO055_LINEAR_ACCEL_DATA_X_LSB_ADDR; when Gravity_Data => Source := BNO055_GRAVITY_DATA_X_LSB_ADDR; end case; Read_Buffer (This.Port, Source, Buffer); -- By reading multiple UInt8s, the device ensures data consistency, -- whereas reading single UInt8s individually does not have that -- guarantee. See the Datasheet, section 3.7 "Data register shadowing" New_X := To_Integer_16 (LSB => Buffer (0), MSB => Buffer (1)); New_Y := To_Integer_16 (LSB => Buffer (2), MSB => Buffer (3)); New_Z := To_Integer_16 (LSB => Buffer (4), MSB => Buffer (5)); case Kind is when Magnetometer_Data => LSB := 16.0; when Euler_Orientation => if Selected_Euler_Units (This) = Degrees then LSB := 16.0; else -- radians LSB := 900.0; end if; when Gyroscope_Data => LSB := 900.0; when Accelerometer_Data => if Selected_Acceleration_Units (This) = Milligravity then LSB := 1.0; else -- Meters_Second_Squared LSB := 100.0; end if; when Linear_Acceleration_Data | Gravity_Data => LSB := 100.0; end case; Result (X) := Float (New_X) / LSB; Result (Y) := Float (New_Y) / LSB; Result (Z) := Float (New_Z) / LSB; return Result; end Output; ---------------------------- -- Quaternion_Orientation -- ---------------------------- function Quaternion_Orientation (This : in out BNO055_9DOF_IMU) return Quaternion is Buffer : Sensor_Data_Buffer (0 .. 7); New_W : Integer_16; New_X : Integer_16; New_Y : Integer_16; New_Z : Integer_16; Result : Quaternion; Scale : constant Float := 1.0 / Float (2 ** 14); -- see section 3.6.5.5 begin Read_Buffer (This.Port, BNO055_QUATERNION_DATA_W_LSB_ADDR, Buffer); -- By reading multiple UInt8s, the device ensures data consistency, -- whereas reading single UInt8s individually does not have that -- guarantee. See the Datasheet, section 3.7 "Data register shadowing" New_W := To_Integer_16 (MSB => Buffer (1), LSB => Buffer (0)); New_X := To_Integer_16 (MSB => Buffer (3), LSB => Buffer (2)); New_Y := To_Integer_16 (MSB => Buffer (5), LSB => Buffer (4)); New_Z := To_Integer_16 (MSB => Buffer (7), LSB => Buffer (6)); Result (1) := Float (New_W) * Scale; Result (2) := Float (New_X) * Scale; Result (3) := Float (New_Y) * Scale; Result (4) := Float (New_Z) * Scale; return Result; end Quaternion_Orientation; ------------------------ -- Sensor_Temperature -- ------------------------ function Sensor_Temperature (This : in out BNO055_9DOF_IMU; Source : Temperature_Source) return Integer_8 is Result : UInt8; begin -- see Datasheet section 3.6.5.8 Write (This.Port, BNO055_TEMP_SOURCE_ADDR, Source'Enum_Rep); Read (This.Port, BNO055_TEMP_ADDR, Value => Result); if Selected_Temperature_Units (This) = Fahrenheit then Result := Result * 2; -- LSB is 2 for Fahrenheit, 1 for Celcius end if; return Integer_8 (Result); end Sensor_Temperature; ------------------------ -- Get_Sensor_Offsets -- ------------------------ function Sensor_Offsets (This : in out BNO055_9DOF_IMU) return Sensor_Offset_Values is Previous_Mode : constant Operating_Modes := This.Mode; Offsets : Sensor_Offset_Values; begin Set_Mode (This, Operating_Mode_Config); Delay_Milliseconds (25); Offsets.Accel_Offset_X := Value_At (This, MSB => ACCEL_OFFSET_X_MSB_ADDR, LSB => ACCEL_OFFSET_X_LSB_ADDR); Offsets.Accel_Offset_Y := Value_At (This, MSB => ACCEL_OFFSET_Y_MSB_ADDR, LSB => ACCEL_OFFSET_Y_LSB_ADDR); Offsets.Accel_Offset_Z := Value_At (This, MSB => ACCEL_OFFSET_Z_MSB_ADDR, LSB => ACCEL_OFFSET_Z_LSB_ADDR); Offsets.Gyro_Offset_X := Value_At (This, MSB => GYRO_OFFSET_X_MSB_ADDR, LSB => GYRO_OFFSET_X_LSB_ADDR); Offsets.Gyro_Offset_Y := Value_At (This, MSB => GYRO_OFFSET_Y_MSB_ADDR, LSB => GYRO_OFFSET_Y_LSB_ADDR); Offsets.Gyro_Offset_Z := Value_At (This, MSB => GYRO_OFFSET_Z_MSB_ADDR, LSB => GYRO_OFFSET_Z_LSB_ADDR); Offsets.Mag_Offset_X := Value_At (This, MSB => MAG_OFFSET_X_MSB_ADDR, LSB => MAG_OFFSET_X_LSB_ADDR); Offsets.Mag_Offset_Y := Value_At (This, MSB => MAG_OFFSET_Y_MSB_ADDR, LSB => MAG_OFFSET_Y_LSB_ADDR); Offsets.Mag_Offset_Z := Value_At (This, MSB => MAG_OFFSET_Z_MSB_ADDR, LSB => MAG_OFFSET_Z_LSB_ADDR); Offsets.Accel_Radius := Value_At (This, MSB => ACCEL_RADIUS_MSB_ADDR, LSB => ACCEL_RADIUS_LSB_ADDR); Offsets.Mag_Radius := Value_At (This, MSB => MAG_RADIUS_MSB_ADDR, LSB => MAG_RADIUS_LSB_ADDR); Set_Mode (This, Previous_Mode); return Offsets; end Sensor_Offsets; ------------------------ -- Set_Sensor_Offsets -- ------------------------ procedure Set_Sensor_Offsets (This : in out BNO055_9DOF_IMU; Offsets : Sensor_Offset_Values) is Previous_Mode : constant Operating_Modes := This.Mode; Outgoing : UInt16; begin Set_Mode (This, Operating_Mode_Config); Delay_Milliseconds (25); Outgoing := UInt16'Mod (Offsets.Accel_Offset_X); Write (This.Port, ACCEL_OFFSET_X_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, ACCEL_OFFSET_X_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Accel_Offset_Y); Write (This.Port, ACCEL_OFFSET_Y_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, ACCEL_OFFSET_Y_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Accel_Offset_Z); Write (This.Port, ACCEL_OFFSET_Z_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, ACCEL_OFFSET_Z_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); -- The Datasheet, section 3.6.4.1 "Accelerometer offset" says the -- configuration only occurs when the MSB of the Z offset is written Outgoing := UInt16'Mod (Offsets.Gyro_Offset_X); Write (This.Port, GYRO_OFFSET_X_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, GYRO_OFFSET_X_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Gyro_Offset_Y); Write (This.Port, GYRO_OFFSET_Y_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, GYRO_OFFSET_Y_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Gyro_Offset_Z); Write (This.Port, GYRO_OFFSET_Z_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, GYRO_OFFSET_Z_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); -- The Datasheet, section 3.6.4.3 "Gyroscope offset" says the -- configuration only occurs when the MSB of the Z offset is written Outgoing := UInt16'Mod (Offsets.Mag_Offset_X); Write (This.Port, MAG_OFFSET_X_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, MAG_OFFSET_X_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Mag_Offset_Y); Write (This.Port, MAG_OFFSET_Y_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, MAG_OFFSET_Y_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); Outgoing := UInt16'Mod (Offsets.Mag_Offset_Z); Write (This.Port, MAG_OFFSET_Z_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, MAG_OFFSET_Z_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); -- The Datasheet, section 3.6.4.2 "Magnetometer offset" says the -- configuration only occurs when the MSB of the Z offset is written Outgoing := UInt16'Mod (Offsets.Accel_Radius); Write (This.Port, ACCEL_RADIUS_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, ACCEL_RADIUS_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); -- The Datasheet, section 3.6.4.4 "Radius" says the -- configuration only occurs when the MSB of the radius is written Outgoing := UInt16'Mod (Offsets.Mag_Radius); Write (This.Port, MAG_RADIUS_LSB_ADDR, Value => UInt8 (Outgoing and 16#FF#)); Write (This.Port, MAG_RADIUS_MSB_ADDR, Value => UInt8 (Shift_Right (Outgoing, 8))); -- The Datasheet, section 3.6.4.4 "Radius" says the -- configuration only occurs when the MSB of the radius is written Set_Mode (This, Previous_Mode); end Set_Sensor_Offsets; ------------------------ -- Set_Units_Register -- ------------------------ procedure Set_Units_Register (This : in out BNO055_9DOF_IMU; New_Value : UInt8; Units_Mask : UInt8) is Value : UInt8; Previous_Mode : constant Operating_Modes := This.Mode; begin if Previous_Mode /= Operating_Mode_Config then Set_Mode (This, Operating_Mode_Config); end if; -- we don't set all the bits within this register in this routine, so we -- read the current value in order to preserve those that are unchanged Read (This.Port, BNO055_UNIT_SEL_ADDR, Value); Value := Value and not Units_Mask; -- clear the bits we're working with here Value := Value or New_Value'Enum_Rep; -- set or clear the bits per the value Write (This.Port, BNO055_UNIT_SEL_ADDR, Value); Delay_Milliseconds (10); if Previous_Mode /= Operating_Mode_Config then Set_Mode (This, Previous_Mode); end if; end Set_Units_Register; ---------------- -- Remap_Axes -- ---------------- procedure Remap_Axes (This : in out BNO055_9DOF_IMU; Map : Axes_Remapping) is New_Mapping : UInt8 := 0; begin New_Mapping := New_Mapping or Axis_Remapping_Selections'Enum_Rep (Map (Z)); New_Mapping := Shift_Left (New_Mapping, 2); New_Mapping := New_Mapping or Axis_Remapping_Selections'Enum_Rep (Map (Y)); New_Mapping := Shift_Left (New_Mapping, 2); New_Mapping := New_Mapping or Axis_Remapping_Selections'Enum_Rep (Map (X)); Write (This.Port, BNO055_AXIS_MAP_CONFIG_ADDR, Value => New_Mapping); Delay_Milliseconds (10); end Remap_Axes; ---------------------- -- Remap_Axes_Signs -- ---------------------- procedure Remap_Axes_Signs (This : in out BNO055_9DOF_IMU; Map : Axes_Sign_Remapping) is New_Mapping : UInt8 := 0; begin New_Mapping := New_Mapping or Axis_Sign_Selections'Enum_Rep (Map (X)); New_Mapping := Shift_Left (New_Mapping, 1); New_Mapping := New_Mapping or Axis_Sign_Selections'Enum_Rep (Map (Y)); New_Mapping := Shift_Left (New_Mapping, 1); New_Mapping := New_Mapping or Axis_Sign_Selections'Enum_Rep (Map (Z)); Write (This.Port, BNO055_AXIS_MAP_SIGN_ADDR, Value => New_Mapping); Delay_Milliseconds (10); end Remap_Axes_Signs; -------------- -- Value_At -- -------------- function Value_At (This : in out BNO055_9DOF_IMU; MSB, LSB : Register_Address) return Integer_16 is High, Low : UInt8; begin Read (This.Port, Register => MSB, Value => High); Read (This.Port, Register => LSB, Value => Low); return To_Integer_16 (LSB => Low, MSB => High); end Value_At; -------------- -- Value_At -- -------------- function Value_At (This : in out BNO055_9DOF_IMU; MSB, LSB : Register_Address) return UInt16 is High, Low : UInt8; Result : UInt16; begin Read (This.Port, Register => MSB, Value => High); Read (This.Port, Register => LSB, Value => Low); Result := UInt16 (High); Result := Shift_Left (Result, 8); Result := Result or UInt16 (Low); return Result; end Value_At; ------------------- -- To_Integer_16 -- ------------------- function To_Integer_16 (LSB : UInt8; MSB : UInt8) return Integer_16 is Result : Integer_32; begin Result := Integer_32 (MSB) * 256; Result := Result + Integer_32 (LSB); if (MSB and 16#80#) /= 0 then Result := -((16#FFFF# - Result) + 1); end if; return Integer_16 (Result); end To_Integer_16; end Bosch_BNO055;
procedure Library (X : Integer) is begin -- Failure pragma Assert (X < 10); -- Success pragma Assert (X > 0); end Library;
pragma Ada_2012; package body EU_Projects.Times.Time_Expressions.Solving is ------------------ -- Add_Equation -- ------------------ procedure Add_Equation (Equations : in out Time_Equation_System; Left : Dotted_Identifier; Right : Symbolic_Duration) is begin if Contains_Left_Term (Equations, Left) then raise Constraint_Error; end if; Equations.M.Insert (Key => Left, New_Item => (Duration_Value, Right.D)); end Add_Equation; ------------------ -- Add_Equation -- ------------------ procedure Add_Equation (Equations : in out Time_Equation_System; Left : Dotted_Identifier; Right : Symbolic_Instant) is begin if Contains_Left_Term (Equations, Left) then raise Constraint_Error; end if; -- Put_Line ("ADD(" & To_String (Left) & "," & Time_Expr.Dump (Right.T) & ")"); Equations.M.Insert (Key => Left, New_Item => (Instant_value, Right.T)); end Add_Equation; ----------- -- Solve -- ----------- function Solve (Equations : Time_Equation_System) return Variable_Map is Eq : Time_Equations.Equation_Tables.Map; R : Time_Expr.Variable_Tables.Map; Success : Boolean; begin for C in Equations.M.Iterate loop Eq.Insert (Key => Equation_Maps.Key (C), New_Item => Equation_Maps.Element (C).Val); end loop; Time_Equations.Triangular_Solve (What => Eq, Result => R, Success => Success); if not Success then raise Unsolvable; end if; declare Result : Variable_Map; begin for C in R.Iterate loop declare use Time_Expr.Variable_Tables; ID : constant Dotted_Identifier := Key (C); Val : constant Scalar_Type := Element (C); begin case Equations.M.Element (ID).Class is when Instant_Value => Result.M.Insert (Key => ID, New_Item => (Class => Instant_Value, I => Instant (Val))); when Duration_Value => Result.M.Insert (Key => ID, New_Item => (Class => Duration_Value, D => Duration (Val))); end case; end; end loop; return Result; end; end Solve; end EU_Projects.Times.Time_Expressions.Solving;
-- Gonzalo Martin Rodriguez -- Ivan Fernandez Samaniego with Priorities; use Priorities; with devices; use devices; with ada.strings.unbounded; use ada.strings.unbounded; with ada.strings.unbounded.text_io; use ada.strings.unbounded.text_io; package Driver is task Distance is pragma Priority (Distance_Priority); end Distance; task Steering is pragma Priority (Steering_Priority); end Steering; task Head is pragma Priority (Head_Priority); end Head; protected Symptoms is pragma Priority (Head_Priority); procedure Write_Head_Symptom (Value: in Boolean); procedure Read_Head_Symptom (Value: out Boolean); procedure Write_Distancia_Insegura (Value: in Boolean); procedure Read_Distancia_Insegura (Value: out Boolean); procedure Write_Distancia_Imprudente (Value: in Boolean); procedure Read_Distancia_Imprudente (Value: out Boolean); procedure Write_Peligro_Colision (Value: in Boolean); procedure Read_Peligro_Colision (Value: out Boolean); procedure Write_Steering_Symptom (Value: in Boolean); procedure Read_Steering_Symptom (Value: out Boolean); procedure Write_HeadPosition; procedure Read_HeadPosition (Value: out HeadPosition_Samples_Type); procedure Write_Steering; procedure Read_Steering (Value: out Steering_Samples_Type); procedure Display_Symptom (Symptom: in Unbounded_String); procedure Show_Symptoms; private Head_Symptom: Boolean := False; Steering_Symptom: Boolean := False; Distancia_Insegura: Boolean := False; Distancia_Imprudente: Boolean := False; Peligro_Colision: Boolean := False; HeadPosition: HeadPosition_Samples_Type := (+2, -2); Steering: Steering_Samples_Type := 0; end Symptoms; protected Measures is pragma Priority (Risk_Priority); procedure Read_Distance (Value: out Distance_Samples_Type); procedure Write_Distance; procedure Show_Distance; procedure Read_Speed (Value: out Speed_Samples_Type); procedure Write_Speed; procedure Show_Speed; private Distance: Distance_Samples_Type; Speed: Speed_Samples_Type; end Measures; end Driver;
-- C32113A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT WHEN A VARIABLE OR CONSTANT HAVING A CONSTRAINED TYPE -- WITH DISCRIMINANTS IS DECLARED WITH AN INITIAL VALUE, -- CONSTRAINT_ERROR IS RAISED IF THE CORRESPONDING DISCRIMINANTS OF -- THE INITIAL VALUE AND THE SUBTYPE DO NOT HAVE THE SAME VALUE. -- HISTORY: -- RJW 07/20/86 -- DWC 06/22/87 ADDED SUBTYPE PRIVAS. ADDED CODE TO PREVENT DEAD -- VARIABLE OPTIMIZATION. WITH REPORT; USE REPORT; PROCEDURE C32113A IS PACKAGE PKG IS TYPE PRIVA (D : INTEGER := 0) IS PRIVATE; SUBTYPE PRIVAS IS PRIVA (IDENT_INT (1)); PRA1 : CONSTANT PRIVAS; TYPE PRIVB (D1, D2 : INTEGER) IS PRIVATE; PRB12 : CONSTANT PRIVB; PRIVATE TYPE PRIVA (D : INTEGER := 0) IS RECORD NULL; END RECORD; TYPE PRIVB (D1, D2 : INTEGER) IS RECORD NULL; END RECORD; PRA1 : CONSTANT PRIVAS := (D => (IDENT_INT (1))); PRB12 : CONSTANT PRIVB := (IDENT_INT (1), IDENT_INT (2)); END PKG; USE PKG; TYPE RECA (D : INTEGER := 0) IS RECORD NULL; END RECORD; TYPE RECB (D1, D2 : INTEGER) IS RECORD NULL; END RECORD; RA1 : CONSTANT RECA (IDENT_INT (1)) := (D => (IDENT_INT (1))); RB12 : CONSTANT RECB := (IDENT_INT (1), IDENT_INT (2)); BEGIN TEST ("C32113A", "CHECK THAT WHEN A VARIABLE OR CONSTANT " & "HAVING A CONSTRAINED TYPE IS DECLARED WITH " & "AN INITIAL VALUE, CONSTRAINT_ERROR IS " & "RAISED IF THE CORRESPONDING DISCRIMINANTS " & "OF THE INITIAL VALUE AND THE SUBTYPE DO " & "NOT HAVE THE SAME VALUE" ); BEGIN DECLARE PR1 : CONSTANT PRIVA (IDENT_INT (0)) := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR1'" ); IF PR1 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR1'" ); END; BEGIN DECLARE PR2 : CONSTANT PRIVA (IDENT_INT (2)) := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR2'" ); IF PR2 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR2'" ); END; BEGIN DECLARE PR3 : PRIVA (IDENT_INT (0)) := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR3'" ); IF PR3 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR3'" ); END; BEGIN DECLARE PR4 : PRIVA (IDENT_INT (2)) := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR4'" ); IF PR4 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR4'" ); END; BEGIN DECLARE SUBTYPE SPRIVA IS PRIVA (IDENT_INT (-1)); PR5 : CONSTANT SPRIVA := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR5'" ); IF PR5 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR5'" ); END; BEGIN DECLARE SUBTYPE SPRIVA IS PRIVA (IDENT_INT (3)); PR6 : SPRIVA := PRA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR6'" ); IF PR6 = PRA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR6'" ); END; BEGIN DECLARE PR7 : CONSTANT PRIVB (IDENT_INT (1), IDENT_INT (1)) := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR7'" ); IF PR7 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR7'" ); END; BEGIN DECLARE PR8 : CONSTANT PRIVB (IDENT_INT (2), IDENT_INT (2)) := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR8'" ); IF PR8 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR8'" ); END; BEGIN DECLARE PR9 : PRIVB (IDENT_INT (1), IDENT_INT (1)) := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR9'" ); IF PR9 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR9'" ); END; BEGIN DECLARE PR10 : PRIVB (IDENT_INT (2), IDENT_INT (2)) := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR10'" ); IF PR10 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR10'" ); END; BEGIN DECLARE SUBTYPE SPRIVB IS PRIVB (IDENT_INT (-1), IDENT_INT (-2)); PR11 : CONSTANT SPRIVB := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR11'" ); IF PR11 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'PR11'" ); END; BEGIN DECLARE SUBTYPE SPRIVB IS PRIVB (IDENT_INT (2), IDENT_INT (1)); PR12 : SPRIVB := PRB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR12'" ); IF PR12 = PRB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'PR12'" ); END; BEGIN DECLARE R1 : CONSTANT RECA (IDENT_INT (0)) := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R1'" ); IF R1 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R1'" ); END; BEGIN DECLARE R2 : CONSTANT RECA (IDENT_INT (2)) := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R2'" ); IF R2 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R2'" ); END; BEGIN DECLARE R3 : RECA (IDENT_INT (0)) := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R3'" ); IF R3 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R3'" ); END; BEGIN DECLARE R4 : RECA (IDENT_INT (2)) := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R4'" ); IF R4 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R4'" ); END; BEGIN DECLARE SUBTYPE SRECA IS RECA (IDENT_INT (-1)); R5 : CONSTANT SRECA := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R5'" ); IF R5 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R5'" ); END; BEGIN DECLARE SUBTYPE SRECA IS RECA (IDENT_INT (3)); R6 : SRECA := RA1; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R6'" ); IF R6 = RA1 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R6'" ); END; BEGIN DECLARE R7 : CONSTANT RECB (IDENT_INT (1), IDENT_INT (1)) := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R7'" ); IF R7 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R7'" ); END; BEGIN DECLARE R8 : CONSTANT RECB (IDENT_INT (2), IDENT_INT (2)) := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R8'" ); IF R8 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R8'" ); END; BEGIN DECLARE R9 : RECB (IDENT_INT (1), IDENT_INT (1)) := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R9'" ); IF R9 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R9'" ); END; BEGIN DECLARE R10 : RECB (IDENT_INT (2), IDENT_INT (2)) := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R10'" ); IF R10 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R10'" ); END; BEGIN DECLARE SUBTYPE SRECB IS RECB (IDENT_INT (-1), IDENT_INT (-2)); R11 : CONSTANT SRECB := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R11'" ); IF R11 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF CONSTANT 'R11'" ); END; BEGIN DECLARE SUBTYPE SRECB IS RECB (IDENT_INT (2), IDENT_INT (1)); R12 : SRECB := RB12; BEGIN FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R12'" ); IF R12 = RB12 THEN COMMENT ("PREVENTING DEAD VARIABLE OPTIMIZATION"); END IF; END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " & "OF VARIABLE 'R12'" ); END; RESULT; END C32113A;
with Ada.Streams.Stream_IO; with Interfaces; package Benchmark_I64 is package ASS_IO renames Ada.Streams.Stream_IO; subtype Long is Long_Integer; procedure Write (N : Long; File_Name : String); procedure Read (N : Long; File_Name : String); end Benchmark_I64;
with AdaM.Any, AdaM.library_Unit, Ada.Containers.Vectors, Ada.Streams; package AdaM.library_Item is type Item is new Any.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_Item (Unit : in AdaM.library_Unit.view) return library_Item.view; procedure free (Self : in out library_Item.view); procedure destruct (Self : in out library_Item.item); -- Attributes -- overriding function Id (Self : access Item) return AdaM.Id; procedure Unit_is (Self : in out Item; Now : AdaM.library_Unit.view); function Unit (Self : in Item) return AdaM.library_Unit.view; private type Item is new Any.item with record library_Unit : AdaM.library_Unit.view; end record; end AdaM.library_Item;
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- This software was developed by John Self of the Arcadia project -- at the University of California, Irvine. -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the University of California, Irvine. The name of the -- University may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -- TITLE DFA construction routines -- AUTHOR: John Self (UCI) -- DESCRIPTION converts non-deterministic finite automatons to finite ones. -- $Header: /dc/uc/self/tmp/gnat_aflex/RCS/dfa.adb,v 1.1 1995/07/04 20:18:39 self Exp self $ with dfa, int_io, misc_defs, text_io, misc, tblcmp, ccl, external_file_manager; with ecs, nfa, tstring, gen, skeleton_manager; use misc_defs, external_file_manager; package body dfa is use TSTRING; -- check_for_backtracking - check a DFA state for backtracking -- -- ds is the number of the state to check and state[) is its out-transitions, -- indexed by equivalence class, and state_rules[) is the set of rules -- associated with this state DID_STK_INIT : BOOLEAN := FALSE; STK : INT_PTR; procedure CHECK_FOR_BACKTRACKING(DS : in INTEGER; STATE : in UNBOUNDED_INT_ARRAY) is use MISC_DEFS; begin if (DFAACC(DS).DFAACC_STATE = 0) then -- state is non-accepting NUM_BACKTRACKING := NUM_BACKTRACKING + 1; if (BACKTRACK_REPORT) then TEXT_IO.PUT(BACKTRACK_FILE, "State #"); INT_IO.PUT(BACKTRACK_FILE, DS, 1); TEXT_IO.PUT(BACKTRACK_FILE, "is non-accepting -"); TEXT_IO.NEW_LINE(BACKTRACK_FILE); -- identify the state DUMP_ASSOCIATED_RULES(BACKTRACK_FILE, DS); -- now identify it further using the out- and jam-transitions DUMP_TRANSITIONS(BACKTRACK_FILE, STATE); TEXT_IO.NEW_LINE(BACKTRACK_FILE); end if; end if; end CHECK_FOR_BACKTRACKING; -- check_trailing_context - check to see if NFA state set constitutes -- "dangerous" trailing context -- -- NOTES -- Trailing context is "dangerous" if both the head and the trailing -- part are of variable size \and/ there's a DFA state which contains -- both an accepting state for the head part of the rule and NFA states -- which occur after the beginning of the trailing context. -- When such a rule is matched, it's impossible to tell if having been -- in the DFA state indicates the beginning of the trailing context -- or further-along scanning of the pattern. In these cases, a warning -- message is issued. -- -- nfa_states[1 .. num_states) is the list of NFA states in the DFA. -- accset[1 .. nacc) is the list of accepting numbers for the DFA state. procedure CHECK_TRAILING_CONTEXT(NFA_STATES : in INT_PTR; NUM_STATES : in INTEGER; ACCSET : in INT_PTR; NACC : in INTEGER) is NS, AR : INTEGER; STATE_VAR, TYPE_VAR : STATE_ENUM; use MISC_DEFS, MISC, TEXT_IO; begin for I in 1 .. NUM_STATES loop NS := NFA_STATES(I); TYPE_VAR := STATE_TYPE(NS); AR := ASSOC_RULE(NS); if ((TYPE_VAR = STATE_NORMAL) or (RULE_TYPE(AR) /= RULE_VARIABLE)) then null; -- do nothing else if (TYPE_VAR = STATE_TRAILING_CONTEXT) then -- potential trouble. Scan set of accepting numbers for -- the one marking the end of the "head". We assume that -- this looping will be fairly cheap since it's rare that -- an accepting number set is large. for J in 1 .. NACC loop if (CHECK_YY_TRAILING_HEAD_MASK(ACCSET(J)) /= 0) then TEXT_IO.PUT(STANDARD_ERROR, "aflex: Dangerous trailing context in rule at line "); INT_IO.PUT(STANDARD_ERROR, RULE_LINENUM(AR), 1); TEXT_IO.NEW_LINE(STANDARD_ERROR); return; end if; end loop; end if; end if; end loop; end CHECK_TRAILING_CONTEXT; -- dump_associated_rules - list the rules associated with a DFA state -- -- goes through the set of NFA states associated with the DFA and -- extracts the first MAX_ASSOC_RULES unique rules, sorts them, -- and writes a report to the given file procedure DUMP_ASSOCIATED_RULES(F : in FILE_TYPE; DS : in INTEGER) is J : INTEGER; NUM_ASSOCIATED_RULES : INTEGER := 0; RULE_SET : INT_PTR; SIZE, RULE_NUM : INTEGER; begin RULE_SET := new UNBOUNDED_INT_ARRAY(0 .. MAX_ASSOC_RULES + 1); SIZE := DFASIZ(DS); for I in 1 .. SIZE loop RULE_NUM := RULE_LINENUM(ASSOC_RULE(DSS(DS)(I))); J := 1; while (J <= NUM_ASSOCIATED_RULES) loop if (RULE_NUM = RULE_SET(J)) then exit; end if; J := J + 1; end loop; if (J > NUM_ASSOCIATED_RULES) then --new rule if (NUM_ASSOCIATED_RULES < MAX_ASSOC_RULES) then NUM_ASSOCIATED_RULES := NUM_ASSOCIATED_RULES + 1; RULE_SET(NUM_ASSOCIATED_RULES) := RULE_NUM; end if; end if; end loop; MISC.BUBBLE(RULE_SET, NUM_ASSOCIATED_RULES); TEXT_IO.PUT(F, " associated rules:"); for I in 1 .. NUM_ASSOCIATED_RULES loop if (I mod 8 = 1) then TEXT_IO.NEW_LINE(F); end if; TEXT_IO.PUT(F, ASCII.HT); INT_IO.PUT(F, RULE_SET(I), 1); end loop; TEXT_IO.NEW_LINE(F); exception when STORAGE_ERROR => MISC.AFLEXFATAL("dynamic memory failure in dump_associated_rules()"); end DUMP_ASSOCIATED_RULES; -- dump_transitions - list the transitions associated with a DFA state -- -- goes through the set of out-transitions and lists them in human-readable -- form (i.e., not as equivalence classes); also lists jam transitions -- (i.e., all those which are not out-transitions, plus EOF). The dump -- is done to the given file. procedure DUMP_TRANSITIONS(F : in FILE_TYPE; STATE : in UNBOUNDED_INT_ARRAY) is EC : INTEGER; OUT_CHAR_SET : C_SIZE_BOOL_ARRAY; begin for I in 1 .. CSIZE loop EC := ECGROUP(I); if (EC < 0) then EC := -EC; end if; OUT_CHAR_SET(I) := (STATE(EC) /= 0); end loop; TEXT_IO.PUT(F, " out-transitions: "); CCL.LIST_CHARACTER_SET(F, OUT_CHAR_SET); -- now invert the members of the set to get the jam transitions for I in 1 .. CSIZE loop OUT_CHAR_SET(I) := not OUT_CHAR_SET(I); end loop; TEXT_IO.NEW_LINE(F); TEXT_IO.PUT(F, "jam-transitions: EOF "); CCL.LIST_CHARACTER_SET(F, OUT_CHAR_SET); TEXT_IO.NEW_LINE(F); end DUMP_TRANSITIONS; -- epsclosure - construct the epsilon closure of a set of ndfa states -- -- NOTES -- the epsilon closure is the set of all states reachable by an arbitrary -- number of epsilon transitions which themselves do not have epsilon -- transitions going out, unioned with the set of states which have non-null -- accepting numbers. t is an array of size numstates of nfa state numbers. -- Upon return, t holds the epsilon closure and numstates is updated. accset -- holds a list of the accepting numbers, and the size of accset is given -- by nacc. t may be subjected to reallocation if it is not large enough -- to hold the epsilon closure. -- -- hashval is the hash value for the dfa corresponding to the state set procedure EPSCLOSURE(T : in out INT_PTR; NS_ADDR : in out INTEGER; ACCSET : in out INT_PTR; NACC_ADDR, HV_ADDR : out INTEGER; RESULT : out INT_PTR) is NS, TSP : INTEGER; NUMSTATES, NACC, HASHVAL, TRANSSYM, NFACCNUM : INTEGER; STKEND : INTEGER; STKPOS : INTEGER; procedure MARK_STATE(STATE : in INTEGER) is begin TRANS1(STATE) := TRANS1(STATE) - MARKER_DIFFERENCE; end MARK_STATE; pragma INLINE(MARK_STATE); function IS_MARKED(STATE : in INTEGER) return BOOLEAN is begin return TRANS1(STATE) < 0; end IS_MARKED; pragma INLINE(IS_MARKED); procedure UNMARK_STATE(STATE : in INTEGER) is begin TRANS1(STATE) := TRANS1(STATE) + MARKER_DIFFERENCE; end UNMARK_STATE; pragma INLINE(UNMARK_STATE); procedure CHECK_ACCEPT(STATE : in INTEGER) is begin NFACCNUM := ACCPTNUM(STATE); if (NFACCNUM /= NIL) then NACC := NACC + 1; ACCSET(NACC) := NFACCNUM; end if; end CHECK_ACCEPT; pragma INLINE(CHECK_ACCEPT); procedure DO_REALLOCATION is begin CURRENT_MAX_DFA_SIZE := CURRENT_MAX_DFA_SIZE + MAX_DFA_SIZE_INCREMENT; NUM_REALLOCS := NUM_REALLOCS + 1; REALLOCATE_INTEGER_ARRAY(T, CURRENT_MAX_DFA_SIZE); REALLOCATE_INTEGER_ARRAY(STK, CURRENT_MAX_DFA_SIZE); end DO_REALLOCATION; pragma INLINE(DO_REALLOCATION); procedure PUT_ON_STACK(STATE : in INTEGER) is begin STKEND := STKEND + 1; if (STKEND >= CURRENT_MAX_DFA_SIZE) then DO_REALLOCATION; end if; STK(STKEND) := STATE; MARK_STATE(STATE); end PUT_ON_STACK; pragma INLINE(PUT_ON_STACK); procedure ADD_STATE(STATE : in INTEGER) is begin NUMSTATES := NUMSTATES + 1; if (NUMSTATES >= CURRENT_MAX_DFA_SIZE) then DO_REALLOCATION; end if; T(NUMSTATES) := STATE; HASHVAL := HASHVAL + STATE; end ADD_STATE; pragma INLINE(ADD_STATE); procedure STACK_STATE(STATE : in INTEGER) is begin PUT_ON_STACK(STATE); CHECK_ACCEPT(STATE); if ((NFACCNUM /= NIL) or (TRANSCHAR(STATE) /= SYM_EPSILON)) then ADD_STATE(STATE); end if; end STACK_STATE; pragma INLINE(STACK_STATE); begin NUMSTATES := NS_ADDR; if (not DID_STK_INIT) then STK := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFA_SIZE); DID_STK_INIT := TRUE; end if; NACC := 0; STKEND := 0; HASHVAL := 0; for NSTATE in 1 .. NUMSTATES loop NS := T(NSTATE); -- the state could be marked if we've already pushed it onto -- the stack if (not IS_MARKED(NS)) then PUT_ON_STACK(NS); null; end if; CHECK_ACCEPT(NS); HASHVAL := HASHVAL + NS; end loop; STKPOS := 1; while (STKPOS <= STKEND) loop NS := STK(STKPOS); TRANSSYM := TRANSCHAR(NS); if (TRANSSYM = SYM_EPSILON) then TSP := TRANS1(NS) + MARKER_DIFFERENCE; if (TSP /= NO_TRANSITION) then if (not IS_MARKED(TSP)) then STACK_STATE(TSP); end if; TSP := TRANS2(NS); if (TSP /= NO_TRANSITION) then if (not IS_MARKED(TSP)) then STACK_STATE(TSP); end if; end if; end if; end if; STKPOS := STKPOS + 1; end loop; -- clear out "visit" markers for CHK_STKPOS in 1 .. STKEND loop if (IS_MARKED(STK(CHK_STKPOS))) then UNMARK_STATE(STK(CHK_STKPOS)); else MISC.AFLEXFATAL("consistency check failed in epsclosure()"); end if; end loop; NS_ADDR := NUMSTATES; HV_ADDR := HASHVAL; NACC_ADDR := NACC; RESULT := T; end EPSCLOSURE; -- increase_max_dfas - increase the maximum number of DFAs procedure INCREASE_MAX_DFAS is begin CURRENT_MAX_DFAS := CURRENT_MAX_DFAS + MAX_DFAS_INCREMENT; NUM_REALLOCS := NUM_REALLOCS + 1; REALLOCATE_INTEGER_ARRAY(BASE, CURRENT_MAX_DFAS); REALLOCATE_INTEGER_ARRAY(DEF, CURRENT_MAX_DFAS); REALLOCATE_INTEGER_ARRAY(DFASIZ, CURRENT_MAX_DFAS); REALLOCATE_INTEGER_ARRAY(ACCSIZ, CURRENT_MAX_DFAS); REALLOCATE_INTEGER_ARRAY(DHASH, CURRENT_MAX_DFAS); REALLOCATE_INT_PTR_ARRAY(DSS, CURRENT_MAX_DFAS); REALLOCATE_DFAACC_UNION(DFAACC, CURRENT_MAX_DFAS); end INCREASE_MAX_DFAS; -- ntod - convert an ndfa to a dfa -- -- creates the dfa corresponding to the ndfa we've constructed. the -- dfa starts out in state #1. procedure NTOD is ACCSET : INT_PTR; DS, NACC, NEWDS : INTEGER; DUPLIST, TARGFREQ, TARGSTATE, STATE : C_SIZE_ARRAY; SYMLIST : C_SIZE_BOOL_ARRAY; HASHVAL, NUMSTATES, DSIZE : INTEGER; NSET, DSET : INT_PTR; TARGPTR, TOTALTRANS, I, J, COMSTATE, COMFREQ, TARG : INTEGER; NUM_START_STATES, TODO_HEAD, TODO_NEXT : INTEGER; SNSRESULT : BOOLEAN; FULL_TABLE_TEMP_FILE : FILE_TYPE; BUF : VSTRING; NUM_NXT_STATES : INTEGER; use TEXT_IO; -- this is so find_table_space(...) will know where to start looking in -- chk/nxt for unused records for space to put in the state begin ACCSET := ALLOCATE_INTEGER_ARRAY(NUM_RULES + 1); NSET := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFA_SIZE); -- the "todo" queue is represented by the head, which is the DFA -- state currently being processed, and the "next", which is the -- next DFA state number available (not in use). We depend on the -- fact that snstods() returns DFA's \in increasing order/, and thus -- need only know the bounds of the dfas to be processed. TODO_HEAD := 0; TODO_NEXT := 0; for CNT in 0 .. CSIZE loop DUPLIST(CNT) := NIL; SYMLIST(CNT) := FALSE; end loop; for CNT in 0 .. NUM_RULES loop ACCSET(CNT) := NIL; end loop; if (TRACE) then NFA.DUMPNFA(SCSET(1)); TEXT_IO.NEW_LINE(STANDARD_ERROR); TEXT_IO.NEW_LINE(STANDARD_ERROR); TEXT_IO.PUT(STANDARD_ERROR, "DFA Dump:"); TEXT_IO.NEW_LINE(STANDARD_ERROR); TEXT_IO.NEW_LINE(STANDARD_ERROR); end if; TBLCMP.INITTBL; if (FULLTBL) then GEN.DO_SECT3_OUT; -- output user code up to ## SKELETON_MANAGER.SKELOUT; -- declare it "short" because it's a real long-shot that that -- won't be large enough begin -- make a temporary file to write yy_nxt array into CREATE(FULL_TABLE_TEMP_FILE, OUT_FILE); exception when USE_ERROR | NAME_ERROR => MISC.AFLEXFATAL("can't create temporary file"); end; NUM_NXT_STATES := 1; TEXT_IO.PUT(FULL_TABLE_TEMP_FILE, "( "); -- generate 0 entries for state #0 for CNT in 0 .. NUMECS loop MISC.MK2DATA(FULL_TABLE_TEMP_FILE, 0); end loop; TEXT_IO.PUT(FULL_TABLE_TEMP_FILE, " )"); -- force extra blank line next dataflush() DATALINE := NUMDATALINES; end if; -- create the first states NUM_START_STATES := LASTSC*2; for CNT in 1 .. NUM_START_STATES loop NUMSTATES := 1; -- for each start condition, make one state for the case when -- we're at the beginning of the line (the '%' operator) and -- one for the case when we're not if (CNT mod 2 = 1) then NSET(NUMSTATES) := SCSET((CNT/2) + 1); else NSET(NUMSTATES) := NFA.MKBRANCH(SCBOL(CNT/2), SCSET(CNT/2)); end if; DFA.EPSCLOSURE(NSET, NUMSTATES, ACCSET, NACC, HASHVAL, NSET); SNSTODS(NSET, NUMSTATES, ACCSET, NACC, HASHVAL, DS, SNSRESULT); if (SNSRESULT) then NUMAS := NUMAS + NACC; TOTNST := TOTNST + NUMSTATES; TODO_NEXT := TODO_NEXT + 1; if (VARIABLE_TRAILING_CONTEXT_RULES and (NACC > 0)) then CHECK_TRAILING_CONTEXT(NSET, NUMSTATES, ACCSET, NACC); end if; end if; end loop; SNSTODS(NSET, 0, ACCSET, 0, 0, END_OF_BUFFER_STATE, SNSRESULT); if (not SNSRESULT) then MISC.AFLEXFATAL("could not create unique end-of-buffer state"); end if; NUMAS := NUMAS + 1; NUM_START_STATES := NUM_START_STATES + 1; TODO_NEXT := TODO_NEXT + 1; while (TODO_HEAD < TODO_NEXT) loop NUM_NXT_STATES := NUM_NXT_STATES + 1; TARGPTR := 0; TOTALTRANS := 0; for STATE_CNT in 1 .. NUMECS loop STATE(STATE_CNT) := 0; end loop; TODO_HEAD := TODO_HEAD + 1; DS := TODO_HEAD; DSET := DSS(DS); DSIZE := DFASIZ(DS); if (TRACE) then TEXT_IO.PUT(STANDARD_ERROR, "state # "); INT_IO.PUT(STANDARD_ERROR, DS, 1); TEXT_IO.PUT_LINE(STANDARD_ERROR, ":"); end if; SYMPARTITION(DSET, DSIZE, SYMLIST, DUPLIST); for SYM in 1 .. NUMECS loop if (SYMLIST(SYM)) then SYMLIST(SYM) := FALSE; if (DUPLIST(SYM) = NIL) then -- symbol has unique out-transitions NUMSTATES := SYMFOLLOWSET(DSET, DSIZE, SYM, NSET); DFA.EPSCLOSURE(NSET, NUMSTATES, ACCSET, NACC, HASHVAL, NSET); SNSTODS(NSET, NUMSTATES, ACCSET, NACC, HASHVAL, NEWDS, SNSRESULT); if (SNSRESULT) then TOTNST := TOTNST + NUMSTATES; TODO_NEXT := TODO_NEXT + 1; NUMAS := NUMAS + NACC; if (VARIABLE_TRAILING_CONTEXT_RULES and (NACC > 0)) then CHECK_TRAILING_CONTEXT(NSET, NUMSTATES, ACCSET, NACC); end if; end if; STATE(SYM) := NEWDS; if (TRACE) then TEXT_IO.PUT(STANDARD_ERROR, ASCII.HT); INT_IO.PUT(STANDARD_ERROR, SYM, 1); TEXT_IO.PUT(STANDARD_ERROR, ASCII.HT); INT_IO.PUT(STANDARD_ERROR, NEWDS, 1); TEXT_IO.NEW_LINE(STANDARD_ERROR); end if; TARGPTR := TARGPTR + 1; TARGFREQ(TARGPTR) := 1; TARGSTATE(TARGPTR) := NEWDS; NUMUNIQ := NUMUNIQ + 1; else -- sym's equivalence class has the same transitions -- as duplist(sym)'s equivalence class TARG := STATE(DUPLIST(SYM)); STATE(SYM) := TARG; if (TRACE) then TEXT_IO.PUT(STANDARD_ERROR, ASCII.HT); INT_IO.PUT(STANDARD_ERROR, SYM, 1); TEXT_IO.PUT(STANDARD_ERROR, ASCII.HT); INT_IO.PUT(STANDARD_ERROR, TARG, 1); TEXT_IO.NEW_LINE(STANDARD_ERROR); end if; -- update frequency count for destination state I := 1; while (TARGSTATE(I) /= TARG) loop I := I + 1; end loop; TARGFREQ(I) := TARGFREQ(I) + 1; NUMDUP := NUMDUP + 1; end if; TOTALTRANS := TOTALTRANS + 1; DUPLIST(SYM) := NIL; end if; end loop; NUMSNPAIRS := NUMSNPAIRS + TOTALTRANS; if (CASEINS and not USEECS) then I := CHARACTER'POS('A'); J := CHARACTER'POS('a'); while (I < CHARACTER'POS('Z')) loop STATE(I) := STATE(J); I := I + 1; J := J + 1; end loop; end if; if (DS > NUM_START_STATES) then CHECK_FOR_BACKTRACKING(DS, STATE); end if; if (FULLTBL) then -- supply array's 0-element TEXT_IO.PUT(FULL_TABLE_TEMP_FILE, ","); MISC.DATAFLUSH(FULL_TABLE_TEMP_FILE); TEXT_IO.PUT(FULL_TABLE_TEMP_FILE, "( "); if (DS = END_OF_BUFFER_STATE) then MISC.MK2DATA(FULL_TABLE_TEMP_FILE, -END_OF_BUFFER_STATE); else MISC.MK2DATA(FULL_TABLE_TEMP_FILE, END_OF_BUFFER_STATE); end if; for CNT in 1 .. NUMECS loop -- jams are marked by negative of state number if ((STATE(CNT) /= 0)) then MISC.MK2DATA(FULL_TABLE_TEMP_FILE, STATE(CNT)); else MISC.MK2DATA(FULL_TABLE_TEMP_FILE, -DS); end if; end loop; TEXT_IO.PUT(FULL_TABLE_TEMP_FILE, " )"); -- force extra blank line next dataflush() DATALINE := NUMDATALINES; else if (DS = END_OF_BUFFER_STATE) then -- special case this state to make sure it does what it's -- supposed to, i.e., jam on end-of-buffer TBLCMP.STACK1(DS, 0, 0, JAMSTATE_CONST); else -- normal, compressed state -- determine which destination state is the most common, and -- how many transitions to it there are COMFREQ := 0; COMSTATE := 0; for CNT in 1 .. TARGPTR loop if (TARGFREQ(CNT) > COMFREQ) then COMFREQ := TARGFREQ(CNT); COMSTATE := TARGSTATE(CNT); end if; end loop; TBLCMP.BLDTBL(STATE, DS, TOTALTRANS, COMSTATE, COMFREQ); end if; end if; end loop; if (FULLTBL) then TEXT_IO.PUT("yy_nxt : constant array(0.."); INT_IO.PUT(NUM_NXT_STATES - 1, 1); TEXT_IO.PUT_LINE(" , ASCII.NUL..ASCII.DEL) of short :="); TEXT_IO.PUT_LINE(" ("); RESET(FULL_TABLE_TEMP_FILE, IN_FILE); while (not END_OF_FILE(FULL_TABLE_TEMP_FILE)) loop TSTRING.GET_LINE(FULL_TABLE_TEMP_FILE, BUF); TSTRING.PUT_LINE(BUF); end loop; DELETE(FULL_TABLE_TEMP_FILE); MISC.DATAEND; else TBLCMP.CMPTMPS; -- create compressed template entries -- create tables for all the states with only one out-transition while (ONESP > 0) loop TBLCMP.MK1TBL(ONESTATE(ONESP), ONESYM(ONESP), ONENEXT(ONESP), ONEDEF( ONESP)); ONESP := ONESP - 1; end loop; TBLCMP.MKDEFTBL; end if; end NTOD; -- snstods - converts a set of ndfa states into a dfa state -- -- on return, the dfa state number is in newds. procedure SNSTODS(SNS : in INT_PTR; NUMSTATES : in INTEGER; ACCSET : in INT_PTR; NACC, HASHVAL : in INTEGER; NEWDS_ADDR : out INTEGER; RESULT : out BOOLEAN) is DIDSORT : BOOLEAN := FALSE; J : INTEGER; NEWDS : INTEGER; OLDSNS : INT_PTR; begin for I in 1 .. LASTDFA loop if (HASHVAL = DHASH(I)) then if (NUMSTATES = DFASIZ(I)) then OLDSNS := DSS(I); if (not DIDSORT) then -- we sort the states in sns so we can compare it to -- oldsns quickly. we use bubble because there probably -- aren't very many states MISC.BUBBLE(SNS, NUMSTATES); DIDSORT := TRUE; end if; J := 1; while (J <= NUMSTATES) loop if (SNS(J) /= OLDSNS(J)) then exit; end if; J := J + 1; end loop; if (J > NUMSTATES) then DFAEQL := DFAEQL + 1; NEWDS_ADDR := I; RESULT := FALSE; return; end if; HSHCOL := HSHCOL + 1; else HSHSAVE := HSHSAVE + 1; end if; end if; end loop; -- make a new dfa LASTDFA := LASTDFA + 1; if (LASTDFA >= CURRENT_MAX_DFAS) then INCREASE_MAX_DFAS; end if; NEWDS := LASTDFA; DSS(NEWDS) := new UNBOUNDED_INT_ARRAY(0 .. NUMSTATES + 1); -- if we haven't already sorted the states in sns, we do so now, so that -- future comparisons with it can be made quickly if (not DIDSORT) then MISC.BUBBLE(SNS, NUMSTATES); end if; for I in 1 .. NUMSTATES loop DSS(NEWDS)(I) := SNS(I); end loop; DFASIZ(NEWDS) := NUMSTATES; DHASH(NEWDS) := HASHVAL; if (NACC = 0) then DFAACC(NEWDS).DFAACC_STATE := 0; ACCSIZ(NEWDS) := 0; else -- find lowest numbered rule so the disambiguating rule will work J := NUM_RULES + 1; for I in 1 .. NACC loop if (ACCSET(I) < J) then J := ACCSET(I); end if; end loop; DFAACC(NEWDS).DFAACC_STATE := J; end if; NEWDS_ADDR := NEWDS; RESULT := TRUE; return; exception when STORAGE_ERROR => MISC.AFLEXFATAL("dynamic memory failure in snstods()"); end SNSTODS; -- symfollowset - follow the symbol transitions one step function SYMFOLLOWSET(DS : in INT_PTR; DSIZE, TRANSSYM : in INTEGER; NSET : in INT_PTR) return INTEGER is NS, TSP, SYM, LENCCL, CH, NUMSTATES, CCLLIST : INTEGER; begin NUMSTATES := 0; for I in 1 .. DSIZE loop -- for each nfa state ns in the state set of ds NS := DS(I); SYM := TRANSCHAR(NS); TSP := TRANS1(NS); if (SYM < 0) then -- it's a character class SYM := -SYM; CCLLIST := CCLMAP(SYM); LENCCL := CCLLEN(SYM); if (CCLNG(SYM) /= 0) then for J in 0 .. LENCCL - 1 loop -- loop through negated character class CH := CHARACTER'POS(CCLTBL(CCLLIST + J)); if (CH > TRANSSYM) then exit; -- transsym isn't in negated ccl else if (CH = TRANSSYM) then goto BOTTOM; -- next 2 end if; end if; end loop; -- didn't find transsym in ccl NUMSTATES := NUMSTATES + 1; NSET(NUMSTATES) := TSP; else for J in 0 .. LENCCL - 1 loop CH := CHARACTER'POS(CCLTBL(CCLLIST + J)); if (CH > TRANSSYM) then exit; else if (CH = TRANSSYM) then NUMSTATES := NUMSTATES + 1; NSET(NUMSTATES) := TSP; exit; end if; end if; end loop; end if; else if ((SYM >= CHARACTER'POS('A')) and (SYM <= CHARACTER'POS('Z')) and CASEINS) then MISC.AFLEXFATAL("consistency check failed in symfollowset"); else if (SYM = SYM_EPSILON) then null; -- do nothing else if (ECGROUP(SYM) = TRANSSYM) then NUMSTATES := NUMSTATES + 1; NSET(NUMSTATES) := TSP; end if; end if; end if; end if; <<BOTTOM>> null; end loop; return NUMSTATES; end SYMFOLLOWSET; -- sympartition - partition characters with same out-transitions procedure SYMPARTITION(DS : in INT_PTR; NUMSTATES : in INTEGER; SYMLIST : in out C_SIZE_BOOL_ARRAY; DUPLIST : in out C_SIZE_ARRAY) is TCH, J, NS, LENCCL, CCLP, ICH : INTEGER; DUPFWD : C_SIZE_ARRAY; -- partitioning is done by creating equivalence classes for those -- characters which have out-transitions from the given state. Thus -- we are really creating equivalence classes of equivalence classes. begin for I in 1 .. NUMECS loop -- initialize equivalence class list DUPLIST(I) := I - 1; DUPFWD(I) := I + 1; end loop; DUPLIST(1) := NIL; DUPFWD(NUMECS) := NIL; DUPFWD(0) := 0; for I in 1 .. NUMSTATES loop NS := DS(I); TCH := TRANSCHAR(NS); if (TCH /= SYM_EPSILON) then if ((TCH < -LASTCCL) or (TCH > CSIZE)) then MISC.AFLEXFATAL("bad transition character detected in sympartition()") ; end if; if (TCH > 0) then -- character transition ECS.MKECHAR(ECGROUP(TCH), DUPFWD, DUPLIST); SYMLIST(ECGROUP(TCH)) := TRUE; else -- character class TCH := -TCH; LENCCL := CCLLEN(TCH); CCLP := CCLMAP(TCH); ECS.MKECCL(CCLTBL(CCLP .. CCLP + LENCCL), LENCCL, DUPFWD, DUPLIST, NUMECS); if (CCLNG(TCH) /= 0) then J := 0; for K in 0 .. LENCCL - 1 loop ICH := CHARACTER'POS(CCLTBL(CCLP + K)); J := J + 1; while (J < ICH) loop SYMLIST(J) := TRUE; J := J + 1; end loop; end loop; J := J + 1; while (J <= NUMECS) loop SYMLIST(J) := TRUE; J := J + 1; end loop; else for K in 0 .. LENCCL - 1 loop ICH := CHARACTER'POS(CCLTBL(CCLP + K)); SYMLIST(ICH) := TRUE; end loop; end if; end if; end if; end loop; end SYMPARTITION; end dfa;
-------------------------------------------------------------------------------- -- Copyright (c) 2013, Felix Krause <contact@flyx.org> -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -------------------------------------------------------------------------------- private package CL.Enumerations is ----------------------------------------------------------------------------- -- OpenCL error codes -- ------------------ -- Literals are prefixed E_* to avoid confusion with the corresponding -- exceptions. ----------------------------------------------------------------------------- type Error_Code is (E_Invalid_Global_Work_Size, E_Invalid_Mip_Level, E_Invalid_Buffer_Size, E_Invalid_GL_Object, E_Invalid_Operation, E_Invalid_Event, E_Invalid_Event_Wait_List, E_Invalid_Global_Offset, E_Invalid_Work_Item_Size, E_Invalid_Work_Group_Size, E_Invalid_Work_Dimension, E_Invalid_Kernel_Args, E_Invalid_Arg_Size, E_Invalid_Arg_Value, E_Invalid_Arg_Index, E_Invalid_Kernel, E_Invalid_Kernel_Definition, E_Invalid_Kernel_Name, E_Invalid_Program_Executable, E_Invalid_Program, E_Invalid_Build_Options, E_Invalid_Binary, E_Invalid_Sampler, E_Invalid_Image_Size, E_Invalid_Image_Format_Descriptor, E_Invalid_Mem_Object, E_Invalid_Host_Ptr, E_Invalid_Command_Queue, E_Invalid_Queue_Properties, E_Invalid_Context, E_Invalid_Device, E_Invalid_Platform, E_Invalid_Device_Type, E_Invalid_Value, E_Kernel_Arg_Info_Not_Available, E_Device_Partition_Failed, E_Link_Program_Failure, E_Linker_Not_Available, E_Compile_Program_Failure, E_Exec_Status_Error_For_Events_In_Wait_List, E_Misaligned_Sub_Buffer_Offset,E_Map_Failure, E_Build_Program_Failure, E_Image_Format_Not_Supported, E_Image_Format_Mismatch, E_Mem_Copy_Overlap, E_Profiling_Info_Not_Available, E_Out_Of_Host_Memory, E_Out_Of_Resources, E_Mem_Object_Allocation_Failure, E_Compiler_Not_Available, E_Device_Not_Available, E_Device_Not_Found, E_Success); for Error_Code use (E_Invalid_Global_Work_Size => -63, E_Invalid_Mip_Level => -62, E_Invalid_Buffer_Size => -61, E_Invalid_GL_Object => -60, E_Invalid_Operation => -59, E_Invalid_Event => -58, E_Invalid_Event_Wait_List => -57, E_Invalid_Global_Offset => -56, E_Invalid_Work_Item_Size => -55, E_Invalid_Work_Group_Size => -54, E_Invalid_Work_Dimension => -53, E_Invalid_Kernel_Args => -52, E_Invalid_Arg_Size => -51, E_Invalid_Arg_Value => -50, E_Invalid_Arg_Index => -49, E_Invalid_Kernel => -48, E_Invalid_Kernel_Definition => -47, E_Invalid_Kernel_Name => -46, E_Invalid_Program_Executable => -45, E_Invalid_Program => -44, E_Invalid_Build_Options => -43, E_Invalid_Binary => -42, E_Invalid_Sampler => -41, E_Invalid_Image_Size => -40, E_Invalid_Image_Format_Descriptor => -39, E_Invalid_Mem_Object => -38, E_Invalid_Host_Ptr => -37, E_Invalid_Command_Queue => -36, E_Invalid_Queue_Properties => -35, E_Invalid_Context => -34, E_Invalid_Device => -33, E_Invalid_Platform => -32, E_Invalid_Device_Type => -31, E_Invalid_Value => -30, E_Kernel_Arg_Info_Not_Available => -19, E_Device_Partition_Failed => -18, E_Link_Program_Failure => -17, E_Linker_Not_Available => -16, E_Compile_Program_Failure => -15, E_Exec_Status_Error_For_Events_In_Wait_List => -14, E_Misaligned_Sub_Buffer_Offset => -13, E_Map_Failure => -12, E_Build_Program_Failure => -11, E_Image_Format_Not_Supported => -10, E_Image_Format_Mismatch => -9, E_Mem_Copy_Overlap => -8, E_Profiling_Info_Not_Available => -7, E_Out_Of_Host_Memory => -6, E_Out_Of_Resources => -5, E_Mem_Object_Allocation_Failure => -4, E_Compiler_Not_Available => -3, E_Device_Not_Available => -2, E_Device_Not_Found => -1, E_Success => 0); for Error_Code'Size use Int'Size; type Error_Ptr is access all CL.Enumerations.Error_Code; pragma Convention (C, Error_Ptr); type Platform_Info is (Profile, Version, Name, Vendor, Extensions); for Platform_Info use (Profile => 16#0900#, Version => 16#0901#, Name => 16#0902#, Vendor => 16#0903#, Extensions => 16#0904#); for Platform_Info'Size use UInt'Size; type Device_Info is (Dev_Type, Vendor_ID, Max_Compute_Units, Max_Work_Item_Dimensions, Max_Work_Group_Size, Max_Work_Item_Sizes, Preferred_Vector_Width_Char, Preferred_Vector_Width_Short, Preferred_Vector_Width_Int, Preferred_Vector_Width_Long, Preferred_Vector_Width_Float, Preferred_Vector_Width_Double, Max_Clock_Frequency, Address_Bits, Max_Read_Image_Args, Max_Write_Image_Args, Max_Mem_Alloc_Size, Image2D_Max_Width, Image2D_Max_Height, Image3D_Max_Width, Image3D_Max_Height, Image3D_Max_Depth, Image_Support, Max_Parameter_Size, Max_Samplers, Mem_Base_Addr_Align, Min_Data_Type_Align_Size, Single_FP_Config, Global_Mem_Cache_Type, Global_Mem_Cacheline_Size, Global_Mem_Cache_Size, Global_Mem_Size, Max_Constant_Buffer_Size, Max_Constant_Args, Local_Mem_Type, Local_Mem_Size, Error_Correction_Support, Profiling_Timer_Resolution, Endian_Little, Available, Compiler_Available, Execution_Capabilities, Queue_Properties, Name, Vendor, Driver_Version, Profile, Version, Extensions, Platform, Preferred_Vector_Width_Half, Host_Unified_Memory, Native_Vector_Width_Char, Native_Vector_Width_Short, Native_Vector_Width_Int, Native_Vector_Width_Long, Native_Vector_Width_Float, Native_Vector_Width_Double, Native_Vector_Width_Half, OpenCL_C_Version); for Device_Info use (Dev_Type => 16#1000#, Vendor_ID => 16#1001#, Max_Compute_Units => 16#1002#, Max_Work_Item_Dimensions => 16#1003#, Max_Work_Group_Size => 16#1004#, Max_Work_Item_Sizes => 16#1005#, Preferred_Vector_Width_Char => 16#1006#, Preferred_Vector_Width_Short => 16#1007#, Preferred_Vector_Width_Int => 16#1008#, Preferred_Vector_Width_Long => 16#1009#, Preferred_Vector_Width_Float => 16#100A#, Preferred_Vector_Width_Double => 16#100B#, Max_Clock_Frequency => 16#100C#, Address_Bits => 16#100D#, Max_Read_Image_Args => 16#100E#, Max_Write_Image_Args => 16#100F#, Max_Mem_Alloc_Size => 16#1010#, Image2D_Max_Width => 16#1011#, Image2D_Max_Height => 16#1012#, Image3D_Max_Width => 16#1013#, Image3D_Max_Height => 16#1014#, Image3D_Max_Depth => 16#1015#, Image_Support => 16#1016#, Max_Parameter_Size => 16#1017#, Max_Samplers => 16#1018#, Mem_Base_Addr_Align => 16#1019#, Min_Data_Type_Align_Size => 16#101A#, Single_FP_Config => 16#101B#, Global_Mem_Cache_Type => 16#101C#, Global_Mem_Cacheline_Size => 16#101D#, Global_Mem_Cache_Size => 16#101E#, Global_Mem_Size => 16#101F#, Max_Constant_Buffer_Size => 16#1020#, Max_Constant_Args => 16#1021#, Local_Mem_Type => 16#1022#, Local_Mem_Size => 16#1023#, Error_Correction_Support => 16#1024#, Profiling_Timer_Resolution => 16#1025#, Endian_Little => 16#1026#, Available => 16#1027#, Compiler_Available => 16#1028#, Execution_Capabilities => 16#1029#, Queue_Properties => 16#102A#, Name => 16#102B#, Vendor => 16#102C#, Driver_Version => 16#102D#, Profile => 16#102E#, Version => 16#102F#, Extensions => 16#1030#, Platform => 16#1031#, -- 0x1032 and 0x1033 are reserved but not yet used Preferred_Vector_Width_Half => 16#1034#, Host_Unified_Memory => 16#1035#, Native_Vector_Width_Char => 16#1036#, Native_Vector_Width_Short => 16#1037#, Native_Vector_Width_Int => 16#1038#, Native_Vector_Width_Long => 16#1039#, Native_Vector_Width_Float => 16#103A#, Native_Vector_Width_Double => 16#103B#, Native_Vector_Width_Half => 16#103C#, OpenCL_C_Version => 16#103D#); for Device_Info'Size use UInt'Size; type Context_Info is (Reference_Count, Devices, Properties, Num_Devices, Platform); for Context_Info use (Reference_Count => 16#1080#, Devices => 16#1081#, Properties => 16#1082#, Num_Devices => 16#1083#, Platform => 16#1084#); for Context_Info'Size use CL.UInt'Size; type Command_Queue_Info is (Queue_Context, Queue_Device, Reference_Count, Properties); for Command_Queue_Info use (Queue_Context => 16#1090#, Queue_Device => 16#1091#, Reference_Count => 16#1092#, Properties => 16#1093#); for Command_Queue_Info'Size use UInt'Size; type Memory_Info is (Mem_Type, Flags, Size, Host_Ptr, Map_Count, Reference_Count, Context, Associated_Memobject, Offset, D3D10_Resource); for Memory_Info use (Mem_Type => 16#1100#, Flags => 16#1101#, Size => 16#1102#, Host_Ptr => 16#1103#, Map_Count => 16#1104#, Reference_Count => 16#1105#, Context => 16#1106#, Associated_Memobject => 16#1107#, Offset => 16#1108#, D3D10_Resource => 16#4015#); for Memory_Info'Size use UInt'Size; type Memory_Object_Type is (T_Buffer, T_Image2D, T_Image3D); for Memory_Object_Type use (T_Buffer => 16#10F0#, T_Image2D => 16#10F1#, T_Image3D => 16#10F2#); for Memory_Object_Type'Size use UInt'Size; type Buffer_Create_Type is (T_Region); for Buffer_Create_Type use (T_Region => 16#1220#); for Buffer_Create_Type'Size use UInt'Size; type Image_Info is (Format, Element_Size, Row_Pitch, Slice_Pitch, Width, Height, Depth, D3D10_Subresource); for Image_Info use (Format => 16#1110#, Element_Size => 16#1111#, Row_Pitch => 16#1112#, Slice_Pitch => 16#1113#, Width => 16#1114#, Height => 16#1115#, Depth => 16#1116#, D3D10_Subresource => 16#4016#); for Image_Info'Size use UInt'Size; type Sampler_Info is (Reference_Count, Context, Normalized_Coords, Addressing_Mode, Filter_Mode); for Sampler_Info use (Reference_Count => 16#1150#, Context => 16#1151#, Normalized_Coords => 16#1152#, Addressing_Mode => 16#1153#, Filter_Mode => 16#1154#); for Sampler_Info'Size use UInt'Size; type Program_Info is (Reference_Count, Context, Num_Devices, Devices, Source_String, Binary_Sizes, Binaries); for Program_Info use (Reference_Count => 16#1160#, Context => 16#1161#, Num_Devices => 16#1162#, Devices => 16#1163#, Source_String => 16#1164#, Binary_Sizes => 16#1165#, Binaries => 16#1166#); for Program_Info'Size use UInt'Size; type Program_Build_Info is (Status, Options, Log); for Program_Build_Info use (Status => 16#1181#, Options => 16#1182#, Log => 16#1183#); for Program_Build_Info'Size use UInt'Size; type Kernel_Info is (Function_Name, Num_Args, Reference_Count, Context, Program); for Kernel_Info use (Function_Name => 16#1190#, Num_Args => 16#1191#, Reference_Count => 16#1192#, Context => 16#1193#, Program => 16#1194#); for Kernel_Info'Size use UInt'Size; type Kernel_Work_Group_Info is (Work_Group_Size, Compile_Work_Group_Size, Local_Mem_Size, Preferred_Work_Group_Size_Multiple, Private_Mem_Size); for Kernel_Work_Group_Info use (Work_Group_Size => 16#11B0#, Compile_Work_Group_Size => 16#11B1#, Local_Mem_Size => 16#11B2#, Preferred_Work_Group_Size_Multiple => 16#11B3#, Private_Mem_Size => 16#11B4#); for Kernel_Work_Group_Info'Size use UInt'Size; type Event_Info is (Command_Queue, Command_T, Reference_Count, Command_Execution_Status, Context); for Event_Info use (Command_Queue => 16#11D0#, Command_T => 16#11D1#, Reference_Count => 16#11D2#, Command_Execution_Status => 16#11D3#, Context => 16#11D4#); for Event_Info'Size use UInt'Size; type Profiling_Info is (Command_Queued, Submit, Start, P_End); for Profiling_Info use (Command_Queued => 16#1280#, Submit => 16#1281#, Start => 16#1282#, P_End => 16#1283#); for Profiling_Info'Size use UInt'Size; end CL.Enumerations;
--////////////////////////////////////////////////////////// -- SFML - Simple and Fast Multimedia Library -- Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org) -- This software is provided 'as-is', without any express or implied warranty. -- In no event will the authors be held liable for any damages arising from the use of this software. -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it freely, -- subject to the following restrictions: -- 1. The origin of this software must not be misrepresented; -- you must not claim that you wrote the original software. -- If you use this software in a product, an acknowledgment -- in the product documentation would be appreciated but is not required. -- 2. Altered source versions must be plainly marked as such, -- and must not be misrepresented as being the original software. -- 3. This notice may not be removed or altered from any source distribution. --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// with Sf.Window.Window; package Sf.Window.Context is --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --/ @brief Create a new context --/ --/ This function activates the new context. --/ --/ @return New sfContext object --/ --////////////////////////////////////////////////////////// function create return sfContext_Ptr; --////////////////////////////////////////////////////////// --/ @brief Destroy a context --/ --/ @param context Context to destroy --/ --////////////////////////////////////////////////////////// procedure destroy (context : sfContext_Ptr); --////////////////////////////////////////////////////////// --/ @brief Activate or deactivate explicitely a context --/ --/ @param context Context object --/ @param active sfTrue to activate, sfFalse to deactivate --/ --/ @return sfTrue on success, sfFalse on failure --/ --////////////////////////////////////////////////////////// function setActive (context : sfContext_Ptr; active : sfBool) return sfBool; --////////////////////////////////////////////////////////// --/ @brief Get the settings of the context. --/ --/ Note that these settings may be different than the ones passed to the --/ constructor; they are indeed adjusted if the original settings are not --/ directly supported by the system. --/ --/ @return Structure containing the settings --/ --////////////////////////////////////////////////////////// function getSettings (context : sfContext_Ptr) return Sf.Window.Window.sfContextSettings; --////////////////////////////////////////////////////////// --/ @brief Get the currently active context's ID --/ --/ The context ID is used to identify contexts when --/ managing unshareable OpenGL resources. --/ --/ @return The active context's ID or 0 if no context is currently active --/ --////////////////////////////////////////////////////////// function getActiveContextId return sfUint64; private pragma Import (C, create, "sfContext_create"); pragma Import (C, destroy, "sfContext_destroy"); pragma Import (C, setActive, "sfContext_setActive"); pragma Import (C, getSettings, "sfContext_getSettings"); pragma Import (C, getActiveContextId, "sfContext_getActiveContextId"); end Sf.Window.Context;
package body Ada.Containers.Murmur_Hash_3 is -- use MurmurHash3_x86_32 procedure Step (h1 : in out Hash_Type; Item : Hash_Type); procedure Step (h1 : in out Hash_Type; Item : Hash_Type) is c1 : constant := 16#cc9e2d51#; c2 : constant := 16#1b873593#; k1 : Hash_Type := Item; begin k1 := k1 * c1; k1 := Rotate_Left (k1, 15); k1 := k1 * c2; h1 := h1 xor k1; end Step; -- implementation function Initialize (Initiator : Hash_Type) return State is begin return (h1 => Initiator, len => 0); end Initialize; procedure Update (S : in out State; Item : Hash_Type) is begin Step (S.h1, Item); S.h1 := Rotate_Left (S.h1, 13); S.h1 := S.h1 * 5 + 16#e6546b64#; S.len := S.len + 4; end Update; procedure Update (S : in out State; Item : Hash_8) is begin Step (S.h1, Hash_Type'Mod (Item)); S.len := S.len + 1; end Update; procedure Update (S : in out State; Item : Hash_16) is begin Step (S.h1, Hash_Type'Mod (Item)); S.len := S.len + 2; end Update; procedure Update (S : in out State; Item : Hash_24) is begin Step (S.h1, Hash_Type'Mod (Item)); S.len := S.len + 3; end Update; procedure Finalize (S : State; Digest : out Hash_Type) is begin Digest := S.h1 xor Hash_Type'Mod (S.len); Digest := Digest xor Shift_Right (Digest, 16); Digest := Digest * 16#85ebca6b#; Digest := Digest xor Shift_Right (Digest, 13); Digest := Digest * 16#c2b2ae35#; Digest := Digest xor Shift_Right (Digest, 16); end Finalize; end Ada.Containers.Murmur_Hash_3;
-----------Package Data, body----------- with Text_IO, Ada.Integer_Text_IO; use Text_IO, Ada.Integer_Text_IO; with Data; package body Data is --Multiplication of matrices function Matrix_Multiplication(A, B: in Matrix) return Matrix is P: Matrix; S: Integer; begin for k in 1..n loop for i in 1..n loop s := 0; for j in 1..n loop S := S + A(k)(j)*B(j)(i); P(k)(i) := s; end loop; end loop; end loop; return P; end Matrix_Multiplication; --Sum of matrices function Matrix_Sum(MA, MB: in Matrix) return Matrix is MC: Matrix; begin --Matrix_Filling_Ones(MC); for i in 1..n loop for j in 1..n loop MC(i)(j):=MA(i)(j)+MB(i)(j); end loop; end loop; return MC; end Matrix_Sum; --Find the max value of Matrix function Matrix_Find_Max(MA: in Matrix) return Integer is max: Integer := MA(1)(1); begin for i in 1..n loop for j in 1..n loop if MA(i)(j) > max then max := MA(i)(j); end if; end loop; end loop; return max; end Matrix_Find_Max; --Find the min value of Matrix function Matrix_Find_Min(MA: in Matrix) return Integer is min: Integer := MA(1)(1); begin for i in 1..n loop for j in 1..n loop if MA(i)(j) < min then min := MA(i)(j); end if; end loop; end loop; return min; end Matrix_Find_Min; --Find the min velue of Vector function Vector_Find_Min(A: in Vector) return Integer is min: Integer :=A(1); begin for i in 1..n loop if A(i) < min then min := A(i); end if; end loop; return min; end Vector_Find_Min; --Matrix translation function Matrix_Translation(MA: in Matrix) return Matrix is MB: Matrix; begin for i in 1..n loop for j in 1..n loop MB(i)(j) := MA(j)(i); end loop; end loop; return MB; end Matrix_Translation; --Multiplication of matrix and integer function Matrix_Integer_Multiplication(A: in Matrix; k: in Integer) return Matrix is P: Matrix; begin for i in 1..n loop for j in 1..n loop P(i)(j):=A(i)(j)*k; end loop; end loop; return P; end Matrix_Integer_Multiplication; --Multiplication of vector and matrix function Vector_Matrix_Multiplication(A: in Vector; B: in Matrix) return Vector is P: Vector; s: Integer; begin for i in 1..n loop s := 0; for j in 1..n loop S := s + A(i)*B(j)(i); end loop; P(i) := S; end loop; return P; end Vector_Matrix_Multiplication; --Multiplication of Vector and Integer function Vector_Integer_Multiplication (A: in Vector; e: in Integer) return Vector is B: Vector; begin for i in 1..n loop B(i) := A(i)*e; end loop; return B; end Vector_Integer_Multiplication; --Difference of Vectors function Vector_Difference(A, B: in Vector) return Vector is S: Vector; begin for i in 1..n loop S(i) := A(i)-B(i); end loop; return S; end Vector_Difference; --Sum of Vectors function Vector_Sum(A, B: in Vector) return Vector is S: Vector; begin for i in 1..n loop S(i) := A(i)+B(i); end loop; return S; end Vector_Sum; function Vector_Multiplication(A, B: in Vector) return Integer is d: Integer := 0; begin for i in 1..n loop d := d + A(i)*B(i); end loop; return d; end Vector_Multiplication; --Sorting of vector function Vector_Sorting(A: in Vector) return Vector is B: Vector; begin for i in 1..n loop for j in i..n loop if A(i)>A(j) then B(j):=A(i); B(i):=A(j); end if; end loop; end loop; return B; end Vector_Sorting; --Filling matrix with ones procedure Matrix_Filling_Ones(A: out Matrix) is begin for i in 1..n loop for j in 1..n loop A(i)(j) := 1; end loop; end loop; end Matrix_Filling_Ones; --Filling vector with ones procedure Vector_Filling_Ones (A: out vector) is begin for i in 1..n loop A(i) := 1; end loop; end Vector_Filling_Ones; --Calculation function 1 function Func1 (A, B, C: in Vector; MA, ME : in Matrix) return Integer is MD:Matrix; D,E:Vector; F:Integer; begin MD:=Matrix_Multiplication(MA,ME); D:=Vector_Sum(B, C); E:=Vector_Matrix_Multiplication(D, MD); F:=Vector_Multiplication(A, E); return F; end Func1; --Calculation function 2 function Func2 (MF, MG, MH, ML: in Matrix) return Integer is MX, MY, MZ: Matrix; max: Integer; begin MZ:=Matrix_Multiplication(MH, ML); MY:=Matrix_Multiplication(MG, MZ); MX:=Matrix_Sum(MF, MY); max:=Matrix_Find_Max(MX); return max; end Func2; --Calculation function 3 function Func3 (A, B, C: in Vector; MB, MM : in Matrix) return Integer is dig, F: Integer; MD, ME:Matrix; D, E:Vector; begin MD:=Matrix_Multiplication(MB, MM); ME:=Matrix_Translation(MD); D:=Vector_Matrix_Multiplication(A, ME); E:=Vector_Sorting(C); F:=Vector_Multiplication(B, E); D(n):=F; dig:=Vector_Find_Min(D); return dig; end Func3; end Data;
package body Polygons is EPSILON : constant := 0.00001; function Ray_Intersects_Segment (Who : Point; Where : Segment) return Boolean is The_Point : Point := Who; Above : Point; Below : Point; M_Red : Float; Red_Is_Infinity : Boolean := False; M_Blue : Float; Blue_Is_Infinity : Boolean := False; begin if Where (1).Y < Where (2).Y then Above := Where (2); Below := Where (1); else Above := Where (1); Below := Where (2); end if; if The_Point.Y = Above.Y or The_Point.Y = Below.Y then The_Point.Y := The_Point.Y + EPSILON; end if; if The_Point.Y < Below.Y or The_Point.Y > Above.Y then return False; elsif The_Point.X > Above.X and The_Point.X > Below.X then return False; elsif The_Point.X < Above.X and The_Point.X < Below.X then return True; else if Above.X /= Below.X then M_Red := (Above.Y - Below.Y) / (Above.X - Below.X); else Red_Is_Infinity := True; end if; if Below.X /= The_Point.X then M_Blue := (The_Point.Y - Below.Y) / (The_Point.X - Below.X); else Blue_Is_Infinity := True; end if; if Blue_Is_Infinity then return True; elsif Red_Is_Infinity then return False; elsif M_Blue >= M_Red then return True; else return False; end if; end if; end Ray_Intersects_Segment; function Create_Polygon (List : Point_List) return Polygon is Result : Polygon (List'Range); Side : Segment; begin for I in List'Range loop Side (1) := List (I); if I = List'Last then Side (2) := List (List'First); else Side (2) := List (I + 1); end if; Result (I) := Side; end loop; return Result; end Create_Polygon; function Is_Inside (Who : Point; Where : Polygon) return Boolean is Count : Natural := 0; begin for Side in Where'Range loop if Ray_Intersects_Segment (Who, Where (Side)) then Count := Count + 1; end if; end loop; if Count mod 2 = 0 then return False; else return True; end if; end Is_Inside; end Polygons;
with AFRL.CMASI.AutomationResponse; use AFRL.CMASI.AutomationResponse; with AFRL.CMASI.Enumerations; with AFRL.CMASI.MissionCommand; use AFRL.CMASI.MissionCommand; with AFRL.CMASI.ServiceStatus; use AFRL.CMASI.ServiceStatus; with AFRL.CMASI.VehicleActionCommand; use AFRL.CMASI.VehicleActionCommand; with AFRL.Impact.ImpactAutomationResponse; use AFRL.Impact.ImpactAutomationResponse; with AVTAS.LMCP.Types; with Common; with UxAS.Messages.lmcptask.PlanningState; use UxAS.Messages.lmcptask.PlanningState; with UxAS.Messages.lmcptask.TaskAssignment; use UxAS.Messages.lmcptask.TaskAssignment; with UxAS.Messages.lmcptask.TaskAssignmentSummary; use UxAS.Messages.lmcptask.TaskAssignmentSummary; with UxAS.Messages.lmcptask.TaskAutomationResponse; use UxAS.Messages.lmcptask.TaskAutomationResponse; with UxAS.Messages.lmcptask.TaskOptionCost; use UxAS.Messages.lmcptask.TaskOptionCost; with UxAS.Messages.Route.RouteResponse; use UxAS.Messages.Route.RouteResponse; package body LMCP_Message_Conversions is ----------------------- -- Local subprograms -- ----------------------- function As_AssignmentCostMatrix_Acc (Msg : LMCP_Messages.AssignmentCostMatrix'Class) return AssignmentCostMatrix_Acc; function As_AutomationResponse_Acc (Msg : LMCP_Messages.AutomationResponse'Class) return AutomationResponse_Acc; function As_ImpactAutomationResponse_Acc (Msg : LMCP_Messages.ImpactAutomationResponse'Class) return ImpactAutomationResponse_Acc; function As_KeyValuePair_Acc (Msg : LMCP_Messages.KeyValuePair) return KeyValuePair_Acc; function As_Location3D_Any (Msg : LMCP_Messages.Location3D) return Location3D_Any; function As_MissionCommand_Acc (Msg : LMCP_Messages.MissionCommand) return MissionCommand_Acc; function As_MissionCommand_Message (Msg : MissionCommand_Acc) return LMCP_Messages.MissionCommand; function As_RouteConstraints_Acc (Msg : LMCP_Messages.RouteConstraints) return RouteConstraints_Acc; function As_RoutePlanRequest_Acc (Msg : LMCP_Messages.RoutePlanRequest'Class) return RoutePlanRequest_Acc; function As_RoutePlanResponse_Acc (Msg : LMCP_Messages.RoutePlanResponse'Class) return RoutePlanResponse_Acc; function As_RouteRequest_Acc (Msg : LMCP_Messages.RouteRequest'Class) return RouteRequest_Acc; function As_RouteResponse_Acc (Msg : LMCP_Messages.RouteResponse'Class) return RouteResponse_Acc; function As_ServiceStatus_Acc (Msg : LMCP_Messages.ServiceStatus'Class) return ServiceStatus_Acc; function As_TaskAssignmentSummary_Acc (Msg : LMCP_Messages.TaskAssignmentSummary'Class) return TaskAssignmentSummary_Acc; function As_TaskAssignment_Acc (Msg : LMCP_Messages.TaskAssignment) return TaskAssignment_Acc; function As_TaskAutomationResponse_Acc (Msg : LMCP_Messages.TaskAutomationResponse'Class) return TaskAutomationResponse_Acc; function As_TaskOptionCost_Acc (Msg : LMCP_Messages.TaskOptionCost) return TaskOptionCost_Acc; function As_TaskOptionCost_Message (Arg : not null TaskOptionCost_Acc) return LMCP_Messages.TaskOptionCost; function As_UniqueAutomationRequest_Acc (Msg : LMCP_Messages.UniqueAutomationRequest'Class) return UniqueAutomationRequest_Acc; function As_VehicleActionCommand_Any (Msg : LMCP_Messages.VehicleActionCommand) return VehicleActionCommand_Any; function As_VehicleActionCommand_Message (Msg : VehicleActionCommand_Any) return LMCP_Messages.VehicleActionCommand; function As_VehicleAction_Acc (Msg : LMCP_Messages.VehicleAction) return VehicleAction_Acc; function As_Waypoint_Acc (Msg : LMCP_Messages.Waypoint) return Waypoint_Acc; --------------------------------- -- As_AssignmentCostMatrix_Acc -- --------------------------------- function As_AssignmentCostMatrix_Acc (Msg : LMCP_Messages.AssignmentCostMatrix'Class) return AssignmentCostMatrix_Acc is Result : constant AssignmentCostMatrix_Acc := new AssignmentCostMatrix; use AVTAS.LMCP.Types; begin Result.all.setCorrespondingAutomationRequestID (Int64 (Msg.CorrespondingAutomationRequestID)); for TaskId of Msg.TaskList loop Result.getTaskList.Append (Int64 (TaskId)); end loop; Result.all.setOperatingRegion (Int64 (Msg.OperatingRegion)); for TOC of Msg.CostMatrix loop Result.getCostMatrix.Append (As_TaskOptionCost_Acc (TOC)); end loop; return Result; end As_AssignmentCostMatrix_Acc; ------------------------------------- -- As_AssignmentCostMatrix_Message -- ------------------------------------- function As_AssignmentCostMatrix_Message (Msg : not null AssignmentCostMatrix_Any) return LMCP_Messages.AssignmentCostMatrix is use all type Common.Int64_Seq; use all type LMCP_Messages.TOC_Seq; Result : LMCP_Messages.AssignmentCostMatrix; begin Result.CorrespondingAutomationRequestID := Common.Int64 (Msg.all.getCorrespondingAutomationRequestID); Result.OperatingRegion := Common.Int64 (Msg.all.getOperatingRegion); for TaskId of Msg.all.getTaskList.all loop Result.TaskList := Add (Result.TaskList, Common.Int64 (TaskId)); end loop; for TaskOptionCost of Msg.all.getCostMatrix.all loop Result.CostMatrix := Add (Result.CostMatrix, As_TaskOptionCost_Message (TaskOptionCost)); end loop; return Result; end As_AssignmentCostMatrix_Message; ---------------------------------- -- As_AutomationRequest_Message -- ---------------------------------- function As_AutomationRequest_Message (Msg : not null AutomationRequest_Any) return LMCP_Messages.AutomationRequest is Result : LMCP_Messages.AutomationRequest; use Common; begin for EntityId of Msg.all.getEntityList.all loop Result.EntityList := Add (Result.EntityList, Int64 (EntityId)); end loop; Result.OperatingRegion := Int64 (Msg.all.getOperatingRegion); for TaskId of Msg.all.getTaskList.all loop Result.TaskList := Add (Result.TaskList, Int64 (TaskId)); end loop; Result.TaskRelationships := Msg.all.getTaskRelationships; Result.RedoAllTasks := Msg.all.getRedoAllTasks; return Result; end As_AutomationRequest_Message; ------------------------------- -- As_AutomationResponse_Acc -- ------------------------------- function As_AutomationResponse_Acc (Msg : LMCP_Messages.AutomationResponse'Class) return AutomationResponse_Acc is Result : constant AutomationResponse_Acc := new AutomationResponse; begin for MissionCommand of Msg.MissionCommandList loop Result.getMissionCommandList.Append (As_MissionCommand_Acc (MissionCommand)); end loop; for VehicleActionCommand of Msg.VehicleCommandList loop Result.getVehicleCommandList.Append (As_VehicleActionCommand_Any (VehicleActionCommand)); end loop; for KVP of Msg.Info loop Result.getInfo.Append (As_KeyValuePair_Acc (KVP)); end loop; return Result; end As_AutomationResponse_Acc; ---------------------------- -- As_EntityState_Message -- ---------------------------- function As_EntityState_Message (Msg : not null EntityState_Any) return LMCP_Messages.EntityState is Result : LMCP_Messages.EntityState; use Common; begin Result.Id := Int64 (Msg.getID); Result.Location := As_Location3D_Message (Msg.getLocation); Result.Heading := Real32 (Msg.getHeading); return Result; end As_EntityState_Message; ---------------------------------------- -- As_ImpactAutomationRequest_Message -- ---------------------------------------- function As_ImpactAutomationRequest_Message (Msg : not null ImpactAutomationRequest_Any) return LMCP_Messages.ImpactAutomationRequest is Result : LMCP_Messages.ImpactAutomationRequest; use Common; begin Result.RequestID := Int64 (Msg.all.getRequestID); for EntityId of Msg.all.getTrialRequest.getEntityList.all loop Result.EntityList := Add (Result.EntityList, Int64 (EntityId)); end loop; Result.OperatingRegion := Int64 (Msg.all.getTrialRequest.getOperatingRegion); for TaskId of Msg.all.getTrialRequest.getTaskList.all loop Result.TaskList := Add (Result.TaskList, Int64 (TaskId)); end loop; Result.TaskRelationships := Msg.all.getTrialRequest.getTaskRelationships; Result.PlayID := Int64 (Msg.all.getPlayID); Result.SolutionID := Int64 (Msg.all.getSolutionID); Result.RedoAllTasks := Msg.all.getTrialRequest.getRedoAllTasks; return Result; end As_ImpactAutomationRequest_Message; ------------------------------------- -- As_ImpactAutomationResponse_Acc -- ------------------------------------- function As_ImpactAutomationResponse_Acc (Msg : LMCP_Messages.ImpactAutomationResponse'Class) return ImpactAutomationResponse_Acc is Result : constant ImpactAutomationResponse_Acc := new ImpactAutomationResponse; use AVTAS.LMCP.Types; begin Result.setResponseID (Int64 (Msg.ResponseID)); for MissionCommand of Msg.MissionCommandList loop Result.getTrialResponse.getMissionCommandList.Append (As_MissionCommand_Acc (MissionCommand)); end loop; for VehicleActionCommand of Msg.VehicleCommandList loop Result.getTrialResponse.getVehicleCommandList.Append (As_VehicleActionCommand_Any (VehicleActionCommand)); end loop; for KVP of Msg.Info loop Result.getTrialResponse.getInfo.Append (As_KeyValuePair_Acc (KVP)); end loop; Result.setPlayID (Int64 (Msg.PlayId)); Result.setSolutionID (Int64 (Msg.SolutionId)); Result.setSandbox (Msg.Sandbox); return Result; end As_ImpactAutomationResponse_Acc; ------------------------- -- As_KeyValuePair_Acc -- ------------------------- function As_KeyValuePair_Acc (Msg : LMCP_Messages.KeyValuePair) return KeyValuePair_Acc is Result : constant KeyValuePair_Acc := new KeyValuePair; begin Result.setKey (Msg.Key); Result.setValue (Msg.Value); return Result; end As_KeyValuePair_Acc; ----------------------------- -- As_KeyValuePair_Message -- ----------------------------- function As_KeyValuePair_Message (Msg : not null KeyValuePair_Acc) return LMCP_Messages.KeyValuePair is Result : LMCP_Messages.KeyValuePair; begin Result.Key := Msg.getKey; Result.Value := Msg.getValue; return Result; end As_KeyValuePair_Message; ----------------------- -- As_Location3D_Any -- ----------------------- function As_Location3D_Any (Msg : LMCP_Messages.Location3D) return Location3D_Any is Result : constant Location3D_Acc := new Location3D; begin Result.setLatitude (AVTAS.LMCP.Types.Real64 (Msg.Latitude)); Result.setLongitude (AVTAS.LMCP.Types.Real64 (Msg.Longitude)); Result.setAltitude (AVTAS.LMCP.Types.Real32 (Msg.Altitude)); case Msg.AltitudeType is when LMCP_Messages.AGL => Result.setAltitudeType (AFRL.CMASI.Enumerations.AGL); when LMCP_Messages.MSL => Result.setAltitudeType (AFRL.CMASI.Enumerations.MSL); end case; return Location3D_Any (Result); end As_Location3D_Any; --------------------------- -- As_Location3D_Message -- --------------------------- function As_Location3D_Message (Msg : not null Location3D_Any) return LMCP_Messages.Location3D is Result : LMCP_Messages.Location3D; begin Result.Latitude := Common.Real64 (Msg.getLatitude); Result.Longitude := Common.Real64 (Msg.getLongitude); Result.Altitude := Common.Real32 (Msg.getAltitude); -- For this enumeration type component we could use 'Val and 'Pos to -- convert the values, but that would not be robust in the face of -- independent changes to either one of the two enumeration type -- decls, especially the order. Therefore we do an explicit comparison. case Msg.getAltitudeType is when AFRL.CMASI.Enumerations.AGL => Result.AltitudeType := LMCP_Messages.AGL; when AFRL.CMASI.Enumerations.MSL => Result.AltitudeType := LMCP_Messages.MSL; end case; return Result; end As_Location3D_Message; --------------------------- -- As_MissionCommand_Acc -- --------------------------- function As_MissionCommand_Acc (Msg : LMCP_Messages.MissionCommand) return MissionCommand_Acc is Result : constant MissionCommand_Acc := new MissionCommand; use AVTAS.LMCP.Types; begin Result.setCommandID (Int64 (Msg.CommandId)); Result.setVehicleID (Int64 (Msg.VehicleId)); for VehicleAction of Msg.VehicleActionList loop Result.getVehicleActionList.Append (VehicleAction_Any (As_VehicleAction_Acc (VehicleAction))); end loop; case Msg.Status is when LMCP_Messages.Pending => Result.setStatus (AFRL.CMASI.Enumerations.Pending); when LMCP_Messages.Approved => Result.setStatus (AFRL.CMASI.Enumerations.Approved); when LMCP_Messages.InProcess => Result.setStatus (AFRL.CMASI.Enumerations.InProcess); when LMCP_Messages.Executed => Result.setStatus (AFRL.CMASI.Enumerations.Executed); when LMCP_Messages.Cancelled => Result.setStatus (AFRL.CMASI.Enumerations.Cancelled); end case; for Waypoint of Msg.WaypointList loop Result.getWaypointList.Append (Waypoint_Any (As_Waypoint_Acc (Waypoint))); end loop; Result.setFirstWaypoint (Int64 (Msg.FirstWaypoint)); return Result; end As_MissionCommand_Acc; ------------------------------- -- As_MissionCommand_Message -- ------------------------------- function As_MissionCommand_Message (Msg : MissionCommand_Acc) return LMCP_Messages.MissionCommand is Result : LMCP_Messages.MissionCommand; use Common; use all type LMCP_Messages.VA_Seq; use all type LMCP_Messages.WP_Seq; begin Result.CommandId := Int64 (Msg.all.getCommandID); Result.VehicleId := Int64 (Msg.all.getVehicleID); for VehicleAction of Msg.all.getVehicleActionList.all loop Result.VehicleActionList := Add (Result.VehicleActionList, As_VehicleAction_Message (VehicleAction)); end loop; case Msg.all.getStatus is when AFRL.CMASI.Enumerations.Pending => Result.Status := LMCP_Messages.Pending; when AFRL.CMASI.Enumerations.Approved => Result.Status := LMCP_Messages.Approved; when AFRL.CMASI.Enumerations.InProcess => Result.Status := LMCP_Messages.InProcess; when AFRL.CMASI.Enumerations.Executed => Result.Status := LMCP_Messages.Executed; when AFRL.CMASI.Enumerations.Cancelled => Result.Status := LMCP_Messages.Cancelled; end case; for Waypoint of Msg.all.getWaypointList.all loop Result.WaypointList := Add (Result.WaypointList, As_Waypoint_Message (Waypoint)); end loop; Result.FirstWaypoint := Int64 (Msg.all.getFirstWaypoint); return Result; end As_MissionCommand_Message; ------------------- -- As_Object_Any -- ------------------- function As_Object_Any (Msg : LMCP_Messages.Message_Root'Class) return AVTAS.LMCP.Object.Object_Any is Result : AVTAS.LMCP.Object.Object_Any; begin -- TODO: Consider using the stream 'Write routines (not the 'Output -- versions) to write the message objects to a byte array, then use -- Unpack to get the LMCP pointer type from that. We'd need a function -- mapping Message_Root tags to the LMCP enumeration identifying message -- types (which handles the necessary ommision of writing the tags) if Msg in LMCP_Messages.RoutePlanRequest'Class then Result := AVTAS.LMCP.Object.Object_Any (As_RoutePlanRequest_Acc (LMCP_Messages.RoutePlanRequest'Class (Msg))); elsif Msg in LMCP_Messages.RoutePlanResponse'Class then Result := AVTAS.LMCP.Object.Object_Any (As_RoutePlanResponse_Acc (LMCP_Messages.RoutePlanResponse'Class (Msg))); elsif Msg in LMCP_Messages.RouteRequest'Class then Result := AVTAS.LMCP.Object.Object_Any (As_RouteRequest_Acc (LMCP_Messages.RouteRequest'Class (Msg))); elsif Msg in LMCP_Messages.RouteResponse'Class then Result := AVTAS.LMCP.Object.Object_Any (As_RouteResponse_Acc (LMCP_Messages.RouteResponse'Class (Msg))); elsif Msg in LMCP_Messages.AssignmentCostMatrix'Class then Result := AVTAS.LMCP.Object.Object_Any (As_AssignmentCostMatrix_Acc (LMCP_Messages.AssignmentCostMatrix'Class (Msg))); elsif Msg in LMCP_Messages.TaskAssignmentSummary'Class then Result := AVTAS.LMCP.Object.Object_Any (As_TaskAssignmentSummary_Acc (LMCP_Messages.TaskAssignmentSummary'Class (Msg))); elsif Msg in LMCP_Messages.UniqueAutomationRequest'Class then Result := AVTAS.LMCP.Object.Object_Any (As_UniqueAutomationRequest_Acc (LMCP_Messages.UniqueAutomationRequest'Class (Msg))); elsif Msg in LMCP_Messages.ServiceStatus'Class then Result := AVTAS.LMCP.Object.Object_Any (As_ServiceStatus_Acc (LMCP_Messages.ServiceStatus'Class (Msg))); elsif Msg in LMCP_Messages.ImpactAutomationResponse'Class then Result := AVTAS.LMCP.Object.Object_Any (As_ImpactAutomationResponse_Acc (LMCP_Messages.ImpactAutomationResponse'Class (Msg))); elsif Msg in LMCP_Messages.TaskAutomationResponse'Class then Result := AVTAS.LMCP.Object.Object_Any (As_TaskAutomationResponse_Acc (LMCP_Messages.TaskAutomationResponse'Class (Msg))); elsif Msg in LMCP_Messages.AutomationResponse'Class then Result := AVTAS.LMCP.Object.Object_Any (As_AutomationResponse_Acc (LMCP_Messages.AutomationResponse'Class (Msg))); else raise Program_Error with "unexpected message kind in Route_Aggregator_Message_Conversions.As_Object_Any"; -- UniqueAutomationRequest is in the class but not sent end if; return Result; end As_Object_Any; ----------------------------- -- As_RouteConstraints_Acc -- ----------------------------- function As_RouteConstraints_Acc (Msg : LMCP_Messages.RouteConstraints) return RouteConstraints_Acc is Result : constant RouteConstraints_Acc := new RouteConstraints; begin Result.setRouteID (AVTAS.LMCP.Types.Int64 (Msg.RouteID)); Result.setStartLocation (As_Location3D_Any (Msg.StartLocation)); Result.setStartHeading (AVTAS.LMCP.Types.Real32 (Msg.StartHeading)); Result.setUseStartHeading (Msg.UseStartHeading); Result.setEndLocation (As_Location3D_Any (Msg.EndLocation)); Result.setEndHeading (AVTAS.LMCP.Types.Real32 (Msg.EndHeading)); Result.setUseEndHeading (Msg.UseEndHeading); return Result; end As_RouteConstraints_Acc; --------------------------------- -- As_RouteConstraints_Message -- --------------------------------- function As_RouteConstraints_Message (Msg : not null RouteConstraints_Any) return LMCP_Messages.RouteConstraints is Result : LMCP_Messages.RouteConstraints; begin Result.RouteID := Common.Int64 (Msg.getRouteID); Result.StartLocation := As_Location3D_Message (Msg.getStartLocation); Result.StartHeading := Common.Real32 (Msg.getStartHeading); Result.UseStartHeading := Msg.getUseStartHeading; Result.EndLocation := As_Location3D_Message (Msg.getEndLocation); Result.EndHeading := Common.Real32 (Msg.getEndHeading); Result.UseEndHeading := Msg.getUseEndHeading; return Result; end As_RouteConstraints_Message; ------------------------------ -- As_RoutePlanRequest_Acc -- ------------------------------ function As_RoutePlanRequest_Acc (Msg : LMCP_Messages.RoutePlanRequest'Class) return RoutePlanRequest_Acc is Result : constant RoutePlanRequest_Acc := new RoutePlanRequest; begin Result.setRequestID (AVTAS.LMCP.Types.Int64 (Msg.RequestID)); Result.setAssociatedTaskID (AVTAS.LMCP.Types.Int64 (Msg.AssociatedTaskID)); Result.setVehicleID (AVTAS.LMCP.Types.Int64 (Msg.VehicleID)); Result.setOperatingRegion (AVTAS.LMCP.Types.Int64 (Msg.OperatingRegion)); Result.setIsCostOnlyRequest (Msg.IsCostOnlyRequest); for RC : LMCP_Messages.RouteConstraints of Msg.RouteRequests loop Result.getRouteRequests.Append (As_RouteConstraints_Acc (RC)); end loop; return Result; end As_RoutePlanRequest_Acc; --------------------------------- -- As_RoutePlanRequest_Message -- --------------------------------- function As_RoutePlanRequest_Message (Msg : not null RoutePlanRequest_Any) return LMCP_Messages.RoutePlanRequest is Result : LMCP_Messages.RoutePlanRequest; begin Result.RequestID := Common.Int64 (Msg.getRequestID); Result.AssociatedTaskID := Common.Int64 (Msg.getAssociatedTaskID); Result.VehicleID := Common.Int64 (Msg.getVehicleID); Result.OperatingRegion := Common.Int64 (Msg.getOperatingRegion); Result.IsCostOnlyRequest := Msg.getIsCostOnlyRequest; for RC of Msg.getRouteRequests.all loop Result.RouteRequests := LMCP_Messages.Add (Result.RouteRequests, As_RouteConstraints_Message (RouteConstraints_Any (RC))); end loop; return Result; end As_RoutePlanRequest_Message; ------------------------------ -- As_RoutePlanResponse_Acc -- ------------------------------ function As_RoutePlanResponse_Acc (Msg : LMCP_Messages.RoutePlanResponse'Class) return RoutePlanResponse_Acc is Result : constant RoutePlanResponse_Acc := new RoutePlanResponse; New_Route_Plan : UxAS.Messages.Route.RoutePlan.RoutePlan_Acc; begin Result.setResponseID (AVTAS.LMCP.Types.Int64 (Msg.ResponseID)); Result.setAssociatedTaskID (AVTAS.LMCP.Types.Int64 (Msg.AssociatedTaskID)); Result.setVehicleID (AVTAS.LMCP.Types.Int64 (Msg.VehicleID)); Result.setOperatingRegion (AVTAS.LMCP.Types.Int64 (Msg.OperatingRegion)); for Plan_Msg : LMCP_Messages.RoutePlan of Msg.RouteResponses loop New_Route_Plan := new UxAS.Messages.Route.RoutePlan.RoutePlan; New_Route_Plan.setRouteID (AVTAS.LMCP.Types.Int64 (Plan_Msg.RouteID)); New_Route_Plan.setRouteCost (AVTAS.LMCP.Types.Int64 (Plan_Msg.RouteCost)); -- waypoints... for WP : LMCP_Messages.Waypoint of Plan_Msg.Waypoints loop New_Route_Plan.getWaypoints.Append (Waypoint_Any (As_Waypoint_Acc (WP))); end loop; -- route errors... for KVP : LMCP_Messages.KeyValuePair of Plan_Msg.RouteError loop New_Route_Plan.getRouteError.Append (As_KeyValuePair_Acc (KVP)); end loop; Result.getRouteResponses.Append (New_Route_Plan); end loop; return Result; end As_RoutePlanResponse_Acc; ---------------------------------- -- As_RoutePlanResponse_Message -- ---------------------------------- function As_RoutePlanResponse_Message (Msg : not null RoutePlanResponse_Any) return LMCP_Messages.RoutePlanResponse is Result : LMCP_Messages.RoutePlanResponse; New_RoutePlan : LMCP_Messages.RoutePlan; use LMCP_Messages; use Common; begin Result.ResponseID := Int64 (Msg.getResponseID); Result.AssociatedTaskID := Int64 (Msg.getAssociatedTaskID); Result.VehicleID := Int64 (Msg.getVehicleID); Result.OperatingRegion := Int64 (Msg.getOperatingRegion); for Plan of Msg.getRouteResponses.all loop New_RoutePlan.RouteID := Int64 (Plan.getRouteID); New_RoutePlan.RouteCost := Int64 (Plan.getRouteCost); for WP of Plan.getWaypoints.all loop New_RoutePlan.Waypoints := Add (New_RoutePlan.Waypoints, As_Waypoint_Message (WP)); end loop; for Error of Plan.getRouteError.all loop New_RoutePlan.RouteError := Add (New_RoutePlan.RouteError, As_KeyValuePair_Message (Error)); end loop; Result.RouteResponses := Add (Result.RouteResponses, New_RoutePlan); end loop; return Result; end As_RoutePlanResponse_Message; -------------------------- -- As_RoutePlan_Message -- -------------------------- function As_RoutePlan_Message (Msg : not null RoutePlan_Any) return LMCP_Messages.RoutePlan is Result : LMCP_Messages.RoutePlan; use LMCP_Messages; begin Result.RouteID := Common.Int64 (Msg.getRouteID); for WP of Msg.getWaypoints.all loop Result.Waypoints := Add (Result.Waypoints, As_Waypoint_Message (WP)); end loop; Result.RouteCost := Common.Int64 (Msg.getRouteCost); for Error of Msg.getRouteError.all loop Result.RouteError := Add (Result.RouteError, As_KeyValuePair_Message (Error)); end loop; return Result; end As_RoutePlan_Message; ------------------------- -- As_RouteRequest_Acc -- ------------------------- function As_RouteRequest_Acc (Msg : LMCP_Messages.RouteRequest'Class) return RouteRequest_Acc is Result : constant RouteRequest_Acc := new RouteRequest; begin Result.setRequestID (AVTAS.LMCP.Types.Int64 (Msg.RequestID)); Result.setAssociatedTaskID (AVTAS.LMCP.Types.Int64 (Msg.AssociatedTaskID)); for VID of Msg.VehicleID loop Result.getVehicleID.Append (AVTAS.LMCP.Types.Int64 (VID)); end loop; Result.setOperatingRegion (AVTAS.LMCP.Types.Int64 (Msg.OperatingRegion)); Result.setIsCostOnlyRequest (Msg.IsCostOnlyRequest); for RC of Msg.RouteRequests loop Result.getRouteRequests.Append (As_RouteConstraints_Acc (RC)); end loop; return Result; end As_RouteRequest_Acc; ----------------------------- -- As_RouteRequest_Message -- ----------------------------- function As_RouteRequest_Message (Msg : not null RouteRequest_Any) return LMCP_Messages.RouteRequest is Result : LMCP_Messages.RouteRequest; begin Result.RequestID := Common.Int64 (Msg.getRequestID); Result.AssociatedTaskID := Common.Int64 (Msg.getAssociatedTaskID); for VID of Msg.getVehicleID.all loop Result.VehicleID := Common.Add (Result.VehicleID, Common.Int64 (VID)); end loop; Result.OperatingRegion := Common.Int64 (Msg.getOperatingRegion); Result.IsCostOnlyRequest := Msg.getIsCostOnlyRequest; for RC of Msg.getRouteRequests.all loop Result.RouteRequests := LMCP_Messages.Add (Result.RouteRequests, As_RouteConstraints_Message (RouteConstraints_Any (RC))); end loop; return Result; end As_RouteRequest_Message; -------------------------- -- As_RouteResponse_Acc -- -------------------------- function As_RouteResponse_Acc (Msg : LMCP_Messages.RouteResponse'Class) return RouteResponse_Acc is Result : constant RouteResponse_Acc := new RouteResponse; begin Result.setResponseID (AVTAS.LMCP.Types.Int64 (Msg.ResponseID)); for RP : LMCP_Messages.RoutePlanResponse of Msg.Routes loop Result.getRoutes.Append (As_RoutePlanResponse_Acc (RP)); end loop; return Result; end As_RouteResponse_Acc; -------------------------- -- As_ServiceStatus_Acc -- -------------------------- function As_ServiceStatus_Acc (Msg : LMCP_Messages.ServiceStatus'Class) return ServiceStatus_Acc is Result : constant ServiceStatus_Acc := new ServiceStatus; use AVTAS.LMCP.Types; begin Result.setPercentComplete (Real32 (Msg.PercentComplete)); for KVP of Msg.Info loop Result.getInfo.Append (As_KeyValuePair_Acc (KVP)); end loop; case Msg.StatusType is when LMCP_Messages.Information => Result.setStatusType (AFRL.CMASI.Enumerations.Information); when LMCP_Messages.Warning => Result.setStatusType (AFRL.CMASI.Enumerations.Warning); when LMCP_Messages.Error => Result.setStatusType (AFRL.CMASI.Enumerations.Error); end case; return Result; end As_ServiceStatus_Acc; ---------------------------------- -- As_TaskAssignmentSummary_Acc -- ---------------------------------- function As_TaskAssignmentSummary_Acc (Msg : LMCP_Messages.TaskAssignmentSummary'Class) return TaskAssignmentSummary_Acc is Result : constant TaskAssignmentSummary_Acc := new TaskAssignmentSummary; use AVTAS.LMCP.Types; begin Result.setCorrespondingAutomationRequestID (Int64 (Msg.CorrespondingAutomationRequestID)); Result.setOperatingRegion (Int64 (Msg.OperatingRegion)); for TaskAssignment of Msg.TaskList loop Result.getTaskList.Append (As_TaskAssignment_Acc (TaskAssignment)); end loop; return Result; end As_TaskAssignmentSummary_Acc; --------------------------- -- As_TaskAssignment_Acc -- --------------------------- function As_TaskAssignment_Acc (Msg : LMCP_Messages.TaskAssignment) return TaskAssignment_Acc is Result : constant TaskAssignment_Acc := new TaskAssignment; use AVTAS.LMCP.Types; begin Result.setTaskID (Int64 (Msg.TaskID)); Result.setOptionID (Int64 (Msg.OptionID)); Result.setAssignedVehicle (Int64 (Msg.AssignedVehicle)); Result.setTimeThreshold (Int64 (Msg.TimeThreshold)); Result.setTimeTaskCompleted (Int64 (Msg.TimeTaskCompleted)); return Result; end As_TaskAssignment_Acc; -------------------------------------- -- As_TaskAutomationRequest_Message -- -------------------------------------- function As_TaskAutomationRequest_Message (Msg : not null TaskAutomationRequest_Any) return LMCP_Messages.TaskAutomationRequest is Result : LMCP_Messages.TaskAutomationRequest; use Common; use all type LMCP_Messages.PlanningState_Seq; begin Result.RequestID := Int64 (Msg.all.getRequestID); for EntityId of Msg.all.getOriginalRequest.getEntityList.all loop Result.EntityList := Add (Result.EntityList, Int64 (EntityId)); end loop; Result.OperatingRegion := Int64 (Msg.all.getOriginalRequest.getOperatingRegion); for MsgPlanningState of Msg.all.getPlanningStates.all loop declare PlanningState : LMCP_Messages.PlanningState; begin PlanningState.EntityID := Int64 (MsgPlanningState.all.getEntityID); PlanningState.PlanningPosition := As_Location3D_Message (MsgPlanningState.all.getPlanningPosition); PlanningState.PlanningHeading := Real32 (MsgPlanningState.all.getPlanningHeading); Result.PlanningStates := Add (Result.PlanningStates, PlanningState); end; end loop; for TaskId of Msg.all.getOriginalRequest.getTaskList.all loop Result.TaskList := Add (Result.TaskList, Int64 (TaskId)); end loop; Result.TaskRelationships := Msg.all.getOriginalRequest.getTaskRelationships; Result.RedoAllTasks := Msg.all.getOriginalRequest.getRedoAllTasks; return Result; end As_TaskAutomationRequest_Message; ----------------------------------- -- As_TaskAutomationResponse_Acc -- ----------------------------------- function As_TaskAutomationResponse_Acc (Msg : LMCP_Messages.TaskAutomationResponse'Class) return TaskAutomationResponse_Acc is Result : constant TaskAutomationResponse_Acc := new TaskAutomationResponse; use AVTAS.LMCP.Types; begin Result.setResponseID (Int64 (Msg.ResponseID)); for MissionCommand of Msg.MissionCommandList loop Result.getOriginalResponse.getMissionCommandList.Append (As_MissionCommand_Acc (MissionCommand)); end loop; for VehicleActionCommand of Msg.VehicleCommandList loop Result.getOriginalResponse.getVehicleCommandList.Append (As_VehicleActionCommand_Any (VehicleActionCommand)); end loop; for KVP of Msg.Info loop Result.getOriginalResponse.getInfo.Append (As_KeyValuePair_Acc (KVP)); end loop; for Msg_FState of Msg.FinalStates loop declare FinalState : constant PlanningState_Acc := new PlanningState; begin FinalState.setEntityID (Int64 (Msg_FState.EntityID)); FinalState.setPlanningPosition (As_Location3D_Any (Msg_FState.PlanningPosition)); FinalState.setPlanningHeading (Real32 (Msg_FState.PlanningHeading)); Result.getFinalStates.Append (FinalState); end; end loop; return Result; end As_TaskAutomationResponse_Acc; --------------------------- -- As_TaskOptionCost_Acc -- --------------------------- function As_TaskOptionCost_Acc (Msg : LMCP_Messages.TaskOptionCost) return TaskOptionCost_Acc is Result : constant TaskOptionCost_Acc := new TaskOptionCost; use AVTAS.LMCP.Types; begin Result.all.setVehicleID (Int64 (Msg.VehicleID)); Result.all.setIntialTaskID (Int64 (Msg.InitialTaskID)); Result.all.setIntialTaskOption (Int64 (Msg.InitialTaskOption)); Result.all.setDestinationTaskID (Int64 (Msg.DestinationTaskID)); Result.all.setDestinationTaskOption (Int64 (Msg.DestinationTaskOption)); Result.all.setTimeToGo (Int64 (Msg.TimeToGo)); return Result; end As_TaskOptionCost_Acc; ------------------------------- -- As_TaskOptionCost_Message -- ------------------------------- function As_TaskOptionCost_Message (Arg : not null TaskOptionCost_Acc) return LMCP_Messages.TaskOptionCost is Result : LMCP_Messages.TaskOptionCost; begin Result.VehicleID := Common.Int64 (Arg.getVehicleID); Result.InitialTaskID := Common.Int64 (Arg.getIntialTaskID); Result.InitialTaskOption := Common.Int64 (Arg.getIntialTaskOption); Result.DestinationTaskID := Common.Int64 (Arg.getDestinationTaskID); Result.DestinationTaskOption := Common.Int64 (Arg.getDestinationTaskOption); Result.TimeToGo := Common.Int64 (Arg.getTimeToGo); return Result; end As_TaskOptionCost_Message; ------------------------------- -- As_TaskPlanOption_Message -- ------------------------------- function As_TaskPlanOption_Message (Msg : not null TaskPlanOptions_Any) return LMCP_Messages.TaskPlanOptions is Result : LMCP_Messages.TaskPlanOptions; use Common; use all type Int64_Seq; use all type LMCP_Messages.TaskOption_Seq; begin Result.CorrespondingAutomationRequestID := Int64 (Msg.getCorrespondingAutomationRequestID); Result.TaskID := Int64 (Msg.getTaskID); Result.Composition := Msg.getComposition; for MsgOption of Msg.getOptions.all loop declare Option : LMCP_Messages.TaskOption; begin Option.TaskID := Int64 (MsgOption.all.getTaskID); Option.OptionID := Int64 (MsgOption.all.getOptionID); Option.Cost := Int64 (MsgOption.all.getCost); Option.StartLocation := As_Location3D_Message (MsgOption.all.getStartLocation); Option.StartHeading := Real32 (MsgOption.all.getStartHeading); Option.EndLocation := As_Location3D_Message (MsgOption.all.getEndLocation); Option.EndHeading := Real32 (MsgOption.all.getEndHeading); for Entity of MsgOption.all.getEligibleEntities.all loop Option.EligibleEntities := Add (Option.EligibleEntities, Int64 (Entity)); end loop; Result.Options := Add (Result.Options, Option); end; end loop; return Result; end As_TaskPlanOption_Message; ------------------------------------ -- As_UniqueAutomationRequest_Acc -- ------------------------------------ function As_UniqueAutomationRequest_Acc (Msg : LMCP_Messages.UniqueAutomationRequest'Class) return UniqueAutomationRequest_Acc is Result : constant UniqueAutomationRequest_Acc := new UniqueAutomationRequest; use AVTAS.LMCP.Types; begin for Msg_PState of Msg.PlanningStates loop declare PState : constant PlanningState_Acc := new PlanningState; begin PState.all.setEntityID (Int64 (Msg_PState.EntityID)); PState.all.setPlanningPosition (As_Location3D_Any (Msg_PState.PlanningPosition)); PState.all.setPlanningHeading (Real32 (Msg_PState.PlanningHeading)); Result.all.getPlanningStates.Append (PState); end; end loop; for EntityId of Msg.EntityList loop Result.getOriginalRequest.getEntityList.Append (Int64 (EntityId)); end loop; for TaskId of Msg.TaskList loop Result.getOriginalRequest.getTaskList.Append (Int64 (TaskId)); end loop; Result.all.setRequestID (Int64 (Msg.RequestID)); Result.all.getOriginalRequest.setTaskRelationships (Msg.TaskRelationships); Result.all.getOriginalRequest.setOperatingRegion (Int64 (Msg.OperatingRegion)); Result.all.getOriginalRequest.setRedoAllTasks (Msg.RedoAllTasks); Result.all.setSandBoxRequest (Msg.SandboxRequest); return Result; end As_UniqueAutomationRequest_Acc; ---------------------------------------- -- As_UniqueAutomationRequest_Message -- ---------------------------------------- function As_UniqueAutomationRequest_Message (Msg : not null UniqueAutomationRequest_Any) return LMCP_Messages.UniqueAutomationRequest is Result : LMCP_Messages.UniqueAutomationRequest; use Common; use all type LMCP_Messages.PlanningState_Seq; begin Result.RequestID := Int64 (Msg.all.getRequestID); for EntityId of Msg.all.getOriginalRequest.getEntityList.all loop Result.EntityList := Add (Result.EntityList, Int64 (EntityId)); end loop; Result.OperatingRegion := Int64 (Msg.all.getOriginalRequest.getOperatingRegion); for MsgPlanningState of Msg.all.getPlanningStates.all loop declare PlanningState : LMCP_Messages.PlanningState; begin PlanningState.EntityID := Int64 (MsgPlanningState.all.getEntityID); PlanningState.PlanningPosition := As_Location3D_Message (MsgPlanningState.all.getPlanningPosition); PlanningState.PlanningHeading := Real32 (MsgPlanningState.all.getPlanningHeading); Result.PlanningStates := Add (Result.PlanningStates, PlanningState); end; end loop; for TaskId of Msg.all.getOriginalRequest.getTaskList.all loop Result.TaskList := Add (Result.TaskList, Int64 (TaskId)); end loop; Result.TaskRelationships := Msg.all.getOriginalRequest.getTaskRelationships; Result.RedoAllTasks := Msg.all.getOriginalRequest.getRedoAllTasks; return Result; end As_UniqueAutomationRequest_Message; ----------------------------------------- -- As_UniqueAutomationResponse_Message -- ----------------------------------------- function As_UniqueAutomationResponse_Message (Msg : not null UniqueAutomationResponse_Any) return LMCP_Messages.UniqueAutomationResponse is Result : LMCP_Messages.UniqueAutomationResponse; use Common; use all type LMCP_Messages.PlanningState_Seq; use all type LMCP_Messages.MissionCommand_Seq; use all type LMCP_Messages.VehicleActionCommand_Seq; use all type LMCP_Messages.KVP_Seq; begin for MissionCommand of Msg.all.getOriginalResponse.getMissionCommandList.all loop Result.MissionCommandList := Add (Result.MissionCommandList, As_MissionCommand_Message (MissionCommand)); end loop; for VehicleActionCommand of Msg.all.getOriginalResponse.getVehicleCommandList.all loop Result.VehicleCommandList := Add (Result.VehicleCommandList, As_VehicleActionCommand_Message (VehicleActionCommand)); end loop; for KVP of Msg.all.getOriginalResponse.getInfo.all loop Result.Info := Add (Result.Info, As_KeyValuePair_Message (KVP)); end loop; Result.ResponseID := Int64 (Msg.all.getResponseID); for MsgFinalState of Msg.all.getFinalStates.all loop declare FinalState : LMCP_Messages.PlanningState; begin FinalState.EntityID := Int64 (MsgFinalState.all.getEntityID); FinalState.PlanningPosition := As_Location3D_Message (MsgFinalState.all.getPlanningPosition); FinalState.PlanningHeading := Real32 (MsgFinalState.all.getPlanningHeading); Result.FinalStates := Add (Result.FinalStates, FinalState); end; end loop; return Result; end As_UniqueAutomationResponse_Message; --------------------------------- -- As_VehicleActionCommand_Any -- --------------------------------- function As_VehicleActionCommand_Any (Msg : LMCP_Messages.VehicleActionCommand) return VehicleActionCommand_Any is Result : constant VehicleActionCommand_Any := new VehicleActionCommand; use AVTAS.LMCP.Types; begin Result.setCommandID (Int64 (Msg.CommandId)); Result.setVehicleID (Int64 (Msg.VehicleId)); for VehicleAction of Msg.VehicleActionList loop Result.getVehicleActionList.Append (VehicleAction_Any (As_VehicleAction_Acc (VehicleAction))); end loop; case Msg.Status is when LMCP_Messages.Pending => Result.setStatus (AFRL.CMASI.Enumerations.Pending); when LMCP_Messages.Approved => Result.setStatus (AFRL.CMASI.Enumerations.Approved); when LMCP_Messages.InProcess => Result.setStatus (AFRL.CMASI.Enumerations.InProcess); when LMCP_Messages.Executed => Result.setStatus (AFRL.CMASI.Enumerations.Executed); when LMCP_Messages.Cancelled => Result.setStatus (AFRL.CMASI.Enumerations.Cancelled); end case; return Result; end As_VehicleActionCommand_Any; ------------------------------------- -- As_VehicleActionCommand_Message -- ------------------------------------- function As_VehicleActionCommand_Message (Msg : VehicleActionCommand_Any) return LMCP_Messages.VehicleActionCommand is Result : LMCP_Messages.VehicleActionCommand; use Common; use all type LMCP_Messages.VA_Seq; begin Result.CommandId := Int64 (Msg.all.getCommandID); Result.VehicleId := Int64 (Msg.all.getVehicleID); for VehicleAction of Msg.all.getVehicleActionList.all loop Result.VehicleActionList := Add (Result.VehicleActionList, As_VehicleAction_Message (VehicleAction)); end loop; case Msg.all.getStatus is when AFRL.CMASI.Enumerations.Pending => Result.Status := LMCP_Messages.Pending; when AFRL.CMASI.Enumerations.Approved => Result.Status := LMCP_Messages.Approved; when AFRL.CMASI.Enumerations.InProcess => Result.Status := LMCP_Messages.InProcess; when AFRL.CMASI.Enumerations.Executed => Result.Status := LMCP_Messages.Executed; when AFRL.CMASI.Enumerations.Cancelled => Result.Status := LMCP_Messages.Cancelled; end case; return Result; end As_VehicleActionCommand_Message; -------------------------- -- As_VehicleAction_Acc -- -------------------------- function As_VehicleAction_Acc (Msg : LMCP_Messages.VehicleAction) return VehicleAction_Acc is Result : constant VehicleAction_Acc := new VehicleAction; begin for Id : Common.Int64 of Msg.AssociatedTaskList loop Result.getAssociatedTaskList.Append (AVTAS.LMCP.Types.Int64 (Id)); end loop; return Result; end As_VehicleAction_Acc; ------------------------------ -- As_VehicleAction_Message -- ------------------------------ function As_VehicleAction_Message (Msg : not null VehicleAction_Any) return LMCP_Messages.VehicleAction is Result : LMCP_Messages.VehicleAction; use Common; begin for VA of Msg.getAssociatedTaskList.all loop Result.AssociatedTaskList := Add (Result.AssociatedTaskList, Common.Int64 (VA)); end loop; return Result; end As_VehicleAction_Message; --------------------- -- As_Waypoint_Acc -- --------------------- function As_Waypoint_Acc (Msg : LMCP_Messages.Waypoint) return Waypoint_Acc is Result : constant Waypoint_Acc := new AFRL.CMASI.Waypoint.Waypoint; begin -- the Location3D components Result.setLatitude (AVTAS.LMCP.Types.Real64 (Msg.Latitude)); Result.setLongitude (AVTAS.LMCP.Types.Real64 (Msg.Longitude)); Result.setAltitude (AVTAS.LMCP.Types.Real32 (Msg.Altitude)); case Msg.AltitudeType is when LMCP_Messages.AGL => Result.setAltitudeType (AFRL.CMASI.Enumerations.AGL); when LMCP_Messages.MSL => Result.setAltitudeType (AFRL.CMASI.Enumerations.MSL); end case; -- the waypoint extensions Result.setNumber (AVTAS.LMCP.Types.Int64 (Msg.Number)); Result.setNextWaypoint (AVTAS.LMCP.Types.Int64 (Msg.NextWaypoint)); Result.setSpeed (AVTAS.LMCP.Types.Real32 (Msg.Speed)); case Msg.SpeedType is when LMCP_Messages.Airspeed => Result.setSpeedType (AFRL.CMASI.Enumerations.Airspeed); when LMCP_Messages.Groundspeed => Result.setSpeedType (AFRL.CMASI.Enumerations.Groundspeed); end case; Result.setClimbRate (AVTAS.LMCP.Types.Real32 (Msg.ClimbRate)); case Msg.TurnType is when LMCP_Messages.TurnShort => Result.setTurnType (AFRL.CMASI.Enumerations.TurnShort); when LMCP_Messages.FlyOver => Result.setTurnType (AFRL.CMASI.Enumerations.FlyOver); end case; for VA of Msg.VehicleActionList loop Result.getVehicleActionList.Append (VehicleAction_Any (As_VehicleAction_Acc (VA))); end loop; Result.setContingencyWaypointA (AVTAS.LMCP.Types.Int64 (Msg.ContingencyWaypointA)); Result.setContingencyWaypointB (AVTAS.LMCP.Types.Int64 (Msg.ContingencyWaypointB)); for Id of Msg.AssociatedTasks loop Result.getAssociatedTasks.Append (AVTAS.LMCP.Types.Int64 (Id)); end loop; return Result; end As_Waypoint_Acc; ------------------------- -- As_Waypoint_Message -- ------------------------- function As_Waypoint_Message (Msg : not null Waypoint_Any) return LMCP_Messages.Waypoint is Result : LMCP_Messages.Waypoint; begin -- the Location3D components LMCP_Messages.Location3D (Result) := As_Location3D_Message (Location3D_Any (Msg)); -- the Waypoint extension components Result.Number := Common.Int64 (Msg.getNumber); Result.NextWaypoint := Common.Int64 (Msg.getNextWaypoint); Result.Speed := Common.Real32 (Msg.getSpeed); case Msg.getSpeedType is when AFRL.CMASI.Enumerations.Airspeed => Result.SpeedType := LMCP_Messages.Airspeed; when AFRL.CMASI.Enumerations.Groundspeed => Result.SpeedType := LMCP_Messages.Groundspeed; end case; Result.ClimbRate := Common.Real32 (Msg.getClimbRate); case Msg.getTurnType is when AFRL.CMASI.Enumerations.TurnShort => Result.TurnType := LMCP_Messages.TurnShort; when AFRL.CMASI.Enumerations.FlyOver => Result.TurnType := LMCP_Messages.FlyOver; end case; for VA of Msg.getVehicleActionList.all loop Result.VehicleActionList := LMCP_Messages.Add (Result.VehicleActionList, As_VehicleAction_Message (VA)); end loop; Result.ContingencyWaypointA := Common.Int64 (Msg.getContingencyWaypointA); Result.ContingencyWaypointB := Common.Int64 (Msg.getContingencyWaypointB); for Id of Msg.getAssociatedTasks.all loop Result.AssociatedTasks := Common.Add (Result.AssociatedTasks, Common.Int64 (Id)); end loop; return Result; end As_Waypoint_Message; end LMCP_Message_Conversions;
----------------------------------------------------------------------- -- css-core-sheets -- CSS stylesheet representation -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with CSS.Core.Refs; with Util.Log.Locations; package body CSS.Core.Sheets is -- ------------------------------ -- Create a CSS rule. -- ------------------------------ function Create_Rule (Document : in CSSStylesheet) return Styles.CSSStyleRule_Access is Result : constant Styles.CSSStyleRule_Access := new Styles.CSSStyleRule; File : constant Util.Log.Locations.File_Info_Access := Document.File; begin Result.Style.Set_File_Info (File); return Result; end Create_Rule; -- ------------------------------ -- Create a CSS font-face rule. -- ------------------------------ function Create_Rule (Document : in CSSStylesheet) return Styles.CSSFontfaceRule_Access is Result : constant Styles.CSSFontfaceRule_Access := new Styles.CSSFontfaceRule; File : constant Util.Log.Locations.File_Info_Access := Document.File; begin Result.Style.Set_File_Info (File); return Result; end Create_Rule; -- ------------------------------ -- Create a CSS media rule. -- ------------------------------ function Create_Rule (Document : in CSSStylesheet) return Medias.CSSMediaRule_Access is Result : constant Medias.CSSMediaRule_Access := new Medias.CSSMediaRule; File : constant Util.Log.Locations.File_Info_Access := Document.File; begin -- Result.Style.Set_File_Info (File); return Result; end Create_Rule; -- ------------------------------ -- Append the CSS rule to the document. -- ------------------------------ procedure Append (Document : in out CSSStylesheet; Rule : in Styles.CSSStyleRule_Access; Line : in Natural; Column : in Natural) is Ref : constant CSS.Core.Refs.Ref := CSS.Core.Refs.Create (Rule.all'Access); begin Rule.Set_Location (Line, Column, Document'Unchecked_Access); Document.Rules.Append (Ref); end Append; -- ------------------------------ -- Append the CSS rule to the document. -- ------------------------------ procedure Append (Document : in out CSSStylesheet; Rule : in Styles.CSSFontfaceRule_Access; Line : in Natural; Column : in Natural) is Ref : constant CSS.Core.Refs.Ref := CSS.Core.Refs.Create (Rule.all'Access); begin Rule.Set_Location (Line, Column, Document'Unchecked_Access); Document.Rules.Append (Ref); end Append; -- ------------------------------ -- Append the media rule to the document. -- ------------------------------ procedure Append (Document : in out CSSStylesheet; Media : in Medias.CSSMediaRule_Access; Rule : in Styles.CSSStyleRule_Access; Line : in Natural; Column : in Natural) is use type Medias.CSSMediaRule_Access; Ref : constant CSS.Core.Refs.Ref := CSS.Core.Refs.Create (Rule.all'Access); begin Rule.Set_Location (Line, Column, Document'Unchecked_Access); if Media /= null then Media.Rules.Append (Ref); else Document.Rules.Append (Ref); end if; end Append; -- ------------------------------ -- Append the CSS rule to the media. -- ------------------------------ procedure Append (Document : in out CSSStylesheet; Rule : in Medias.CSSMediaRule_Access; Line : in Natural; Column : in Natural) is Ref : constant CSS.Core.Refs.Ref := CSS.Core.Refs.Create (Rule.all'Access); begin Rule.Set_Location (Line, Column, Document'Unchecked_Access); Document.Rules.Append (Ref); end Append; -- ------------------------------ -- Iterate over the properties of each CSS rule. The <tt>Process</tt> procedure -- is called with the CSS rule and the property as parameter. -- ------------------------------ procedure Iterate_Properties (Document : in CSSStylesheet; Process : not null access procedure (Rule : in Styles.CSSStyleRule'Class; Property : in Properties.CSSProperty)) is use Styles; procedure Process_Rule (Pos : in CSS.Core.Vectors.Cursor); procedure Process_Rule (Pos : in CSS.Core.Vectors.Cursor) is procedure Process_Property (Prop : in Properties.CSSProperty); Rule : constant CSSStyleRule_Access := Styles.Element (Pos); procedure Process_Property (Prop : in Properties.CSSProperty) is begin Process (Rule.all, Prop); end Process_Property; begin if Rule /= null then Rule.Style.Iterate (Process_Property'Access); end if; end Process_Rule; begin Document.Rules.Iterate (Process_Rule'Access); end Iterate_Properties; end CSS.Core.Sheets;
------ WHILE / LOOP / FOR procedure Hello is a: Integer; b: Float ; c: Boolean; function uno(a,b:in Integer) return Integer is begin Put(one); for I in 1..1 loop Get(a); end loop; return True; end uno; begin b := 2.0; c := True; while (n > 3) loop if (a>3) or (a<0) then exit when (a = 2); end if; a := a +1; end loop; end Hello;
-- $Id: Idents.md,v 1.6 1992/08/07 14:45:41 grosch rel $ -- $Log: Idents.md,v $ -- Ich, Doktor Josef Grosch, Informatiker, Sept. 1994 with Text_Io, Strings, StringM; use Text_Io, Strings, StringM; package Idents is subtype tIdent is Integer range 0 .. 2 ** 16 - 1; NoIdent : tIdent; -- := MakeIdent (NoString); -- A default identifer (empty string). function MakeIdent (s: tString) return tIdent; -- The string 's' is mapped to a unique number -- (an integer) which is returned. procedure GetString (i: tIdent; s: in out tString); -- Returns the string 's' whose number is 'i'. function GetStringRef (i: tIdent) return tStringRef; -- Returns a reference to the string whose -- number is 'i'. function MaxIdent return tIdent; -- Returns the current maximal value of the -- type 'tIdent'. procedure WriteIdent (f: File_Type; i: tIdent); -- The string encoded by the ident 'i' is -- printed on file 'f'. procedure WriteIdents ; -- The contents of the identifier table is -- printed on the terminal. procedure InitIdents ; -- The identifier table is initialized. procedure WriteHashTable; end Idents;
with Memory.Transform.Offset; use Memory.Transform.Offset; with Memory.Join; use Memory.Join; package body Test.Offset is procedure Run_Tests is mem : constant Monitor_Pointer := Create_Monitor(0, True); bank : constant Monitor_Pointer := Create_Monitor(0, False); offset : Offset_Pointer := Create_Offset; join : constant Join_Pointer := Create_Join(offset, 0); begin Set_Memory(bank.all, join); Set_Memory(offset.all, mem); Set_Bank(offset.all, bank); Set_Value(offset.all, 3); Check(Get_Time(mem.all) = 0); Check(Get_Time(offset.all) = 0); Check(Get_Writes(offset.all) = 0); Check(Get_Cost(offset.all) = 0); Read(offset.all, 0, 8); Check(bank.last_addr = 3); Check(mem.last_addr = 0); Check(bank.reads = 1); Check(mem.reads = 1); Check(bank.writes = 0); Check(mem.writes = 0); Read(offset.all, 5, 8); Check(bank.last_addr = 8); Check(mem.last_addr = 5); Check(bank.reads = 2); Check(mem.reads = 2); Check(bank.writes = 0); Check(mem.writes = 0); Write(offset.all, 5, 4); Check(bank.last_addr = 8); Check(mem.last_addr = 5); Check(bank.reads = 2); Check(mem.reads = 2); Check(bank.writes = 1); Check(mem.writes = 1); Write(offset.all, 2, 8); Check(bank.last_addr = 5); Check(mem.last_addr = 2); Check(bank.reads = 2); Check(mem.reads = 2); Check(bank.writes = 2); Check(mem.writes = 2); Read(offset.all, Address_Type(2) ** 32 - 6, 8); Check(bank.last_addr = Address_Type(2) ** 32 - 3); Check(mem.last_addr = Address_Type(2) ** 32 - 6); Check(bank.reads = 3); Check(mem.reads = 3); Check(bank.writes = 2); Check(mem.writes = 2); Destroy(Memory_Pointer(offset)); end Run_Tests; end Test.Offset;
package body System.Interrupt_Management is function Reserve (Interrupt : Interrupt_ID) return Boolean is begin return Ada.Interrupts.Is_Reserved ( Ada.Interrupts.Interrupt_Id (Interrupt)); end Reserve; end System.Interrupt_Management;
package ewok.tasks.debug with spark_mode => on is procedure crashdump (frame_a : in ewok.t_stack_frame_access); end ewok.tasks.debug;
-- see OpenUxAS\src\Communications\LmcpMessage.h with AVTAS.LMCP.Object; package UxAS.Comms.Data.LMCP_Messages is type LMCP_Message is tagged limited record -- these are public member data in the C++ version so they are visible -- in this base class (even if extensions are private, as they should be) -- Message attributes associated with the payload -- std::unique_ptr<MessageAttributes> m_attributes; Attributes : Message_Attributes_Ref; -- Data payload to be transported -- std::shared_ptr<avtas::lmcp::Object> m_object; Payload : AVTAS.LMCP.Object.Object_Any; end record; type LMCP_Message_Ref is access all LMCP_Message; type Any_LMCP_Message is access all LMCP_Message'Class; -- Ada: since the components are public we don't define a constructor function end UxAS.Comms.Data.LMCP_Messages;
with GESTE; with GESTE.Sprite.Animated; use GESTE.Sprite.Animated; with GESTE.Tile_Bank; with GESTE.Maths_Types; use GESTE.Maths_Types; with Ada.Text_IO; with Console_Char_Screen; procedure Sprite_Animation is use type GESTE.Pix_Point; package Console_Screen is new Console_Char_Screen (Width => 5, Height => 5, Buffer_Size => 256, Init_Char => ' '); Palette : aliased constant GESTE.Palette_Type := ('#', '0', 'T', ' '); Background : Character := '_'; Tiles : aliased constant GESTE.Tile_Array := (1 => ((3, 3, 3, 3, 1), (3, 3, 3, 1, 3), (3, 3, 1, 3, 3), (3, 1, 3, 3, 3), (1, 3, 3, 3, 3)), 2 => ((1, 3, 3, 3, 3), (3, 1, 3, 3, 3), (3, 3, 1, 3, 3), (3, 3, 3, 1, 3), (3, 3, 3, 3, 1)) ); Collisions : aliased constant GESTE.Tile_Collisions_Array := (1 => ((False, False, False, False, True), (False, False, False, True, False), (False, False, True, False, False), (False, True, False, False, False), (True, False, False, False, False)), 2 => ((True, False, False, False, False), (False, True, False, False, False), (False, False, True, False, False), (False, False, False, True, False), (False, False, False, False, True)) ); Anim : aliased constant Animation_Array := ((1, 1), (2, 1), (1, 1)); Bank : aliased GESTE.Tile_Bank.Instance (Tiles'Unrestricted_Access, Collisions'Unrestricted_Access, Palette'Unrestricted_Access); Sprite_A : aliased GESTE.Sprite.Animated.Instance (Bank => Bank'Unrestricted_Access, Init_Frame => 1); begin Sprite_A.Move ((0, 0)); Sprite_A.Enable_Collisions; Sprite_A.Set_Animation (Anim'Unchecked_Access, Looping => False); GESTE.Add (Sprite_A'Unrestricted_Access, 0); GESTE.Render_Window (Window => Console_Screen.Screen_Rect, Background => Background, Buffer => Console_Screen.Buffer, Push_Pixels => Console_Screen.Push_Pixels'Unrestricted_Access, Set_Drawing_Area => Console_Screen.Set_Drawing_Area'Unrestricted_Access); Console_Screen.Print; Ada.Text_IO.New_Line; Sprite_A.Signal_Frame; GESTE.Render_Dirty (Screen_Rect => Console_Screen.Screen_Rect, Background => Background, Buffer => Console_Screen.Buffer, Push_Pixels => Console_Screen.Push_Pixels'Unrestricted_Access, Set_Drawing_Area => Console_Screen.Set_Drawing_Area'Unrestricted_Access); Console_Screen.Print; Ada.Text_IO.New_Line; Sprite_A.Signal_Frame; GESTE.Render_Dirty (Screen_Rect => Console_Screen.Screen_Rect, Background => Background, Buffer => Console_Screen.Buffer, Push_Pixels => Console_Screen.Push_Pixels'Unrestricted_Access, Set_Drawing_Area => Console_Screen.Set_Drawing_Area'Unrestricted_Access); Console_Screen.Print; Ada.Text_IO.New_Line; Sprite_A.Signal_Frame; if Sprite_A.Anim_Done then Ada.Text_IO.Put_Line ("Animation done"); else Ada.Text_IO.Put_Line ("Animation not done"); end if; end Sprite_Animation;
-- { dg-do compile } package body itypes is Size : constant := 10; type Arr is array (1 .. size) of Integer; type Rec is record Field1 : Arr := (others => 0); Field2 : Arr := (others => 0); Field3 : Arr := (others => 0); Field4 : Arr := (others => 0); Field5 : Arr := (others => 0); Field6 : Arr := (others => 0); Field7 : Arr := (others => 0); end record; procedure Proc is Temp1 : Rec; begin null; end; end;
with Ada.Strings.Unbounded; with Ada.Containers.Vectors; package Menu is -- More convenient way to access unbounded strings package SU renames Ada.Strings.Unbounded; -- Access to procedure to call for items type T_Func_Ptr is access procedure; -- An item in the menu type T_Item is record Symbol : Character; Name : SU.Unbounded_String; Func : T_Func_Ptr; end record; -- A collection of items package T_Items is new Ada.Containers.Vectors (Element_Type => T_Item, Index_Type => Natural); -- A menu type T_Menu is record Title : SU.Unbounded_String; Items : T_Items.Vector; end record; procedure Add_Item(M : in out T_Menu; Item : in T_Item); -- Show a menu's title and all of its items procedure Show(M : in T_Menu); -- Show a menu, ask answer and call corresponding func procedure Query(M : in T_Menu); end Menu;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --UInt8 -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- Driver package for the FT6x06 touch screen panel -- Based on the ft6x06 driver from MCD Application Team with HAL; use HAL; with HAL.I2C; use HAL.I2C; with HAL.Touch_Panel; package FT6x06 is type FT6x06_Device (Port : not null Any_I2C_Port; I2C_Addr : I2C_Address) is limited new HAL.Touch_Panel.Touch_Panel_Device with private; function Check_Id (This : in out FT6x06_Device) return Boolean; -- Check the device Id: returns true on a FT5336 touch panel, False is -- none is found. procedure TP_Set_Use_Interrupts (This : in out FT6x06_Device; Enabled : Boolean); -- Whether the touch panel uses interrupts of polling to process touch -- information overriding procedure Set_Bounds (This : in out FT6x06_Device; Width : Natural; Height : Natural; Swap : HAL.Touch_Panel.Swap_State); -- Set screen bounds. Touch_State must should stay within screen bounds overriding function Active_Touch_Points (This : in out FT6x06_Device) return HAL.Touch_Panel.Touch_Identifier; -- Retrieve the number of active touch points overriding function Get_Touch_Point (This : in out FT6x06_Device; Touch_Id : HAL.Touch_Panel.Touch_Identifier) return HAL.Touch_Panel.TP_Touch_State; -- Retrieves the position and pressure information of the specified -- touch overriding function Get_All_Touch_Points (This : in out FT6x06_Device) return HAL.Touch_Panel.TP_State; -- Retrieves the position and pressure information of every active touch -- points private type FT6x06_Device (Port : not null Any_I2C_Port; I2C_Addr : I2C_Address) is limited new HAL.Touch_Panel.Touch_Panel_Device with record LCD_Natural_Width : Natural := 0; LCD_Natural_Height : Natural := 0; Swap : HAL.Touch_Panel.Swap_State := 0; end record; function I2C_Read (This : in out FT6x06_Device; Reg : UInt8; Status : out Boolean) return UInt8; procedure I2C_Write (This : in out FT6x06_Device; Reg : UInt8; Data : UInt8; Status : out Boolean); ------------------------------------------------------------ -- Definitions for FT6206 I2C register addresses on 8 bit -- ------------------------------------------------------------ -- Current mode register of the FT6206 (R/W) FT6206_DEV_MODE_REG : constant UInt8 := 16#00#; -- Possible values of FT6206_DEV_MODE_REG FT6206_DEV_MODE_WORKING : constant UInt8 := 16#00#; FT6206_DEV_MODE_FACTORY : constant UInt8 := 16#04#; FT6206_DEV_MODE_MASK : constant UInt8 := 16#07#; FT6206_DEV_MODE_SHIFT : constant UInt8 := 16#04#; -- Gesture ID register FT6206_GEST_ID_REG : constant UInt8 := 16#01#; -- Possible values of FT6206_GEST_ID_REG FT6206_GEST_ID_NO_GESTURE : constant UInt8 := 16#00#; FT6206_GEST_ID_MOVE_UP : constant UInt8 := 16#10#; FT6206_GEST_ID_MOVE_RIGHT : constant UInt8 := 16#14#; FT6206_GEST_ID_MOVE_DOWN : constant UInt8 := 16#18#; FT6206_GEST_ID_MOVE_LEFT : constant UInt8 := 16#1C#; FT6206_GEST_ID_ZOOM_IN : constant UInt8 := 16#40#; FT6206_GEST_ID_ZOOM_OUT : constant UInt8 := 16#49#; -- Touch Data Status register : gives number of active touch points (0..5) FT6206_TD_STAT_REG : constant UInt8 := 16#02#; -- Values related to FT6206_TD_STAT_REG FT6206_TD_STAT_MASK : constant UInt8 := 16#0F#; FT6206_TD_STAT_SHIFT : constant UInt8 := 16#00#; -- Values Pn_XH and Pn_YH related FT6206_TOUCH_EVT_FLAG_PRESS_DOWN : constant UInt8 := 16#00#; FT6206_TOUCH_EVT_FLAG_LIFT_UP : constant UInt8 := 16#01#; FT6206_TOUCH_EVT_FLAG_CONTACT : constant UInt8 := 16#02#; FT6206_TOUCH_EVT_FLAG_NO_EVENT : constant UInt8 := 16#03#; FT6206_TOUCH_EVT_FLAG_SHIFT : constant UInt8 := 16#06#; FT6206_TOUCH_EVT_FLAG_MASK : constant UInt8 := 2#1100_0000#; FT6206_TOUCH_POS_MSB_MASK : constant UInt8 := 16#0F#; FT6206_TOUCH_POS_MSB_SHIFT : constant UInt8 := 16#00#; -- Values Pn_XL and Pn_YL related FT6206_TOUCH_POS_LSB_MASK : constant UInt8 := 16#FF#; FT6206_TOUCH_POS_LSB_SHIFT : constant UInt8 := 16#00#; -- Values Pn_WEIGHT related FT6206_TOUCH_WEIGHT_MASK : constant UInt8 := 16#FF#; FT6206_TOUCH_WEIGHT_SHIFT : constant UInt8 := 16#00#; -- Values related to FT6206_Pn_MISC_REG FT6206_TOUCH_AREA_MASK : constant UInt8 := 2#0100_0000#; FT6206_TOUCH_AREA_SHIFT : constant UInt8 := 16#04#; type FT6206_Pressure_Registers is record XH_Reg : UInt8; XL_Reg : UInt8; YH_Reg : UInt8; YL_Reg : UInt8; -- Touch Pressure register value (R) Weight_Reg : UInt8; -- Touch area register Misc_Reg : UInt8; end record; FT6206_Px_Regs : constant array (Positive range <>) of FT6206_Pressure_Registers := (1 => (XH_Reg => 16#03#, XL_Reg => 16#04#, YH_Reg => 16#05#, YL_Reg => 16#06#, Weight_Reg => 16#07#, Misc_Reg => 16#08#), 2 => (XH_Reg => 16#09#, XL_Reg => 16#0A#, YH_Reg => 16#0B#, YL_Reg => 16#0C#, Weight_Reg => 16#0D#, Misc_Reg => 16#0E#)); -- Threshold for touch detection FT6206_TH_GROUP_REG : constant UInt8 := 16#80#; -- Values FT6206_TH_GROUP_REG : threshold related FT6206_THRESHOLD_MASK : constant UInt8 := 16#FF#; FT6206_THRESHOLD_SHIFT : constant UInt8 := 16#00#; -- Filter function coefficients FT6206_TH_DIFF_REG : constant UInt8 := 16#85#; -- Control register FT6206_CTRL_REG : constant UInt8 := 16#86#; -- Values related to FT6206_CTRL_REG -- Will keep the Active mode when there is no touching FT6206_CTRL_KEEP_ACTIVE_MODE : constant UInt8 := 16#00#; -- Switching from Active mode to Monitor mode automatically when there -- is no touching FT6206_CTRL_KEEP_AUTO_SWITCH_MONITOR_MODE : constant UInt8 := 16#01#; -- The time period of switching from Active mode to Monitor mode when -- there is no touching FT6206_TIMEENTERMONITOR_REG : constant UInt8 := 16#87#; -- Report rate in Active mode FT6206_PERIODACTIVE_REG : constant UInt8 := 16#88#; -- Report rate in Monitor mode FT6206_PERIODMONITOR_REG : constant UInt8 := 16#89#; -- The value of the minimum allowed angle while Rotating gesture mode FT6206_RADIAN_VALUE_REG : constant UInt8 := 16#91#; -- Maximum offset while Moving Left and Moving Right gesture FT6206_OFFSET_LEFT_RIGHT_REG : constant UInt8 := 16#92#; -- Maximum offset while Moving Up and Moving Down gesture FT6206_OFFSET_UP_DOWN_REG : constant UInt8 := 16#93#; -- Minimum distance while Moving Left and Moving Right gesture FT6206_DISTANCE_LEFT_RIGHT_REG : constant UInt8 := 16#94#; -- Minimum distance while Moving Up and Moving Down gesture FT6206_DISTANCE_UP_DOWN_REG : constant UInt8 := 16#95#; -- Maximum distance while Zoom In and Zoom Out gesture FT6206_DISTANCE_ZOOM_REG : constant UInt8 := 16#96#; -- High 8-bit of LIB Version info FT6206_LIB_VER_H_REG : constant UInt8 := 16#A1#; -- Low 8-bit of LIB Version info FT6206_LIB_VER_L_REG : constant UInt8 := 16#A2#; -- Chip Selecting FT6206_CIPHER_REG : constant UInt8 := 16#A3#; -- Interrupt mode register (used when in interrupt mode) FT6206_GMODE_REG : constant UInt8 := 16#A4#; FT6206_G_MODE_INTERRUPT_MASK : constant UInt8 := 16#03#; -- Possible values of FT6206_GMODE_REG FT6206_G_MODE_INTERRUPT_POLLING : constant UInt8 := 16#00#; FT6206_G_MODE_INTERRUPT_TRIGGER : constant UInt8 := 16#01#; -- Current power mode the FT6206 system is in (R) FT6206_PWR_MODE_REG : constant UInt8 := 16#A5#; -- FT6206 firmware version FT6206_FIRMID_REG : constant UInt8 := 16#A6#; -- FT6206 Chip identification register FT6206_CHIP_ID_REG : constant UInt8 := 16#A8#; -- Possible values of FT6206_CHIP_ID_REG FT6206_ID_VALUE : constant UInt8 := 16#11#; -- Release code version FT6206_RELEASE_CODE_ID_REG : constant UInt8 := 16#AF#; -- Current operating mode the FT6206 system is in (R) FT6206_STATE_REG : constant UInt8 := 16#BC#; end FT6x06;
with Ada.Interrupts.Names; package STM32.CORDIC.Interrupts is procedure Calculate_CORDIC_Function (This : in out CORDIC_Coprocessor; Argument : UInt32_Array; Result : out UInt32_Array); -- Uses the interrupt interface to get the calculated funtion result. procedure Calculate_CORDIC_Function (This : in out CORDIC_Coprocessor; Argument : UInt16_Array; Result : out UInt16_Array); -- Uses the interrupt interface to get the calculated funtion result. private type Buffer_Content is array (Integer range <>) of UInt32; type Ring_Buffer is record Content : Buffer_Content (0 .. 9); Head : Integer := 0; Tail : Integer := 0; end record; Ring_Buffer_Full : exception; -- Raised when the Ring Buffer is full (Head and Tail is the same). protected Receiver is pragma Interrupt_Priority; entry Get_Result (Value : out UInt32); private Buffer : Ring_Buffer; Data_Available : Boolean := False; procedure Interrupt_Handler; pragma Attach_Handler (Interrupt_Handler, Ada.Interrupts.Names.Cordic_Interrupt); end Receiver; end STM32.CORDIC.Interrupts;
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- The primary authors of ayacc were David Taback and Deepak Tolani. -- Enhancements were made by Ronald J. Schmalz. -- -- Send requests for ayacc information to ayacc-info@ics.uci.edu -- Send bug reports for ayacc to ayacc-bugs@ics.uci.edu -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the University of California, Irvine. The name of the -- University may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -- Module : lexical_analyzer.ada -- Component of : ayacc -- Version : 1.2 -- Date : 11/21/86 12:30:26 -- SCCS File : disk21~/rschm/hasee/sccs/ayacc/sccs/sxlexical_analyzer.ada -- $Header: lexical_analyzer.a,v 0.1 86/04/01 15:05:14 ada Exp $ -- $Log: lexical_analyzer.a,v $ -- Revision 0.1 86/04/01 15:05:14 ada -- This version fixes some minor bugs with empty grammars -- and $$ expansion. It also uses vads5.1b enhancements -- such as pragma inline. -- -- -- Revision 0.0 86/02/19 18:36:57 ada -- -- These files comprise the initial version of Ayacc -- designed and implemented by David Taback and Deepak Tolani. -- Ayacc has been compiled and tested under the Verdix Ada compiler -- version 4.06 on a vax 11/750 running Unix 4.2BSD. -- with Source_File; package Lexical_Analyzer is function Get_Lexeme_Text return String; -- Scanned text. type Ayacc_Token is (Token, Start, Left, Right, Nonassoc, Prec, With_Clause, Use_Clause, Identifier, Character_Literal, Comma, Colon, Semicolon, Vertical_Bar, Left_Brace, Mark, Eof_Token); function Get_Token return Ayacc_Token; function Line_Number return Natural; -- Current line of source file procedure Handle_Action(Rule, Rule_Length : Integer); procedure Print_Context_Lines renames Source_File.Print_Context_Lines; procedure Dump_Declarations; Illegal_Token : exception; end Lexical_Analyzer;
package LinkedLists is type IntElem; type IntElemPtr is access IntElem; type IntElem is record val : Integer; nxt : IntElemPtr; end record; type Obj is tagged; type ObjPtr is access Obj; type Obj is tagged record nxt : ObjPtr; end record; end LinkedLists;
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.AES; with Util.Encoders.AES; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Lzma.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String); package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write", Test_Compress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)", Test_Compress_File_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Read+Write", Test_Compress_Decompress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Read+Write+AES-CBC", Test_Compress_Encrypt_Decompress_Decrypt_Stream'Access); end Add_Tests; procedure Test_Compress_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma"); begin Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 1024); Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_Stream; procedure Test_Compress_File_Stream (T : in out Test) is Stream : aliased File_Stream; In_Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-big-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma"); begin In_Stream.Open (Ada.Streams.Stream_IO.In_File, Util.Tests.Get_Path ("regtests/files/test-big-stream.bin")); Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 32768); Util.Streams.Copy (From => In_Stream, Into => Buffer); Buffer.Flush; Buffer.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_File_Stream; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is use Ada.Strings.Unbounded; Path : constant String := Util.Tests.Get_Test_Path ("stream-lzma-aes-" & Label & ".aes"); Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); File : aliased File_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream; Print : Util.Streams.Texts.Print_Stream; Reader : Util.Streams.Texts.Reader_Stream; begin -- Print -> Compress -> Cipher -> File File.Create (Mode => Out_File, Name => Path); if Encrypt then Cipher.Produces (File'Unchecked_Access, 64); Cipher.Set_Key (Key, Mode); Compress.Initialize (Cipher'Unchecked_Access, 1024); else Compress.Initialize (File'Unchecked_Access, 1024); end if; Print.Initialize (Compress'Unchecked_Access); for I in 1 .. Count loop Print.Write (Item & ASCII.LF); end loop; Print.Close; -- File -> Decipher -> Decompress -> Reader File.Open (Mode => In_File, Name => Path); if Encrypt then Decipher.Consumes (File'Unchecked_Access, 128); Decipher.Set_Key (Key, Mode); Decompress.Initialize (Decipher'Unchecked_Access, 1024); else Decompress.Initialize (File'Unchecked_Access, 1024); end if; Reader.Initialize (From => Decompress'Unchecked_Access); declare Line_Count : Natural := 0; begin while not Reader.Is_Eof loop declare Line : Unbounded_String; begin Reader.Read_Line (Line); exit when Length (Line) = 0; if Item & ASCII.LF /= Line then Util.Tests.Assert_Equals (T, Item & ASCII.LF, To_String (Line)); end if; Line_Count := Line_Count + 1; end; end loop; File.Close; Util.Tests.Assert_Equals (T, Count, Line_Count); end; end Test_Stream_File; procedure Test_Compress_Decompress_Stream (T : in out Test) is begin Test_Stream_File (T, "abcdefgh", 1000, False, Util.Encoders.AES.CBC, "NONE"); end Test_Compress_Decompress_Stream; procedure Test_Compress_Encrypt_Decompress_Decrypt_Stream (T : in out Test) is begin Test_Stream_File (T, "abcdefgh", 1000, True, Util.Encoders.AES.CBC, "AES-CBC"); end Test_Compress_Encrypt_Decompress_Decrypt_Stream; end Util.Streams.Buffered.Lzma.Tests;
with System; package Init12 is type Arr1 is array (1 .. 3) of Integer; for Arr1'Scalar_Storage_Order use System.Low_Order_First; type Arr11 is array (1 .. 2, 1 .. 2) of Integer; for Arr11'Scalar_Storage_Order use System.Low_Order_First; type Arr2 is array (1 .. 3) of Integer; for Arr2'Scalar_Storage_Order use System.High_Order_First; type Arr22 is array (1 .. 2, 1 .. 2) of Integer; for Arr22'Scalar_Storage_Order use System.High_Order_First; My_A1 : constant Arr1 := (16#AB0012#, 16#CD0034#, 16#EF0056#); My_A11 : constant Arr11 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); My_A2 : constant Arr2 := (16#AB0012#, 16#CD0034#, 16#EF0056#); My_A22 : constant Arr22 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); end Init12;
pragma License (Unrestricted); -- implementation unit required by compiler with System.Packed_Arrays; package System.Compare_Array_Unsigned_64 is pragma Preelaborate; -- It can not be Pure, subprograms would become __attribute__((const)). type Unsigned_64 is mod 2 ** 64; for Unsigned_64'Size use 64; for Unsigned_64'Alignment use 1; package Ordering is new Packed_Arrays.Ordering (Unsigned_64); -- required to compare arrays by compiler (s-caun64.ads) function Compare_Array_U64 ( Left : Address; Right : Address; Left_Len : Natural; Right_Len : Natural) return Integer renames Ordering.Compare; end System.Compare_Array_Unsigned_64;
with agar.gui.surface; with agar.gui.widget; with agar.gui.types; package agar.gui.window is use type c.unsigned; use type agar.gui.types.window_flags_t; subtype window_t is agar.gui.types.window_t; subtype window_access_t is agar.gui.types.window_access_t; -- -- constants -- caption_max : constant c.unsigned := agar.gui.types.window_caption_max; -- -- types -- subtype flags_t is agar.gui.types.window_flags_t; WINDOW_MODAL : constant flags_t := 16#000001#; WINDOW_MAXIMIZED : constant flags_t := 16#000002#; WINDOW_MINIMIZED : constant flags_t := 16#000004#; WINDOW_KEEPABOVE : constant flags_t := 16#000008#; WINDOW_KEEPBELOW : constant flags_t := 16#000010#; WINDOW_DENYFOCUS : constant flags_t := 16#000020#; WINDOW_NOTITLE : constant flags_t := 16#000040#; WINDOW_NOBORDERS : constant flags_t := 16#000080#; WINDOW_NOHRESIZE : constant flags_t := 16#000100#; WINDOW_NOVRESIZE : constant flags_t := 16#000200#; WINDOW_NOCLOSE : constant flags_t := 16#000400#; WINDOW_NOMINIMIZE : constant flags_t := 16#000800#; WINDOW_NOMAXIMIZE : constant flags_t := 16#001000#; WINDOW_NOBACKGROUND : constant flags_t := 16#008000#; WINDOW_NOUPDATERECT : constant flags_t := 16#010000#; WINDOW_FOCUSONATTACH : constant flags_t := 16#020000#; WINDOW_HMAXIMIZE : constant flags_t := 16#040000#; WINDOW_VMAXIMIZE : constant flags_t := 16#080000#; WINDOW_NOMOVE : constant flags_t := 16#100000#; WINDOW_NOCLIPPING : constant flags_t := 16#200000#; WINDOW_NORESIZE : constant flags_t := WINDOW_NOHRESIZE or WINDOW_NOVRESIZE; WINDOW_NOBUTTONS : constant flags_t := WINDOW_NOCLOSE or WINDOW_NOMINIMIZE or WINDOW_NOMAXIMIZE; WINDOW_PLAIN : constant flags_t := WINDOW_NOTITLE or WINDOW_NOBORDERS; subtype alignment_t is agar.gui.types.window_alignment_t; type close_action_t is ( WINDOW_HIDE, WINDOW_DETACH, WINDOW_NONE ); for close_action_t use ( WINDOW_HIDE => 0, WINDOW_DETACH => 1, WINDOW_NONE => 2 ); for close_action_t'size use c.unsigned'size; pragma convention (c, close_action_t); subtype percent_t is positive range 1 .. 100; -- -- API -- function allocate (flags : flags_t := 0) return window_access_t; pragma import (c, allocate, "AG_WindowNew"); function allocate_named (flags : flags_t := 0; name : string) return window_access_t; pragma inline (allocate_named); procedure set_caption (window : window_access_t; caption : string); pragma inline (set_caption); procedure set_icon (window : window_access_t; surface : agar.gui.surface.surface_access_t); pragma import (c, set_icon, "agar_window_set_icon"); procedure set_icon_no_copy (window : window_access_t; surface : agar.gui.surface.surface_access_t); pragma import (c, set_icon_no_copy, "agar_window_set_icon_no_copy"); procedure set_close_action (window : window_access_t; mode : close_action_t); pragma import (c, set_close_action, "AG_WindowSetCloseAction"); procedure set_padding (window : window_access_t; left : natural; right : natural; top : natural; bottom : natural); pragma inline (set_padding); procedure set_spacing (window : window_access_t; spacing : natural); pragma inline (set_spacing); procedure set_position (window : window_access_t; alignment : alignment_t; cascade : boolean); pragma inline (set_position); procedure set_geometry (window : window_access_t; x : natural; y : natural; width : natural; height : natural); pragma inline (set_geometry); procedure set_geometry_aligned (window : window_access_t; alignment : alignment_t; width : positive; height : positive); pragma inline (set_geometry_aligned); procedure set_geometry_aligned_percent (window : window_access_t; alignment : alignment_t; width : percent_t; height : percent_t); pragma inline (set_geometry_aligned_percent); procedure set_geometry_bounded (window : window_access_t; x : natural; y : natural; width : natural; height : natural); pragma inline (set_geometry_bounded); procedure set_geometry_max (window : window_access_t); pragma import (c, set_geometry_max, "AG_WindowSetGeometryMax"); procedure set_minimum_size (window : window_access_t; width : natural; height : natural); pragma inline (set_minimum_size); procedure set_minimum_size_percentage (window : window_access_t; percent : percent_t); pragma inline (set_minimum_size_percentage); procedure maximize (window : window_access_t); pragma import (c, maximize, "AG_WindowMaximize"); procedure unmaximize (window : window_access_t); pragma import (c, unmaximize, "AG_WindowUnmaximize"); procedure minimize (window : window_access_t); pragma import (c, minimize, "AG_WindowMinimize"); procedure unminimize (window : window_access_t); pragma import (c, unminimize, "AG_WindowUnminimize"); procedure attach (window : window_access_t; subwindow : window_access_t); pragma import (c, attach, "AG_WindowAttach"); procedure detach (window : window_access_t; subwindow : window_access_t); pragma import (c, detach, "AG_WindowDetach"); procedure update (window : window_access_t); pragma import (c, update, "agar_window_update"); -- visibility procedure show (window : window_access_t); pragma import (c, show, "AG_WindowShow"); procedure hide (window : window_access_t); pragma import (c, hide, "AG_WindowHide"); function is_visible (window : window_access_t) return c.int; pragma import (c, is_visible, "agar_window_is_visible"); function is_visible (window : window_access_t) return boolean; pragma inline (is_visible); procedure set_visibility (window : window_access_t; visible : boolean); pragma inline (set_visibility); -- focus procedure focus (window : window_access_t); pragma import (c, focus, "AG_WindowFocus"); function focus_named (name : string) return boolean; pragma inline (focus_named); function find_focused (window : window_access_t) return agar.gui.widget.widget_access_t; pragma import (c, find_focused, "AG_WidgetFindFocused"); function is_focused (window : window_access_t) return c.int; pragma import (c, is_focused, "agar_window_is_focused"); function is_focused (window : window_access_t) return boolean; pragma inline (is_focused); -- function widget (window : window_access_t) return agar.gui.widget.widget_access_t renames agar.gui.types.window_widget; end agar.gui.window;
-- PR debug/80321 -- { dg-do compile } -- { dg-options "-O2 -g" } with Debug10_Pkg; use Debug10_Pkg; procedure Debug10 (T : Entity_Id) is procedure Inner (E : Entity_Id); pragma Inline (Inner); procedure Inner (E : Entity_Id) is begin if E /= Empty and then not Nodes (E + 3).Flag16 then Debug10 (E); end if; end Inner; function Ekind (E : Entity_Id) return Entity_Kind is begin return N_To_E (Nodes (E + 1).Nkind); end Ekind; begin if T = Empty then return; end if; Nodes (T + 3).Flag16 := True; if Ekind (T) in Object_Kind then Inner (T); elsif Ekind (T) in Type_Kind then Inner (T); if Ekind (T) in Record_Kind then if Ekind (T) = E_Class_Wide_Subtype then Inner (T); end if; elsif Ekind (T) in Array_Kind then Inner (T); elsif Ekind (T) in Access_Kind then Inner (T); elsif Ekind (T) in Scalar_Kind then if My_Scalar_Range (T) /= Empty and then My_Test (My_Scalar_Range (T)) then if My_Is_Entity_Name (T) then Inner (T); end if; if My_Is_Entity_Name (T) then Inner (T); end if; end if; end if; end if; end;
-- { dg-do compile } with Varsize3_Pkg1; use Varsize3_Pkg1; procedure Varsize3_6 is Filter : Arr renames True.E; begin null; end;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- ADA.NUMERICS.GENERIC_ELEMENTARY_FUNCTIONS -- -- -- -- S p e c -- -- -- -- Copyright (C) 2012, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the Post aspects that have been added to the spec. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ generic type Float_Type is digits <>; package Ada.Numerics.Generic_Elementary_Functions is pragma Pure; function Sqrt (X : Float_Type'Base) return Float_Type'Base with Post => Sqrt'Result >= 0.0 and then (if X = 0.0 then Sqrt'Result = 0.0) and then (if X = 1.0 then Sqrt'Result = 1.0); function Log (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 1.0 then Log'Result = 0.0); function Log (X, Base : Float_Type'Base) return Float_Type'Base with Post => (if X = 1.0 then Log'Result = 0.0); function Exp (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Exp'Result = 1.0); function "**" (Left, Right : Float_Type'Base) return Float_Type'Base with Post => "**"'Result >= 0.0 and then (if Right = 0.0 then "**"'Result = 1.0) and then (if Right = 1.0 then "**"'Result = Left) and then (if Left = 1.0 then "**"'Result = 1.0) and then (if Left = 0.0 then "**"'Result = 0.0); function Sin (X : Float_Type'Base) return Float_Type'Base with Post => Sin'Result in -1.0 .. 1.0 and then (if X = 0.0 then Sin'Result = 0.0); function Sin (X, Cycle : Float_Type'Base) return Float_Type'Base with Post => Sin'Result in -1.0 .. 1.0 and then (if X = 0.0 then Sin'Result = 0.0); function Cos (X : Float_Type'Base) return Float_Type'Base with Post => Cos'Result in -1.0 .. 1.0 and then (if X = 0.0 then Cos'Result = 1.0); function Cos (X, Cycle : Float_Type'Base) return Float_Type'Base with Post => Cos'Result in -1.0 .. 1.0 and then (if X = 0.0 then Cos'Result = 1.0); function Tan (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Tan'Result = 0.0); function Tan (X, Cycle : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Tan'Result = 0.0); function Cot (X : Float_Type'Base) return Float_Type'Base; function Cot (X, Cycle : Float_Type'Base) return Float_Type'Base; function Arcsin (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Arcsin'Result = 0.0); function Arcsin (X, Cycle : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Arcsin'Result = 0.0); function Arccos (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 1.0 then Arccos'Result = 0.0); function Arccos (X, Cycle : Float_Type'Base) return Float_Type'Base with Post => (if X = 1.0 then Arccos'Result = 0.0); function Arctan (Y : Float_Type'Base; X : Float_Type'Base := 1.0) return Float_Type'Base with Post => (if X > 0.0 and Y = 0.0 then Arctan'Result = 0.0); function Arctan (Y : Float_Type'Base; X : Float_Type'Base := 1.0; Cycle : Float_Type'Base) return Float_Type'Base with Post => (if X > 0.0 and Y = 0.0 then Arctan'Result = 0.0); function Arccot (X : Float_Type'Base; Y : Float_Type'Base := 1.0) return Float_Type'Base with Post => (if X > 0.0 and Y = 0.0 then Arccot'Result = 0.0); function Arccot (X : Float_Type'Base; Y : Float_Type'Base := 1.0; Cycle : Float_Type'Base) return Float_Type'Base with Post => (if X > 0.0 and Y = 0.0 then Arccot'Result = 0.0); function Sinh (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Sinh'Result = 0.0); function Cosh (X : Float_Type'Base) return Float_Type'Base with Post => Cosh'Result >= 1.0 and then (if X = 0.0 then Cosh'Result = 1.0); function Tanh (X : Float_Type'Base) return Float_Type'Base with Post => Tanh'Result in -1.0 .. 1.0 and then (if X = 0.0 then Tanh'Result = 0.0); function Coth (X : Float_Type'Base) return Float_Type'Base with Post => abs Coth'Result >= 1.0; function Arcsinh (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Arcsinh'Result = 0.0); function Arccosh (X : Float_Type'Base) return Float_Type'Base with Post => Arccosh'Result >= 0.0 and then (if X = 1.0 then Arccosh'Result = 0.0); function Arctanh (X : Float_Type'Base) return Float_Type'Base with Post => (if X = 0.0 then Arctanh'Result = 0.0); function Arccoth (X : Float_Type'Base) return Float_Type'Base; end Ada.Numerics.Generic_Elementary_Functions;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . W C H _ S T W -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2000 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Interfaces; use Interfaces; with System.WCh_Con; use System.WCh_Con; with System.WCh_JIS; use System.WCh_JIS; package body System.WCh_StW is --------------------------- -- String_To_Wide_String -- --------------------------- function String_To_Wide_String (S : String; EM : WC_Encoding_Method) return Wide_String is R : Wide_String (1 .. S'Length); RP : Natural; SP : Natural; U1 : Unsigned_16; U2 : Unsigned_16; U3 : Unsigned_16; U : Unsigned_16; Last : constant Natural := S'Last; function Get_Hex (C : Character) return Unsigned_16; -- Converts character from hex digit to value in range 0-15. The -- input must be in 0-9, A-F, or a-f, and no check is needed. procedure Get_Hex_4; -- Translates four hex characters starting at S (SP) to a single -- wide character. Used in WCEM_Hex and WCEM_Brackets mode. SP -- is not modified by the call. The resulting wide character value -- is stored in R (RP). RP is not modified by the call. function Get_Hex (C : Character) return Unsigned_16 is begin if C in '0' .. '9' then return Character'Pos (C) - Character'Pos ('0'); elsif C in 'A' .. 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; else return Character'Pos (C) - Character'Pos ('a') + 10; end if; end Get_Hex; procedure Get_Hex_4 is begin R (RP) := Wide_Character'Val ( Get_Hex (S (SP + 3)) + 16 * (Get_Hex (S (SP + 2)) + 16 * (Get_Hex (S (SP + 1)) + 16 * (Get_Hex (S (SP + 0)))))); end Get_Hex_4; -- Start of processing for String_To_Wide_String begin SP := S'First; RP := 0; case EM is -- ESC-Hex representation when WCEM_Hex => while SP <= Last - 4 loop RP := RP + 1; if S (SP) = ASCII.ESC then SP := SP + 1; Get_Hex_4; SP := SP + 4; else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; -- Upper bit shift, internal code = external code when WCEM_Upper => while SP < Last loop RP := RP + 1; if S (SP) >= Character'Val (16#80#) then U1 := Character'Pos (S (SP)); U2 := Character'Pos (S (SP + 1)); R (RP) := Wide_Character'Val (256 * U1 + U2); SP := SP + 2; else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; -- Upper bit shift, shift-JIS when WCEM_Shift_JIS => while SP < Last loop RP := RP + 1; if S (SP) >= Character'Val (16#80#) then R (RP) := Shift_JIS_To_JIS (S (SP), S (SP + 1)); SP := SP + 2; else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; -- Upper bit shift, EUC when WCEM_EUC => while SP < Last loop RP := RP + 1; if S (SP) >= Character'Val (16#80#) then R (RP) := EUC_To_JIS (S (SP), S (SP + 1)); SP := SP + 2; else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; -- Upper bit shift, UTF-8 when WCEM_UTF8 => while SP < Last loop RP := RP + 1; if S (SP) >= Character'Val (16#80#) then U1 := Character'Pos (S (SP)); U2 := Character'Pos (S (SP + 1)); U := Shift_Left (U1 and 2#00011111#, 6) + (U2 and 2#00111111#); SP := SP + 2; if U1 >= 2#11100000# then U3 := Character'Pos (S (SP)); U := Shift_Left (U, 6) + (U3 and 2#00111111#); SP := SP + 1; end if; R (RP) := Wide_Character'Val (U); else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; -- Brackets representation when WCEM_Brackets => while SP <= Last - 7 loop RP := RP + 1; if S (SP) = '[' and then S (SP + 1) = '"' and then S (SP + 2) /= '"' then SP := SP + 2; Get_Hex_4; SP := SP + 6; else R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end if; end loop; end case; while SP <= Last loop RP := RP + 1; R (RP) := Wide_Character'Val (Character'Pos (S (SP))); SP := SP + 1; end loop; return R (1 .. RP); end String_To_Wide_String; end System.WCh_StW;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Log.Loggers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; begin P.Parse_String (Content); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; begin P.Parse_String (Content); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); end Test_Parser; end Util.Serialize.IO.JSON.Tests;
-- ----------------------------------------------------------------- -- -- AdaSDL -- -- Binding to Simple Direct Media Layer -- -- Copyright (C) 2001 A.M.F.Vargas -- -- Antonio M. F. Vargas -- -- Ponta Delgada - Azores - Portugal -- -- http://www.adapower.net/~avargas -- -- E-mail: avargas@adapower.net -- -- ----------------------------------------------------------------- -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public -- -- License as published by the Free Software Foundation; either -- -- version 2 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from -- -- this unit, or you link this unit with other files to produce an -- -- executable, this unit does not by itself cause the resulting -- -- executable to be covered by the GNU General Public License. This -- -- exception does not however invalidate any other reasons why the -- -- executable file might be covered by the GNU Public License. -- -- ----------------------------------------------------------------- -- -- **************************************************************** -- -- 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 SDL.Byteorder.Extra; package body SDL.Audio is use type C.int; ------------- -- LoadWAV -- ------------- function LoadWAV (file : C.Strings.chars_ptr; spec : AudioSpec_ptr; audio_buf : Uint8_ptr_ptr; audio_len : Uint32_ptr) return AudioSpec_ptr is use SDL.RWops; begin return LoadWAV_RW ( RWFromFile ( file, C.Strings.New_String ("rb")), 1, spec, audio_buf, audio_len); end LoadWAV; ------------- -- LoadWAV_VP -- ------------- procedure Load_WAV ( file : C.Strings.chars_ptr; spec : AudioSpec_ptr; -- out AudioSpec audio_buf : Uint8_ptr_ptr; -- out Uint8_ptr audio_len : Uint32_ptr; -- out Uint32 Valid_WAV : out Boolean) is use SDL.RWops; Audio_Spec_Pointer : AudioSpec_ptr; begin Audio_Spec_Pointer := LoadWAV_RW ( RWFromFile ( file, C.Strings.New_String ("rb")), 1, spec, audio_buf, audio_len); -- LoadWAV_RW_VP ( -- Audio_Spec_Pointer, -- RWFromFile ( -- file, -- C.Strings.New_String ("rb")), -- 1, -- spec, -- audio_buf, -- audio_len); Valid_WAV := Audio_Spec_Pointer /= null; end Load_WAV; ----------------------- -- Get_Audio_S16_Sys -- ----------------------- function Get_Audio_S16_Sys return Format_Flag is use SDL.Byteorder; use SDL.Byteorder.Extra; begin if BYTE_ORDER = LIL_ENDIAN then return AUDIO_S16LSB; else return AUDIO_S16MSB; end if; end Get_Audio_S16_Sys; ----------------------- -- Get_Audio_U16_Sys -- ----------------------- function Get_Audio_U16_Sys return Format_Flag is use SDL.Byteorder; use SDL.Byteorder.Extra; begin if BYTE_ORDER = LIL_ENDIAN then return AUDIO_U16LSB; else return AUDIO_S16LSB; end if; end Get_Audio_U16_Sys; end SDL.Audio;
with Sorok, Ada.Command_Line, Ada.Integer_Text_IO; use Sorok; procedure SorDemo is N: Integer; S: Sor(Ada.Command_Line.Argument_Count); begin for I in 1..Ada.Command_Line.Argument_Count loop N := Integer'Value(Ada.Command_Line.Argument(I)); Hiext( S, N ); end loop; while not Is_Empty(S) loop Lopop( S, N ); Ada.Integer_Text_IO.Put(N); end loop; end SorDemo;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ -- Purpose: -- Help with manipulation of Element package Asis.Gela.Element_Utils is function Compound_Name_Image (Compount_Name : Asis.Element) return Wide_String; procedure Set_Enclosing_Element (Item : Asis.Element; Parent : Asis.Element); procedure Set_Enclosing_Compilation_Unit (Item : Asis.Element; Unit : Asis.Compilation_Unit); function To_Unit_Name (Compount_Name : Asis.Element) return Asis.Element; procedure Copy_Element (Source : Asis.Element; Target : Asis.Element); procedure Set_Resolved (Element : Asis.Element; List : Asis.Defining_Name_List); procedure Set_Override (Defining_Name : Asis.Element; Homograph : Asis.Element); function Override (Defining_Name : Asis.Element) return Asis.Element; procedure Add_To_Visible (Declaration : Asis.Element; Item : Asis.Element; Before : Asis.Program_Text := ""); procedure Add_Defining_Name (Item : Asis.Element; Name : Asis.Element); procedure Remove_Defining_Name (Item : Asis.Element; Name : Asis.Element); procedure Set_Name_Declaration (Item : Asis.Element; Name : Asis.Declaration); procedure Set_Pragma_Kind (Element : Asis.Pragma_Element); procedure Add_Type_Operator (Tipe : Asis.Definition; Oper : Asis.Declaration); procedure Add_Inherited_Subprogram (Tipe : Asis.Definition; Proc : Asis.Declaration); function Base_Subprogram_Derivation (Proc : Asis.Declaration) return Asis.Declaration; procedure Add_Pragma (Item : Asis.Element; The_Pragma : Asis.Pragma_Element); procedure Set_Derived_Type (Tipe : Asis.Type_Definition; Parent : Asis.Declaration; Root : Asis.Declaration; Struct : Asis.Declaration); procedure Set_Called_Function (Call : Asis.Element; Name : Asis.Declaration; Dispatched : Boolean); procedure Set_Corresponding_Statement (Stmt : Asis.Statement; Target : Asis.Statement); procedure Set_Completion (Declaration : Asis.Defining_Name; Completion : Asis.Declaration); procedure Set_Normalized_Params (Call : Asis.Element; Param : Asis.Association_List; Profile : Asis.Parameter_Specification_List); procedure Set_Representation_Value (Enum : Asis.Declaration; Value : Wide_String); procedure Set_Corresponding_Type (Funct : Asis.Declaration; Tipe : Asis.Type_Definition); function Generic_Actual (Decl : Asis.Declaration) return Asis.Expression; end Asis.Gela.Element_Utils; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Calendar.Arithmetic; with Ada.Calendar.Formatting; with Ada.Characters.Latin_1; with Ada.Directories; with File_Operations; with Parameters; with Utilities; package body PortScan.Log is package DIR renames Ada.Directories; package CAR renames Ada.Calendar.Arithmetic; package CFM renames Ada.Calendar.Formatting; package LAT renames Ada.Characters.Latin_1; package FOP renames File_Operations; package PM renames Parameters; package UTL renames Utilities; -------------------------------------------------------------------------------------------- -- log_duration -------------------------------------------------------------------------------------------- function log_duration (start, stop : CAL.Time) return String is raw : HT.Text := HT.SUS ("Duration:"); diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; use type CAR.Day_Count; begin CAR.Difference (Left => stop, Right => start, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); if diff_days > 0 then if diff_days = 1 then HT.SU.Append (raw, " 1 day and " & CFM.Image (Elapsed_Time => diff_secs)); else HT.SU.Append (raw, diff_days'Img & " days and " & CFM.Image (Elapsed_Time => diff_secs)); end if; else HT.SU.Append (raw, " " & CFM.Image (Elapsed_Time => diff_secs)); end if; return HT.USS (raw); end log_duration; -------------------------------------------------------------------------------------------- -- bulk_run_duration -------------------------------------------------------------------------------------------- function bulk_run_duration return String is begin return log_duration (start_time, stop_time); end bulk_run_duration; -------------------------------------------------------------------------------------------- -- log_name -------------------------------------------------------------------------------------------- function log_name (sid : port_id) return String is portvar : constant String := get_port_variant (all_ports (sid)); origin : constant String := HT.part_1 (portvar, ":"); variant : constant String := HT.part_2 (portvar, ":"); begin return HT.USS (PM.configuration.dir_logs) & "/logs/" & origin & "___" & variant & ".log"; end log_name; -------------------------------------------------------------------------------------------- -- log_section -------------------------------------------------------------------------------------------- function log_section (title : String) return String is hyphens : constant String := (1 .. 50 => '-'); begin return LAT.LF & hyphens & LAT.LF & "-- " & title & LAT.LF & hyphens; end log_section; ------------------------------------------------------------------po-------------------------- -- timestamp -------------------------------------------------------------------------------------------- function timestamp (hack : CAL.Time; www_format : Boolean := False) return String is function MON (T : CAL.Time) return String; function WKDAY (T : CAL.Time) return String; function daystring (T : CAL.Time) return String; function MON (T : CAL.Time) return String is num : CAL.Month_Number := CAL.Month (T); begin case num is when 1 => return "JAN"; when 2 => return "FEB"; when 3 => return "MAR"; when 4 => return "APR"; when 5 => return "MAY"; when 6 => return "JUN"; when 7 => return "JUL"; when 8 => return "AUG"; when 9 => return "SEP"; when 10 => return "OCT"; when 11 => return "NOV"; when 12 => return "DEC"; end case; end MON; function WKDAY (T : CAL.Time) return String is day : CFM.Day_Name := CFM.Day_Of_Week (T); begin case day is when CFM.Monday => return "Monday"; when CFM.Tuesday => return "Tuesday"; when CFM.Wednesday => return "Wednesday"; when CFM.Thursday => return "Thursday"; when CFM.Friday => return "Friday"; when CFM.Saturday => return "Saturday"; when CFM.Sunday => return "Sunday"; end case; end WKDAY; function daystring (T : CAL.Time) return String is daynum : Natural := Natural (CAL.Day (T)); begin return HT.zeropad (daynum, 2); end daystring; begin if www_format then return daystring (hack) & " " & MON (hack) & CAL.Year (hack)'Img & ", " & CFM.Image (hack)(11 .. 19) & " UTC"; end if; return WKDAY (hack) & "," & daystring (hack) & " " & MON (hack) & CAL.Year (hack)'Img & " at" & CFM.Image (hack)(11 .. 19) & " UTC"; end timestamp; -------------------------------------------------------------------------------------------- -- scan_duration -------------------------------------------------------------------------------------------- function scan_duration return String is begin return elapsed_HH_MM_SS (start => scan_start, stop => scan_stop); end scan_duration; -------------------------------------------------------------------------------------------- -- elapsed_now -------------------------------------------------------------------------------------------- function elapsed_now return String is begin return elapsed_HH_MM_SS (start => start_time, stop => CAL.Clock); end elapsed_now; -------------------------------------------------------------------------------------------- -- elapsed_HH_MM_SS -------------------------------------------------------------------------------------------- function elapsed_HH_MM_SS (start, stop : CAL.Time) return String is diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; secs_per_hour : constant Integer := 3600; total_hours : Integer; total_minutes : Integer; work_hours : Integer; work_seconds : Integer; use type CAR.Day_Count; begin CAR.Difference (Left => stop, Right => start, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); -- Seems the ACF image is shit, so let's roll our own. If more than -- 100 hours, change format to "HHH:MM.M" work_seconds := Integer (diff_secs); total_hours := work_seconds / secs_per_hour; total_hours := total_hours + Integer (diff_days) * 24; if total_hours < 24 then if work_seconds < 0 then return "--:--:--"; else work_seconds := work_seconds - (total_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := work_seconds - (total_minutes * 60); return HT.zeropad (total_hours, 2) & LAT.Colon & HT.zeropad (total_minutes, 2) & LAT.Colon & HT.zeropad (work_seconds, 2); end if; elsif total_hours < 100 then if work_seconds < 0 then return HT.zeropad (total_hours, 2) & ":00:00"; else work_hours := work_seconds / secs_per_hour; work_seconds := work_seconds - (work_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := work_seconds - (total_minutes * 60); return HT.zeropad (total_hours, 2) & LAT.Colon & HT.zeropad (total_minutes, 2) & LAT.Colon & HT.zeropad (work_seconds, 2); end if; else if work_seconds < 0 then return HT.zeropad (total_hours, 3) & ":00.0"; else work_hours := work_seconds / secs_per_hour; work_seconds := work_seconds - (work_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := (work_seconds - (total_minutes * 60)) * 10 / 60; return HT.zeropad (total_hours, 3) & LAT.Colon & HT.zeropad (total_minutes, 2) & '.' & HT.int2str (work_seconds); end if; end if; end elapsed_HH_MM_SS; -------------------------------------------------------------------------------------------- -- split_collection -------------------------------------------------------------------------------------------- function split_collection (line : String; title : String) return String is -- Everything, including spaces, between quotes is preserved. -- Quotes preceded by backslashes within quotes are considered literals. -- Also supported is escaped spaces outside of quotes, e.g. -- TYPING=The\ Quick\ Brown\ Fox mask : String := UTL.mask_quoted_string (line); linelen : constant Natural := line'Length; keepit : Boolean; newline : Boolean := True; counter : Natural := 0; meatlen : Natural := 0; onechar : Character; meatstr : String (1 .. linelen); begin loop exit when counter = linelen; keepit := True; if mask (mask'First + counter) = LAT.Reverse_Solidus then keepit := False; elsif mask (mask'First + counter) = LAT.Space then if newline then keepit := False; elsif mask (mask'First + counter - 1) = LAT.Reverse_Solidus then onechar := LAT.Space; else onechar := LAT.LF; end if; else onechar := line (mask'First + counter); end if; if keepit then meatlen := meatlen + 1; meatstr (meatlen) := onechar; newline := (onechar = LAT.LF); end if; counter := counter + 1; end loop; return log_section (title) & LAT.LF & meatstr (1 .. meatlen) & LAT.LF & LAT.LF; end split_collection; -------------------------------------------------------------------------------------------- -- dump_port_variables -------------------------------------------------------------------------------------------- procedure dump_port_variables (log_handle : TIO.File_Type; contents : String) is type result_range is range 0 .. 6; markers : HT.Line_Markers; linenum : result_range := result_range'First; begin HT.initialize_markers (contents, markers); loop exit when not HT.next_line_present (contents, markers); exit when linenum = result_range'Last; linenum := linenum + 1; declare line : constant String := HT.extract_line (contents, markers); begin case linenum is when 0 => null; -- impossible when 1 => TIO.Put_Line (log_handle, split_collection (line, "CONFIGURE_ENV")); when 2 => TIO.Put_Line (log_handle, split_collection (line, "CONFIGURE_ARGS")); when 3 => TIO.Put_Line (log_handle, split_collection (line, "MAKE_ENV")); when 4 => TIO.Put_Line (log_handle, split_collection (line, "MAKE_ARGS")); when 5 => TIO.Put_Line (log_handle, split_collection (line, "PLIST_SUB")); when 6 => TIO.Put_Line (log_handle, split_collection (line, "SUB_LIST")); end case; end; end loop; end dump_port_variables; -------------------------------------------------------------------------------------------- -- log_phase_end -------------------------------------------------------------------------------------------- procedure log_phase_end (log_handle : TIO.File_Type) is begin TIO.Put_Line (log_handle, "" & LAT.LF); end log_phase_end; -------------------------------------------------------------------------------------------- -- log_phase_begin -------------------------------------------------------------------------------------------- procedure log_phase_begin (log_handle : TIO.File_Type; phase : String) is hyphens : constant String := (1 .. 80 => '-'); middle : constant String := "-- Phase: " & phase; begin TIO.Put_Line (log_handle, LAT.LF & hyphens & LAT.LF & middle & LAT.LF & hyphens); end log_phase_begin; -------------------------------------------------------------------------------------------- -- finalize_log -------------------------------------------------------------------------------------------- procedure finalize_log (log_handle : in out TIO.File_Type; head_time : CAL.Time; tail_time : out CAL.Time) is begin TIO.Put_Line (log_handle, log_section ("Termination")); tail_time := CAL.Clock; TIO.Put_Line (log_handle, "Finished: " & timestamp (tail_time)); TIO.Put_Line (log_handle, log_duration (start => head_time, stop => tail_time)); TIO.Close (log_handle); end finalize_log; -------------------------------------------------------------------------------------------- -- initialize_log -------------------------------------------------------------------------------------------- function initialize_log (log_handle : in out TIO.File_Type; head_time : out CAL.Time; seq_id : port_id; slave_root : String; UNAME : String; BENV : String; COPTS : String; PTVAR : String; block_dog : Boolean) return Boolean is H_ENV : constant String := "Environment"; H_OPT : constant String := "Options"; CFG1 : constant String := "/etc/make.conf"; CFG2 : constant String := "/etc/mk.conf"; begin head_time := CAL.Clock; declare log_path : constant String := log_name (seq_id); begin if DIR.Exists (log_path) then DIR.Delete_File (log_path); end if; FOP.mkdirp_from_filename (log_path); TIO.Create (File => log_handle, Mode => TIO.Out_File, Name => log_path); exception when error : others => raise scan_log_error with "failed to create log " & log_path; end; TIO.Put_Line (log_handle, "=> Building " & get_port_variant (all_ports (seq_id)) & " (version " & HT.USS (all_ports (seq_id).pkgversion) & ")"); TIO.Put_Line (log_handle, "Started : " & timestamp (head_time)); TIO.Put (log_handle, "Platform: " & UNAME); if block_dog then TIO.Put (log_handle, "Watchdog: Disabled"); end if; if BENV = discerr then TIO.Put_Line (log_handle, LAT.LF & "Environment definition failed, " & "aborting entire build"); return False; end if; TIO.Put_Line (log_handle, LAT.LF & log_section (H_ENV)); TIO.Put (log_handle, BENV); TIO.Put_Line (log_handle, "" & LAT.LF); TIO.Put_Line (log_handle, log_section (H_OPT)); TIO.Put (log_handle, COPTS); TIO.Put_Line (log_handle, "" & LAT.LF); dump_port_variables (log_handle, PTVAR); TIO.Put_Line (log_handle, log_section (CFG1)); TIO.Put (log_handle, FOP.get_file_contents (slave_root & CFG1)); TIO.Put_Line (log_handle, "" & LAT.LF); return True; end initialize_log; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_scan_start_time (mark : CAL.Time) is begin scan_start := mark; end set_scan_start_time; -------------------------------------------------------------------------------------------- -- set_scan_complete -------------------------------------------------------------------------------------------- procedure set_scan_complete (mark : CAL.Time) is begin scan_stop := mark; end set_scan_complete; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_overall_start_time (mark : CAL.Time) is begin start_time := mark; end set_overall_start_time; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_overall_complete (mark : CAL.Time) is begin stop_time := mark; end set_overall_complete; -------------------------------------------------------------------------------------------- -- start_logging -------------------------------------------------------------------------------------------- procedure start_logging (flavor : count_type) is logpath : String := HT.USS (PM.configuration.dir_logs) & "/logs/" & logname (flavor); begin if DIR.Exists (logpath) then DIR.Delete_File (logpath); end if; TIO.Create (File => Flog (flavor), Mode => TIO.Out_File, Name => logpath); if flavor = total then TIO.Put_Line (Flog (total), "-=> Chronology of last build <=-" & LAT.LF & "Started: " & timestamp (start_time) & LAT.LF & "Ports to build: " & HT.int2str (original_queue_size) & LAT.LF & LAT.LF & "Purging any ignored/broken ports first ..."); TIO.Flush (Flog (total)); end if; exception when others => raise overall_log with "Failed to create " & logpath & bailing; end start_logging; -------------------------------------------------------------------------------------------- -- stop_logging -------------------------------------------------------------------------------------------- procedure stop_logging (flavor : count_type) is begin if flavor = total then TIO.Put_Line (Flog (flavor), "Finished: " & timestamp (stop_time)); TIO.Put_Line (Flog (flavor), log_duration (start => start_time, stop => stop_time)); TIO.Put_Line (Flog (flavor), LAT.LF & "---------------------------" & LAT.LF & "-- Final Statistics" & LAT.LF & "---------------------------" & LAT.LF & " Initial queue size:" & bld_counter (total)'Img & LAT.LF & " ports built:" & bld_counter (success)'Img & LAT.LF & " ignored:" & bld_counter (ignored)'Img & LAT.LF & " skipped:" & bld_counter (skipped)'Img & LAT.LF & " failed:" & bld_counter (failure)'Img); end if; TIO.Close (Flog (flavor)); end stop_logging; -------------------------------------------------------------------------------------------- -- scribe -------------------------------------------------------------------------------------------- procedure scribe (flavor : count_type; line : String; flush_after : Boolean) is begin TIO.Put_Line (Flog (flavor), line); if flush_after then TIO.Flush (Flog (flavor)); end if; end scribe; -------------------------------------------------------------------------------------------- -- flush_log -------------------------------------------------------------------------------------------- procedure flush_log (flavor : count_type) is begin TIO.Flush (Flog (flavor)); end flush_log; -------------------------------------------------------------------------------------------- -- set_build_counters -------------------------------------------------------------------------------------------- procedure set_build_counters (A, B, C, D, E : Natural) is begin bld_counter := (A, B, C, D, E); end set_build_counters; -------------------------------------------------------------------------------------------- -- increment_build_counter -------------------------------------------------------------------------------------------- procedure increment_build_counter (flavor : count_type; quantity : Natural := 1) is begin bld_counter (flavor) := bld_counter (flavor) + quantity; end increment_build_counter; -------------------------------------------------------------------------------------------- -- start_obsolete_package_logging -------------------------------------------------------------------------------------------- procedure start_obsolete_package_logging is logpath : constant String := HT.USS (PM.configuration.dir_logs) & "/logs/06_obsolete_packages.log"; begin if DIR.Exists (logpath) then DIR.Delete_File (logpath); end if; TIO.Create (File => obsolete_pkg_log, Mode => TIO.Out_File, Name => logpath); obsolete_log_open := True; exception when others => obsolete_log_open := False; end start_obsolete_package_logging; -------------------------------------------------------------------------------------------- -- stop_obsolete_package_logging -------------------------------------------------------------------------------------------- procedure stop_obsolete_package_logging is begin TIO.Close (obsolete_pkg_log); end stop_obsolete_package_logging; -------------------------------------------------------------------------------------------- -- obsolete_notice -------------------------------------------------------------------------------------------- procedure obsolete_notice (message : String; write_to_screen : Boolean) is begin if obsolete_log_open then TIO.Put_Line (obsolete_pkg_log, message); end if; if write_to_screen then TIO.Put_Line (message); end if; end obsolete_notice; -------------------------------------------------------------------------------------------- -- www_timestamp_start_time -------------------------------------------------------------------------------------------- function www_timestamp_start_time return String is begin return timestamp (start_time, True); end www_timestamp_start_time; -------------------------------------------------------------------------------------------- -- ports_remaining_to_build -------------------------------------------------------------------------------------------- function ports_remaining_to_build return Integer is begin return bld_counter (total) - bld_counter (success) - bld_counter (failure) - bld_counter (ignored) - bld_counter (skipped); end ports_remaining_to_build; -------------------------------------------------------------------------------------------- -- port_counter_value -------------------------------------------------------------------------------------------- function port_counter_value (flavor : count_type) return Integer is begin return bld_counter (flavor); end port_counter_value; -------------------------------------------------------------------------------------------- -- hourly_build_rate -------------------------------------------------------------------------------------------- function hourly_build_rate return Natural is pkg_that_count : constant Natural := bld_counter (success) + bld_counter (failure); begin return get_packages_per_hour (pkg_that_count, start_time); end hourly_build_rate; -------------------------------------------------------------------------------------------- -- get_packages_per_hour -------------------------------------------------------------------------------------------- function get_packages_per_hour (packages_done : Natural; from_when : CAL.Time) return Natural is diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; result : Natural; rightnow : CAL.Time := CAL.Clock; work_seconds : Integer; work_days : Integer; use type CAR.Day_Count; begin if packages_done = 0 then return 0; end if; CAR.Difference (Left => rightnow, Right => from_when, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); work_seconds := Integer (diff_secs); work_days := Integer (diff_days); work_seconds := work_seconds + (work_days * 3600 * 24); if work_seconds < 0 then -- should be impossible to get here. return 0; end if; result := packages_done * 3600; result := result / work_seconds; return result; exception when others => return 0; end get_packages_per_hour; -------------------------------------------------------------------------------------------- -- impulse_rate -------------------------------------------------------------------------------------------- function impulse_rate return Natural is pkg_that_count : constant Natural := bld_counter (success) + bld_counter (failure); pkg_diff : Natural; result : Natural; begin if impulse_counter = impulse_range'Last then impulse_counter := impulse_range'First; else impulse_counter := impulse_counter + 1; end if; if impulse_data (impulse_counter).virgin then impulse_data (impulse_counter).hack := CAL.Clock; impulse_data (impulse_counter).packages := pkg_that_count; impulse_data (impulse_counter).virgin := False; return get_packages_per_hour (pkg_that_count, start_time); end if; pkg_diff := pkg_that_count - impulse_data (impulse_counter).packages; result := get_packages_per_hour (packages_done => pkg_diff, from_when => impulse_data (impulse_counter).hack); impulse_data (impulse_counter).hack := CAL.Clock; impulse_data (impulse_counter).packages := pkg_that_count; return result; exception when others => return 0; end impulse_rate; end PortScan.Log;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- R T S F I N D -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Casing; use Casing; with Csets; use Csets; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Fname; use Fname; with Fname.UF; use Fname.UF; with Lib; use Lib; with Lib.Load; use Lib.Load; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Output; use Output; with Opt; use Opt; with Restrict; use Restrict; with Sem; use Sem; with Sem_Ch7; use Sem_Ch7; with Sem_Dist; use Sem_Dist; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Stand; use Stand; with Snames; use Snames; with Tbuild; use Tbuild; with Uname; use Uname; package body Rtsfind is RTE_Available_Call : Boolean := False; -- Set True during call to RTE from RTE_Available. Tells RTE to set -- RTE_Is_Available to False rather than generating an error message. RTE_Is_Available : Boolean; -- Set True by RTE_Available on entry. When RTE_Available_Call is set -- True, set False if RTE would otherwise generate an error message. ---------------- -- Unit table -- ---------------- -- The unit table has one entry for each unit included in the definition -- of the type RTU_Id in the spec. The table entries are initialized in -- Initialize to set the Entity field to Empty, indicating that the -- corresponding unit has not yet been loaded. The fields are set when -- a unit is loaded to contain the defining entity for the unit, the -- unit name, and the unit number. -- Note that a unit can be loaded either by a call to find an entity -- within the unit (e.g. RTE), or by an explicit with of the unit. In -- the latter case it is critical to make a call to Set_RTU_Loaded to -- ensure that the entry in this table reflects the load. type RT_Unit_Table_Record is record Entity : Entity_Id; Uname : Unit_Name_Type; Unum : Unit_Number_Type; Withed : Boolean; end record; RT_Unit_Table : array (RTU_Id) of RT_Unit_Table_Record; -------------------------- -- Runtime Entity Table -- -------------------------- -- There is one entry in the runtime entity table for each entity that is -- included in the definition of the RE_Id type in the spec. The entries -- are set by Initialize_Rtsfind to contain Empty, indicating that the -- entity has not yet been located. Once the entity is located for the -- first time, its ID is stored in this array, so that subsequent calls -- for the same entity can be satisfied immediately. RE_Table : array (RE_Id) of Entity_Id; -------------------------- -- Generation of WITH's -- -------------------------- -- When a unit is implicitly loaded as a result of a call to RTE, it -- is necessary to create an implicit WITH to ensure that the object -- is correctly loaded by the binder. Such WITH statements are only -- required when the request is from the extended main unit (if a -- client needs a WITH, that will be taken care of when the client -- is compiled). -- We always attach the WITH to the main unit. This is not perfectly -- accurate in terms of elaboration requirements, but it is close -- enough, since the units that are accessed using rtsfind do not -- have delicate elaboration requirements. -- The flag Withed in the unit table record is initially set to False. -- It is set True if a WITH has been generated for the main unit for -- the corresponding unit. ----------------------- -- Local Subprograms -- ----------------------- procedure Entity_Not_Defined (Id : RE_Id); -- Outputs error messages for an entity that is not defined in the -- run-time library (the form of the error message is tailored for -- no run time/configurable run time mode as required). procedure Load_Fail (S : String; U_Id : RTU_Id; Id : RE_Id); -- Internal procedure called if we can't sucessfully locate or -- process a run-time unit. The parameters give information about -- the error message to be given. S is a reason for failing to -- compile the file and U_Id is the unit id. RE_Id is the RE_Id -- originally passed to RTE. The message in S is one of the -- following: -- -- "not found" -- "had parser errors" -- "had semantic errors" -- -- The "not found" case is treated specially in that it is considered -- a normal situation in configurable run-time mode (and the message in -- this case is suppressed unless we are operating in All_Errors_Mode). function Get_Unit_Name (U_Id : RTU_Id) return Unit_Name_Type; -- Retrieves the Unit Name given a unit id represented by its -- enumeration value in RTU_Id. procedure Load_RTU (U_Id : RTU_Id; Id : RE_Id := RE_Null; Use_Setting : Boolean := False); -- Load the unit whose Id is given if not already loaded. The unit is -- loaded, analyzed, and added to the WITH list, and the entry in -- RT_Unit_Table is updated to reflect the load. Use_Setting is used -- to indicate the initial setting for the Is_Potentially_Use_Visible -- flag of the entity for the loaded unit (if it is indeed loaded). -- A value of False means nothing special need be done. A value of -- True indicates that this flag must be set to True. It is needed -- only in the Text_IO_Kludge procedure, which may materialize an -- entity of Text_IO (or [Wide_]Wide_Text_IO) that was previously unknown. -- Id is the RE_Id value of the entity which was originally requested. -- Id is used only for error message detail, and if it is RE_Null, then -- the attempt to output the entity name is ignored. procedure Output_Entity_Name (Id : RE_Id; Msg : String); -- Output continuation error message giving qualified name of entity -- corresponding to Id, appending the string given by Msg. This call -- is only effective in All_Errors mode. function RE_Chars (E : RE_Id) return Name_Id; -- Given a RE_Id value returns the Chars of the corresponding entity procedure RTE_Error_Msg (Msg : String); -- Generates a message by calling Error_Msg_N specifying Current_Error_Node -- as the node location using the given Msg text. Special processing in the -- case where RTE_Available_Call is set. In this case, no message is output -- and instead RTE_Is_Available is set to False. Note that this can only be -- used if you are sure that the message comes directly or indirectly from -- a call to the RTE function. ------------------------ -- Entity_Not_Defined -- ------------------------ procedure Entity_Not_Defined (Id : RE_Id) is begin if No_Run_Time_Mode then -- If the error occurs when compiling the body of a predefined -- unit for inlining purposes, the body must be illegal in this -- mode, and there is no point in continuing. if Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Sloc (Current_Error_Node)))) then Error_Msg_N ("construct not allowed in no run time mode!", Current_Error_Node); raise Unrecoverable_Error; else RTE_Error_Msg ("|construct not allowed in no run time mode"); end if; elsif Configurable_Run_Time_Mode then RTE_Error_Msg ("|construct not allowed in this configuration>"); else RTE_Error_Msg ("run-time configuration error"); end if; Output_Entity_Name (Id, "not defined"); end Entity_Not_Defined; ------------------- -- Get_Unit_Name -- ------------------- function Get_Unit_Name (U_Id : RTU_Id) return Unit_Name_Type is Uname_Chars : constant String := RTU_Id'Image (U_Id); begin Name_Len := Uname_Chars'Length; Name_Buffer (1 .. Name_Len) := Uname_Chars; Set_Casing (All_Lower_Case); if U_Id in Ada_Child then Name_Buffer (4) := '.'; if U_Id in Ada_Calendar_Child then Name_Buffer (13) := '.'; elsif U_Id in Ada_Finalization_Child then Name_Buffer (17) := '.'; elsif U_Id in Ada_Interrupts_Child then Name_Buffer (15) := '.'; elsif U_Id in Ada_Real_Time_Child then Name_Buffer (14) := '.'; elsif U_Id in Ada_Streams_Child then Name_Buffer (12) := '.'; elsif U_Id in Ada_Text_IO_Child then Name_Buffer (12) := '.'; elsif U_Id in Ada_Wide_Text_IO_Child then Name_Buffer (17) := '.'; elsif U_Id in Ada_Wide_Wide_Text_IO_Child then Name_Buffer (22) := '.'; end if; elsif U_Id in Interfaces_Child then Name_Buffer (11) := '.'; elsif U_Id in System_Child then Name_Buffer (7) := '.'; if U_Id in System_Tasking_Child then Name_Buffer (15) := '.'; end if; if U_Id in System_Tasking_Restricted_Child then Name_Buffer (26) := '.'; end if; if U_Id in System_Tasking_Protected_Objects_Child then Name_Buffer (33) := '.'; end if; if U_Id in System_Tasking_Async_Delays_Child then Name_Buffer (28) := '.'; end if; end if; -- Add %s at end for spec Name_Buffer (Name_Len + 1) := '%'; Name_Buffer (Name_Len + 2) := 's'; Name_Len := Name_Len + 2; return Name_Find; end Get_Unit_Name; ---------------- -- Initialize -- ---------------- procedure Initialize is begin -- Initialize the unit table for J in RTU_Id loop RT_Unit_Table (J).Entity := Empty; end loop; for J in RE_Id loop RE_Table (J) := Empty; end loop; RTE_Is_Available := False; end Initialize; ------------ -- Is_RTE -- ------------ function Is_RTE (Ent : Entity_Id; E : RE_Id) return Boolean is E_Unit_Name : Unit_Name_Type; Ent_Unit_Name : Unit_Name_Type; S : Entity_Id; E1 : Entity_Id; E2 : Entity_Id; begin if No (Ent) then return False; -- If E has already a corresponding entity, check it directly, -- going to full views if they exist to deal with the incomplete -- and private type cases properly. elsif Present (RE_Table (E)) then E1 := Ent; if Is_Type (E1) and then Present (Full_View (E1)) then E1 := Full_View (E1); end if; E2 := RE_Table (E); if Is_Type (E2) and then Present (Full_View (E2)) then E2 := Full_View (E2); end if; return E1 = E2; end if; -- If the unit containing E is not loaded, we already know that -- the entity we have cannot have come from this unit. E_Unit_Name := Get_Unit_Name (RE_Unit_Table (E)); if not Is_Loaded (E_Unit_Name) then return False; end if; -- Here the unit containing the entity is loaded. We have not made -- an explicit call to RTE to get the entity in question, but we may -- have obtained a reference to it indirectly from some other entity -- in the same unit, or some other unit that references it. -- Get the defining unit of the entity S := Scope (Ent); if Ekind (S) /= E_Package then return False; end if; Ent_Unit_Name := Get_Unit_Name (Unit_Declaration_Node (S)); -- If the defining unit of the entity we are testing is not the -- unit containing E, then they cannot possibly match. if Ent_Unit_Name /= E_Unit_Name then return False; end if; -- If the units match, then compare the names (remember that no -- overloading is permitted in entities fetched using Rtsfind). if RE_Chars (E) = Chars (Ent) then RE_Table (E) := Ent; -- If front-end inlining is enabled, we may be within a body that -- contains inlined functions, which has not been retrieved through -- rtsfind, and therefore is not yet recorded in the RT_Unit_Table. -- Add the unit information now, it must be fully available. declare U : RT_Unit_Table_Record renames RT_Unit_Table (RE_Unit_Table (E)); begin if No (U.Entity) then U.Entity := S; U.Uname := E_Unit_Name; U.Unum := Get_Source_Unit (S); end if; end; return True; else return False; end if; end Is_RTE; ------------ -- Is_RTU -- ------------ function Is_RTU (Ent : Entity_Id; U : RTU_Id) return Boolean is E : constant Entity_Id := RT_Unit_Table (U).Entity; begin return Present (E) and then E = Ent; end Is_RTU; ---------------------------- -- Is_Text_IO_Kludge_Unit -- ---------------------------- function Is_Text_IO_Kludge_Unit (Nam : Node_Id) return Boolean is Prf : Node_Id; Sel : Node_Id; begin if Nkind (Nam) /= N_Expanded_Name then return False; end if; Prf := Prefix (Nam); Sel := Selector_Name (Nam); if Nkind (Sel) /= N_Expanded_Name or else Nkind (Prf) /= N_Identifier or else Chars (Prf) /= Name_Ada then return False; end if; Prf := Prefix (Sel); Sel := Selector_Name (Sel); return Nkind (Prf) = N_Identifier and then (Chars (Prf) = Name_Text_IO or else Chars (Prf) = Name_Wide_Text_IO or else Chars (Prf) = Name_Wide_Wide_Text_IO) and then Nkind (Sel) = N_Identifier and then Chars (Sel) in Text_IO_Package_Name; end Is_Text_IO_Kludge_Unit; --------------- -- Load_Fail -- --------------- procedure Load_Fail (S : String; U_Id : RTU_Id; Id : RE_Id) is M : String (1 .. 100); P : Natural := 0; begin -- Output header message if Configurable_Run_Time_Mode then RTE_Error_Msg ("construct not allowed in configurable run-time mode"); else RTE_Error_Msg ("run-time library configuration error"); end if; -- Output file name and reason string if S /= "not found" or else not Configurable_Run_Time_Mode or else All_Errors_Mode then M (1 .. 6) := "\file "; P := 6; Get_Name_String (Get_File_Name (RT_Unit_Table (U_Id).Uname, Subunit => False)); M (P + 1 .. P + Name_Len) := Name_Buffer (1 .. Name_Len); P := P + Name_Len; M (P + 1) := ' '; P := P + 1; M (P + 1 .. P + S'Length) := S; P := P + S'Length; RTE_Error_Msg (M (1 .. P)); -- Output entity name Output_Entity_Name (Id, "not available"); end if; raise RE_Not_Available; end Load_Fail; -------------- -- Load_RTU -- -------------- procedure Load_RTU (U_Id : RTU_Id; Id : RE_Id := RE_Null; Use_Setting : Boolean := False) is U : RT_Unit_Table_Record renames RT_Unit_Table (U_Id); Priv_Par : constant Elist_Id := New_Elmt_List; Lib_Unit : Node_Id; procedure Save_Private_Visibility; -- If the current unit is the body of child unit or the spec of a -- private child unit, the private declarations of the parent (s) -- are visible. If the unit to be loaded is another public sibling, -- its compilation will affect the visibility of the common ancestors. -- Indicate those that must be restored. procedure Restore_Private_Visibility; -- Restore the visibility of ancestors after compiling RTU -------------------------------- -- Restore_Private_Visibility -- -------------------------------- procedure Restore_Private_Visibility is E_Par : Elmt_Id; begin E_Par := First_Elmt (Priv_Par); while Present (E_Par) loop if not In_Private_Part (Node (E_Par)) then Install_Private_Declarations (Node (E_Par)); end if; Next_Elmt (E_Par); end loop; end Restore_Private_Visibility; ----------------------------- -- Save_Private_Visibility -- ----------------------------- procedure Save_Private_Visibility is Par : Entity_Id; begin Par := Scope (Current_Scope); while Present (Par) and then Par /= Standard_Standard loop if Ekind (Par) = E_Package and then Is_Compilation_Unit (Par) and then In_Private_Part (Par) then Append_Elmt (Par, Priv_Par); end if; Par := Scope (Par); end loop; end Save_Private_Visibility; -- Start of processing for Load_RTU begin -- Nothing to do if unit is already loaded if Present (U.Entity) then return; end if; -- Note if secondary stack is used if U_Id = System_Secondary_Stack then Opt.Sec_Stack_Used := True; end if; -- Otherwise we need to load the unit, First build unit name -- from the enumeration literal name in type RTU_Id. U.Uname := Get_Unit_Name (U_Id); U.Withed := False; declare Loaded : Boolean; pragma Warnings (Off, Loaded); begin Loaded := Is_Loaded (U.Uname); end; -- Now do the load call, note that setting Error_Node to Empty is -- a signal to Load_Unit that we will regard a failure to find the -- file as a fatal error, and that it should not output any kind -- of diagnostics, since we will take care of it here. U.Unum := Load_Unit (Load_Name => U.Uname, Required => False, Subunit => False, Error_Node => Empty); if U.Unum = No_Unit then Load_Fail ("not found", U_Id, Id); elsif Fatal_Error (U.Unum) then Load_Fail ("had parser errors", U_Id, Id); end if; -- Make sure that the unit is analyzed declare Was_Analyzed : constant Boolean := Analyzed (Cunit (Current_Sem_Unit)); begin -- Pretend that the current unit is analyzed, in case it is System -- or some such. This allows us to put some declarations, such as -- exceptions and packed arrays of Boolean, into System even though -- expanding them requires System... -- This is a bit odd but works fine. If the RTS unit does not depend -- in any way on the current unit, then it never gets back into the -- current unit's tree, and the change we make to the current unit -- tree is never noticed by anyone (it is undone in a moment). That -- is the normal situation. -- If the RTS Unit *does* depend on the current unit, for instance, -- when you are compiling System, then you had better have finished -- analyzing the part of System that is depended on before you try -- to load the RTS Unit. This means having the System ordered in an -- appropriate manner. Set_Analyzed (Cunit (Current_Sem_Unit), True); if not Analyzed (Cunit (U.Unum)) then Save_Private_Visibility; Semantics (Cunit (U.Unum)); Restore_Private_Visibility; if Fatal_Error (U.Unum) then Load_Fail ("had semantic errors", U_Id, Id); end if; end if; -- Undo the pretence Set_Analyzed (Cunit (Current_Sem_Unit), Was_Analyzed); end; Lib_Unit := Unit (Cunit (U.Unum)); U.Entity := Defining_Entity (Lib_Unit); if Use_Setting then Set_Is_Potentially_Use_Visible (U.Entity, True); end if; end Load_RTU; ----------------------- -- Output_Entity_Name -- ------------------------ procedure Output_Entity_Name (Id : RE_Id; Msg : String) is M : String (1 .. 2048); P : Natural := 0; -- M (1 .. P) is current message to be output RE_Image : constant String := RE_Id'Image (Id); begin if Id = RE_Null or else not All_Errors_Mode then return; end if; M (1 .. 9) := "\entity """; P := 9; -- Add unit name to message, excluding %s or %b at end Get_Name_String (Get_Unit_Name (RE_Unit_Table (Id))); Name_Len := Name_Len - 2; Set_Casing (Mixed_Case); M (P + 1 .. P + Name_Len) := Name_Buffer (1 .. Name_Len); P := P + Name_Len; -- Add a qualifying period M (P + 1) := '.'; P := P + 1; -- Add entity name and closing quote to message Name_Len := RE_Image'Length - 3; Name_Buffer (1 .. Name_Len) := RE_Image (4 .. RE_Image'Length); Set_Casing (Mixed_Case); M (P + 1 .. P + Name_Len) := Name_Buffer (1 .. Name_Len); P := P + Name_Len; M (P + 1) := '"'; P := P + 1; -- Add message M (P + 1) := ' '; P := P + 1; M (P + 1 .. P + Msg'Length) := Msg; P := P + Msg'Length; -- Output message at current error node location RTE_Error_Msg (M (1 .. P)); end Output_Entity_Name; -------------- -- RE_Chars -- -------------- function RE_Chars (E : RE_Id) return Name_Id is RE_Name_Chars : constant String := RE_Id'Image (E); begin -- Copy name skipping initial RE_ or RO_XX characters if RE_Name_Chars (1 .. 2) = "RE" then for J in 4 .. RE_Name_Chars'Last loop Name_Buffer (J - 3) := Fold_Lower (RE_Name_Chars (J)); end loop; Name_Len := RE_Name_Chars'Length - 3; else for J in 7 .. RE_Name_Chars'Last loop Name_Buffer (J - 6) := Fold_Lower (RE_Name_Chars (J)); end loop; Name_Len := RE_Name_Chars'Length - 6; end if; return Name_Find; end RE_Chars; --------- -- RTE -- --------- function RTE (E : RE_Id) return Entity_Id is U_Id : constant RTU_Id := RE_Unit_Table (E); U : RT_Unit_Table_Record renames RT_Unit_Table (U_Id); Lib_Unit : Node_Id; Pkg_Ent : Entity_Id; Ename : Name_Id; -- The following flag is used to disable front-end inlining when RTE -- is invoked. This prevents the analysis of other runtime bodies when -- a particular spec is loaded through Rtsfind. This is both efficient, -- and it prevents spurious visibility conflicts between use-visible -- user entities, and entities in run-time packages. -- In configurable run-time mode, subprograms marked Inlined_Always must -- be inlined, so in the case we retain the Front_End_Inlining mode. Save_Front_End_Inlining : Boolean; function Check_CRT (Eid : Entity_Id) return Entity_Id; -- Check entity Eid to ensure that configurable run-time restrictions -- are met. May generate an error message and raise RE_Not_Available -- if the entity E does not exist (i.e. Eid is Empty) procedure Check_RPC; -- Reject programs that make use of distribution features not supported -- on the current target. On such targets (VMS, Vxworks, others?) we -- only provide a minimal body for System.Rpc that only supplies an -- implementation of partition_id. function Find_Local_Entity (E : RE_Id) return Entity_Id; -- This function is used when entity E is in this compilation's main -- unit. It gets the value from the already compiled declaration. function Make_Unit_Name (N : Node_Id) return Node_Id; -- If the unit is a child unit, build fully qualified name for use -- in With_Clause. --------------- -- Check_CRT -- --------------- function Check_CRT (Eid : Entity_Id) return Entity_Id is begin if No (Eid) then Entity_Not_Defined (E); raise RE_Not_Available; -- Entity is available else -- If in No_Run_Time mode and entity is not in one of the -- specially permitted units, raise the exception. if No_Run_Time_Mode and then not OK_No_Run_Time_Unit (U_Id) then Entity_Not_Defined (E); raise RE_Not_Available; end if; -- Otherwise entity is accessible return Eid; end if; end Check_CRT; --------------- -- Check_RPC -- --------------- procedure Check_RPC is begin -- Bypass this check if debug flag -gnatdR set if Debug_Flag_RR then return; end if; -- Otherwise we need the check if we are going after one of -- the critical entities in System.RPC in stubs mode. -- ??? Should we do this for other s-parint/s-polint entities -- too? if (Distribution_Stub_Mode = Generate_Receiver_Stub_Body or else Distribution_Stub_Mode = Generate_Caller_Stub_Body) and then (E = RE_Do_Rpc or else E = RE_Do_Apc or else E = RE_Params_Stream_Type or else E = RE_Request_Access) and then Get_PCS_Name = Name_No_DSA then Set_Standard_Error; Write_Str ("distribution feature not supported"); Write_Eol; raise Unrecoverable_Error; end if; end Check_RPC; ------------------------ -- Find_System_Entity -- ------------------------ function Find_Local_Entity (E : RE_Id) return Entity_Id is RE_Str : String renames RE_Id'Image (E); Ent : Entity_Id; Save_Nam : constant String := Name_Buffer (1 .. Name_Len); -- Save name buffer and length over call begin Name_Len := Natural'Max (0, RE_Str'Length - 3); Name_Buffer (1 .. Name_Len) := RE_Str (RE_Str'First + 3 .. RE_Str'Last); Ent := Entity_Id (Get_Name_Table_Info (Name_Find)); Name_Len := Save_Nam'Length; Name_Buffer (1 .. Name_Len) := Save_Nam; return Ent; end Find_Local_Entity; -------------------- -- Make_Unit_Name -- -------------------- function Make_Unit_Name (N : Node_Id) return Node_Id is Nam : Node_Id; Scop : Entity_Id; begin Nam := New_Reference_To (U.Entity, Standard_Location); Scop := Scope (U.Entity); if Nkind (N) = N_Defining_Program_Unit_Name then while Scop /= Standard_Standard loop Nam := Make_Expanded_Name (Standard_Location, Chars => Chars (U.Entity), Prefix => New_Reference_To (Scop, Standard_Location), Selector_Name => Nam); Set_Entity (Nam, U.Entity); Scop := Scope (Scop); end loop; end if; return Nam; end Make_Unit_Name; -- Start of processing for RTE begin -- Doing a rtsfind in system.ads is special, as we cannot do this -- when compiling System itself. So if we are compiling system then -- we should already have acquired and processed the declaration -- of the entity. The test is to see if this compilation's main unit -- is System. If so, return the value from the already compiled -- declaration and otherwise do a regular find. -- Not pleasant, but these kinds of annoying recursion when -- writing an Ada compiler in Ada have to be broken somewhere! if Present (Main_Unit_Entity) and then Chars (Main_Unit_Entity) = Name_System and then Analyzed (Main_Unit_Entity) and then not Is_Child_Unit (Main_Unit_Entity) then return Check_CRT (Find_Local_Entity (E)); end if; Save_Front_End_Inlining := Front_End_Inlining; Front_End_Inlining := Configurable_Run_Time_Mode; -- Load unit if unit not previously loaded if No (RE_Table (E)) then Load_RTU (U_Id, Id => E); Lib_Unit := Unit (Cunit (U.Unum)); -- In the subprogram case, we are all done, the entity we want -- is the entity for the subprogram itself. Note that we do not -- bother to check that it is the entity that was requested. -- the only way that could fail to be the case is if runtime is -- hopelessly misconfigured, and it isn't worth testing for this. if Nkind (Lib_Unit) = N_Subprogram_Declaration then RE_Table (E) := U.Entity; -- Otherwise we must have the package case. First check package -- entity itself (e.g. RTE_Name for System.Interrupts.Name) else pragma Assert (Nkind (Lib_Unit) = N_Package_Declaration); Ename := RE_Chars (E); -- First we search the package entity chain Pkg_Ent := First_Entity (U.Entity); while Present (Pkg_Ent) loop if Ename = Chars (Pkg_Ent) then RE_Table (E) := Pkg_Ent; Check_RPC; goto Found; end if; Next_Entity (Pkg_Ent); end loop; -- If we did not find the entity in the package entity chain, -- then check if the package entity itself matches. Note that -- we do this check after searching the entity chain, since -- the rule is that in case of ambiguity, we prefer the entity -- defined within the package, rather than the package itself. if Ename = Chars (U.Entity) then RE_Table (E) := U.Entity; end if; -- If we didn't find the entity we want, something is wrong. -- We just leave RE_Table (E) set to Empty and the appropriate -- action will be taken by Check_CRT when we exit. end if; end if; -- See if we have to generate a WITH for this entity. We generate -- a WITH if the current unit is part of the extended main code -- unit, and if we have not already added the with. The WITH is -- added to the appropriate unit (the current one). We do not need -- to generate a WITH for an ???? <<Found>> if (not U.Withed) and then In_Extended_Main_Code_Unit (Cunit_Entity (Current_Sem_Unit)) and then not RTE_Available_Call then U.Withed := True; declare Withn : Node_Id; Lib_Unit : Node_Id; begin Lib_Unit := Unit (Cunit (U.Unum)); Withn := Make_With_Clause (Standard_Location, Name => Make_Unit_Name (Defining_Unit_Name (Specification (Lib_Unit)))); Set_Library_Unit (Withn, Cunit (U.Unum)); Set_Corresponding_Spec (Withn, U.Entity); Set_First_Name (Withn, True); Set_Implicit_With (Withn, True); Mark_Rewrite_Insertion (Withn); Append (Withn, Context_Items (Cunit (Current_Sem_Unit))); Check_Restriction_No_Dependence (Name (Withn), Current_Error_Node); end; end if; Front_End_Inlining := Save_Front_End_Inlining; return Check_CRT (RE_Table (E)); end RTE; ------------------- -- RTE_Available -- ------------------- function RTE_Available (E : RE_Id) return Boolean is Dummy : Entity_Id; pragma Warnings (Off, Dummy); Result : Boolean; Save_RTE_Available_Call : constant Boolean := RTE_Available_Call; Save_RTE_Is_Available : constant Boolean := RTE_Is_Available; -- These are saved recursively because the call to load a unit -- caused by an upper level call may perform a recursive call -- to this routine during analysis of the corresponding unit. begin RTE_Available_Call := True; RTE_Is_Available := True; Dummy := RTE (E); Result := RTE_Is_Available; RTE_Available_Call := Save_RTE_Available_Call; RTE_Is_Available := Save_RTE_Is_Available; return Result; exception when RE_Not_Available => RTE_Available_Call := Save_RTE_Available_Call; RTE_Is_Available := Save_RTE_Is_Available; return False; end RTE_Available; ------------------- -- RTE_Error_Msg -- ------------------- procedure RTE_Error_Msg (Msg : String) is begin if RTE_Available_Call then RTE_Is_Available := False; else Error_Msg_N (Msg, Current_Error_Node); -- Bump count of violations if we are in configurable run-time -- mode and this is not a continuation message. -- LLVM local if Configurable_Run_Time_Mode and then Msg (Msg'First) /= '\' then Configurable_Run_Time_Violations := Configurable_Run_Time_Violations + 1; end if; end if; end RTE_Error_Msg; ---------------- -- RTU_Loaded -- ---------------- function RTU_Loaded (U : RTU_Id) return Boolean is begin return Present (RT_Unit_Table (U).Entity); end RTU_Loaded; -------------------- -- Set_RTU_Loaded -- -------------------- procedure Set_RTU_Loaded (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Unum : constant Unit_Number_Type := Get_Source_Unit (Loc); Uname : constant Unit_Name_Type := Unit_Name (Unum); E : constant Entity_Id := Defining_Entity (Unit (Cunit (Unum))); begin pragma Assert (Is_Predefined_File_Name (Unit_File_Name (Unum))); -- Loop through entries in RTU table looking for matching entry for U_Id in RTU_Id'Range loop -- Here we have a match if Get_Unit_Name (U_Id) = Uname then declare U : RT_Unit_Table_Record renames RT_Unit_Table (U_Id); -- The RT_Unit_Table entry that may need updating begin -- If entry is not set, set it now if No (U.Entity) then U.Entity := E; U.Uname := Get_Unit_Name (U_Id); U.Unum := Unum; U.Withed := False; end if; return; end; end if; end loop; end Set_RTU_Loaded; -------------------- -- Text_IO_Kludge -- -------------------- procedure Text_IO_Kludge (Nam : Node_Id) is Chrs : Name_Id; type Name_Map_Type is array (Text_IO_Package_Name) of RTU_Id; Name_Map : constant Name_Map_Type := Name_Map_Type'( Name_Decimal_IO => Ada_Text_IO_Decimal_IO, Name_Enumeration_IO => Ada_Text_IO_Enumeration_IO, Name_Fixed_IO => Ada_Text_IO_Fixed_IO, Name_Float_IO => Ada_Text_IO_Float_IO, Name_Integer_IO => Ada_Text_IO_Integer_IO, Name_Modular_IO => Ada_Text_IO_Modular_IO); Wide_Name_Map : constant Name_Map_Type := Name_Map_Type'( Name_Decimal_IO => Ada_Wide_Text_IO_Decimal_IO, Name_Enumeration_IO => Ada_Wide_Text_IO_Enumeration_IO, Name_Fixed_IO => Ada_Wide_Text_IO_Fixed_IO, Name_Float_IO => Ada_Wide_Text_IO_Float_IO, Name_Integer_IO => Ada_Wide_Text_IO_Integer_IO, Name_Modular_IO => Ada_Wide_Text_IO_Modular_IO); Wide_Wide_Name_Map : constant Name_Map_Type := Name_Map_Type'( Name_Decimal_IO => Ada_Wide_Wide_Text_IO_Decimal_IO, Name_Enumeration_IO => Ada_Wide_Wide_Text_IO_Enumeration_IO, Name_Fixed_IO => Ada_Wide_Wide_Text_IO_Fixed_IO, Name_Float_IO => Ada_Wide_Wide_Text_IO_Float_IO, Name_Integer_IO => Ada_Wide_Wide_Text_IO_Integer_IO, Name_Modular_IO => Ada_Wide_Wide_Text_IO_Modular_IO); begin -- Nothing to do if name is not identifier or a selected component -- whose selector_name is not an identifier. if Nkind (Nam) = N_Identifier then Chrs := Chars (Nam); elsif Nkind (Nam) = N_Selected_Component and then Nkind (Selector_Name (Nam)) = N_Identifier then Chrs := Chars (Selector_Name (Nam)); else return; end if; -- Nothing to do if name is not one of the Text_IO subpackages -- Otherwise look through loaded units, and if we find Text_IO -- or [Wide_]Wide_Text_IO already loaded, then load the proper child. if Chrs in Text_IO_Package_Name then for U in Main_Unit .. Last_Unit loop Get_Name_String (Unit_File_Name (U)); if Name_Len = 12 then -- Here is where we do the loads if we find one of the units -- Ada.Text_IO or Ada.[Wide_]Wide_Text_IO. An interesting -- detail is that these units may already be used (i.e. their -- In_Use flags may be set). Normally when the In_Use flag is -- set, the Is_Potentially_Use_Visible flag of all entities in -- the package is set, but the new entity we are mysteriously -- adding was not there to have its flag set at the time. So -- that's why we pass the extra parameter to RTU_Find, to make -- sure the flag does get set now. Given that those generic -- packages are in fact child units, we must indicate that -- they are visible. if Name_Buffer (1 .. 12) = "a-textio.ads" then Load_RTU (Name_Map (Chrs), Use_Setting => In_Use (Cunit_Entity (U))); Set_Is_Visible_Child_Unit (RT_Unit_Table (Name_Map (Chrs)).Entity); elsif Name_Buffer (1 .. 12) = "a-witeio.ads" then Load_RTU (Wide_Name_Map (Chrs), Use_Setting => In_Use (Cunit_Entity (U))); Set_Is_Visible_Child_Unit (RT_Unit_Table (Wide_Name_Map (Chrs)).Entity); elsif Name_Buffer (1 .. 12) = "a-ztexio.ads" then Load_RTU (Wide_Wide_Name_Map (Chrs), Use_Setting => In_Use (Cunit_Entity (U))); Set_Is_Visible_Child_Unit (RT_Unit_Table (Wide_Wide_Name_Map (Chrs)).Entity); end if; end if; end loop; end if; end Text_IO_Kludge; end Rtsfind;
------------------------------------------------------------------------------ -- -- -- Internet Protocol Suite Package -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This package provides low-level interfaces to libtls for the management of -- "contexts", and the sending and receiving of data through those contexts with Ada.Streams; with Ada.Finalization; with Interfaces.C; limited with INET.TLS; with INET.Internal.UNIX_Sockets; package INET.Internal.TLS is package UNIX_Sockets renames Internal.UNIX_Sockets; ----------------------- -- Common Facilities -- ----------------------- use type Interfaces.C.size_t; type Random_Data is array (Interfaces.C.size_t range <>) of Interfaces.C.unsigned_char with Pack => True, Convention => C; procedure Cryptographic_Randomize (Data : out Random_Data); procedure Cryptographic_Randomize (Value: out Interfaces.Unsigned_32); -- Provides cryptographically random values for arbitrary data -- (usually keys), or unsigned 32-bit integers. This means high-entropy -- random data, typically harvested by the operating system. ----------------- -- TLS_Context -- ----------------- type TLS_Context is abstract tagged limited private; -- A TLS_Context represents the state of a TLS connection, and libtls -- needs the context in order to send or receive. The context is configured -- for each connection, and eventually associated with a socket. function Available (Context: TLS_Context) return Boolean; -- True if the context has been configured OR established procedure Shutdown (Context: in out TLS_Context) with Post'Class => not Context.Available; -- Closes-down the underlying session, but does not reset or free the -- context. Those operations are handled by finalization or one of -- the Establish or Configure operations of the derrived types procedure Handshake (Context: in out TLS_Context; Socket : in UNIX_Sockets.UNIX_Socket; Timeout: in Duration) with Pre'Class => Context.Available; -- Causes a TLS handshake to be executed immediately. If the handshake -- fails, TLS_Handshake_Failed is propegated with the corresponding error -- message from libtls -- -- If the handshake times-out, TLS_Handshake_Failed will be raised, but -- the context will not be closed. -- -- If Context is not Available, Program_Error is raised -------------------------- -- TLS_Listener_Context -- -------------------------- type TLS_Listener_Context is limited new TLS_Context with private; not overriding procedure Configure (Context : in out TLS_Listener_Context; Configuration: in INET.TLS.TLS_Server_Configuration'Class) with Post'Class => Context.Available; -- TLS_Listener_Contexts are configured with a handle from a -- TLS_Server_Configuration'Class object, and is able to initialize new -- TLS_Stream_Contexts -- -- The Caller shall ensure that Configuration is from a -- TLS_Server_Configuration object -- -- If the context is already Available, the context is closed and reset. -- -- ** Note ** -- libtls internally links the configuration to the context, and so as long -- as the TLS_Configuration object remains visible, it can be modified -- directly, such as adding ticket keys, and this will affect all associated -- contexts. A full reconfiguration is therefore not necessary for such -- operations. ------------------------ -- TLS_Stream_Context -- ------------------------ type TLS_Stream_Context is limited new TLS_Context with private; -- "native" TLS: A context for reliable stream transports (usually TCP or -- SCTP). not overriding procedure Establish (Context : in out TLS_Stream_Context; Listener_Context: in TLS_Listener_Context'Class; Socket : in UNIX_Sockets.UNIX_Socket; Timeout : in Duration) with Pre'Class => not Context.Available and Listener_Context.Available and UNIX_Sockets.Socket_Active (Socket), Post'Class => Context.Available; -- Setting up a new server TLS stream via a TLS_Listener_Context. not overriding procedure Establish (Context : in out TLS_Stream_Context; Configuration: in INET.TLS.TLS_Client_Configuration'Class; Socket : in UNIX_Sockets.UNIX_Socket; Timeout : in Duration) with Pre'Class => not Context.Available and UNIX_Sockets.Socket_Active (Socket), Post'Class => Context.Available; -- Setting up a new TLS stream to a remote server not overriding procedure Establish (Context : in out TLS_Stream_Context; Configuration: in INET.TLS.TLS_Client_Configuration'Class; Server_Name : in String; Socket : in UNIX_Sockets.UNIX_Socket; Timeout : in Duration) with Pre'Class => not Context.Available and UNIX_Sockets.Socket_Active (Socket), Post'Class => Context.Available; -- Setting up a new TLS stream to a remote server with SNI -- Sets up and configures, TLS context, associating it with some existing -- TCP connection, and then invokes Hanshake on Context. -- -- If Context is currently Available, Program_Error is raised. -- -- If Server_Name is specified, the SNI extension (RFC 4366) is enforced. -- -- Any failure raises TLS_Error with an appropriate message. -- -- Timeout is passed directly to Handshake, with the same consequences not overriding procedure TLS_Send_Immediate (Context: in out TLS_Stream_Context; Buffer : in Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) with Pre'Class => Context.Available; not overriding procedure TLS_Receive_Immediate (Context: in out TLS_Stream_Context; Buffer : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) with Pre'Class => Context.Available; -- Attempts to Send or Receive over an established TLS context. The -- underlying socket is assumed to be non-blocking. -- -- If an error occurs, TLS_Error is raised with the appropriate error -- message. -- type TLS_Datagram_Context is limited new TLS_Context with private; -- DTLS: A context for (unreliable) datagram transports. -- ** Future implementation ** -- private type Context_Handle is new INET_Extension_Handle; -- A "C" pointer to the "struct tls" structure in libtls. This is a -- transparent structure Null_Context_Handle: constant Context_Handle := Context_Handle (Null_Handle); type TLS_Context is abstract limited new Ada.Finalization.Limited_Controlled with record Avail : Boolean := False; Handle: Context_Handle := Null_Context_Handle; end record; overriding procedure Finalize (Context: in out TLS_Context); -- Deactivates and deinitializes Context type TLS_Listener_Context is limited new TLS_Context with null record; type TLS_Stream_Context is limited new TLS_Context with null record; end INET.Internal.TLS;
package Giza.Bitmap_Fonts.FreeSerif12pt7b is Font : constant Giza.Font.Ref_Const; private FreeSerif12pt7bBitmaps : aliased constant Font_Bitmap := ( 16#FF#, 16#FE#, 16#A8#, 16#3F#, 16#CF#, 16#3C#, 16#F3#, 16#8A#, 16#20#, 16#0C#, 16#40#, 16#C4#, 16#08#, 16#40#, 16#8C#, 16#08#, 16#C7#, 16#FF#, 16#18#, 16#81#, 16#88#, 16#10#, 16#81#, 16#08#, 16#FF#, 16#E1#, 16#18#, 16#31#, 16#03#, 16#10#, 16#21#, 16#02#, 16#10#, 16#04#, 16#07#, 16#C6#, 16#5B#, 16#12#, 16#C4#, 16#B1#, 16#0F#, 16#41#, 16#F0#, 16#1E#, 16#01#, 16#E0#, 16#58#, 16#13#, 16#84#, 16#E1#, 16#3C#, 16#4F#, 16#96#, 16#3F#, 16#01#, 16#00#, 16#00#, 16#04#, 16#03#, 16#83#, 16#03#, 16#9F#, 16#81#, 16#C2#, 16#20#, 16#60#, 16#90#, 16#38#, 16#24#, 16#0C#, 16#12#, 16#03#, 16#0D#, 16#00#, 16#C6#, 16#47#, 16#9E#, 16#23#, 16#10#, 16#09#, 16#84#, 16#04#, 16#E1#, 16#03#, 16#30#, 16#40#, 16#8C#, 16#20#, 16#43#, 16#08#, 16#10#, 16#C4#, 16#08#, 16#1E#, 16#00#, 16#03#, 16#C0#, 16#02#, 16#30#, 16#03#, 16#08#, 16#01#, 16#84#, 16#00#, 16#C4#, 16#00#, 16#7C#, 16#F8#, 16#1C#, 16#38#, 16#1E#, 16#08#, 16#33#, 16#0C#, 16#31#, 16#C4#, 16#10#, 16#74#, 16#18#, 16#3A#, 16#0C#, 16#0E#, 16#07#, 16#03#, 16#83#, 16#C3#, 16#E2#, 16#7E#, 16#3E#, 16#FF#, 16#A0#, 16#04#, 16#21#, 16#08#, 16#61#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C1#, 16#04#, 16#18#, 16#20#, 16#40#, 16#81#, 16#81#, 16#02#, 16#04#, 16#18#, 16#20#, 16#83#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#86#, 16#10#, 16#84#, 16#20#, 16#30#, 16#B3#, 16#D7#, 16#54#, 16#38#, 16#7C#, 16#D3#, 16#30#, 16#30#, 16#10#, 16#04#, 16#00#, 16#80#, 16#10#, 16#02#, 16#00#, 16#41#, 16#FF#, 16#C1#, 16#00#, 16#20#, 16#04#, 16#00#, 16#80#, 16#10#, 16#00#, 16#DF#, 16#95#, 16#00#, 16#FC#, 16#FC#, 16#02#, 16#0C#, 16#10#, 16#20#, 16#C1#, 16#02#, 16#0C#, 16#10#, 16#20#, 16#C1#, 16#02#, 16#0C#, 16#10#, 16#60#, 16#C0#, 16#1E#, 16#0C#, 16#C6#, 16#19#, 16#86#, 16#C0#, 16#B0#, 16#3C#, 16#0F#, 16#03#, 16#C0#, 16#F0#, 16#3C#, 16#0F#, 16#03#, 16#C0#, 16#D8#, 16#66#, 16#18#, 16#CC#, 16#1E#, 16#00#, 16#11#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#FC#, 16#1E#, 16#18#, 16#C4#, 16#1A#, 16#06#, 16#01#, 16#80#, 16#60#, 16#10#, 16#0C#, 16#02#, 16#01#, 16#00#, 16#C0#, 16#60#, 16#30#, 16#18#, 16#1F#, 16#F8#, 16#1E#, 16#18#, 16#E8#, 16#18#, 16#06#, 16#01#, 16#00#, 16#80#, 16#F0#, 16#7E#, 16#03#, 16#C0#, 16#70#, 16#0C#, 16#03#, 16#00#, 16#C0#, 16#6E#, 16#11#, 16#F8#, 16#01#, 16#00#, 16#C0#, 16#70#, 16#2C#, 16#0B#, 16#04#, 16#C2#, 16#30#, 16#8C#, 16#43#, 16#20#, 16#C8#, 16#33#, 16#FF#, 16#03#, 16#00#, 16#C0#, 16#30#, 16#0C#, 16#00#, 16#03#, 16#F1#, 16#00#, 16#40#, 16#18#, 16#0F#, 16#80#, 16#F8#, 16#0E#, 16#01#, 16#C0#, 16#30#, 16#0C#, 16#03#, 16#00#, 16#C0#, 16#20#, 16#1B#, 16#8C#, 16#7C#, 16#00#, 16#01#, 16#C3#, 16#C1#, 16#C0#, 16#C0#, 16#70#, 16#18#, 16#0E#, 16#F3#, 16#CE#, 16#C1#, 16#F0#, 16#3C#, 16#0F#, 16#03#, 16#C0#, 16#D8#, 16#36#, 16#08#, 16#C6#, 16#1E#, 16#00#, 16#3F#, 16#D0#, 16#38#, 16#08#, 16#02#, 16#01#, 16#80#, 16#40#, 16#10#, 16#0C#, 16#02#, 16#00#, 16#80#, 16#20#, 16#10#, 16#04#, 16#01#, 16#00#, 16#80#, 16#20#, 16#1F#, 16#18#, 16#6C#, 16#0F#, 16#03#, 16#C0#, 16#F8#, 16#67#, 16#30#, 16#F0#, 16#1E#, 16#09#, 16#E6#, 16#3B#, 16#07#, 16#C0#, 16#F0#, 16#3C#, 16#0D#, 16#86#, 16#1F#, 16#00#, 16#1E#, 16#08#, 16#C6#, 16#1B#, 16#02#, 16#C0#, 16#F0#, 16#3C#, 16#0F#, 16#03#, 16#E0#, 16#DC#, 16#73#, 16#EC#, 16#06#, 16#01#, 16#80#, 16#C0#, 16#70#, 16#38#, 16#38#, 16#18#, 16#00#, 16#FC#, 16#00#, 16#3F#, 16#CC#, 16#C0#, 16#00#, 16#00#, 16#06#, 16#77#, 16#12#, 16#40#, 16#00#, 16#00#, 16#07#, 16#01#, 16#E0#, 16#78#, 16#1E#, 16#07#, 16#00#, 16#C0#, 16#0F#, 16#00#, 16#3C#, 16#00#, 16#F0#, 16#03#, 16#C0#, 16#07#, 16#00#, 16#10#, 16#FF#, 16#F0#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#FF#, 16#80#, 16#0E#, 16#00#, 16#3C#, 16#00#, 16#F0#, 16#03#, 16#C0#, 16#0F#, 16#00#, 16#30#, 16#0E#, 16#07#, 16#81#, 16#E0#, 16#78#, 16#0E#, 16#00#, 16#00#, 16#00#, 16#7C#, 16#86#, 16#83#, 16#C3#, 16#03#, 16#03#, 16#06#, 16#0C#, 16#08#, 16#08#, 16#10#, 16#10#, 16#00#, 16#00#, 16#30#, 16#30#, 16#30#, 16#03#, 16#F0#, 16#06#, 16#06#, 16#06#, 16#00#, 16#86#, 16#00#, 16#26#, 16#0E#, 16#D3#, 16#0C#, 16#C7#, 16#0C#, 16#63#, 16#84#, 16#31#, 16#C6#, 16#18#, 16#E3#, 16#08#, 16#71#, 16#8C#, 16#4C#, 16#C6#, 16#46#, 16#3D#, 16#C1#, 16#80#, 16#00#, 16#30#, 16#10#, 16#07#, 16#F0#, 16#00#, 16#80#, 16#00#, 16#60#, 16#00#, 16#70#, 16#00#, 16#38#, 16#00#, 16#2E#, 16#00#, 16#13#, 16#00#, 16#19#, 16#C0#, 16#08#, 16#60#, 16#04#, 16#38#, 16#04#, 16#0C#, 16#03#, 16#FF#, 16#03#, 16#03#, 16#81#, 16#00#, 16#E1#, 16#80#, 16#70#, 16#C0#, 16#3D#, 16#F0#, 16#3F#, 16#FF#, 16#83#, 16#0C#, 16#30#, 16#63#, 16#06#, 16#30#, 16#63#, 16#06#, 16#30#, 16#C3#, 16#F0#, 16#30#, 16#E3#, 16#06#, 16#30#, 16#33#, 16#03#, 16#30#, 16#33#, 16#07#, 16#30#, 16#EF#, 16#FC#, 16#07#, 16#E2#, 16#38#, 16#3C#, 16#C0#, 16#3B#, 16#00#, 16#36#, 16#00#, 16#38#, 16#00#, 16#30#, 16#00#, 16#60#, 16#00#, 16#C0#, 16#01#, 16#80#, 16#03#, 16#00#, 16#03#, 16#00#, 16#06#, 16#00#, 16#06#, 16#00#, 16#47#, 16#03#, 16#03#, 16#F8#, 16#FF#, 16#C0#, 16#30#, 16#78#, 16#30#, 16#1C#, 16#30#, 16#0E#, 16#30#, 16#06#, 16#30#, 16#03#, 16#30#, 16#03#, 16#30#, 16#03#, 16#30#, 16#03#, 16#30#, 16#03#, 16#30#, 16#03#, 16#30#, 16#06#, 16#30#, 16#06#, 16#30#, 16#0C#, 16#30#, 16#78#, 16#FF#, 16#C0#, 16#FF#, 16#FC#, 16#C0#, 16#33#, 16#00#, 16#4C#, 16#00#, 16#30#, 16#00#, 16#C0#, 16#43#, 16#03#, 16#0F#, 16#FC#, 16#30#, 16#30#, 16#C0#, 16#43#, 16#00#, 16#0C#, 16#00#, 16#30#, 16#08#, 16#C0#, 16#23#, 16#03#, 16#BF#, 16#FE#, 16#FF#, 16#FC#, 16#C0#, 16#33#, 16#00#, 16#4C#, 16#00#, 16#30#, 16#00#, 16#C0#, 16#43#, 16#03#, 16#0F#, 16#FC#, 16#30#, 16#30#, 16#C0#, 16#43#, 16#00#, 16#0C#, 16#00#, 16#30#, 16#00#, 16#C0#, 16#03#, 16#00#, 16#3F#, 16#00#, 16#07#, 16#E4#, 16#1C#, 16#3C#, 16#30#, 16#0C#, 16#60#, 16#0C#, 16#60#, 16#04#, 16#C0#, 16#00#, 16#C0#, 16#00#, 16#C0#, 16#3F#, 16#C0#, 16#0C#, 16#C0#, 16#0C#, 16#C0#, 16#0C#, 16#60#, 16#0C#, 16#60#, 16#0C#, 16#30#, 16#0C#, 16#1C#, 16#1C#, 16#07#, 16#E0#, 16#FC#, 16#3F#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#3F#, 16#FC#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#30#, 16#0C#, 16#FC#, 16#3F#, 16#FC#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#3F#, 16#3F#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#0C#, 16#C8#, 16#F0#, 16#FC#, 16#FE#, 16#30#, 16#38#, 16#30#, 16#20#, 16#30#, 16#40#, 16#30#, 16#80#, 16#33#, 16#00#, 16#36#, 16#00#, 16#3E#, 16#00#, 16#37#, 16#00#, 16#33#, 16#80#, 16#31#, 16#C0#, 16#30#, 16#E0#, 16#30#, 16#70#, 16#30#, 16#38#, 16#30#, 16#3C#, 16#FC#, 16#7F#, 16#FC#, 16#00#, 16#60#, 16#00#, 16#C0#, 16#01#, 16#80#, 16#03#, 16#00#, 16#06#, 16#00#, 16#0C#, 16#00#, 16#18#, 16#00#, 16#30#, 16#00#, 16#60#, 16#00#, 16#C0#, 16#01#, 16#80#, 16#03#, 16#00#, 16#26#, 16#00#, 16#8C#, 16#07#, 16#7F#, 16#FE#, 16#F8#, 16#01#, 16#E7#, 16#00#, 16#70#, 16#F0#, 16#0E#, 16#1E#, 16#03#, 16#C3#, 16#C0#, 16#58#, 16#5C#, 16#1B#, 16#0B#, 16#82#, 16#61#, 16#38#, 16#4C#, 16#27#, 16#11#, 16#84#, 16#72#, 16#30#, 16#8E#, 16#C6#, 16#10#, 16#F0#, 16#C2#, 16#1E#, 16#18#, 16#41#, 16#83#, 16#1C#, 16#30#, 16#67#, 16#C4#, 16#3F#, 16#F0#, 16#1F#, 16#78#, 16#0E#, 16#3C#, 16#04#, 16#3E#, 16#04#, 16#2E#, 16#04#, 16#27#, 16#04#, 16#23#, 16#84#, 16#23#, 16#C4#, 16#21#, 16#E4#, 16#20#, 16#F4#, 16#20#, 16#74#, 16#20#, 16#3C#, 16#20#, 16#1C#, 16#20#, 16#1C#, 16#70#, 16#0C#, 16#F8#, 16#04#, 16#07#, 16#C0#, 16#30#, 16#60#, 16#C0#, 16#63#, 16#00#, 16#66#, 16#00#, 16#D8#, 16#00#, 16#F0#, 16#01#, 16#E0#, 16#03#, 16#C0#, 16#07#, 16#80#, 16#0F#, 16#00#, 16#1B#, 16#00#, 16#66#, 16#00#, 16#C6#, 16#03#, 16#06#, 16#0C#, 16#03#, 16#E0#, 16#FF#, 16#83#, 16#0E#, 16#30#, 16#73#, 16#03#, 16#30#, 16#33#, 16#03#, 16#30#, 16#63#, 16#0E#, 16#3F#, 16#83#, 16#00#, 16#30#, 16#03#, 16#00#, 16#30#, 16#03#, 16#00#, 16#30#, 16#0F#, 16#C0#, 16#0F#, 16#E0#, 16#18#, 16#30#, 16#30#, 16#18#, 16#60#, 16#0C#, 16#60#, 16#0C#, 16#C0#, 16#06#, 16#C0#, 16#06#, 16#C0#, 16#06#, 16#C0#, 16#06#, 16#C0#, 16#06#, 16#C0#, 16#06#, 16#60#, 16#0C#, 16#60#, 16#0C#, 16#30#, 16#18#, 16#18#, 16#30#, 16#07#, 16#C0#, 16#03#, 16#C0#, 16#01#, 16#E0#, 16#00#, 16#78#, 16#00#, 16#1F#, 16#FF#, 16#80#, 16#61#, 16#C0#, 16#C1#, 16#C1#, 16#81#, 16#83#, 16#03#, 16#06#, 16#06#, 16#0C#, 16#1C#, 16#18#, 16#70#, 16#3F#, 16#80#, 16#67#, 16#00#, 16#C7#, 16#01#, 16#8F#, 16#03#, 16#0F#, 16#06#, 16#0E#, 16#0C#, 16#0E#, 16#7E#, 16#0F#, 16#1F#, 16#46#, 16#19#, 16#81#, 16#30#, 16#27#, 16#02#, 16#F0#, 16#0F#, 16#00#, 16#F8#, 16#07#, 16#C0#, 16#38#, 16#03#, 16#C0#, 16#34#, 16#06#, 16#80#, 16#DC#, 16#32#, 16#7C#, 16#FF#, 16#FF#, 16#86#, 16#0E#, 16#0C#, 16#1C#, 16#18#, 16#10#, 16#30#, 16#00#, 16#60#, 16#00#, 16#C0#, 16#01#, 16#80#, 16#03#, 16#00#, 16#06#, 16#00#, 16#0C#, 16#00#, 16#18#, 16#00#, 16#30#, 16#00#, 16#60#, 16#00#, 16#C0#, 16#07#, 16#E0#, 16#FC#, 16#1F#, 16#30#, 16#0E#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#30#, 16#04#, 16#18#, 16#08#, 16#1C#, 16#18#, 16#07#, 16#E0#, 16#FE#, 16#0F#, 16#9C#, 16#03#, 16#0E#, 16#01#, 16#83#, 16#00#, 16#81#, 16#C0#, 16#40#, 16#60#, 16#40#, 16#38#, 16#20#, 16#0C#, 16#30#, 16#07#, 16#10#, 16#01#, 16#88#, 16#00#, 16#E8#, 16#00#, 16#34#, 16#00#, 16#1C#, 16#00#, 16#06#, 16#00#, 16#03#, 16#00#, 16#01#, 16#00#, 16#FC#, 16#FC#, 16#3D#, 16#E1#, 16#C0#, 16#63#, 16#83#, 16#01#, 16#86#, 16#0E#, 16#04#, 16#1C#, 16#18#, 16#10#, 16#70#, 16#70#, 16#80#, 16#C3#, 16#C2#, 16#03#, 16#8B#, 16#08#, 16#06#, 16#6E#, 16#40#, 16#1D#, 16#19#, 16#00#, 16#74#, 16#78#, 16#00#, 16#E1#, 16#E0#, 16#03#, 16#83#, 16#80#, 16#0E#, 16#0C#, 16#00#, 16#10#, 16#10#, 16#00#, 16#40#, 16#40#, 16#7F#, 16#1F#, 16#9E#, 16#03#, 16#07#, 16#03#, 16#01#, 16#C3#, 16#00#, 16#71#, 16#00#, 16#19#, 16#00#, 16#0F#, 16#00#, 16#03#, 16#80#, 16#01#, 16#E0#, 16#01#, 16#B0#, 16#01#, 16#9C#, 16#00#, 16#87#, 16#00#, 16#81#, 16#C0#, 16#80#, 16#E0#, 16#C0#, 16#79#, 16#F8#, 16#7F#, 16#FE#, 16#1F#, 16#78#, 16#0C#, 16#38#, 16#08#, 16#1C#, 16#18#, 16#0E#, 16#10#, 16#06#, 16#20#, 16#07#, 16#40#, 16#03#, 16#C0#, 16#01#, 16#80#, 16#01#, 16#80#, 16#01#, 16#80#, 16#01#, 16#80#, 16#01#, 16#80#, 16#01#, 16#80#, 16#01#, 16#80#, 16#07#, 16#E0#, 16#7F#, 16#FB#, 16#00#, 16#C8#, 16#07#, 16#20#, 16#38#, 16#00#, 16#C0#, 16#07#, 16#00#, 16#38#, 16#01#, 16#C0#, 16#07#, 16#00#, 16#38#, 16#01#, 16#C0#, 16#06#, 16#00#, 16#38#, 16#05#, 16#C0#, 16#3E#, 16#01#, 16#BF#, 16#FE#, 16#FE#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#F0#, 16#C1#, 16#83#, 16#03#, 16#06#, 16#0C#, 16#0C#, 16#18#, 16#10#, 16#30#, 16#60#, 16#40#, 16#C1#, 16#81#, 16#03#, 16#06#, 16#F8#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#C7#, 16#F0#, 16#0C#, 16#07#, 16#01#, 16#60#, 16#D8#, 16#23#, 16#18#, 16#C4#, 16#1B#, 16#06#, 16#80#, 16#C0#, 16#FF#, 16#F0#, 16#C7#, 16#0C#, 16#30#, 16#3E#, 16#31#, 16#8C#, 16#30#, 16#0C#, 16#03#, 16#07#, 16#C6#, 16#33#, 16#0C#, 16#C3#, 16#31#, 16#C7#, 16#B8#, 16#20#, 16#38#, 16#06#, 16#01#, 16#80#, 16#60#, 16#18#, 16#06#, 16#F1#, 16#C6#, 16#61#, 16#D8#, 16#36#, 16#0D#, 16#83#, 16#60#, 16#D8#, 16#26#, 16#19#, 16#84#, 16#3E#, 16#00#, 16#1E#, 16#23#, 16#63#, 16#C0#, 16#C0#, 16#C0#, 16#C0#, 16#C0#, 16#E1#, 16#72#, 16#3C#, 16#00#, 16#80#, 16#E0#, 16#18#, 16#06#, 16#01#, 16#80#, 16#61#, 16#D8#, 16#8E#, 16#61#, 16#B0#, 16#6C#, 16#1B#, 16#06#, 16#C1#, 16#B0#, 16#6E#, 16#19#, 16#CE#, 16#3D#, 16#C0#, 16#1E#, 16#08#, 16#E4#, 16#1B#, 16#FE#, 16#C0#, 16#30#, 16#0C#, 16#03#, 16#81#, 16#60#, 16#9C#, 16#41#, 16#E0#, 16#0F#, 16#08#, 16#C4#, 16#06#, 16#03#, 16#01#, 16#81#, 16#F0#, 16#60#, 16#30#, 16#18#, 16#0C#, 16#06#, 16#03#, 16#01#, 16#80#, 16#C0#, 16#60#, 16#FC#, 16#00#, 16#1F#, 16#03#, 16#1F#, 16#60#, 16#C6#, 16#0C#, 16#60#, 16#C3#, 16#18#, 16#1F#, 16#02#, 16#00#, 16#40#, 16#07#, 16#FC#, 16#40#, 16#24#, 16#02#, 16#C0#, 16#2C#, 16#04#, 16#E0#, 16#83#, 16#F0#, 16#30#, 16#1E#, 16#00#, 16#C0#, 16#18#, 16#03#, 16#00#, 16#60#, 16#0D#, 16#E1#, 16#CE#, 16#30#, 16#C6#, 16#18#, 16#C3#, 16#18#, 16#63#, 16#0C#, 16#61#, 16#8C#, 16#31#, 16#86#, 16#79#, 16#E0#, 16#31#, 16#80#, 16#00#, 16#09#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#DF#, 16#0C#, 16#30#, 16#00#, 16#00#, 16#31#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#30#, 16#F2#, 16#F0#, 16#20#, 16#1C#, 16#01#, 16#80#, 16#30#, 16#06#, 16#00#, 16#C0#, 16#18#, 16#FB#, 16#08#, 16#62#, 16#0C#, 16#81#, 16#E0#, 16#3E#, 16#06#, 16#E0#, 16#CE#, 16#18#, 16#C3#, 16#0E#, 16#F3#, 16#E0#, 16#13#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#F8#, 16#F7#, 16#8F#, 16#0E#, 16#3C#, 16#E3#, 16#0C#, 16#18#, 16#C3#, 16#06#, 16#30#, 16#C1#, 16#8C#, 16#30#, 16#63#, 16#0C#, 16#18#, 16#C3#, 16#06#, 16#30#, 16#C1#, 16#8C#, 16#30#, 16#67#, 16#9E#, 16#3C#, 16#F7#, 16#87#, 16#18#, 16#C3#, 16#18#, 16#63#, 16#0C#, 16#61#, 16#8C#, 16#31#, 16#86#, 16#30#, 16#C6#, 16#19#, 16#E7#, 16#80#, 16#1E#, 16#18#, 16#E4#, 16#1B#, 16#03#, 16#C0#, 16#F0#, 16#3C#, 16#0F#, 16#03#, 16#60#, 16#9C#, 16#41#, 16#E0#, 16#77#, 16#87#, 16#18#, 16#C3#, 16#98#, 16#33#, 16#06#, 16#60#, 16#CC#, 16#19#, 16#83#, 16#30#, 16#C7#, 16#10#, 16#DC#, 16#18#, 16#03#, 16#00#, 16#60#, 16#0C#, 16#07#, 16#E0#, 16#1E#, 16#8C#, 16#E6#, 16#1B#, 16#06#, 16#C1#, 16#B0#, 16#6C#, 16#1B#, 16#06#, 16#E1#, 16#98#, 16#E3#, 16#D8#, 16#06#, 16#01#, 16#80#, 16#60#, 16#18#, 16#1F#, 16#37#, 16#7B#, 16#30#, 16#30#, 16#30#, 16#30#, 16#30#, 16#30#, 16#30#, 16#30#, 16#7C#, 16#7B#, 16#0E#, 16#1C#, 16#1E#, 16#0F#, 16#07#, 16#C3#, 16#87#, 16#8A#, 16#E0#, 16#21#, 16#8F#, 16#98#, 16#61#, 16#86#, 16#18#, 16#61#, 16#86#, 16#19#, 16#38#, 16#E3#, 16#98#, 16#66#, 16#19#, 16#86#, 16#61#, 16#98#, 16#66#, 16#19#, 16#86#, 16#61#, 16#9C#, 16#E3#, 16#DC#, 16#F8#, 16#EE#, 16#08#, 16#C1#, 16#18#, 16#41#, 16#88#, 16#32#, 16#03#, 16#40#, 16#68#, 16#06#, 16#00#, 16#C0#, 16#10#, 16#00#, 16#F3#, 16#E7#, 16#61#, 16#83#, 16#70#, 16#C2#, 16#30#, 16#C2#, 16#30#, 16#C4#, 16#19#, 16#64#, 16#19#, 16#68#, 16#0E#, 16#38#, 16#0E#, 16#30#, 16#0C#, 16#30#, 16#04#, 16#10#, 16#FB#, 16#C6#, 16#30#, 16#64#, 16#0F#, 16#00#, 16#C0#, 16#0C#, 16#03#, 16#C0#, 16#98#, 16#21#, 16#8C#, 16#3B#, 16#CF#, 16#80#, 16#F8#, 16#EE#, 16#08#, 16#C1#, 16#18#, 16#41#, 16#88#, 16#31#, 16#03#, 16#40#, 16#68#, 16#06#, 16#00#, 16#C0#, 16#08#, 16#02#, 16#00#, 16#40#, 16#10#, 16#1E#, 16#03#, 16#80#, 16#7F#, 16#90#, 16#E0#, 16#30#, 16#18#, 16#0E#, 16#03#, 16#01#, 16#C0#, 16#E0#, 16#30#, 16#5C#, 16#3F#, 16#F8#, 16#19#, 16#8C#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#B0#, 16#63#, 16#18#, 16#C6#, 16#31#, 16#8C#, 16#61#, 16#80#, 16#FF#, 16#FF#, 16#80#, 16#C3#, 16#18#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#06#, 16#C6#, 16#31#, 16#8C#, 16#63#, 16#18#, 16#CC#, 16#00#, 16#38#, 16#06#, 16#62#, 16#41#, 16#C0#); FreeSerif12pt7bGlyphs : aliased constant Glyph_Array := ( (0, 0, 0, 6, 0, 1), -- 0x20 ' ' (0, 2, 16, 8, 3, -15), -- 0x21 '!' (4, 6, 6, 10, 1, -15), -- 0x22 '"' (9, 12, 16, 12, 0, -15), -- 0x23 '#' (33, 10, 18, 12, 1, -16), -- 0x24 '$' (56, 18, 17, 20, 1, -16), -- 0x25 '%' (95, 17, 16, 19, 1, -15), -- 0x26 '&' (129, 2, 6, 5, 1, -15), -- 0x27 ''' (131, 6, 20, 8, 1, -15), -- 0x28 '(' (146, 6, 20, 8, 1, -15), -- 0x29 ')' (161, 8, 10, 12, 3, -14), -- 0x2A '*' (171, 11, 11, 14, 1, -10), -- 0x2B '+' (187, 3, 6, 6, 2, -2), -- 0x2C ',' (190, 6, 1, 8, 1, -5), -- 0x2D '-' (191, 2, 3, 6, 2, -2), -- 0x2E '.' (192, 7, 17, 7, 0, -16), -- 0x2F '/' (207, 10, 17, 12, 1, -16), -- 0x30 '0' (229, 6, 17, 12, 3, -16), -- 0x31 '1' (242, 10, 15, 12, 1, -14), -- 0x32 '2' (261, 10, 16, 12, 1, -15), -- 0x33 '3' (281, 10, 16, 12, 1, -15), -- 0x34 '4' (301, 10, 17, 12, 1, -16), -- 0x35 '5' (323, 10, 17, 12, 1, -16), -- 0x36 '6' (345, 10, 16, 12, 0, -15), -- 0x37 '7' (365, 10, 17, 12, 1, -16), -- 0x38 '8' (387, 10, 18, 12, 1, -16), -- 0x39 '9' (410, 2, 12, 6, 2, -11), -- 0x3A ':' (413, 4, 15, 6, 2, -11), -- 0x3B ';' (421, 12, 13, 14, 1, -12), -- 0x3C '<' (441, 12, 6, 14, 1, -8), -- 0x3D '=' (450, 12, 13, 14, 1, -11), -- 0x3E '>' (470, 8, 17, 11, 2, -16), -- 0x3F '?' (487, 17, 16, 21, 2, -15), -- 0x40 '@' (521, 17, 16, 17, 0, -15), -- 0x41 'A' (555, 12, 16, 15, 1, -15), -- 0x42 'B' (579, 15, 16, 16, 1, -15), -- 0x43 'C' (609, 16, 16, 17, 0, -15), -- 0x44 'D' (641, 14, 16, 15, 0, -15), -- 0x45 'E' (669, 14, 16, 14, 0, -15), -- 0x46 'F' (697, 16, 16, 17, 1, -15), -- 0x47 'G' (729, 16, 16, 17, 0, -15), -- 0x48 'H' (761, 6, 16, 8, 1, -15), -- 0x49 'I' (773, 8, 16, 9, 0, -15), -- 0x4A 'J' (789, 16, 16, 17, 1, -15), -- 0x4B 'K' (821, 15, 16, 15, 0, -15), -- 0x4C 'L' (851, 19, 16, 21, 1, -15), -- 0x4D 'M' (889, 16, 16, 17, 1, -15), -- 0x4E 'N' (921, 15, 16, 17, 1, -15), -- 0x4F 'O' (951, 12, 16, 14, 0, -15), -- 0x50 'P' (975, 16, 20, 17, 1, -15), -- 0x51 'Q' (1015, 15, 16, 16, 0, -15), -- 0x52 'R' (1045, 11, 16, 13, 0, -15), -- 0x53 'S' (1067, 15, 16, 15, 0, -15), -- 0x54 'T' (1097, 16, 16, 17, 1, -15), -- 0x55 'U' (1129, 17, 16, 17, 0, -15), -- 0x56 'V' (1163, 22, 16, 23, 0, -15), -- 0x57 'W' (1207, 17, 16, 17, 0, -15), -- 0x58 'X' (1241, 16, 16, 17, 0, -15), -- 0x59 'Y' (1273, 14, 16, 15, 1, -15), -- 0x5A 'Z' (1301, 5, 20, 8, 2, -15), -- 0x5B '[' (1314, 7, 17, 7, 0, -16), -- 0x5C '\' (1329, 5, 20, 8, 1, -15), -- 0x5D ']' (1342, 10, 9, 11, 1, -15), -- 0x5E '^' (1354, 12, 1, 12, 0, 3), -- 0x5F '_' (1356, 5, 4, 6, 0, -15), -- 0x60 '`' (1359, 10, 11, 10, 1, -10), -- 0x61 'a' (1373, 10, 17, 12, 1, -16), -- 0x62 'b' (1395, 8, 11, 11, 1, -10), -- 0x63 'c' (1406, 10, 17, 12, 1, -16), -- 0x64 'd' (1428, 10, 11, 11, 1, -10), -- 0x65 'e' (1442, 9, 17, 9, 0, -16), -- 0x66 'f' (1462, 12, 16, 11, 0, -10), -- 0x67 'g' (1486, 11, 17, 12, 0, -16), -- 0x68 'h' (1510, 5, 16, 7, 0, -15), -- 0x69 'i' (1520, 6, 21, 8, 0, -15), -- 0x6A 'j' (1536, 11, 17, 12, 1, -16), -- 0x6B 'k' (1560, 5, 17, 6, 0, -16), -- 0x6C 'l' (1571, 18, 11, 19, 0, -10), -- 0x6D 'm' (1596, 11, 11, 12, 0, -10), -- 0x6E 'n' (1612, 10, 11, 12, 1, -10), -- 0x6F 'o' (1626, 11, 16, 12, 0, -10), -- 0x70 'p' (1648, 10, 16, 12, 1, -10), -- 0x71 'q' (1668, 8, 11, 8, 0, -10), -- 0x72 'r' (1679, 7, 11, 9, 1, -10), -- 0x73 's' (1689, 6, 13, 7, 1, -12), -- 0x74 't' (1699, 10, 11, 12, 1, -10), -- 0x75 'u' (1713, 11, 11, 11, 0, -10), -- 0x76 'v' (1729, 16, 11, 16, 0, -10), -- 0x77 'w' (1751, 11, 11, 12, 0, -10), -- 0x78 'x' (1767, 11, 16, 11, 0, -10), -- 0x79 'y' (1789, 10, 11, 10, 0, -10), -- 0x7A 'z' (1803, 5, 21, 12, 2, -16), -- 0x7B '{' (1817, 1, 17, 5, 2, -16), -- 0x7C '|' (1820, 5, 21, 12, 5, -15), -- 0x7D '}' (1834, 12, 3, 12, 0, -6)); -- 0x7E '~' Font_D : aliased constant Bitmap_Font := (FreeSerif12pt7bBitmaps'Access, FreeSerif12pt7bGlyphs'Access, 28); Font : constant Giza.Font.Ref_Const := Font_D'Access; end Giza.Bitmap_Fonts.FreeSerif12pt7b;
-- Ada_GUI implementation based on Gnoga. Adapted 2021 -- -- -- GNOGA - The GNU Omnificent GUI for Ada -- -- -- -- G N O G A . G U I . E L E M E N T . M U L T I M E D I A -- -- -- -- S p e c -- -- -- -- -- -- Copyright (C) 2014 David Botton -- -- -- -- This library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU General Public License as published by the -- -- Free Software Foundation; either version 3, or (at your option) any -- -- later version. This library is distributed in the hope that it will be -- -- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are -- -- granted additional permissions described in the GCC Runtime Library -- -- Exception, version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- For more information please go to http://www.gnoga.com -- ------------------------------------------------------------------------------ package Ada_GUI.Gnoga.Gui.Element.Multimedia is ------------------------------------------------------------------------- -- Multimedia_Types ------------------------------------------------------------------------- -- Base type for multimedia Elements type Multimedia_Type is new Gnoga.Gui.Element.Element_Type with private; type Multimedia_Access is access all Multimedia_Type; type Pointer_To_Multimedia_Class is access all Multimedia_Type'Class; ------------------------------------------------------------------------- -- Media_Type - Properties ------------------------------------------------------------------------- procedure Loop_Media (Media : in out Multimedia_Type; Value : in Boolean); function Loop_Media (Media : Multimedia_Type) return Boolean; function Media_Duration (Media : Multimedia_Type) return Float; -- Returns the duration of Media in seconds. procedure Media_Source (Media : in out Multimedia_Type; Source : in String); function Media_Source (Media : Multimedia_Type) return String; -- Returns the URL of the current Media procedure Media_Position (Media : in out Multimedia_Type; Seconds : in Float); function Media_Position (Media : Multimedia_Type) return Float; -- Position of Media in seconds procedure Muted (Media : in out Multimedia_Type; Value : in Boolean); function Muted (Media : Multimedia_Type) return Boolean; function Paused (Media : Multimedia_Type) return Boolean; function Playback_Ended (Media : Multimedia_Type) return Boolean; -- Returns true of Media position has reached end of its duration procedure Playback_Rate (Media : in out Multimedia_Type; Value : in Float); function Playback_Rate (Media : Multimedia_Type) return Float; -- Playback rate. -- Common values - 1.0 normal, 0.5 half speed, -1.0 reverse function Ready_To_Play (Media : Multimedia_Type) return Boolean; -- True if media is ready to be played in element function Seeking (Media : Multimedia_Type) return Boolean; -- True if user is seeking through media subtype Volume_Range is Float range 0.0 .. 1.0; procedure Volume (Media : in out Multimedia_Type; Value : Volume_Range); function Volume (Media : Multimedia_Type) return Volume_Range; -- Media volume (not system volume) in Volume_Range ------------------------------------------------------------------------- -- Media_Type - Methods ------------------------------------------------------------------------- procedure Play (Media : in out Multimedia_Type); procedure Pause (Media : in out Multimedia_Type); procedure Load (Media : in out Multimedia_Type); -- Loads or reloads media function Can_Play (Media : Multimedia_Type; Media_Type : String) return Boolean; -- Returns true if browser claims support of a media type. Browsers -- report possibility but not guarantees of being able to support a -- media type. -- -- Common values: -- video/ogg -- video/mp4 -- video/webm -- audio/mpeg -- audio/ogg -- audio/mp4 -- audio/mp3 -- -- Common values, including codecs: -- video/ogg; codecs="theora, vorbis" -- video/mp4; codecs="avc1.4D401E, mp4a.40.2" -- video/webm; codecs="vp8.0, vorbis" -- audio/ogg; codecs="vorbis" -- audio/mp4; codecs="mp4a.40.5" ------------------------------------------------------------------------- -- Audio_Types ------------------------------------------------------------------------- type Audio_Type is new Multimedia_Type with private; type Audio_Access is access all Audio_Type; type Pointer_To_Audio_Class is access all Audio_Type'Class; ------------------------------------------------------------------------- -- Audio_Type - Creation Methods ------------------------------------------------------------------------- procedure Create (Audio : in out Audio_Type; Parent : in out Gnoga.Gui.Base_Type'Class; Source : in String := ""; Controls : in Boolean := True; Preload : in Boolean := False; Autoplay : in Boolean := False; Autoloop : in Boolean := False; Muted : in Boolean := False; ID : in String := ""); -- Create an Audio control with audio from Content ------------------------------------------------------------------------- -- Video_Types ------------------------------------------------------------------------- type Video_Type is new Multimedia_Type with private; type Video_Access is access all Video_Type; type Pointer_To_Video_Class is access all Video_Type'Class; ------------------------------------------------------------------------- -- Video_Type - Creation Methods ------------------------------------------------------------------------- procedure Create (Video : in out Video_Type; Parent : in out Gnoga.Gui.Base_Type'Class; Source : in String := ""; Controls : in Boolean := True; Preload : in Boolean := False; Poster : in String := ""; Autoplay : in Boolean := False; Autoloop : in Boolean := False; Muted : in Boolean := False; ID : in String := ""); -- Create an Video control with Video from Content. Poster is a URL -- to an image to display until play begins. private type Multimedia_Type is new Gnoga.Gui.Element.Element_Type with null record; type Audio_Type is new Multimedia_Type with null record; type Video_Type is new Multimedia_Type with null record; end Ada_GUI.Gnoga.Gui.Element.Multimedia;
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure aaa_02if is type stringptr is access all char_array; procedure PString(s : stringptr) is begin String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all)); end; function f(i : in Integer) return Boolean is begin if i = 0 then return TRUE; end if; return FALSE; end; begin if f(4) then PString(new char_array'( To_C("true <-" & Character'Val(10) & " ->" & Character'Val(10)))); else PString(new char_array'( To_C("false <-" & Character'Val(10) & " ->" & Character'Val(10)))); end if; PString(new char_array'( To_C("small test end" & Character'Val(10)))); end;
pragma License (Unrestricted); -- extended unit package Ada.Characters.ASCII.Handling is -- There are functions handling only lower-half characters in -- 16#00# .. 16#7F#. pragma Pure; function Is_Control (Item : Character) return Boolean; function Is_Graphic (Item : Character) return Boolean; function Is_Letter (Item : Character) return Boolean; function Is_Lower (Item : Character) return Boolean; function Is_Upper (Item : Character) return Boolean; function Is_Basic (Item : Character) return Boolean renames Is_Letter; function Is_Digit (Item : Character) return Boolean; function Is_Decimal_Digit (Item : Character) return Boolean renames Is_Digit; function Is_Hexadecimal_Digit (Item : Character) return Boolean; function Is_Alphanumeric (Item : Character) return Boolean; function Is_Special (Item : Character) return Boolean; pragma Inline (Is_Graphic); pragma Inline (Is_Lower); pragma Inline (Is_Upper); pragma Inline (Is_Digit); function To_Lower (Item : Character) return Character; function To_Upper (Item : Character) return Character; function To_Basic (Item : Character) return Character; -- extended function To_Case_Folding (Item : Character) return Character renames To_Lower; pragma Inline (To_Basic); function To_Lower (Item : String) return String; function To_Upper (Item : String) return String; function To_Case_Folding (Item : String) return String renames To_Lower; end Ada.Characters.ASCII.Handling;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with System.Storage_Elements; with System.Storage_Pools.Subpools; package Program.Dummy_Subpools is pragma Preelaborate; type Dummy_Storage_Pool is new System.Storage_Pools.Subpools.Root_Storage_Pool_With_Subpools with private; private type Dummy_Subpool is new System.Storage_Pools.Subpools.Root_Subpool with null record; type Dummy_Storage_Pool is new System.Storage_Pools.Subpools.Root_Storage_Pool_With_Subpools with record Last_Subpool : System.Storage_Pools.Subpools.Subpool_Handle; end record; overriding procedure Allocate_From_Subpool (Self : in out Dummy_Storage_Pool; Address : out System.Address; Size : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count; Subpool : not null System.Storage_Pools.Subpools.Subpool_Handle); overriding procedure Deallocate_Subpool (Self : in out Dummy_Storage_Pool; Subpool : in out System.Storage_Pools.Subpools.Subpool_Handle); overriding function Create_Subpool (Self : in out Dummy_Storage_Pool) return not null System.Storage_Pools.Subpools.Subpool_Handle; overriding function Default_Subpool_For_Pool (Self : in out Dummy_Storage_Pool) return not null System.Storage_Pools.Subpools.Subpool_Handle; end Program.Dummy_Subpools;
with Memory.Flash; with Util; use Util; separate (Parser) procedure Parse_Flash(parser : in out Parser_Type; result : out Memory_Pointer) is word_size : Positive := 8; block_size : Positive := 256; read_latency : Time_Type := 10; write_latency : Time_Type := 1000; begin while Get_Type(parser) = Open loop Match(parser, Open); declare name : constant String := Get_Value(parser); begin Match(parser, Literal); declare value : constant String := Get_Value(parser); begin Match(parser, Literal); if name = "word_size" then word_size := Positive'Value(value); elsif name = "block_size" then block_size := Positive'Value(value); elsif name = "read_latency" then read_latency := Time_Type'Value(value); elsif name = "write_latency" then write_latency := Time_Type'Value(value); else Raise_Error(parser, "invalid attribute in flash: " & name); end if; end; end; Match(parser, Close); end loop; result := Memory_Pointer(Flash.Create_Flash(word_size, block_size, read_latency, write_latency)); exception when Data_Error | Constraint_Error => Raise_Error(parser, "invalid value in flash"); end Parse_Flash;
Revert to older code compatible with gcc9 --- gpr/src/gpr-compilation-protocol.adb.orig 2021-05-19 05:22:13 UTC +++ gpr/src/gpr-compilation-protocol.adb @@ -22,7 +22,7 @@ -- -- ------------------------------------------------------------------------------ -with Ada.Calendar.Conversions; use Ada.Calendar; +with Ada.Calendar.Time_Zones; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Characters.Handling; with Ada.Directories; use Ada.Directories; @@ -972,18 +972,29 @@ package body GPR.Compilation.Protocol is procedure Set_File_Stamp (Path_Name : String; Time_Stamp : Time_Stamp_Type) is - function TS (First, Last : Positive) return Integer is - (Integer'Value (String (Time_Stamp (First .. Last)))); - -- Converts substring from Time_Stamp to Integer + use type Time_Zones.Time_Offset; + + TS : constant String (Time_Stamp_Type'Range) := String (Time_Stamp); + + T : constant Time := + Time_Of (Year => Year_Number'Value (TS (1 .. 4)), + Month => Month_Number'Value (TS (5 .. 6)), + Day => Day_Number'Value (TS (7 .. 8)), + Hour => Hour_Number'Value (TS (9 .. 10)), + Minute => Minute_Number'Value (TS (11 .. 12)), + Second => Second_Number'Value (TS (13 .. 14)), + Time_Zone => -Time_Zones.UTC_Time_Offset); + -- Time_Zone is negative to translate the UTC Time_Stamp to local time begin Set_File_Last_Modify_Time_Stamp (Path_Name, - To_Ada - (time_t - (Conversions.To_Unix_Time - (Time_Of - (TS (1, 4), TS (5, 6), TS (7, 8), - TS (9, 10), TS (11, 12), TS (13, 14)))))); + GM_Time_Of + (Year => Formatting.Year (T), + Month => Formatting.Month (T), + Day => Formatting.Day (T), + Hour => Formatting.Hour (T), + Minute => Formatting.Minute (T), + Second => Formatting.Second (T))); end Set_File_Stamp; -----------------------
-- Copyright (c) 2021, Karsten Lueth (kl@kloc-consulting.de) -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -- OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -- WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -- USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. with MicroBit.Display; with MicroBit.I2C; with LSM303AGR; with nRF.Temperature; procedure Read_Temperature is LSM303 : LSM303AGR.LSM303AGR_Accelerometer (MicroBit.I2C.Controller); T : Integer; begin if not MicroBit.I2C.Initialized then MicroBit.I2C.Initialize; end if; LSM303.Configure (Dyna_Range => LSM303AGR.Two_G, Rate => LSM303AGR.Hz_10); LSM303.Enable_Temperature_Sensor (True); loop T := Integer (nRF.Temperature.Read); MicroBit.Display.Display (Integer'Image(T)); T := Integer (LSM303.Read_Temperature); MicroBit.Display.Display ("/" & Integer'Image(T)); end loop; end Read_Temperature;
-- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Tk.Bind.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only with Ada.Environment_Variables; use Ada.Environment_Variables; with Tcl.Variables; use Tcl.Variables; with Tk.MainWindow; use Tk.MainWindow; -- begin read only -- end read only package body Tk.Bind.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only function Wrap_Test_Modifier_Type_Image_4c8acf_353f1d (Modifier: Modifiers_Type) return String is begin declare Test_Modifier_Type_Image_4c8acf_353f1d_Result: constant String := GNATtest_Generated.GNATtest_Standard.Tk.Bind.Modifier_Type_Image (Modifier); begin return Test_Modifier_Type_Image_4c8acf_353f1d_Result; end; end Wrap_Test_Modifier_Type_Image_4c8acf_353f1d; -- end read only -- begin read only procedure Test_Modifier_Type_Image_test_modifier_type_image (Gnattest_T: in out Test); procedure Test_Modifier_Type_Image_4c8acf_353f1d (Gnattest_T: in out Test) renames Test_Modifier_Type_Image_test_modifier_type_image; -- id:2.2/4c8acf146866aa03/Modifier_Type_Image/1/0/test_modifier_type_image/ procedure Test_Modifier_Type_Image_test_modifier_type_image (Gnattest_T: in out Test) is function Modifier_Type_Image (Modifier: Modifiers_Type) return String renames Wrap_Test_Modifier_Type_Image_4c8acf_353f1d; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (Modifier_Type_Image(BUTTON_1) = "Button-1", "Failed to get Image of Modifier_Type."); -- begin read only end Test_Modifier_Type_Image_test_modifier_type_image; -- end read only -- begin read only function Wrap_Test_Key_Syms_Type_Image_c4d722_679161 (Key: Key_Syms) return String is begin declare Test_Key_Syms_Type_Image_c4d722_679161_Result: constant String := GNATtest_Generated.GNATtest_Standard.Tk.Bind.Key_Syms_Type_Image (Key); begin return Test_Key_Syms_Type_Image_c4d722_679161_Result; end; end Wrap_Test_Key_Syms_Type_Image_c4d722_679161; -- end read only -- begin read only procedure Test_Key_Syms_Type_Image_test_key_syms_image (Gnattest_T: in out Test); procedure Test_Key_Syms_Type_Image_c4d722_679161 (Gnattest_T: in out Test) renames Test_Key_Syms_Type_Image_test_key_syms_image; -- id:2.2/c4d7226df5041a94/Key_Syms_Type_Image/1/0/test_key_syms_image/ procedure Test_Key_Syms_Type_Image_test_key_syms_image (Gnattest_T: in out Test) is function Key_Syms_Type_Image(Key: Key_Syms) return String renames Wrap_Test_Key_Syms_Type_Image_c4d722_679161; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (Key_Syms_Type_Image(KEY_SPACE) = "Key-space", "Failed to get image of the space key."); Assert (Key_Syms_Type_Image(SHIFT_KEY_B) = "Key-B", "Failed to get image of the capital B key."); Assert (Key_Syms_Type_Image(SHIFT_KEY_KANA_A) = "Key-kana_A", "Failed to get image of capital kana_a key"); Assert (Key_Syms_Type_Image(KEY_ARABIC_COMMA) = "Key-Arabic_comma", "Failed to get image of arabic comma."); Assert (Key_Syms_Type_Image(SHIFT_KEY_SERBIAN_DJE) = "Key-Serbian_DJE", "Failed to get image for capital Serbian dje key"); Assert (Key_Syms_Type_Image(KEY_CYRILLIC_YU) = "Key-Cyrillic_yu", "Failed to get image of cyrillic yu."); Assert (Key_Syms_Type_Image(SHIFT_KEY_CYRILLIC_YU) = "Key-Cyrillic_YU", "Failed to get image of capital cyrillic yu."); Assert (Key_Syms_Type_Image(SHIFT_KEY_GREEK_ALPHAACCENT) = "Key-Greek_ALPHAaccent", "Failed to get image of capital Greek alpha accent."); Assert (Key_Syms_Type_Image(SHIFT_KEY_GREEK_OMICRONACCENT) = "Key-Greek_OMICRONaccent", "Failed to get image of capital Greek omicron accent."); Assert (Key_Syms_Type_Image(KEY_GREEK_ALPHAACCENT) = "Key-Greek_alphaaccent", "Failed to get image of Greek alpha accent."); Assert (Key_Syms_Type_Image(SHIFT_KEY_GREEK_ALPHA) = "Key-Greek_ALPHA", "Failed to get image of capital Greek alpha."); Assert (Key_Syms_Type_Image(KEY_BACKSPACE) = "Key-Backspace", "Failed to get image of the backspace key."); Assert (Key_Syms_Type_Image(KEY_SCROLL_LOCK) = "Key-Scroll_Lock", "Failed to get image of the scroll lock key."); Assert (Key_Syms_Type_Image(KEY_KANJI) = "Key-Kanji", "Failed to get image of the kanji key."); -- begin read only end Test_Key_Syms_Type_Image_test_key_syms_image; -- end read only -- begin read only procedure Wrap_Test_Tk_Bind_09337a_b9da3f (Window: Tk_Widget; Sequence: Modifiers_Type; Script: Tcl_String; Append: Boolean := False) is begin begin pragma Assert(Window /= Null_Widget and Length(Source => Script) > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(tk-bind.ads:0):Test_Bind test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Tk.Bind.Tk_Bind (Window, Sequence, Script, Append); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(tk-bind.ads:0:):Test_Bind test commitment violated"); end; end Wrap_Test_Tk_Bind_09337a_b9da3f; -- end read only -- begin read only procedure Test_1_Tk_Bind_test_bind(Gnattest_T: in out Test); procedure Test_Tk_Bind_09337a_b9da3f(Gnattest_T: in out Test) renames Test_1_Tk_Bind_test_bind; -- id:2.2/09337ab9ce5ba9c4/Tk_Bind/1/0/test_bind/ procedure Test_1_Tk_Bind_test_bind(Gnattest_T: in out Test) is procedure Tk_Bind (Window: Tk_Widget; Sequence: Modifiers_Type; Script: Tcl_String; Append: Boolean := False) renames Wrap_Test_Tk_Bind_09337a_b9da3f; -- end read only pragma Unreferenced(Gnattest_T); begin if Value("DISPLAY", "")'Length = 0 then Assert(True, "No display, can't test"); return; end if; Tk_Bind(Get_Main_Window, BUTTON_1, To_Tcl_String("exit")); Assert (Tcl_Eval("bind .").Result = "<Button-1>", "Failed to set bind for Tk main window with simple sequence"); -- begin read only end Test_1_Tk_Bind_test_bind; -- end read only -- begin read only procedure Wrap_Test_Tk_Bind_45f058_8585f0 (Window: Tk_Widget; Sequence: Modifiers_Array; Script: Tcl_String; Append: Boolean := False) is begin begin pragma Assert (Window /= Null_Widget and Sequence /= Empty_Modifiers_Array and Length(Source => Script) > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(tk-bind.ads:0):Test_Bind2 test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Tk.Bind.Tk_Bind (Window, Sequence, Script, Append); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(tk-bind.ads:0:):Test_Bind2 test commitment violated"); end; end Wrap_Test_Tk_Bind_45f058_8585f0; -- end read only -- begin read only procedure Test_2_Tk_Bind_test_bind2(Gnattest_T: in out Test); procedure Test_Tk_Bind_45f058_8585f0(Gnattest_T: in out Test) renames Test_2_Tk_Bind_test_bind2; -- id:2.2/45f058fa2634d176/Tk_Bind/0/0/test_bind2/ procedure Test_2_Tk_Bind_test_bind2(Gnattest_T: in out Test) is procedure Tk_Bind (Window: Tk_Widget; Sequence: Modifiers_Array; Script: Tcl_String; Append: Boolean := False) renames Wrap_Test_Tk_Bind_45f058_8585f0; -- end read only pragma Unreferenced(Gnattest_T); begin if Value("DISPLAY", "")'Length = 0 then Assert(True, "No display, can't test"); return; end if; Tk_Bind(Get_Main_Window, (CONTROL, BUTTON_1), To_Tcl_String("exit")); Assert (Tcl_Eval("bind .").Result = "<Control-Button-1> <Button-1>", "Failed to set bind for Tk main window with array sequence"); -- begin read only end Test_2_Tk_Bind_test_bind2; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Tk.Bind.Test_Data.Tests;
pragma License (Unrestricted); -- generalized unit of Ada.Text_IO.Unbounded_IO with Ada.Strings.Generic_Unbounded; generic with package Unbounded_Strings is new Strings.Generic_Unbounded (<>); with procedure Put ( File : File_Type; Item : Unbounded_Strings.String_Type) is <>; with procedure Put_Line ( File : File_Type; Item : Unbounded_Strings.String_Type) is <>; with procedure Get_Line ( File : File_Type; Item : out Unbounded_Strings.String_Type; Last : out Natural) is <>; package Ada.Text_IO.Generic_Unbounded_IO is procedure Put ( File : File_Type; -- Output_File_Type Item : Unbounded_Strings.Unbounded_String); procedure Put ( Item : Unbounded_Strings.Unbounded_String); procedure Put_Line ( File : File_Type; -- Output_File_Type Item : Unbounded_Strings.Unbounded_String); procedure Put_Line ( Item : Unbounded_Strings.Unbounded_String); function Get_Line ( File : File_Type) -- Input_File_Type return Unbounded_Strings.Unbounded_String; function Get_Line return Unbounded_Strings.Unbounded_String; procedure Get_Line ( File : File_Type; -- Input_File_Type Item : out Unbounded_Strings.Unbounded_String); procedure Get_Line ( Item : out Unbounded_Strings.Unbounded_String); end Ada.Text_IO.Generic_Unbounded_IO;
<html> <head> <title>ThaiCreate.Com PHP & MySQL (mysqli)</title> </head> <body> <?php $serverName = "localhost"; $userName = "root"; $userPassword = ""; $dbName = "cookweeb"; $conn = mysqli_connect($serverName,$userName,$userPassword,$dbName); if (mysqli_connect_errno()) { echo "Database Connect Failed : " . mysqli_connect_error(); } else { echo "Database Connected."; } ?> </body> </html>
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Utilities; with Parameters; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package UTL renames Utilities; package PM renames Parameters; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch : supported_arch; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector; flavor : Positive); procedure send (varname : String; crate : list_crate.Map; flavor : Positive); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure print_module (position : string_crate.Cursor); procedure print_verbation (position : string_crate.Cursor); procedure print_if_defined (varname, value : String); procedure dump_list (position : list_crate.Cursor); procedure dump_variant_index (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); procedure dump_makesum (position : string_crate.Cursor); procedure dump_ext_zip (position : string_crate.Cursor); procedure dump_ext_7z (position : string_crate.Cursor); procedure dump_ext_lha (position : string_crate.Cursor); procedure dump_ext_deb (position : string_crate.Cursor); procedure dump_line (position : string_crate.Cursor); procedure dump_extract_head_tail (position : list_crate.Cursor); procedure dump_dirty_extract (position : string_crate.Cursor); procedure dump_standard_target (target : String); procedure dump_opsys_target (target : String); procedure dump_option_target (target : String); procedure dump_broken; procedure dump_catchall; procedure dump_has_configure (value : HT.Text); procedure dump_distname; procedure dump_license; procedure dump_subr; procedure dump_info; procedure dump_conditional_vars; write_to_file : constant Boolean := (output_file /= ""); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure print_if_defined (varname, value : String) is begin if value /= "" then send (varname & LAT.Equals_Sign & value); end if; end print_if_defined; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & "yes"); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector; flavor : Positive) is begin if crate.Is_Empty then return; end if; case flavor is when 1 => send (varname & "=", True); crate.Iterate (Process => print_item'Access); send (""); when 2 => varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); when 3 => crate.Iterate (Process => dump_ext_zip'Access); when 4 => crate.Iterate (Process => dump_ext_7z'Access); when 5 => crate.Iterate (Process => dump_ext_lha'Access); when 7 => crate.Iterate (Process => dump_dirty_extract'Access); when 9 => send (varname & "=", True); crate.Iterate (Process => dump_makesum'Access); send (""); when 10 => send (varname & "=", True); crate.Iterate (Process => print_module'Access); send (""); when 11 => crate.Iterate (Process => dump_ext_deb'Access); when others => raise dev_error; end case; end send; procedure send (varname : String; crate : list_crate.Map; flavor : Positive) is begin varname_prefix := HT.SUS (varname); case flavor is when 1 => crate.Iterate (Process => dump_list'Access); when 6 => crate.Iterate (Process => dump_extract_head_tail'Access); when 8 => crate.Iterate (Process => dump_variant_index'Access); when others => raise dev_error; end case; end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end dump_list; procedure dump_variant_index (position : list_crate.Cursor) is index : String := HT.USS (list_crate.Element (position).group); begin if index = variant then send (HT.USS (varname_prefix) & LAT.Equals_Sign, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end if; end dump_variant_index; procedure dump_extract_head_tail (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin if not list_crate.Element (position).list.Is_Empty then send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end if; end dump_extract_head_tail; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send (" ", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure print_module (position : string_crate.Cursor) is module_w_args : String := HT.USS (string_crate.Element (position)); module : String := HT.part_1 (module_w_args); begin if not passive_uses_module (module) then send (module_w_args & " ", True); end if; end print_module; procedure dump_line (position : string_crate.Cursor) is begin send (HT.USS (string_crate.Element (position))); end dump_line; procedure dump_distfiles (position : string_crate.Cursor) is index : String := HT.int2str (string_crate.To_Index (position)); pload : String := HT.USS (string_crate.Element (position)); NDX : String := HT.USS (varname_prefix) & "_" & index & LAT.Equals_Sign; begin if HT.leads (pload, "generated:") then declare group : String := HT.part_2 (pload, ":"); dlsite : String := HT.USS (specs.dl_sites.Element (HT.SUS (group)).list.First_Element); begin if HT.leads (dlsite, "GITHUB/") or else HT.leads (dlsite, "GITHUB_PRIVATE/") or else HT.leads (dlsite, "GHPRIV/") then send (NDX & generate_github_distfile (dlsite) & ":" & group); return; elsif HT.leads (dlsite, "GITLAB/") then send (NDX & generate_gitlab_distfile (dlsite) & ":" & group); return; elsif HT.leads (dlsite, "CRATES/") then send (NDX & generate_crates_distfile (dlsite) & ":" & group); return; else -- seems like a mistake, fall through null; end if; end; end if; send (NDX & pload); end dump_distfiles; procedure dump_distname is begin if not HT.IsBlank (specs.distname) then send ("DISTNAME", specs.distname); else if HT.equivalent (list_crate.Element (specs.dl_sites.First).group, dlgroup_none) then return; end if; declare first_dlsite : constant String := HT.USS (specs.dl_sites.Element (HT.SUS (dlgroup_main)).list.First_Element); begin if HT.leads (first_dlsite, "GITHUB/") or else HT.leads (first_dlsite, "GITHUB_PRIVATE/") or else HT.leads (first_dlsite, "GHPRIV/") then send ("DISTNAME", generate_github_distname (first_dlsite)); elsif HT.leads (first_dlsite, "GITLAB/") then send ("DISTNAME", generate_gitlab_distname (first_dlsite)); elsif HT.leads (first_dlsite, "CRATES/") then send ("DISTNAME", generate_crates_distname (first_dlsite)); end if; end; end if; end dump_distname; procedure dump_makesum (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin send (HT.int2str (index) & " ", True); end dump_makesum; procedure dump_ext_zip (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo"); send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}"); end dump_ext_zip; procedure dump_ext_7z (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=7z x -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_7z; procedure dump_ext_lha (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_lha; procedure dump_ext_deb (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=ar -x"); send ("EXTRACT_TAIL_" & N & "=&& ${TAR} -xf data.tar.*"); end dump_ext_deb; procedure dump_dirty_extract (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("DIRTY_EXTRACT_" & N & "=yes"); end dump_dirty_extract; procedure dump_standard_target (target : String) is target_text : HT.Text := HT.SUS (target); begin if specs.make_targets.Contains (target_text) then send (""); send (target & LAT.Colon); specs.make_targets.Element (target_text).list.Iterate (Process => dump_line'Access); end if; end dump_standard_target; procedure dump_opsys_target (target : String) is os_target : HT.Text := HT.SUS (target & LAT.Hyphen & UTL.lower_opsys (opsys)); std_target : String := target & "-opsys"; begin if specs.make_targets.Contains (os_target) then send (""); send (std_target & LAT.Colon); send (LAT.HT & "# " & UTL.mixed_opsys (opsys) & "-specific"); specs.make_targets.Element (os_target).list.Iterate (Process => dump_line'Access); end if; end dump_opsys_target; procedure dump_option_target (target : String) is procedure precheck (position : string_crate.Cursor); procedure check (position : string_crate.Cursor); -- Logic: considered "used" if option is OFF and <target>-<OPTION NAME>-OFF is set. -- vice versa with "ON" -- Iterate for each option. -- If precheck indicates use, iterate again with check to write out the target. target_used : Boolean := False; std_target : String := target & "-option"; procedure precheck (position : string_crate.Cursor) is base : String := HT.USS (string_crate.Element (position)); WON : HT.Text := HT.SUS (target & "-" & base & "-ON"); WOFF : HT.Text := HT.SUS (target & "-" & base & "-OFF"); opt_on : Boolean := specs.option_current_setting (base); begin if not target_used then if opt_on then if specs.make_targets.Contains (WON) then target_used := True; end if; else if specs.make_targets.Contains (WOFF) then target_used := True; end if; end if; end if; end precheck; procedure check (position : string_crate.Cursor) is base : String := HT.USS (string_crate.Element (position)); WON : HT.Text := HT.SUS (target & "-" & base & "-ON"); WOFF : HT.Text := HT.SUS (target & "-" & base & "-OFF"); opt_on : Boolean := specs.option_current_setting (base); begin if opt_on then if specs.make_targets.Contains (WON) then send (LAT.HT & "# " & base & " option ON"); specs.make_targets.Element (WON).list.Iterate (Process => dump_line'Access); end if; else if specs.make_targets.Contains (WOFF) then send (LAT.HT & "# " & base & " option OFF"); specs.make_targets.Element (WOFF).list.Iterate (Process => dump_line'Access); end if; end if; end check; begin specs.ops_avail.Iterate (Process => precheck'Access); if target_used then send (""); send (std_target & LAT.Colon); specs.ops_avail.Iterate (Process => check'Access); end if; end dump_option_target; procedure dump_broken is procedure precheck (position : list_crate.Cursor); procedure check (position : list_crate.Cursor); procedure send_prefix (reason_number : Natural); procedure send_reason (reason_number : Natural; reason : String); num_reasons : Natural := 0; curnum : Natural := 1; cpu_ia64 : constant String := UTL.cpu_arch (x86_64) & "_"; cpu_ia32 : constant String := UTL.cpu_arch (i386) & "_"; cpu_armv8 : constant String := UTL.cpu_arch (aarch64) & "_"; separator : constant String := ": "; varname : constant String := "IGNORE="; procedure precheck (position : list_crate.Cursor) is procedure precheck_list (position : string_crate.Cursor); broken_Key : String := HT.USS (list_crate.Element (position).group); procedure precheck_list (position : string_crate.Cursor) is begin if broken_Key = broken_all then num_reasons := num_reasons + 1; end if; end precheck_list; begin list_crate.Element (position).list.Iterate (Process => precheck_list'Access); end precheck; procedure check (position : list_crate.Cursor) is procedure check_list (position : string_crate.Cursor); broken_Key : String := HT.USS (list_crate.Element (position).group); procedure check_list (position : string_crate.Cursor) is reason : String := HT.USS (string_crate.Element (position)); used : Boolean := False; begin if broken_Key = broken_all then send_prefix (curnum); send_reason (curnum, reason); curnum := curnum + 1; end if; end check_list; begin list_crate.Element (position).list.Iterate (Process => check_list'Access); end check; procedure send_prefix (reason_number : Natural) is begin if num_reasons > 1 then send ("[Reason " & HT.int2str (reason_number) & "] ", True); end if; end send_prefix; procedure send_reason (reason_number : Natural; reason : String) is begin if reason_number = num_reasons then send (reason); else send (reason & " \"); end if; end send_reason; begin specs.broken.Iterate (Process => precheck'Access); if num_reasons > 0 then if num_reasons > 1 then send (varname & "\"); else send (varname, True); end if; specs.broken.Iterate (Process => check'Access); end if; end dump_broken; procedure dump_has_configure (value : HT.Text) is valuestr : String := HT.USS (value); begin if valuestr = boolean_yes then send ("HAS_CONFIGURE=yes"); elsif valuestr = "gnu" then send ("GNU_CONFIGURE=yes"); end if; end dump_has_configure; procedure dump_catchall is procedure dump_group (position : list_crate.Cursor); procedure dump_nv (position : string_crate.Cursor); key_text : HT.Text; procedure dump_group (position : list_crate.Cursor) is rec : group_list renames list_crate.Element (position); begin key_text := rec.group; rec.list.Iterate (dump_nv'Access); end dump_group; procedure dump_nv (position : string_crate.Cursor) is text_value : HT.Text renames string_crate.Element (position); nvkey : constant String := HT.USS (key_text); begin if nvkey = "CC" or else nvkey = "CXX" or else nvkey = "CPP" then send (nvkey & "=" & HT.USS (text_value)); else send (nvkey & "+=" & HT.USS (text_value)); end if; end dump_nv; begin specs.catch_all.Iterate (dump_group'Access); end dump_catchall; procedure dump_info is procedure scan (position : string_crate.Cursor); procedure print (position : list_crate.Cursor); tempstore : list_crate.Map; procedure scan (position : string_crate.Cursor) is procedure update (Key : HT.Text; Element : in out group_list); value : String := HT.USS (string_crate.Element (position)); newkey : HT.Text := HT.SUS (HT.part_1 (value, ":")); newval : HT.Text := HT.SUS (HT.part_2 (value, ":")); procedure update (Key : HT.Text; Element : in out group_list) is begin Element.list.Append (newval); end update; begin if not tempstore.Contains (newkey) then declare newrec : group_list; begin newrec.group := newkey; tempstore.Insert (newkey, newrec); end; end if; tempstore.Update_Element (Position => tempstore.Find (newkey), Process => update'Access); end scan; procedure print (position : list_crate.Cursor) is procedure print_page (position : string_crate.Cursor); rec : group_list renames list_crate.Element (position); procedure print_page (position : string_crate.Cursor) is begin send (" " & HT.USS (string_crate.Element (position)), True); end print_page; begin send ("INFO_" & HT.USS (rec.group) & LAT.Equals_Sign, True); rec.list.Iterate (print_page'Access); send (""); end print; begin specs.info.Iterate (scan'Access); tempstore.Iterate (print'Access); end dump_info; procedure dump_conditional_vars is procedure print_var (position : string_crate.Cursor); key_opsys : HT.Text := HT.SUS (UTL.lower_opsys (opsys)); key_arch : HT.Text := HT.SUS (UTL.cpu_arch (arch)); procedure print_var (position : string_crate.Cursor) is full : String := HT.USS (string_crate.Element (position)); varname : String := HT.part_1 (full, "="); varval : String := HT.part_2 (full, "="); begin if varname = "MAKEFILE_LINE" then send (varval); else send (varname & "+=" & varval); end if; end print_var; begin if specs.var_opsys.Contains (key_opsys) then specs.var_opsys.Element (key_opsys).list.Iterate (print_var'Access); end if; if specs.var_arch.Contains (key_arch) then specs.var_arch.Element (key_arch).list.Iterate (print_var'Access); end if; end dump_conditional_vars; procedure dump_license is procedure dump_lic_terms (position : string_crate.Cursor); procedure dump_lic_file (position : string_crate.Cursor); procedure dump_lic_awk (position : string_crate.Cursor); procedure dump_lic_source (position : string_crate.Cursor); procedure dump_spkg_licenses (position : string_crate.Cursor); procedure dump_lic_terms (position : string_crate.Cursor) is value : String := HT.USS (string_crate.Element (position)); spkg : String := HT.part_1 (value, ":"); path : String := HT.part_2 (value, ":"); begin send ("LICENSE_TERMS_" & spkg & " = " & path); end dump_lic_terms; procedure dump_lic_file (position : string_crate.Cursor) is value : String := HT.USS (string_crate.Element (position)); lic : String := HT.part_1 (value, ":"); path : String := HT.part_2 (value, ":"); begin send ("LICENSE_FILE_" & lic & " = " & path); end dump_lic_file; procedure dump_lic_awk (position : string_crate.Cursor) is value : String := HT.USS (string_crate.Element (position)); lic : String := HT.part_1 (value, ":"); delim : String (1 .. 1) := (others => LAT.Quotation); code : String := HT.specific_field (HT.part_2 (value, ":"), 2, delim); begin send ("LICENSE_AWK_" & lic & " = " & code); end dump_lic_awk; procedure dump_lic_source (position : string_crate.Cursor) is value : String := HT.USS (string_crate.Element (position)); lic : String := HT.part_1 (value, ":"); path : String := HT.part_2 (value, ":"); begin send ("LICENSE_SOURCE_" & lic & " = " & path); end dump_lic_source; procedure dump_spkg_licenses (position : string_crate.Cursor) is procedure search (name_pos : string_crate.Cursor); value : String := HT.USS (string_crate.Element (position)); lic : String := HT.part_1 (value, ":"); spkg : String := HT.part_2 (value, ":"); LNAME : String := "LICENSE_NAME_" & lic & " = "; ltype : license_type := determine_license (lic); cname : HT.Text; procedure search (name_pos : string_crate.Cursor) is inner_value : String := HT.USS (string_crate.Element (name_pos)); inner_lic : String := HT.part_1 (inner_value, ":"); inner_desc : String := HT.part_2 (inner_value, ":"); begin if inner_lic = lic then cname := HT.SUS (HT.specific_field (inner_desc, 2, "" & LAT.Quotation)); end if; end search; begin send ("LICENSE_" & spkg & " += " & lic); case ltype is when CUSTOM1 | CUSTOM2 | CUSTOM3 | CUSTOM4 => specs.lic_names.Iterate (search'Access); send (LNAME & HT.USS (cname)); when others => send (LNAME & standard_license_names (ltype)); end case; end dump_spkg_licenses; begin if specs.licenses.Is_Empty and then specs.lic_terms.Is_Empty then return; else send ("LICENSE_SET=yes"); end if; send ("LICENSE_SCHEME=" & HT.USS (specs.lic_scheme)); specs.lic_terms.Iterate (dump_lic_terms'Access); specs.lic_files.Iterate (dump_lic_file'Access); specs.lic_awk.Iterate (dump_lic_awk'Access); specs.lic_source.Iterate (dump_lic_source'Access); specs.licenses.Iterate (dump_spkg_licenses'Access); end dump_license; procedure dump_subr is procedure dump_script (position : string_crate.Cursor); procedure dump_script (position : string_crate.Cursor) is value : String := HT.USS (string_crate.Element (position)); filename : String := HT.part_1 (value, ":"); subpkg : String := HT.part_2 (value, ":"); begin send ("RC_SUBR_" & subpkg & " += " & filename); end dump_script; begin specs.subr_scripts.Iterate (dump_script'Access); end dump_subr; procedure print_verbation (position : string_crate.Cursor) is begin send (HT.USS (string_crate.Element (position)), False); end print_verbation; begin if not specs.variant_exists (variant) then TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!"); return; end if; if write_to_file then TIO.Create (File => makefile_handle, Mode => TIO.Out_File, Name => output_file); end if; -- The pkg manifests did use many of these, but they will be generated by ravenadm send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF); send ("NAMEBASE", HT.USS (specs.namebase)); send ("VERSION", HT.USS (specs.version)); send ("REVISION", specs.revision, 0); send ("EPOCH", specs.epoch, 0); send ("VARIANT", variant); send ("DL_SITES", specs.dl_sites, 1); send ("DISTFILE", specs.distfiles, 2); send ("DIST_SUBDIR", specs.dist_subdir); dump_distname; send ("MAKESUM_INDEX", specs.distfiles, 9); send ("PF_INDEX", specs.patchfiles, 1); send ("DF_INDEX", specs.df_index, 1); send ("SUBPACKAGES", specs.subpackages, 8); send ("EXTRACT_ONLY", specs.extract_only, 1); send ("DIRTY_EXTRACT", specs.extract_dirty, 7); send ("ZIP-EXTRACT", specs.extract_zip, 3); send ("7Z-EXTRACT", specs.extract_7z, 4); send ("LHA-EXTRACT", specs.extract_lha, 5); send ("DEB-EXTRACT", specs.extract_deb, 11); send ("EXTRACT_HEAD", specs.extract_head, 6); send ("EXTRACT_TAIL", specs.extract_tail, 6); dump_broken; send ("USERS", specs.users, 1); send ("GROUPS", specs.groups, 1); send ("USES", specs.uses, 10); dump_license; print_if_defined ("PREFIX", HT.USS (specs.prefix)); dump_info; dump_catchall; send ("NO_CCACHE", specs.skip_ccache, True); send ("PATCH_WRKSRC", specs.patch_wrksrc); send ("PATCH_STRIP", specs.patch_strip, 1); send ("PATCH_DIST_STRIP", specs.pfiles_strip, 1); dump_has_configure (specs.config_must); send ("GNU_CONFIGURE_PREFIX", specs.config_prefix); send ("CONFIGURE_OUTSOURCE", specs.config_outsrc, True); send ("CONFIGURE_WRKSRC", specs.config_wrksrc); send ("CONFIGURE_SCRIPT", specs.config_script); send ("CONFIGURE_TARGET", specs.config_target); send ("CONFIGURE_ARGS", specs.config_args, 1); send ("CONFIGURE_ENV", specs.config_env, 1); send ("NO_BUILD", specs.skip_build, True); send ("BUILD_WRKSRC", specs.build_wrksrc); send ("BUILD_TARGET", specs.build_target, 1); send ("NO_INSTALL", specs.skip_install, True); send ("INSTALL_REQ_TOOLCHAIN", specs.shift_install, True); send ("INSTALL_WRKSRC", specs.install_wrksrc); send ("INSTALL_TARGET", specs.install_tgt, 1); send ("SOVERSION", specs.soversion); send ("PLIST_SUB", specs.plist_sub, 1); send ("SUB_FILES", specs.sub_files, 1); send ("SUB_LIST", specs.sub_list, 1); send ("MANDIRS", specs.mandirs, 1); send ("MAKEFILE", specs.makefile); send ("MAKE_ENV", specs.make_env, 1); send ("MAKE_ARGS", specs.make_args, 1); send ("OPTIMIZER_LEVEL", specs.optimizer_lvl, 2); send ("WITH_DEBUG", specs.debugging_on, True); send ("CFLAGS", specs.cflags, 1); send ("CXXFLAGS", specs.cxxflags, 1); send ("CPPFLAGS", specs.cppflags, 1); send ("LDFLAGS", specs.ldflags, 1); send ("CMAKE_ARGS", specs.cmake_args, 1); send ("QMAKE_ARGS", specs.qmake_args, 1); dump_conditional_vars; send ("SINGLE_JOB", specs.single_job, True); send ("DESTDIR_VIA_ENV", specs.destdir_env, True); send ("DESTDIRNAME", specs.destdirname); send ("TEST_TARGET", specs.test_tgt, 1); send ("TEST_ARGS", specs.test_args, 1); send ("TEST_ENV", specs.test_env, 1); send ("GENERATED", specs.generated, True); send ("PHP_EXTENSIONS", specs.php_extensions, 1); send ("CARGO_SKIP_CONFIGURE", specs.cgo_skip_conf, True); send ("CARGO_SKIP_BUILD", specs.cgo_skip_build, True); send ("CARGO_SKIP_INSTALL", specs.cgo_skip_inst, True); send ("CARGO_CONFIG_ARGS", specs.cgo_conf_args, 1); send ("CARGO_BUILD_ARGS", specs.cgo_build_args, 1); send ("CARGO_INSTALL_ARGS", specs.cgo_inst_args, 1); send ("CARGO_FEATURES", specs.cgo_features, 1); send ("CARGO_CARGOLOCK", specs.cgo_cargolock); send ("CARGO_CARGOTOML", specs.cgo_cargotoml); send ("CARGO_CARGO_BIN", specs.cgo_cargo_bin); send ("CARGO_TARGET_DIR", specs.cgo_target_dir); send ("CARGO_VENDOR_DIR", specs.cgo_vendor_dir); if specs.job_limit > 0 and then specs.job_limit < Natural (PM.configuration.jobs_limit) then send ("MAKE_JOBS_NUMBER_LIMIT", specs.job_limit, 0); end if; dump_subr; specs.mk_verbatim.Iterate (print_verbation'Access); declare function get_phasestr (index : Positive) return String; function get_prefix (index : Positive) return String; function get_phasestr (index : Positive) return String is begin case index is when 1 => return "fetch"; when 2 => return "extract"; when 3 => return "patch"; when 4 => return "configure"; when 5 => return "build"; when 6 => return "install"; when 7 => return "stage"; when 8 => return "test"; when others => return ""; end case; end get_phasestr; function get_prefix (index : Positive) return String is begin case index is when 1 => return "pre-"; when 2 => return "do-"; when 3 => return "post-"; when others => return ""; end case; end get_prefix; begin for phase in Positive range 1 .. 8 loop for prefix in Positive range 1 .. 3 loop declare target : String := get_prefix (prefix) & get_phasestr (phase); begin dump_standard_target (target); dump_opsys_target (target); dump_option_target (target); end; end loop; end loop; end; handle_github_relocations (specs, makefile_handle); send (LAT.LF & ".include " & LAT.Quotation & "/xports/Mk/raven.mk" & LAT.Quotation); if write_to_file then TIO.Close (makefile_handle); end if; exception when others => if TIO.Is_Open (makefile_handle) then TIO.Close (makefile_handle); end if; end generator; -------------------------------------------------------------------------------------------- -- generate_github_distfile -------------------------------------------------------------------------------------------- function generate_github_distname (download_site : String) return String is gh_args : constant String := HT.part_2 (download_site, "/"); num_colons : constant Natural := HT.count_char (gh_args, LAT.Colon); begin if num_colons < 2 then -- NOT EXPECTED!!! give garbage so maintainer notices and fixes it return gh_args; end if; declare proj : constant String := HT.specific_field (gh_args, 2, ":"); vers : constant String := HT.replace_all (S => HT.specific_field (gh_args, 3, ":"), reject => LAT.Plus_Sign, shiny => LAT.Hyphen); begin if vers (vers'First) = 'v' then return proj & LAT.Hyphen & vers (vers'First + 1 .. vers'Last); else return proj & LAT.Hyphen & vers; end if; end; end generate_github_distname; -------------------------------------------------------------------------------------------- -- generate_gitlab_distname -------------------------------------------------------------------------------------------- function generate_gitlab_distname (download_site : String) return String is lab_args : constant String := HT.part_2 (download_site, "/"); num_colons : constant Natural := HT.count_char (lab_args, LAT.Colon); begin if num_colons < 2 then -- NOT EXPECTED!!! give garbage so maintainer notices and fixes it return lab_args; end if; -- So far gitlab doesn't seem to transform tags like github does, so keep the -- leading 'v' and '+' characters until this is proven wrong. declare proj : constant String := HT.specific_field (lab_args, 2, ":"); vers : constant String := HT.specific_field (lab_args, 3, ":"); begin return proj & LAT.Hyphen & vers; end; end generate_gitlab_distname; -------------------------------------------------------------------------------------------- -- generate_crates_distname -------------------------------------------------------------------------------------------- function generate_crates_distname (download_site : String) return String is url_args : constant String := HT.part_2 (download_site, "/"); num_colons : constant Natural := HT.count_char (url_args, LAT.Colon); begin if num_colons < 1 then -- NOT EXPECTED!!! give garbage so maintainer notices and fixes it return url_args; end if; declare proj : constant String := HT.specific_field (url_args, 1, ":"); vers : constant String := HT.specific_field (url_args, 2, ":"); begin return proj & LAT.Hyphen & vers; end; end generate_crates_distname; -------------------------------------------------------------------------------------------- -- handle_github_relocations -------------------------------------------------------------------------------------------- procedure handle_github_relocations (specs : Portspecs; makefile : TIO.File_Type) is procedure send (data : String); procedure filter_to_generated (position : string_crate.Cursor); procedure check_for_generated (position : string_crate.Cursor); procedure check_for_generated_shift (position : string_crate.Cursor); procedure check_for_generated_crate (position : string_crate.Cursor); target_set : Boolean := False; shift_tgt_set : Boolean := False; crate_tgt_set : Boolean := False; write_to_file : Boolean := (TIO.Is_Open (makefile)); genfile_list : string_crate.Vector; procedure send (data : String) is begin if write_to_file then TIO.Put_Line (makefile, data); else TIO.Put_Line (data); end if; end send; procedure check_for_generated (position : string_crate.Cursor) is pload : String := HT.USS (string_crate.Element (position)); begin declare group : HT.Text := HT.SUS (HT.part_2 (pload, ":")); dlsite : String := HT.USS (specs.dl_sites.Element (group).list.First_Element); gh_args : String := HT.part_2 (dlsite, "/"); num_colons : constant Natural := HT.count_char (gh_args, LAT.Colon); begin if not HT.leads (dlsite, "GITHUB/") and then not HT.leads (dlsite, "GITHUB_PRIVATE/") and then not HT.leads (dlsite, "GHPRIV/") and then not HT.leads (dlsite, "GITLAB/") then return; end if; if num_colons < 3 then -- It's a github site, but there's no extraction wrksrc override return; end if; if HT.specific_field (gh_args, 4, ":") = "" then -- The extraction field is blank (usually seen with private github repositories -- So no extraction override in this case either return; end if; if not target_set then send (LAT.LF & "github-relocation:"); target_set := True; end if; send (LAT.HT & "# relocate " & HT.specific_field (gh_args, 1, ":") & "/" & HT.specific_field (gh_args, 2, ":") & " project"); declare reldir : constant String := HT.specific_field (gh_args, 4, ":"); extractdir : constant String := HT.replace_all (S => generate_github_distname (dlsite), reject => LAT.Colon, shiny => LAT.Hyphen); begin send (LAT.HT & "@${RM} -r ${WRKSRC}/" & reldir & LAT.LF & LAT.HT & "@${ECHO_MSG} " & LAT.Quotation & "==> Relocating " & extractdir & " to WRKSRC/" & reldir & LAT.Quotation & LAT.LF & LAT.HT & "@${MV} ${WRKDIR}/" & extractdir & " ${WRKSRC}/" & reldir & LAT.LF & LAT.HT & "@${LN} -s ${WRKSRC:T}/" & reldir & " ${WRKDIR}/" & extractdir); end; end; end check_for_generated; procedure check_for_generated_shift (position : string_crate.Cursor) is pload : String := HT.USS (string_crate.Element (position)); begin declare group : HT.Text := HT.SUS (HT.part_2 (pload, ":")); dlsite : String := HT.USS (specs.dl_sites.Element (group).list.First_Element); gh_args : String := HT.part_2 (dlsite, "/"); num_colons : constant Natural := HT.count_char (gh_args, LAT.Colon); begin if not HT.leads (dlsite, "GITHUB_PRIVATE/") and then not HT.leads (dlsite, "GHPRIV/") and then not HT.leads (dlsite, "GITLAB/") then return; end if; if num_colons < 2 then return; end if; -- Gitlab and github private use full hashes in the tarball regardless of the -- reference used to generate it. Thus it's cleanest if we can shift it's location -- to the normal $WRKSRC location after extraction. if not shift_tgt_set then send (LAT.LF & "shift-wrksrc:"); shift_tgt_set := True; end if; declare account : constant String := HT.specific_field (gh_args, 1, ":"); project : constant String := HT.specific_field (gh_args, 2, ":"); taghash : constant String := HT.specific_field (gh_args, 3, ":"); wrksrc : constant String := "${WRKDIR}/" & project & "-" & taghash; begin send (LAT.HT & "# redefine " & account & "/" & project & " work directory"); if HT.leads (dlsite, "GITLAB/") then send (LAT.HT & "@${MV} ${WRKDIR}/" & project & "-* " & wrksrc); else -- GITHUB_PRIVATE, GHPRIV send (LAT.HT & "@${MV} ${WRKDIR}/" & account & "-" & project & "-* " & wrksrc); end if; end; end; end check_for_generated_shift; procedure check_for_generated_crate (position : string_crate.Cursor) is pload : String := HT.USS (string_crate.Element (position)); begin declare group : HT.Text := HT.SUS (HT.part_2 (pload, ":")); dlsite : String := HT.USS (specs.dl_sites.Element (group).list.First_Element); url_args : String := HT.part_2 (dlsite, "/"); crate : constant String := HT.replace_char (url_args, ':', "-"); num_colons : constant Natural := HT.count_char (url_args, LAT.Colon); begin if not HT.leads (dlsite, "CRATES/") then return; end if; if num_colons < 1 then return; end if; if not crate_tgt_set then crate_tgt_set := True; send (LAT.LF & "crate-relocation:"); send (LAT.HT & "@${ECHO_MSG} " & LAT.Quotation & "===> Moving crates to ${CARGO_VENDOR_DIR}" & LAT.Quotation); send (LAT.HT & "@${MKDIR} ${CARGO_VENDOR_DIR}"); end if; send (LAT.LF & LAT.HT & "# relocate " & crate & " crate"); send (LAT.HT & "@${MV} ${WRKDIR}/" & crate & " ${CARGO_VENDOR_DIR}/" & crate); send (LAT.HT & "@${PRINTF} '{" & LAT.Quotation & "package" & LAT.Quotation & ":" & LAT.Quotation & "%s" & LAT.Quotation & "," & LAT.Quotation & "files" & LAT.Quotation & ":{}}' $$(${SHA256} -q ${DISTDIR}/${DIST_SUBDIR}/" & crate & ".tar.gz) > ${CARGO_VENDOR_DIR}/" & crate & "/.cargo-checksum.json"); end; end check_for_generated_crate; procedure filter_to_generated (position : string_crate.Cursor) is pload : HT.Text renames string_crate.Element (position); begin if HT.leads (pload, "generated:") then genfile_list.Append (pload); end if; end filter_to_generated; begin specs.distfiles.Iterate (filter_to_generated'Access); genfile_list.Iterate (check_for_generated'Access); genfile_list.Iterate (check_for_generated_shift'Access); genfile_list.Iterate (check_for_generated_crate'Access); end handle_github_relocations; -------------------------------------------------------------------------------------------- -- standard_license_names -------------------------------------------------------------------------------------------- function standard_license_names (license : license_type) return String is AGPL : constant String := "GNU Affero General Public License version "; GPL : constant String := "GNU General Public License version "; LGPL : constant String := "GNU Library General Public License version "; RLE3 : constant String := "GNU GPL version 3 Runtime Library Exception"; AL : constant String := "Apache License "; ART : constant String := "Artistic License version "; later : constant String := " or later"; CCA : constant String := "Creative Commons Attribution "; begin case license is when CUSTOM1 | CUSTOM2 | CUSTOM3 | CUSTOM4 => return "Don't use for custom licenses"; when INVALID => return "error, invalid license"; when AFL => return "Academic Free License 3.0"; when AGPLv3 => return AGPL & "3"; when AGPLv3x => return AGPL & "3" & later; when APACHE10 => return AL & "1.0"; when APACHE11 => return AL & "1.1"; when APACHE20 => return AL & "2.0"; when ART10 => return ART & "1.0"; when ART20 => return ART & "2.0"; when ARTPERL10 => return "Artistic License (perl) version 1.0"; when BSD2CLAUSE => return "BSD 2-clause 'Simplified' License"; when BSD3CLAUSE => return "BSD 3-clause 'New' or 'Revised' License"; when BSD4CLAUSE => return "BSD 4-clause 'Original' or 'Old' License"; when BSDGROUP => return "BSD, check license for number of clauses"; when CC0_10 => return "Creative Commons Zero v1.0 Universal"; when CC_30 => return CCA & "3.0"; when CC_40 => return CCA & "4.0"; when CC_NC_30 => return CCA & "Non-Commercial 3.0"; when CC_NC_40 => return CCA & "Non-Commercial 4.0"; when CC_NCND_30 => return CCA & "Non-Commercial No Derivatives 3.0"; when CC_NCND_40 => return CCA & "Non-Commercial No Derivatives 4.0"; when CC_NCSA_30 => return CCA & "Non-Commercial Share-Alike 3.0"; when CC_NCSA_40 => return CCA & "Non-Commercial Share-Alike 4.0"; when CC_ND_30 => return CCA & "No Derivatives 3.0"; when CC_ND_40 => return CCA & "No Derivatives 4.0"; when CC_SA_30 => return CCA & "Share-Alike 3.0"; when CC_SA_40 => return CCA & "Share-Alike 4.0"; when CDDL => return "Common Development and Distribution License 1.0"; when GFDL => return "GNU Free Documentation License"; when GMGPL => return "GNAT Modified General Public License (v2)"; when GMGPL3 => return "GNAT Modified General Public License (v3)"; when GPLv1 => return GPL & "1"; when GPLv1x => return GPL & "1" & later; when GPLv2 => return GPL & "2"; when GPLv2x => return GPL & "2" & later; when GPLv3 => return GPL & "3"; when GPLv3x => return GPL & "3" & later; when GPLv3RLE => return RLE3; when GPLv3RLEx => return RLE3 & later; when HPND => return "Historical Permission Notice and Disclaimer"; when LGPL20 => return LGPL & "2.0"; when LGPL20x => return LGPL & "2.0" & later; when LGPL21 => return LGPL & "2.1"; when LGPL21x => return LGPL & "2.1" & later; when LGPL3 => return LGPL & "3.0"; when LGPL3x => return LGPL & "3.0" & later; when ISCL => return "Internet Systems Consortium License"; when MIT => return "MIT license / X11 license"; when MPL => return "Mozilla Public License"; when PUBDOM => return "Public Domain"; when OPENSSL => return "OpenSSL License"; when POSTGRESQL => return "PostgreSQL Licence"; when PSFL => return "Python Software Foundation License"; when RUBY => return "Ruby License"; when ZLIB => return "zlib License"; end case; end standard_license_names; -------------------------------------------------------------------------------------------- -- passive_uses_module -------------------------------------------------------------------------------------------- function passive_uses_module (value : String) return Boolean is -- Some modules are implemented entirely in ravenadm, so don't output them -- to the makefile which add unnecessary includes commands. total_modules : constant Positive := 26; subtype uses_string is String (1 .. 13); -- Keep in alphabetical order for future conversion to binary search all_keywords : constant array (1 .. total_modules) of uses_string := ( "ada ", "bison ", "bz2 ", "c++ ", "cclibs ", "compiler ", "cpe ", "execinfo ", "expat ", "fortran ", "gettext-tools", "gif ", "gprbuild ", "jpeg ", "lz4 ", "lzo ", "makeinfo ", "mesa ", "pcre ", "pkgconfig ", "png ", "readline ", "sqlite ", "tiff ", "zlib ", "zstd " ); bandolier : uses_string := (others => ' '); begin declare module : String := HT.part_1 (value, ":"); begin if module'Length > uses_string'Length then return False; end if; bandolier (1 .. module'Length) := module; end; for index in all_keywords'Range loop if all_keywords (index) = bandolier then return True; end if; end loop; return False; end passive_uses_module; end Port_Specification.Makefile;
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure record2 is type stringptr is access all char_array; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; procedure SkipSpaces is C : Character; Eol : Boolean; begin loop Look_Ahead(C, Eol); exit when Eol or C /= ' '; Get(C); end loop; end; type toto; type toto_PTR is access toto; type toto is record foo : Integer; bar : Integer; blah : Integer; end record; function mktoto(v1 : in Integer) return toto_PTR is t : toto_PTR; begin t := new toto; t.foo := v1; t.bar := 0; t.blah := 0; return t; end; function result(t : in toto_PTR) return Integer is begin t.blah := t.blah + 1; return t.foo + t.blah * t.bar + t.bar * t.foo; end; t : toto_PTR; begin t := mktoto(4); Get(t.bar); SkipSpaces; Get(t.blah); PInt(result(t)); end;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- ADA.NUMERICS.GENERIC_ELEMENTARY_FUNCTIONS -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2014, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This is the Ada Cert Math specific version of a-ngelfu.adb -- This body does not implement Ada.Numerics.Generic_Elementary_Functions as -- defined by the standard. See the package specification for more details. with Ada.Numerics.Elementary_Functions; with Ada.Numerics.Long_Elementary_Functions; with Ada.Numerics.Long_Long_Elementary_Functions; use Ada.Numerics.Elementary_Functions; use Ada.Numerics.Long_Elementary_Functions; use Ada.Numerics.Long_Long_Elementary_Functions; package body Ada.Numerics.Generic_Elementary_Functions with SPARK_Mode is subtype T is Float_Type'Base; subtype F is Float; subtype LF is Long_Float; subtype LLF is Long_Long_Float; Is_Float : constant Boolean := T'Machine_Mantissa = Float'Machine_Mantissa and then Float (T'First) = Float'First and then Float (T'Last) = Float'Last; Is_Long_Float : constant Boolean := T'Machine_Mantissa = Long_Float'Machine_Mantissa and then Long_Float (T'First) = Long_Float'First and then Long_Float (T'Last) = Long_Float'Last; Is_Long_Long_Float : constant Boolean := not (T'Machine_Mantissa = Long_Float'Machine_Mantissa) and then T'Machine_Mantissa = Long_Long_Float'Machine_Mantissa and then Long_Long_Float (T'First) = Long_Long_Float'First and then Long_Long_Float (T'Last) = Long_Long_Float'Last; ---------- -- "**" -- ---------- function "**" (Left, Right : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (F (Left) ** F (Right)) elsif Is_Long_Float then T (LF (Left) ** LF (Right)) elsif Is_Long_Long_Float then T (LLF (Left) ** LLF (Right)) else raise Program_Error); ------------ -- Arccos -- ------------ -- Natural cycle function Arccos (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arccos (F (X))) elsif Is_Long_Float then T (Arccos (LF (X))) elsif Is_Long_Long_Float then T (Arccos (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Arccos (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arccos (F (X), F (Cycle))) elsif Is_Long_Float then T (Arccos (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Arccos (LLF (X), LLF (Cycle))) else raise Program_Error); ------------- -- Arccosh -- ------------- function Arccosh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arccosh (F (X))) elsif Is_Long_Float then T (Arccosh (LF (X))) elsif Is_Long_Long_Float then T (Arccosh (LLF (X))) else raise Program_Error); ------------ -- Arccot -- ------------ -- Natural cycle function Arccot (X : Float_Type'Base; Y : Float_Type'Base := 1.0) return Float_Type'Base is (if Is_Float then T (Arccot (F (X), F (Y))) elsif Is_Long_Float then T (Arccot (LF (X), LF (Y))) elsif Is_Long_Long_Float then T (Arccot (LLF (X), LLF (Y))) else raise Program_Error); -- Arbitrary cycle function Arccot (X : Float_Type'Base; Y : Float_Type'Base := 1.0; Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arccot (F (X), F (Y), F (Cycle))) elsif Is_Long_Float then T (Arccot (LF (X), LF (Y), LF (Cycle))) elsif Is_Long_Long_Float then T (Arccot (LLF (X), LLF (Y), LLF (Cycle))) else raise Program_Error); ------------- -- Arccoth -- ------------- function Arccoth (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arccoth (F (X))) elsif Is_Long_Float then T (Arccoth (LF (X))) elsif Is_Long_Long_Float then T (Arccoth (LLF (X))) else raise Program_Error); ------------ -- Arcsin -- ------------ -- Natural cycle function Arcsin (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arcsin (F (X))) elsif Is_Long_Float then T (Arcsin (LF (X))) elsif Is_Long_Long_Float then T (Arcsin (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Arcsin (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arcsin (F (X), F (Cycle))) elsif Is_Long_Float then T (Arcsin (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Arcsin (LLF (X), LLF (Cycle))) else raise Program_Error); ------------- -- Arcsinh -- ------------- function Arcsinh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arcsinh (F (X))) elsif Is_Long_Float then T (Arcsinh (LF (X))) elsif Is_Long_Long_Float then T (Arcsinh (LLF (X))) else raise Program_Error); ------------ -- Arctan -- ------------ -- Natural cycle function Arctan (Y : Float_Type'Base; X : Float_Type'Base := 1.0) return Float_Type'Base is (if Is_Float then T (Arctan (F (Y), F (X))) elsif Is_Long_Float then T (Arctan (LF (Y), LF (X))) elsif Is_Long_Long_Float then T (Arctan (LLF (Y), LLF (X))) else raise Program_Error); -- Arbitrary cycle function Arctan (Y : Float_Type'Base; X : Float_Type'Base := 1.0; Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arctan (F (Y), F (X), F (Cycle))) elsif Is_Long_Float then T (Arctan (LF (Y), LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Arctan (LLF (Y), LLF (X), LLF (Cycle))) else raise Program_Error); ------------- -- Arctanh -- ------------- function Arctanh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Arctanh (F (X))) elsif Is_Long_Float then T (Arctanh (LF (X))) elsif Is_Long_Long_Float then T (Arctanh (LLF (X))) else raise Program_Error); --------- -- Cos -- --------- -- Natural cycle function Cos (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Cos (F (X))) elsif Is_Long_Float then T (Cos (LF (X))) elsif Is_Long_Long_Float then T (Cos (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Cos (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Cos (F (X), F (Cycle))) elsif Is_Long_Float then T (Cos (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Cos (LLF (X), LLF (Cycle))) else raise Program_Error); ---------- -- Cosh -- ---------- function Cosh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Cosh (F (X))) elsif Is_Long_Float then T (Cosh (LF (X))) elsif Is_Long_Long_Float then T (Cosh (LLF (X))) else raise Program_Error); --------- -- Cot -- --------- -- Natural cycle function Cot (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Cot (F (X))) elsif Is_Long_Float then T (Cot (LF (X))) elsif Is_Long_Long_Float then T (Cot (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Cot (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Cot (F (X), F (Cycle))) elsif Is_Long_Float then T (Cot (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Cot (LLF (X), LLF (Cycle))) else raise Program_Error); ---------- -- Coth -- ---------- function Coth (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Coth (F (X))) elsif Is_Long_Float then T (Coth (LF (X))) elsif Is_Long_Long_Float then T (Coth (LLF (X))) else raise Program_Error); --------- -- Exp -- --------- function Exp (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Exp (F (X))) elsif Is_Long_Float then T (Exp (LF (X))) elsif Is_Long_Long_Float then T (Exp (LLF (X))) else raise Program_Error); --------- -- Log -- --------- -- Natural base function Log (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Log (F (X))) elsif Is_Long_Float then T (Log (LF (X))) elsif Is_Long_Long_Float then T (Log (LLF (X))) else raise Program_Error); -- Arbitrary base function Log (X, Base : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Log (F (X), F (Base))) elsif Is_Long_Float then T (Log (LF (X), LF (Base))) elsif Is_Long_Long_Float then T (Log (LLF (X), LLF (Base))) else raise Program_Error); --------- -- Sin -- --------- -- Natural cycle function Sin (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Sin (F (X))) elsif Is_Long_Float then T (Sin (LF (X))) elsif Is_Long_Long_Float then T (Sin (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Sin (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Sin (F (X), F (Cycle))) elsif Is_Long_Float then T (Sin (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Sin (LLF (X), LLF (Cycle))) else raise Program_Error); ---------- -- Sinh -- ---------- function Sinh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Sinh (F (X))) elsif Is_Long_Float then T (Sinh (LF (X))) elsif Is_Long_Long_Float then T (Sinh (LLF (X))) else raise Program_Error); ---------- -- Sqrt -- ---------- function Sqrt (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Sqrt (F (X))) elsif Is_Long_Float then T (Sqrt (LF (X))) elsif Is_Long_Long_Float then T (Sqrt (LLF (X))) else raise Program_Error); --------- -- Tan -- --------- -- Natural cycle function Tan (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Tan (F (X))) elsif Is_Long_Float then T (Tan (LF (X))) elsif Is_Long_Long_Float then T (Tan (LLF (X))) else raise Program_Error); -- Arbitrary cycle function Tan (X, Cycle : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Tan (F (X), F (Cycle))) elsif Is_Long_Float then T (Tan (LF (X), LF (Cycle))) elsif Is_Long_Long_Float then T (Tan (LLF (X), LLF (Cycle))) else raise Program_Error); ---------- -- Tanh -- ---------- function Tanh (X : Float_Type'Base) return Float_Type'Base is (if Is_Float then T (Tanh (F (X))) elsif Is_Long_Float then T (Tanh (LF (X))) elsif Is_Long_Long_Float then T (Tanh (LLF (X))) else raise Program_Error); end Ada.Numerics.Generic_Elementary_Functions;
with System; package Lv.Tasks is type Instance is private; type Prio_T is (Prio_Off, Prio_Lowest, Prio_Low, Prio_Mid, Prio_High, Prio_Highest, Prio_Num); -- Call it periodically to handle lv_tasks. procedure Handler; -- Create a new lv_task -- @param task a function which is the task itself -- @param period call period in ms unit -- @param prio priority of the task (LV_TASK_PRIO_OFF means the task is stopped) -- @param param free parameter -- @return pointer to the new task function Create (Proc : access procedure (Param : System.Address); Period : Uint32_T; Prio : Prio_T; Param : System.Address) return Instance; -- Delete a lv_task -- @param lv_task_p pointer to task created by lv_task_p procedure Del (Self : Instance); -- Set new priority for a lv_task -- @param lv_task_p pointer to a lv_task -- @param prio the new priority procedure Set_Prio (Self : Instance; Prio : Prio_T); -- Set new period for a lv_task -- @param lv_task_p pointer to a lv_task -- @param period the new period procedure Set_Period (Self : Instance; Period : Uint32_T); -- Make a lv_task ready. It will not wait its period. -- @param lv_task_p pointer to a lv_task. procedure Ready (Self : Instance); -- Delete the lv_task after one call -- @param lv_task_p pointer to a lv_task. procedure Once (Self : Instance); -- Reset a lv_task. -- It will be called the previously set period milliseconds later. -- @param lv_task_p pointer to a lv_task. procedure Reset (Self : Instance); -- Enable or disable the whole lv_task handling -- @param en: true: lv_task handling is running, false: lv_task handling is suspended procedure Enable (En : U_Bool); -- Get idle percentage -- @return the lv_task idle in percentage function Get_Idle return Uint8_T; private type Instance is new System.Address; -- This Init is already called in lv_init() procedure Init; ------------- -- Imports -- ------------- pragma Import (C, Handler, "lv_task_handler"); pragma Import (C, Create, "lv_task_create"); pragma Import (C, Del, "lv_task_del"); pragma Import (C, Set_Prio, "lv_task_set_prio"); pragma Import (C, Set_Period, "lv_task_set_period"); pragma Import (C, Ready, "lv_task_ready"); pragma Import (C, Once, "lv_task_once"); pragma Import (C, Reset, "lv_task_reset"); pragma Import (C, Enable, "lv_task_enable"); pragma Import (C, Get_Idle, "lv_task_get_idle"); pragma Import (C, Init, "lv_task_init"); for Prio_T'Size use 8; for Prio_T use (Prio_Off => 0, Prio_Lowest => 1, Prio_Low => 2, Prio_Mid => 3, Prio_High => 4, Prio_Highest => 5, Prio_Num => 6); end Lv.Tasks;
-- Copyright (c) 2021 Bartek thindil Jasicki <thindil@laeran.pl> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with Tashy2; with Tcl.Commands; package body Tcl.Lists is function Split_List (List: String; Interpreter: Tcl_Interpreter := Get_Interpreter) return Array_List with SPARK_Mode => Off is use Tcl.Commands; function Tcl_Split_List (Interp: Tcl_Interpreter; Tcl_List: chars_ptr; Argc_Ptr: out int; Argv_Ptr: out Argv_Pointer.Pointer) return Tcl_Results with Import, Convention => C, External_Name => "Tcl_SplitList"; Amount: Natural := 0; Values: Argv_Pointer.Pointer; begin if Tcl_Split_List (Interp => Interpreter, Tcl_List => New_String(Str => List), Argc_Ptr => int(Amount), Argv_Ptr => Values) = TCL_ERROR then return Empty_Array_List; end if; if Amount = 0 then return Empty_Array_List; end if; return Ada_Array: Array_List(1 .. Amount) := (others => Null_Tcl_String) do Convert_List_To_Array_Loop : for I in Ada_Array'Range loop Ada_Array(I) := To_Unbounded_String (Source => Get_Argument(Arguments_Pointer => Values, Index => I - 1)); end loop Convert_List_To_Array_Loop; end return; end Split_List; function Merge_List(List: Array_List) return String is use Tashy2; function Tcl_Merge (Argc: int; Argv: chars_ptr_array) return chars_ptr with Global => null, Import, Convention => C, External_Name => "Tcl_Merge"; New_List: chars_ptr_array(1 .. List'Length) := (others => Null_Ptr); Index: size_t := New_List'First; begin Convert_Ada_String_To_C_Loop : for Item of List loop pragma Loop_Invariant(Index in New_List'Range); New_List(Index) := To_C_String(Str => To_Ada_String(Source => Item)); Index := Index + 1; exit Convert_Ada_String_To_C_Loop when Index > New_List'Last; end loop Convert_Ada_String_To_C_Loop; return From_C_String (Item => Tcl_Merge(Argc => List'Length, Argv => New_List)); end Merge_List; end Tcl.Lists;
-- -- Copyright (C) 2015-2018 secunet Security Networks AG -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- private package HW.GFX.GMA.Config with Initializes => (Valid_Port_GPU, Raw_Clock) is CPU : constant CPU_Type := Haswell; CPU_Var : constant CPU_Variant := Normal; Internal_Display : constant Internal_Type := DP; Analog_I2C_Port : constant PCH_Port := PCH_DAC; EDP_Low_Voltage_Swing : constant Boolean := False; DDI_HDMI_Buffer_Translation : constant Integer := -1; Default_MMIO_Base : constant := 0 ; LVDS_Dual_Threshold : constant := 95_000_000; ---------------------------------------------------------------------------- Default_MMIO_Base_Set : constant Boolean := Default_MMIO_Base /= 0; Has_Internal_Display : constant Boolean := Internal_Display /= None; Internal_Is_EDP : constant Boolean := Internal_Display = DP; Have_DVI_I : constant Boolean := Analog_I2C_Port /= PCH_DAC; Has_Presence_Straps : constant Boolean := CPU /= Broxton; ----- CPU pipe: -------- Disable_Trickle_Feed : constant Boolean := not (CPU in Haswell .. Broadwell); Pipe_Enabled_Workaround : constant Boolean := CPU = Broadwell; Has_EDP_Transcoder : constant Boolean := CPU >= Haswell; Use_PDW_For_EDP_Scaling : constant Boolean := CPU = Haswell; Has_Pipe_DDI_Func : constant Boolean := CPU >= Haswell; Has_Trans_Clk_Sel : constant Boolean := CPU >= Haswell; Has_Pipe_MSA_Misc : constant Boolean := CPU >= Haswell; Has_Pipeconf_Misc : constant Boolean := CPU >= Broadwell; Has_Pipeconf_BPC : constant Boolean := CPU /= Haswell; Has_Plane_Control : constant Boolean := CPU >= Broxton; Has_DSP_Linoff : constant Boolean := CPU <= Ivybridge; Has_PF_Pipe_Select : constant Boolean := CPU in Ivybridge .. Haswell; Has_Cursor_FBC_Control : constant Boolean := CPU >= Ivybridge; VGA_Plane_Workaround : constant Boolean := CPU = Ivybridge; Has_GMCH_DP_Transcoder : constant Boolean := CPU = G45; Has_GMCH_VGACNTRL : constant Boolean := CPU = G45; Has_GMCH_PFIT_CONTROL : constant Boolean := CPU = G45; ----- Panel power: ----- Has_PP_Write_Protection : constant Boolean := CPU <= Ivybridge; Has_PP_Port_Select : constant Boolean := CPU <= Ivybridge; Use_PP_VDD_Override : constant Boolean := CPU <= Ivybridge; Has_PCH_Panel_Power : constant Boolean := CPU >= Ironlake; ----- PCH/FDI: --------- Has_PCH : constant Boolean := CPU /= Broxton and CPU /= G45; Has_PCH_DAC : constant Boolean := CPU in Ironlake .. Ivybridge or (CPU in Broadwell .. Haswell and CPU_Var = Normal); Has_PCH_Aux_Channels : constant Boolean := CPU in Ironlake .. Broadwell; VGA_Has_Sync_Disable : constant Boolean := CPU <= Ivybridge; Has_Trans_Timing_Ovrrde : constant Boolean := CPU >= Sandybridge; Has_DPLL_SEL : constant Boolean := CPU in Ironlake .. Ivybridge; Has_FDI_BPC : constant Boolean := CPU in Ironlake .. Ivybridge; Has_FDI_Composite_Sel : constant Boolean := CPU = Ivybridge; Has_Trans_DP_Ctl : constant Boolean := CPU in Sandybridge .. Ivybridge; Has_FDI_C : constant Boolean := CPU = Ivybridge; Has_FDI_RX_Power_Down : constant Boolean := CPU in Haswell .. Broadwell; Has_GMCH_RawClk : constant Boolean := CPU = G45; ----- DDI: ------------- End_EDP_Training_Late : constant Boolean := CPU in Haswell .. Broadwell; Has_Per_DDI_Clock_Sel : constant Boolean := CPU in Haswell .. Broadwell; Has_HOTPLUG_CTL : constant Boolean := CPU in Haswell .. Broadwell; Has_SHOTPLUG_CTL_A : constant Boolean := (CPU in Haswell .. Broadwell and CPU_Var = ULT) or CPU >= Skylake; Has_DDI_PHYs : constant Boolean := CPU = Broxton; Has_DDI_D : constant Boolean := CPU >= Haswell and CPU_Var = Normal and not Has_DDI_PHYs; Has_DDI_E : constant Boolean := -- might be disabled by x4 eDP Has_DDI_D; Has_DDI_Buffer_Trans : constant Boolean := CPU >= Haswell and CPU /= Broxton; Has_Low_Voltage_Swing : constant Boolean := CPU >= Broxton; Has_Iboost_Config : constant Boolean := CPU >= Skylake; Need_DP_Aux_Mutex : constant Boolean := False; -- Skylake & (PSR | GTC) ----- GMBUS: ----------- Ungate_GMBUS_Unit_Level : constant Boolean := CPU >= Skylake; GMBUS_Alternative_Pins : constant Boolean := CPU = Broxton; Has_PCH_GMBUS : constant Boolean := CPU >= Ironlake; ----- Power: ----------- Has_IPS : constant Boolean := (CPU = Haswell and CPU_Var = ULT) or CPU = Broadwell; Has_IPS_CTL_Mailbox : constant Boolean := CPU = Broadwell; Has_Per_Pipe_SRD : constant Boolean := CPU >= Broadwell; ----- GTT: ------------- Fold_39Bit_GTT_PTE : constant Boolean := CPU <= Haswell; ---------------------------------------------------------------------------- Max_Pipe : constant Pipe_Index := (if CPU <= Sandybridge then Secondary else Tertiary); type Supported_Pipe_Array is array (Pipe_Index) of Boolean; Supported_Pipe : constant Supported_Pipe_Array := (Primary => Primary <= Max_Pipe, Secondary => Secondary <= Max_Pipe, Tertiary => Tertiary <= Max_Pipe); type Valid_Per_Port is array (Port_Type) of Boolean; type Valid_Per_GPU is array (CPU_Type) of Valid_Per_Port; Valid_Port_GPU : Valid_Per_GPU := (G45 => (Disabled => False, Internal => Config.Internal_Display = LVDS, HDMI3 => False, others => True), Ironlake => (Disabled => False, Internal => Config.Internal_Display = LVDS, others => True), Sandybridge => (Disabled => False, Internal => Config.Internal_Display = LVDS, others => True), Ivybridge => (Disabled => False, Internal => Config.Internal_Display /= None, others => True), Haswell => (Disabled => False, Internal => Config.Internal_Display = DP, HDMI3 => CPU_Var = Normal, DP3 => CPU_Var = Normal, Analog => CPU_Var = Normal, others => True), Broadwell => (Disabled => False, Internal => Config.Internal_Display = DP, HDMI3 => CPU_Var = Normal, DP3 => CPU_Var = Normal, Analog => CPU_Var = Normal, others => True), Broxton => (Internal => Config.Internal_Display = DP, DP1 => True, DP2 => True, HDMI1 => True, HDMI2 => True, others => False), Skylake => (Disabled => False, Internal => Config.Internal_Display = DP, Analog => False, others => True)) with Part_Of => GMA.Config_State; Valid_Port : Valid_Per_Port renames Valid_Port_GPU (CPU); Last_Digital_Port : constant Digital_Port := (if Has_DDI_E then DIGI_E else DIGI_C); ---------------------------------------------------------------------------- type FDI_Per_Port is array (Port_Type) of Boolean; Is_FDI_Port : constant FDI_Per_Port := (case CPU is when Ironlake .. Ivybridge => FDI_Per_Port' (Internal => Internal_Display = LVDS, others => True), when Haswell .. Broadwell => FDI_Per_Port' (Analog => Has_PCH_DAC, others => False), when others => FDI_Per_Port' (others => False)); type FDI_Lanes_Per_Port is array (GPU_Port) of DP_Lane_Count; FDI_Lane_Count : constant FDI_Lanes_Per_Port := (DIGI_D => DP_Lane_Count_2, others => (if CPU in Ironlake .. Ivybridge then DP_Lane_Count_4 else DP_Lane_Count_2)); FDI_Training : constant FDI_Training_Type := (case CPU is when Ironlake => Simple_Training, when Sandybridge => Full_Training, when others => Auto_Training); ---------------------------------------------------------------------------- Default_DDI_HDMI_Buffer_Translation : constant DDI_HDMI_Buf_Trans_Range := (case CPU is when Haswell => 6, when Broadwell => 7, when Broxton => 8, when Skylake => 8, when others => 0); ---------------------------------------------------------------------------- Default_CDClk_Freq : constant Frequency_Type := (case CPU is when G45 => 320_000_000, -- unused when Ironlake | Haswell | Broadwell => 450_000_000, when Sandybridge | Ivybridge => 400_000_000, when Broxton => 288_000_000, when Skylake => 337_500_000); Default_RawClk_Freq : constant Frequency_Type := (case CPU is when G45 => 100_000_000, -- unused, depends on FSB when Ironlake | Sandybridge | Ivybridge => 125_000_000, when Haswell | Broadwell => (if CPU_Var = Normal then 125_000_000 else 24_000_000), when Broxton => Frequency_Type'First, -- none needed when Skylake => 24_000_000); Raw_Clock : Frequency_Type := Default_RawClk_Freq with Part_Of => GMA.Config_State; ---------------------------------------------------------------------------- -- Maximum source width with enabled scaler. This only accounts -- for simple 1:1 pipe:scaler mappings. type Width_Per_Pipe is array (Pipe_Index) of Pos16; Maximum_Scalable_Width : constant Width_Per_Pipe := (case CPU is when G45 => -- TODO: Is this true? (Primary => 4096, Secondary => 2048, Tertiary => Pos16'First), when Ironlake..Haswell => (Primary => 4096, Secondary => 2048, Tertiary => 2048), when Broadwell..Skylake => (Primary => 4096, Secondary => 4096, Tertiary => 4096)); -- Maximum X position of hardware cursors Maximum_Cursor_X : constant := (case CPU is when G45 .. Ivybridge => 4095, when Haswell .. Skylake => 8191); Maximum_Cursor_Y : constant := 4095; ---------------------------------------------------------------------------- -- FIXME: Unknown for Broxton, Linux' i915 contains a fixme too :-D HDMI_Max_Clock_24bpp : constant Frequency_Type := (if CPU >= Haswell then 300_000_000 else 225_000_000); ---------------------------------------------------------------------------- GTT_Offset : constant := (case CPU is when G45 .. Haswell => 16#0020_0000#, when Broadwell .. Skylake => 16#0080_0000#); GTT_Size : constant := (case CPU is when G45 .. Haswell => 16#0020_0000#, -- Limit Broadwell to 4MiB to have a stable -- interface (i.e. same number of entries): when Broadwell .. Skylake => 16#0040_0000#); GTT_PTE_Size : constant := (case CPU is when G45 .. Haswell => 4, when Broadwell .. Skylake => 8); Fence_Base : constant := (case CPU is when G45 .. Ironlake => 16#0000_3000#, when Sandybridge .. Skylake => 16#0010_0000#); Fence_Count : constant := (case CPU is when G45 .. Sandybridge => 16, when Ivybridge .. Skylake => 32); ---------------------------------------------------------------------------- use type HW.Word16; function Is_Broadwell_H (Device_Id : Word16) return Boolean is (Device_Id = 16#1612# or Device_Id = 16#1622# or Device_Id = 16#162a#); function Is_Skylake_U (Device_Id : Word16) return Boolean is (Device_Id = 16#1906# or Device_Id = 16#1916# or Device_Id = 16#1923# or Device_Id = 16#1926# or Device_Id = 16#1927#); -- Rather catch too much here than too little, -- it's only used to distinguish generations. function Is_GPU (Device_Id : Word16; CPU : CPU_Type; CPU_Var : CPU_Variant) return Boolean is (case CPU is when G45 => (Device_Id and 16#ff02#) = 16#2e02# or (Device_Id and 16#fffe#) = 16#2a42#, when Ironlake => (Device_Id and 16#fff3#) = 16#0042#, when Sandybridge => (Device_Id and 16#ffc2#) = 16#0102#, when Ivybridge => (Device_Id and 16#ffc3#) = 16#0142#, when Haswell => (case CPU_Var is when Normal => (Device_Id and 16#ffc3#) = 16#0402# or (Device_Id and 16#ffc3#) = 16#0d02#, when ULT => (Device_Id and 16#ffc3#) = 16#0a02#), when Broadwell => ((Device_Id and 16#ffc3#) = 16#1602# or (Device_Id and 16#ffcf#) = 16#160b# or (Device_Id and 16#ffcf#) = 16#160d#) and (case CPU_Var is when Normal => Is_Broadwell_H (Device_Id), when ULT => not Is_Broadwell_H (Device_Id)), when Broxton => (Device_Id and 16#fffe#) = 16#5a84#, when Skylake => ((Device_Id and 16#ffc3#) = 16#1902# or (Device_Id and 16#ffcf#) = 16#190b# or (Device_Id and 16#ffcf#) = 16#190d# or (Device_Id and 16#fff9#) = 16#1921#) and (case CPU_Var is when Normal => not Is_Skylake_U (Device_Id), when ULT => Is_Skylake_U (Device_Id))); function Compatible_GPU (Device_Id : Word16) return Boolean is (Is_GPU (Device_Id, CPU, CPU_Var)); end HW.GFX.GMA.Config;
package Loop_Optimization1 is type Number is range 0 .. 127; type Group_List is array (Positive range <>) of Number; subtype Index is Natural range 1 .. 5; function Groups (T : Integer) return Group_List; pragma Import (Ada, Groups); type Group_Chain (Length : Index := 1) is record Groups : Group_List(1 .. Length); end record; type Group_Chain_List is array (Positive range <>) of Group_Chain; function Group_Chains (T : Integer) return Group_Chain_List; pragma Import (Ada, Group_Chains); type R (I : Boolean) is null record; type R_Access is access R; type R_List is array (Positive range <>) of R_Access; type R_List_Access is access R_List; type D is record L : R_List_Access; end record; procedure Create (A : in out D; Val : Integer); end Loop_Optimization1;
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_alloc_named_color_reply_t is -- Item -- type Item is record response_type : aliased Interfaces.Unsigned_8; pad0 : aliased Interfaces.Unsigned_8; sequence : aliased Interfaces.Unsigned_16; length : aliased Interfaces.Unsigned_32; pixel : aliased Interfaces.Unsigned_32; exact_red : aliased Interfaces.Unsigned_16; exact_green : aliased Interfaces.Unsigned_16; exact_blue : aliased Interfaces.Unsigned_16; visual_red : aliased Interfaces.Unsigned_16; visual_green : aliased Interfaces.Unsigned_16; visual_blue : aliased Interfaces.Unsigned_16; end record; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_alloc_named_color_reply_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_alloc_named_color_reply_t.Item, Element_Array => xcb.xcb_alloc_named_color_reply_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_alloc_named_color_reply_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_alloc_named_color_reply_t.Pointer, Element_Array => xcb.xcb_alloc_named_color_reply_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_alloc_named_color_reply_t;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . T E S T _ R E S U L T S -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2011, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with AUnit.Memory.Utils; -- Record test results. package body AUnit.Test_Results is ----------------------- -- Local Subprograms -- ----------------------- function Alloc_Failure is new AUnit.Memory.Utils.Gen_Alloc (Test_Failure, Test_Failure_Access); function Alloc_Error is new AUnit.Memory.Utils.Gen_Alloc (Test_Error, Test_Error_Access); E_Count : Count_Type; F_Count : Count_Type; S_Count : Count_Type; procedure Iterate_Error (Position : Result_Lists.Cursor); procedure Iterate_Failure (Position : Result_Lists.Cursor); procedure Iterate_Success (Position : Result_Lists.Cursor); function Is_Error (Position : Result_Lists.Cursor) return Boolean; function Is_Failure (Position : Result_Lists.Cursor) return Boolean; function Is_Success (Position : Result_Lists.Cursor) return Boolean; generic with function Test (Position : Result_Lists.Cursor) return Boolean; procedure Gen_Extract (R : in out Result; E : in out Result_Lists.List); ------------------- -- Iterate_Error -- ------------------- procedure Iterate_Error (Position : Result_Lists.Cursor) is begin if Result_Lists.Element (Position).Error /= null then E_Count := E_Count + 1; end if; end Iterate_Error; --------------------- -- Iterate_Failure -- --------------------- procedure Iterate_Failure (Position : Result_Lists.Cursor) is begin if Result_Lists.Element (Position).Failure /= null then F_Count := F_Count + 1; end if; end Iterate_Failure; --------------------- -- Iterate_Success -- --------------------- procedure Iterate_Success (Position : Result_Lists.Cursor) is begin if Result_Lists.Element (Position).Error = null and then Result_Lists.Element (Position).Failure = null then S_Count := S_Count + 1; end if; end Iterate_Success; ----------------- -- Gen_Extract -- ----------------- procedure Gen_Extract (R : in out Result; E : in out Result_Lists.List) is C : Result_Lists.Cursor; Prev : Result_Lists.Cursor; use Result_Lists; begin C := First (R.Result_List); Prev := No_Element; while Has_Element (C) loop if Test (C) then Splice (Target => E, Before => No_Element, Source => R.Result_List, Position => C); if Prev = No_Element then C := First (R.Result_List); else C := Next (Prev); end if; else Prev := C; Next (C); end if; end loop; end Gen_Extract; -------------- -- Is_Error -- -------------- function Is_Error (Position : Result_Lists.Cursor) return Boolean is begin return Result_Lists.Element (Position).Error /= null; end Is_Error; ---------------- -- Is_Failure -- ---------------- function Is_Failure (Position : Result_Lists.Cursor) return Boolean is begin return Result_Lists.Element (Position).Failure /= null; end Is_Failure; ---------------- -- Is_Success -- ---------------- function Is_Success (Position : Result_Lists.Cursor) return Boolean is begin return not Is_Error (Position) and then not Is_Failure (Position); end Is_Success; --------------- -- Add_Error -- --------------- procedure Add_Error (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Error : Test_Error; Elapsed : Time) is Val : constant Test_Result := (Test_Name, Routine_Name, Failure => null, Error => Alloc_Error, Elapsed => Elapsed); use Result_Lists; begin Val.Error.all := Error; Append (R.Result_List, Val); end Add_Error; ----------------- -- Add_Failure -- ----------------- procedure Add_Failure (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Failure : Test_Failure; Elapsed : Time) is Val : constant Test_Result := (Test_Name, Routine_Name, Failure => Alloc_Failure, Error => null, Elapsed => Elapsed); use Result_Lists; begin Val.Failure.all := Failure; Append (R.Result_List, Val); end Add_Failure; ----------------- -- Add_Success -- ----------------- procedure Add_Success (R : in out Result; Test_Name : Message_String; Routine_Name : Message_String; Elapsed : Time) is Val : constant Test_Result := (Test_Name, Routine_Name, null, null, Elapsed); use Result_Lists; begin Append (R.Result_List, Val); end Add_Success; ----------------- -- Set_Elapsed -- ----------------- procedure Set_Elapsed (R : in out Result; T : Time_Measure.Time) is begin R.Elapsed_Time := T; end Set_Elapsed; ----------------- -- Error_Count -- ----------------- function Error_Count (R : Result) return Count_Type is use Result_Lists; begin E_Count := 0; Iterate (R.Result_List, Iterate_Error'Access); return E_Count; end Error_Count; ------------ -- Errors -- ------------ procedure Errors (R : in out Result; E : in out Result_Lists.List) is procedure Extract is new Gen_Extract (Is_Error); begin Extract (R, E); end Errors; ------------------- -- Failure_Count -- ------------------- function Failure_Count (R : Result) return Count_Type is use Result_Lists; begin F_Count := 0; Iterate (R.Result_List, Iterate_Failure'Access); return F_Count; end Failure_Count; -------------- -- Failures -- -------------- procedure Failures (R : in out Result; F : in out Result_Lists.List) is procedure Extract is new Gen_Extract (Is_Failure); begin Extract (R, F); end Failures; ------------- -- Elapsed -- ------------- function Elapsed (R : Result) return Time_Measure.Time is begin return R.Elapsed_Time; end Elapsed; ---------------- -- Start_Test -- ---------------- procedure Start_Test (R : in out Result; Subtest_Count : Count_Type) is begin R.Tests_Run := R.Tests_Run + Subtest_Count; end Start_Test; ------------------- -- Success_Count -- ------------------- function Success_Count (R : Result) return Count_Type is begin S_Count := 0; Result_Lists.Iterate (R.Result_List, Iterate_Success'Access); return S_Count; end Success_Count; --------------- -- Successes -- --------------- procedure Successes (R : in out Result; S : in out Result_Lists.List) is procedure Extract is new Gen_Extract (Is_Success); begin Extract (R, S); end Successes; ---------------- -- Successful -- ---------------- function Successful (R : Result) return Boolean is begin return Success_Count (R) = Test_Count (R); end Successful; ---------------- -- Test_Count -- ---------------- function Test_Count (R : Result) return Ada_Containers.Count_Type is begin return R.Tests_Run; end Test_Count; ----------- -- Clear -- ----------- procedure Clear (R : in out Result) is begin R.Tests_Run := 0; R.Elapsed_Time := Time_Measure.Null_Time; Result_Lists.Clear (R.Result_List); end Clear; end AUnit.Test_Results;
-- compile with -gnatW8 with Ada.Text_IO; use Ada.Text_IO; with Ada.Wide_Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings.Unbounded; procedure Test_Types is type Cows_Counter_Type is new Natural; type Fixed_Point_Type is delta 0.01 range 0.0 .. 1_166_405_539.00; -- decimal fixed point type Money is delta 0.001 digits 15; type Byte is mod 2**8; for Byte'Size use 8; subtype Age_Type is Integer range 0 .. 150; package SU renames Ada.Strings.Unbounded; subtype U_String is SU.Unbounded_String; function Us (S : String) return U_String renames SU.To_Unbounded_String; -- A record type Person is record Name : U_String; Surname : U_String; Age : Age_Type; Married : Boolean; end record; function To_String (P : Person) return String is begin return SU.To_String (P.Name) & " " & Su.To_String (P.Surname) & ", " & Integer'Image (P.Age) & " years old, " & (if P.Married then "married" else "single"); end To_String; -- overload the concat op, just for moo function "&" (L : String; R : Cows_Counter_Type) return String is begin return L & Integer'Image (Integer (R)); end "&"; Cows_In_The_Park : constant Cows_Counter_Type := 0; Newborn_Cows : constant Integer := 1; Huge_Number : constant Long_Integer := Long_Integer'Last; Very_Huge_Number : constant Long_Long_Integer := Long_Long_Integer'First; Normal_Float : constant Float := Float'Last; Big_Float : constant Long_Float := Long_Float'Last; Huge_Float : constant Long_Long_Float := Long_Long_Float'Last; -- ANSI ESC seq for Bold and normal Esc_Char : constant Character := Character'Val (27); Bold_On : constant String := Esc_Char & "[1m"; Fancy_Off : constant String := Esc_Char & "[0m"; -- this is a way to encode a character by its code Strange_Sign : constant Wide_Character := '["A345"]'; -- or we can write it "for real", provided the source code encoding -- matches the one chosen by the compiler... I use UTF-8 and GNAT -- compiler, therefore I've added the -gnatW8 option Greek_Letter : constant Wide_Character := 'α'; -- Also with Wide_Character we can use the attribute-function Val -- to convert the code of a character into the character No_Hiragana : constant Wide_Character := Wide_Character'Val (16#306e#); -- always with the -gnatW8 option, we can write "wide string" -- directly. Hello_String : constant Wide_String := "→Hello← "; -- A second longs a second One_Second : constant Duration := 1.0; T : Duration; -- these are bytes; let's see the wrap-around arithmetic Byte_1 : constant Byte := 254; Byte_2 : constant Byte := Byte_1 + 1; Byte_3 : constant Byte := Byte_2 + 1; Homer_Simpson : constant Person := (Name => Us ("Homer"), Surname => Us ("Simpson"), Age => 54, Married => True); package LI is new Integer_IO (Long_Integer); package LLI is new Integer_IO (Long_Long_Integer); package F is new Float_IO (Float); package FF is new Float_IO (Long_Float); package FFF is new Float_IO (Long_Long_Float); package D is new Fixed_IO (Duration); package M is new Modular_IO (Byte); -- we can also have our special Cow IO package Cow is new Integer_IO (Cows_Counter_Type); package W renames Ada.Wide_Text_IO; begin -- the following won't compile --Cows_In_The_Park := Cows_In_The_Park + Newborn_Cows; Put_Line ("cows in the park: " & Cows_In_The_Park); Cow.Put (Cows_In_The_Park); Put ("; "); Put ("newborn cows: "); Put (Newborn_Cows); New_Line; Put (Integer (Cows_Counter_Type'Last)); New_Line; LI.Put (Huge_Number); New_Line; LLI.Put (Very_Huge_Number); New_Line; Put (Integer'First); Put (Integer'Last); New_Line; Put (Float'Digits); Put (" §§ "); F.Put (Float'First); New_Line; delay One_Second; -- let's waste a second of your time Put (Long_Float'Digits); New_Line; Put (Long_Long_Float'Digits); New_Line; F.Put (Normal_Float); Put (" << Float"); New_Line; FF.Put (Big_Float); Put (" << Long_Float"); New_Line; FFF.Put (Huge_Float); Put (" << Long_Long_Float"); New_Line; Put_Line (Bold_On & "BOLD" & Fancy_Off); W.Put_Line (Hello_String & Greek_Letter & Strange_Sign & No_Hiragana); T := 1.0; while T > 0.01 loop D.Put (T, Aft => 2); delay T; T := T / 2.0; end loop; New_Line; F.Put (Float (Duration'Delta)); New_Line; F.Put (Float (Duration'First)); F.Put (Float (Duration'Last)); New_Line; F.Put (Float (Duration'Small)); New_Line; F.Put (Float (Fixed_Point_Type'Small)); New_Line; F.Put (Float (Money'Small)); New_Line; F.Put (Float (Money'First)); F.Put (Float (Money'Last)); New_Line; M.Put (Byte_1); M.Put (Byte_2); M.Put (Byte_3); New_Line; -- Let's try with a different base; unfortunately, it uses the Ada -- notation, found no way to remove it to write e.g. FF instead of -- 16#FF#. M.Put (Byte_1, Width => 8, Base => 16); M.Put (Byte_2, Width => 8, Base => 16); M.Put (Byte_3, Width => 8, Base => 2); New_Line; Put_Line (To_String (Homer_Simpson)); end Test_Types;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. with Ada.Text_IO; with Support_Utils.Developer_Parameters; use Support_Utils.Developer_Parameters; procedure Words_Engine.Put_Stat (S : String) is begin if Ada.Text_IO.Is_Open (Stats) then Ada.Text_IO.Put_Line (Stats, S); end if; end Words_Engine.Put_Stat;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T L I N K -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1996-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Gnatlink usage: please consult the gnat documentation with Gnatvsn; use Gnatvsn; with Hostparm; with Osint; use Osint; with Output; use Output; with System; use System; with Table; with Ada.Command_Line; use Ada.Command_Line; with GNAT.OS_Lib; use GNAT.OS_Lib; with Interfaces.C_Streams; use Interfaces.C_Streams; procedure Gnatlink is pragma Ident (Gnat_Version_String); package Gcc_Linker_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Gcc_Linker_Options"); -- Comments needed ??? package Libpath is new Table.Table ( Table_Component_Type => Character, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 4096, Table_Increment => 2, Table_Name => "Gnatlink.Libpath"); -- Comments needed ??? package Linker_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Linker_Options"); -- Comments needed ??? package Linker_Objects is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Linker_Objects"); -- This table collects the objects file to be passed to the linker. In the -- case where the linker command line is too long then programs objects -- are put on the Response_File_Objects table. Note that the binder object -- file and the user's objects remain in this table. This is very -- important because on the GNU linker command line the -L switch is not -- used to look for objects files but -L switch is used to look for -- objects listed in the response file. This is not a problem with the -- applications objects as they are specified with a fullname. package Response_File_Objects is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Response_File_Objects"); -- This table collects the objects file that are to be put in the response -- file. Only application objects are collected there (see details in -- Linker_Objects table comments) package Binder_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, -- equals low bound of Argument_List for Spawn Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Binder_Options"); -- This table collects the arguments to be passed to compile the binder -- generated file. subtype chars_ptr is System.Address; Gcc : String_Access := Program_Name ("gcc"); Read_Mode : constant String := "r" & ASCII.Nul; Begin_Info : String := "-- BEGIN Object file/option list"; End_Info : String := "-- END Object file/option list "; -- Note: above lines are modified in C mode, see option processing Gcc_Path : String_Access; Linker_Path : String_Access; Output_File_Name : String_Access; Ali_File_Name : String_Access; Binder_Spec_Src_File : String_Access; Binder_Body_Src_File : String_Access; Binder_Ali_File : String_Access; Binder_Obj_File : String_Access; Tname : Temp_File_Name; Tname_FD : File_Descriptor := Invalid_FD; -- Temporary file used by linker to pass list of object files on -- certain systems with limitations on size of arguments. Debug_Flag_Present : Boolean := False; Verbose_Mode : Boolean := False; Very_Verbose_Mode : Boolean := False; Ada_Bind_File : Boolean := True; -- Set to True if bind file is generated in Ada Compile_Bind_File : Boolean := True; -- Set to False if bind file is not to be compiled Object_List_File_Supported : Boolean; pragma Import (C, Object_List_File_Supported, "objlist_file_supported"); -- Predicate indicating whether the linker has an option whereby the -- names of object files can be passed to the linker in a file. Object_List_File_Required : Boolean := False; -- Set to True to force generation of a response file function Base_Name (File_Name : in String) return String; -- Return just the file name part without the extension (if present). procedure Delete (Name : in String); -- Wrapper to unlink as status is ignored by this application. procedure Error_Msg (Message : in String); -- Output the error or warning Message procedure Exit_With_Error (Error : in String); -- Output Error and exit program with a fatal condition. procedure Process_Args; -- Go through all the arguments and build option tables. procedure Process_Binder_File (Name : in String); -- Reads the binder file and extracts linker arguments. function Value (chars : chars_ptr) return String; -- Return NUL-terminated string chars as an Ada string. procedure Write_Usage; -- Show user the program options. --------------- -- Base_Name -- --------------- function Base_Name (File_Name : in String) return String is Findex1 : Natural; Findex2 : Natural; begin Findex1 := File_Name'First; -- The file might be specified by a full path name. However, -- we want the path to be stripped away. for J in reverse File_Name'Range loop if Is_Directory_Separator (File_Name (J)) then Findex1 := J + 1; exit; end if; end loop; Findex2 := File_Name'Last; while Findex2 > Findex1 and then File_Name (Findex2) /= '.' loop Findex2 := Findex2 - 1; end loop; if Findex2 = Findex1 then Findex2 := File_Name'Last + 1; end if; return File_Name (Findex1 .. Findex2 - 1); end Base_Name; ------------ -- Delete -- ------------ procedure Delete (Name : in String) is Status : int; begin Status := unlink (Name'Address); end Delete; --------------- -- Error_Msg -- --------------- procedure Error_Msg (Message : in String) is begin Write_Str (Base_Name (Command_Name)); Write_Str (": "); Write_Str (Message); Write_Eol; end Error_Msg; --------------------- -- Exit_With_Error -- --------------------- procedure Exit_With_Error (Error : in String) is begin Error_Msg (Error); Exit_Program (E_Fatal); end Exit_With_Error; ------------------ -- Process_Args -- ------------------ procedure Process_Args is Next_Arg : Integer; begin Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-c"); -- If the main program is in Ada it is compiled with the following -- switches: -- -gnatA stops reading gnat.adc, since we don't know what -- pagmas would work, and we do not need it anyway. -- -gnatWb allows brackets coding for wide characters -- -gnatiw allows wide characters in identifiers. This is needed -- because bindgen uses brackets encoding for all upper -- half and wide characters in identifier names. if Ada_Bind_File then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-gnatA"); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-gnatWb"); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-gnatiw"); end if; -- Loop through arguments of gnatlink command Next_Arg := 1; loop exit when Next_Arg > Argument_Count; Process_One_Arg : declare Arg : String := Argument (Next_Arg); begin -- Case of argument which is a switch -- We definitely need section by section comments here ??? if Arg'Length /= 0 and then (Arg (1) = Switch_Character or else Arg (1) = '-') then if Arg'Length > 4 and then Arg (2 .. 5) = "gnat" then Exit_With_Error ("invalid switch: """ & Arg & """ (gnat not needed here)"); end if; if Arg (2) = 'g' and then (Arg'Length < 5 or else Arg (2 .. 5) /= "gnat") then Debug_Flag_Present := True; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); elsif Arg'Length = 2 then case Arg (2) is when 'A' => Ada_Bind_File := True; Begin_Info := "-- BEGIN Object file/option list"; End_Info := "-- END Object file/option list "; when 'b' => Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); Next_Arg := Next_Arg + 1; if Next_Arg > Argument_Count then Exit_With_Error ("Missing argument for -b"); end if; Get_Machine_Name : declare Name_Arg : String_Access := new String'(Argument (Next_Arg)); begin Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Name_Arg; Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Name_Arg; end Get_Machine_Name; when 'C' => Ada_Bind_File := False; Begin_Info := "/* BEGIN Object file/option list"; End_Info := " END Object file/option list */"; when 'f' => if Object_List_File_Supported then Object_List_File_Required := True; else Exit_With_Error ("Object list file not supported on this target"); end if; when 'n' => Compile_Bind_File := False; when 'o' => Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Next_Arg := Next_Arg + 1; if Next_Arg > Argument_Count then Exit_With_Error ("Missing argument for -o"); end if; Output_File_Name := new String'(Argument (Next_Arg)); Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Output_File_Name; when 'v' => -- Support "double" verbose mode. Second -v -- gets sent to the linker and binder phases. if Verbose_Mode then Very_Verbose_Mode := True; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); else Verbose_Mode := True; end if; when others => Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end case; elsif Arg (2) = 'B' then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); elsif Arg'Length >= 7 and then Arg (1 .. 7) = "--LINK=" then if Arg'Length = 7 then Exit_With_Error ("Missing argument for --LINK="); end if; Linker_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Arg (8 .. Arg'Last)); if Linker_Path = null then Exit_With_Error ("Could not locate linker: " & Arg (8 .. Arg'Last)); end if; elsif Arg'Length > 6 and then Arg (1 .. 6) = "--GCC=" then declare Program_Args : Argument_List_Access := Argument_String_To_List (Arg (7 .. Arg'Last)); begin Gcc := new String'(Program_Args.all (1).all); -- Set appropriate flags for switches passed for J in 2 .. Program_Args.all'Last loop declare Arg : String := Program_Args.all (J).all; AF : Integer := Arg'First; begin if Arg'Length /= 0 and then (Arg (AF) = Switch_Character or else Arg (AF) = '-') then if Arg (AF + 1) = 'g' and then (Arg'Length = 2 or else Arg (AF + 2) in '0' .. '3' or else Arg (AF + 2 .. Arg'Last) = "coff") then Debug_Flag_Present := True; end if; end if; -- Pass to gcc for compiling binder generated file -- No use passing libraries, it will just generate -- a warning if not (Arg (AF .. AF + 1) = "-l" or else Arg (AF .. AF + 1) = "-L") then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'(Arg); end if; -- Pass to gcc for linking program. Gcc_Linker_Options.Increment_Last; Gcc_Linker_Options.Table (Gcc_Linker_Options.Last) := new String'(Arg); end; end loop; end; -- Send all multi-character switches not recognized as -- a special case by gnatlink to the linker/loader stage. else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end if; -- Here if argument is a file name rather than a switch else if Arg'Length > 4 and then Arg (Arg'Last - 3 .. Arg'Last) = ".ali" then if Ali_File_Name = null then Ali_File_Name := new String'(Arg); else Exit_With_Error ("cannot handle more than one ALI file"); end if; elsif Is_Regular_File (Arg & ".ali") and then Ali_File_Name = null then Ali_File_Name := new String'(Arg & ".ali"); elsif Arg'Length > Get_Object_Suffix.all'Length and then Arg (Arg'Last - Get_Object_Suffix.all'Length + 1 .. Arg'Last) = Get_Object_Suffix.all then Linker_Objects.Increment_Last; Linker_Objects.Table (Linker_Objects.Last) := new String'(Arg); else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end if; end if; end Process_One_Arg; Next_Arg := Next_Arg + 1; end loop; -- If Ada bind file, then compile it with warnings suppressed, because -- otherwise the with of the main program may cause junk warnings. if Ada_Bind_File then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-gnatws"); end if; end Process_Args; ------------------------- -- Process_Binder_File -- ------------------------- procedure Process_Binder_File (Name : in String) is Fd : FILEs; Link_Bytes : Integer := 0; Link_Max : Integer; pragma Import (C, Link_Max, "link_max"); Next_Line : String (1 .. 1000); Nlast : Integer; Nfirst : Integer; Objs_Begin : Integer := 0; Objs_End : Integer := 0; Status : int; N : Integer; GNAT_Static : Boolean := False; -- Save state of -static option. GNAT_Shared : Boolean := False; -- Save state of -shared option. Run_Path_Option_Ptr : Address; pragma Import (C, Run_Path_Option_Ptr, "run_path_option"); -- Pointer to string representing the native linker option which -- specifies the path where the dynamic loader should find shared -- libraries. Equal to null string if this system doesn't support it. Object_Library_Ext_Ptr : Address; pragma Import (C, Object_Library_Ext_Ptr, "object_library_extension"); -- Pointer to string specifying the default extension for -- object libraries, e.g. Unix uses ".a", VMS uses ".olb". Object_File_Option_Ptr : Address; pragma Import (C, Object_File_Option_Ptr, "object_file_option"); -- Pointer to a string representing the linker option which specifies -- the response file. Using_GNU_Linker : Boolean; pragma Import (C, Using_GNU_Linker, "using_gnu_linker"); -- Predicate indicating whether this target uses the GNU linker. In -- this case we must output a GNU linker compatible response file. procedure Get_Next_Line; -- Read the next line from the binder file without the line -- terminator. function Is_Option_Present (Opt : in String) return Boolean; -- Return true if the option Opt is already present in -- Linker_Options table. procedure Get_Next_Line is Fchars : chars; begin Fchars := fgets (Next_Line'Address, Next_Line'Length, Fd); if Fchars = System.Null_Address then Exit_With_Error ("Error reading binder output"); end if; Nfirst := Next_Line'First; Nlast := Nfirst; while Nlast <= Next_Line'Last and then Next_Line (Nlast) /= ASCII.LF and then Next_Line (Nlast) /= ASCII.CR loop Nlast := Nlast + 1; end loop; Nlast := Nlast - 1; end Get_Next_Line; function Is_Option_Present (Opt : in String) return Boolean is begin for I in 1 .. Linker_Options.Last loop if Linker_Options.Table (I).all = Opt then return True; end if; end loop; return False; end Is_Option_Present; -- Start of processing for Process_Binder_File begin Fd := fopen (Name'Address, Read_Mode'Address); if Fd = NULL_Stream then Exit_With_Error ("Failed to open binder output"); end if; -- Skip up to the Begin Info line loop Get_Next_Line; exit when Next_Line (Nfirst .. Nlast) = Begin_Info; end loop; loop Get_Next_Line; -- Go to end when end line is reached (this will happen in -- No_Run_Time mode where no -L switches are generated) exit when Next_Line (Nfirst .. Nlast) = End_Info; if Ada_Bind_File then Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast); Nlast := Nlast - 8; end if; -- Go to next section when switches are reached exit when Next_Line (1) = '-'; -- Otherwise we have another object file to collect Linker_Objects.Increment_Last; -- Mark the positions of first and last object files in case -- they need to be placed with a named file on systems having -- linker line limitations. if Objs_Begin = 0 then Objs_Begin := Linker_Objects.Last; end if; Linker_Objects.Table (Linker_Objects.Last) := new String'(Next_Line (Nfirst .. Nlast)); Link_Bytes := Link_Bytes + Nlast - Nfirst; end loop; Objs_End := Linker_Objects.Last; -- On systems that have limitations on handling very long linker lines -- we make use of the system linker option which takes a list of object -- file names from a file instead of the command line itself. What we do -- is to replace the list of object files by the special linker option -- which then reads the object file list from a file instead. The option -- to read from a file instead of the command line is only triggered if -- a conservative threshold is passed. if Object_List_File_Required or else (Object_List_File_Supported and then Link_Bytes > Link_Max) then -- Create a temporary file containing the Ada user object files -- needed by the link. This list is taken from the bind file -- and is output one object per line for maximal compatibility with -- linkers supporting this option. Create_Temp_File (Tname_FD, Tname); -- If target is using the GNU linker we must add a special header -- and footer in the response file. -- The syntax is : INPUT (object1.o object2.o ... ) if Using_GNU_Linker then declare GNU_Header : aliased constant String := "INPUT ("; begin Status := Write (Tname_FD, GNU_Header'Address, GNU_Header'Length); end; end if; for J in Objs_Begin .. Objs_End loop Status := Write (Tname_FD, Linker_Objects.Table (J).all'Address, Linker_Objects.Table (J).all'Length); Status := Write (Tname_FD, ASCII.LF'Address, 1); Response_File_Objects.Increment_Last; Response_File_Objects.Table (Response_File_Objects.Last) := Linker_Objects.Table (J); end loop; -- handle GNU linker response file footer. if Using_GNU_Linker then declare GNU_Footer : aliased constant String := ")"; begin Status := Write (Tname_FD, GNU_Footer'Address, GNU_Footer'Length); end; end if; Close (Tname_FD); -- Add the special objects list file option together with the name -- of the temporary file (removing the null character) to the objects -- file table. Linker_Objects.Table (Objs_Begin) := new String'(Value (Object_File_Option_Ptr) & Tname (Tname'First .. Tname'Last - 1)); -- The slots containing these object file names are then removed -- from the objects table so they do not appear in the link. They -- are removed by moving up the linker options and non-Ada object -- files appearing after the Ada object list in the table. N := Objs_End - Objs_Begin + 1; for J in Objs_End + 1 .. Linker_Objects.Last loop Linker_Objects.Table (J - N + 1) := Linker_Objects.Table (J); end loop; Linker_Objects.Set_Last (Linker_Objects.Last - N + 1); end if; -- Process switches and options if Next_Line (Nfirst .. Nlast) /= End_Info then loop -- Add binder options only if not already set on the command -- line. This rule is a way to control the linker options order. if not Is_Option_Present (Next_Line (Nfirst .. Nlast)) then if Next_Line (Nfirst .. Nlast) = "-static" then GNAT_Static := True; elsif Next_Line (Nfirst .. Nlast) = "-shared" then GNAT_Shared := True; else if Nlast > Nfirst + 2 and then Next_Line (Nfirst .. Nfirst + 1) = "-L" then -- Construct a library search path for use later -- to locate static gnatlib libraries. if Libpath.Last > 1 then Libpath.Increment_Last; Libpath.Table (Libpath.Last) := Path_Separator; end if; for I in Nfirst + 2 .. Nlast loop Libpath.Increment_Last; Libpath.Table (Libpath.Last) := Next_Line (I); end loop; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); elsif Next_Line (Nfirst .. Nlast) = "-ldecgnat" or else Next_Line (Nfirst .. Nlast) = "-lgnarl" or else Next_Line (Nfirst .. Nlast) = "-lgnat" then -- Given a Gnat standard library, search the -- library path to find the library location declare File_Path : String_Access; Object_Lib_Extension : constant String := Value (Object_Library_Ext_Ptr); File_Name : String := "lib" & Next_Line (Nfirst + 2 .. Nlast) & Object_Lib_Extension; begin File_Path := Locate_Regular_File (File_Name, String (Libpath.Table (1 .. Libpath.Last))); if File_Path /= null then if GNAT_Static then -- If static gnatlib found, explicitly -- specify to overcome possible linker -- default usage of shared version. Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(File_Path.all); elsif GNAT_Shared then -- If shared gnatlib desired, add the -- appropriate system specific switch -- so that it can be located at runtime. declare Run_Path_Opt : constant String := Value (Run_Path_Option_Ptr); begin if Run_Path_Opt'Length /= 0 then -- Output the system specific linker -- command that allows the image -- activator to find the shared library -- at runtime. Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Run_Path_Opt & File_Path (1 .. File_Path'Length - File_Name'Length)); end if; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end; end if; else -- If gnatlib library not found, then -- add it anyway in case some other -- mechanimsm may find it. Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end if; end; else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end if; end if; end if; Get_Next_Line; exit when Next_Line (Nfirst .. Nlast) = End_Info; if Ada_Bind_File then Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast); Nlast := Nlast - 8; end if; end loop; end if; Status := fclose (Fd); end Process_Binder_File; ----------- -- Value -- ----------- function Value (chars : chars_ptr) return String is function Strlen (chars : chars_ptr) return Natural; pragma Import (C, Strlen); begin if chars = Null_Address then return ""; else declare subtype Result_Type is String (1 .. Strlen (chars)); Result : Result_Type; for Result'Address use chars; begin return Result; end; end if; end Value; ----------------- -- Write_Usage -- ----------------- procedure Write_Usage is begin Write_Str ("Usage: "); Write_Str (Base_Name (Command_Name)); Write_Str (" switches mainprog.ali [non-Ada-objects] [linker-options]"); Write_Eol; Write_Eol; Write_Line (" mainprog.ali the ALI file of the main program"); Write_Eol; Write_Line (" -A Binder generated source file is in Ada (default)"); Write_Line (" -C Binder generated source file is in C"); Write_Line (" -f force object file list to be generated"); Write_Line (" -g Compile binder source file with debug information"); Write_Line (" -n Do not compile the binder source file"); Write_Line (" -v verbose mode"); Write_Line (" -v -v very verbose mode"); Write_Eol; Write_Line (" -o nam Use 'nam' as the name of the executable"); Write_Line (" -b target Compile the binder source to run on target"); Write_Line (" -Bdir Load compiler executables from dir"); Write_Line (" --GCC=comp Use comp as the compiler"); Write_Line (" --LINK=nam Use 'nam' for the linking rather than 'gcc'"); Write_Eol; Write_Line (" [non-Ada-objects] list of non Ada object files"); Write_Line (" [linker-options] other options for the linker"); end Write_Usage; -- Start of processing for Gnatlink begin if Argument_Count = 0 then Write_Usage; Exit_Program (E_Fatal); end if; if Hostparm.Java_VM then Gcc := new String'("jgnat"); Ada_Bind_File := True; Begin_Info := "-- BEGIN Object file/option list"; End_Info := "-- END Object file/option list "; end if; Process_Args; -- Locate all the necessary programs and verify required files are present Gcc_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all); if Gcc_Path = null then Exit_With_Error ("Couldn't locate " & Gcc.all); end if; if Linker_Path = null then Linker_Path := Gcc_Path; end if; if Ali_File_Name = null then Exit_With_Error ("Required 'name'.ali not present."); end if; if not Is_Regular_File (Ali_File_Name.all) then Exit_With_Error (Ali_File_Name.all & " not found."); end if; if Verbose_Mode then Write_Eol; Write_Str ("GNATLINK "); Write_Str (Gnat_Version_String); Write_Str (" Copyright 1996-2001 Free Software Foundation, Inc."); Write_Eol; end if; -- If there wasn't an output specified, then use the base name of -- the .ali file name. if Output_File_Name = null then Output_File_Name := new String'(Base_Name (Ali_File_Name.all) & Get_Debuggable_Suffix.all); Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'("-o"); Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Output_File_Name.all); end if; -- Warn if main program is called "test", as that may be a built-in command -- on Unix. On non-Unix systems executables have a suffix, so the warning -- will not appear. However, do not warn in the case of a cross compiler. -- Assume that if the executable name is not gnatlink, this is a cross -- tool. if Base_Name (Command_Name) = "gnatlink" and then Output_File_Name.all = "test" then Error_Msg ("warning: executable name """ & Output_File_Name.all & """ may conflict with shell command"); end if; -- Perform consistency checks -- Transform the .ali file name into the binder output file name. Make_Binder_File_Names : declare Fname : String := Base_Name (Ali_File_Name.all); Fname_Len : Integer := Fname'Length; function Get_Maximum_File_Name_Length return Integer; pragma Import (C, Get_Maximum_File_Name_Length, "__gnat_get_maximum_file_name_length"); Maximum_File_Name_Length : Integer := Get_Maximum_File_Name_Length; Second_Char : Character; -- Second character of name of files begin -- Set proper second character of file name if not Ada_Bind_File then Second_Char := '_'; elsif Hostparm.OpenVMS then Second_Char := '$'; else Second_Char := '~'; end if; -- If the length of the binder file becomes too long due to -- the addition of the "b?" prefix, then truncate it. if Maximum_File_Name_Length > 0 then while Fname_Len > Maximum_File_Name_Length - 2 loop Fname_Len := Fname_Len - 1; end loop; end if; if Ada_Bind_File then Binder_Spec_Src_File := new String'('b' & Second_Char & Fname (Fname'First .. Fname'First + Fname_Len - 1) & ".ads"); Binder_Body_Src_File := new String'('b' & Second_Char & Fname (Fname'First .. Fname'First + Fname_Len - 1) & ".adb"); Binder_Ali_File := new String'('b' & Second_Char & Fname (Fname'First .. Fname'First + Fname_Len - 1) & ".ali"); else Binder_Body_Src_File := new String'('b' & Second_Char & Fname (Fname'First .. Fname'First + Fname_Len - 1) & ".c"); end if; Binder_Obj_File := new String'('b' & Second_Char & Fname (Fname'First .. Fname'First + Fname_Len - 1) & Get_Object_Suffix.all); if Fname_Len /= Fname'Length then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-o"); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Binder_Obj_File; end if; end Make_Binder_File_Names; Process_Binder_File (Binder_Body_Src_File.all & ASCII.NUL); -- Compile the binder file. This is fast, so we always do it, unless -- specifically told not to by the -n switch if Compile_Bind_File then Bind_Step : declare Success : Boolean; Args : Argument_List (1 .. Binder_Options.Last + 1); begin for J in Binder_Options.First .. Binder_Options.Last loop Args (J) := Binder_Options.Table (J); end loop; Args (Args'Last) := Binder_Body_Src_File; if Verbose_Mode then Write_Str (Base_Name (Gcc_Path.all)); for J in Args'Range loop Write_Str (" "); Write_Str (Args (J).all); end loop; Write_Eol; end if; GNAT.OS_Lib.Spawn (Gcc_Path.all, Args, Success); if not Success then Exit_Program (E_Fatal); end if; end Bind_Step; end if; -- Now, actually link the program. -- Skip this step for now on the JVM since the Java interpreter will do -- the actual link at run time. We might consider packing all class files -- in a .zip file during this step. if not Hostparm.Java_VM then Link_Step : declare Num_Args : Natural := (Linker_Options.Last - Linker_Options.First + 1) + (Gcc_Linker_Options.Last - Gcc_Linker_Options.First + 1) + (Linker_Objects.Last - Linker_Objects.First + 1); Stack_Op : Boolean := False; IDENT_Op : Boolean := False; begin -- Remove duplicate stack size setting from the Linker_Options -- table. The stack setting option "-Xlinker --stack=R,C" can be -- found in one line when set by a pragma Linker_Options or in two -- lines ("-Xlinker" then "--stack=R,C") when set on the command -- line. We also check for the "-Wl,--stack=R" style option. -- We must remove the second stack setting option instance -- because the one on the command line will always be the first -- one. And any subsequent stack setting option will overwrite the -- previous one. This is done especially for GNAT/NT where we set -- the stack size for tasking programs by a pragma in the NT -- specific tasking package System.Task_Primitives.Oparations. for J in Linker_Options.First .. Linker_Options.Last loop if Linker_Options.Table (J).all = "-Xlinker" and then J < Linker_Options.Last and then Linker_Options.Table (J + 1)'Length > 8 and then Linker_Options.Table (J + 1) (1 .. 8) = "--stack=" then if Stack_Op then Linker_Options.Table (J .. Linker_Options.Last - 2) := Linker_Options.Table (J + 2 .. Linker_Options.Last); Linker_Options.Decrement_Last; Linker_Options.Decrement_Last; Num_Args := Num_Args - 2; else Stack_Op := True; end if; end if; -- Here we just check for a canonical form that matches the -- pragma Linker_Options set in the NT runtime. if (Linker_Options.Table (J)'Length > 17 and then Linker_Options.Table (J) (1 .. 17) = "-Xlinker --stack=") or else (Linker_Options.Table (J)'Length > 12 and then Linker_Options.Table (J) (1 .. 12) = "-Wl,--stack=") then if Stack_Op then Linker_Options.Table (J .. Linker_Options.Last - 1) := Linker_Options.Table (J + 1 .. Linker_Options.Last); Linker_Options.Decrement_Last; Num_Args := Num_Args - 1; else Stack_Op := True; end if; end if; -- Remove duplicate IDENTIFICATION directives (VMS) if Linker_Options.Table (J)'Length > 27 and then Linker_Options.Table (J) (1 .. 27) = "--for-linker=IDENTIFICATION=" then if IDENT_Op then Linker_Options.Table (J .. Linker_Options.Last - 1) := Linker_Options.Table (J + 1 .. Linker_Options.Last); Linker_Options.Decrement_Last; Num_Args := Num_Args - 1; else IDENT_Op := True; end if; end if; end loop; -- Prepare arguments for call to linker Call_Linker : declare Success : Boolean; Args : Argument_List (1 .. Num_Args + 1); Index : Integer := Args'First; begin Args (Index) := Binder_Obj_File; -- Add the object files and any -largs libraries for J in Linker_Objects.First .. Linker_Objects.Last loop Index := Index + 1; Args (Index) := Linker_Objects.Table (J); end loop; -- Add the linker options from the binder file for J in Linker_Options.First .. Linker_Options.Last loop Index := Index + 1; Args (Index) := Linker_Options.Table (J); end loop; -- Finally add the libraries from the --GCC= switch for J in Gcc_Linker_Options.First .. Gcc_Linker_Options.Last loop Index := Index + 1; Args (Index) := Gcc_Linker_Options.Table (J); end loop; if Verbose_Mode then Write_Str (Linker_Path.all); for J in Args'Range loop Write_Str (" "); Write_Str (Args (J).all); end loop; Write_Eol; -- If we are on very verbose mode (-v -v) and a response file -- is used we display its content. if Very_Verbose_Mode and then Tname_FD /= Invalid_FD then Write_Eol; Write_Str ("Response file (" & Tname (Tname'First .. Tname'Last - 1) & ") content : "); Write_Eol; for J in Response_File_Objects.First .. Response_File_Objects.Last loop Write_Str (Response_File_Objects.Table (J).all); Write_Eol; end loop; Write_Eol; end if; end if; GNAT.OS_Lib.Spawn (Linker_Path.all, Args, Success); -- Delete the temporary file used in conjuction with linking if -- one was created. See Process_Bind_File for details. if Tname_FD /= Invalid_FD then Delete (Tname); end if; if not Success then Error_Msg ("cannot call " & Linker_Path.all); Exit_Program (E_Fatal); end if; end Call_Linker; end Link_Step; end if; -- Only keep the binder output file and it's associated object -- file if compiling with the -g option. These files are only -- useful if debugging. if not Debug_Flag_Present then if Binder_Ali_File /= null then Delete (Binder_Ali_File.all & ASCII.NUL); end if; if Binder_Spec_Src_File /= null then Delete (Binder_Spec_Src_File.all & ASCII.NUL); end if; Delete (Binder_Body_Src_File.all & ASCII.NUL); if not Hostparm.Java_VM then Delete (Binder_Obj_File.all & ASCII.NUL); end if; end if; Exit_Program (E_Success); exception when others => Exit_With_Error ("INTERNAL ERROR. Please report."); end Gnatlink;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . B B . C P U _ S P E C I F I C -- -- -- -- S p e c -- -- -- -- Copyright (C) 1999-2002 Universidad Politecnica de Madrid -- -- Copyright (C) 2003-2004 The European Space Agency -- -- Copyright (C) 2003-2020, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the primitives which are dependent on the -- underlying processor. pragma Restrictions (No_Elaboration_Code); with System; package System.BB.CPU_Specific is pragma Preelaborate; ------------------------ -- Context management -- ------------------------ -- The context buffer is a type that represents thread's state and is not -- otherwise stored in main memory. This typically includes all user- -- visible registers, and possibly some other status as well. -- In case different contexts have different amounts of state (for example, -- due to absence of a floating-point unit in a particular configuration, -- or just the FPU not being used), it is expected that these details are -- handled in the implementation. type Context_Buffer is record -- Only callee-saved registers need to be saved R1 : System.Address; R2 : System.Address; R13 : System.Address; R14 : System.Address; R15 : System.Address; R16 : System.Address; R17 : System.Address; R18 : System.Address; R19 : System.Address; R20 : System.Address; R21 : System.Address; R22 : System.Address; R23 : System.Address; R24 : System.Address; R25 : System.Address; R26 : System.Address; R27 : System.Address; R28 : System.Address; R29 : System.Address; R30 : System.Address; R31 : System.Address; CR : System.Address; LR : System.Address; F14 : Long_Float; F15 : Long_Float; F16 : Long_Float; F17 : Long_Float; F18 : Long_Float; F19 : Long_Float; F20 : Long_Float; F21 : Long_Float; F22 : Long_Float; F23 : Long_Float; F24 : Long_Float; F25 : Long_Float; F26 : Long_Float; F27 : Long_Float; F28 : Long_Float; F29 : Long_Float; F30 : Long_Float; F31 : Long_Float; FPSCR : Long_Long_Integer; end record; Stack_Alignment : constant := 16; -- Stack alignment defined by the ABI -------------------- -- Initialization -- -------------------- procedure Initialize_CPU; procedure Finish_Initialize_Context (Buffer : not null access Context_Buffer); -- Complete context initialization --------------------------------- -- Interrupt and trap handling -- --------------------------------- type Vector_Id is range 0 .. 16#2fff#; External_Interrupt_Excp : constant Vector_Id := 16#500#; Decrementer_Excp : constant Vector_Id := 16#900#; System_Management_Excp : constant Vector_Id := 16#1400#; procedure Install_Exception_Handler (Service_Routine : System.Address; Vector : Vector_Id); -- Install a new handler in the exception table procedure Install_Error_Handlers; -- Called at system initialization time to install a CPU specific trap -- handler, GNAT_Error_Handler, that converts synchronous traps to -- appropriate exceptions. ------------- -- Variant -- ------------- PowerPC_Book_E : constant Boolean := False; -- Does the CPU implement PowerPC Book-E standard ------------------------------ -- CPU Register Definitions -- ------------------------------ -- Machine State Register (MSR) type Privilege is (Supervisor, User); type Machine_State_Register is record Power_Management_Enable : Boolean; Temporary_GPR_Enable : Boolean; Exception_Little_Endian_Enable : Boolean; External_Interrupt_Enable : Boolean; Privilege_Level : Privilege; Floating_Point_Available : Boolean; Machine_Check_Enable : Boolean; FP_Exception_Mode_0 : Boolean; Single_Step_Trace_Enable : Boolean; Branch_Trace_Enable : Boolean; FP_Exception_Mode_1 : Boolean; Critical_Interrupt_Enable : Boolean; Exception_Prefix : Boolean; Instruction_Address_Space : Boolean; Data_Address_Space : Boolean; Recoverable_Exception : Boolean; Little_Endian_Mode_Enable : Boolean; end record with Size => 32; for Machine_State_Register use record Power_Management_Enable at 0 range 13 .. 13; Temporary_GPR_Enable at 0 range 14 .. 14; Exception_Little_Endian_Enable at 0 range 15 .. 15; External_Interrupt_Enable at 0 range 16 .. 16; Privilege_Level at 0 range 17 .. 17; Floating_Point_Available at 0 range 18 .. 18; Machine_Check_Enable at 0 range 19 .. 19; FP_Exception_Mode_0 at 0 range 20 .. 20; Single_Step_Trace_Enable at 0 range 21 .. 21; Branch_Trace_Enable at 0 range 22 .. 22; FP_Exception_Mode_1 at 0 range 23 .. 23; Critical_Interrupt_Enable at 0 range 24 .. 24; Exception_Prefix at 0 range 25 .. 25; Instruction_Address_Space at 0 range 26 .. 26; Data_Address_Space at 0 range 27 .. 27; Recoverable_Exception at 0 range 30 .. 30; Little_Endian_Mode_Enable at 0 range 31 .. 31; end record; end System.BB.CPU_Specific;
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2014, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with System.Storage_Elements; package body STM32F4.DMA is ------------ -- Enable -- ------------ procedure Enable (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector) is Temp : Stream_Config_Register; -- this register requires 32-bit accesses, hence the temporary begin Temp := Unit.Streams (Stream).CR; Temp.Stream_Enabled := True; Unit.Streams (Stream).CR := Temp; end Enable; ------------- -- Enabled -- ------------- function Enabled (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return Boolean is Temp : Stream_Config_Register; -- this register requires 32-bit accesses, hence the temporary begin Temp := Unit.Streams (Stream).CR; return Temp.Stream_Enabled; end Enabled; ------------- -- Disable -- ------------- procedure Disable (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector) is Temp : Stream_Config_Register; -- this register requires 32-bit accesses, hence the temporary begin Temp := Unit.Streams (Stream).CR; Temp.Stream_Enabled := False; Unit.Streams (Stream).CR := Temp; -- the STMicro Reference Manual RM0090, Doc Id 018909 Rev 6, pg 319, step -- 1 says we must await the bit actually clearing, to confirm no ongoing -- operation remains active loop Temp := Unit.Streams (Stream).CR; exit when not Temp.Stream_Enabled; end loop; end Disable; --------------------------- -- Set_Interrupt_Enabler -- --------------------------- procedure Set_Interrupt_Enabler (This_Stream : in out DMA_Stream; Source : DMA_Interrupt; Value : Boolean) is begin if Source = FIFO_Error_Interrupt then -- use the FCR declare Temp : FIFO_Control_Register; begin Temp := This_Stream.FCR; Temp.FIFO_Interrupt_Enabled := Value; This_Stream.FCR := Temp; end; else -- use the CR declare Temp : Stream_Config_Register; begin Temp := This_Stream.CR; case Source is when Direct_Mode_Error_Interrupt => Temp.DMEI_Enabled := Value; when Transfer_Error_Interrupt => Temp.TEI_Enabled := Value; when Half_Transfer_Complete_Interrupt => Temp.HTI_Enabled := Value; when Transfer_Complete_Interrupt => Temp.TCI_Enabled := Value; when FIFO_Error_Interrupt => -- not possible since we've already checked for it above null; end case; This_Stream.CR := Temp; end; end if; end Set_Interrupt_Enabler; ---------------------- -- Enable_Interrupt -- ---------------------- procedure Enable_Interrupt (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Source : DMA_Interrupt) is begin Set_Interrupt_Enabler (Unit.Streams (Stream), Source, True); end Enable_Interrupt; ----------------------- -- Disable_Interrupt -- ----------------------- procedure Disable_Interrupt (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Source : DMA_Interrupt) is begin Set_Interrupt_Enabler (Unit.Streams (Stream), Source, False); end Disable_Interrupt; ----------------------- -- Interrupt_Enabled -- ----------------------- function Interrupt_Enabled (Unit : DMA_Controller; Stream : DMA_Stream_Selector; Source : DMA_Interrupt) return Boolean is Result : Boolean; This_Stream : DMA_Stream renames Unit.Streams (Stream); -- this is a bit heavy, considering it will be called from interrupt -- handlers. -- TODO: consider a much lower level implementation, based on bit-masks. begin if Source = FIFO_Error_Interrupt then -- use the FCR declare Temp : FIFO_Control_Register; begin Temp := This_Stream.FCR; Result := Temp.FIFO_Interrupt_Enabled; end; else -- use the CR declare Temp : Stream_Config_Register; begin Temp := This_Stream.CR; case Source is when Direct_Mode_Error_Interrupt => Result := Temp.DMEI_Enabled; when Transfer_Error_Interrupt => Result := Temp.TEI_Enabled; when Half_Transfer_Complete_Interrupt => Result := Temp.HTI_Enabled; when Transfer_Complete_Interrupt => Result := Temp.TCI_Enabled; when FIFO_Error_Interrupt => -- not possible since we've already checked for it above null; end case; end; end if; return Result; end Interrupt_Enabled; -------------------- -- Start_Transfer -- -------------------- procedure Start_Transfer (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Source : Address; Destination : Address; Data_Count : Half_Word) is begin Disable (Unit, Stream); -- per the RM, eg section 10.5.6 for the NDTR Configure_Data_Flow (Unit, Stream, Source => Source, Destination => Destination, Data_Count => Data_Count); Enable (Unit, Stream); end Start_Transfer; ------------------------------------ -- Start_Transfer_with_Interrupts -- ------------------------------------ procedure Start_Transfer_With_Interrupts (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Source : Address; Destination : Address; Data_Count : Half_Word; Enabled_Interrupts : Interrupt_Selections := (others => True)) is begin Disable (Unit, Stream); -- per the RM, eg section 10.5.6 for the NDTR Configure_Data_Flow (Unit, Stream, Source => Source, Destination => Destination, Data_Count => Data_Count); for Selected_Interrupt in Enabled_Interrupts'Range loop if Enabled_Interrupts (Selected_Interrupt) then Enable_Interrupt (Unit, Stream, Selected_Interrupt); end if; end loop; Enable (Unit, Stream); end Start_Transfer_with_Interrupts; ------------------------- -- Configure_Data_Flow -- ------------------------- procedure Configure_Data_Flow (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Source : Address; Destination : Address; Data_Count : Half_Word) is This_Stream : DMA_Stream renames Unit.Streams (Stream); Temp : Stream_Config_Register; begin This_Stream.NDTR := Word (Data_Count); Temp := This_Stream.CR; if Temp.Direction = Memory_To_Peripheral then This_Stream.PAR := Destination; This_Stream.M0AR := Source; else This_Stream.PAR := Source; This_Stream.M0AR := Destination; end if; end Configure_Data_Flow; -------------------- -- Abort_Transfer -- -------------------- procedure Abort_Transfer (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Result : out DMA_Error_Code) is Max_Abort_Time : constant Time_Span := Seconds (1); Timeout : Time; This_Stream : DMA_Stream renames Unit.Streams (Stream); Temp : Stream_Config_Register; begin Disable (Unit, Stream); Timeout := Clock + Max_Abort_Time; loop Temp := This_Stream.CR; -- we need 32-bit accesses exit when not Temp.Stream_Enabled; if Clock > Timeout then Result := DMA_Timeout_Error; return; end if; end loop; Result := DMA_No_Error; end Abort_Transfer; ------------------------- -- Poll_For_Completion -- ------------------------- procedure Poll_For_Completion (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Expected_Level : DMA_Transfer_Level; Timeout : Time_Span; Result : out DMA_Error_Code) is Deadline : constant Time := Clock + Timeout; begin Result := DMA_No_Error; -- initially anyway Polling : loop if Expected_Level = Full_Transfer then exit when Status (Unit, Stream, Transfer_Complete_Indicated); else exit when Status (Unit, Stream, Half_Transfer_Complete_Indicated); end if; if Status (Unit, Stream, Transfer_Error_Indicated) or Status (Unit, Stream, FIFO_Error_Indicated) or Status (Unit, Stream, Direct_Mode_Error_Indicated) then Clear_Status (Unit, Stream, Transfer_Error_Indicated); Clear_Status (Unit, Stream, FIFO_Error_Indicated); Clear_Status (Unit, Stream, Direct_Mode_Error_Indicated); Result := DMA_Device_Error; return; end if; if Clock > Deadline then Result := DMA_Timeout_Error; return; end if; end loop Polling; Clear_Status (Unit, Stream, Half_Transfer_Complete_Indicated); if Expected_Level = Full_Transfer then Clear_Status (Unit, Stream, Transfer_Complete_Indicated); else Clear_Status (Unit, Stream, Half_Transfer_Complete_Indicated); end if; end Poll_For_Completion; ------------------ -- Clear_Status -- ------------------ procedure Clear_Status (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Flag : DMA_Status_Flag) is Group : constant Stream_Group := DMA_Stream_Selector'Pos (Stream) mod 4; Bit : constant Bit_Numbers := Status_Flag_Bits (Flag) (Group); Mask : constant Word := Shift_Left (1, Integer (Bit)); Temp : Word; begin if Stream < Stream_4 then Temp := Unit.LIFCR; Temp := Temp or Mask; -- yes, 1, because this is the CLEAR register Unit.LIFCR := Temp; else Temp := Unit.HIFCR; Temp := Temp or Mask; -- yes, 1, because this is the CLEAR register Unit.HIFCR := Temp; end if; end Clear_Status; ---------------------- -- Clear_All_Status -- ---------------------- procedure Clear_All_Status (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector) is Group : constant Stream_Group := DMA_Stream_Selector'Pos (Stream) mod 4; Temp : Word; begin if Stream < Stream_4 then Temp := Unit.LIFCR; else Temp := Unit.HIFCR; end if; for Flag in DMA_Status_Flag loop declare Bit : constant Bit_Numbers := Status_Flag_Bits (Flag) (Group); Mask : constant Word := Shift_Left (1, Integer (Bit)); begin Temp := Temp or Mask; end; end loop; if Stream < Stream_4 then Unit.LIFCR := Temp; else Unit.HIFCR := Temp; end if; end Clear_All_Status; ------------ -- Status -- ------------ function Status (Unit : DMA_Controller; Stream : DMA_Stream_Selector; Flag : DMA_Status_Flag) return Boolean is Group : constant Stream_Group := DMA_Stream_Selector'Pos (Stream) mod 4; Bit : constant Bit_Numbers := Status_Flag_Bits (Flag) (Group); Mask : constant Word := Shift_Left (1, Integer (Bit)); Temp : Word; begin if Stream < Stream_4 then Temp := Unit.LISR; else Temp := Unit.HISR; end if; return (Temp and Mask) = Mask; end Status; ----------------- -- Set_Counter -- ----------------- procedure Set_Counter (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Data_Count : Half_Word) is This_Stream : DMA_Stream renames Unit.Streams (Stream); begin This_Stream.NDTR := Word (Data_Count); end Set_Counter; --------------------- -- Current_Counter -- --------------------- function Current_Counter (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return Half_Word is This_Stream : DMA_Stream renames Unit.Streams (Stream); begin return Half_Word (This_Stream.NDTR); end Current_Counter; --------------------- -- Double_Buffered -- --------------------- function Double_Buffered (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return Boolean is CR : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return CR.Double_Buffered; end Double_Buffered; ------------------- -- Circular_Mode -- ------------------- function Circular_Mode (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return Boolean is CR : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return CR.Circular_Mode; end Circular_Mode; --------------- -- Configure -- --------------- procedure Configure (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Config : DMA_Stream_Configuration) is -- see HAL_DMA_Init in STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dma.h This_Stream : DMA_Stream renames Unit.Streams (Stream); begin -- the STMicro Reference Manual RM0090, Doc Id 018909 Rev 6, pg 319 says -- we must disable the stream before configuring it Disable (Unit, Stream); declare Temp : Stream_Config_Register := This_Stream.CR; begin Temp.Current_Target := Memory_Buffer_0; Temp.Channel := Config.Channel; Temp.Direction := Config.Direction; Temp.P_Inc_Mode := Config.Increment_Peripheral_Address; Temp.M_Inc_Mode := Config.Increment_Memory_Address; Temp.P_Data_Size := Config.Peripheral_Data_Format; Temp.M_Data_Size := Config.Memory_Data_Format; Temp.Priority := Config.Priority; case Config.Operation_Mode is when Normal_Mode => Temp.Circular_Mode := False; Temp.P_Flow_Controller := False; when Peripheral_Flow_Control_Mode => Temp.Circular_Mode := False; Temp.P_Flow_Controller := True; when Circular_Mode => Temp.Circular_Mode := True; Temp.P_Flow_Controller := False; end case; -- the memory burst and peripheral burst values are only used when -- the FIFO is enabled if Config.FIFO_Enabled then Temp.M_Burst := Config.Memory_Burst_Size; Temp.P_Burst := Config.Peripheral_Burst_Size; else Temp.M_Burst := Memory_Burst_Single; Temp.P_Burst := Peripheral_Burst_Single; end if; This_Stream.CR := Temp; end; declare Temp : FIFO_Control_Register := This_Stream.FCR; begin Temp.Direct_Mode_Enabled := not Config.FIFO_Enabled; if Config.FIFO_Enabled then Temp.FIFO_Threshold := Config.FIFO_Threshold; else Temp.FIFO_Threshold := FIFO_Threshold_1_Quart_Full_Configuration; -- 0, default end if; This_Stream.FCR := Temp; end; end Configure; ----------- -- Reset -- ----------- procedure Reset (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector) is This_Stream : DMA_Stream renames Unit.Streams (Stream); function As_Stream_Config_Register is new Ada.Unchecked_Conversion (Source => Word, Target => Stream_Config_Register); function As_FIFO_Control_Register is new Ada.Unchecked_Conversion (Source => Word, Target => FIFO_Control_Register); begin Disable (Unit, Stream); This_Stream.CR := As_Stream_Config_Register (0); This_Stream.NDTR := 0; This_Stream.PAR := System.Null_Address; This_Stream.M0AR := System.Null_Address; This_Stream.M1AR := System.Null_Address; -- Clear the FIFO control register bits except sets bit 5 to show FIFO -- is empty and bit 0 to set threshold selection to 1/2 full (???) This_Stream.FCR := As_FIFO_Control_Register (2#100001#); Clear_All_Status (Unit, Stream); end Reset; --------------------------- -- Peripheral_Data_Width -- --------------------------- function Peripheral_Data_Width (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Data_Transfer_Widths is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return Current.P_Data_Size; end Peripheral_Data_Width; ----------------------- -- Memory_Data_Width -- ----------------------- function Memory_Data_Width (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Data_Transfer_Widths is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return Current.M_Data_Size; end Memory_Data_Width; ------------------------ -- Transfer_Direction -- ------------------------ function Transfer_Direction (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Data_Transfer_Direction is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return Current.Direction; end Transfer_Direction; -------------------- -- Operating_Mode -- -------------------- function Operating_Mode (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Mode is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin if Current.P_Flow_Controller then return Peripheral_Flow_Control_Mode; elsif Current.Circular_Mode then return Circular_Mode; end if; return Normal_Mode; end Operating_Mode; -------------- -- Priority -- -------------- function Priority (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Priority_Level is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return Current.Priority; end Priority; --------------------------- -- Current_Memory_Buffer -- --------------------------- function Current_Memory_Buffer (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return Memory_Buffer_Target is CR : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return CR.Current_Target; end Current_Memory_Buffer; ----------------------- -- Set_Memory_Buffer -- ----------------------- procedure Set_Memory_Buffer (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Buffer : Memory_Buffer_Target; To : System.Address) is This_Stream : DMA_Stream renames Unit.Streams (Stream); begin case Buffer is when Memory_Buffer_0 => This_Stream.M0AR := To; when Memory_Buffer_1 => This_Stream.M1AR := To; end case; end Set_Memory_Buffer; ---------------------------------- -- Select_Current_Memory_Buffer -- ---------------------------------- procedure Select_Current_Memory_Buffer (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Buffer : Memory_Buffer_Target) is Temp_CR : Stream_Config_Register := Unit.Streams (Stream).CR; begin Temp_CR.Current_Target := Buffer; Unit.Streams (Stream).CR := Temp_CR; end Select_Current_Memory_Buffer; ------------------------------------ -- Configure_Double_Buffered_Mode -- ------------------------------------ procedure Configure_Double_Buffered_Mode (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector; Buffer_0_Value : Address; Buffer_1_Value : Address; First_Buffer_Used : Memory_Buffer_Target) is This_Stream : DMA_Stream renames Unit.Streams (Stream); Temp_CR : Stream_Config_Register := This_Stream.CR; begin This_Stream.M0AR := Buffer_0_Value; This_Stream.M1AR := Buffer_1_Value; Temp_CR.Current_Target := First_Buffer_Used; Unit.Streams (Stream).CR := Temp_CR; end Configure_Double_Buffered_Mode; --------------------------------- -- Enable_Double_Buffered_Mode -- --------------------------------- procedure Enable_Double_Buffered_Mode (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector) is Temp_CR : Stream_Config_Register := Unit.Streams (Stream).CR; begin Temp_CR.Double_Buffered := True; Unit.Streams (Stream).CR := Temp_CR; end Enable_Double_Buffered_Mode; ---------------------------------- -- Disable_Double_Buffered_Mode -- ---------------------------------- procedure Disable_Double_Buffered_Mode (Unit : in out DMA_Controller; Stream : DMA_Stream_Selector)is Temp_CR : Stream_Config_Register := Unit.Streams (Stream).CR; begin Temp_CR.Double_Buffered := False; Unit.Streams (Stream).CR := Temp_CR; end Disable_Double_Buffered_Mode; ---------------------- -- Selected_Channel -- ---------------------- function Selected_Channel (Unit : DMA_Controller; Stream : DMA_Stream_Selector) return DMA_Channel_Selector is Current : constant Stream_Config_Register := Unit.Streams (Stream).CR; begin return Current.Channel; end Selected_Channel; ------------- -- Aligned -- ------------- function Aligned (This : Address; Width : DMA_Data_Transfer_Widths) return Boolean is use System.Storage_Elements; begin case Width is when Words => return To_Integer (This) mod 4 = 0; when HalfWords => return To_Integer (This) mod 2 = 0; when Bytes => return True; end case; end Aligned; end STM32F4.DMA;
package VisitFailurePackage is VisitFailure: Exception; procedure RaiseVisitFailure(msg: String); end VisitFailurePackage;
-- ----------------------------------------------------------------- -- -- -- -- This is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public -- -- License as published by the Free Software Foundation; either -- -- version 2 of the License, or (at your option) any later version. -- -- -- -- This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public -- -- License along with this library; if not, write to the -- -- Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- -- Boston, MA 02111-1307, USA. -- -- -- -- ----------------------------------------------------------------- -- -- ----------------------------------------------------------------- -- -- This is a translation, to the Ada programming language, of the -- -- original C test files written by Sam Lantinga - www.libsdl.org -- -- translation made by Antonio F. Vargas - www.adapower.net/~avargas -- -- ----------------------------------------------------------------- -- with System.OS_Interface; with Interfaces.C.Strings; with Ada.Text_IO; use Ada.Text_IO; with GNAT.OS_Lib; with SDL.Thread; with SDL.Error; with SDL.Quit; with Lib_C; with TortureThread_Sprogs; use TortureThread_Sprogs; procedure TortureThread is package C renames Interfaces.C; use type C.int; package CS renames Interfaces.C.Strings; package Tr renames SDL.Thread; use type Tr.SDL_Thread_ptr; package Er renames SDL.Error; type threads_Array is array (C.int range 0 .. NUMTHREADS - 1) of Tr.SDL_Thread_ptr; pragma Convention (C, threads_Array); threads : threads_Array; begin -- Load the SDL library if SDL.Init(0) < 0 then Put_Line ("Couldn't initialize SDL: " & Er.Get_Error); GNAT.OS_Lib.OS_Exit (1); end if; SDL.Quit.atexit (SDL.SDL_Quit'Access); Lib_C.Set_Signal (System.OS_Interface.SIGSEGV, null); for i in threads'Range loop time_for_threads_to_die (i) := 0; threads (i) := Tr.CreateThread (ThreadFunc'Access, To_Address (i)); if threads (i) = Tr.null_SDL_Thread_ptr then Put_Line ("Couldn't create thread: " & Er.Get_Error); GNAT.OS_Lib.OS_Exit (1); end if; end loop; for i in time_for_threads_to_die'Range loop time_for_threads_to_die (i) := 1; end loop; for i in reverse threads'Range loop Tr.WaitThread (threads (i), null); end loop; GNAT.OS_Lib.OS_Exit (0); -- Never reached end TortureThread;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Logger.Facility is ------------------ -- error_mode -- ------------------ function error_mode (facility : LogFacility) return Error_Modes is begin return facility.prop_error_mode; end error_mode; ---------------------- -- set_error_mode -- ---------------------- procedure set_error_mode (facility : out LogFacility; mode : Error_Modes) is begin facility.prop_error_mode := mode; end set_error_mode; -------------------- -- set_log_file -- -------------------- procedure set_log_file (facility : LogFacility; filename : String) is begin facility.listener_file.all.set_filepath (filename); end set_log_file; --------------------- -- standard_logger -- --------------------- procedure standard_logger (facility : out LogFacility; logger : TLogger; action : TAction) is use type ALF.File_Logger_access; use type ALS.Screen_Logger_access; begin case logger is when screen => case action is when detach => if facility.listener_screen = null then raise ALREADY_DETACHED; else facility.listener_screen := null; end if; when attach => if facility.listener_screen = null then facility.listener_screen := logger_screen'Access; else raise ALREADY_ATTACHED; end if; end case; when file => case action is when detach => if facility.listener_file = null then raise ALREADY_DETACHED; else facility.listener_file := null; end if; when attach => if facility.listener_file = null then facility.listener_file := logger_file'Access; else raise ALREADY_ATTACHED; end if; end case; end case; end standard_logger; ---------------------------- -- detach_custom_logger -- ---------------------------- procedure detach_custom_logger (facility : out LogFacility) is use type AL.BaseClass_Logger_access; begin if facility.listener_custom = null then raise ALREADY_DETACHED; else facility.listener_custom := null; end if; end detach_custom_logger; ---------------------------- -- attach_custom_logger -- ---------------------------- procedure attach_custom_logger (facility : out LogFacility; logger_access : AL.BaseClass_Logger_access) is use type AL.BaseClass_Logger_access; begin if facility.listener_custom = null then facility.listener_custom := logger_access; else raise ALREADY_ATTACHED; end if; end attach_custom_logger; ------------------- -- log_nominal -- ------------------- procedure log_nominal (facility : LogFacility; driver : Driver_Type; category : Log_Category; message : CT.Text) is use type AL.Screen.Screen_Logger_access; use type AL.File.File_Logger_access; use type AL.BaseClass_Logger_access; begin if facility.listener_screen /= null then facility.listener_screen.all.set_information (driver => driver, category => category, message => message); facility.listener_screen.all.reaction; end if; if facility.listener_file /= null then facility.listener_file.all.set_information (driver => driver, category => category, message => message); facility.listener_file.all.reaction; end if; if facility.listener_custom /= null then facility.listener_custom.all.set_information (driver => driver, category => category, message => message); facility.listener_custom.all.reaction; end if; end log_nominal; ------------------- -- log_problem -- ------------------- procedure log_problem (facility : LogFacility; driver : Driver_Type; category : Log_Category; message : CT.Text; error_msg : CT.Text := CT.blank; error_code : Driver_Codes := 0; sqlstate : SQL_State := stateless; break : Boolean := False) is use type Error_Modes; use type AL.Screen.Screen_Logger_access; use type AL.File.File_Logger_access; use type AL.BaseClass_Logger_access; QND : constant String := CT.USS (message); begin if not break and then facility.prop_error_mode = silent then return; end if; if facility.listener_screen /= null then facility.listener_screen.all.set_information (driver => driver, category => category, message => message, error_msg => error_msg, error_code => error_code, sqlstate => sqlstate); facility.listener_screen.all.reaction; end if; if facility.listener_file /= null then facility.listener_file.all.set_information (driver => driver, category => category, message => message, error_msg => error_msg, error_code => error_code, sqlstate => sqlstate); facility.listener_file.all.reaction; end if; if facility.listener_custom /= null then facility.listener_custom.all.set_information (driver => driver, category => category, message => message, error_msg => error_msg, error_code => error_code, sqlstate => sqlstate); facility.listener_custom.all.reaction; end if; if break or else facility.prop_error_mode = raise_exception then raise ERRMODE_EXCEPTION with QND; end if; end log_problem; end AdaBase.Logger.Facility;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- Copyright (C) 2016, 2017, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Setup Application = -- The <tt>AWA.Setup</tt> package implements a simple setup application -- that allows to configure the database, the Google and Facebook application -- identifiers and some other configuration parameters. It is intended to -- help in the installation process of any AWA-based application. -- -- It defines a specific web application that is installed in the web container -- for the duration of the setup. The setup application takes control over all -- the web requests during the lifetime of the installation. As soon as the -- installation is finished, the normal application is configured and installed -- in the web container and the user is automatically redirected to it. -- -- == Integration == -- To be able to use the setup application, you will need to add the following -- line in your GNAT project file: -- -- with "awa_setup"; -- -- The setup application can be integrated as an AWA command by instantiating -- the `AWA.Commands.Setup` generic package. To integrate the `setup` command, -- you will do: -- -- with AWA.Commands.Start; -- with AWA.Commands.Setup; -- ... -- package Start_Command is new AWA.Commands.Start (Server_Commands); -- package Setup_Command is new AWA.Commands.Setup (Start_Command); -- -- @include awa-setup-applications.ads package AWA.Setup is pragma Pure; end AWA.Setup;