content
stringlengths
23
1.05M
with COBS; package body Test_Utils.Abstract_Encoder.COBS_Simple is ------------- -- Receive -- ------------- overriding procedure Receive (This : in out Instance; Data : Storage_Element) is begin This.Input.Append (Data); end Receive; ------------------ -- End_Of_Frame -- ------------------ overriding procedure End_Of_Frame (This : in out Instance) is begin if not This.Input.Is_Empty then declare In_Arr : Storage_Array_Access := To_Array_Access (This.Input); Max_Out : constant Storage_Count := COBS.Max_Encoding_Length (In_Arr'Length); Out_Arr : Storage_Array_Access := new Storage_Array (1 .. Max_Out); Success : Boolean; Last : Storage_Offset; begin COBS.Encode (Data => In_Arr.all, Output => Out_Arr.all, Output_Last => Last, Success => Success); if Success then for Elt of Out_Arr (Out_Arr'First .. Last) loop This.Push_To_Frame (Elt); end loop; end if; This.Push_To_Frame (0); This.Input.Clear; Free (In_Arr); Free (Out_Arr); end; end if; end End_Of_Frame; ------------ -- Update -- ------------ overriding procedure Update (This : in out Instance) is begin null; end Update; ----------------- -- End_Of_Test -- ----------------- overriding procedure End_Of_Test (This : in out Instance) is begin This.End_Of_Frame; This.Save_Frame; end End_Of_Test; end Test_Utils.Abstract_Encoder.COBS_Simple;
package Giza.Bitmap_Fonts.FreeMonoBold8pt7b is Font : constant Giza.Font.Ref_Const; private FreeMonoBold8pt7bBitmaps : aliased constant Font_Bitmap := ( 16#FF#, 16#FC#, 16#F0#, 16#49#, 16#24#, 16#92#, 16#48#, 16#36#, 16#36#, 16#36#, 16#FF#, 16#FF#, 16#3C#, 16#7F#, 16#7F#, 16#6C#, 16#6C#, 16#6C#, 16#30#, 16#F3#, 16#E6#, 16#0C#, 16#1F#, 16#8F#, 16#C3#, 16#C7#, 16#F8#, 16#C1#, 16#83#, 16#00#, 16#71#, 16#92#, 16#26#, 16#47#, 16#EE#, 16#23#, 16#09#, 16#12#, 16#18#, 16#3C#, 16#F9#, 16#83#, 16#07#, 16#1B#, 16#F3#, 16#7F#, 16#7E#, 16#49#, 16#24#, 16#36#, 16#64#, 16#CC#, 16#CC#, 16#C6#, 16#63#, 16#C6#, 16#62#, 16#33#, 16#33#, 16#36#, 16#6C#, 16#18#, 16#18#, 16#FF#, 16#7E#, 16#3C#, 16#7E#, 16#24#, 16#30#, 16#C3#, 16#3F#, 16#FC#, 16#C3#, 16#0C#, 16#30#, 16#6B#, 16#48#, 16#FF#, 16#FF#, 16#F0#, 16#02#, 16#0C#, 16#10#, 16#60#, 16#C3#, 16#06#, 16#18#, 16#30#, 16#C1#, 16#86#, 16#0C#, 16#00#, 16#3C#, 16#7E#, 16#E7#, 16#C3#, 16#C3#, 16#C3#, 16#C3#, 16#C3#, 16#E7#, 16#7E#, 16#3C#, 16#38#, 16#F1#, 16#60#, 16#C1#, 16#83#, 16#06#, 16#0C#, 16#7E#, 16#FC#, 16#79#, 16#FB#, 16#18#, 16#30#, 16#61#, 16#86#, 16#18#, 16#61#, 16#FF#, 16#F8#, 16#79#, 16#FC#, 16#18#, 16#31#, 16#C3#, 16#81#, 16#83#, 16#07#, 16#F9#, 16#E0#, 16#38#, 16#E5#, 16#96#, 16#9B#, 16#FF#, 16#CF#, 16#3C#, 16#7C#, 16#7C#, 16#60#, 16#7C#, 16#7E#, 16#03#, 16#03#, 16#43#, 16#FE#, 16#7C#, 16#1E#, 16#7D#, 16#86#, 16#0F#, 16#9F#, 16#B1#, 16#E3#, 16#C6#, 16#F8#, 16#E0#, 16#FF#, 16#FC#, 16#18#, 16#30#, 16#41#, 16#83#, 16#0C#, 16#18#, 16#20#, 16#3C#, 16#7E#, 16#C3#, 16#C3#, 16#C3#, 16#7E#, 16#7E#, 16#C3#, 16#C3#, 16#FF#, 16#3C#, 16#38#, 16#FB#, 16#1E#, 16#3C#, 16#6F#, 16#CF#, 16#83#, 16#0D#, 16#F3#, 16#C0#, 16#F0#, 16#3C#, 16#6C#, 16#00#, 16#D6#, 16#90#, 16#03#, 16#0E#, 16#38#, 16#E0#, 16#38#, 16#0E#, 16#03#, 16#FF#, 16#FF#, 16#00#, 16#FF#, 16#FF#, 16#C0#, 16#70#, 16#3C#, 16#0F#, 16#1C#, 16#70#, 16#C0#, 16#7D#, 16#FF#, 16#18#, 16#33#, 16#C2#, 16#00#, 16#00#, 16#30#, 16#60#, 16#3C#, 16#3F#, 16#38#, 16#D8#, 16#6C#, 16#F6#, 16#FB#, 16#CD#, 16#E6#, 16#FF#, 16#E7#, 16#D8#, 16#0F#, 16#E3#, 16#E0#, 16#7C#, 16#1F#, 16#81#, 16#E0#, 16#78#, 16#33#, 16#0C#, 16#C3#, 16#F1#, 16#FE#, 16#F3#, 16#FC#, 16#F0#, 16#FE#, 16#7F#, 16#98#, 16#CC#, 16#67#, 16#E3#, 16#F9#, 16#86#, 16#C3#, 16#FF#, 16#FF#, 16#80#, 16#3F#, 16#7F#, 16#E3#, 16#C0#, 16#C0#, 16#C0#, 16#C0#, 16#E0#, 16#7F#, 16#3E#, 16#FE#, 16#7F#, 16#98#, 16#EC#, 16#36#, 16#1B#, 16#0D#, 16#86#, 16#C7#, 16#FF#, 16#7F#, 16#00#, 16#FF#, 16#FF#, 16#63#, 16#78#, 16#78#, 16#78#, 16#7B#, 16#63#, 16#FF#, 16#FF#, 16#FF#, 16#FF#, 16#63#, 16#78#, 16#78#, 16#78#, 16#78#, 16#60#, 16#F8#, 16#F8#, 16#3F#, 16#3F#, 16#B8#, 16#D8#, 16#0C#, 16#06#, 16#7F#, 16#3F#, 16#C6#, 16#7F#, 16#1F#, 16#00#, 16#73#, 16#9C#, 16#E3#, 16#18#, 16#C6#, 16#3F#, 16#8F#, 16#E3#, 16#18#, 16#C6#, 16#F3#, 16#FC#, 16#F0#, 16#FF#, 16#F3#, 16#0C#, 16#30#, 16#C3#, 16#0C#, 16#FF#, 16#F0#, 16#1F#, 16#1F#, 16#06#, 16#06#, 16#06#, 16#06#, 16#C6#, 16#C6#, 16#FE#, 16#78#, 16#FE#, 16#FE#, 16#6C#, 16#78#, 16#70#, 16#78#, 16#6C#, 16#6C#, 16#F7#, 16#F7#, 16#F0#, 16#F0#, 16#60#, 16#60#, 16#60#, 16#60#, 16#63#, 16#63#, 16#FF#, 16#FF#, 16#E1#, 16#FC#, 16#F7#, 16#39#, 16#CE#, 16#7F#, 16#9B#, 16#66#, 16#D9#, 16#86#, 16#F3#, 16#FC#, 16#F0#, 16#E3#, 16#FC#, 16#F7#, 16#99#, 16#E6#, 16#6D#, 16#9B#, 16#66#, 16#79#, 16#9E#, 16#F3#, 16#BC#, 16#60#, 16#1E#, 16#1F#, 16#E6#, 16#1B#, 16#03#, 16#C0#, 16#F0#, 16#3C#, 16#0D#, 16#86#, 16#7F#, 16#87#, 16#80#, 16#FC#, 16#FE#, 16#63#, 16#63#, 16#63#, 16#7E#, 16#7E#, 16#60#, 16#F8#, 16#F8#, 16#1E#, 16#1F#, 16#E6#, 16#1B#, 16#03#, 16#C0#, 16#F0#, 16#3C#, 16#0D#, 16#86#, 16#7F#, 16#87#, 16#83#, 16#FC#, 16#FE#, 16#FE#, 16#7F#, 16#98#, 16#CC#, 16#67#, 16#E3#, 16#E1#, 16#98#, 16#C6#, 16#F3#, 16#F8#, 16#C0#, 16#3F#, 16#7F#, 16#C3#, 16#C0#, 16#FC#, 16#3E#, 16#07#, 16#C3#, 16#FE#, 16#FC#, 16#FF#, 16#FF#, 16#DB#, 16#DB#, 16#18#, 16#18#, 16#18#, 16#18#, 16#3C#, 16#3C#, 16#F3#, 16#FC#, 16#F6#, 16#19#, 16#86#, 16#61#, 16#98#, 16#66#, 16#19#, 16#86#, 16#3F#, 16#07#, 16#80#, 16#F3#, 16#FC#, 16#F6#, 16#18#, 16#84#, 16#33#, 16#0C#, 16#C1#, 16#A0#, 16#78#, 16#0C#, 16#03#, 16#00#, 16#F3#, 16#FC#, 16#F4#, 16#19#, 16#36#, 16#7D#, 16#9F#, 16#E7#, 16#F1#, 16#CC#, 16#73#, 16#0C#, 16#40#, 16#E3#, 16#B8#, 16#E6#, 16#30#, 16#F8#, 16#1C#, 16#0F#, 16#83#, 16#61#, 16#8C#, 16#F3#, 16#FC#, 16#F0#, 16#E3#, 16#F1#, 16#D8#, 16#C6#, 16#C1#, 16#E0#, 16#60#, 16#30#, 16#18#, 16#1E#, 16#0F#, 16#00#, 16#FD#, 16#FB#, 16#36#, 16#C1#, 16#06#, 16#19#, 16#E3#, 16#FF#, 16#FC#, 16#FF#, 16#6D#, 16#B6#, 16#DB#, 16#F0#, 16#C0#, 16#81#, 16#81#, 16#03#, 16#02#, 16#06#, 16#0C#, 16#0C#, 16#18#, 16#18#, 16#30#, 16#20#, 16#FD#, 16#B6#, 16#DB#, 16#6F#, 16#F0#, 16#10#, 16#70#, 16#F3#, 16#3C#, 16#20#, 16#FF#, 16#FF#, 16#F0#, 16#88#, 16#80#, 16#7C#, 16#7E#, 16#3E#, 16#FE#, 16#C6#, 16#FF#, 16#7F#, 16#E0#, 16#38#, 16#06#, 16#01#, 16#BC#, 16#7F#, 16#9C#, 16#76#, 16#0D#, 16#C7#, 16#FF#, 16#BB#, 16#C0#, 16#3F#, 16#7F#, 16#E3#, 16#C0#, 16#C1#, 16#7F#, 16#3E#, 16#07#, 16#03#, 16#80#, 16#C7#, 16#67#, 16#F7#, 16#1B#, 16#0D#, 16#86#, 16#7F#, 16#9F#, 16#C0#, 16#3C#, 16#FE#, 16#C2#, 16#FF#, 16#FF#, 16#FF#, 16#7E#, 16#3D#, 16#F6#, 16#3F#, 16#FD#, 16#86#, 16#18#, 16#FB#, 16#E0#, 16#3F#, 16#BF#, 16#F0#, 16#D8#, 16#6E#, 16#73#, 16#F8#, 16#EC#, 16#06#, 16#1F#, 16#0F#, 16#00#, 16#E0#, 16#70#, 16#18#, 16#0D#, 16#C7#, 16#F3#, 16#19#, 16#8C#, 16#C6#, 16#F7#, 16#FB#, 16#C0#, 16#18#, 16#30#, 16#03#, 16#C7#, 16#83#, 16#06#, 16#0C#, 16#FF#, 16#FC#, 16#31#, 16#81#, 16#FF#, 16#8C#, 16#63#, 16#18#, 16#C7#, 16#FF#, 16#00#, 16#E0#, 16#E0#, 16#60#, 16#7E#, 16#7E#, 16#78#, 16#70#, 16#7C#, 16#EF#, 16#EF#, 16#78#, 16#F0#, 16#60#, 16#C1#, 16#83#, 16#06#, 16#0C#, 16#FF#, 16#FC#, 16#FB#, 16#7F#, 16#DB#, 16#6D#, 16#B6#, 16#DF#, 16#6F#, 16#B6#, 16#EE#, 16#FF#, 16#63#, 16#63#, 16#63#, 16#F7#, 16#F7#, 16#3C#, 16#7E#, 16#C7#, 16#C3#, 16#C7#, 16#7E#, 16#3C#, 16#EF#, 16#3F#, 16#E7#, 16#0D#, 16#83#, 16#71#, 16#DF#, 16#E6#, 16#F1#, 16#80#, 16#F8#, 16#3E#, 16#00#, 16#3D#, 16#DF#, 16#FE#, 16#3B#, 16#06#, 16#E3#, 16#9F#, 16#E3#, 16#D8#, 16#06#, 16#07#, 16#C1#, 16#F0#, 16#EE#, 16#FF#, 16#70#, 16#60#, 16#60#, 16#F8#, 16#F8#, 16#7F#, 16#FF#, 16#1B#, 16#E8#, 16#7F#, 16#FF#, 16#00#, 16#60#, 16#C1#, 16#87#, 16#EF#, 16#CC#, 16#18#, 16#31#, 16#7E#, 16#78#, 16#E7#, 16#73#, 16#98#, 16#CC#, 16#66#, 16#33#, 16#FC#, 16#FE#, 16#F7#, 16#FB#, 16#D8#, 16#C6#, 16#C3#, 16#60#, 16#E0#, 16#70#, 16#E3#, 16#F1#, 16#DB#, 16#6F#, 16#F3#, 16#71#, 16#B8#, 16#8C#, 16#77#, 16#3B#, 16#87#, 16#03#, 16#83#, 16#63#, 16#BB#, 16#DE#, 16#E3#, 16#F1#, 16#D8#, 16#CC#, 16#43#, 16#61#, 16#E0#, 16#60#, 16#70#, 16#F8#, 16#7C#, 16#00#, 16#FF#, 16#FD#, 16#8C#, 16#43#, 16#FF#, 16#C0#, 16#37#, 16#66#, 16#6C#, 16#C6#, 16#66#, 16#73#, 16#FF#, 16#FF#, 16#FF#, 16#CE#, 16#66#, 16#63#, 16#36#, 16#66#, 16#EC#, 16#70#, 16#F8#, 16#1F#, 16#0E#); FreeMonoBold8pt7bGlyphs : aliased constant Glyph_Array := ( (0, 0, 0, 10, 0, 1), -- 0x20 ' ' (0, 2, 10, 10, 4, -9), -- 0x21 '!' (3, 6, 5, 10, 2, -9), -- 0x22 '"' (7, 8, 11, 10, 1, -9), -- 0x23 '#' (18, 7, 13, 10, 2, -10), -- 0x24 '$' (30, 7, 10, 10, 1, -9), -- 0x25 '%' (39, 7, 9, 10, 1, -8), -- 0x26 '&' (47, 3, 5, 10, 3, -9), -- 0x27 ''' (49, 4, 12, 10, 4, -9), -- 0x28 '(' (55, 4, 12, 10, 2, -9), -- 0x29 ')' (61, 8, 7, 10, 1, -9), -- 0x2A '*' (68, 6, 9, 10, 2, -8), -- 0x2B '+' (75, 3, 5, 10, 2, -1), -- 0x2C ',' (77, 8, 2, 10, 1, -5), -- 0x2D '-' (79, 2, 2, 10, 4, -1), -- 0x2E '.' (80, 7, 13, 10, 1, -10), -- 0x2F '/' (92, 8, 11, 10, 1, -10), -- 0x30 '0' (103, 7, 10, 10, 1, -9), -- 0x31 '1' (112, 7, 11, 10, 1, -10), -- 0x32 '2' (122, 7, 11, 10, 2, -10), -- 0x33 '3' (132, 6, 9, 10, 3, -8), -- 0x34 '4' (139, 8, 10, 10, 1, -9), -- 0x35 '5' (149, 7, 11, 10, 2, -10), -- 0x36 '6' (159, 7, 10, 10, 1, -9), -- 0x37 '7' (168, 8, 11, 10, 1, -10), -- 0x38 '8' (179, 7, 11, 10, 2, -10), -- 0x39 '9' (189, 2, 7, 10, 4, -6), -- 0x3A ':' (191, 3, 10, 10, 2, -6), -- 0x3B ';' (195, 8, 7, 10, 1, -7), -- 0x3C '<' (202, 8, 5, 10, 1, -6), -- 0x3D '=' (207, 8, 7, 10, 1, -7), -- 0x3E '>' (214, 7, 10, 10, 2, -9), -- 0x3F '?' (223, 9, 13, 10, 1, -10), -- 0x40 '@' (238, 10, 10, 10, 0, -9), -- 0x41 'A' (251, 9, 10, 10, 1, -9), -- 0x42 'B' (263, 8, 10, 10, 1, -9), -- 0x43 'C' (273, 9, 10, 10, 0, -9), -- 0x44 'D' (285, 8, 10, 10, 1, -9), -- 0x45 'E' (295, 8, 10, 10, 1, -9), -- 0x46 'F' (305, 9, 10, 10, 1, -9), -- 0x47 'G' (317, 10, 10, 10, 0, -9), -- 0x48 'H' (330, 6, 10, 10, 2, -9), -- 0x49 'I' (338, 8, 10, 10, 1, -9), -- 0x4A 'J' (348, 8, 10, 10, 1, -9), -- 0x4B 'K' (358, 8, 10, 10, 2, -9), -- 0x4C 'L' (368, 10, 10, 10, 0, -9), -- 0x4D 'M' (381, 10, 10, 10, 0, -9), -- 0x4E 'N' (394, 10, 10, 10, 0, -9), -- 0x4F 'O' (407, 8, 10, 10, 1, -9), -- 0x50 'P' (417, 10, 12, 10, 0, -9), -- 0x51 'Q' (432, 9, 10, 10, 0, -9), -- 0x52 'R' (444, 8, 10, 10, 1, -9), -- 0x53 'S' (454, 8, 10, 10, 1, -9), -- 0x54 'T' (464, 10, 10, 10, 0, -9), -- 0x55 'U' (477, 10, 10, 10, 0, -9), -- 0x56 'V' (490, 10, 10, 10, 0, -9), -- 0x57 'W' (503, 10, 10, 10, 0, -9), -- 0x58 'X' (516, 9, 10, 10, 0, -9), -- 0x59 'Y' (528, 7, 10, 10, 2, -9), -- 0x5A 'Z' (537, 3, 12, 10, 4, -9), -- 0x5B '[' (542, 7, 13, 10, 1, -10), -- 0x5C '\' (554, 3, 12, 10, 2, -9), -- 0x5D ']' (559, 7, 5, 10, 1, -9), -- 0x5E '^' (564, 10, 2, 10, 0, 2), -- 0x5F '_' (567, 3, 3, 10, 3, -10), -- 0x60 '`' (569, 8, 7, 10, 1, -6), -- 0x61 'a' (576, 10, 10, 10, 0, -9), -- 0x62 'b' (589, 8, 7, 10, 1, -6), -- 0x63 'c' (596, 9, 10, 10, 1, -9), -- 0x64 'd' (608, 8, 7, 10, 1, -6), -- 0x65 'e' (615, 6, 10, 10, 2, -9), -- 0x66 'f' (623, 9, 10, 10, 1, -6), -- 0x67 'g' (635, 9, 10, 10, 1, -9), -- 0x68 'h' (647, 7, 10, 10, 1, -9), -- 0x69 'i' (656, 5, 13, 10, 3, -9), -- 0x6A 'j' (665, 8, 10, 10, 1, -9), -- 0x6B 'k' (675, 7, 10, 10, 1, -9), -- 0x6C 'l' (684, 9, 7, 10, 0, -6), -- 0x6D 'm' (692, 8, 7, 10, 1, -6), -- 0x6E 'n' (699, 8, 7, 10, 1, -6), -- 0x6F 'o' (706, 10, 10, 10, 0, -6), -- 0x70 'p' (719, 10, 10, 10, 0, -6), -- 0x71 'q' (732, 8, 7, 10, 2, -6), -- 0x72 'r' (739, 7, 7, 10, 2, -6), -- 0x73 's' (746, 7, 10, 10, 1, -9), -- 0x74 't' (755, 9, 7, 10, 1, -6), -- 0x75 'u' (763, 9, 7, 10, 0, -6), -- 0x76 'v' (771, 9, 7, 10, 0, -6), -- 0x77 'w' (779, 9, 7, 10, 0, -6), -- 0x78 'x' (787, 9, 10, 10, 0, -6), -- 0x79 'y' (799, 6, 7, 10, 2, -6), -- 0x7A 'z' (805, 4, 12, 10, 3, -9), -- 0x7B '{' (811, 2, 12, 10, 4, -9), -- 0x7C '|' (814, 4, 12, 10, 3, -9), -- 0x7D '}' (820, 8, 4, 10, 1, -6)); -- 0x7E '~' Font_D : aliased constant Bitmap_Font := (FreeMonoBold8pt7bBitmaps'Access, FreeMonoBold8pt7bGlyphs'Access, 16); Font : constant Giza.Font.Ref_Const := Font_D'Access; end Giza.Bitmap_Fonts.FreeMonoBold8pt7b;
----------------------------------------------------------------------- -- util-beans-objects -- Generic Typed Data Representation -- Copyright (C) 2009, 2010, 2011, 2013, 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. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Unchecked_Deallocation; with Ada.Tags; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Beans.Basic; package body Util.Beans.Objects is use Util.Concurrent.Counters; use Ada.Characters.Conversions; function UTF8_Decode (S : in String) return Wide_Wide_String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; -- Find the data type to be used for an arithmetic operation between two objects. function Get_Arithmetic_Type (Left, Right : Object) return Data_Type; -- Find the data type to be used for a composition operation between two objects. function Get_Compose_Type (Left, Right : Object) return Data_Type; -- Find the best type to be used to compare two operands. function Get_Compare_Type (Left, Right : Object) return Data_Type; Integer_Type : aliased constant Int_Type := Int_Type '(null record); Bool_Type : aliased constant Boolean_Type := Boolean_Type '(null record); Str_Type : aliased constant String_Type := String_Type '(null record); WString_Type : aliased constant Wide_String_Type := Wide_String_Type '(null record); Flt_Type : aliased constant Float_Type := Float_Type '(null record); Duration_Type : aliased constant Duration_Type_Def := Duration_Type_Def '(null record); Bn_Type : aliased constant Bean_Type := Bean_Type '(null record); Ar_Type : aliased constant Array_Type := Array_Type '(null record); -- ------------------------------ -- Convert the value into a wide string. -- ------------------------------ function To_Wide_Wide_String (Type_Def : in Basic_Type; Value : in Object_Value) return Wide_Wide_String is begin return UTF8_Decode (Object_Type'Class (Type_Def).To_String (Value)); end To_Wide_Wide_String; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Basic_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def, Value); begin return 0.0; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Basic_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def, Value); begin return False; end To_Boolean; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in Basic_Type; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def, Value); begin return 0.0; end To_Duration; -- ------------------------------ -- Returns False -- ------------------------------ function Is_Empty (Type_Def : in Basic_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def, Value); begin return False; end Is_Empty; -- ------------------------------ -- Null Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : Null_Type) return String is pragma Unreferenced (Type_Def); begin return "Null"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : Null_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_NULL; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Null_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def, Value); begin return "null"; end To_String; -- ------------------------------ -- Returns True -- ------------------------------ function Is_Empty (Type_Def : in Null_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def, Value); begin return True; end Is_Empty; -- ------------------------------ -- Integer Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : Int_Type) return String is pragma Unreferenced (Type_Def); begin return "Integer"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : Int_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_INTEGER; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Int_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); S : constant String := Long_Long_Integer'Image (Value.Int_Value); begin if Value.Int_Value >= 0 then return S (S'First + 1 .. S'Last); else return S; end if; end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Int_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); begin return Value.Int_Value; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Int_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); begin return Long_Long_Float (Value.Int_Value); end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Int_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); begin return Value.Int_Value /= 0; end To_Boolean; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in Int_Type; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def); begin return Duration (Value.Int_Value); end To_Duration; -- ------------------------------ -- Float Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Float_Type) return String is pragma Unreferenced (Type_Def); begin return "Float"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Float_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_FLOAT; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Float_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Long_Long_Float'Image (Value.Float_Value); end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Float_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); begin return Long_Long_Integer (Value.Float_Value); end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Float_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); begin return Value.Float_Value; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Float_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); begin return Value.Float_Value /= 0.0; end To_Boolean; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in Float_Type; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def); begin return Duration (Value.Float_Value); end To_Duration; -- ------------------------------ -- String Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in String_Type) return String is pragma Unreferenced (Type_Def); begin return "String"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in String_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_STRING; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in String_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin if Proxy = null then return "null"; else return Proxy.Value; end if; end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in String_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin if Proxy = null then return 0; else return Long_Long_Integer'Value (Proxy.Value); end if; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in String_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin if Proxy = null then return 0.0; else return Long_Long_Float'Value (Proxy.Value); end if; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in String_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin return Proxy /= null and then (Proxy.Value = "true" or Proxy.Value = "TRUE" or Proxy.Value = "1"); end To_Boolean; -- ------------------------------ -- Returns True if the value is empty. -- ------------------------------ function Is_Empty (Type_Def : in String_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin return Proxy = null or else Proxy.Value = ""; end Is_Empty; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in String_Type; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def); Proxy : constant String_Proxy_Access := Value.String_Proxy; begin if Proxy = null then return 0.0; else return Duration'Value (Proxy.Value); end if; end To_Duration; -- ------------------------------ -- Wide String Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Wide_String_Type) return String is pragma Unreferenced (Type_Def); begin return "WideString"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Wide_String_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_WIDE_STRING; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Wide_String_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin if Proxy = null then return "null"; else return To_String (Proxy.Value); end if; end To_String; -- ------------------------------ -- Convert the value into a wide string. -- ------------------------------ function To_Wide_Wide_String (Type_Def : in Wide_String_Type; Value : in Object_Value) return Wide_Wide_String is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin if Proxy = null then return "null"; else return Proxy.Value; end if; end To_Wide_Wide_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Wide_String_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin if Proxy = null then return 0; else return Long_Long_Integer'Value (To_String (Proxy.Value)); end if; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Wide_String_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin if Proxy = null then return 0.0; else return Long_Long_Float'Value (To_String (Proxy.Value)); end if; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Wide_String_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin return Proxy /= null and then (Proxy.Value = "true" or Proxy.Value = "TRUE" or Proxy.Value = "1"); end To_Boolean; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in Wide_String_Type; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin if Proxy = null then return 0.0; else return Duration'Value (To_String (Proxy.Value)); end if; end To_Duration; -- ------------------------------ -- Returns True if the value is empty. -- ------------------------------ function Is_Empty (Type_Def : in Wide_String_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant Wide_String_Proxy_Access := Value.Wide_Proxy; begin return Proxy = null or else Proxy.Value = ""; end Is_Empty; -- ------------------------------ -- Boolean Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Boolean_Type) return String is pragma Unreferenced (Type_Def); begin return "Boolean"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Boolean_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_BOOLEAN; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Boolean_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin if Value.Bool_Value then return "TRUE"; else return "FALSE"; end if; end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Boolean_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); begin if Value.Bool_Value then return 1; else return 0; end if; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Boolean_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); begin if Value.Bool_Value then return 1.0; else return 0.0; end if; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Boolean_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); begin return Value.Bool_Value; end To_Boolean; -- ------------------------------ -- Duration Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Duration_Type_Def) return String is pragma Unreferenced (Type_Def); begin return "Duration"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Duration_Type_Def) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_TIME; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Duration_Type_Def; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Duration'Image (Value.Time_Value); end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Duration_Type_Def; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def); begin return Long_Long_Integer (Value.Time_Value); end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Duration_Type_Def; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def); begin return Long_Long_Float (Value.Time_Value); end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Duration_Type_Def; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); begin return Value.Time_Value > 0.0; end To_Boolean; -- ------------------------------ -- Convert the value into a duration. -- ------------------------------ function To_Duration (Type_Def : in Duration_Type_Def; Value : in Object_Value) return Duration is pragma Unreferenced (Type_Def); begin return Value.Time_Value; end To_Duration; -- ------------------------------ -- Bean Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Bean_Type) return String is pragma Unreferenced (Type_Def); begin return "Bean"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Bean_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_BEAN; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Bean_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin if Value.Proxy = null then return "<null bean>"; else return "<" & Ada.Tags.Expanded_Name (Value.Proxy'Tag) & ">"; end if; end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Bean_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def, Value); begin return 0; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Bean_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def, Value); begin return 0.0; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Bean_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant Bean_Proxy_Access := Value.Proxy; begin return Proxy /= null; end To_Boolean; -- ------------------------------ -- Returns True if the value is empty. -- ------------------------------ function Is_Empty (Type_Def : in Bean_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant Bean_Proxy_Access := Value.Proxy; begin if Proxy = null then return True; end if; if not (Proxy.all in Bean_Proxy'Class) then return False; end if; if not (Bean_Proxy (Proxy.all).Bean.all in Util.Beans.Basic.List_Bean'Class) then return False; end if; declare L : constant Util.Beans.Basic.List_Bean_Access := Beans.Basic.List_Bean'Class (Bean_Proxy (Proxy.all).Bean.all)'Unchecked_Access; begin return L.Get_Count = 0; end; end Is_Empty; -- ------------------------------ -- Array Type -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Array_Type) return String is pragma Unreferenced (Type_Def); begin return "Array"; end Get_Name; -- ------------------------------ -- Get the base data type. -- ------------------------------ function Get_Data_Type (Type_Def : in Array_Type) return Data_Type is pragma Unreferenced (Type_Def); begin return TYPE_ARRAY; end Get_Data_Type; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Array_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin if Value.Array_Proxy = null then return "<null array>"; else return "<array>"; end if; end To_String; -- ------------------------------ -- Convert the value into an integer. -- ------------------------------ function To_Long_Long (Type_Def : in Array_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def, Value); begin return 0; end To_Long_Long; -- ------------------------------ -- Convert the value into a float. -- ------------------------------ function To_Long_Float (Type_Def : in Array_Type; Value : in Object_Value) return Long_Long_Float is pragma Unreferenced (Type_Def, Value); begin return 0.0; end To_Long_Float; -- ------------------------------ -- Convert the value into a boolean. -- ------------------------------ function To_Boolean (Type_Def : in Array_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); Proxy : constant Bean_Proxy_Access := Value.Proxy; begin return Proxy /= null; end To_Boolean; -- ------------------------------ -- Returns True if the value is empty. -- ------------------------------ function Is_Empty (Type_Def : in Array_Type; Value : in Object_Value) return Boolean is pragma Unreferenced (Type_Def); begin if Value.Array_Proxy = null then return True; else return Value.Array_Proxy.Len = 0; end if; end Is_Empty; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_Long_Long (Type_Def : in Basic_Type; Value : in Object_Value) return Long_Long_Integer is pragma Unreferenced (Type_Def, Value); begin return 0; end To_Long_Long; -- ------------------------------ -- Check whether the object contains a value. -- Returns true if the object does not contain a value. -- ------------------------------ function Is_Null (Value : in Object) return Boolean is begin return Value.V.Of_Type = TYPE_NULL; end Is_Null; -- ------------------------------ -- Check whether the object is empty. -- If the object is null, returns true. -- If the object is the empty string, returns true. -- If the object is a list bean whose Get_Count is 0, returns true. -- Otherwise returns false. -- ------------------------------ function Is_Empty (Value : in Object) return Boolean is begin return Value.Type_Def.Is_Empty (Value.V); end Is_Empty; function Get_Array_Bean (Value : in Object) return access Util.Beans.Basic.Array_Bean'Class is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (Value); begin if Bean = null or else not (Bean.all in Util.Beans.Basic.Array_Bean'Class) then return null; else return Util.Beans.Basic.Array_Bean'Class (Bean.all)'Access; end if; end Get_Array_Bean; -- ------------------------------ -- Returns True if the object is an array. -- ------------------------------ function Is_Array (Value : in Object) return Boolean is begin if Value.V.Of_Type = TYPE_ARRAY then return True; elsif Value.V.Of_Type /= TYPE_BEAN then return False; else return Get_Array_Bean (Value) /= null; end if; end Is_Array; -- ------------------------------ -- Generic Object holding a value -- ------------------------------ -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Type_Name (Value : in Object) return String is begin return Value.Type_Def.Get_Name; end Get_Type_Name; -- ------------------------------ -- Get a type identification for the object value. -- ------------------------------ function Get_Type (Value : in Object) return Data_Type is begin return Value.V.Of_Type; end Get_Type; -- ------------------------------ -- Get the type definition of the object value. -- ------------------------------ function Get_Type (Value : Object) return Object_Type_Access is begin return Value.Type_Def; end Get_Type; -- ------------------------------ -- Get the value identified by the name in the bean object. -- If the value object is not a bean, returns the null object. -- ------------------------------ function Get_Value (Value : in Object; Name : in String) return Object is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (Value); begin if Bean = null then return Null_Object; else return Bean.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set into the target object a value identified by the name. -- The target object must be a <tt>Bean</tt> instance that implements the <tt>Set_Value</tt> -- procedure. The operation does nothing if this is not the case. -- ------------------------------ procedure Set_Value (Into : in Object; Name : in String; Value : in Object) is Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (Into); begin if Bean /= null and then Bean.all in Util.Beans.Basic.Bean'Class then Util.Beans.Basic.Bean'Class (Bean.all).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Get the number of elements in the array object. -- Returns 0 if the object is not an array. -- ------------------------------ function Get_Count (From : in Object) return Natural is use type Util.Beans.Basic.Array_Bean_Access; Bean : Util.Beans.Basic.Array_Bean_Access; begin if From.V.Of_Type = TYPE_ARRAY then return From.V.Array_Proxy.Len; elsif From.V.Of_Type /= TYPE_BEAN or else From.V.Proxy = null then return 0; else Bean := Get_Array_Bean (From); if Bean = null then return 0; else return Bean.Get_Count; end if; end if; end Get_Count; -- ------------------------------ -- Get the array element at the given position. -- ------------------------------ function Get_Value (From : in Object; Position : in Positive) return Object is use type Util.Beans.Basic.Array_Bean_Access; Bean : Util.Beans.Basic.Array_Bean_Access; begin if From.V.Of_Type = TYPE_BEAN then Bean := Get_Array_Bean (From); if Bean /= null then return Bean.Get_Row (Position); else return Null_Object; end if; elsif From.V.Of_Type /= TYPE_ARRAY then return Null_Object; elsif From.V.Array_Proxy.Len < Position then return Null_Object; else return From.V.Array_Proxy.Values (Position); end if; end Get_Value; -- ------------------------------ -- Convert the object to the corresponding type. -- ------------------------------ function To_String (Value : Object) return String is begin return Value.Type_Def.To_String (Value.V); end To_String; -- ------------------------------ -- Convert the object to a wide string. -- ------------------------------ function To_Wide_Wide_String (Value : Object) return Wide_Wide_String is begin return Value.Type_Def.To_Wide_Wide_String (Value.V); end To_Wide_Wide_String; -- ------------------------------ -- Convert the object to an unbounded string. -- ------------------------------ function To_Unbounded_String (Value : Object) return Unbounded_String is begin case Value.V.Of_Type is when TYPE_STRING => if Value.V.String_Proxy = null then return To_Unbounded_String ("null"); end if; return To_Unbounded_String (Value.V.String_Proxy.Value); when others => return To_Unbounded_String (To_String (Value)); end case; end To_Unbounded_String; -- ------------------------------ -- Convert the object to an unbounded wide string. -- ------------------------------ function To_Unbounded_Wide_Wide_String (Value : Object) return Unbounded_Wide_Wide_String is begin case Value.V.Of_Type is when TYPE_WIDE_STRING => if Value.V.Wide_Proxy = null then return To_Unbounded_Wide_Wide_String ("null"); end if; return To_Unbounded_Wide_Wide_String (Value.V.Wide_Proxy.Value); when TYPE_STRING => if Value.V.String_Proxy = null then return To_Unbounded_Wide_Wide_String ("null"); end if; return To_Unbounded_Wide_Wide_String (UTF8_Decode (Value.V.String_Proxy.Value)); when others => return To_Unbounded_Wide_Wide_String (To_Wide_Wide_String (To_String (Value))); end case; end To_Unbounded_Wide_Wide_String; -- ------------------------------ -- Convert the object to an integer. -- ------------------------------ function To_Integer (Value : Object) return Integer is begin return Integer (Value.Type_Def.To_Long_Long (Value.V)); end To_Integer; -- ------------------------------ -- Convert the object to an integer. -- ------------------------------ function To_Long_Integer (Value : Object) return Long_Integer is begin return Long_Integer (Value.Type_Def.To_Long_Long (Value.V)); end To_Long_Integer; -- ------------------------------ -- Convert the object to a long integer. -- ------------------------------ function To_Long_Long_Integer (Value : Object) return Long_Long_Integer is begin return Value.Type_Def.To_Long_Long (Value.V); end To_Long_Long_Integer; -- ------------------------------ -- Convert the object to a duration. -- ------------------------------ function To_Duration (Value : in Object) return Duration is begin return Value.Type_Def.To_Duration (Value.V); end To_Duration; function To_Bean (Value : in Object) return access Util.Beans.Basic.Readonly_Bean'Class is -- Proxy : constant Bean_Proxy_Access; begin if Value.V.Of_Type = TYPE_BEAN and then Value.V.Proxy /= null then return Bean_Proxy (Value.V.Proxy.all).Bean; else return null; end if; end To_Bean; -- ------------------------------ -- Convert the object to a boolean. -- ------------------------------ function To_Boolean (Value : Object) return Boolean is begin return Value.Type_Def.To_Boolean (Value.V); end To_Boolean; -- ------------------------------ -- Convert the object to a float. -- ------------------------------ function To_Float (Value : Object) return Float is begin return Float (Value.Type_Def.To_Long_Float (Value.V)); end To_Float; -- ------------------------------ -- Convert the object to a long float. -- ------------------------------ function To_Long_Float (Value : Object) return Long_Float is begin return Long_Float (Value.Type_Def.To_Long_Float (Value.V)); end To_Long_Float; -- ------------------------------ -- Convert the object to a long float. -- ------------------------------ function To_Long_Long_Float (Value : Object) return Long_Long_Float is begin return Value.Type_Def.To_Long_Float (Value.V); end To_Long_Long_Float; -- ------------------------------ -- Convert an integer into a generic typed object. -- ------------------------------ function To_Object (Value : Integer) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (Value)), Type_Def => Integer_Type'Access); end To_Object; -- ------------------------------ -- Convert an integer into a generic typed object. -- ------------------------------ function To_Object (Value : Long_Integer) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (Value)), Type_Def => Integer_Type'Access); end To_Object; -- ------------------------------ -- Convert an integer into a generic typed object. -- ------------------------------ function To_Object (Value : Long_Long_Integer) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Value), Type_Def => Integer_Type'Access); end To_Object; -- ------------------------------ -- Convert a boolean into a generic typed object. -- ------------------------------ function To_Object (Value : Boolean) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_BOOLEAN, Bool_Value => Value), Type_Def => Bool_Type'Access); end To_Object; -- ------------------------------ -- Convert a float into a generic typed object. -- ------------------------------ function To_Object (Value : Float) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_FLOAT, Float_Value => Long_Long_Float (Value)), Type_Def => Flt_Type'Access); end To_Object; -- ------------------------------ -- Convert a long float into a generic typed object. -- ------------------------------ function To_Object (Value : Long_Float) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_FLOAT, Float_Value => Long_Long_Float (Value)), Type_Def => Flt_Type'Access); end To_Object; -- ------------------------------ -- Convert a long long float into a generic typed object. -- ------------------------------ function To_Object (Value : Long_Long_Float) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_FLOAT, Float_Value => Value), Type_Def => Flt_Type'Access); end To_Object; -- ------------------------------ -- Convert a duration into a generic typed object. -- ------------------------------ function To_Object (Value : in Duration) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value), Type_Def => Duration_Type'Access); end To_Object; -- ------------------------------ -- Convert a string into a generic typed object. -- ------------------------------ function To_Object (Value : String) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_STRING, String_Proxy => new String_Proxy '(Ref_Counter => ONE, Len => Value'Length, Value => Value)), Type_Def => Str_Type'Access); end To_Object; -- ------------------------------ -- Convert a wide string into a generic typed object. -- ------------------------------ function To_Object (Value : Wide_Wide_String) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_WIDE_STRING, Wide_Proxy => new Wide_String_Proxy '(Ref_Counter => ONE, Len => Value'Length, Value => Value)), Type_Def => WString_Type'Access); end To_Object; -- ------------------------------ -- Convert an unbounded string into a generic typed object. -- ------------------------------ function To_Object (Value : Unbounded_String) return Object is Len : constant Natural := Length (Value); begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_STRING, String_Proxy => new String_Proxy '(Ref_Counter => ONE, Len => Len, Value => To_String (Value))), Type_Def => Str_Type'Access); end To_Object; -- ------------------------------ -- Convert a unbounded wide string into a generic typed object. -- ------------------------------ function To_Object (Value : Unbounded_Wide_Wide_String) return Object is Len : constant Natural := Length (Value); begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_WIDE_STRING, Wide_Proxy => new Wide_String_Proxy '(Ref_Counter => ONE, Len => Len, Value => To_Wide_Wide_String (Value))), Type_Def => WString_Type'Access); end To_Object; function To_Object (Value : access Util.Beans.Basic.Readonly_Bean'Class; Storage : in Storage_Type := DYNAMIC) return Object is begin if Value = null then return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_BEAN, Proxy => null), Type_Def => Bn_Type'Access); else return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_BEAN, Proxy => new Bean_Proxy '(Ref_Counter => ONE, Bean => Value, Storage => Storage)), Type_Def => Bn_Type'Access); end if; end To_Object; function To_Object (Value : in Object_Array) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_ARRAY, Array_Proxy => new Array_Proxy '(Ref_Counter => ONE, Len => Value'Length, Count => Value'Length, Values => Value)), Type_Def => Ar_Type'Access); end To_Object; -- ------------------------------ -- Convert the object to an object of another time. -- Force the object to be an integer. -- ------------------------------ function Cast_Integer (Value : Object) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Value.Type_Def.To_Long_Long (Value.V)), Type_Def => Integer_Type'Access); end Cast_Integer; -- ------------------------------ -- Force the object to be a float. -- ------------------------------ function Cast_Float (Value : Object) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_FLOAT, Float_Value => Value.Type_Def.To_Long_Float (Value.V)), Type_Def => Flt_Type'Access); end Cast_Float; -- ------------------------------ -- Convert the object to an object of another time. -- Force the object to be a duration. -- ------------------------------ function Cast_Duration (Value : Object) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value.Type_Def.To_Duration (Value.V)), Type_Def => Duration_Type'Access); end Cast_Duration; -- ------------------------------ -- Force the object to be a string. -- ------------------------------ function Cast_String (Value : Object) return Object is begin if Value.V.Of_Type = TYPE_STRING or Value.V.Of_Type = TYPE_WIDE_STRING then return Value; else return To_Object (To_Wide_Wide_String (Value)); end if; end Cast_String; -- ------------------------------ -- Find the best type to be used to compare two operands. -- -- ------------------------------ function Get_Compare_Type (Left, Right : Object) return Data_Type is begin -- Operands are of the same type. if Left.V.Of_Type = Right.V.Of_Type then return Left.V.Of_Type; end if; -- 12 >= "23" -- if Left.Of_Type = TYPE_STRING or case Left.V.Of_Type is when TYPE_BOOLEAN => case Right.V.Of_Type is when TYPE_INTEGER | TYPE_BOOLEAN | TYPE_TIME => return TYPE_INTEGER; when TYPE_FLOAT | TYPE_STRING | TYPE_WIDE_STRING => return Right.V.Of_Type; when others => null; end case; when TYPE_INTEGER => case Right.V.Of_Type is when TYPE_BOOLEAN | TYPE_TIME => return TYPE_INTEGER; when TYPE_FLOAT => return TYPE_FLOAT; when others => null; end case; when TYPE_TIME => case Right.V.Of_Type is when TYPE_INTEGER | TYPE_BOOLEAN | TYPE_FLOAT => return TYPE_INTEGER; when others => null; end case; when TYPE_FLOAT => case Right.V.Of_Type is when TYPE_INTEGER | TYPE_BOOLEAN => return TYPE_FLOAT; when TYPE_TIME => return TYPE_INTEGER; when others => null; end case; when others => null; end case; return TYPE_STRING; end Get_Compare_Type; -- ------------------------------ -- Find the data type to be used for an arithmetic operation between two objects. -- ------------------------------ function Get_Arithmetic_Type (Left, Right : Object) return Data_Type is begin if Left.V.Of_Type = TYPE_FLOAT or Right.V.Of_Type = TYPE_FLOAT then return TYPE_FLOAT; end if; if Left.V.Of_Type = TYPE_INTEGER or Right.V.Of_Type = TYPE_INTEGER then return TYPE_INTEGER; end if; if Left.V.Of_Type = TYPE_BOOLEAN and Right.V.Of_Type = TYPE_BOOLEAN then return TYPE_BOOLEAN; end if; return TYPE_FLOAT; end Get_Arithmetic_Type; -- ------------------------------ -- Find the data type to be used for a composition operation between two objects. -- ------------------------------ function Get_Compose_Type (Left, Right : Object) return Data_Type is begin if Left.V.Of_Type = Right.V.Of_Type then return Left.V.Of_Type; end if; if Left.V.Of_Type = TYPE_FLOAT or Right.V.Of_Type = TYPE_FLOAT then return TYPE_FLOAT; end if; if Left.V.Of_Type = TYPE_INTEGER or Right.V.Of_Type = TYPE_INTEGER then return TYPE_INTEGER; end if; if Left.V.Of_Type = TYPE_TIME or Right.V.Of_Type = TYPE_TIME then return TYPE_TIME; end if; if Left.V.Of_Type = TYPE_BOOLEAN and Right.V.Of_Type = TYPE_BOOLEAN then return TYPE_BOOLEAN; end if; return TYPE_FLOAT; end Get_Compose_Type; -- ------------------------------ -- Comparison of objects -- ------------------------------ generic with function Int_Comparator (Left, Right : Long_Long_Integer) return Boolean; with function Time_Comparator (Left, Right : Duration) return Boolean; with function Boolean_Comparator (Left, Right : Boolean) return Boolean; with function Float_Comparator (Left, Right : Long_Long_Float) return Boolean; with function String_Comparator (Left, Right : String) return Boolean; with function Wide_String_Comparator (Left, Right : Wide_Wide_String) return Boolean; function Compare (Left, Right : Object) return Boolean; -- ------------------------------ -- Comparison of objects -- ------------------------------ function Compare (Left, Right : Object) return Boolean is T : constant Data_Type := Get_Compare_Type (Left, Right); begin case T is when TYPE_BOOLEAN => return Boolean_Comparator (Left.Type_Def.To_Boolean (Left.V), Right.Type_Def.To_Boolean (Right.V)); when TYPE_INTEGER => return Int_Comparator (Left.Type_Def.To_Long_Long (Left.V), Right.Type_Def.To_Long_Long (Right.V)); when TYPE_TIME => return Time_Comparator (Left.Type_Def.To_Duration (Left.V), Right.Type_Def.To_Duration (Right.V)); when TYPE_FLOAT => return Float_Comparator (Left.Type_Def.To_Long_Float (Left.V), Right.Type_Def.To_Long_Float (Right.V)); when TYPE_STRING => return String_Comparator (To_String (Left), To_String (Right)); when TYPE_WIDE_STRING => return Wide_String_Comparator (To_Wide_Wide_String (Left), To_Wide_Wide_String (Right)); when others => return False; end case; end Compare; function ">" (Left, Right : Object) return Boolean is function Cmp is new Compare (Int_Comparator => ">", Time_Comparator => ">", Boolean_Comparator => ">", Float_Comparator => ">", String_Comparator => ">", Wide_String_Comparator => ">"); begin return Cmp (Left, Right); end ">"; function "<" (Left, Right : Object) return Boolean is function Cmp is new Compare (Int_Comparator => "<", Time_Comparator => "<", Boolean_Comparator => "<", Float_Comparator => "<", String_Comparator => "<", Wide_String_Comparator => "<"); begin return Cmp (Left, Right); end "<"; function "<=" (Left, Right : Object) return Boolean is function Cmp is new Compare (Int_Comparator => "<=", Time_Comparator => "<=", Boolean_Comparator => "<=", Float_Comparator => "<=", String_Comparator => "<=", Wide_String_Comparator => "<="); begin return Cmp (Left, Right); end "<="; function ">=" (Left, Right : Object) return Boolean is function Cmp is new Compare (Int_Comparator => ">=", Time_Comparator => ">=", Boolean_Comparator => ">=", Float_Comparator => ">=", String_Comparator => ">=", Wide_String_Comparator => ">="); begin return Cmp (Left, Right); end ">="; -- function "=" (Left, Right : Object) return Boolean; function "=" (Left, Right : Object) return Boolean is function Cmp is new Compare (Int_Comparator => "=", Time_Comparator => "=", Boolean_Comparator => "=", Float_Comparator => "=", String_Comparator => "=", Wide_String_Comparator => "="); begin return Cmp (Left, Right); end "="; -- ------------------------------ -- Arithmetic operations of objects -- ------------------------------ generic with function Int_Operation (Left, Right : Long_Long_Integer) return Long_Long_Integer; with function Duration_Operation (Left, Right : Duration) return Duration; with function Float_Operation (Left, Right : Long_Long_Float) return Long_Long_Float; function Arith (Left, Right : Object) return Object; -- Comparison of objects function Arith (Left, Right : Object) return Object is begin -- If we have a time object, keep the time definition. if Left.V.Of_Type = TYPE_TIME then return Result : Object do Result.Type_Def := Left.Type_Def; Result.V := Object_Value '(Of_Type => TYPE_TIME, Time_Value => Duration_Operation (Left.Type_Def.To_Duration (Left.V), Right.Type_Def.To_Duration (Right.V))); end return; end if; if Right.V.Of_Type = TYPE_TIME then return Result : Object do Result.Type_Def := Right.Type_Def; Result.V := Object_Value '(Of_Type => TYPE_TIME, Time_Value => Duration_Operation (Left.Type_Def.To_Duration (Left.V), Right.Type_Def.To_Duration (Right.V))); end return; end if; declare T : constant Data_Type := Get_Arithmetic_Type (Left, Right); begin case T is when TYPE_INTEGER => return To_Object (Int_Operation (Left.Type_Def.To_Long_Long (Left.V), Right.Type_Def.To_Long_Long (Right.V))); when TYPE_FLOAT => return To_Object (Float_Operation (Left.Type_Def.To_Long_Float (Left.V), Right.Type_Def.To_Long_Float (Right.V))); when others => return Left; end case; end; end Arith; -- Arithmetic operations on objects function "+" (Left, Right : Object) return Object is function Operation is new Arith (Int_Operation => "+", Duration_Operation => "+", Float_Operation => "+"); begin return Operation (Left, Right); end "+"; function "-" (Left, Right : Object) return Object is function Operation is new Arith (Int_Operation => "-", Duration_Operation => "-", Float_Operation => "-"); begin return Operation (Left, Right); end "-"; function "-" (Left : Object) return Object is begin case Left.V.Of_Type is when TYPE_INTEGER => return To_Object (-Left.Type_Def.To_Long_Long (Left.V)); when TYPE_TIME => return To_Object (-Left.Type_Def.To_Duration (Left.V)); when TYPE_FLOAT => return To_Object (-(Left.Type_Def.To_Long_Float (Left.V))); when others => return Left; end case; end "-"; function "*" (Left, Right : Object) return Object is function Operation is new Arith (Int_Operation => "*", Duration_Operation => "+", Float_Operation => "*"); begin return Operation (Left, Right); end "*"; function "/" (Left, Right : Object) return Object is function Operation is new Arith (Int_Operation => "/", Duration_Operation => "-", Float_Operation => "/"); begin return Operation (Left, Right); end "/"; function "mod" (Left, Right : Object) return Object is function "mod" (Left, Right : Long_Long_Float) return Long_Long_Float; function "mod" (Left, Right : Long_Long_Float) return Long_Long_Float is L : constant Long_Long_Integer := Long_Long_Integer (Left); R : constant Long_Long_Integer := Long_Long_Integer (Right); begin return Long_Long_Float (L mod R); end "mod"; function Operation is new Arith (Int_Operation => "mod", Duration_Operation => "-", Float_Operation => "mod"); begin return Operation (Left, Right); end "mod"; function "&" (Left, Right : Object) return Object is T : constant Data_Type := Get_Compose_Type (Left, Right); begin case T is when TYPE_BOOLEAN => return To_Object (To_Boolean (Left) and To_Boolean (Right)); when others => return To_Object (To_String (Left) & To_String (Right)); end case; end "&"; overriding procedure Adjust (Obj : in out Object) is begin case Obj.V.Of_Type is when TYPE_BEAN => if Obj.V.Proxy /= null then Util.Concurrent.Counters.Increment (Obj.V.Proxy.Ref_Counter); end if; when TYPE_ARRAY => if Obj.V.Array_Proxy /= null then Util.Concurrent.Counters.Increment (Obj.V.Array_Proxy.Ref_Counter); end if; when TYPE_STRING => if Obj.V.String_Proxy /= null then Util.Concurrent.Counters.Increment (Obj.V.String_Proxy.Ref_Counter); end if; when TYPE_WIDE_STRING => if Obj.V.Wide_Proxy /= null then Util.Concurrent.Counters.Increment (Obj.V.Wide_Proxy.Ref_Counter); end if; when others => null; end case; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Basic.Readonly_Bean'Class, Name => Basic.Readonly_Bean_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Array_Proxy, Name => Array_Proxy_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Proxy'Class, Name => Bean_Proxy_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => String_Proxy, Name => String_Proxy_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Wide_String_Proxy, Name => Wide_String_Proxy_Access); overriding procedure Finalize (Obj : in out Object) is Release : Boolean; begin case Obj.V.Of_Type is when TYPE_STRING => if Obj.V.String_Proxy /= null then Util.Concurrent.Counters.Decrement (Obj.V.String_Proxy.Ref_Counter, Release); if Release then Free (Obj.V.String_Proxy); else Obj.V.String_Proxy := null; end if; end if; when TYPE_WIDE_STRING => if Obj.V.Wide_Proxy /= null then Util.Concurrent.Counters.Decrement (Obj.V.Wide_Proxy.Ref_Counter, Release); if Release then Free (Obj.V.Wide_Proxy); else Obj.V.Wide_Proxy := null; end if; end if; when TYPE_BEAN => if Obj.V.Proxy /= null then Util.Concurrent.Counters.Decrement (Obj.V.Proxy.Ref_Counter, Release); if Release then Obj.V.Proxy.all.Release; Free (Obj.V.Proxy); else Obj.V.Proxy := null; end if; end if; when TYPE_ARRAY => if Obj.V.Array_Proxy /= null then Util.Concurrent.Counters.Decrement (Obj.V.Array_Proxy.Ref_Counter, Release); if Release then Free (Obj.V.Array_Proxy); else Obj.V.Array_Proxy := null; end if; end if; when others => null; end case; end Finalize; -- ------------------------------ -- Release the object pointed to by the proxy (if necessary). -- ------------------------------ overriding procedure Release (P : in out Bean_Proxy) is begin if P.Storage = DYNAMIC and P.Bean /= null then declare Bean : Basic.Readonly_Bean_Access := P.Bean.all'Access; begin P.Bean := null; Free (Bean); end; end if; end Release; end Util.Beans.Objects;
with Ada.Containers.Generic_Array_Access_Types; with Ada.Containers.Generic_Array_Types; with Ada.Unchecked_Deallocation; procedure cntnr_Array is begin declare -- String package Arrays is new Ada.Containers.Generic_Array_Types (Positive, Character, String); begin declare -- Swap Data : String := "AB"; begin Arrays.Swap (Data, 1, 2); pragma Assert (Data = "BA"); end; end; declare -- String_Access type String_Access is access String; procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Arrays is new Ada.Containers.Generic_Array_Access_Types ( Positive, Character, String, String_Access); package Arrays_Operators is new Arrays.Operators; use Arrays_Operators; begin declare -- Swap Data : String_Access := new String'("AB"); begin Arrays.Swap (Data, 1, 2); pragma Assert (Data.all = "BA"); Free (Data); end; declare -- Generic_Sorting package Sorting is new Arrays.Generic_Sorting; Data : String_Access := new String'("asdfghjkl"); Data_2 : String_Access := new String'("zxcvbnm"); begin Sorting.Sort (Data); pragma Assert (Sorting.Is_Sorted (Data)); Sorting.Sort (Data_2); Sorting.Merge (Data, Data_2); pragma Assert (Data_2 = null); pragma Assert (Data.all = "abcdfghjklmnsvxz"); Free (Data); end; declare -- Concatenation operators use type Ada.Containers.Count_Type; X : String_Access := new String'("ABC"); Y : String_Access; begin pragma Assert (Arrays.Length (X) = 3); Arrays.Assign (Y, X & 'D'); pragma Assert (Arrays.Length (Y) = 4); pragma Assert (Y.all = "ABCD"); Arrays.Assign (Y, X & 'D' & 'E'); pragma Assert (Y.all = "ABCDE"); Arrays.Assign (Y, X & 'D' & 'E' & 'F'); pragma Assert (Y.all = "ABCDEF"); Free (X); Free (Y); end; declare -- Insert/Append/Prepend/Delete/Delete_First/Delete_Last use type Ada.Containers.Count_Type; X : aliased String_Access := new String'("ABCD"); begin Arrays.Delete (X, 2, 2); pragma Assert (X.all = "AD"); Arrays.Insert (X, 2, 'Z'); pragma Assert (X.all = "AZD"); Arrays.Append (X, 'a'); pragma Assert (X.all = "AZDa"); Arrays.Prepend (X, 'p'); pragma Assert (X.all = "pAZDa"); Arrays.Delete_First (X); Arrays.Delete_Last (X); pragma Assert (X.all = "AZD"); Arrays.Insert (X, X'First, "aa"); pragma Assert (X.all = "aaAZD"); Arrays.Insert (X, X'Last + 1, "zz"); pragma Assert (X.all = "aaAZDzz"); Free (X); X := new String'(10 .. 9 => <>); pragma Assert (X'Length = 0); Arrays.Append (X, 'A'); pragma Assert (X.all = "A"); pragma Assert (X'First = 10); Arrays.Append (X, 'C'); pragma Assert (X.all = "AC"); pragma Assert (X'First = 10); Arrays.Insert (X, 11, 'B'); pragma Assert (X.all = "ABC"); pragma Assert (X'First = 10); Arrays.Prepend (X, 'q'); pragma Assert (X.all = "qABC"); pragma Assert (X'First = 10); Arrays.Delete (X, 10, 1); pragma Assert (X.all = "ABC"); pragma Assert (X'First = 10); Free (X); end; declare -- Set_Length X : aliased String_Access; begin X := new String'(10 .. 9 => <>); Arrays.Set_Length (X, 1); pragma Assert (X'First = 10 and then X'Last = 10); X (10) := 'I'; Arrays.Set_Length (X, 2); pragma Assert (X'First = 10 and then X'Last = 11); X (11) := 'J'; pragma Assert (X.all = "IJ"); Free (X); end; declare -- Generic_Reversing package Reversing is new Arrays.Generic_Reversing; Data : String_Access := new String'("12345"); begin Reversing.Reverse_Elements (Data); pragma Assert (Data.all = "54321"); Reversing.Reverse_Rotate_Elements (Data, 3); pragma Assert (Data.all = "32154"); Reversing.Juggling_Rotate_Elements (Data, 3); pragma Assert (Data.all = "15432"); Reversing.Reverse_Rotate_Elements (Data, Arrays.First_Index (Data)); Reversing.Reverse_Rotate_Elements (Data, Arrays.Last_Index (Data) + 1); Reversing.Juggling_Rotate_Elements (Data, Arrays.First_Index (Data)); Reversing.Juggling_Rotate_Elements (Data, Arrays.Last_Index (Data) + 1); pragma Assert (Data.all = "15432"); end; end ; pragma Debug (Ada.Debug.Put ("OK")); end cntnr_Array;
package body Web.Producers is procedure Append (Container : in out Node_Array_Access; Item : in Node) is Old : Node_Array_Access := Container; begin if Old = null then Container := new Node_Array'(1 => Item); else begin Container := new Node_Array'(Old.all & Item); exception when others => Free (Old); raise; end; Free (Old); end if; end Append; procedure Release (Data : in out Data_Access) is procedure Cleanup (Item : in out Node_Array_Access) is begin if Item /= null then for I in Item'Range loop if Item (I).Nodes /= null then Cleanup (Item (I).Nodes); end if; end loop; Free (Item); end if; end Cleanup; begin if Data /= null then Data.Reference_Count := Data.Reference_Count - 1; if Data.Reference_Count = 0 then Free (Data.Source); Cleanup (Data.Root_Nodes); Free (Data); end if; end if; end Release; function Find_Part (Template : Producers.Template; Part : String) return Node_Array_Access is begin if Part'Length = 0 then return Template.Nodes; else if Template.Nodes /= null then for I in Template.Nodes'Range loop declare It : Node renames Template.Nodes (I); begin if Template.Data.Source (It.Tag_First .. It.Tag_Last) = Part then return It.Nodes; -- OK end if; end; end loop; end if; raise Data_Error with """" & Part & """ was not found."; end if; end Find_Part; -- implementation function Is_Empty (Object : Template) return Boolean is begin return Object.Data = null; end Is_Empty; function Is_Parsed (Object : Template) return Boolean is begin return Object.Nodes /= null; end Is_Parsed; function Read ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Length : Ada.Streams.Stream_Element_Count; Parsing : Boolean := True) return Template is Source : String_Access := new String (1 .. Natural (Length)); begin String'Read (Stream, Source.all); return Result : Template := (Ada.Finalization.Limited_Controlled with Data => new Data'(Reference_Count => 1, Source => Source, Root_Nodes => null), Nodes => null) do Source := null; -- free on Finalize if Parsing then Parse (Result); end if; end return; exception when others => Free (Source); raise; end Read; procedure Parse (Template : in out Producers.Template) is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Template) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => not Is_Parsed (Template) or else raise Status_Error); Source : constant not null access constant String := Template.Data.Source; I : Positive := Source'First; Text_First : Positive := I; procedure Process (Nodes : in out Node_Array_Access; Tag : in String) is Text_Last : Natural; Tag_First : Positive; Tag_Last : Natural; begin while I <= Source'Last loop if Source (I) = '<' then Text_Last := I - 1; I := I + 1; if Source (I) = '/' then I := I + 1; if Source (I) = '?' then -- </?XXX> I := I + 1; Tag_First := I; while Source (I) /= '>' loop I := I + 1; end loop; Tag_Last := I - 1; I := I + 1; if Source (Tag_First .. Tag_Last) = Tag then if Text_First <= Text_Last then Append ( Nodes, Node'( Text_First => Text_First, Text_Last => Text_Last, Tag_First => 1, Tag_Last => 0, Nodes => null)); end if; Text_First := I; return; end if; end if; elsif Source (I) = '?' then I := I + 1; Tag_First := I; loop case Source (I) is when '/' => Tag_Last := I - 1; I := I + 1; if Source (I) /= '>' then raise Data_Error; end if; exit; when '>' => Tag_Last := I - 1; exit; when others => null; end case; I := I + 1; end loop; I := I + 1; if Source (I - 2) /= '?' then -- <?XXX> declare Sub_Nodes : Node_Array_Access := null; Current_Text_First : constant Positive := Text_First; Current_Text_Last : constant Natural := Text_Last; begin Text_First := I; if Source (I - 2) /= '/' then Process (Sub_Nodes, Source (Tag_First .. Tag_Last)); end if; Append ( Nodes, Node'( Text_First => Current_Text_First, Text_Last => Current_Text_Last, Tag_First => Tag_First, Tag_Last => Tag_Last, Nodes => Sub_Nodes)); end; end if; else while Source (I) /= '>' loop if Source (I) = '"' then loop I := I + 1; exit when Source (I) = '"'; end loop; I := I + 1; elsif Source (I) = '?' then -- <tag ?XXX> Text_Last := I - 1; I := I + 1; if Source (I) = '?' then -- <tag ?? ...> Append ( Nodes, Node'( Text_First => Text_First, Text_Last => Text_Last, Tag_First => 1, Tag_Last => 0, Nodes => null)); loop I := I + 1; case Source (I) is when '/' | '>' => exit; when '"' => loop I := I + 1; exit when Source (I) = '"'; end loop; when others => null; end case; end loop; Text_First := I; else Tag_First := I; loop case Source (I) is when ' ' | '=' | '/' | '>' => exit; when others => null; end case; I := I + 1; end loop; Tag_Last := I - 1; Append ( Nodes, Node'( Text_First => Text_First, Text_Last => Text_Last, Tag_First => Tag_First, Tag_Last => Tag_Last, Nodes => null)); Text_First := I; end if; else I := I + 1; end if; end loop; end if; else I := I + 1; end if; end loop; end Process; Nodes : Node_Array_Access := null; begin Process (Nodes, ""); if Text_First <= Template.Data.Source'Last then Append ( Nodes, Node'( Text_First => Text_First, Text_Last => Source'Last, Tag_First => 1, Tag_Last => 0, Nodes => null)); elsif Nodes = null then Nodes := new Node_Array'(1 .. 0 => <>); -- empty source file end if; Template.Data.Root_Nodes := Nodes; Template.Nodes := Nodes; end Parse; procedure Read_Parsed_Information ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Template : in out Producers.Template) is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Template) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => not Is_Parsed (Template) or else raise Status_Error); procedure R (Nodes : in out Node_Array_Access) is Length : Integer; begin Integer'Read (Stream, Length); if Length > 0 then Nodes := new Node_Array (1 .. Length); for I in 1 .. Length loop Integer'Read (Stream, Nodes (I).Text_First); Integer'Read (Stream, Nodes (I).Text_Last); Integer'Read (Stream, Nodes (I).Tag_First); Integer'Read (Stream, Nodes (I).Tag_Last); R (Nodes (I).Nodes); end loop; end if; end R; begin pragma Assert (Template.Data.Root_Nodes = null); R (Template.Data.Root_Nodes); if Template.Data.Root_Nodes = null then Template.Data.Root_Nodes := new Node_Array'(1 .. 0 => <>); end if; Template.Nodes := Template.Data.Root_Nodes; end Read_Parsed_Information; procedure Write_Parsed_Information ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Template : in Producers.Template) is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Template) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Is_Parsed (Template) or else raise Status_Error); begin if Template.Nodes /= Template.Data.Root_Nodes then -- sub template raise Constraint_Error; else pragma Assert (Template.Data.Root_Nodes /= null); declare procedure W (Nodes : in Node_Array_Access) is begin if Nodes /= null then pragma Assert (Nodes'First = 1); Integer'Write (Stream, Nodes'Length); for I in Nodes'Range loop Integer'Write (Stream, Nodes (I).Text_First); Integer'Write (Stream, Nodes (I).Text_Last); Integer'Write (Stream, Nodes (I).Tag_First); Integer'Write (Stream, Nodes (I).Tag_Last); W (Nodes (I).Nodes); end loop; else Integer'Write (Stream, 0); end if; end W; begin W (Template.Data.Root_Nodes); end; end if; end Write_Parsed_Information; overriding procedure Finalize (Object : in out Template) is begin Release (Object.Data); Object.Nodes := null; end Finalize; -- implementation of producing by while loop procedure Start_Produce ( Produce : out Produce_Type; Output : not null access Ada.Streams.Root_Stream_Type'Class; Template : in Producers.Template'Class; Part : in String := "") is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Producers.Template (Template)) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Is_Parsed (Producers.Template (Template)) or else raise Status_Error); begin Produce.Output := Output; Produce.Sub_Template.Data := Template.Data; Template.Data.Reference_Count := Template.Data.Reference_Count + 1; Produce.Nodes := Find_Part (Producers.Template (Template), Part); if Produce.Nodes /= null then Produce.Position := Produce.Nodes'First - 1; Next (Produce); end if; end Start_Produce; function More (Produce : Produce_Type) return Boolean is begin return Produce.Nodes /= null and then Produce.Position <= Produce.Nodes'Last; end More; function Tag (Produce : Produce_Type) return String is It : Node renames Produce.Nodes (Produce.Position); begin return Produce.Sub_Template.Data.Source (It.Tag_First .. It.Tag_Last); end Tag; function Contents (Produce : Produce_Type) return Template_Constant_Reference_Type is X : constant not null access constant Template := Produce.Sub_Template'Access; begin return (Element => X); -- return (Element => Produce.Sub_Template'Access); -- Note: [gcc-6] It is wrongly detected as dangling. (Bug 70867) -- It's able to avoid this bug by using a temporary variable. end Contents; procedure Next (Produce : in out Produce_Type) is pragma Check (Pre, Check => (Produce.Nodes /= null and then Produce.Position <= Produce.Nodes'Last) or else raise Status_Error); begin loop Produce.Position := Produce.Position + 1; exit when Produce.Position > Produce.Nodes'Last; declare It : Node renames Produce.Nodes (Produce.Position); begin String'Write ( Produce.Output, Produce.Sub_Template.Data.Source (It.Text_First .. It.Text_Last)); Produce.Sub_Template.Nodes := It.Nodes; exit when It.Tag_First <= It.Tag_Last; end; end loop; end Next; procedure End_Produce (Produce : in out Produce_Type) is begin Produce.Output := null; Produce.Nodes := null; Produce.Position := 0; Finalize (Produce.Sub_Template); end End_Produce; -- producing by generalized iterator function Current (Object : Template_Iterator) return Cursor is Index : Natural; Produce : access constant Produce_Type; begin if More (Object.Produce) then Index := Object.Produce.Position; Produce := Object.Produce'Unchecked_Access; else Index := 0; Produce := null; end if; return (Index => Index, Produce => Produce); end Current; -- implementation of producing by generalized iterator function Has_Element (Position : Cursor) return Boolean is begin return Position.Index > 0; end Has_Element; function Tag (Position : Cursor) return String is pragma Check (Pre, Check => Has_Element (Position) or else raise Constraint_Error); pragma Check (Pre, Check => Position.Index = Position.Produce.Position or else raise Status_Error); begin return Tag (Position.Produce.all); end Tag; function Contents (Position : Cursor) return Template_Constant_Reference_Type is pragma Check (Pre, Check => Has_Element (Position) or else raise Constraint_Error); pragma Check (Pre, Check => Position.Index = Position.Produce.Position or else raise Status_Error); begin return Contents (Position.Produce.all); end Contents; function Produce ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Template : Producers.Template'Class; Part : String := "") return Template_Iterator_Interfaces.Forward_Iterator'Class is begin return Result : Template_Iterator do Start_Produce ( Result.Produce, Output, Template, -- checking the predicate Part); Result.First_Index := Result.Produce.Position; end return; end Produce; overriding function First (Object : Template_Iterator) return Cursor is pragma Check (Pre, Check => Object.Produce.Position = Object.First_Index or else raise Status_Error); begin return Current (Object); end First; overriding function Next (Object : Template_Iterator; Position : Cursor) return Cursor is pragma Check (Pre, Check => Has_Element (Position) or else raise Constraint_Error); pragma Check (Pre, Check => Position.Index = Position.Produce.Position or else raise Status_Error); begin Next (Object.Variable_View.Produce); return Current (Object); end Next; -- implementation of producing by closure procedure Produce ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Template : in Producers.Template'Class; Part : in String := ""; Handler : not null access procedure ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Producers.Template)) is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Producers.Template (Template)) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Is_Parsed (Producers.Template (Template)) or else raise Status_Error); Nodes : constant Node_Array_Access := Find_Part (Producers.Template (Template), Part); begin if Nodes /= null then for I in Nodes'Range loop declare It : Node renames Nodes (I); begin String'Write (Output, Template.Data.Source (It.Text_First .. It.Text_Last)); if It.Tag_First <= It.Tag_Last then declare Sub_Template : constant Producers.Template := Producers.Template'(Ada.Finalization.Limited_Controlled with Data => Template.Data, Nodes => It.Nodes); begin Template.Data.Reference_Count := Template.Data.Reference_Count + 1; Handler ( Output, Template.Data.Source (It.Tag_First .. It.Tag_Last), Sub_Template); end; end if; end; end loop; end if; end Produce; procedure Generic_Produce ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Template : in Producers.Template'Class; Part : in String := ""; Handler : not null access procedure ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : in Producers.Template; Params : access Parameter); Params : access Parameter) is procedure Handle ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Tag : in String; Contents : Producers.Template) is begin Handler (Output, Tag, Contents, Params); end Handle; begin Produce ( Output, Template, -- Status_Error would be raised if Object is not parsed Part, Handle'Access); end Generic_Produce; -- implementation of producing for the simple case procedure Produce ( Output : not null access Ada.Streams.Root_Stream_Type'Class; Template : in Producers.Template'Class; -- Parsed_Template Part : in String := "") is pragma Check (Dynamic_Predicate, Check => not Is_Empty (Producers.Template (Template)) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Is_Parsed (Producers.Template (Template)) or else raise Status_Error); Nodes : constant Node_Array_Access := Find_Part (Producers.Template (Template), Part); begin if Nodes /= null then for I in Nodes'Range loop declare It : Node renames Nodes (I); begin String'Write (Output, Template.Data.Source (It.Text_First .. It.Text_Last)); if It.Tag_First <= It.Tag_Last then raise Data_Error; -- some handler is required end if; end; end loop; end if; end Produce; end Web.Producers;
----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017, 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.Properties; with Util.Log.Loggers; with Bbox.API; with Druss.Gateways; with Ada.Strings.Unbounded; package body Druss.Commands.Ping is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Ping"); -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Do_Ping (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String); Box : Bbox.API.Client_Type; procedure Ping_Device (Manager : in Util.Properties.Manager; Name : in String) is Id : constant String := Manager.Get (Name & ".id", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Log.Info ("Ping command on {0}", Manager.Get (Name & ".ipaddress", "")); Box.Post ("hosts/" & Id, "action=ping"); end Ping_Device; begin if Ada.Strings.Unbounded.Length (Gateway.Passwd) = 0 then return; end if; Gateway.Refresh; Box.Set_Server (To_String (Gateway.Ip)); Box.Login (To_String (Gateway.Passwd)); Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Ping_Device'Access); end Do_Ping; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); begin if Manager.Get (Name & ".active", "") = "0" then return; end if; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); Print_Perf (Console, F_ACTIVE, Manager.Get (Name & ".ping.average", "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Do_Ping'Access); delay 5.0; Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_ACTIVE, "Ping", 15); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_Ping; -- ------------------------------ -- Execute a ping from the gateway to each device. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Count = 0 then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_Ping (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_Ping (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_Ping (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "ping: Ask the Bbox to ping the devices"); Console.Notice (N_HELP, "Usage: ping [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Ask the Bbox to ping the devices. By default it will ping"); Console.Notice (N_HELP, " all the devices that have been discovered by the Bbox."); Console.Notice (N_HELP, " The command will wait 5 seconds and it will list the active"); Console.Notice (N_HELP, " devices with their ping performance."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all Ping all the devices"); Console.Notice (N_HELP, " active Ping the active devices only"); Console.Notice (N_HELP, " inative Ping the inactive devices only"); end Help; end Druss.Commands.Ping;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Ada.Tags, Ada.Characters.Handling, Ada.Assertions, Apsepp_Testing_System_Test_Fixture, Apsepp.Generic_Fixture.Creator, Apsepp.Tags, Apsepp_Test_Node_Barrier, Apsepp_Test_Node_Class_Early_Test_Case, Apsepp.Test_Reporter_Class.Struct_Builder, Apsepp.Test_Event_Class, Apsepp.Test_Node_Class, Apsepp.Test_Reporter_Data_Struct_Class.Impl.Testing, Apsepp.Scope_Debug; package body Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case is use Ada.Tags, Ada.Characters.Handling, Apsepp_Testing_System_Test_Fixture, Apsepp_Test_Node_Barrier, Apsepp.Test_Reporter_Class.Struct_Builder, Apsepp.Test_Event_Class, Apsepp.Test_Node_Class, Apsepp.Test_Reporter_Data_Struct_Class.Impl, Apsepp.Test_Reporter_Data_Struct_Class.Impl.Testing; ---------------------------------------------------------------------------- function TSF return Testing_System_Test_Fixture_Access renames Instance; ---------------------------------------------------------------------------- TRSB : Test_Reporter_Struct_Builder; ---------------------------------------------------------------------------- procedure Validate (K : Positive; Event_Kind : Test_Event_Kind; Event_Data : Test_Event_Data; Char : ISO_646; Char_To_Tag : Char_To_Tag_Func; Msg_Pref : String) is ----------------------------------------------------- procedure Put_Array (A : Node_Tag_Tree_As_Array; Msg_Pref : String) is use Apsepp.Scope_Debug; Entity_Name : constant String := "Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case" & ".Put_Array"; C_D_T : constant Controlled_Debug_Tracer := Create_N (Entity_Name); Line : constant String (1 .. 53) := (others => '-'); First_Done : Boolean := False; begin for E of A loop if not First_Done then First_Done := True; C_D_T.Trace (Msg_Pref & Line); end if; declare Active_String : constant String := (if E.Active then "x" else " "); Parent_Index_Image : constant String := Natural'Image (E.Parent_Index); N : constant Positive := 3; Pad : constant String (1 .. N - Parent_Index_Image'Length) := (others => ' '); Parent_Index_String : constant String (1 .. 3) := Pad & Parent_Index_Image; begin C_D_T.Trace (Active_String & Parent_Index_String & " " & Expanded_Name (E.Node_Tag)); end; end loop; if First_Done then C_D_T.Trace (Msg_Pref & Line); end if; end Put_Array; ----------------------------------------------------- function Node_Data_Tree_Change_OK (Node_Tag_Tree_Old , Node_Tag_Tree_New : Node_Tag_Tree_As_Array; New_Node_Tag , New_Node_Parent_Tag : Tag := No_Tag; Deactivated_Node_Tag : Tag := No_Tag) return Boolean is Old_Length : constant Natural := Node_Tag_Tree_Old'Length; New_Length : constant Natural := Node_Tag_Tree_New'Length; K_Added : Natural := 0; Deactivated_Found : Boolean := False; function Offs return Natural is (if K_Added = 0 then 0 else 1); function O_Ta (K : Natural) return Tag is (Tree_Tag (Node_Tag_Tree_Old, K)); function N_Ta (K : Natural) return Tag is (Tree_Tag (Node_Tag_Tree_New, K)); function O_P_Ta (K : Natural) return Tag is (Tree_Parent_Tag (Node_Tag_Tree_Old, K)); function N_P_Ta (K : Natural) return Tag is (Tree_Parent_Tag (Node_Tag_Tree_New, K)); function O_Ac (K : Positive) return Boolean is (Tree_Active (Node_Tag_Tree_Old, K)); function N_Ac (K : Positive) return Boolean is (Tree_Active (Node_Tag_Tree_New, K)); Ret : Boolean := New_Length = Old_Length or else New_Length = Old_Length + 1; begin if not Ret then return Ret; end if; for K in Node_Tag_Tree_New'Range loop if K <= Node_Tag_Tree_Old'Last then if N_Ta (K) /= O_Ta (K - Offs) then Ret := K_Added = 0 and then N_Ac (K); K_Added := K; else Ret := N_P_Ta (K) = O_P_Ta (K - Offs); if N_Ac (K) xor O_Ac (K - Offs) then Ret := Ret and then O_Ac (K - Offs) and then not Deactivated_Found and then N_Ta (K) = Deactivated_Node_Tag; Deactivated_Found := True; end if; end if; else if K_Added = 0 then K_Added := K; else Ret := N_Ta (K) = O_Ta (K - Offs) and then N_P_Ta (K) = O_P_Ta (K - Offs); end if; end if; exit when not Ret; end loop; if not Ret then return Ret; end if; Ret := Deactivated_Node_Tag = No_Tag or else Deactivated_Found; if not Ret then return Ret; end if; if K_Added = 0 then Ret := New_Node_Tag = No_Tag and then New_Node_Parent_Tag = No_Tag; else Ret := N_Ta (K_Added) = New_Node_Tag and then N_P_Ta (K_Added) = New_Node_Parent_Tag; end if; return Ret; end Node_Data_Tree_Change_OK; ----------------------------------------------------- function Event_Data_As_Expected (Data : Flattened_Event_Data; Node_Tag : Tag; Has_E : Boolean := False; R_Index : Test_Routine_Count := 0; Assert_Num : Test_Assert_Count := 0) return Boolean is (Data.Node_Tag = Node_Tag and then Data.Has_E = Has_E and then Data.R_Index = R_Index and then Data.Assert_Num = Assert_Num and then Data.Previous_Child_Tag = No_Tag); ----------------------------------------------------- Is_Runner : constant Boolean := Is_Lower (Char); Temp_Tag : constant Tag := Char_To_Tag (To_Upper (Char)); Node_Tag : constant Tag := (if Is_Runner then (if Temp_Tag = TSF.A then TSF.A_R elsif Temp_Tag = TSF.B then TSF.B_R elsif Temp_Tag = TSF.C then TSF.C_R elsif Temp_Tag = TSF.D then TSF.D_R else TSF.E_R) else Temp_Tag); Data_Bef : constant access constant Test_Reporter_Data := TRSB.Struct_Pointer; Data_Aft : access constant Test_Reporter_Data; Parent_Node_Tag : constant Tag := (if Node_Tag = TSF.A then TSF.A_R elsif Node_Tag = TSF.B then TSF.B_R elsif Node_Tag = TSF.C then TSF.C_R elsif Node_Tag = TSF.D then TSF.C_R -- Intentional. elsif Node_Tag = TSF.E then TSF.E_R else No_Tag); T_B_L : constant Natural := Node_Tag_Tree_Node_Count (Data_Bef.all); T_B : Node_Tag_Tree_As_Array (1 .. T_B_L); Ev_B_L : constant Natural := Event_Vector_Length (Data_Bef.all); Ev_B : Event_Data_Array (1 .. Ev_B_L); begin To_Arrays (Data_Bef.all, T_B, Ev_B); if Parent_Node_Tag /= No_Tag then TRSB.Provide_Node_Lineage ((Parent_Node_Tag, Node_Tag)); end if; Ada.Assertions.Assert (K > 1 or else Data_Bef.Is_Empty, Msg_Pref & "Non-empty data structure before first event"); case Event_Kind is when Failed_Child_Test_Node_Access => TRSB.Report_Failed_Child_Test_Node_Access (Node_Tag, Event_Data.Previous_Child_Tag, Event_Data.E.all); when Unexpected_Node_Cond_Check_Error => TRSB.Report_Unexpected_Node_Cond_Check_Error (Node_Tag, Event_Data.E.all); when Unexpected_Node_Run_Error => TRSB.Report_Unexpected_Node_Run_Error (Node_Tag, Event_Data.E.all); when Node_Cond_Check_Start => TRSB.Report_Node_Cond_Check_Start (Node_Tag); when Passed_Node_Cond_Check => TRSB.Report_Passed_Node_Cond_Check (Node_Tag); when Failed_Node_Cond_Check => TRSB.Report_Failed_Node_Cond_Check (Node_Tag); when Passed_Node_Cond_Assert => TRSB.Report_Passed_Node_Cond_Assert (Node_Tag); when Failed_Node_Cond_Assert => TRSB.Report_Failed_Node_Cond_Assert (Node_Tag); when Node_Run_Start => TRSB.Report_Node_Run_Start (Node_Tag); when Test_Routine_Start => TRSB.Report_Test_Routine_Start (Node_Tag, Event_Data.R_Index); when Test_Routines_Cancellation => TRSB.Report_Test_Routines_Cancellation (Node_Tag, Latest_R_Index (Data_Bef.all, Node_Tag) + 1, Event_Data.R_Index); when Failed_Test_Routine_Access => TRSB.Report_Failed_Test_Routine_Access (Node_Tag, Event_Data.R_Index, Event_Data.E.all); when Failed_Test_Routine_Setup => TRSB.Report_Failed_Test_Routine_Setup (Node_Tag, Event_Data.R_Index, Event_Data.E.all); when Passed_Test_Assert => TRSB.Report_Passed_Test_Assert (Node_Tag, Event_Data.R_Index, Event_Data.Assert_Num /= 0, Event_Data.Assert_Num); when Failed_Test_Assert => TRSB.Report_Failed_Test_Assert (Node_Tag, Event_Data.R_Index, Event_Data.Assert_Num /= 0, Event_Data.Assert_Num, Event_Data.E.all); when Unexpected_Routine_Exception => TRSB.Report_Unexpected_Routine_Exception (Node_Tag, Event_Data.R_Index, Event_Data.E.all); when Passed_Test_Routine => TRSB.Report_Passed_Test_Routine (Node_Tag, Event_Data.R_Index); when Failed_Test_Routine => TRSB.Report_Failed_Test_Routine (Node_Tag, Event_Data.R_Index); when Passed_Node_Run => TRSB.Report_Passed_Node_Run (Node_Tag); when Failed_Node_Run => TRSB.Report_Failed_Node_Run (Node_Tag); end case; Data_Aft := TRSB.Struct_Pointer; Ada.Assertions.Assert (not Data_Aft.Is_Empty, Msg_Pref & "Empty data structure after first event"); Ada.Assertions.Assert (Event_Vector_Length (Data_Aft.all) = K, Msg_Pref & "K is" & Positive'Image (K) & " but " & "Data_Aft.Event_Vector_Length is" & Positive'Image (Event_Vector_Length (Data_Aft.all))); declare T_A_L : constant Natural := Node_Tag_Tree_Node_Count (Data_Aft.all); T_A : Node_Tag_Tree_As_Array (1 .. T_A_L); Ev_A_L : constant Natural := Event_Vector_Length (Data_Aft.all); Ev_A : Event_Data_Array (1 .. Ev_A_L); Ev_A_1 : Event_Data_Array (1 .. Ev_B_L); C_R_I : Test_Routine_Count; C_A_N : Test_Assert_Count; N_D_T_C_OK, E_D_A_E : Boolean; begin To_Arrays (Data_Aft.all, T_A, Ev_A); Ev_A_1 := Ev_A (1 .. Ev_B_L); Ada.Assertions.Assert (Ev_A_1 = Ev_B, "Corrupted test event vector"); Put_Array (T_A, Msg_Pref); C_R_I := Current_R_Index (Ev_A, Ev_A'Last); C_A_N := Current_Assert_Num (Ev_A, Ev_A'Last); case Event_Kind is when Failed_Child_Test_Node_Access => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A, Node_Tag, Parent_Node_Tag); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True); when Unexpected_Node_Cond_Check_Error => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A, Node_Tag, Parent_Node_Tag); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True); when Unexpected_Node_Run_Error => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True); when Node_Cond_Check_Start => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A, Node_Tag, Parent_Node_Tag); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Passed_Node_Cond_Check => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Failed_Node_Cond_Check => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True); when Passed_Node_Cond_Assert => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Failed_Node_Cond_Assert => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True); when Node_Run_Start => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Test_Routine_Start => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, R_Index => C_R_I + 1); when Test_Routines_Cancellation => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Failed_Test_Routine_Access => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True, R_Index => C_R_I); when Failed_Test_Routine_Setup => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True, R_Index => C_R_I); when Passed_Test_Assert => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, R_Index => C_R_I, Assert_Num => C_A_N + 1); when Failed_Test_Assert => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True, R_Index => C_R_I, Assert_Num => C_A_N + 1); when Unexpected_Routine_Exception => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, Has_E => True, R_Index => C_R_I); when Passed_Test_Routine => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, R_Index => C_R_I); when Failed_Test_Routine => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag, R_Index => C_R_I); when Passed_Node_Run => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A, Deactivated_Node_Tag => Node_Tag); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); when Failed_Node_Run => N_D_T_C_OK := Node_Data_Tree_Change_OK (T_B, T_A, Deactivated_Node_Tag => Node_Tag); E_D_A_E := Event_Data_As_Expected (Ev_A(Ev_A'Last), Node_Tag); end case; Ada.Assertions.Assert (N_D_T_C_OK, "Corrupted node data tree"); Ada.Assertions.Assert (E_D_A_E, "Current event not as expected"); end; end Validate; ---------------------------------------------------------------------------- procedure Early_Test_TRCSBETC is use Apsepp_Test_Node_Class_Early_Test_Case; package Testing_System_T_F_Creator is new Testing_System_T_F.Creator; Expected_Tag : Apsepp.Tags.Tag_Array_Access; begin Ada.Assertions.Assert (Testing_System_T_F_Creator.Has_Actually_Created, "Test fixture already locked"); Expected_Tag := new Tag_Array'(Routine_State_Array_To_Tag_Array (Expected_Routine_State_Array)); TSF.Run_Test (Expected_Tag, Validate'Access); TRSB.Process; Apsepp.Tags.Free (Expected_Tag); exception when others => Apsepp.Tags.Free (Expected_Tag); raise; end Early_Test_TRCSBETC; ---------------------------------------------------------------------------- overriding function Early_Routine (Obj : Apsepp_Test_Reporter_Class_Struct_Builder_E_T_C) return Apsepp.Abstract_Early_Test_Case.Test_Routine is (Early_Test_TRCSBETC'Access); ---------------------------------------------------------------------------- end Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case;
with Interfaces; package Tkmrpc.Operations is subtype Operation_Type is Interfaces.Unsigned_64; end Tkmrpc.Operations;
with ada.unchecked_Deallocation; package body physics.Object is procedure free (Self : in out View) is procedure deallocate is new ada.unchecked_Deallocation (Item'Class, View); begin if Self /= null then Self.destruct; end if; deallocate (Self); end free; protected body safe_Dynamics is procedure set (To : in Matrix_4x4) is begin Dynamics := To; end set; function get return Matrix_4x4 is begin return Dynamics; end get; procedure set_Spin (To : in Matrix_3x3) is use linear_Algebra_3D; begin set_Rotation (Dynamics, To); end set_Spin; function get_Spin return Matrix_3x3 is use linear_Algebra_3D; begin return get_Rotation (Dynamics); end get_Spin; procedure set_Site (To : in Vector_3) is use linear_Algebra_3D; begin set_Translation (Dynamics, To); end set_Site; function get_Site return Vector_3 is use linear_Algebra_3D; begin return get_Translation (Dynamics); end get_Site; end safe_Dynamics; end physics.Object;
with AAA.Strings; use AAA.Strings; package Filesystem is function Read_Directory(Path: String; Recursive: Boolean) return AAA.Strings.Vector; function Count_Files(Path : String) return Natural; function Is_Valid_File(Name : String) return Boolean; function Get_Executable_Path return String; private end Filesystem;
package body Linear_Search with SPARK_Mode is function Search (A : Ar; I : Integer) return T is begin for Index in T range Ar'First .. Ar'Last loop if A (Index) = I then return Index; else null; end if; end loop; return 0; end Search; end Linear_Search;
package body System.Formatting.Literals.Float is pragma Suppress (All_Checks); function copysignl (X, Y : Long_Long_Float) return Long_Long_Float with Import, Convention => Intrinsic, External_Name => "__builtin_copysignl"; procedure Get_Aft ( Item : String; Last : in out Natural; Result : out Long_Long_Float; Base : Number_Base); procedure Get_Aft ( Item : String; Last : in out Natural; Result : out Long_Long_Float; Base : Number_Base) is Scale : Long_Long_Float := 1.0; Old_Last : constant Natural := Last + 1; -- skip '.' begin Result := 0.0; if Old_Last <= Item'Last and then Item (Old_Last) = '.' then Last := Old_Last; while Last < Item'Last loop declare X : Digit; Is_Invalid : Boolean; begin if Item (Last + 1) = '_' then exit when Last = Old_Last or else Last + 1 >= Item'Last; Last := Last + 1; end if; Value (Item (Last + 1), X, Is_Invalid); exit when Is_Invalid or else X >= Base; if Scale <= Long_Long_Float'Last / Long_Long_Float (Base) then Result := Result * Long_Long_Float (Base) + Long_Long_Float (X); Scale := Scale * Long_Long_Float (Base); end if; Last := Last + 1; end; end loop; Result := Result / Scale; end if; end Get_Aft; procedure Get_Fore ( Item : String; Last : in out Natural; Result : out Long_Long_Float; Base : Number_Base; Error : out Boolean); procedure Get_Fore ( Item : String; Last : in out Natural; Result : out Long_Long_Float; Base : Number_Base; Error : out Boolean) is Old_Last : constant Natural := Last; begin Result := 0.0; while Last < Item'Last loop declare X : Digit; Is_Invalid : Boolean; begin if Item (Last + 1) = '_' then exit when Last = Old_Last or else Last + 1 >= Item'Last; Last := Last + 1; end if; Value (Item (Last + 1), X, Is_Invalid); exit when Is_Invalid or else X >= Base; -- implies '.' if Result > (Long_Long_Float'Last - Long_Long_Float (X)) / Long_Long_Float (Base) then Error := True; return; -- error end if; Result := Result * Long_Long_Float (Base) + Long_Long_Float (X); Last := Last + 1; end; end loop; Error := False; end Get_Fore; -- implementation procedure Get_Literal ( Item : String; Last : out Natural; Result : out Long_Long_Float; Error : out Boolean) is Sign : Long_Long_Float; Before_Fore : Positive; Aft : Long_Long_Float; Base : Number_Base := 10; Mark : Character; Exponent : Integer; begin Last := Item'First - 1; Skip_Spaces (Item, Last); if Last < Item'Last and then Item (Last + 1) = '-' then Last := Last + 1; Sign := -1.0; else if Last < Item'Last and then Item (Last + 1) = '+' then Last := Last + 1; end if; Sign := 1.0; end if; Before_Fore := Last; Get_Fore (Item, Last, Result, Base => Base, Error => Error); if not Error then if Last < Item'Last and then (Item (Last + 1) = '#' or else Item (Last + 1) = ':') then Mark := Item (Last + 1); Last := Last + 1; if Result not in Long_Long_Float (Number_Base'First) .. Long_Long_Float (Number_Base'Last) then Error := True; else Base := Number_Base (Result); Before_Fore := Last; Get_Fore (Item, Last, Result, Base => Base, Error => Error); if not Error then Get_Aft (Item, Last, Aft, Base => Base); if Last = Before_Fore then Error := True; -- no fore nor aft else Result := Result + Aft; if Last >= Item'Last or else Item (Last + 1) /= Mark then Error := True; else Last := Last + 1; end if; end if; end if; end if; else Get_Aft (Item, Last, Aft, Base => Base); if Last = Before_Fore then Error := True; -- no fore nor aft else Result := Result + Aft; end if; end if; if not Error then Get_Exponent (Item, Last, Exponent, Positive_Only => False, Error => Error); if not Error then if Exponent /= 0 then Result := Result * Long_Long_Float (Base) ** Exponent; end if; Result := copysignl (Result, Sign); end if; end if; end if; end Get_Literal; end System.Formatting.Literals.Float;
-- Abstract : -- -- Translate a wisitoken grammar file to a tree-sitter grammar file. -- -- References: -- -- [1] tree-sitter grammar: https://tree-sitter.github.io/tree-sitter/creating-parsers#the-grammar-dsl -- -- Copyright (C) 2020 Stephen Leake All Rights Reserved. -- -- 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 MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. pragma License (GPL); with Ada.Command_Line; with Ada.Directories; with Ada.Exceptions; with Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO; with GNAT.Traceback.Symbolic; with WisiToken.Syntax_Trees.LR_Utils; with WisiToken.Parse.LR.Parser_No_Recover; with WisiToken.Syntax_Trees; with WisiToken.Text_IO_Trace; with WisiToken_Grammar_Runtime; with Wisitoken_Grammar_Actions; use Wisitoken_Grammar_Actions; with Wisitoken_Grammar_Main; procedure WisiToken.To_Tree_Sitter is procedure Put_Usage is begin Put_Line ("wisitoken-to_tree_sitter [--verbosity <level] <wisitoken grammar file> <language_name>"); end Put_Usage; procedure Print_Tree_Sitter (Data : in WisiToken_Grammar_Runtime.User_Data_Type; Tree : in Syntax_Trees.Tree; Output_File_Name : in String; Language_Name : in String) is use WisiToken.Syntax_Trees; File : File_Type; -- Local specs procedure Put_RHS_Item_List (Node : in Valid_Node_Index; First : in Boolean) with Pre => Tree.ID (Node) = +rhs_item_list_ID; -- Local bodies function Get_Text (Tree_Index : in Valid_Node_Index) return String is function Strip_Delimiters (Tree_Index : in Valid_Node_Index) return String is Region : Buffer_Region renames Data.Terminals.all (Tree.Terminal (Tree_Index)).Byte_Region; begin if -Tree.ID (Tree_Index) in RAW_CODE_ID | REGEXP_ID | ACTION_ID then -- Strip delimiters. We don't strip leading/trailing spaces to preserve indent. return Data.Grammar_Lexer.Buffer_Text ((Region.First + 2, Region.Last - 2)); -- We don't strip string delimiters; tree-setter can use the same ones. else return Data.Grammar_Lexer.Buffer_Text (Region); end if; end Strip_Delimiters; begin case Tree.Label (Tree_Index) is when Shared_Terminal => return Strip_Delimiters (Tree_Index); when Virtual_Terminal => -- Terminal keyword inserted during tree edit. We could check for -- Identifier, but that will be caught later. return Image (Tree.ID (Tree_Index), Wisitoken_Grammar_Actions.Descriptor); when Virtual_Identifier => raise SAL.Programmer_Error; when Nonterm => declare use all type Ada.Strings.Unbounded.Unbounded_String; Result : Ada.Strings.Unbounded.Unbounded_String; Tree_Indices : constant Valid_Node_Index_Array := Tree.Get_Terminals (Tree_Index); Need_Space : Boolean := False; begin for Tree_Index of Tree_Indices loop Result := Result & (if Need_Space then " " else "") & Get_Text (Tree_Index); Need_Space := True; end loop; return -Result; end; end case; end Get_Text; procedure Not_Translated (Label : in String; Node : in Valid_Node_Index) is begin New_Line (File); Put (File, "// " & Label & ": not translated: " & Node_Index'Image (Node) & ":" & Tree.Image (Node, Wisitoken_Grammar_Actions.Descriptor, Include_Children => True)); end Not_Translated; procedure Put_RHS_Alternative_List (Node : in Valid_Node_Index; First : in Boolean) with Pre => Tree.ID (Node) = +rhs_alternative_list_ID is begin case Tree.RHS_Index (Node) is when 0 => -- If only alternative, don't need "choice()". Put_RHS_Item_List (Tree.Child (Node, 1), First => True); when 1 => if First then Put (File, "choice("); end if; Put_RHS_Alternative_List (Tree.Child (Node, 1), First => False); Put (File, ", "); Put_RHS_Item_List (Tree.Child (Node, 3), First => True); if First then Put (File, ")"); end if; when others => Not_Translated ("Put_RHS_Alternative_List", Node); end case; end Put_RHS_Alternative_List; procedure Put_RHS_Optional_Item (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_optional_item_ID is begin Put (File, "optional("); case Tree.RHS_Index (Node) is when 0 | 1 => Put_RHS_Alternative_List (Tree.Child (Node, 2), First => True); when 2 => Put (File, "$." & Get_Text (Tree.Child (Node, 1))); when 3 => -- STRING_LITERAL_2 Put (File, Get_Text (Tree.Child (Node, 1))); when others => Not_Translated ("Put_RHS_Optional_Item", Node); end case; Put (File, ")"); end Put_RHS_Optional_Item; procedure Put_RHS_Multiple_Item (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_multiple_item_ID is begin case Tree.RHS_Index (Node) is when 0 | 3 => Put (File, "repeat("); Put_RHS_Alternative_List (Tree.Child (Node, 2), First => True); Put (File, ")"); when 1 | 2 => Put (File, "repeat1("); Put_RHS_Alternative_List (Tree.Child (Node, 2), First => True); Put (File, ")"); when 4 => Put (File, "repeat1("); Put (File, "$." & Get_Text (Tree.Child (Node, 1))); Put (File, ")"); when 5 => Put (File, "repeat("); Put (File, "$." & Get_Text (Tree.Child (Node, 1))); Put (File, ")"); when others => Not_Translated ("Put_RHS_Multiple_Item", Node); end case; end Put_RHS_Multiple_Item; procedure Put_RHS_Group_Item (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_group_item_ID is begin Not_Translated ("Put_RHS_Group_Item", Node); -- maybe just plain ()? end Put_RHS_Group_Item; procedure Put_RHS_Item (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_item_ID is begin case Tree.RHS_Index (Node) is when 0 => declare use WisiToken_Grammar_Runtime; Ident : constant String := Get_Text (Node); Decl : constant Node_Index := Find_Declaration (Data, Tree, Ident); begin if Decl = Invalid_Node_Index then Raise_Programmer_Error ("decl for '" & Ident & "' not found", Data, Tree, Node); elsif Tree.ID (Decl) = +nonterminal_ID then Put (File, "$." & Get_Text (Tree.Child (Decl, 1))); else case Tree.RHS_Index (Decl) is when 0 => case To_Token_Enum (Tree.ID (Tree.Child (Tree.Child (Decl, 2), 1))) is when KEYWORD_ID => Put (File, Get_Text (Tree.Child (Decl, 4))); when NON_GRAMMAR_ID => Not_Translated ("put_rhs_item", Node); when Wisitoken_Grammar_Actions.TOKEN_ID => declare use WisiToken.Syntax_Trees.LR_Utils; Iter : constant Syntax_Trees.LR_Utils.Iterator := Iterate (Data, Tree, Tree.Child (Decl, 4), +declaration_item_ID); Item : constant Valid_Node_Index := Tree.Child (Syntax_Trees.LR_Utils.Node (First (Iter)), 1); begin case To_Token_Enum (Tree.ID (Item)) is when REGEXP_ID => Put (File, "$." & Ident); when STRING_LITERAL_1_ID | STRING_LITERAL_2_ID => -- FIXME: case insensitive? Put (File, Get_Text (Item)); when others => Not_Translated ("put_rhs_item ident token", Node); end case; end; when others => Not_Translated ("put_rhs_item ident", Node); end case; when others => Not_Translated ("put_rhs_item 0", Node); end case; end if; end; when 1 => -- STRING_LITERAL_2 Put (File, Get_Text (Node)); when 2 => -- ignore attribute null; when 3 => Put_RHS_Optional_Item (Tree.Child (Node, 1)); when 4 => Put_RHS_Multiple_Item (Tree.Child (Node, 1)); when 5 => Put_RHS_Group_Item (Tree.Child (Node, 1)); when others => Not_Translated ("Put_RHS_Item", Node); end case; end Put_RHS_Item; procedure Put_RHS_Element (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_element_ID is begin case Tree.RHS_Index (Node) is when 0 => Put_RHS_Item (Tree.Child (Node, 1)); when 1 => -- Ignore the label Put_RHS_Item (Tree.Child (Node, 3)); when others => Not_Translated ("Put_RHS_Element", Node); end case; end Put_RHS_Element; procedure Put_RHS_Item_List (Node : in Valid_Node_Index; First : in Boolean) is Children : constant Valid_Node_Index_Array := Tree.Children (Node); begin if Children'Length = 1 then Put_RHS_Element (Children (1)); else if First then Put (File, "seq("); end if; Put_RHS_Item_List (Children (1), First => False); Put (File, ", "); Put_RHS_Element (Children (2)); if First then Put (File, ")"); end if; end if; end Put_RHS_Item_List; procedure Put_RHS (Node : in Valid_Node_Index) with Pre => Tree.ID (Node) = +rhs_ID is begin case Tree.RHS_Index (Node) is when 0 => Put (File, "/* empty */,"); when 1 .. 3 => Put_RHS_Item_List (Tree.Child (Node, 1), First => True); -- ignore actions when others => Not_Translated ("put_rhs", Node); end case; end Put_RHS; procedure Put_RHS_List (Node : in Valid_Node_Index; First : in Boolean) with Pre => Tree.ID (Node) = +rhs_list_ID is Children : constant Valid_Node_Index_Array := Tree.Children (Node); begin case Tree.RHS_Index (Node) is when 0 => Put_RHS (Children (1)); when 1 => if First then Put (File, "choice("); end if; Put_RHS_List (Children (1), First => False); Put (File, ","); Put_RHS (Children (3)); if First then Put (File, ")"); end if; when others => Not_Translated ("Put_RHS_List", Node); end case; end Put_RHS_List; procedure Process_Node (Node : in Valid_Node_Index) is begin case To_Token_Enum (Tree.ID (Node)) is -- Enum_Token_ID alphabetical order when compilation_unit_ID => Process_Node (Tree.Child (Node, 1)); when compilation_unit_list_ID => declare Children : constant Valid_Node_Index_Array := Tree.Children (Node); begin case To_Token_Enum (Tree.ID (Children (1))) is when compilation_unit_list_ID => Process_Node (Children (1)); Process_Node (Children (2)); when compilation_unit_ID => Process_Node (Children (1)); when others => raise SAL.Programmer_Error; end case; end; when declaration_ID => case Tree.RHS_Index (Node) is when 0 => if Tree.ID (Tree.Child (Tree.Child (Node, 2), 1)) = +Wisitoken_Grammar_Actions.TOKEN_ID then declare use Ada.Strings; use Ada.Strings.Fixed; use WisiToken.Syntax_Trees.LR_Utils; Name : constant String := Get_Text (Tree.Child (Node, 3)); Iter : constant Syntax_Trees.LR_Utils.Iterator := WisiToken_Grammar_Runtime.Iterate (Data, Tree, Tree.Child (Node, 4), +declaration_item_ID); Item : constant Valid_Node_Index := Tree.Child (Syntax_Trees.LR_Utils.Node (First (Iter)), 1); begin case To_Token_Enum (Tree.ID (Item)) is when REGEXP_ID => Put_Line (File, Name & ": $ => /" & Trim (Get_Text (Item), Both) & "/,"); when others => null; end case; end; end if; when others => null; end case; when nonterminal_ID => declare Children : constant Valid_Node_Index_Array := Tree.Children (Node); begin Put (File, Get_Text (Children (1)) & ": $ => "); Put_RHS_List (Children (3), First => True); Put_Line (File, ","); end; when wisitoken_accept_ID => Process_Node (Tree.Child (Node, 1)); when others => raise SAL.Not_Implemented with Image (Tree.ID (Node), Wisitoken_Grammar_Actions.Descriptor); end case; end Process_Node; begin Create (File, Out_File, Output_File_Name); Put_Line (File, "// generated from " & Data.Grammar_Lexer.File_Name & " -*- buffer-read-only:t -*-"); -- FIXME: copy copyright, license? Put_Line (File, "module.exports = grammar({"); Put_Line (File, " name: '" & Language_Name & "',"); Put_Line (File, " rules: {"); Process_Node (Tree.Root); Put_Line (File, " }"); Put_Line (File, "});"); Close (File); end Print_Tree_Sitter; Trace : aliased WisiToken.Text_IO_Trace.Trace (Wisitoken_Grammar_Actions.Descriptor'Access); Input_Data : aliased WisiToken_Grammar_Runtime.User_Data_Type; Grammar_Parser : WisiToken.Parse.LR.Parser_No_Recover.Parser; Input_File_Name : Ada.Strings.Unbounded.Unbounded_String; Language_Name : Ada.Strings.Unbounded.Unbounded_String; begin Wisitoken_Grammar_Main.Create_Parser (Parser => Grammar_Parser, Trace => Trace'Unchecked_Access, User_Data => Input_Data'Unchecked_Access); declare use Ada.Command_Line; Arg : Integer := 1; begin if not (Argument_Count in 1 .. 4) then Put_Usage; Set_Exit_Status (Failure); return; end if; loop exit when Arg > Argument_Count; if Argument (Arg) = "--verbosity" then Arg := Arg + 1; Trace_Generate_EBNF := Integer'Value (Argument (Arg)); Arg := Arg + 1; else exit; end if; end loop; -- no more options Input_File_Name := +Argument (Arg); Arg := Arg + 1; Language_Name := +Argument (Arg); end; begin Grammar_Parser.Lexer.Reset_With_File (-Input_File_Name); exception when Ada.Text_IO.Name_Error | Ada.Text_IO.Use_Error => raise Ada.Text_IO.Name_Error with "input file '" & (-Input_File_Name) & "' could not be opened."; end; begin Grammar_Parser.Parse; exception when WisiToken.Syntax_Error => Grammar_Parser.Put_Errors; raise; end; Grammar_Parser.Execute_Actions; declare use Ada.Directories; Output_File_Name : constant String := Base_Name (-Input_File_Name) & ".js"; Tree : WisiToken.Syntax_Trees.Tree renames Grammar_Parser.Parsers.First_State_Ref.Tree; begin if Trace_Generate_EBNF > Outline then Put_Line ("'" & (-Input_File_Name) & "' => '" & Output_File_Name & "'"); end if; if Trace_Generate_EBNF > Detail then Put_Line ("wisitoken tree:"); Tree.Print_Tree (Wisitoken_Grammar_Actions.Descriptor); Ada.Text_IO.New_Line; end if; Print_Tree_Sitter (Input_Data, Tree, Output_File_Name, -Language_Name); end; exception when WisiToken.Syntax_Error | WisiToken.Parse_Error => -- error message already output Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : others => declare use Ada.Exceptions; use Ada.Command_Line; begin Put_Line (Standard_Error, Exception_Name (E) & ": " & Exception_Message (E)); Put_Line (Standard_Error, GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); Set_Exit_Status (Failure); end; end WisiToken.To_Tree_Sitter;
-- This spec has been automatically generated from STM32F072x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; package STM32_SVD.COMP is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CSR_COMP1EN_Field is STM32_SVD.Bit; subtype CSR_COMP1_INP_DAC_Field is STM32_SVD.Bit; subtype CSR_COMP1MODE_Field is STM32_SVD.UInt2; subtype CSR_COMP1INSEL_Field is STM32_SVD.UInt3; subtype CSR_COMP1OUTSEL_Field is STM32_SVD.UInt3; subtype CSR_COMP1POL_Field is STM32_SVD.Bit; subtype CSR_COMP1HYST_Field is STM32_SVD.UInt2; subtype CSR_COMP1OUT_Field is STM32_SVD.Bit; subtype CSR_COMP1LOCK_Field is STM32_SVD.Bit; subtype CSR_COMP2EN_Field is STM32_SVD.Bit; subtype CSR_COMP2MODE_Field is STM32_SVD.UInt2; subtype CSR_COMP2INSEL_Field is STM32_SVD.UInt3; subtype CSR_WNDWEN_Field is STM32_SVD.Bit; subtype CSR_COMP2OUTSEL_Field is STM32_SVD.UInt3; subtype CSR_COMP2POL_Field is STM32_SVD.Bit; subtype CSR_COMP2HYST_Field is STM32_SVD.UInt2; subtype CSR_COMP2OUT_Field is STM32_SVD.Bit; subtype CSR_COMP2LOCK_Field is STM32_SVD.Bit; -- control and status register type CSR_Register is record -- Comparator 1 enable COMP1EN : CSR_COMP1EN_Field := 16#0#; -- COMP1_INP_DAC COMP1_INP_DAC : CSR_COMP1_INP_DAC_Field := 16#0#; -- Comparator 1 mode COMP1MODE : CSR_COMP1MODE_Field := 16#0#; -- Comparator 1 inverting input selection COMP1INSEL : CSR_COMP1INSEL_Field := 16#0#; -- unspecified Reserved_7_7 : STM32_SVD.Bit := 16#0#; -- Comparator 1 output selection COMP1OUTSEL : CSR_COMP1OUTSEL_Field := 16#0#; -- Comparator 1 output polarity COMP1POL : CSR_COMP1POL_Field := 16#0#; -- Comparator 1 hysteresis COMP1HYST : CSR_COMP1HYST_Field := 16#0#; -- Read-only. Comparator 1 output COMP1OUT : CSR_COMP1OUT_Field := 16#0#; -- Comparator 1 lock COMP1LOCK : CSR_COMP1LOCK_Field := 16#0#; -- Comparator 2 enable COMP2EN : CSR_COMP2EN_Field := 16#0#; -- unspecified Reserved_17_17 : STM32_SVD.Bit := 16#0#; -- Comparator 2 mode COMP2MODE : CSR_COMP2MODE_Field := 16#0#; -- Comparator 2 inverting input selection COMP2INSEL : CSR_COMP2INSEL_Field := 16#0#; -- Window mode enable WNDWEN : CSR_WNDWEN_Field := 16#0#; -- Comparator 2 output selection COMP2OUTSEL : CSR_COMP2OUTSEL_Field := 16#0#; -- Comparator 2 output polarity COMP2POL : CSR_COMP2POL_Field := 16#0#; -- Comparator 2 hysteresis COMP2HYST : CSR_COMP2HYST_Field := 16#0#; -- Read-only. Comparator 2 output COMP2OUT : CSR_COMP2OUT_Field := 16#0#; -- Comparator 2 lock COMP2LOCK : CSR_COMP2LOCK_Field := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record COMP1EN at 0 range 0 .. 0; COMP1_INP_DAC at 0 range 1 .. 1; COMP1MODE at 0 range 2 .. 3; COMP1INSEL at 0 range 4 .. 6; Reserved_7_7 at 0 range 7 .. 7; COMP1OUTSEL at 0 range 8 .. 10; COMP1POL at 0 range 11 .. 11; COMP1HYST at 0 range 12 .. 13; COMP1OUT at 0 range 14 .. 14; COMP1LOCK at 0 range 15 .. 15; COMP2EN at 0 range 16 .. 16; Reserved_17_17 at 0 range 17 .. 17; COMP2MODE at 0 range 18 .. 19; COMP2INSEL at 0 range 20 .. 22; WNDWEN at 0 range 23 .. 23; COMP2OUTSEL at 0 range 24 .. 26; COMP2POL at 0 range 27 .. 27; COMP2HYST at 0 range 28 .. 29; COMP2OUT at 0 range 30 .. 30; COMP2LOCK at 0 range 31 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Comparator type COMP_Peripheral is record -- control and status register CSR : aliased CSR_Register; end record with Volatile; for COMP_Peripheral use record CSR at 0 range 0 .. 31; end record; -- Comparator COMP_Periph : aliased COMP_Peripheral with Import, Address => System'To_Address (16#4001001C#); end STM32_SVD.COMP;
with openGL.Tasks, GL.Pointers, GL.lean, ada.Characters.latin_1, ada.Strings.unbounded, ada.Text_IO, Interfaces.C.Strings; package body openGL.Program is use gl.lean, Interfaces, ada.Text_IO; compiling_in_debug_Mode : constant Boolean := True; type Shader_view is access all Shader.item'Class; -------------- -- Parameters -- procedure Program_is (Self : in out Parameters; Now : in openGL.Program.view) is begin Self.Program := Now; end Program_is; function Program (Self : in Parameters) return openGL.Program.view is begin return Self.Program; end Program; --------- --- Forge -- procedure define (Self : in out Item; use_vertex_Shader : in Shader.view; use_fragment_Shader : in Shader.view) is begin Tasks.check; Self.gl_Program := glCreateProgram; glAttachShader (Self.gl_Program, use_vertex_Shader.gl_Shader); glAttachShader (Self.gl_Program, use_fragment_Shader.gl_Shader); Self. vertex_Shader := use_vertex_Shader; Self.fragment_Shader := use_fragment_Shader; glLinkProgram (Self.gl_Program); declare use type C.int; Status : aliased gl.glInt; begin glGetProgramiv (Self.gl_Program, GL_LINK_STATUS, Status'unchecked_Access); if Status = 0 then declare link_Log : constant String := Self.ProgramInfoLog; begin Self.destroy; raise Error with "Program link error ~ " & link_Log; end; end if; end; if compiling_in_debug_Mode then glValidateProgram (Self.gl_Program); end if; end define; procedure define (Self : in out Item; use_vertex_Shader_File : in String; use_fragment_Shader_File : in String) is use openGL.Shader; the_vertex_Shader : constant Shader_view := new openGL.Shader.item; the_fragment_Shader : constant Shader_view := new openGL.Shader.item; begin the_vertex_Shader .define (openGL.Shader.vertex, use_vertex_Shader_File); the_fragment_Shader.define (openGL.Shader.fragment, use_fragment_Shader_File); Self.define ( the_vertex_Shader.all'Access, the_fragment_Shader.all'Access); end define; procedure destroy (Self : in out Item) is begin Tasks.check; glDeleteProgram (Self.gl_Program); end destroy; -------------- -- Attributes -- function Attribute (Self : access Item'Class; Named : in String) return openGL.Attribute.view is begin for Each in 1 .. Self.attribute_Count loop if Self.Attributes (Each).Name = Named then return Self.Attributes (Each); end if; end loop; raise Error with "'" & Named & "' is not a valid program attribute."; end Attribute; function attribute_Location (Self : access Item'Class; Named : in String) return gl.GLuint is use gl.Pointers; use type gl.GLint; attribute_Name : C.strings.chars_ptr := C.Strings.new_String (Named & ada.characters.Latin_1.NUL); begin Tasks.check; declare gl_Location : constant gl.GLint := glGetAttribLocation (Self.gl_Program, to_GLchar_access (attribute_Name)); begin if gl_Location = -1 then raise Error with "Requested attribute '" & Named & "' has no gl location in program."; end if; C.Strings.free (attribute_Name); return gl.GLuint (gl_Location); end; end attribute_Location; function is_defined (Self : in Item'Class) return Boolean is use type a_gl_Program; begin return Self.gl_Program /= 0; end is_defined; function ProgramInfoLog (Self : in Item) return String is use C, GL; info_log_Length : aliased glInt := 0; chars_Written : aliased glSizei := 0; begin Tasks.check; glGetProgramiv (Self.gl_Program, GL_INFO_LOG_LENGTH, info_log_Length'unchecked_Access); if info_log_Length = 0 then return ""; end if; declare use GL.Pointers; info_Log : aliased C.char_array := C.char_array' (1 .. C.size_t (info_log_Length) => <>); info_Log_ptr : constant C.strings.chars_ptr := C.strings.to_chars_ptr (info_Log'unchecked_Access); begin glGetProgramInfoLog (Self.gl_Program, glSizei (info_log_Length), chars_Written'unchecked_Access, to_GLchar_access (info_Log_ptr)); return C.to_Ada (info_Log); end; end ProgramInfoLog; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.bool is the_Variable : Variable.uniform.bool; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.int is the_Variable : Variable.uniform.int; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.float is the_Variable : Variable.uniform.float; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.vec3 is the_Variable : Variable.uniform.vec3; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.vec4 is the_Variable : Variable.uniform.vec4; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.mat3 is the_Variable : Variable.uniform.mat3; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.mat4 is the_Variable : Variable.uniform.mat4; begin the_Variable.define (Self, Named); return the_Variable; end uniform_Variable; -------------- -- Operations -- procedure add (Self : in out Item; Attribute : in openGL.Attribute.view) is begin Self.attribute_Count := Self.attribute_Count + 1; Self.Attributes (Self.attribute_Count) := Attribute; end add; procedure enable (Self : in out Item) is use type gl.GLuint; begin Tasks.check; if Self.gl_Program = 0 then Item'Class (Self).define; -- TODO: This appears to do nothing. end if; glUseProgram (self.gl_Program); end enable; procedure enable_Attributes (Self : in Item) is begin for Each in 1 .. Self.attribute_Count loop Self.Attributes (Each).enable; end loop; end enable_Attributes; procedure mvp_Matrix_is (Self : in out Item'Class; Now : in Matrix_4x4) is begin Self.mvp_Matrix := Now; end mvp_Matrix_is; procedure inverse_modelview_Matrix_is (Self : in out Item'Class; Now : in Matrix_3x3) is begin Self.inverse_modelview_Matrix := Now; end inverse_modelview_Matrix_is; procedure directional_Light_is (Self : in out Item'Class; light_Id : in Positive; Now : in Light.directional.item) is begin Self.directional_Light (light_Id) := Now; end directional_Light_is; procedure Scale_is (Self : in out Item'Class; Now : in Vector_3) is begin Self.Scale := Now; end Scale_is; procedure Shine_is (Self : in out Item'Class; Now : in Shine) is begin Self.Shine := Now; end Shine_is; procedure set_mvp_Uniform (Self : in Item) is the_mvp_Uniform : constant Variable.uniform.mat4 := Self.uniform_Variable ("mvp_Matrix"); begin the_mvp_Uniform.Value_is (Self.mvp_Matrix); end set_mvp_Uniform; -- Privvy -- function gl_Program (Self : in Item) return a_gl_Program is begin return Self.gl_Program; end gl_Program; end openGL.Program;
-- This spec has been automatically generated from STM32L151.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.COMP is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CSR_INSEL_Field is HAL.UInt3; subtype CSR_OUTSEL_Field is HAL.UInt3; -- CSR_FCH array type CSR_FCH_Field_Array is array (3 .. 4) of Boolean with Component_Size => 1, Size => 2; -- Type definition for CSR_FCH type CSR_FCH_Field (As_Array : Boolean := False) is record case As_Array is when False => -- FCH as a value Val : HAL.UInt2; when True => -- FCH as an array Arr : CSR_FCH_Field_Array; end case; end record with Unchecked_Union, Size => 2; for CSR_FCH_Field use record Val at 0 range 0 .. 1; Arr at 0 range 0 .. 1; end record; -- comparator control and status register type CSR_Register is record -- 10 kO pull-up resistor PU10K : Boolean := False; -- 400 kO pull-up resistor PU400K : Boolean := False; -- 10 kO pull-down resistor PD10K : Boolean := False; -- 400 kO pull-down resistor PD400K : Boolean := False; -- Comparator 1 enable CMP1EN : Boolean := False; -- SW1 analog switch enable SW1 : Boolean := False; -- unspecified Reserved_6_6 : HAL.Bit := 16#0#; -- Read-only. Comparator 1 output CMP1OUT : Boolean := False; -- unspecified Reserved_8_11 : HAL.UInt4 := 16#0#; -- Comparator 2 speed mode SPEED : Boolean := False; -- Read-only. Comparator 2 output CMP2OUT : Boolean := False; -- unspecified Reserved_14_15 : HAL.UInt2 := 16#0#; -- VREFINT output enable VREFOUTEN : Boolean := False; -- Window mode enable WNDWE : Boolean := False; -- Inverted input selection INSEL : CSR_INSEL_Field := 16#0#; -- Comparator 2 output selection OUTSEL : CSR_OUTSEL_Field := 16#0#; -- unspecified Reserved_24_25 : HAL.UInt2 := 16#0#; -- Select GPIO port PA3 as fast ADC input channel CH3. FCH : CSR_FCH_Field := (As_Array => False, Val => 16#0#); -- Select GPIO port PC3 as re-routed ADC input channel CH13. RCH13 : Boolean := False; -- Channel Acquisition Interrupt Enable / Clear CAIE : Boolean := False; -- Read-only. Channel acquisition interrupt flag CAIF : Boolean := False; -- Suspend Timer Mode TSUSP : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record PU10K at 0 range 0 .. 0; PU400K at 0 range 1 .. 1; PD10K at 0 range 2 .. 2; PD400K at 0 range 3 .. 3; CMP1EN at 0 range 4 .. 4; SW1 at 0 range 5 .. 5; Reserved_6_6 at 0 range 6 .. 6; CMP1OUT at 0 range 7 .. 7; Reserved_8_11 at 0 range 8 .. 11; SPEED at 0 range 12 .. 12; CMP2OUT at 0 range 13 .. 13; Reserved_14_15 at 0 range 14 .. 15; VREFOUTEN at 0 range 16 .. 16; WNDWE at 0 range 17 .. 17; INSEL at 0 range 18 .. 20; OUTSEL at 0 range 21 .. 23; Reserved_24_25 at 0 range 24 .. 25; FCH at 0 range 26 .. 27; RCH13 at 0 range 28 .. 28; CAIE at 0 range 29 .. 29; CAIF at 0 range 30 .. 30; TSUSP at 0 range 31 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Comparators type COMP_Peripheral is record -- comparator control and status register CSR : aliased CSR_Register; end record with Volatile; for COMP_Peripheral use record CSR at 0 range 0 .. 31; end record; -- Comparators COMP_Periph : aliased COMP_Peripheral with Import, Address => System'To_Address (16#40007C00#); end STM32_SVD.COMP;
-- TITLE main body -- AUTHOR: John Self (UCI) -- DESCRIPTION driver routines for aflex. Calls drivers for all -- high level routines from other packages. -- $Header: /co/ua/self/arcadia/aflex/ada/src/RCS/mainS.a,v 1.5 90/01/12 15:20:14 self Exp Locker: self $ --*************************************************************************** -- This file is subject to the Arcadia License Agreement. -- -- (see notice in aflex.a) -- --*************************************************************************** -- aflex - tool to generate fast lexical analyzers package MAIN_BODY is procedure AFLEXEND(STATUS : in INTEGER); procedure AFLEXINIT; procedure READIN; procedure SET_UP_INITIAL_ALLOCATIONS; AFLEX_TERMINATE : exception; TERMINATION_STATUS : INTEGER; end MAIN_BODY;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 7 -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-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. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Types; use Types; package Exp_Ch7 is procedure Expand_N_Package_Body (N : Node_Id); procedure Expand_N_Package_Declaration (N : Node_Id); ----------------------------- -- Finalization Management -- ----------------------------- function In_Finalization_Root (E : Entity_Id) return Boolean; -- True if current scope is in package System.Finalization_Root. Used -- to avoid certain expansions that would involve circularity in the -- Rtsfind mechanism. procedure Build_Final_List (N : Node_Id; Typ : Entity_Id); -- Build finalization list for anonymous access types, and for access -- types that are frozen before their designated types are known to -- be controlled. procedure Build_Controlling_Procs (Typ : Entity_Id); -- Typ is a record, and array type having controlled components. -- Create the procedures Deep_Initialize, Deep_Adjust and Deep_Finalize -- that take care of finalization management at run-time. procedure Build_Late_Proc (Typ : Entity_Id; Nam : Name_Id); -- Build one controlling procedure when a late body overrides one of -- the controlling operations. function Controller_Component (Typ : Entity_Id) return Entity_Id; -- Returns the entity of the component whose name is 'Name_uController' function Controlled_Type (T : Entity_Id) return Boolean; -- True if T potentially needs finalization actions function Find_Final_List (E : Entity_Id; Ref : Node_Id := Empty) return Node_Id; -- E is an entity representing a controlled object, a controlled type -- or a scope. If Ref is not empty, it is a reference to a controlled -- record, the closest Final list is in the controller component of -- the record containing Ref otherwise this function returns a -- reference to the final list attached to the closest dynamic scope -- (that can be E itself) creating this final list if necessary. function Has_New_Controlled_Component (E : Entity_Id) return Boolean; -- E is a type entity. Give the same resul as Has_Controlled_Component -- except for tagged extensions where the result is True only if the -- latest extension contains a controlled component. function Make_Attach_Call (Obj_Ref : Node_Id; Flist_Ref : Node_Id; With_Attach : Node_Id) return Node_Id; -- Attach the referenced object to the referenced Final Chain -- 'Flist_Ref' With_Attach is an expression of type Short_Short_Integer -- which can be either '0' to signify no attachment, '1' for -- attachement to a simply linked list or '2' for attachement to a -- doubly linked list. function Make_Init_Call (Ref : Node_Id; Typ : Entity_Id; Flist_Ref : Node_Id; With_Attach : Node_Id) return List_Id; -- Ref is an expression (with no-side effect and is not required to -- have been previously analyzed) that references the object to be -- initialized. Typ is the expected type of Ref, which is a controlled -- type (Is_Controlled) or a type with controlled components -- (Has_Controlled). With_Attach is an integer expression representing -- the level of attachment, see Attach_To_Final_List's Nb_Link param -- documentation in s-finimp.ads. -- -- This function will generate the appropriate calls to make -- sure that the objects referenced by Ref are initialized. The -- generate code is quite different depending on the fact the type -- IS_Controlled or HAS_Controlled but this is not the problem of the -- caller, the details are in the body. function Make_Adjust_Call (Ref : Node_Id; Typ : Entity_Id; Flist_Ref : Node_Id; With_Attach : Node_Id; Allocator : Boolean := False) return List_Id; -- Ref is an expression (with no-side effect and is not required to -- have been previously analyzed) that references the object to be -- adjusted. Typ is the expected type of Ref, which is a controlled -- type (Is_Controlled) or a type with controlled components -- (Has_Controlled). With_Attach is an integer expression representing -- the level of attachment, see Attach_To_Final_List's Nb_Link param -- documentation in s-finimp.ads. Note: if Typ is Finalize_Storage_Only -- and the object is at library level, then With_Attach will be ignored, -- and a zero link level will be passed to Attach_To_Final_List. -- -- This function will generate the appropriate calls to make -- sure that the objects referenced by Ref are adjusted. The generated -- code is quite different depending on the fact the type IS_Controlled -- or HAS_Controlled but this is not the problem of the caller, the -- details are in the body. The objects must be attached when the adjust -- takes place after an initialization expression but not when it takes -- place after a regular assignment. -- -- If Allocator is True, we are adjusting a newly-created object. The -- existing chaining pointers should not be left unchanged, because they -- may come from a bit-for-bit copy of those from an initializing object. -- So, when this flag is True, if the chaining pointers should otherwise -- be left unset, instead they are reset to null. function Make_Final_Call (Ref : Node_Id; Typ : Entity_Id; With_Detach : Node_Id) return List_Id; -- Ref is an expression (with no-side effect and is not required -- to have been previously analyzed) that references the object to -- be Finalized. Typ is the expected type of Ref, which is a -- controlled type (Is_Controlled) or a type with controlled -- components (Has_Controlled). With_Detach is a boolean expression -- indicating whether to detach the controlled object from whatever -- finalization list it is currently attached to. -- -- This function will generate the appropriate calls to make -- sure that the objects referenced by Ref are finalized. The generated -- code is quite different depending on the fact the type IS_Controlled -- or HAS_Controlled but this is not the problem of the caller, the -- details are in the body. The objects must be detached when finalizing -- an unchecked deallocated object but not when finalizing the target of -- an assignment, it is not necessary either on scope exit. procedure Expand_Ctrl_Function_Call (N : Node_Id); -- Expand a call to a function returning a controlled value. That is to -- say attach the result of the call to the current finalization list, -- which is the one of the transient scope created for such constructs. -------------------------------------------- -- Task and Protected Object finalization -- -------------------------------------------- function Cleanup_Array (N : Node_Id; Obj : Node_Id; Typ : Entity_Id) return List_Id; -- Generate loops to finalize any tasks or simple protected objects -- that are subcomponents of an array. function Cleanup_Protected_Object (N : Node_Id; Ref : Node_Id) return Node_Id; -- Generate code to finalize a protected object without entries function Cleanup_Record (N : Node_Id; Obj : Node_Id; Typ : Entity_Id) return List_Id; -- For each subcomponent of a record that contains tasks or simple -- protected objects, generate the appropriate finalization call. function Cleanup_Task (N : Node_Id; Ref : Node_Id) return Node_Id; -- Generate code to finalize a task function Has_Simple_Protected_Object (T : Entity_Id) return Boolean; -- Check whether composite type contains a simple protected component function Is_Simple_Protected_Type (T : Entity_Id) return Boolean; -- Check whether argument is a protected type without entries. -- Protected types with entries are controlled, and their cleanup -- is handled by the standard finalization machinery. For simple -- protected types we generate inline code to release their locks. -------------------------------- -- Transient Scope Management -- -------------------------------- procedure Expand_Cleanup_Actions (N : Node_Id); -- Expand the necessary stuff into a scope to enable finalization of local -- objects and deallocation of transient data when exiting the scope. N is -- a "scope node" that is to say one of the following: N_Block_Statement, -- N_Subprogram_Body, N_Task_Body, N_Entry_Body. procedure Establish_Transient_Scope (N : Node_Id; Sec_Stack : Boolean); -- Push a new transient scope on the scope stack. N is the node responsible -- for the need of a transient scope. If Sec_Stack is True then the -- secondary stack is brought in, otherwise it isn't. function Node_To_Be_Wrapped return Node_Id; -- return the node to be wrapped if the current scope is transient procedure Store_Before_Actions_In_Scope (L : List_Id); -- Append the list L of actions to the end of the before-actions store -- in the top of the scope stack procedure Store_After_Actions_In_Scope (L : List_Id); -- Append the list L of actions to the beginning of the after-actions -- store in the top of the scope stack procedure Wrap_Transient_Declaration (N : Node_Id); -- N is an object declaration. Expand the finalization calls after the -- declaration and make the outer scope beeing the transient one. procedure Wrap_Transient_Expression (N : Node_Id); -- N is a sub-expression. Expand a transient block around an expression procedure Wrap_Transient_Statement (N : Node_Id); -- N is a statement. Expand a transient block around an instruction end Exp_Ch7;
package body openGL.Light is function is_On (Self : in Item) return Boolean is begin return Self.On; end is_On; procedure is_On (Self : in out Item; Now : in Boolean := True) is begin Self.On := Now; end is_On; function Site (Self : in Item) return openGL.Site is begin return Self.Site; end Site; procedure Site_is (Self : in out Item; Now : in openGL.Site) is begin Self.Site := Now; end Site_is; end openGL.Light;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Cross_Reference_Updaters; with Program.Elements.Discrete_Ranges; with Program.Elements.Expressions; with Program.Interpretations; with Program.Visibility; package Program.Complete_Contexts is pragma Preelaborate; procedure Resolve_To_Expected_Type (Element : not null Program.Elements.Element_Access; Sets : not null Program.Interpretations.Context_Access; Setter : not null Program.Cross_Reference_Updaters .Cross_Reference_Updater_Access; Expect : Program.Visibility.View) with Pre => Expect.Kind in Program.Visibility.Type_View_Kind; procedure Resolve_To_Any_Type (Element : not null Program.Elements.Expressions.Expression_Access; Sets : not null Program.Interpretations.Context_Access; Setter : not null Program.Cross_Reference_Updaters .Cross_Reference_Updater_Access; Result : out Program.Visibility.View); procedure Resolve_To_Discrete_Type (Element : not null Program.Elements.Expressions.Expression_Access; Sets : not null Program.Interpretations.Context_Access; Setter : not null Program.Cross_Reference_Updaters .Cross_Reference_Updater_Access; Result : out Program.Visibility.View); private function Up (Element : not null access Program.Elements.Element'Class; Sets : not null Program.Interpretations.Context_Access) return Program.Interpretations.Interpretation_Set; -- Visit subtree rooted at the Element and construct set of possible -- interpretations for it. procedure Down (Element : not null access Program.Elements.Element'Class; Solution : Program.Interpretations.Solution; Setter : not null Program.Cross_Reference_Updaters .Cross_Reference_Updater_Access; Sets : not null Program.Interpretations.Context_Access); -- Assign solution to the Element and all its children. procedure Resolve_Parameters (Arguments : Program.Interpretations.Interpretation_Set_Array; Parameters : Program.Visibility.View_Array; Callback : access procedure (Down : Program.Interpretations.Solution_Array); Down : in out Program.Interpretations.Solution_Array; Index : Positive := 1); -- For each parameter starting from Parameters (Index), find an -- expression interpretation in Arguments provided that its type is an -- expected type of the parameter. Then fill corresponding solutions in -- Down and call Callback (Down). end Program.Complete_Contexts;
with System.Formatting.Decimal; package body System.Img_LLD is procedure Image_Long_Long_Decimal ( V : Long_Long_Integer; S : in out String; P : out Natural; Scale : Integer) is Fore_Last : Natural; begin Formatting.Decimal.Image ( V, S, Fore_Last, P, Scale, Aft_Width => Integer'Max (1, Scale)); end Image_Long_Long_Decimal; end System.Img_LLD;
package ADMBase.Coords is function x_coord (i : Integer) return Real; function y_coord (j : Integer) return Real; function z_coord (k : Integer) return Real; end ADMBase.Coords;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . R E G P A T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1986 by University of Toronto. -- -- Copyright (C) 1999-2019, 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 is an altered Ada 95 version of the original V8 style regular -- expression library written in C by Henry Spencer. Apart from the -- translation to Ada, the interface has been considerably changed to -- use the Ada String type instead of C-style nul-terminated strings. -- Beware that some of this code is subtly aware of the way operator -- precedence is structured in regular expressions. Serious changes in -- regular-expression syntax might require a total rethink. with System.IO; use System.IO; with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Unchecked_Conversion; package body System.Regpat is Debug : constant Boolean := False; -- Set to True to activate debug traces. This is normally set to constant -- False to simply delete all the trace code. It is to be edited to True -- for internal debugging of the package. ---------------------------- -- Implementation details -- ---------------------------- -- This is essentially a linear encoding of a nondeterministic -- finite-state machine, also known as syntax charts or -- "railroad normal form" in parsing technology. -- Each node is an opcode plus a "next" pointer, possibly plus an -- operand. "Next" pointers of all nodes except BRANCH implement -- concatenation; a "next" pointer with a BRANCH on both ends of it -- is connecting two alternatives. -- The operand of some types of node is a literal string; for others, -- it is a node leading into a sub-FSM. In particular, the operand of -- a BRANCH node is the first node of the branch. -- (NB this is *not* a tree structure: the tail of the branch connects -- to the thing following the set of BRANCHes). -- You can see the exact byte-compiled version by using the Dump -- subprogram. However, here are a few examples: -- (a|b): 1 : BRANCH (next at 9) -- 4 : EXACT (next at 17) operand=a -- 9 : BRANCH (next at 17) -- 12 : EXACT (next at 17) operand=b -- 17 : EOP (next at 0) -- -- (ab)*: 1 : CURLYX (next at 25) { 0, 32767} -- 8 : OPEN 1 (next at 12) -- 12 : EXACT (next at 18) operand=ab -- 18 : CLOSE 1 (next at 22) -- 22 : WHILEM (next at 0) -- 25 : NOTHING (next at 28) -- 28 : EOP (next at 0) -- The opcodes are: type Opcode is -- Name Operand? Meaning (EOP, -- no End of program MINMOD, -- no Next operator is not greedy -- Classes of characters ANY, -- no Match any one character except newline SANY, -- no Match any character, including new line ANYOF, -- class Match any character in this class EXACT, -- str Match this string exactly EXACTF, -- str Match this string (case-folding is one) NOTHING, -- no Match empty string SPACE, -- no Match any whitespace character NSPACE, -- no Match any non-whitespace character DIGIT, -- no Match any numeric character NDIGIT, -- no Match any non-numeric character ALNUM, -- no Match any alphanumeric character NALNUM, -- no Match any non-alphanumeric character -- Branches BRANCH, -- node Match this alternative, or the next -- Simple loops (when the following node is one character in length) STAR, -- node Match this simple thing 0 or more times PLUS, -- node Match this simple thing 1 or more times CURLY, -- 2num node Match this simple thing between n and m times. -- Complex loops CURLYX, -- 2num node Match this complex thing {n,m} times -- The nums are coded on two characters each WHILEM, -- no Do curly processing and see if rest matches -- Matches after or before a word BOL, -- no Match "" at beginning of line MBOL, -- no Same, assuming multiline (match after \n) SBOL, -- no Same, assuming single line (don't match at \n) EOL, -- no Match "" at end of line MEOL, -- no Same, assuming multiline (match before \n) SEOL, -- no Same, assuming single line (don't match at \n) BOUND, -- no Match "" at any word boundary NBOUND, -- no Match "" at any word non-boundary -- Parenthesis groups handling REFF, -- num Match some already matched string, folded OPEN, -- num Mark this point in input as start of #n CLOSE); -- num Analogous to OPEN for Opcode'Size use 8; -- Opcode notes: -- BRANCH -- The set of branches constituting a single choice are hooked -- together with their "next" pointers, since precedence prevents -- anything being concatenated to any individual branch. The -- "next" pointer of the last BRANCH in a choice points to the -- thing following the whole choice. This is also where the -- final "next" pointer of each individual branch points; each -- branch starts with the operand node of a BRANCH node. -- STAR,PLUS -- '?', and complex '*' and '+', are implemented with CURLYX. -- branches. Simple cases (one character per match) are implemented with -- STAR and PLUS for speed and to minimize recursive plunges. -- OPEN,CLOSE -- ...are numbered at compile time. -- EXACT, EXACTF -- There are in fact two arguments, the first one is the length (minus -- one of the string argument), coded on one character, the second -- argument is the string itself, coded on length + 1 characters. -- A node is one char of opcode followed by two chars of "next" pointer. -- "Next" pointers are stored as two 8-bit pieces, high order first. The -- value is a positive offset from the opcode of the node containing it. -- An operand, if any, simply follows the node. (Note that much of the -- code generation knows about this implicit relationship.) -- Using two bytes for the "next" pointer is vast overkill for most -- things, but allows patterns to get big without disasters. Next_Pointer_Bytes : constant := 3; -- Points after the "next pointer" data. An instruction is therefore: -- 1 byte: instruction opcode -- 2 bytes: pointer to next instruction -- * bytes: optional data for the instruction ----------------------- -- Character classes -- ----------------------- -- This is the implementation for character classes ([...]) in the -- syntax for regular expressions. Each character (0..256) has an -- entry into the table. This makes for a very fast matching -- algorithm. type Class_Byte is mod 256; type Character_Class is array (Class_Byte range 0 .. 31) of Class_Byte; type Bit_Conversion_Array is array (Class_Byte range 0 .. 7) of Class_Byte; Bit_Conversion : constant Bit_Conversion_Array := (1, 2, 4, 8, 16, 32, 64, 128); type Std_Class is (ANYOF_NONE, ANYOF_ALNUM, -- Alphanumeric class [a-zA-Z0-9] ANYOF_NALNUM, ANYOF_SPACE, -- Space class [ \t\n\r\f] ANYOF_NSPACE, ANYOF_DIGIT, -- Digit class [0-9] ANYOF_NDIGIT, ANYOF_ALNUMC, -- Alphanumeric class [a-zA-Z0-9] ANYOF_NALNUMC, ANYOF_ALPHA, -- Alpha class [a-zA-Z] ANYOF_NALPHA, ANYOF_ASCII, -- Ascii class (7 bits) 0..127 ANYOF_NASCII, ANYOF_CNTRL, -- Control class ANYOF_NCNTRL, ANYOF_GRAPH, -- Graphic class ANYOF_NGRAPH, ANYOF_LOWER, -- Lower case class [a-z] ANYOF_NLOWER, ANYOF_PRINT, -- printable class ANYOF_NPRINT, ANYOF_PUNCT, -- ANYOF_NPUNCT, ANYOF_UPPER, -- Upper case class [A-Z] ANYOF_NUPPER, ANYOF_XDIGIT, -- Hexadecimal digit ANYOF_NXDIGIT ); procedure Set_In_Class (Bitmap : in out Character_Class; C : Character); -- Set the entry to True for C in the class Bitmap function Get_From_Class (Bitmap : Character_Class; C : Character) return Boolean; -- Return True if the entry is set for C in the class Bitmap procedure Reset_Class (Bitmap : out Character_Class); -- Clear all the entries in the class Bitmap pragma Inline (Set_In_Class); pragma Inline (Get_From_Class); pragma Inline (Reset_Class); ----------------------- -- Local Subprograms -- ----------------------- function "=" (Left : Character; Right : Opcode) return Boolean; function Is_Alnum (C : Character) return Boolean; -- Return True if C is an alphanum character or an underscore ('_') function Is_White_Space (C : Character) return Boolean; -- Return True if C is a whitespace character function Is_Printable (C : Character) return Boolean; -- Return True if C is a printable character function Operand (P : Pointer) return Pointer; -- Return a pointer to the first operand of the node at P function String_Length (Program : Program_Data; P : Pointer) return Program_Size; -- Return the length of the string argument of the node at P function String_Operand (P : Pointer) return Pointer; -- Return a pointer to the string argument of the node at P procedure Bitmap_Operand (Program : Program_Data; P : Pointer; Op : out Character_Class); -- Return a pointer to the string argument of the node at P function Get_Next (Program : Program_Data; IP : Pointer) return Pointer; -- Dig the next instruction pointer out of a node procedure Optimize (Self : in out Pattern_Matcher); -- Optimize a Pattern_Matcher by noting certain special cases function Read_Natural (Program : Program_Data; IP : Pointer) return Natural; -- Return the 2-byte natural coded at position IP -- All of the subprograms above are tiny and should be inlined pragma Inline ("="); pragma Inline (Is_Alnum); pragma Inline (Is_White_Space); pragma Inline (Get_Next); pragma Inline (Operand); pragma Inline (Read_Natural); pragma Inline (String_Length); pragma Inline (String_Operand); type Expression_Flags is record Has_Width, -- Known never to match null string Simple, -- Simple enough to be STAR/PLUS operand SP_Start : Boolean; -- Starts with * or + end record; Worst_Expression : constant Expression_Flags := (others => False); -- Worst case procedure Dump_Until (Program : Program_Data; Index : in out Pointer; Till : Pointer; Indent : Natural; Do_Print : Boolean := True); -- Dump the program until the node Till (not included) is met. Every line -- is indented with Index spaces at the beginning Dumps till the end if -- Till is 0. procedure Dump_Operation (Program : Program_Data; Index : Pointer; Indent : Natural); -- Same as above, but only dumps a single operation, and compute its -- indentation from the program. --------- -- "=" -- --------- function "=" (Left : Character; Right : Opcode) return Boolean is begin return Character'Pos (Left) = Opcode'Pos (Right); end "="; -------------------- -- Bitmap_Operand -- -------------------- procedure Bitmap_Operand (Program : Program_Data; P : Pointer; Op : out Character_Class) is function Convert is new Ada.Unchecked_Conversion (Program_Data, Character_Class); begin Op (0 .. 31) := Convert (Program (P + Next_Pointer_Bytes .. P + 34)); end Bitmap_Operand; ------------- -- Compile -- ------------- procedure Compile (Matcher : out Pattern_Matcher; Expression : String; Final_Code_Size : out Program_Size; Flags : Regexp_Flags := No_Flags) is -- We can't allocate space until we know how big the compiled form -- will be, but we can't compile it (and thus know how big it is) -- until we've got a place to put the code. So we cheat: we compile -- it twice, once with code generation turned off and size counting -- turned on, and once "for real". -- This also means that we don't allocate space until we are sure -- that the thing really will compile successfully, and we never -- have to move the code and thus invalidate pointers into it. -- Beware that the optimization-preparation code in here knows -- about some of the structure of the compiled regexp. PM : Pattern_Matcher renames Matcher; Program : Program_Data renames PM.Program; Emit_Ptr : Pointer := Program_First; Parse_Pos : Natural := Expression'First; -- Input-scan pointer Parse_End : constant Natural := Expression'Last; ---------------------------- -- Subprograms for Create -- ---------------------------- procedure Emit (B : Character); -- Output the Character B to the Program. If code-generation is -- disabled, simply increments the program counter. function Emit_Node (Op : Opcode) return Pointer; -- If code-generation is enabled, Emit_Node outputs the -- opcode Op and reserves space for a pointer to the next node. -- Return value is the location of new opcode, i.e. old Emit_Ptr. procedure Emit_Natural (IP : Pointer; N : Natural); -- Split N on two characters at position IP procedure Emit_Class (Bitmap : Character_Class); -- Emits a character class procedure Case_Emit (C : Character); -- Emit C, after converting is to lower-case if the regular -- expression is case insensitive. procedure Parse (Parenthesized : Boolean; Capturing : Boolean; Flags : out Expression_Flags; IP : out Pointer); -- Parse regular expression, i.e. main body or parenthesized thing. -- Caller must absorb opening parenthesis. Capturing should be set to -- True when we have an open parenthesis from which we want the user -- to extra text. procedure Parse_Branch (Flags : out Expression_Flags; First : Boolean; IP : out Pointer); -- Implements the concatenation operator and handles '|'. -- First should be true if this is the first item of the alternative. procedure Parse_Piece (Expr_Flags : out Expression_Flags; IP : out Pointer); -- Parse something followed by possible [*+?] procedure Parse_Atom (Expr_Flags : out Expression_Flags; IP : out Pointer); -- Parse_Atom is the lowest level parse procedure. -- -- Optimization: Gobbles an entire sequence of ordinary characters so -- that it can turn them into a single node, which is smaller to store -- and faster to run. Backslashed characters are exceptions, each -- becoming a separate node; the code is simpler that way and it's -- not worth fixing. procedure Insert_Operator (Op : Opcode; Operand : Pointer; Greedy : Boolean := True); -- Insert_Operator inserts an operator in front of an already-emitted -- operand and relocates the operand. This applies to PLUS and STAR. -- If Minmod is True, then the operator is non-greedy. function Insert_Operator_Before (Op : Opcode; Operand : Pointer; Greedy : Boolean; Opsize : Pointer) return Pointer; -- Insert an operator before Operand (and move the latter forward in the -- program). Opsize is the size needed to represent the operator. This -- returns the position at which the operator was inserted, and moves -- Emit_Ptr after the new position of the operand. procedure Insert_Curly_Operator (Op : Opcode; Min : Natural; Max : Natural; Operand : Pointer; Greedy : Boolean := True); -- Insert an operator for CURLY ({Min}, {Min,} or {Min,Max}). -- If Minmod is True, then the operator is non-greedy. procedure Link_Tail (P, Val : Pointer); -- Link_Tail sets the next-pointer at the end of a node chain procedure Link_Operand_Tail (P, Val : Pointer); -- Link_Tail on operand of first argument; noop if operand-less procedure Fail (M : String); pragma No_Return (Fail); -- Fail with a diagnostic message, if possible function Is_Curly_Operator (IP : Natural) return Boolean; -- Return True if IP is looking at a '{' that is the beginning -- of a curly operator, i.e. it matches {\d+,?\d*} function Is_Mult (IP : Natural) return Boolean; -- Return True if C is a regexp multiplier: '+', '*' or '?' procedure Get_Curly_Arguments (IP : Natural; Min : out Natural; Max : out Natural; Greedy : out Boolean); -- Parse the argument list for a curly operator. -- It is assumed that IP is indeed pointing at a valid operator. -- So what is IP and how come IP is not referenced in the body ??? procedure Parse_Character_Class (IP : out Pointer); -- Parse a character class. -- The calling subprogram should consume the opening '[' before. procedure Parse_Literal (Expr_Flags : out Expression_Flags; IP : out Pointer); -- Parse_Literal encodes a string of characters to be matched exactly function Parse_Posix_Character_Class return Std_Class; -- Parse a posix character class, like [:alpha:] or [:^alpha:]. -- The caller is supposed to absorb the opening [. pragma Inline (Is_Mult); pragma Inline (Emit_Natural); pragma Inline (Parse_Character_Class); -- since used only once --------------- -- Case_Emit -- --------------- procedure Case_Emit (C : Character) is begin if (Flags and Case_Insensitive) /= 0 then Emit (To_Lower (C)); else -- Dump current character Emit (C); end if; end Case_Emit; ---------- -- Emit -- ---------- procedure Emit (B : Character) is begin if Emit_Ptr <= PM.Size then Program (Emit_Ptr) := B; end if; Emit_Ptr := Emit_Ptr + 1; end Emit; ---------------- -- Emit_Class -- ---------------- procedure Emit_Class (Bitmap : Character_Class) is subtype Program31 is Program_Data (0 .. 31); function Convert is new Ada.Unchecked_Conversion (Character_Class, Program31); begin -- What is the mysterious constant 31 here??? Can't it be expressed -- symbolically (size of integer - 1 or some such???). In any case -- it should be declared as a constant (and referenced presumably -- as this constant + 1 below. if Emit_Ptr + 31 <= PM.Size then Program (Emit_Ptr .. Emit_Ptr + 31) := Convert (Bitmap); end if; Emit_Ptr := Emit_Ptr + 32; end Emit_Class; ------------------ -- Emit_Natural -- ------------------ procedure Emit_Natural (IP : Pointer; N : Natural) is begin if IP + 1 <= PM.Size then Program (IP + 1) := Character'Val (N / 256); Program (IP) := Character'Val (N mod 256); end if; end Emit_Natural; --------------- -- Emit_Node -- --------------- function Emit_Node (Op : Opcode) return Pointer is Result : constant Pointer := Emit_Ptr; begin if Emit_Ptr + 2 <= PM.Size then Program (Emit_Ptr) := Character'Val (Opcode'Pos (Op)); Program (Emit_Ptr + 1) := ASCII.NUL; Program (Emit_Ptr + 2) := ASCII.NUL; end if; Emit_Ptr := Emit_Ptr + Next_Pointer_Bytes; return Result; end Emit_Node; ---------- -- Fail -- ---------- procedure Fail (M : String) is begin raise Expression_Error with M; end Fail; ------------------------- -- Get_Curly_Arguments -- ------------------------- procedure Get_Curly_Arguments (IP : Natural; Min : out Natural; Max : out Natural; Greedy : out Boolean) is pragma Unreferenced (IP); Save_Pos : Natural := Parse_Pos + 1; begin Min := 0; Max := Max_Curly_Repeat; while Expression (Parse_Pos) /= '}' and then Expression (Parse_Pos) /= ',' loop Parse_Pos := Parse_Pos + 1; end loop; Min := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1)); if Expression (Parse_Pos) = ',' then Save_Pos := Parse_Pos + 1; while Expression (Parse_Pos) /= '}' loop Parse_Pos := Parse_Pos + 1; end loop; if Save_Pos /= Parse_Pos then Max := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1)); end if; else Max := Min; end if; if Parse_Pos < Expression'Last and then Expression (Parse_Pos + 1) = '?' then Greedy := False; Parse_Pos := Parse_Pos + 1; else Greedy := True; end if; end Get_Curly_Arguments; --------------------------- -- Insert_Curly_Operator -- --------------------------- procedure Insert_Curly_Operator (Op : Opcode; Min : Natural; Max : Natural; Operand : Pointer; Greedy : Boolean := True) is Old : Pointer; begin Old := Insert_Operator_Before (Op, Operand, Greedy, Opsize => 7); Emit_Natural (Old + Next_Pointer_Bytes, Min); Emit_Natural (Old + Next_Pointer_Bytes + 2, Max); end Insert_Curly_Operator; ---------------------------- -- Insert_Operator_Before -- ---------------------------- function Insert_Operator_Before (Op : Opcode; Operand : Pointer; Greedy : Boolean; Opsize : Pointer) return Pointer is Dest : constant Pointer := Emit_Ptr; Old : Pointer; Size : Pointer := Opsize; begin -- If not greedy, we have to emit another opcode first if not Greedy then Size := Size + Next_Pointer_Bytes; end if; -- Move the operand in the byte-compilation, so that we can insert -- the operator before it. if Emit_Ptr + Size <= PM.Size then Program (Operand + Size .. Emit_Ptr + Size) := Program (Operand .. Emit_Ptr); end if; -- Insert the operator at the position previously occupied by the -- operand. Emit_Ptr := Operand; if not Greedy then Old := Emit_Node (MINMOD); Link_Tail (Old, Old + Next_Pointer_Bytes); end if; Old := Emit_Node (Op); Emit_Ptr := Dest + Size; return Old; end Insert_Operator_Before; --------------------- -- Insert_Operator -- --------------------- procedure Insert_Operator (Op : Opcode; Operand : Pointer; Greedy : Boolean := True) is Discard : Pointer; pragma Warnings (Off, Discard); begin Discard := Insert_Operator_Before (Op, Operand, Greedy, Opsize => Next_Pointer_Bytes); end Insert_Operator; ----------------------- -- Is_Curly_Operator -- ----------------------- function Is_Curly_Operator (IP : Natural) return Boolean is Scan : Natural := IP; begin if Expression (Scan) /= '{' or else Scan + 2 > Expression'Last or else not Is_Digit (Expression (Scan + 1)) then return False; end if; Scan := Scan + 1; -- The first digit loop Scan := Scan + 1; if Scan > Expression'Last then return False; end if; exit when not Is_Digit (Expression (Scan)); end loop; if Expression (Scan) = ',' then loop Scan := Scan + 1; if Scan > Expression'Last then return False; end if; exit when not Is_Digit (Expression (Scan)); end loop; end if; return Expression (Scan) = '}'; end Is_Curly_Operator; ------------- -- Is_Mult -- ------------- function Is_Mult (IP : Natural) return Boolean is C : constant Character := Expression (IP); begin return C = '*' or else C = '+' or else C = '?' or else (C = '{' and then Is_Curly_Operator (IP)); end Is_Mult; ----------------------- -- Link_Operand_Tail -- ----------------------- procedure Link_Operand_Tail (P, Val : Pointer) is begin if P <= PM.Size and then Program (P) = BRANCH then Link_Tail (Operand (P), Val); end if; end Link_Operand_Tail; --------------- -- Link_Tail -- --------------- procedure Link_Tail (P, Val : Pointer) is Scan : Pointer; Temp : Pointer; Offset : Pointer; begin -- Find last node (the size of the pattern matcher might be too -- small, so don't try to read past its end). Scan := P; while Scan + Next_Pointer_Bytes <= PM.Size loop Temp := Get_Next (Program, Scan); exit when Temp = Scan; Scan := Temp; end loop; Offset := Val - Scan; Emit_Natural (Scan + 1, Natural (Offset)); end Link_Tail; ----------- -- Parse -- ----------- -- Combining parenthesis handling with the base level of regular -- expression is a trifle forced, but the need to tie the tails of the -- the branches to what follows makes it hard to avoid. procedure Parse (Parenthesized : Boolean; Capturing : Boolean; Flags : out Expression_Flags; IP : out Pointer) is E : String renames Expression; Br, Br2 : Pointer; Ender : Pointer; Par_No : Natural; New_Flags : Expression_Flags; Have_Branch : Boolean := False; begin Flags := (Has_Width => True, others => False); -- Tentatively -- Make an OPEN node, if parenthesized if Parenthesized and then Capturing then if Matcher.Paren_Count > Max_Paren_Count then Fail ("too many ()"); end if; Par_No := Matcher.Paren_Count + 1; Matcher.Paren_Count := Matcher.Paren_Count + 1; IP := Emit_Node (OPEN); Emit (Character'Val (Par_No)); else IP := 0; Par_No := 0; end if; -- Pick up the branches, linking them together Parse_Branch (New_Flags, True, Br); if Br = 0 then IP := 0; return; end if; if Parse_Pos <= Parse_End and then E (Parse_Pos) = '|' then Insert_Operator (BRANCH, Br); Have_Branch := True; end if; if IP /= 0 then Link_Tail (IP, Br); -- OPEN -> first else IP := Br; end if; if not New_Flags.Has_Width then Flags.Has_Width := False; end if; Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start; while Parse_Pos <= Parse_End and then (E (Parse_Pos) = '|') loop Parse_Pos := Parse_Pos + 1; Parse_Branch (New_Flags, False, Br); if Br = 0 then IP := 0; return; end if; Link_Tail (IP, Br); -- BRANCH -> BRANCH if not New_Flags.Has_Width then Flags.Has_Width := False; end if; Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start; end loop; -- Make a closing node, and hook it on the end if Parenthesized then if Capturing then Ender := Emit_Node (CLOSE); Emit (Character'Val (Par_No)); Link_Tail (IP, Ender); else -- Need to keep looking after the closing parenthesis Ender := Emit_Ptr; end if; else Ender := Emit_Node (EOP); Link_Tail (IP, Ender); end if; if Have_Branch and then Emit_Ptr <= PM.Size + 1 then -- Hook the tails of the branches to the closing node Br := IP; loop Link_Operand_Tail (Br, Ender); Br2 := Get_Next (Program, Br); exit when Br2 = Br; Br := Br2; end loop; end if; -- Check for proper termination if Parenthesized then if Parse_Pos > Parse_End or else E (Parse_Pos) /= ')' then Fail ("unmatched ()"); end if; Parse_Pos := Parse_Pos + 1; elsif Parse_Pos <= Parse_End then if E (Parse_Pos) = ')' then Fail ("unmatched ')'"); else Fail ("junk on end"); -- "Can't happen" end if; end if; end Parse; ---------------- -- Parse_Atom -- ---------------- procedure Parse_Atom (Expr_Flags : out Expression_Flags; IP : out Pointer) is C : Character; begin -- Tentatively set worst expression case Expr_Flags := Worst_Expression; C := Expression (Parse_Pos); Parse_Pos := Parse_Pos + 1; case (C) is when '^' => IP := Emit_Node (if (Flags and Multiple_Lines) /= 0 then MBOL elsif (Flags and Single_Line) /= 0 then SBOL else BOL); when '$' => IP := Emit_Node (if (Flags and Multiple_Lines) /= 0 then MEOL elsif (Flags and Single_Line) /= 0 then SEOL else EOL); when '.' => IP := Emit_Node (if (Flags and Single_Line) /= 0 then SANY else ANY); Expr_Flags.Has_Width := True; Expr_Flags.Simple := True; when '[' => Parse_Character_Class (IP); Expr_Flags.Has_Width := True; Expr_Flags.Simple := True; when '(' => declare New_Flags : Expression_Flags; begin if Parse_Pos <= Parse_End - 1 and then Expression (Parse_Pos) = '?' and then Expression (Parse_Pos + 1) = ':' then Parse_Pos := Parse_Pos + 2; -- Non-capturing parenthesis Parse (True, False, New_Flags, IP); else -- Capturing parenthesis Parse (True, True, New_Flags, IP); Expr_Flags.Has_Width := Expr_Flags.Has_Width or else New_Flags.Has_Width; Expr_Flags.SP_Start := Expr_Flags.SP_Start or else New_Flags.SP_Start; if IP = 0 then return; end if; end if; end; when '|' | ASCII.LF | ')' => Fail ("internal urp"); -- Supposed to be caught earlier when '?' | '+' | '*' => Fail (C & " follows nothing"); when '{' => if Is_Curly_Operator (Parse_Pos - 1) then Fail (C & " follows nothing"); else Parse_Literal (Expr_Flags, IP); end if; when '\' => if Parse_Pos > Parse_End then Fail ("trailing \"); end if; Parse_Pos := Parse_Pos + 1; case Expression (Parse_Pos - 1) is when 'b' => IP := Emit_Node (BOUND); when 'B' => IP := Emit_Node (NBOUND); when 's' => IP := Emit_Node (SPACE); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'S' => IP := Emit_Node (NSPACE); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'd' => IP := Emit_Node (DIGIT); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'D' => IP := Emit_Node (NDIGIT); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'w' => IP := Emit_Node (ALNUM); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'W' => IP := Emit_Node (NALNUM); Expr_Flags.Simple := True; Expr_Flags.Has_Width := True; when 'A' => IP := Emit_Node (SBOL); when 'G' => IP := Emit_Node (SEOL); when '0' .. '9' => IP := Emit_Node (REFF); declare Save : constant Natural := Parse_Pos - 1; begin while Parse_Pos <= Expression'Last and then Is_Digit (Expression (Parse_Pos)) loop Parse_Pos := Parse_Pos + 1; end loop; Emit (Character'Val (Natural'Value (Expression (Save .. Parse_Pos - 1)))); end; when others => Parse_Pos := Parse_Pos - 1; Parse_Literal (Expr_Flags, IP); end case; when others => Parse_Literal (Expr_Flags, IP); end case; end Parse_Atom; ------------------ -- Parse_Branch -- ------------------ procedure Parse_Branch (Flags : out Expression_Flags; First : Boolean; IP : out Pointer) is E : String renames Expression; Chain : Pointer; Last : Pointer; New_Flags : Expression_Flags; Discard : Pointer; pragma Warnings (Off, Discard); begin Flags := Worst_Expression; -- Tentatively IP := (if First then Emit_Ptr else Emit_Node (BRANCH)); Chain := 0; while Parse_Pos <= Parse_End and then E (Parse_Pos) /= ')' and then E (Parse_Pos) /= ASCII.LF and then E (Parse_Pos) /= '|' loop Parse_Piece (New_Flags, Last); if Last = 0 then IP := 0; return; end if; Flags.Has_Width := Flags.Has_Width or else New_Flags.Has_Width; if Chain = 0 then -- First piece Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start; else Link_Tail (Chain, Last); end if; Chain := Last; end loop; -- Case where loop ran zero CURLY if Chain = 0 then Discard := Emit_Node (NOTHING); end if; end Parse_Branch; --------------------------- -- Parse_Character_Class -- --------------------------- procedure Parse_Character_Class (IP : out Pointer) is Bitmap : Character_Class; Invert : Boolean := False; In_Range : Boolean := False; Named_Class : Std_Class := ANYOF_NONE; Value : Character; Last_Value : Character := ASCII.NUL; begin Reset_Class (Bitmap); -- Do we have an invert character class ? if Parse_Pos <= Parse_End and then Expression (Parse_Pos) = '^' then Invert := True; Parse_Pos := Parse_Pos + 1; end if; -- First character can be ] or - without closing the class if Parse_Pos <= Parse_End and then (Expression (Parse_Pos) = ']' or else Expression (Parse_Pos) = '-') then Set_In_Class (Bitmap, Expression (Parse_Pos)); Parse_Pos := Parse_Pos + 1; end if; -- While we don't have the end of the class while Parse_Pos <= Parse_End and then Expression (Parse_Pos) /= ']' loop Named_Class := ANYOF_NONE; Value := Expression (Parse_Pos); Parse_Pos := Parse_Pos + 1; -- Do we have a Posix character class if Value = '[' then Named_Class := Parse_Posix_Character_Class; elsif Value = '\' then if Parse_Pos = Parse_End then Fail ("Trailing \"); end if; Value := Expression (Parse_Pos); Parse_Pos := Parse_Pos + 1; case Value is when 'w' => Named_Class := ANYOF_ALNUM; when 'W' => Named_Class := ANYOF_NALNUM; when 's' => Named_Class := ANYOF_SPACE; when 'S' => Named_Class := ANYOF_NSPACE; when 'd' => Named_Class := ANYOF_DIGIT; when 'D' => Named_Class := ANYOF_NDIGIT; when 'n' => Value := ASCII.LF; when 'r' => Value := ASCII.CR; when 't' => Value := ASCII.HT; when 'f' => Value := ASCII.FF; when 'e' => Value := ASCII.ESC; when 'a' => Value := ASCII.BEL; -- when 'x' => ??? hexadecimal value -- when 'c' => ??? control character -- when '0'..'9' => ??? octal character when others => null; end case; end if; -- Do we have a character class? if Named_Class /= ANYOF_NONE then -- A range like 'a-\d' or 'a-[:digit:] is not a range if In_Range then Set_In_Class (Bitmap, Last_Value); Set_In_Class (Bitmap, '-'); In_Range := False; end if; -- Expand the range case Named_Class is when ANYOF_NONE => null; when ANYOF_ALNUM | ANYOF_ALNUMC => for Value in Class_Byte'Range loop if Is_Alnum (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NALNUM | ANYOF_NALNUMC => for Value in Class_Byte'Range loop if not Is_Alnum (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_SPACE => for Value in Class_Byte'Range loop if Is_White_Space (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NSPACE => for Value in Class_Byte'Range loop if not Is_White_Space (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_DIGIT => for Value in Class_Byte'Range loop if Is_Digit (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NDIGIT => for Value in Class_Byte'Range loop if not Is_Digit (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_ALPHA => for Value in Class_Byte'Range loop if Is_Letter (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NALPHA => for Value in Class_Byte'Range loop if not Is_Letter (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_ASCII => for Value in 0 .. 127 loop Set_In_Class (Bitmap, Character'Val (Value)); end loop; when ANYOF_NASCII => for Value in 128 .. 255 loop Set_In_Class (Bitmap, Character'Val (Value)); end loop; when ANYOF_CNTRL => for Value in Class_Byte'Range loop if Is_Control (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NCNTRL => for Value in Class_Byte'Range loop if not Is_Control (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_GRAPH => for Value in Class_Byte'Range loop if Is_Graphic (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NGRAPH => for Value in Class_Byte'Range loop if not Is_Graphic (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_LOWER => for Value in Class_Byte'Range loop if Is_Lower (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NLOWER => for Value in Class_Byte'Range loop if not Is_Lower (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_PRINT => for Value in Class_Byte'Range loop if Is_Printable (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NPRINT => for Value in Class_Byte'Range loop if not Is_Printable (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_PUNCT => for Value in Class_Byte'Range loop if Is_Printable (Character'Val (Value)) and then not Is_White_Space (Character'Val (Value)) and then not Is_Alnum (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NPUNCT => for Value in Class_Byte'Range loop if not Is_Printable (Character'Val (Value)) or else Is_White_Space (Character'Val (Value)) or else Is_Alnum (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_UPPER => for Value in Class_Byte'Range loop if Is_Upper (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NUPPER => for Value in Class_Byte'Range loop if not Is_Upper (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_XDIGIT => for Value in Class_Byte'Range loop if Is_Hexadecimal_Digit (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; when ANYOF_NXDIGIT => for Value in Class_Byte'Range loop if not Is_Hexadecimal_Digit (Character'Val (Value)) then Set_In_Class (Bitmap, Character'Val (Value)); end if; end loop; end case; -- Not a character range elsif not In_Range then Last_Value := Value; if Parse_Pos > Expression'Last then Fail ("Empty character class []"); end if; if Expression (Parse_Pos) = '-' and then Parse_Pos < Parse_End and then Expression (Parse_Pos + 1) /= ']' then Parse_Pos := Parse_Pos + 1; -- Do we have a range like '\d-a' and '[:space:]-a' -- which is not a real range if Named_Class /= ANYOF_NONE then Set_In_Class (Bitmap, '-'); else In_Range := True; end if; else Set_In_Class (Bitmap, Value); end if; -- Else in a character range else if Last_Value > Value then Fail ("Invalid Range [" & Last_Value'Img & "-" & Value'Img & "]"); end if; while Last_Value <= Value loop Set_In_Class (Bitmap, Last_Value); Last_Value := Character'Succ (Last_Value); end loop; In_Range := False; end if; end loop; -- Optimize case-insensitive ranges (put the upper case or lower -- case character into the bitmap) if (Flags and Case_Insensitive) /= 0 then for C in Character'Range loop if Get_From_Class (Bitmap, C) then Set_In_Class (Bitmap, To_Lower (C)); Set_In_Class (Bitmap, To_Upper (C)); end if; end loop; end if; -- Optimize inverted classes if Invert then for J in Bitmap'Range loop Bitmap (J) := not Bitmap (J); end loop; end if; Parse_Pos := Parse_Pos + 1; -- Emit the class IP := Emit_Node (ANYOF); Emit_Class (Bitmap); end Parse_Character_Class; ------------------- -- Parse_Literal -- ------------------- -- This is a bit tricky due to quoted chars and due to -- the multiplier characters '*', '+', and '?' that -- take the SINGLE char previous as their operand. -- On entry, the character at Parse_Pos - 1 is going to go -- into the string, no matter what it is. It could be -- following a \ if Parse_Atom was entered from the '\' case. -- Basic idea is to pick up a good char in C and examine -- the next char. If Is_Mult (C) then twiddle, if it's a \ -- then frozzle and if it's another magic char then push C and -- terminate the string. If none of the above, push C on the -- string and go around again. -- Start_Pos is used to remember where "the current character" -- starts in the string, if due to an Is_Mult we need to back -- up and put the current char in a separate 1-character string. -- When Start_Pos is 0, C is the only char in the string; -- this is used in Is_Mult handling, and in setting the SIMPLE -- flag at the end. procedure Parse_Literal (Expr_Flags : out Expression_Flags; IP : out Pointer) is Start_Pos : Natural := 0; C : Character; Length_Ptr : Pointer; Has_Special_Operator : Boolean := False; begin Parse_Pos := Parse_Pos - 1; -- Look at current character IP := Emit_Node (if (Flags and Case_Insensitive) /= 0 then EXACTF else EXACT); Length_Ptr := Emit_Ptr; Emit_Ptr := String_Operand (IP); Parse_Loop : loop C := Expression (Parse_Pos); -- Get current character case C is when '.' | '[' | '(' | ')' | '|' | ASCII.LF | '$' | '^' => if Start_Pos = 0 then Start_Pos := Parse_Pos; Emit (C); -- First character is always emitted else exit Parse_Loop; -- Else we are done end if; when '?' | '+' | '*' | '{' => if Start_Pos = 0 then Start_Pos := Parse_Pos; Emit (C); -- First character is always emitted -- Are we looking at an operator, or is this -- simply a normal character ? elsif not Is_Mult (Parse_Pos) then Start_Pos := Parse_Pos; Case_Emit (C); else -- We've got something like "abc?d". Mark this as a -- special case. What we want to emit is a first -- constant string for "ab", then one for "c" that will -- ultimately be transformed with a CURLY operator, A -- special case has to be handled for "a?", since there -- is no initial string to emit. Has_Special_Operator := True; exit Parse_Loop; end if; when '\' => Start_Pos := Parse_Pos; if Parse_Pos = Parse_End then Fail ("Trailing \"); else case Expression (Parse_Pos + 1) is when 'b' | 'B' | 's' | 'S' | 'd' | 'D' | 'w' | 'W' | '0' .. '9' | 'G' | 'A' => exit Parse_Loop; when 'n' => Emit (ASCII.LF); when 't' => Emit (ASCII.HT); when 'r' => Emit (ASCII.CR); when 'f' => Emit (ASCII.FF); when 'e' => Emit (ASCII.ESC); when 'a' => Emit (ASCII.BEL); when others => Emit (Expression (Parse_Pos + 1)); end case; Parse_Pos := Parse_Pos + 1; end if; when others => Start_Pos := Parse_Pos; Case_Emit (C); end case; Parse_Pos := Parse_Pos + 1; exit Parse_Loop when Parse_Pos > Parse_End or else Emit_Ptr - Length_Ptr = 254; end loop Parse_Loop; -- Is the string followed by a '*+?{' operator ? If yes, and if there -- is an initial string to emit, do it now. if Has_Special_Operator and then Emit_Ptr >= Length_Ptr + Next_Pointer_Bytes then Emit_Ptr := Emit_Ptr - 1; Parse_Pos := Start_Pos; end if; if Length_Ptr <= PM.Size then Program (Length_Ptr) := Character'Val (Emit_Ptr - Length_Ptr - 2); end if; Expr_Flags.Has_Width := True; -- Slight optimization when there is a single character if Emit_Ptr = Length_Ptr + 2 then Expr_Flags.Simple := True; end if; end Parse_Literal; ----------------- -- Parse_Piece -- ----------------- -- Note that the branching code sequences used for '?' and the -- general cases of '*' and + are somewhat optimized: they use -- the same NOTHING node as both the endmarker for their branch -- list and the body of the last branch. It might seem that -- this node could be dispensed with entirely, but the endmarker -- role is not redundant. procedure Parse_Piece (Expr_Flags : out Expression_Flags; IP : out Pointer) is Op : Character; New_Flags : Expression_Flags; Greedy : Boolean := True; begin Parse_Atom (New_Flags, IP); if IP = 0 then return; end if; if Parse_Pos > Parse_End or else not Is_Mult (Parse_Pos) then Expr_Flags := New_Flags; return; end if; Op := Expression (Parse_Pos); Expr_Flags := (if Op /= '+' then (SP_Start => True, others => False) else (Has_Width => True, others => False)); -- Detect non greedy operators in the easy cases if Op /= '{' and then Parse_Pos + 1 <= Parse_End and then Expression (Parse_Pos + 1) = '?' then Greedy := False; Parse_Pos := Parse_Pos + 1; end if; -- Generate the byte code case Op is when '*' => if New_Flags.Simple then Insert_Operator (STAR, IP, Greedy); else Link_Tail (IP, Emit_Node (WHILEM)); Insert_Curly_Operator (CURLYX, 0, Max_Curly_Repeat, IP, Greedy); Link_Tail (IP, Emit_Node (NOTHING)); end if; when '+' => if New_Flags.Simple then Insert_Operator (PLUS, IP, Greedy); else Link_Tail (IP, Emit_Node (WHILEM)); Insert_Curly_Operator (CURLYX, 1, Max_Curly_Repeat, IP, Greedy); Link_Tail (IP, Emit_Node (NOTHING)); end if; when '?' => if New_Flags.Simple then Insert_Curly_Operator (CURLY, 0, 1, IP, Greedy); else Link_Tail (IP, Emit_Node (WHILEM)); Insert_Curly_Operator (CURLYX, 0, 1, IP, Greedy); Link_Tail (IP, Emit_Node (NOTHING)); end if; when '{' => declare Min, Max : Natural; begin Get_Curly_Arguments (Parse_Pos, Min, Max, Greedy); if New_Flags.Simple then Insert_Curly_Operator (CURLY, Min, Max, IP, Greedy); else Link_Tail (IP, Emit_Node (WHILEM)); Insert_Curly_Operator (CURLYX, Min, Max, IP, Greedy); Link_Tail (IP, Emit_Node (NOTHING)); end if; end; when others => null; end case; Parse_Pos := Parse_Pos + 1; if Parse_Pos <= Parse_End and then Is_Mult (Parse_Pos) then Fail ("nested *+{"); end if; end Parse_Piece; --------------------------------- -- Parse_Posix_Character_Class -- --------------------------------- function Parse_Posix_Character_Class return Std_Class is Invert : Boolean := False; Class : Std_Class := ANYOF_NONE; E : String renames Expression; -- Class names. Note that code assumes that the length of all -- classes starting with the same letter have the same length. Alnum : constant String := "alnum:]"; Alpha : constant String := "alpha:]"; Ascii_C : constant String := "ascii:]"; Cntrl : constant String := "cntrl:]"; Digit : constant String := "digit:]"; Graph : constant String := "graph:]"; Lower : constant String := "lower:]"; Print : constant String := "print:]"; Punct : constant String := "punct:]"; Space : constant String := "space:]"; Upper : constant String := "upper:]"; Word : constant String := "word:]"; Xdigit : constant String := "xdigit:]"; begin -- Case of character class specified if Parse_Pos <= Parse_End and then Expression (Parse_Pos) = ':' then Parse_Pos := Parse_Pos + 1; -- Do we have something like: [[:^alpha:]] if Parse_Pos <= Parse_End and then Expression (Parse_Pos) = '^' then Invert := True; Parse_Pos := Parse_Pos + 1; end if; -- Check for class names based on first letter case Expression (Parse_Pos) is when 'a' => -- All 'a' classes have the same length (Alnum'Length) if Parse_Pos + Alnum'Length - 1 <= Parse_End then if E (Parse_Pos .. Parse_Pos + Alnum'Length - 1) = Alnum then Class := (if Invert then ANYOF_NALNUMC else ANYOF_ALNUMC); Parse_Pos := Parse_Pos + Alnum'Length; elsif E (Parse_Pos .. Parse_Pos + Alpha'Length - 1) = Alpha then Class := (if Invert then ANYOF_NALPHA else ANYOF_ALPHA); Parse_Pos := Parse_Pos + Alpha'Length; elsif E (Parse_Pos .. Parse_Pos + Ascii_C'Length - 1) = Ascii_C then Class := (if Invert then ANYOF_NASCII else ANYOF_ASCII); Parse_Pos := Parse_Pos + Ascii_C'Length; else Fail ("Invalid character class: " & E); end if; else Fail ("Invalid character class: " & E); end if; when 'c' => if Parse_Pos + Cntrl'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Cntrl'Length - 1) = Cntrl then Class := (if Invert then ANYOF_NCNTRL else ANYOF_CNTRL); Parse_Pos := Parse_Pos + Cntrl'Length; else Fail ("Invalid character class: " & E); end if; when 'd' => if Parse_Pos + Digit'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Digit'Length - 1) = Digit then Class := (if Invert then ANYOF_NDIGIT else ANYOF_DIGIT); Parse_Pos := Parse_Pos + Digit'Length; end if; when 'g' => if Parse_Pos + Graph'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Graph'Length - 1) = Graph then Class := (if Invert then ANYOF_NGRAPH else ANYOF_GRAPH); Parse_Pos := Parse_Pos + Graph'Length; else Fail ("Invalid character class: " & E); end if; when 'l' => if Parse_Pos + Lower'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Lower'Length - 1) = Lower then Class := (if Invert then ANYOF_NLOWER else ANYOF_LOWER); Parse_Pos := Parse_Pos + Lower'Length; else Fail ("Invalid character class: " & E); end if; when 'p' => -- All 'p' classes have the same length if Parse_Pos + Print'Length - 1 <= Parse_End then if E (Parse_Pos .. Parse_Pos + Print'Length - 1) = Print then Class := (if Invert then ANYOF_NPRINT else ANYOF_PRINT); Parse_Pos := Parse_Pos + Print'Length; elsif E (Parse_Pos .. Parse_Pos + Punct'Length - 1) = Punct then Class := (if Invert then ANYOF_NPUNCT else ANYOF_PUNCT); Parse_Pos := Parse_Pos + Punct'Length; else Fail ("Invalid character class: " & E); end if; else Fail ("Invalid character class: " & E); end if; when 's' => if Parse_Pos + Space'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Space'Length - 1) = Space then Class := (if Invert then ANYOF_NSPACE else ANYOF_SPACE); Parse_Pos := Parse_Pos + Space'Length; else Fail ("Invalid character class: " & E); end if; when 'u' => if Parse_Pos + Upper'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Upper'Length - 1) = Upper then Class := (if Invert then ANYOF_NUPPER else ANYOF_UPPER); Parse_Pos := Parse_Pos + Upper'Length; else Fail ("Invalid character class: " & E); end if; when 'w' => if Parse_Pos + Word'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Word'Length - 1) = Word then Class := (if Invert then ANYOF_NALNUM else ANYOF_ALNUM); Parse_Pos := Parse_Pos + Word'Length; else Fail ("Invalid character class: " & E); end if; when 'x' => if Parse_Pos + Xdigit'Length - 1 <= Parse_End and then E (Parse_Pos .. Parse_Pos + Xdigit'Length - 1) = Xdigit then Class := (if Invert then ANYOF_NXDIGIT else ANYOF_XDIGIT); Parse_Pos := Parse_Pos + Xdigit'Length; else Fail ("Invalid character class: " & E); end if; when others => Fail ("Invalid character class: " & E); end case; -- Character class not specified else return ANYOF_NONE; end if; return Class; end Parse_Posix_Character_Class; -- Local Declarations Result : Pointer; Expr_Flags : Expression_Flags; pragma Unreferenced (Expr_Flags); -- Start of processing for Compile begin Parse (False, False, Expr_Flags, Result); if Result = 0 then Fail ("Couldn't compile expression"); end if; Final_Code_Size := Emit_Ptr - 1; -- Do we want to actually compile the expression, or simply get the -- code size ??? if Emit_Ptr <= PM.Size then Optimize (PM); end if; PM.Flags := Flags; end Compile; function Compile (Expression : String; Flags : Regexp_Flags := No_Flags) return Pattern_Matcher is -- Assume the compiled regexp will fit in 1000 chars. If it does not we -- will have to compile a second time once the correct size is known. If -- it fits, we save a significant amount of time by avoiding the second -- compilation. Dummy : Pattern_Matcher (1000); Size : Program_Size; begin Compile (Dummy, Expression, Size, Flags); if Size <= Dummy.Size then return Pattern_Matcher' (Size => Size, First => Dummy.First, Anchored => Dummy.Anchored, Must_Have => Dummy.Must_Have, Must_Have_Length => Dummy.Must_Have_Length, Paren_Count => Dummy.Paren_Count, Flags => Dummy.Flags, Program => Dummy.Program (Dummy.Program'First .. Dummy.Program'First + Size - 1)); else -- We have to recompile now that we know the size -- ??? Can we use Ada 2005's return construct ? declare Result : Pattern_Matcher (Size); begin Compile (Result, Expression, Size, Flags); return Result; end; end if; end Compile; procedure Compile (Matcher : out Pattern_Matcher; Expression : String; Flags : Regexp_Flags := No_Flags) is Size : Program_Size; begin Compile (Matcher, Expression, Size, Flags); if Size > Matcher.Size then raise Expression_Error with "Pattern_Matcher is too small"; end if; end Compile; -------------------- -- Dump_Operation -- -------------------- procedure Dump_Operation (Program : Program_Data; Index : Pointer; Indent : Natural) is Current : Pointer := Index; begin Dump_Until (Program, Current, Current + 1, Indent); end Dump_Operation; ---------------- -- Dump_Until -- ---------------- procedure Dump_Until (Program : Program_Data; Index : in out Pointer; Till : Pointer; Indent : Natural; Do_Print : Boolean := True) is function Image (S : String) return String; -- Remove leading space ----------- -- Image -- ----------- function Image (S : String) return String is begin if S (S'First) = ' ' then return S (S'First + 1 .. S'Last); else return S; end if; end Image; -- Local variables Op : Opcode; Next : Pointer; Length : Pointer; Local_Indent : Natural := Indent; -- Start of processing for Dump_Until begin while Index < Till loop Op := Opcode'Val (Character'Pos ((Program (Index)))); Next := Get_Next (Program, Index); if Do_Print then declare Point : constant String := Pointer'Image (Index); begin Put ((1 .. 4 - Point'Length => ' ') & Point & ":" & (1 .. Local_Indent * 2 => ' ') & Opcode'Image (Op)); end; -- Print the parenthesis number if Op = OPEN or else Op = CLOSE or else Op = REFF then Put (Image (Natural'Image (Character'Pos (Program (Index + Next_Pointer_Bytes))))); end if; if Next = Index then Put (" (-)"); else Put (" (" & Image (Pointer'Image (Next)) & ")"); end if; end if; case Op is when ANYOF => declare Bitmap : Character_Class; Last : Character := ASCII.NUL; Current : Natural := 0; Current_Char : Character; begin Bitmap_Operand (Program, Index, Bitmap); if Do_Print then Put ("["); while Current <= 255 loop Current_Char := Character'Val (Current); -- First item in a range if Get_From_Class (Bitmap, Current_Char) then Last := Current_Char; -- Search for the last item in the range loop Current := Current + 1; exit when Current > 255; Current_Char := Character'Val (Current); exit when not Get_From_Class (Bitmap, Current_Char); end loop; if not Is_Graphic (Last) then Put (Last'Img); else Put (Last); end if; if Character'Succ (Last) /= Current_Char then Put ("\-" & Character'Pred (Current_Char)); end if; else Current := Current + 1; end if; end loop; Put_Line ("]"); end if; Index := Index + Next_Pointer_Bytes + Bitmap'Length; end; when EXACT | EXACTF => Length := String_Length (Program, Index); if Do_Print then Put (" (" & Image (Program_Size'Image (Length + 1)) & " chars) <" & String (Program (String_Operand (Index) .. String_Operand (Index) + Length))); Put_Line (">"); end if; Index := String_Operand (Index) + Length + 1; -- Node operand when BRANCH | STAR | PLUS => if Do_Print then New_Line; end if; Index := Index + Next_Pointer_Bytes; Dump_Until (Program, Index, Pointer'Min (Next, Till), Local_Indent + 1, Do_Print); when CURLY | CURLYX => if Do_Print then Put_Line (" {" & Image (Natural'Image (Read_Natural (Program, Index + Next_Pointer_Bytes))) & "," & Image (Natural'Image (Read_Natural (Program, Index + 5))) & "}"); end if; Index := Index + 7; Dump_Until (Program, Index, Pointer'Min (Next, Till), Local_Indent + 1, Do_Print); when OPEN => if Do_Print then New_Line; end if; Index := Index + 4; Local_Indent := Local_Indent + 1; when CLOSE | REFF => if Do_Print then New_Line; end if; Index := Index + 4; if Op = CLOSE then Local_Indent := Local_Indent - 1; end if; when others => Index := Index + Next_Pointer_Bytes; if Do_Print then New_Line; end if; exit when Op = EOP; end case; end loop; end Dump_Until; ---------- -- Dump -- ---------- procedure Dump (Self : Pattern_Matcher) is Program : Program_Data renames Self.Program; Index : Pointer := Program'First; -- Start of processing for Dump begin Put_Line ("Must start with (Self.First) = " & Character'Image (Self.First)); if (Self.Flags and Case_Insensitive) /= 0 then Put_Line (" Case_Insensitive mode"); end if; if (Self.Flags and Single_Line) /= 0 then Put_Line (" Single_Line mode"); end if; if (Self.Flags and Multiple_Lines) /= 0 then Put_Line (" Multiple_Lines mode"); end if; Dump_Until (Program, Index, Self.Program'Last + 1, 0); end Dump; -------------------- -- Get_From_Class -- -------------------- function Get_From_Class (Bitmap : Character_Class; C : Character) return Boolean is Value : constant Class_Byte := Character'Pos (C); begin return (Bitmap (Value / 8) and Bit_Conversion (Value mod 8)) /= 0; end Get_From_Class; -------------- -- Get_Next -- -------------- function Get_Next (Program : Program_Data; IP : Pointer) return Pointer is begin return IP + Pointer (Read_Natural (Program, IP + 1)); end Get_Next; -------------- -- Is_Alnum -- -------------- function Is_Alnum (C : Character) return Boolean is begin return Is_Alphanumeric (C) or else C = '_'; end Is_Alnum; ------------------ -- Is_Printable -- ------------------ function Is_Printable (C : Character) return Boolean is begin -- Printable if space or graphic character or other whitespace -- Other white space includes (HT/LF/VT/FF/CR = codes 9-13) return C in Character'Val (32) .. Character'Val (126) or else C in ASCII.HT .. ASCII.CR; end Is_Printable; -------------------- -- Is_White_Space -- -------------------- function Is_White_Space (C : Character) return Boolean is begin -- Note: HT = 9, LF = 10, VT = 11, FF = 12, CR = 13 return C = ' ' or else C in ASCII.HT .. ASCII.CR; end Is_White_Space; ----------- -- Match -- ----------- procedure Match (Self : Pattern_Matcher; Data : String; Matches : out Match_Array; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) is Program : Program_Data renames Self.Program; -- Shorter notation First_In_Data : constant Integer := Integer'Max (Data_First, Data'First); Last_In_Data : constant Integer := Integer'Min (Data_Last, Data'Last); -- Global work variables Input_Pos : Natural; -- String-input pointer BOL_Pos : Natural; -- Beginning of input, for ^ check Matched : Boolean := False; -- Until proven True Matches_Full : Match_Array (0 .. Natural'Max (Self.Paren_Count, Matches'Last)); -- Stores the value of all the parenthesis pairs. -- We do not use directly Matches, so that we can also use back -- references (REFF) even if Matches is too small. type Natural_Array is array (Match_Count range <>) of Natural; Matches_Tmp : Natural_Array (Matches_Full'Range); -- Save the opening position of parenthesis Last_Paren : Natural := 0; -- Last parenthesis seen Greedy : Boolean := True; -- True if the next operator should be greedy type Current_Curly_Record; type Current_Curly_Access is access all Current_Curly_Record; type Current_Curly_Record is record Paren_Floor : Natural; -- How far back to strip parenthesis data Cur : Integer; -- How many instances of scan we've matched Min : Natural; -- Minimal number of scans to match Max : Natural; -- Maximal number of scans to match Greedy : Boolean; -- Whether to work our way up or down Scan : Pointer; -- The thing to match Next : Pointer; -- What has to match after it Lastloc : Natural; -- Where we started matching this scan Old_Cc : Current_Curly_Access; -- Before we started this one end record; -- Data used to handle the curly operator and the plus and star -- operators for complex expressions. Current_Curly : Current_Curly_Access := null; -- The curly currently being processed ----------------------- -- Local Subprograms -- ----------------------- function Index (Start : Positive; C : Character) return Natural; -- Find character C in Data starting at Start and return position function Repeat (IP : Pointer; Max : Natural := Natural'Last) return Natural; -- Repeatedly match something simple, report how many -- It only matches on things of length 1. -- Starting from Input_Pos, it matches at most Max CURLY. function Try (Pos : Positive) return Boolean; -- Try to match at specific point function Match (IP : Pointer) return Boolean; -- This is the main matching routine. Conceptually the strategy -- is simple: check to see whether the current node matches, -- call self recursively to see whether the rest matches, -- and then act accordingly. -- -- In practice Match makes some effort to avoid recursion, in -- particular by going through "ordinary" nodes (that don't -- need to know whether the rest of the match failed) by -- using a loop instead of recursion. -- Why is the above comment part of the spec rather than body ??? function Match_Whilem return Boolean; -- Return True if a WHILEM matches the Current_Curly function Recurse_Match (IP : Pointer; From : Natural) return Boolean; pragma Inline (Recurse_Match); -- Calls Match recursively. It saves and restores the parenthesis -- status and location in the input stream correctly, so that -- backtracking is possible function Match_Simple_Operator (Op : Opcode; Scan : Pointer; Next : Pointer; Greedy : Boolean) return Boolean; -- Return True it the simple operator (possibly non-greedy) matches Dump_Indent : Integer := -1; procedure Dump_Current (Scan : Pointer; Prefix : Boolean := True); procedure Dump_Error (Msg : String); -- Debug: print the current context pragma Inline (Index); pragma Inline (Repeat); -- These are two complex functions, but used only once pragma Inline (Match_Whilem); pragma Inline (Match_Simple_Operator); ----------- -- Index -- ----------- function Index (Start : Positive; C : Character) return Natural is begin for J in Start .. Last_In_Data loop if Data (J) = C then return J; end if; end loop; return 0; end Index; ------------------- -- Recurse_Match -- ------------------- function Recurse_Match (IP : Pointer; From : Natural) return Boolean is L : constant Natural := Last_Paren; Tmp_F : constant Match_Array := Matches_Full (From + 1 .. Matches_Full'Last); Start : constant Natural_Array := Matches_Tmp (From + 1 .. Matches_Tmp'Last); Input : constant Natural := Input_Pos; Dump_Indent_Save : constant Integer := Dump_Indent; begin if Match (IP) then return True; end if; Last_Paren := L; Matches_Full (Tmp_F'Range) := Tmp_F; Matches_Tmp (Start'Range) := Start; Input_Pos := Input; Dump_Indent := Dump_Indent_Save; return False; end Recurse_Match; ------------------ -- Dump_Current -- ------------------ procedure Dump_Current (Scan : Pointer; Prefix : Boolean := True) is Length : constant := 10; Pos : constant String := Integer'Image (Input_Pos); begin if Prefix then Put ((1 .. 5 - Pos'Length => ' ')); Put (Pos & " <" & Data (Input_Pos .. Integer'Min (Last_In_Data, Input_Pos + Length - 1))); Put ((1 .. Length - 1 - Last_In_Data + Input_Pos => ' ')); Put ("> |"); else Put (" "); end if; Dump_Operation (Program, Scan, Indent => Dump_Indent); end Dump_Current; ---------------- -- Dump_Error -- ---------------- procedure Dump_Error (Msg : String) is begin Put (" | "); Put ((1 .. Dump_Indent * 2 => ' ')); Put_Line (Msg); end Dump_Error; ----------- -- Match -- ----------- function Match (IP : Pointer) return Boolean is Scan : Pointer := IP; Next : Pointer; Op : Opcode; Result : Boolean; begin Dump_Indent := Dump_Indent + 1; State_Machine : loop pragma Assert (Scan /= 0); -- Determine current opcode and count its usage in debug mode Op := Opcode'Val (Character'Pos (Program (Scan))); -- Calculate offset of next instruction. Second character is most -- significant in Program_Data. Next := Get_Next (Program, Scan); if Debug then Dump_Current (Scan); end if; case Op is when EOP => Dump_Indent := Dump_Indent - 1; return True; -- Success when BRANCH => if Program (Next) /= BRANCH then Next := Operand (Scan); -- No choice, avoid recursion else loop if Recurse_Match (Operand (Scan), 0) then Dump_Indent := Dump_Indent - 1; return True; end if; Scan := Get_Next (Program, Scan); exit when Scan = 0 or else Program (Scan) /= BRANCH; end loop; exit State_Machine; end if; when NOTHING => null; when BOL => exit State_Machine when Input_Pos /= BOL_Pos and then ((Self.Flags and Multiple_Lines) = 0 or else Data (Input_Pos - 1) /= ASCII.LF); when MBOL => exit State_Machine when Input_Pos /= BOL_Pos and then Data (Input_Pos - 1) /= ASCII.LF; when SBOL => exit State_Machine when Input_Pos /= BOL_Pos; when EOL => -- A combination of MEOL and SEOL if (Self.Flags and Multiple_Lines) = 0 then -- Single line mode exit State_Machine when Input_Pos <= Data'Last; elsif Input_Pos <= Last_In_Data then exit State_Machine when Data (Input_Pos) /= ASCII.LF; else exit State_Machine when Last_In_Data /= Data'Last; end if; when MEOL => if Input_Pos <= Last_In_Data then exit State_Machine when Data (Input_Pos) /= ASCII.LF; else exit State_Machine when Last_In_Data /= Data'Last; end if; when SEOL => -- If there is a character before Data'Last (even if -- Last_In_Data stops before then), we can't have the -- end of the line. exit State_Machine when Input_Pos <= Data'Last; when BOUND | NBOUND => -- Was last char in word ? declare N : Boolean := False; Ln : Boolean := False; begin if Input_Pos /= First_In_Data then N := Is_Alnum (Data (Input_Pos - 1)); end if; Ln := (if Input_Pos > Last_In_Data then False else Is_Alnum (Data (Input_Pos))); if Op = BOUND then if N = Ln then exit State_Machine; end if; else if N /= Ln then exit State_Machine; end if; end if; end; when SPACE => exit State_Machine when Input_Pos > Last_In_Data or else not Is_White_Space (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when NSPACE => exit State_Machine when Input_Pos > Last_In_Data or else Is_White_Space (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when DIGIT => exit State_Machine when Input_Pos > Last_In_Data or else not Is_Digit (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when NDIGIT => exit State_Machine when Input_Pos > Last_In_Data or else Is_Digit (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when ALNUM => exit State_Machine when Input_Pos > Last_In_Data or else not Is_Alnum (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when NALNUM => exit State_Machine when Input_Pos > Last_In_Data or else Is_Alnum (Data (Input_Pos)); Input_Pos := Input_Pos + 1; when ANY => exit State_Machine when Input_Pos > Last_In_Data or else Data (Input_Pos) = ASCII.LF; Input_Pos := Input_Pos + 1; when SANY => exit State_Machine when Input_Pos > Last_In_Data; Input_Pos := Input_Pos + 1; when EXACT => declare Opnd : Pointer := String_Operand (Scan); Current : Positive := Input_Pos; Last : constant Pointer := Opnd + String_Length (Program, Scan); begin while Opnd <= Last loop exit State_Machine when Current > Last_In_Data or else Program (Opnd) /= Data (Current); Current := Current + 1; Opnd := Opnd + 1; end loop; Input_Pos := Current; end; when EXACTF => declare Opnd : Pointer := String_Operand (Scan); Current : Positive := Input_Pos; Last : constant Pointer := Opnd + String_Length (Program, Scan); begin while Opnd <= Last loop exit State_Machine when Current > Last_In_Data or else Program (Opnd) /= To_Lower (Data (Current)); Current := Current + 1; Opnd := Opnd + 1; end loop; Input_Pos := Current; end; when ANYOF => declare Bitmap : Character_Class; begin Bitmap_Operand (Program, Scan, Bitmap); exit State_Machine when Input_Pos > Last_In_Data or else not Get_From_Class (Bitmap, Data (Input_Pos)); Input_Pos := Input_Pos + 1; end; when OPEN => declare No : constant Natural := Character'Pos (Program (Operand (Scan))); begin Matches_Tmp (No) := Input_Pos; end; when CLOSE => declare No : constant Natural := Character'Pos (Program (Operand (Scan))); begin Matches_Full (No) := (Matches_Tmp (No), Input_Pos - 1); if Last_Paren < No then Last_Paren := No; end if; end; when REFF => declare No : constant Natural := Character'Pos (Program (Operand (Scan))); Data_Pos : Natural; begin -- If we haven't seen that parenthesis yet if Last_Paren < No then Dump_Indent := Dump_Indent - 1; if Debug then Dump_Error ("REFF: No match, backtracking"); end if; return False; end if; Data_Pos := Matches_Full (No).First; while Data_Pos <= Matches_Full (No).Last loop if Input_Pos > Last_In_Data or else Data (Input_Pos) /= Data (Data_Pos) then Dump_Indent := Dump_Indent - 1; if Debug then Dump_Error ("REFF: No match, backtracking"); end if; return False; end if; Input_Pos := Input_Pos + 1; Data_Pos := Data_Pos + 1; end loop; end; when MINMOD => Greedy := False; when STAR | PLUS | CURLY => declare Greed : constant Boolean := Greedy; begin Greedy := True; Result := Match_Simple_Operator (Op, Scan, Next, Greed); Dump_Indent := Dump_Indent - 1; return Result; end; when CURLYX => -- Looking at something like: -- 1: CURLYX {n,m} (->4) -- 2: code for complex thing (->3) -- 3: WHILEM (->0) -- 4: NOTHING declare Min : constant Natural := Read_Natural (Program, Scan + Next_Pointer_Bytes); Max : constant Natural := Read_Natural (Program, Scan + Next_Pointer_Bytes + 2); Cc : aliased Current_Curly_Record; Has_Match : Boolean; begin Cc := (Paren_Floor => Last_Paren, Cur => -1, Min => Min, Max => Max, Greedy => Greedy, Scan => Scan + 7, Next => Next, Lastloc => 0, Old_Cc => Current_Curly); Greedy := True; Current_Curly := Cc'Unchecked_Access; Has_Match := Match (Next - Next_Pointer_Bytes); -- Start on the WHILEM Current_Curly := Cc.Old_Cc; Dump_Indent := Dump_Indent - 1; if not Has_Match then if Debug then Dump_Error ("CURLYX failed..."); end if; end if; return Has_Match; end; when WHILEM => Result := Match_Whilem; Dump_Indent := Dump_Indent - 1; if Debug and then not Result then Dump_Error ("WHILEM: no match, backtracking"); end if; return Result; end case; Scan := Next; end loop State_Machine; if Debug then Dump_Error ("failed..."); Dump_Indent := Dump_Indent - 1; end if; -- If we get here, there is no match. For successful matches when EOP -- is the terminating point. return False; end Match; --------------------------- -- Match_Simple_Operator -- --------------------------- function Match_Simple_Operator (Op : Opcode; Scan : Pointer; Next : Pointer; Greedy : Boolean) return Boolean is Next_Char : Character := ASCII.NUL; Next_Char_Known : Boolean := False; No : Integer; -- Can be negative Min : Natural; Max : Natural := Natural'Last; Operand_Code : Pointer; Old : Natural; Last_Pos : Natural; Save : constant Natural := Input_Pos; begin -- Lookahead to avoid useless match attempts when we know what -- character comes next. if Program (Next) = EXACT then Next_Char := Program (String_Operand (Next)); Next_Char_Known := True; end if; -- Find the minimal and maximal values for the operator case Op is when STAR => Min := 0; Operand_Code := Operand (Scan); when PLUS => Min := 1; Operand_Code := Operand (Scan); when others => Min := Read_Natural (Program, Scan + Next_Pointer_Bytes); Max := Read_Natural (Program, Scan + Next_Pointer_Bytes + 2); Operand_Code := Scan + 7; end case; if Debug then Dump_Current (Operand_Code, Prefix => False); end if; -- Non greedy operators if not Greedy then -- Test we can repeat at least Min times if Min /= 0 then No := Repeat (Operand_Code, Min); if No < Min then if Debug then Dump_Error ("failed... matched" & No'Img & " times"); end if; return False; end if; end if; Old := Input_Pos; -- Find the place where 'next' could work if Next_Char_Known then -- Last position to check if Max = Natural'Last then Last_Pos := Last_In_Data; else Last_Pos := Input_Pos + Max; if Last_Pos > Last_In_Data then Last_Pos := Last_In_Data; end if; end if; -- Look for the first possible opportunity if Debug then Dump_Error ("Next_Char must be " & Next_Char); end if; loop -- Find the next possible position while Input_Pos <= Last_Pos and then Data (Input_Pos) /= Next_Char loop Input_Pos := Input_Pos + 1; end loop; if Input_Pos > Last_Pos then return False; end if; -- Check that we still match if we stop at the position we -- just found. declare Num : constant Natural := Input_Pos - Old; begin Input_Pos := Old; if Debug then Dump_Error ("Would we still match at that position?"); end if; if Repeat (Operand_Code, Num) < Num then return False; end if; end; -- Input_Pos now points to the new position if Match (Get_Next (Program, Scan)) then return True; end if; Old := Input_Pos; Input_Pos := Input_Pos + 1; end loop; -- We do not know what the next character is else while Max >= Min loop if Debug then Dump_Error ("Non-greedy repeat, N=" & Min'Img); Dump_Error ("Do we still match Next if we stop here?"); end if; -- If the next character matches if Recurse_Match (Next, 1) then return True; end if; Input_Pos := Save + Min; -- Could not or did not match -- move forward if Repeat (Operand_Code, 1) /= 0 then Min := Min + 1; else if Debug then Dump_Error ("Non-greedy repeat failed..."); end if; return False; end if; end loop; end if; return False; -- Greedy operators else No := Repeat (Operand_Code, Max); if Debug and then No < Min then Dump_Error ("failed... matched" & No'Img & " times"); end if; -- ??? Perl has some special code here in case the next -- instruction is of type EOL, since $ and \Z can match before -- *and* after newline at the end. -- ??? Perl has some special code here in case (paren) is True -- Else, if we don't have any parenthesis while No >= Min loop if not Next_Char_Known or else (Input_Pos <= Last_In_Data and then Data (Input_Pos) = Next_Char) then if Match (Next) then return True; end if; end if; -- Could not or did not work, we back up No := No - 1; Input_Pos := Save + No; end loop; return False; end if; end Match_Simple_Operator; ------------------ -- Match_Whilem -- ------------------ -- This is really hard to understand, because after we match what we -- are trying to match, we must make sure the rest of the REx is going -- to match for sure, and to do that we have to go back UP the parse -- tree by recursing ever deeper. And if it fails, we have to reset -- our parent's current state that we can try again after backing off. function Match_Whilem return Boolean is Cc : constant Current_Curly_Access := Current_Curly; N : constant Natural := Cc.Cur + 1; Ln : Natural := 0; Lastloc : constant Natural := Cc.Lastloc; -- Detection of 0-len begin -- If degenerate scan matches "", assume scan done if Input_Pos = Cc.Lastloc and then N >= Cc.Min then -- Temporarily restore the old context, and check that we -- match was comes after CURLYX. Current_Curly := Cc.Old_Cc; if Current_Curly /= null then Ln := Current_Curly.Cur; end if; if Match (Cc.Next) then return True; end if; if Current_Curly /= null then Current_Curly.Cur := Ln; end if; Current_Curly := Cc; return False; end if; -- First, just match a string of min scans if N < Cc.Min then Cc.Cur := N; Cc.Lastloc := Input_Pos; if Debug then Dump_Error ("Tests that we match at least" & Cc.Min'Img & " N=" & N'Img); end if; if Match (Cc.Scan) then return True; end if; Cc.Cur := N - 1; Cc.Lastloc := Lastloc; if Debug then Dump_Error ("failed..."); end if; return False; end if; -- Prefer next over scan for minimal matching if not Cc.Greedy then Current_Curly := Cc.Old_Cc; if Current_Curly /= null then Ln := Current_Curly.Cur; end if; if Recurse_Match (Cc.Next, Cc.Paren_Floor) then return True; end if; if Current_Curly /= null then Current_Curly.Cur := Ln; end if; Current_Curly := Cc; -- Maximum greed exceeded ? if N >= Cc.Max then if Debug then Dump_Error ("failed..."); end if; return False; end if; -- Try scanning more and see if it helps Cc.Cur := N; Cc.Lastloc := Input_Pos; if Debug then Dump_Error ("Next failed, what about Current?"); end if; if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then return True; end if; Cc.Cur := N - 1; Cc.Lastloc := Lastloc; return False; end if; -- Prefer scan over next for maximal matching if N < Cc.Max then -- more greed allowed ? Cc.Cur := N; Cc.Lastloc := Input_Pos; if Debug then Dump_Error ("Recurse at current position"); end if; if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then return True; end if; end if; -- Failed deeper matches of scan, so see if this one works Current_Curly := Cc.Old_Cc; if Current_Curly /= null then Ln := Current_Curly.Cur; end if; if Debug then Dump_Error ("Failed matching for later positions"); end if; if Match (Cc.Next) then return True; end if; if Current_Curly /= null then Current_Curly.Cur := Ln; end if; Current_Curly := Cc; Cc.Cur := N - 1; Cc.Lastloc := Lastloc; if Debug then Dump_Error ("failed..."); end if; return False; end Match_Whilem; ------------ -- Repeat -- ------------ function Repeat (IP : Pointer; Max : Natural := Natural'Last) return Natural is Scan : Natural := Input_Pos; Last : Natural; Op : constant Opcode := Opcode'Val (Character'Pos (Program (IP))); Count : Natural; C : Character; Is_First : Boolean := True; Bitmap : Character_Class; begin if Max = Natural'Last or else Scan + Max - 1 > Last_In_Data then Last := Last_In_Data; else Last := Scan + Max - 1; end if; case Op is when ANY => while Scan <= Last and then Data (Scan) /= ASCII.LF loop Scan := Scan + 1; end loop; when SANY => Scan := Last + 1; when EXACT => -- The string has only one character if Repeat was called C := Program (String_Operand (IP)); while Scan <= Last and then C = Data (Scan) loop Scan := Scan + 1; end loop; when EXACTF => -- The string has only one character if Repeat was called C := Program (String_Operand (IP)); while Scan <= Last and then To_Lower (C) = Data (Scan) loop Scan := Scan + 1; end loop; when ANYOF => if Is_First then Bitmap_Operand (Program, IP, Bitmap); Is_First := False; end if; while Scan <= Last and then Get_From_Class (Bitmap, Data (Scan)) loop Scan := Scan + 1; end loop; when ALNUM => while Scan <= Last and then Is_Alnum (Data (Scan)) loop Scan := Scan + 1; end loop; when NALNUM => while Scan <= Last and then not Is_Alnum (Data (Scan)) loop Scan := Scan + 1; end loop; when SPACE => while Scan <= Last and then Is_White_Space (Data (Scan)) loop Scan := Scan + 1; end loop; when NSPACE => while Scan <= Last and then not Is_White_Space (Data (Scan)) loop Scan := Scan + 1; end loop; when DIGIT => while Scan <= Last and then Is_Digit (Data (Scan)) loop Scan := Scan + 1; end loop; when NDIGIT => while Scan <= Last and then not Is_Digit (Data (Scan)) loop Scan := Scan + 1; end loop; when others => raise Program_Error; end case; Count := Scan - Input_Pos; Input_Pos := Scan; return Count; end Repeat; --------- -- Try -- --------- function Try (Pos : Positive) return Boolean is begin Input_Pos := Pos; Last_Paren := 0; Matches_Full := (others => No_Match); if Match (Program_First) then Matches_Full (0) := (Pos, Input_Pos - 1); return True; end if; return False; end Try; -- Start of processing for Match begin -- Do we have the regexp Never_Match? if Self.Size = 0 then Matches := (others => No_Match); return; end if; -- If there is a "must appear" string, look for it if Self.Must_Have_Length > 0 then declare First : constant Character := Program (Self.Must_Have); Must_First : constant Pointer := Self.Must_Have; Must_Last : constant Pointer := Must_First + Pointer (Self.Must_Have_Length - 1); Next_Try : Natural := Index (First_In_Data, First); begin while Next_Try /= 0 and then Data (Next_Try .. Next_Try + Self.Must_Have_Length - 1) = String (Program (Must_First .. Must_Last)) loop Next_Try := Index (Next_Try + 1, First); end loop; if Next_Try = 0 then Matches := (others => No_Match); return; -- Not present end if; end; end if; -- Mark beginning of line for ^ BOL_Pos := Data'First; -- Simplest case first: an anchored match need be tried only once if Self.Anchored and then (Self.Flags and Multiple_Lines) = 0 then Matched := Try (First_In_Data); elsif Self.Anchored then declare Next_Try : Natural := First_In_Data; begin -- Test the first position in the buffer Matched := Try (Next_Try); -- Else only test after newlines if not Matched then while Next_Try <= Last_In_Data loop while Next_Try <= Last_In_Data and then Data (Next_Try) /= ASCII.LF loop Next_Try := Next_Try + 1; end loop; Next_Try := Next_Try + 1; if Next_Try <= Last_In_Data then Matched := Try (Next_Try); exit when Matched; end if; end loop; end if; end; elsif Self.First /= ASCII.NUL then -- We know what char it must start with declare Next_Try : Natural := Index (First_In_Data, Self.First); begin while Next_Try /= 0 loop Matched := Try (Next_Try); exit when Matched; Next_Try := Index (Next_Try + 1, Self.First); end loop; end; else -- Messy cases: try all locations (including for the empty string) Matched := Try (First_In_Data); if not Matched then for S in First_In_Data + 1 .. Last_In_Data loop Matched := Try (S); exit when Matched; end loop; end if; end if; -- Matched has its value for J in Last_Paren + 1 .. Matches'Last loop Matches_Full (J) := No_Match; end loop; Matches := Matches_Full (Matches'Range); end Match; ----------- -- Match -- ----------- function Match (Self : Pattern_Matcher; Data : String; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Natural is Matches : Match_Array (0 .. 0); begin Match (Self, Data, Matches, Data_First, Data_Last); if Matches (0) = No_Match then return Data'First - 1; else return Matches (0).First; end if; end Match; function Match (Self : Pattern_Matcher; Data : String; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Boolean is Matches : Match_Array (0 .. 0); begin Match (Self, Data, Matches, Data_First, Data_Last); return Matches (0).First >= Data'First; end Match; procedure Match (Expression : String; Data : String; Matches : out Match_Array; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) is PM : Pattern_Matcher (Size); Finalize_Size : Program_Size; pragma Unreferenced (Finalize_Size); begin if Size = 0 then Match (Compile (Expression), Data, Matches, Data_First, Data_Last); else Compile (PM, Expression, Finalize_Size); Match (PM, Data, Matches, Data_First, Data_Last); end if; end Match; ----------- -- Match -- ----------- function Match (Expression : String; Data : String; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Natural is PM : Pattern_Matcher (Size); Final_Size : Program_Size; pragma Unreferenced (Final_Size); begin if Size = 0 then return Match (Compile (Expression), Data, Data_First, Data_Last); else Compile (PM, Expression, Final_Size); return Match (PM, Data, Data_First, Data_Last); end if; end Match; ----------- -- Match -- ----------- function Match (Expression : String; Data : String; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Boolean is Matches : Match_Array (0 .. 0); PM : Pattern_Matcher (Size); Final_Size : Program_Size; pragma Unreferenced (Final_Size); begin if Size = 0 then Match (Compile (Expression), Data, Matches, Data_First, Data_Last); else Compile (PM, Expression, Final_Size); Match (PM, Data, Matches, Data_First, Data_Last); end if; return Matches (0).First >= Data'First; end Match; ------------- -- Operand -- ------------- function Operand (P : Pointer) return Pointer is begin return P + Next_Pointer_Bytes; end Operand; -------------- -- Optimize -- -------------- procedure Optimize (Self : in out Pattern_Matcher) is Scan : Pointer; Program : Program_Data renames Self.Program; begin -- Start with safe defaults (no optimization): -- * No known first character of match -- * Does not necessarily start at beginning of line -- * No string known that has to appear in data Self.First := ASCII.NUL; Self.Anchored := False; Self.Must_Have := Program'Last + 1; Self.Must_Have_Length := 0; Scan := Program_First; -- First instruction (can be anything) if Program (Scan) = EXACT then Self.First := Program (String_Operand (Scan)); elsif Program (Scan) = BOL or else Program (Scan) = SBOL or else Program (Scan) = MBOL then Self.Anchored := True; end if; end Optimize; ----------------- -- Paren_Count -- ----------------- function Paren_Count (Regexp : Pattern_Matcher) return Match_Count is begin return Regexp.Paren_Count; end Paren_Count; ----------- -- Quote -- ----------- function Quote (Str : String) return String is S : String (1 .. Str'Length * 2); Last : Natural := 0; begin for J in Str'Range loop case Str (J) is when '^' | '$' | '|' | '*' | '+' | '?' | '{' | '}' | '[' | ']' | '(' | ')' | '\' | '.' => S (Last + 1) := '\'; S (Last + 2) := Str (J); Last := Last + 2; when others => S (Last + 1) := Str (J); Last := Last + 1; end case; end loop; return S (1 .. Last); end Quote; ------------------ -- Read_Natural -- ------------------ function Read_Natural (Program : Program_Data; IP : Pointer) return Natural is begin return Character'Pos (Program (IP)) + 256 * Character'Pos (Program (IP + 1)); end Read_Natural; ----------------- -- Reset_Class -- ----------------- procedure Reset_Class (Bitmap : out Character_Class) is begin Bitmap := (others => 0); end Reset_Class; ------------------ -- Set_In_Class -- ------------------ procedure Set_In_Class (Bitmap : in out Character_Class; C : Character) is Value : constant Class_Byte := Character'Pos (C); begin Bitmap (Value / 8) := Bitmap (Value / 8) or Bit_Conversion (Value mod 8); end Set_In_Class; ------------------- -- String_Length -- ------------------- function String_Length (Program : Program_Data; P : Pointer) return Program_Size is begin pragma Assert (Program (P) = EXACT or else Program (P) = EXACTF); return Character'Pos (Program (P + Next_Pointer_Bytes)); end String_Length; -------------------- -- String_Operand -- -------------------- function String_Operand (P : Pointer) return Pointer is begin return P + 4; end String_Operand; end System.Regpat;
-- @file get_rdate.adb -- @date 7 July 2019 -- @author Chester Gillon -- @brief Example program using GNAT.sockets to get the date from a RFC 868 TCP protocol server -- @details The output as seconds since the Linux epoch can be verified by running: -- $ date -d @`./get_rdate sandy-ubuntu` -- Sun 7 Jul 19:42:14 BST 2019 with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Command_Line; with Ada.Strings.Fixed; with Interfaces; use Interfaces; with GNAT.Sockets; procedure Get_RDate is Rdate_Client : GNAT.Sockets.Socket_Type; Address : GNAT.Sockets.Sock_Addr_Type; Channel : GNAT.Sockets.Stream_Access; Rdate_Port : GNAT.Sockets.Port_Type := 37; -- Define am array to receive the rdate time as a big-endian 32-bit number of seconds -- since the epoch of 00:00 (midnight) 1 January 1900 GMT type Rdate_Time_Packet is Array (0..3) of Interfaces.Unsigned_8; Raw_Time : Rdate_Time_Packet; Host_Rdate_Time : Interfaces.Unsigned_32; -- From RFC 868 Rdate_To_Linux_Epoch_Seconds : constant := 2208988800; Time_Since_Linux_Epoch : Interfaces.Unsigned_32; begin if Ada.Command_Line.Argument_Count /= 1 then Ada.Text_IO.Put_Line ("Usage: " & Ada.Command_Line.Command_Name & "get_rdate <rdate_server>"); return; end if; declare Rdate_Server : constant String := Ada.Command_Line.Argument (1); begin -- Connect to the specified rdate server and retrieve a packet with the time GNAT.Sockets.Initialize; GNAT.Sockets.Create_Socket (Rdate_Client); Address.Addr := GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (Rdate_Server)); Address.Port := Rdate_Port; GNAT.Sockets.Connect_Socket (Rdate_Client, Address); Channel := GNAT.Sockets.Stream (Rdate_Client); Rdate_Time_Packet'Read (Channel, Raw_Time); GNAT.Sockets.Close_Socket (Rdate_Client); -- Convert the big-endian received rdate Host_Rdate_Time := Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(0)), 24) + Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(1)), 16) + Interfaces.Shift_Left (Interfaces.Unsigned_32 (Raw_Time(2)), 8) + Interfaces.Unsigned_32 (Raw_Time(3)); -- Display the time as the number of seconds since the Linux epoch. Time_Since_Linux_Epoch := Host_Rdate_Time - Rdate_To_Linux_Epoch_Seconds; declare Raw_Image : constant String := Interfaces.Unsigned_32'Image (Time_Since_Linux_Epoch); begin Ada.Text_Io.Put (Ada.Strings.Fixed.Trim (Raw_Image, Ada.Strings.Left)); end; end; end Get_Rdate;
---------------------------------------------------------------------- -- -- New_maze : create a new maze -- -- written by -- -- Edmond Schonberg -- -- Ada Project -- Courant Institute -- New York University -- 251 Mercer Street -- New York, New York 10012 -- ----------------------------------------------------------------------- with random_numbers; use random_numbers; with system; separate(maze) procedure new_maze(start, goal: position; num_lines: integer) is -- create a new maze with a given number of paths, including two long ones -- that lead to source and destination. pos: position; d: direction ; l: integer ; task type liner is -- one is created for each path. entry draw(pos: position; dir: direction; len: integer); end liner; type new_liner is access liner ; next_line: new_liner ; function max_len(p: position; d: direction) return integer is -- establish distance from any point to boundary, -- along a given direction. begin case d is when up => return p.row ; when right => return (80 - p.col) ; when down => return (23 - p.row) ; when left => return p.col ; end case ; end max_len; task body liner is p: position ; d: direction ; l: integer; begin accept draw(pos: position; dir:direction; len: integer) do p := pos ; d := dir ; l := len ; end draw ; for i in 1..l loop putc(' ', p.row, p.col) ; dist(p.row, p.col) := max_dist ; p := next_pos(p, d) ; end loop ; end liner ; begin clear ; case SYSTEM.SYSTEM_NAME is when SYSTEM.PC_DOS => fill_screen(ASCII.SI); when others => fill_screen('#'); end case; pos := start ; -- first path starts at source. d := up; -- which is always on bottom row. l := 20 ; for i in 1..num_lines loop -- create the right number of tasks, and start each at a random posi- -- tion, going in a random direction towards the boundary. next_line := new liner ; next_line.draw(pos, d, l) ; pos := (2*(1 + random_int(11)), 2*(1 + random_int(38))) ; d := direction'val(random_int(40) mod 4) ; l := max_len(pos, d) ; l := l/2 + random_int(l/4) ; end loop ; -- One more for path leading to destination. (always on top row). next_line := new liner ; next_line.draw(goal, down, 22) ; exception when storage_error | program_error => puts("unable to create new tasks. Try simpler maze.", 23,1); end new_maze ;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with GNAT.OS_Lib; use GNAT.OS_Lib; procedure Lolicon is Age : Integer; procedure Intice is begin -- Nothing because weebs are already attracted to underage anime girls. null; end Intice; procedure Call_The_FBI (Check: in Integer) is Result : Integer; Arguments : Argument_List := (1 => new String'("call_911")); begin if Check < 15 then Spawn (Program_Name => "call_911", Args => Arguments, Output_File_Descriptor => Standout, Return_Code => Result ); for Index in Arguments'Range loop Free(Arguments(Index)); end loop; else put("Probably just something weird happened."); end if; end Call_The_FBI; begin put("What's the girl's age? "); get(Age); Call_The_FBI(Age); end Lolicon;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Program.Nodes.Attribute_References is function Create (Prefix : not null Program.Elements.Expressions .Expression_Access; Apostrophe_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Attribute_Designator : not null Program.Elements.Identifiers .Identifier_Access; Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access; Expressions : Program.Elements.Expressions.Expression_Access; Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access) return Attribute_Reference is begin return Result : Attribute_Reference := (Prefix => Prefix, Apostrophe_Token => Apostrophe_Token, Attribute_Designator => Attribute_Designator, Left_Bracket_Token => Left_Bracket_Token, Expressions => Expressions, Right_Bracket_Token => Right_Bracket_Token, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Prefix : not null Program.Elements.Expressions .Expression_Access; Attribute_Designator : not null Program.Elements.Identifiers .Identifier_Access; Expressions : Program.Elements.Expressions.Expression_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False) return Implicit_Attribute_Reference is begin return Result : Implicit_Attribute_Reference := (Prefix => Prefix, Attribute_Designator => Attribute_Designator, Expressions => Expressions, Is_Part_Of_Implicit => Is_Part_Of_Implicit, Is_Part_Of_Inherited => Is_Part_Of_Inherited, Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null) do Initialize (Result); end return; end Create; overriding function Prefix (Self : Base_Attribute_Reference) return not null Program.Elements.Expressions.Expression_Access is begin return Self.Prefix; end Prefix; overriding function Attribute_Designator (Self : Base_Attribute_Reference) return not null Program.Elements.Identifiers.Identifier_Access is begin return Self.Attribute_Designator; end Attribute_Designator; overriding function Expressions (Self : Base_Attribute_Reference) return Program.Elements.Expressions.Expression_Access is begin return Self.Expressions; end Expressions; overriding function Apostrophe_Token (Self : Attribute_Reference) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Apostrophe_Token; end Apostrophe_Token; overriding function Left_Bracket_Token (Self : Attribute_Reference) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Left_Bracket_Token; end Left_Bracket_Token; overriding function Right_Bracket_Token (Self : Attribute_Reference) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Right_Bracket_Token; end Right_Bracket_Token; overriding function Is_Part_Of_Implicit (Self : Implicit_Attribute_Reference) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Attribute_Reference) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Attribute_Reference) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; procedure Initialize (Self : aliased in out Base_Attribute_Reference'Class) is begin Set_Enclosing_Element (Self.Prefix, Self'Unchecked_Access); Set_Enclosing_Element (Self.Attribute_Designator, Self'Unchecked_Access); if Self.Expressions.Assigned then Set_Enclosing_Element (Self.Expressions, Self'Unchecked_Access); end if; null; end Initialize; overriding function Is_Attribute_Reference_Element (Self : Base_Attribute_Reference) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Attribute_Reference_Element; overriding function Is_Expression_Element (Self : Base_Attribute_Reference) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Expression_Element; overriding procedure Visit (Self : not null access Base_Attribute_Reference; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Attribute_Reference (Self); end Visit; overriding function To_Attribute_Reference_Text (Self : aliased in out Attribute_Reference) return Program.Elements.Attribute_References .Attribute_Reference_Text_Access is begin return Self'Unchecked_Access; end To_Attribute_Reference_Text; overriding function To_Attribute_Reference_Text (Self : aliased in out Implicit_Attribute_Reference) return Program.Elements.Attribute_References .Attribute_Reference_Text_Access is pragma Unreferenced (Self); begin return null; end To_Attribute_Reference_Text; end Program.Nodes.Attribute_References;
-- Ada-GUI version of MP: a Music Player -- Copyright (C) 2021 by PragmAda Software Engineering. All rights reserved. -- Released under the terms of the BSD 3-Clause license; see https://opensource.org/licenses with Ada.Containers.Vectors; with Ada.Directories; with Ada.Exceptions; with Ada.Numerics.Discrete_Random; with Ada.Strings.Bounded; with Ada.Strings.Unbounded; with Ada.Text_IO; with Ada_GUI; with PragmARC.Persistent_Skip_List_Unbounded; procedure MP is package B_Strings is new Ada.Strings.Bounded.Generic_Bounded_Length (Max => 400); use B_Strings; subtype Path_Name is Bounded_String; function Less (Left : Path_Name; Right : Path_Name) return Boolean; -- Files in the working directory are < files in subdirectories package Path_Lists is new PragmARC.Persistent_Skip_List_Unbounded (Element => Path_Name, "<" => Less); type Song_Info is record Position : Positive; Path : Path_Name; end record; package Song_Lists is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Song_Info); function Less (Left : Path_Name; Right : Path_Name) return Boolean is function Slash_Count (Path : Path_Name) return Natural; function Slash_Count (Path : Path_Name) return Natural is Result : Natural := 0; Path_S : constant String := To_String (Path); begin -- Slash_Count All_Chars : for I in Path_S'Range loop if Path_S (I) = '/' then Result := Result + 1; end if; end loop All_Chars; return Result; end Slash_Count; Count_L : constant Natural := Slash_Count (Left); Count_R : constant Natural := Slash_Count (Right); begin -- Less if Count_L = 0 and Count_R > 0 then return True; end if; if Count_R = 0 and Count_L > 0 then return False; end if; return Left < Right; end Less; List : Path_Lists.Persistent_Skip_List := Path_Lists.Open_List ("playlist.mpl", Write_On_Modify => True); Song : Song_Lists.Vector; procedure Make_Song_List (List : in out Song_Lists.Vector); -- Adds all the songs in MP.List to List procedure Shuffle (List : in out Song_Lists.Vector); -- Randomizes List procedure Add_Song; -- Adds Path to List if Path is not null procedure Browse_Songs; -- Displays a file-selection dialog and allows selection of a file in the current directory or below -- If a file is selected, puts its name relative to the current directory in Path procedure Delete_Song; -- Deletes the currently selected song procedure Quit_Now; -- Tears down the GUI and saves the playlist procedure Refresh; -- Shuffles List into Song and updates Count function Start (Song : in String) return Boolean; -- Tries to start playing a file named Song -- Returns True if successful; False otherwise Player : Ada_GUI.Widget_ID; Sel : Ada_GUI.Widget_ID; Count : Ada_GUI.Widget_ID; Delete : Ada_GUI.Widget_ID; Path : Ada_GUI.Widget_ID; Browse : Ada_GUI.Widget_ID; Add : Ada_GUI.Widget_ID; Play : Ada_GUI.Widget_ID; Skip : Ada_GUI.Widget_ID; Quit : Ada_GUI.Widget_ID; Quit_After : Ada_GUI.Widget_ID; Event : Ada_GUI.Next_Result_Info; Current : Song_Info; Index : Positive := 1; procedure Make_Song_List (List : in out Song_Lists.Vector) is Position : Natural := 0; procedure Add_One (Item : in Path_Name) is -- Empty; begin -- Add_One Position := Position + 1; List.Append (New_Item => (Position => Position, Path => Item) ); Sel.Insert (Text => To_String (Item) ); end Add_One; procedure Add_All is new Path_Lists.Iterate (Action => Add_One); begin -- Make_Song_List List.Clear; Add_All (List => MP.List); end Make_Song_List; procedure Shuffle (List : in out Song_Lists.Vector) is subtype Index is Integer range 1 .. List.Last_Index; package Index_Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Index); Gen : Index_Random.Generator; J : Index; T : Song_Info; begin -- Shuffle Index_Random.Reset (Gen => Gen); Swap_All : for I in 1 .. List.Last_Index loop J := Index_Random.Random (Gen); T := List.Element (I); List.Replace_Element (Index => I, New_Item => List.Element (J) ); List.Replace_Element (Index => J, New_Item => T); end loop Swap_All; end Shuffle; procedure Add_Song is Name : constant String := Path.Text; begin -- Add_Song if Name = "" then return; end if; List.Insert (Item => To_Bounded_String (Name) ); Refresh; Path.Set_Text (Text => ""); exception -- Add_Song when Error : others => Ada.Text_IO.Put_Line (Item => "Add_Song " & Ada.Exceptions.Exception_Information (Error) ); end Add_Song; Current_Directory : constant String := Ada.Directories.Current_Directory; procedure Browse_Songs is Pick : Ada_GUI.File_Result_Info := Ada_GUI.Selected_File (Current_Directory); begin -- Browse_Songs if not Pick.Picked then return; end if; Get_Name : declare Name : constant String := Ada.Strings.Unbounded.To_String (Pick.Value); begin -- Get_Name if Name'Length > Current_Directory'Length and then Name (Name'First .. Name'First + Current_Directory'Length - 1) = Current_Directory then Path.Set_Text (Text => Name (Name'First + Current_Directory'Length + 1 .. Name'Last) ); end if; end Get_Name; exception -- Browse_Songs when Error : others => Ada.Text_IO.Put_Line (Item => "Browse_Songs " & Ada.Exceptions.Exception_Information (Error) ); end Browse_Songs; procedure Delete_Song is Index : constant Natural := Sel.Selected; begin -- Delete_Song if Index = 0 then return; end if; List.Delete (Item => To_Bounded_String (Sel.Text) ); Refresh; exception -- Delete_Song when Error : others => Ada.Text_IO.Put_Line (Item => "Delete_Song " & Ada.Exceptions.Exception_Information (Error) ); end Delete_Song; Title : constant String := "MP"; procedure Quit_Now is -- Empty begin -- Quit_Now Ada_GUI.Set_Title (Title => Title); Ada_GUI.End_GUI; exception -- Quit_Now when Error : others => Ada.Text_IO.Put_Line (Item => "Quit_Now " & Ada.Exceptions.Exception_Information (Error) ); end Quit_Now; procedure Refresh is -- Empty begin -- Refresh Sel.Clear; Make_Song_List (List => Song); Count.Set_Text (Text => Integer'Image (Sel.Length) ); Shuffle (List => Song); exception -- Refresh when Error : others => Ada.Text_IO.Put_Line (Item => "Refresh " & Ada.Exceptions.Exception_Information (Error) ); end Refresh; function Start (Song : in String) return Boolean is -- Empty begin -- Start Player.Set_Source (Source => Song); Ada_GUI.Set_Title (Title => Title & ' ' & Song); Wait_For_Ready : for I in 1 .. 10 loop if Player.Ready then Player.Play; return True; end if; delay 0.01; end loop Wait_For_Ready; return False; exception -- Start when Error : others => Ada.Text_IO.Put_Line (Item => "Start " & Ada.Exceptions.Exception_Information (Error) ); return False; end Start; use type Ada_GUI.Event_Kind_ID; use type Ada_GUI.Widget_ID; begin -- MP Ada_GUI.Set_Up (Title => Title, ID => 8089); Player := Ada_GUI.New_Audio_Player; Sel := Ada_GUI.New_Selection_List (Break_Before => True, Height => 30); Count := Ada_GUI.New_Text_Box (Label => "Number of songs:", Break_Before => True); Delete := Ada_GUI.New_Button (Text => "Delete", Break_Before => True); Path := Ada_GUI.New_Text_Box (Width => 100); Browse := Ada_GUI.New_Button (Text => "Browse"); Add := Ada_GUI.New_Button (Text => "Add"); Play := Ada_GUI.New_Button (Text => "Play", Break_Before => True); Skip := Ada_GUI.New_Button (Text => "Skip"); Quit := Ada_GUI.New_Button (Text => "Quit"); Quit_After := Ada_GUI.New_Check_Box (Label => "Quit after this song"); Refresh; -- Now we're ready to go -- If Song is empty, we wait until a song is added or the user clicks on Quit, ignoring other buttons Wait_For_Song : loop exit Wait_For_Song when List.Length > 0; Event := Ada_GUI.Next_Event; if not Event.Timed_Out and then Event.Event.Kind = Ada_GUI.Left_Click then if Event.Event.ID = Add then Add_Song; elsif Event.Event.ID = Browse then Browse_Songs; elsif Event.Event.ID = Quit then Quit_Now; return; else null; end if; end if; end loop Wait_For_Song; Forever : loop exit Forever when Ada_GUI.Window_Closed; Current := Song.Element (Index); Sel.Set_Selected (Index => Current.Position); if Start (To_String (Current.Path) ) then Wait_For_End : loop Event := Ada_GUI.Next_Event (Timeout => 0.1); if Event.Timed_Out then exit Wait_For_End when Player.Playback_Ended; elsif Event.Event.Kind = Ada_GUI.Left_Click then exit Forever when Event.Event.ID = Quit; if Event.Event.ID = Play then exit Wait_For_End when not Start (Sel.Text); elsif Event.Event.ID = Skip then Ada_GUI.Set_Title (Title => Title); exit Wait_For_End; elsif Event.Event.ID = Add then Add_Song; elsif Event.Event.ID = Browse then Browse_Songs; elsif Event.Event.ID = Delete then Delete_Song; else null; end if; else null; end if; end loop Wait_For_End; end if; exit Forever when Quit_After.Active; Index := Index + 1; if Index > Song.Last_Index then Index := 1; end if; end loop Forever; Quit_Now; exception -- MP when others => if Ada_GUI.Set_Up then Quit_Now; end if; end MP;
-- This spec has been automatically generated from cm7.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; -- Processor Features package Cortex_M_SVD.PF is pragma Preelaborate; --------------- -- Registers -- --------------- -- Level of Coherency type CLIDR_LoC_Field is ( -- Level 1, if neither instruction nor data cache is implemented Level_1, -- Level 2, if either cache is implemented Level_2) with Size => 3; for CLIDR_LoC_Field use (Level_1 => 0, Level_2 => 1); -- Level of Unification type CLIDR_LoU_Field is ( -- Level 1, if neither instruction nor data cache is implemented Level_1, -- Level 2, if either cache is implemented Level_2) with Size => 3; for CLIDR_LoU_Field use (Level_1 => 0, Level_2 => 1); -- Cache Level ID Register type CLIDR_Register is record -- Read-only. An instrumentation Cache is implemented at L1 ICL1 : Boolean; -- Read-only. Data Cache is implemented at L1 DCL1 : Boolean; -- Read-only. Unified Cache is implemented at L1 UCL1 : Boolean; -- unspecified Reserved_3_23 : HAL.UInt21; -- Read-only. Level of Coherency LoC : CLIDR_LoC_Field; -- Read-only. Level of Unification LoU : CLIDR_LoU_Field; -- unspecified Reserved_30_31 : HAL.UInt2; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CLIDR_Register use record ICL1 at 0 range 0 .. 0; DCL1 at 0 range 1 .. 1; UCL1 at 0 range 2 .. 2; Reserved_3_23 at 0 range 3 .. 23; LoC at 0 range 24 .. 26; LoU at 0 range 27 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; -- Smallest cache line of all the instruction caches. type CTR_IMinLine_Field is ( -- 8 words for the Cortex-M7 processor. Line_8_Words) with Size => 4; for CTR_IMinLine_Field use (Line_8_Words => 3); -- Smallest cache line of all the data caches. type CTR_DMinLine_Field is ( -- 8 words for the Cortex-M7 processor. Line_8_Words) with Size => 4; for CTR_DMinLine_Field use (Line_8_Words => 3); subtype CTR_ERG_Field is HAL.UInt4; -- Cache Writable Granule. type CTR_CWG_Field is ( -- 8 words granularity for the Cortex-M7 processor. Granularity_8_Words) with Size => 4; for CTR_CWG_Field use (Granularity_8_Words => 3); -- Cache Writable Granule. type CTR_Format_Field is ( -- ARMv7 register forat. Armv7) with Size => 3; for CTR_Format_Field use (Armv7 => 4); -- Cache Type Register type CTR_Register is record -- Read-only. Smallest cache line of all the instruction caches. IMinLine : CTR_IMinLine_Field; -- unspecified Reserved_4_15 : HAL.UInt12; -- Read-only. Smallest cache line of all the data caches. DMinLine : CTR_DMinLine_Field; -- Read-only. Exclusive Reservation Granule. The local monitor within -- the processor does not hold any physical address. It treats any STREX -- instruction access as matching the address of the previous LDREX -- instruction. This means that the implemented exclusive reservation -- granule is the entire memory address range. ERG : CTR_ERG_Field; -- Read-only. Cache Writable Granule. CWG : CTR_CWG_Field; -- unspecified Reserved_28_28 : HAL.Bit; -- Read-only. Cache Writable Granule. Format : CTR_Format_Field; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CTR_Register use record IMinLine at 0 range 0 .. 3; Reserved_4_15 at 0 range 4 .. 15; DMinLine at 0 range 16 .. 19; ERG at 0 range 20 .. 23; CWG at 0 range 24 .. 27; Reserved_28_28 at 0 range 28 .. 28; Format at 0 range 29 .. 31; end record; subtype CCSIDR_LineSize_Field is HAL.UInt3; subtype CCSIDR_Associativity_Field is HAL.UInt10; subtype CCSIDR_NumSets_Field is HAL.UInt15; -- Cache Size ID Register type CCSIDR_Register is record -- Read-only. Indicates the number of words in each cache line. Encoded -- as 2 - log(2) number of words. e.g. 0 means 4 words, 1 means 8 words. LineSize : CCSIDR_LineSize_Field; -- Read-only. Indicates the number of ways as (ways - 1) Associativity : CCSIDR_Associativity_Field; -- Read-only. Indicates the number of sets as (sets - 1) NumSets : CCSIDR_NumSets_Field; -- Read-only. Indicates support available for write allocation. WA : Boolean; -- Read-only. Indicates support available for read allocation. RA : Boolean; -- Read-only. Indicates support available for write back. WB : Boolean; -- Read-only. Indicates support available for write through. WT : Boolean; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CCSIDR_Register use record LineSize at 0 range 0 .. 2; Associativity at 0 range 3 .. 12; NumSets at 0 range 13 .. 27; WA at 0 range 28 .. 28; RA at 0 range 29 .. 29; WB at 0 range 30 .. 30; WT at 0 range 31 .. 31; end record; -- Selects the cache currently visible in the CCSIDR. type CSSELR_InD_Field is ( -- Data cache is selected. Data_Cache, -- Instruction cache is selected. Instruction_Cache) with Size => 1; for CSSELR_InD_Field use (Data_Cache => 0, Instruction_Cache => 1); -- Identifies the cache level selected. type CSSELR_Level_Field is ( -- Level 1 cache is selected. Level_1) with Size => 3; for CSSELR_Level_Field use (Level_1 => 0); -- Cache Size Selection Register type CSSELR_Register is record -- Selects the cache currently visible in the CCSIDR. InD : CSSELR_InD_Field := Cortex_M_SVD.PF.Data_Cache; -- Identifies the cache level selected. Level : CSSELR_Level_Field := Cortex_M_SVD.PF.Level_1; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSSELR_Register use record InD at 0 range 0 .. 0; Level at 0 range 1 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Processor Features type PF_Peripheral is record -- Cache Level ID Register CLIDR : aliased CLIDR_Register; -- Cache Type Register CTR : aliased CTR_Register; -- Cache Size ID Register CCSIDR : aliased CCSIDR_Register; -- Cache Size Selection Register CSSELR : aliased CSSELR_Register; end record with Volatile; for PF_Peripheral use record CLIDR at 16#0# range 0 .. 31; CTR at 16#4# range 0 .. 31; CCSIDR at 16#8# range 0 .. 31; CSSELR at 16#C# range 0 .. 31; end record; -- Processor Features PF_Periph : aliased PF_Peripheral with Import, Address => PF_Base; end Cortex_M_SVD.PF;
with STM32GD.GPIO.Pin; with STM32GD.GPIO.IRQ; with STM32GD.SPI.Peripheral; with STM32GD.I2C.Peripheral; with STM32GD.USART.Peripheral; package HAL is generic package Pin renames STM32GD.GPIO.Pin; generic package Pin_IRQ renames STM32GD.GPIO.IRQ; generic package SPI renames STM32GD.SPI.Peripheral; generic package I2C renames STM32GD.I2C.Peripheral; generic package USART renames STM32GD.USART.Peripheral; end HAL;
package body opengl.Display.privvy is function to_eGL (Self : in Display.item'Class) return eGL.EGLDisplay is begin return Self.Thin; end to_eGL; end opengl.Display.privvy;
----------------------------------------------------------------------- -- keystore-buffers -- Buffer management for the keystore -- Copyright (C) 2019 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. ----------------------------------------------------------------------- package body Keystore.Buffers is -- ------------------------------ -- Get a printable representation of storage block for the logs. -- ------------------------------ function To_String (Value : in Storage_Block) return String is Sid : constant String := Storage_Identifier'Image (Value.Storage); Bid : constant String := Block_Number'Image (Value.Block); begin return Sid (Sid'First + 1 .. Sid'Last) & "." & Bid (Bid'First + 1 .. Bid'Last); end To_String; -- ------------------------------ -- Find a buffer from the set of allocate an instance to hold it. -- ------------------------------ function Find_Or_Allocate (Container : in Buffer_Map; Storage : in Storage_Identifier; Block : in Block_Number) return Storage_Buffer is Buffer : Storage_Buffer; Pos : Buffer_Cursor; Key : constant Storage_Block := Storage_Block '(Storage, Block); begin Buffer.Block := Key; Pos := Container.Find (Key); if Buffer_Maps.Has_Element (Pos) then Buffer.Data := Buffer_Maps.Element (Pos); else Buffer.Data := Buffer_Refs.Create; end if; return Buffer; end Find_Or_Allocate; -- ------------------------------ -- Find a buffer from the container. -- ------------------------------ function Find (Container : in Buffer_Map; Block : in Storage_Block) return Storage_Buffer is Buffer : Storage_Buffer; Pos : Buffer_Cursor; begin Buffer.Block := Block; Pos := Container.Find (Block); if Buffer_Maps.Has_Element (Pos) then Buffer.Data := Buffer_Maps.Element (Pos); end if; return Buffer; end Find; -- ------------------------------ -- Allocate a buffer for the storage block. -- ------------------------------ function Allocate (Block : in Storage_Block) return Storage_Buffer is Buffer : Storage_Buffer; begin Buffer.Block := Block; Buffer.Data := Buffer_Refs.Create; return Buffer; end Allocate; end Keystore.Buffers;
-- Lambda Calculus interpreter -- --------------------------- -- Parses and reduces Lamdba Calculus statements. -- -- Source: -- lambda - definitions and helper functions -- lambda_REPL - [This file] REPL and command line parsers -- lambda_parser - parse tree generator -- lambda_reducer - optimises and reduces lambda expressions -- with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Text_IO; use Ada.Text_IO; with Ada.Text_IO.Unbounded_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Exceptions; use Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Containers; use Ada.Containers; with Ada.Containers.Multiway_Trees; with lambda; use lambda; with lambda_parser; use lambda_parser; with lambda_reducer; use lambda_reducer; Package body Lambda_REPL is -- The Read|Evaulate|Print Loop procedure REPL is I : Instructions.Tree := Instructions.Empty_Tree; Prompt : constant string := "Unbounded> "; S : Statement (1..Max_Statement_Length); L : Natural; begin -- TBD: Load the environment context -- (environment settings, eg trace on/off) -- (library of Synonyms) L := 0; loop L := L+1; begin --Put(Integer'Image(L) & " " & Prompt); Put(Prompt); -- Read a line S := Get_Statement; New_Line; -- parse the line if not parse_Commands(S) then I := parse_Statement(S); Log_Format(I); -- reduce the line I := reduce(I); Log_Format(I); -- print the line Put_Line("-> " & format(I)); end if; exception when Ada.IO_Exceptions.END_ERROR => New_Line; exit; when E: others => Put_Line(Exception_Name(E) & ": " & Exception_Message(E) & " in " & Ada.Strings.Fixed.Trim(Source => S, Side => Both) ); end; end loop; Put_Line("Bye"); -- TBD: Save the environment context if required end; -- Command line Lambda expression parser procedure Evaluate ( S : in Statement ) is begin null; end; -- Parse commands from the REPL -- -- Commands are: -- : "EXIT" | "QUIT" : Exit -- : "HELP" : Print the help/usage message -- : "LS" : List saved expressions -- : "RM <symbol>" : Delete an expression -- : "TRACE" : Display tracing level -- : "TRACE <feature> " : Set verbose tracing for [ON|OFF|PARSE|REDUCE|FORMAT] functions function parse_Commands( S: Statement ) return Boolean is X : SU.Unbounded_String; Token : String := Empty_Statement; From : Natural := 1; -- REPL command tokeniser -- Command => the statement to tokenise -- From => current position in the Command. Returns = when end of Command reached -- Token => next token extracted from the Command -- procedure Next_Token( Command : Statement; From : in out Natural; Token : out Statement ) is Cmd_Set : Character_Set := To_Set( Sequence => "ABCDEFGHIJKLMNOPQRSTUVWXYZ-abcdefghijklmnopqrstuvwxyz"); First : Positive; Last : Natural; begin Find_Token(Command, Cmd_Set, From, Inside, First, Last); if Last = 0 then Token := Empty_Statement; From := 0; else Token := Ada.Strings.Fixed.Head( Command(First..Last), Max_Statement_Length, ' '); if Last < Command'Last then From := Last + 1; else From := 0; end if; end if; end; begin From := 1; next_token(S, From, Token); X := SU.To_Unbounded_String(To_Upper(trim(Token, Both))); if X = "EXIT" OR X = "QUIT" then Log("Exit"); raise Ada.IO_Exceptions.END_ERROR; elsif X = "LS" then Log("List saved expressions"); List_Synonyms; return True; elsif X = "RM" then Log("Remove synonym"); loop next_token(S, From, Token); exit when From = 0; Remove_Synonym(Token); end loop; return True; -- This is a little ugly elsif X = "TRACE" then loop next_token(S, From, Token); exit when From = 0; X := SU.To_Unbounded_String(To_Upper(trim(Token, Both))); if X = "PARSE" then Trace_Parse := not Trace_Parse; elsif X = "REDUCE" then Trace_Reduce := not Trace_Reduce; elsif X = "FORMAT" then Trace_Format := not Trace_Format; elsif X = "ON" then Trace := TRUE; elsif X = "OFF" then Trace := FALSE; else raise Syntax_Error with "Invalid parameter: " & To_String(X); end if; end loop; if Trace then Put(". Trace on"); if Trace_Parse then Put(" - PARSE"); end if; if Trace_Reduce then Put(" - REDUCE"); end if; if Trace_Format then Put(" - FORMAT"); end if; new_line; else Put_Line(". Trace off"); end if; return True; elsif X = "HELP" then Put_Line("EXIT | QUIT : Exit Unbounded"); Put_Line("HELP : Display this message"); Put_Line("LS : List all saved expressions"); Put_Line("RM <symbol> : Delete an expression"); Put_Line("TRACE : Display the tracing level"); Put_Line("TRACE <feature> : Set verbose tracing [ON|OFF|PARSE|REDUCE|FORMAT]"); return True; end if; return False; end parse_Commands; -- ========================================================================================== -- Private functions -- ========================================================================================== -- -- Input a Lambda statement function Get_Statement return Statement is Buffer : SU.Unbounded_String := SU.Null_Unbounded_String; begin Buffer := Ada.Text_IO.Unbounded_IO.Get_Line; return Ada.Strings.Fixed.Head(Source => SU.To_String(Buffer), Count => Max_Statement_Length, Pad => ' '); end Get_Statement; end Lambda_REPL;
with Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Blade; with Blade_Types; with GA_Maths; with GA_Utilities; with Metric; with Multivectors; use Multivectors; with Multivector_Type; procedure General_Inverse_Test is use Blade.Names_Package; BV_Names : Blade.Basis_Vector_Names; C3_Met_Matrix : constant Metric.Metric_Matrix (1 .. 5, 1 .. 5) := ((0.0, 0.0, 0.0, 0.0, -1.0), (0.0, 1.0, 0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 0.0 ,1.0, 0.0), (-1.0, 0.0, 0.0 , 0.0, 0.0)); C3_Metric : constant Metric.Metric_Record := Metric.New_Metric (C3_Met_Matrix); no_bv : Multivector := Basis_Vector (Blade_Types.C3_no); e1_bv : Multivector := Basis_Vector (Blade_Types.C3_e1); e2_bv : Multivector := Basis_Vector (Blade_Types.C3_e2); e3_bv : Multivector := Basis_Vector (Blade_Types.C3_e3); ni_bv : Multivector := Basis_Vector (Blade_Types.C3_ni); MV_A1 : Multivector; MV_A2 : Multivector; MV_A : Multivector; MV_A_Inv : Multivector; NP_1 : constant Multivector := New_Normalized_Point (-0.356756, -0.881980, 0.0); NP_1_OP : Multivector; NP_1_IP : Multivector; NP_1_GP_Met : Multivector; NP_1_IP_Met : Multivector; NP_1_Inv : Multivector; NP_1_GP : Multivector; begin BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("no")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e1")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e2")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e3")); BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("ni")); MV_A1 := Outer_Product (e2_bv, e3_bv); MV_A2 := e1_bv + Outer_Product (e2_bv, e3_bv); MV_A := e1_bv + Outer_Product (Outer_Product (e2_bv, e3_bv), e1_bv); GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A1", MV_A1); GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A2", MV_A2); GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A", MV_A); MV_A_Inv := General_Inverse (MV_A); GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A_Inv", MV_A_Inv); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1", NP_1); NP_1_OP := Outer_Product (NP_1, NP_1); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_OP", NP_1_OP); -- GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A", MV_A); -- MV_A_GP := Geometric_Product (MV_A, MV_A); -- GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A_GP", MV_A_GP); -- MV_A_GP_Met := Geometric_Product (MV_A, MV_A, C3_Metric); -- GA_Utilities.Print_Multivector ("General_Inverse_Test MV_A_GP_Met", MV_A_GP_Met); -- MV_A_Inv := General_Inverse (MV_A, C3_Metric); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1", NP_1); NP_1_OP := Outer_Product (NP_1, NP_1); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_OP", NP_1_OP); NP_1_GP := Geometric_Product (NP_1, NP_1); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_GP", NP_1_GP); NP_1_GP_Met := Geometric_Product (NP_1, NP_1, C3_Metric); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_GP_Met", NP_1_GP_Met); NP_1_IP := Inner_Product (NP_1, NP_1,Blade.Left_Contraction); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_IP", NP_1_IP); NP_1_IP_Met := Geometric_Product (NP_1, NP_1, C3_Metric); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_IP_Met", NP_1_IP_Met); NP_1_Inv := General_Inverse (NP_1, C3_Metric); GA_Utilities.Print_Multivector ("General_Inverse_Test NP_1_Inv", NP_1_Inv); exception when anError : others => Put_Line ("An exception occurred in General_Inverse_Test."); raise; end General_Inverse_Test;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Ada.Exceptions; with Natools.References.Tools; package body Natools.Reference_Tests is package Tools is new Refs.Tools; procedure Check_Ref (Report : in out NT.Reporter'Class; Name : in String; Ref : in Refs.Reference; Expected_Count : in Natural; Continue : in out Boolean); -- Check the given reference and report failure if any -- Do nothing if Continue is False procedure Check_Consistency (Report : in out NT.Reporter'Class; Name : in String; Left, Right : in Refs.Reference; Continue : in out Boolean); -- Check consistency between two reference and report if failed -- Do nothing if Continue is False procedure Check_Count (Report : in out NT.Reporter'Class; Name : in String; Expected_Count : in Integer; Continue : in out Boolean); -- Check instance count and report failure if any -- Do nothing if Continue is False -------------------- -- Object counter -- -------------------- function Factory return Counter is begin Instance_Count := Instance_Count + 1; return Counter'(Ada.Finalization.Limited_Controlled with Instance_Number => Instance_Count); end Factory; overriding procedure Initialize (Object : in out Counter) is begin Instance_Count := Instance_Count + 1; Object.Instance_Number := Instance_Count; end Initialize; overriding procedure Finalize (Object : in out Counter) is pragma Unreferenced (Object); begin Instance_Count := Instance_Count - 1; end Finalize; ------------------------ -- Helper subprograms -- ------------------------ procedure Check_Consistency (Report : in out NT.Reporter'Class; Name : in String; Left, Right : in Refs.Reference; Continue : in out Boolean) is begin if Continue and then not Tools.Is_Consistent (Left, Right) then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Inconsistent references found"); Continue := False; end if; end Check_Consistency; procedure Check_Count (Report : in out NT.Reporter'Class; Name : in String; Expected_Count : in Integer; Continue : in out Boolean) is begin if not Continue then return; end if; if Instance_Count < 0 then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Invalid Instance_Count " & Integer'Image (Instance_Count)); Continue := False; elsif Instance_Count /= Expected_Count then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Unexpected Instance_Count" & Integer'Image (Instance_Count) & " instead of" & Integer'Image (Expected_Count)); Continue := False; end if; end Check_Count; procedure Check_Ref (Report : in out NT.Reporter'Class; Name : in String; Ref : in Refs.Reference; Expected_Count : in Natural; Continue : in out Boolean) is Actual_Count : constant Integer := Tools.Count (Ref); begin if not Continue then return; end if; if not Tools.Is_Valid (Ref) then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Invalid internal state for reference"); Continue := False; elsif Actual_Count /= Expected_Count then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Unexpected reference count" & Natural'Image (Actual_Count) & " instead of" & Natural'Image (Expected_Count)); Continue := False; elsif not Ref.Is_Empty and then Ref.Is_Last /= (Actual_Count = 1) then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Unexpected result of Is_Last (" & Boolean'Image (Ref.Is_Last) & ") while counter is" & Natural'Image (Actual_Count)); Continue := False; end if; end Check_Ref; -------------------- -- Invidual tests -- -------------------- procedure Test_Data_Access (Report : in out NT.Reporter'Class) is Argument_Count : Natural; Result : Boolean; procedure Check (Self : in Counter); procedure Set (Self : in out Counter); procedure Check (Self : in Counter) is begin Result := Argument_Count = Self.Instance_Number; Argument_Count := Self.Instance_Number; end Check; procedure Set (Self : in out Counter) is begin Self.Instance_Number := Argument_Count; end Set; Name : constant String := "Data access"; begin declare Ref_1 : Refs.Reference := Refs.Create (Factory'Access); Ref_2 : Refs.Reference; begin Ref_2.Replace (Factory'Access); Argument_Count := 42; Ref_2.Update (Set'Access); Ref_1.Update.Data.Instance_Number := 18; Argument_Count := 18; Ref_1.Query (Check'Access); if not Result then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Stored 18, retrieved" & Integer'Image (Argument_Count)); return; end if; Ref_1.Reset; Argument_Count := Ref_2.Query.Data.Instance_Number; if Argument_Count /= 42 then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Stored 42, retrieved" & Integer'Image (Argument_Count)); return; end if; end; NT.Item (Report, Name, NT.Success); exception when Error : others => NT.Report_Exception (Report, Name, Error); end Test_Data_Access; procedure Test_Double_Finalize (Report : in out NT.Reporter'Class) is Name : constant String := "Double finalize"; Initial_Count : constant Integer := Instance_Count; Continue : Boolean := True; begin declare Ref : Refs.Reference := Refs.Create (Factory'Access); begin Ref.Finalize; end; Check_Count (Report, Name, Initial_Count, Continue); if Continue then NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end Test_Double_Finalize; procedure Test_Implicit_Dereference (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Implicit dereference"); Other_Number : constant Integer := 123; procedure Set_Number (Object : in out Counter); procedure Set_Number (Object : in out Counter) is begin Object.Instance_Number := Other_Number; end Set_Number; begin declare Ref : constant Refs.Reference := Refs.Create (Factory'Access); Original_Number : constant Natural := Ref.Query.Instance_Number; begin Set_Number (Ref.Update); Ref.Update.Instance_Number := Original_Number; end; exception when Error : others => Test.Report_Exception (Error); end Test_Implicit_Dereference; procedure Test_Instance_Counts (Report : in out NT.Reporter'Class) is Name : constant String := "Instance counts"; Initial_Count : constant Integer := Instance_Count; Continue : Boolean := True; begin declare procedure Check (Count_0, Count_1, Count_2, Delta_I : in Integer); Ref_0 : Refs.Reference := Refs.Create (Factory'Access); Ref_1 : Refs.Reference := Refs.Create (Refs.Data_Access'(null)); Ref_2 : Refs.Reference; procedure Check (Count_0, Count_1, Count_2, Delta_I : in Integer) is begin Check_Ref (Report, Name, Ref_0, Count_0, Continue); Check_Ref (Report, Name, Ref_1, Count_1, Continue); Check_Ref (Report, Name, Ref_2, Count_2, Continue); Check_Consistency (Report, Name, Ref_0, Ref_1, Continue); Check_Consistency (Report, Name, Ref_1, Ref_2, Continue); Check_Consistency (Report, Name, Ref_2, Ref_0, Continue); Check_Count (Report, Name, Initial_Count + Delta_I, Continue); end Check; begin Check (1, 0, 0, 1); if Continue then Ref_1 := Refs.Create (new Counter); end if; Check (1, 1, 0, 2); if Continue then Ref_2 := Ref_0; end if; Check (2, 1, 2, 2); if Continue then Ref_1 := Ref_0; end if; Check (3, 3, 3, 1); if Continue then Ref_2.Replace (new Counter); end if; Check (2, 2, 1, 2); if Continue then Ref_1.Reset; Ref_0 := Ref_1; end if; Check (0, 0, 1, 1); end; Check_Count (Report, Name, Initial_Count, Continue); if Continue then NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end Test_Instance_Counts; procedure Test_Reference_Counts (Report : in out NT.Reporter'Class) is Name : constant String := "Reference counts"; Initial_Count : constant Integer := Instance_Count; Continue : Boolean := True; begin declare procedure Check (Count_0, Count_1, Count_2 : in Integer); Ref_0 : constant Refs.Reference := Refs.Create (Factory'Access); Ref_1 : Refs.Reference := Ref_0; Ref_2 : Refs.Reference; procedure Check (Count_0, Count_1, Count_2 : in Integer) is begin Check_Ref (Report, Name, Ref_0, Count_0, Continue); Check_Ref (Report, Name, Ref_1, Count_1, Continue); Check_Ref (Report, Name, Ref_2, Count_2, Continue); Check_Consistency (Report, Name, Ref_0, Ref_1, Continue); Check_Consistency (Report, Name, Ref_1, Ref_2, Continue); Check_Consistency (Report, Name, Ref_2, Ref_0, Continue); end Check; begin Check (2, 2, 0); if Continue then Ref_2 := Ref_0; end if; Check (3, 3, 3); if Continue then Refs.Reset (Ref_1); end if; Check (2, 0, 2); end; Check_Count (Report, Name, Initial_Count, Continue); if Continue then NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end Test_Reference_Counts; procedure Test_Reference_Tests (Report : in out NT.Reporter'Class) is Name : constant String := "Reference tests"; Initial_Count : constant Integer := Instance_Count; Continue : Boolean := True; begin declare use type Refs.Reference; Ref : Refs.Reference; Base : constant Refs.Reference := Refs.Create (Factory'Access); begin if not Ref.Is_Empty then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Default reference is not empty"); return; end if; if Base.Is_Empty then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Created reference is empty"); return; end if; Ref.Replace (Factory'Access); if Ref.Is_Empty then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Replaced reference is empty"); return; end if; if Ref = Base then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Unexpected equality between Ref and Base"); return; end if; Ref := Base; if Ref /= Base then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Unexpected inequality between Ref and Base"); return; end if; end; Check_Count (Report, Name, Initial_Count, Continue); if Continue then NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end Test_Reference_Tests; procedure Test_Task_Safety (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Task safety"); Success : Boolean := True; protected Protected_Report is procedure Report_Exception (Ex : Ada.Exceptions.Exception_Occurrence); end Protected_Report; protected body Protected_Report is procedure Report_Exception (Ex : Ada.Exceptions.Exception_Occurrence) is begin Test.Report_Exception (Ex, NT.Fail); end Report_Exception; end Protected_Report; task type Checker is entry Start (Count : in Natural; Ref : in Refs.Immutable_Reference); end Checker; task body Checker is Starting_Value, Last : Natural; R : Refs.Immutable_Reference; begin accept Start (Count : in Natural; Ref : in Refs.Immutable_Reference) do Last := Count; R := Ref; end Start; Starting_Value := R.Query.Data.Instance_Number; for I in 1 .. Last loop declare Temp : constant Refs.Immutable_Reference := R; begin if Temp.Query.Data.Instance_Number /= Starting_Value then Success := False; end if; end; end loop; exception when Error : others => Protected_Report.Report_Exception (Error); end Checker; Start : constant Ada.Calendar.Time := Ada.Calendar.Clock; begin declare Base : constant Refs.Immutable_Reference := Refs.Create (Factory'Access); begin declare Checkers : array (1 .. 16) of Checker; begin for I in Checkers'Range loop Checkers (I).Start (10 ** 6, Base); end loop; end; if not Success then Test.Fail ("Success somehow got to False"); end if; end; Test.Info ("Test run in " & Duration'Image (Ada.Calendar."-" (Ada.Calendar.Clock, Start))); exception when Error : others => Test.Report_Exception (Error); Test.Info ("Test run in " & Duration'Image (Ada.Calendar."-" (Ada.Calendar.Clock, Start))); end Test_Task_Safety; --------------------- -- Test everything -- --------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Test_Data_Access (Report); Test_Double_Finalize (Report); Test_Implicit_Dereference (Report); Test_Instance_Counts (Report); Test_Reference_Counts (Report); Test_Reference_Tests (Report); end All_Tests; end Natools.Reference_Tests;
-- -- This library is free software; you can redistribute it and/or modify -- it under the terms of the GNU Library General Public License as -- published by the Free Software Foundation; either version 3 of the -- License; or (at your option) any later version. -- This package provides queue abstractions that have a capacity limited only -- by available memory. These queues are not thread-safe. generic type Element is private; package Unbounded_Sequential_Queues is type Queue is tagged limited private; Underflow : exception; Overflow : exception; procedure Insert (Into : in out Queue; Item : in Element); procedure Remove (From : in out Queue; Item : out Element); function Size (Q : Queue) return Natural; function Empty (Q : Queue) return Boolean; -- Size(Q) = 0 generic with procedure Process (Item : in Element; Continue : out Boolean); procedure Iteration (Over : in Queue); private type Node; type Link is access Node; type Node is record Data : Element; Next : Link; end record; type Queue is tagged limited record Count : Natural := 0; Rear, Front : Link; end record; end Unbounded_Sequential_Queues;
------------------------------------------------------------------------------ -- -- -- 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 NRF51_SVD.TWI; use NRF51_SVD.TWI; package body nRF51.TWI is procedure Stop_Sequence (This : in out TWI_Master'Class); ------------------- -- Stop_Sequence -- ------------------- procedure Stop_Sequence (This : in out TWI_Master'Class) is begin -- Stop sequence This.Periph.EVENTS_STOPPED := 0; This.Periph.TASKS_STOP := 1; while This.Periph.EVENTS_STOPPED = 0 loop null; end loop; end Stop_Sequence; ------------ -- Enable -- ------------ procedure Enable (This : in out TWI_Master) is begin This.Periph.ENABLE.ENABLE := Enabled; end Enable; ------------- -- Disable -- ------------- procedure Disable (This : in out TWI_Master) is begin This.Periph.ENABLE.ENABLE := Disabled; end Disable; ------------- -- Enabled -- ------------- function Enabled (This : TWI_Master) return Boolean is begin return This.Periph.ENABLE.ENABLE = Enabled; end Enabled; --------------- -- Configure -- --------------- procedure Configure (This : in out TWI_Master; SCL, SDA : GPIO_Pin_Index; Speed : TWI_Speed) is begin This.Periph.PSELSCL := UInt32 (SCL); This.Periph.PSELSDA := UInt32 (SDA); This.Periph.FREQUENCY := (case Speed is when TWI_100kbps => 16#0198_0000#, when TWI_250kbps => 16#0400_0000#, when TWI_400kbps => 16#0668_0000#); end Configure; ---------------- -- Disconnect -- ---------------- procedure Disconnect (This : in out TWI_Master) is begin This.Periph.PSELSCL := 16#FFFF_FFFF#; This.Periph.PSELSDA := 16#FFFF_FFFF#; end Disconnect; --------------------- -- Master_Transmit -- --------------------- overriding procedure Master_Transmit (This : in out TWI_Master; Addr : I2C_Address; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is pragma Unreferenced (Timeout); Index : Integer := Data'First + 1; begin if Data'Length = 0 then Status := Ok; return; end if; -- Clear errors This.Periph.ERRORSRC.OVERRUN := Errorsrc_Overrun_Field_Reset; This.Periph.ERRORSRC.ANACK := Errorsrc_Anack_Field_Reset; This.Periph.ERRORSRC.DNACK := Errorsrc_Dnack_Field_Reset; -- Set Address This.Periph.ADDRESS.ADDRESS := UInt7 (Addr); -- Prepare first byte This.Periph.TXD.TXD := Data (Data'First); -- Start TX sequence This.Periph.TASKS_STARTTX := 1; loop loop if This.Periph.EVENTS_ERROR /= 0 then Status := Err_Error; -- Clear the error This.Periph.EVENTS_ERROR := 0; -- Stop sequence This.Periph.TASKS_STOP := 1; return; end if; exit when This.Periph.EVENTS_TXDSENT /= 0; end loop; -- Clear the event This.Periph.EVENTS_TXDSENT := 0; exit when Index > Data'Last; This.Periph.TXD.TXD := Data (Index); Index := Index + 1; end loop; if This.Do_Stop_Sequence then Stop_Sequence (This); end if; Status := Ok; end Master_Transmit; -------------------- -- Master_Receive -- -------------------- overriding procedure Master_Receive (This : in out TWI_Master; Addr : I2C_Address; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is pragma Unreferenced (Timeout); begin if Data'Length = 0 then Status := Ok; return; end if; -- Clear errors This.Periph.ERRORSRC.OVERRUN := Clear; This.Periph.ERRORSRC.ANACK := Clear; This.Periph.ERRORSRC.DNACK := Clear; -- Set Address This.Periph.ADDRESS.ADDRESS := UInt7 (Addr); -- Configure SHORTS to automatically suspend TWI port when receiving a -- byte. This.Periph.SHORTS.BB_SUSPEND := Enabled; This.Periph.SHORTS.BB_STOP := Disabled; -- Start RX sequence This.Periph.TASKS_STARTRX := 1; for Index in Data'Range loop loop if This.Periph.EVENTS_ERROR /= 0 then Status := Err_Error; -- Clear the error This.Periph.EVENTS_ERROR := 0; Stop_Sequence (This); return; end if; exit when This.Periph.EVENTS_RXDREADY /= 0; end loop; if Index = Data'Last and then This.Do_Stop_Sequence then -- Configure SHORTS to automatically stop the TWI port and produce -- a STOP event on the bus when receiving a byte. This.Periph.SHORTS.BB_SUSPEND := Disabled; This.Periph.SHORTS.BB_STOP := Enabled; end if; -- Clear the event This.Periph.EVENTS_RXDREADY := 0; Data (Index) := This.Periph.RXD.RXD; end loop; Status := Ok; end Master_Receive; --------------- -- Mem_Write -- --------------- overriding procedure Mem_Write (This : in out TWI_Master; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is begin This.Do_Stop_Sequence := False; case Mem_Addr_Size is when Memory_Size_8b => This.Master_Transmit (Addr => Addr, Data => (0 => UInt8 (Mem_Addr)), Status => Status, Timeout => Timeout); when Memory_Size_16b => This.Master_Transmit (Addr => Addr, Data => (UInt8 (Shift_Right (Mem_Addr, 8)), UInt8 (Mem_Addr and 16#FF#)), Status => Status, Timeout => Timeout); end case; This.Do_Stop_Sequence := True; if Status /= Ok then return; end if; This.Master_Transmit (Addr => Addr, Data => Data, Status => Status, Timeout => Timeout); end Mem_Write; -------------- -- Mem_Read -- -------------- overriding procedure Mem_Read (This : in out TWI_Master; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000) is begin This.Do_Stop_Sequence := False; case Mem_Addr_Size is when Memory_Size_8b => This.Master_Transmit (Addr => Addr, Data => (0 => UInt8 (Mem_Addr)), Status => Status, Timeout => Timeout); when Memory_Size_16b => This.Master_Transmit (Addr => Addr, Data => (UInt8 (Shift_Right (Mem_Addr, 8)), UInt8 (Mem_Addr and 16#FF#)), Status => Status, Timeout => Timeout); end case; This.Do_Stop_Sequence := True; if Status /= Ok then return; end if; This.Master_Receive (Addr => Addr, Data => Data, Status => Status, Timeout => Timeout); end Mem_Read; end nRF51.TWI;
with Day.Test; package body AOC_Suite is function Suite return Access_Test_Suite is Ret : constant Access_Test_Suite := new Test_Suite; begin Ret.Add_Test (new Day.Test.Test); return Ret; end Suite; end AOC_Suite;
-- { dg-do run } -- { dg-options "-flto" { target lto } } with Lto10_Pkg; use Lto10_Pkg; procedure Lto10 is A : Integer := Minus_One; Pos : Position; begin Pos := Pix.Pos; if A /= Minus_One then raise Program_Error; end if; end;
PROCEDURE object_renaming_declaration IS soureVal : Integer; renamedVal : Integer renames soureVal; BEGIN NULL; END;
with Compiler, Ada.Wide_Wide_Text_IO.Text_Streams; use Compiler, Ada.Wide_Wide_Text_IO.Text_Streams; package Compiler.Print is use Compiler.Node_List; procedure Debug (S : Stream_Access; AST : List); procedure Recreate (S : Stream_Access; AST : List); private end Compiler.Print;
type Link; type Link_Access is access Link; type Link is record Next : Link_Access := null; Data : Integer; end record;
-- -- 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. -- with HW.Debug; with GNAT.Source_Info; with HW.GFX.GMA.DP_Info; package body HW.GFX.GMA.Transcoder is type Default_Transcoder_Array is array (Pipe_Index) of Transcoder_Index; Default_Transcoder : constant Default_Transcoder_Array := (Primary => Trans_A, Secondary => Trans_B, Tertiary => Trans_C); function Get_Idx (Pipe : Pipe_Index; Port : GPU_Port) return Transcoder_Index is begin return (if Config.Has_EDP_Transcoder and then Port = DIGI_A then Trans_EDP else Default_Transcoder (Pipe)); end Get_Idx; ---------------------------------------------------------------------------- TRANS_CLK_SEL_PORT_NONE : constant := 0 * 2 ** 29; type TRANS_CLK_SEL_PORT_Array is array (Digital_Port) of Word32; TRANS_CLK_SEL_PORT : constant TRANS_CLK_SEL_PORT_Array := (DIGI_A => 0 * 2 ** 29, -- DDI A is not selectable DIGI_B => 2 * 2 ** 29, DIGI_C => 3 * 2 ** 29, DIGI_D => 4 * 2 ** 29, DIGI_E => 5 * 2 ** 29); TRANS_CONF_ENABLE : constant := 1 * 2 ** 31; TRANS_CONF_ENABLED_STATUS : constant := 1 * 2 ** 30; TRANS_CONF_ENABLE_DITHER : constant := 1 * 2 ** 4; type BPC_Array is array (BPC_Type) of Word32; TRANS_CONF_BPC : constant BPC_Array := (6 => 2 * 2 ** 5, 8 => 0 * 2 ** 5, 10 => 1 * 2 ** 5, 12 => 3 * 2 ** 5, others => 0 * 2 ** 5); -- default to 8 BPC function BPC_Conf (BPC : BPC_Type; Dither : Boolean) return Word32 is begin return (if Config.Has_Pipeconf_BPC then TRANS_CONF_BPC (BPC) else 0) or (if Dither then TRANS_CONF_ENABLE_DITHER else 0); end BPC_Conf; ---------------------------------------------------------------------------- DDI_FUNC_CTL_ENABLE : constant := 1 * 2 ** 31; DDI_FUNC_CTL_MODE_SELECT_MASK : constant := 7 * 2 ** 24; DDI_FUNC_CTL_MODE_SELECT_HDMI : constant := 0 * 2 ** 24; DDI_FUNC_CTL_MODE_SELECT_DVI : constant := 1 * 2 ** 24; DDI_FUNC_CTL_MODE_SELECT_DP_SST : constant := 2 * 2 ** 24; DDI_FUNC_CTL_MODE_SELECT_DP_MST : constant := 3 * 2 ** 24; DDI_FUNC_CTL_MODE_SELECT_FDI : constant := 4 * 2 ** 24; type DDI_Select_Array is array (Digital_Port) of Word32; DDI_FUNC_CTL_DDI_SELECT : constant DDI_Select_Array := (DIGI_A => 0 * 2 ** 28, DIGI_B => 1 * 2 ** 28, DIGI_C => 2 * 2 ** 28, DIGI_D => 3 * 2 ** 28, DIGI_E => 4 * 2 ** 28); type DDI_Mode_Array is array (Display_Type) of Word32; DDI_FUNC_CTL_MODE_SELECT : constant DDI_Mode_Array := (VGA => DDI_FUNC_CTL_MODE_SELECT_FDI, HDMI => DDI_FUNC_CTL_MODE_SELECT_DVI, DP => DDI_FUNC_CTL_MODE_SELECT_DP_SST, others => 0); type HV_Sync_Array is array (Boolean) of Word32; DDI_FUNC_CTL_VSYNC : constant HV_Sync_Array := (False => 0 * 2 ** 17, True => 1 * 2 ** 17); DDI_FUNC_CTL_HSYNC : constant HV_Sync_Array := (False => 0 * 2 ** 16, True => 1 * 2 ** 16); DDI_FUNC_CTL_EDP_SELECT_MASK : constant := 7 * 2 ** 12; DDI_FUNC_CTL_EDP_SELECT_ALWAYS_ON : constant := 0 * 2 ** 12; DDI_FUNC_CTL_EDP_SELECT : constant array (Pipe_Index) of Word32 := (Primary => 4 * 2 ** 12, Secondary => 5 * 2 ** 12, Tertiary => 6 * 2 ** 12); type Port_Width_Array is array (DP_Lane_Count) of Word32; DDI_FUNC_CTL_PORT_WIDTH : constant Port_Width_Array := (DP_Lane_Count_1 => 0 * 2 ** 1, DP_Lane_Count_2 => 1 * 2 ** 1, DP_Lane_Count_4 => 3 * 2 ** 1); DDI_FUNC_CTL_BPC : constant BPC_Array := (6 => 2 * 2 ** 20, 8 => 0 * 2 ** 20, 10 => 1 * 2 ** 20, 12 => 3 * 2 ** 20, others => 0 * 2 ** 20); -- default to 8 BPC ---------------------------------------------------------------------------- TRANS_MSA_MISC_SYNC_CLK : constant := 1 * 2 ** 0; TRANS_MSA_MISC_BPC : constant BPC_Array := (6 => 0 * 2 ** 5, 8 => 1 * 2 ** 5, 10 => 2 * 2 ** 5, 12 => 3 * 2 ** 5, 16 => 4 * 2 ** 5, others => 1 * 2 ** 5); -- default to 8 BPC function TRANS_DATA_M_TU (Transfer_Unit : Positive) return Word32 is begin return Shift_Left (Word32 (Transfer_Unit - 1), 25); end TRANS_DATA_M_TU; ---------------------------------------------------------------------------- function Encode (LSW, MSW : Pos32) return Word32 is begin return Shift_Left (Word32 (MSW - 1), 16) or Word32 (LSW - 1); end Encode; ---------------------------------------------------------------------------- procedure Setup_Link (Trans : Transcoder_Regs; Link : DP_Link; Mode : Mode_Type) with Global => (In_Out => Registers.Register_State), Depends => (Registers.Register_State =>+ (Trans, Link, Mode)) is Data_M, Link_M : DP_Info.M_Type; Data_N, Link_N : DP_Info.N_Type; begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); DP_Info.Calculate_M_N (Link => Link, Mode => Mode, Data_M => Data_M, Data_N => Data_N, Link_M => Link_M, Link_N => Link_N); Registers.Write (Register => Trans.DATA_M1, Value => TRANS_DATA_M_TU (64) or Word32 (Data_M)); Registers.Write (Register => Trans.DATA_N1, Value => Word32 (Data_N)); Registers.Write (Register => Trans.LINK_M1, Value => Word32 (Link_M)); Registers.Write (Register => Trans.LINK_N1, Value => Word32 (Link_N)); if Config.Has_Pipe_MSA_Misc then Registers.Write (Register => Trans.MSA_MISC, Value => TRANS_MSA_MISC_SYNC_CLK or TRANS_MSA_MISC_BPC (Mode.BPC)); end if; end Setup_Link; ---------------------------------------------------------------------------- procedure Setup (Pipe : Pipe_Index; Port_Cfg : Port_Config) is use type HW.GFX.GMA.Registers.Registers_Invalid_Index; Trans : Transcoder_Regs renames Transcoders (Get_Idx (Pipe, Port_Cfg.Port)); M : constant Mode_Type := Port_Cfg.Mode; begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); if Config.Has_Trans_Clk_Sel and then Trans.CLK_SEL /= Registers.Invalid_Register and then Port_Cfg.Port in Digital_Port then Registers.Write (Register => Trans.CLK_SEL, Value => TRANS_CLK_SEL_PORT (Port_Cfg.Port)); end if; if Port_Cfg.Is_FDI then Setup_Link (Trans, Port_Cfg.FDI, Port_Cfg.Mode); elsif Port_Cfg.Display = DP then Setup_Link (Trans, Port_Cfg.DP, Port_Cfg.Mode); end if; Registers.Write (Trans.HTOTAL, Encode (M.H_Visible, M.H_Total)); Registers.Write (Trans.HBLANK, Encode (M.H_Visible, M.H_Total)); Registers.Write (Trans.HSYNC, Encode (M.H_Sync_Begin, M.H_Sync_End)); Registers.Write (Trans.VTOTAL, Encode (M.V_Visible, M.V_Total)); Registers.Write (Trans.VBLANK, Encode (M.V_Visible, M.V_Total)); Registers.Write (Trans.VSYNC, Encode (M.V_Sync_Begin, M.V_Sync_End)); end Setup; ---------------------------------------------------------------------------- procedure On (Pipe : Pipe_Index; Port_Cfg : Port_Config; Dither : Boolean; Scale : Boolean) is Trans : Transcoder_Regs renames Transcoders (Get_Idx (Pipe, Port_Cfg.Port)); EDP_Select : constant Word32 := (if Pipe = Primary and not Scale then DDI_FUNC_CTL_EDP_SELECT_ALWAYS_ON else DDI_FUNC_CTL_EDP_SELECT (Pipe)); begin if Config.Has_Pipe_DDI_Func and Port_Cfg.Port in Digital_Port then Registers.Write (Register => Trans.DDI_FUNC_CTL, Value => DDI_FUNC_CTL_ENABLE or DDI_FUNC_CTL_DDI_SELECT (Port_Cfg.Port) or DDI_FUNC_CTL_MODE_SELECT (Port_Cfg.Display) or DDI_FUNC_CTL_BPC (Port_Cfg.Mode.BPC) or DDI_FUNC_CTL_VSYNC (Port_Cfg.Mode.V_Sync_Active_High) or DDI_FUNC_CTL_HSYNC (Port_Cfg.Mode.H_Sync_Active_High) or EDP_Select or DDI_FUNC_CTL_PORT_WIDTH (Port_Cfg.DP.Lane_Count)); end if; Registers.Write (Register => Trans.CONF, Value => TRANS_CONF_ENABLE or (if not Config.Has_Pipeconf_Misc then BPC_Conf (Port_Cfg.Mode.BPC, Dither) else 0)); Registers.Posting_Read (Trans.CONF); end On; ---------------------------------------------------------------------------- procedure Trans_Off (Trans : Transcoder_Regs) is Enabled : Boolean; begin Registers.Is_Set_Mask (Trans.CONF, TRANS_CONF_ENABLE, Enabled); if Enabled then Registers.Unset_Mask (Trans.CONF, TRANS_CONF_ENABLE); end if; -- Workaround for Broadwell: -- Status may be wrong if pipe hasn't been enabled since reset. if not Config.Pipe_Enabled_Workaround or else Enabled then -- synchronously wait until pipe is truly off Registers.Wait_Unset_Mask (Register => Trans.CONF, Mask => TRANS_CONF_ENABLED_STATUS, TOut_MS => 40); end if; if Config.Has_Pipe_DDI_Func then Registers.Write (Trans.DDI_FUNC_CTL, 0); end if; end Trans_Off; procedure Off (Pipe : Pipe_Index) is DDI_Func_Ctl : Word32; begin if Config.Has_EDP_Transcoder then Registers.Read (Registers.PIPE_EDP_DDI_FUNC_CTL, DDI_Func_Ctl); DDI_Func_Ctl := DDI_Func_Ctl and DDI_FUNC_CTL_EDP_SELECT_MASK; if (Pipe = Primary and DDI_Func_Ctl = DDI_FUNC_CTL_EDP_SELECT_ALWAYS_ON) or DDI_Func_Ctl = DDI_FUNC_CTL_EDP_SELECT (Pipe) then Trans_Off (Transcoders (Trans_EDP)); end if; end if; Trans_Off (Transcoders (Default_Transcoder (Pipe))); end Off; procedure Clk_Off (Pipe : Pipe_Index) is use type Registers.Registers_Invalid_Index; Trans : Transcoder_Regs renames Transcoders (Default_Transcoder (Pipe)); begin if Config.Has_Trans_Clk_Sel and then Trans.CLK_SEL /= Registers.Invalid_Register then Registers.Write (Trans.CLK_SEL, TRANS_CLK_SEL_PORT_NONE); end if; end Clk_Off; end HW.GFX.GMA.Transcoder;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T P R E P -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings.Fixed; with Ada.Command_Line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; with GNAT.Heap_Sort_G; with GNAT.Command_Line; with Gnatvsn; procedure GNATprep is pragma Ident (Gnatvsn.Gnat_Version_String); Version_String : constant String := "$Revision$"; type Strptr is access String; Usage_Error : exception; -- Raised if a usage error is detected, causes termination of processing -- with an appropriate error message and error exit status set. Fatal_Error : exception; -- Exception raised if fatal error detected Expression_Error : exception; -- Exception raised when an invalid boolean expression is found -- on a preprocessor line ------------------------ -- Argument Line Data -- ------------------------ Infile_Name : Strptr; Outfile_Name : Strptr; Deffile_Name : Strptr; -- Names of files Infile : File_Type; Outfile : File_Type; Deffile : File_Type; Opt_Comment_Deleted_Lines : Boolean := False; -- Set if -c switch set Blank_Deleted_Lines : Boolean := False; -- Set if -b switch set List_Symbols : Boolean := False; -- Set if -s switch set Source_Ref_Pragma : Boolean := False; -- Set if -r switch set Undefined_Is_False : Boolean := False; -- Set if -u switch set -- Record command line options --------------------------- -- Definitions File Data -- --------------------------- Num_Syms : Natural := 0; -- Number of symbols defined in definitions file Symbols : array (0 .. 10_000) of Strptr; Values : array (0 .. 10_000) of Strptr; -- Symbol names and values. Note that the zero'th element is used only -- during the call to Sort (to hold a temporary value, as required by -- the GNAT.Heap_Sort_G interface). --------------------- -- Input File Data -- --------------------- Current_File_Name : Strptr; -- Holds name of file being read (definitions file or input file) Line_Buffer : String (1 .. 20_000); -- Hold one line Line_Length : Natural; -- Length of line in Line_Buffer Line_Num : Natural; -- Current input file line number Ptr : Natural; -- Input scan pointer for line in Line_Buffer type Keyword is (K_Not, K_Then, K_If, K_Else, K_End, K_Elsif, K_And, K_Or, K_Open_Paren, K_Close_Paren, K_Defined, K_Andthen, K_Orelse, K_Equal, K_None); -- Keywords that are recognized on preprocessor lines. K_None indicates -- that no keyword was present. K : Keyword; -- Scanned keyword Start_Sym, End_Sym : Natural; -- First and last positions of scanned symbol Num_Errors : Natural := 0; -- Number of errors detected ----------------------- -- Preprocessor Data -- ----------------------- -- The following record represents the state of an #if structure: type PP_Rec is record If_Line : Positive; -- Line number for #if line Else_Line : Natural; -- Line number for #else line, zero = no else seen yet Deleting : Boolean; -- True if lines currently being deleted Match_Seen : Boolean; -- True if either the #if condition or one of the previously seen -- #elsif lines was true, meaning that any future #elsif sections -- or the #else section, is to be deleted. end record; PP_Depth : Natural; -- Preprocessor #if nesting level. A value of zero means that we are -- outside any #if structure. PP : array (0 .. 100) of PP_Rec; -- Stack of records showing state of #if structures. PP (1) is the -- outer level entry, and PP (PP_Depth) is the active entry. PP (0) -- contains a dummy entry whose Deleting flag is always set to False. ----------------- -- Subprograms -- ----------------- function At_End_Of_Line return Boolean; -- First advances Ptr using Skip_Spaces. Then returns True if Ptr is -- either at the end of the line, or at a -- comment sequence. procedure Error (Msg : String); -- Post error message with given text. The line number is taken from -- Line_Num, and the column number from Ptr. function Eval_Condition (Parenthesis : Natural := 0; Do_Eval : Boolean := True) return Boolean; -- Eval the condition found in the current Line. The condition can -- include any of the 'and', 'or', 'not', and parenthesis subexpressions. -- If Line is an invalid expression, then Expression_Error is raised, -- after an error message has been printed. Line can include 'then' -- followed by a comment, which is automatically ignored. If Do_Eval -- is False, then the expression is not evaluated at all, and symbols -- are just skipped. function Eval_Symbol (Do_Eval : Boolean) return Boolean; -- Read and evaluate the next symbol or expression (A, A'Defined, A=...) -- If it is followed by 'Defined or an equality test, read as many symbols -- as needed. Do_Eval has the same meaning as in Eval_Condition procedure Help_Page; -- Print a help page to summarize the usage of gnatprep function Is_Preprocessor_Line return Boolean; -- Tests if current line is a preprocessor line, i.e. that its first -- non-blank character is a # character. If so, then a result of True -- is returned, and Ptr is set to point to the character following the -- # character. If not, False is returned and Ptr is undefined. procedure No_Junk; -- Make sure no junk is present on a preprocessor line. Ptr points past -- the scanned preprocessor syntax. function OK_Identifier (S : String) return Boolean; -- Tests if given referenced string is valid Ada identifier function Matching_Strings (S1, S2 : String) return Boolean; -- Check if S1 and S2 are the same string (this is a case independent -- comparison, lower and upper case letters are considered to match). -- Duplicate quotes in S2 are considered as a single quote ("" => ") procedure Parse_Def_File; -- Parse the deffile given by the user function Scan_Keyword return Keyword; -- Advances Ptr to end of line or next non-blank using Skip_Spaces. Then -- attempts to scan out a recognized keyword. if a recognized keyword is -- found, sets Ptr past it, and returns the code for the keyword, if not, -- then Ptr is left unchanged pointing to a non-blank character or to the -- end of the line. function Symbol_Scanned return Boolean; -- On entry, Start_Sym is set to the first character of an identifier -- symbol to be scanned out. On return, End_Sym is set to the last -- character of the identifier, and the result indicates if the scanned -- symbol is a valid identifier (True = valid). Ptr is not changed. procedure Skip_Spaces; -- Skips Ptr past tabs and spaces to next non-blank, or one character -- past the end of line. function Variable_Index (Name : String) return Natural; -- Returns the index of the variable in the table. If the variable is not -- found, returns Natural'Last -------------------- -- At_End_Of_Line -- -------------------- function At_End_Of_Line return Boolean is begin Skip_Spaces; return Ptr > Line_Length or else (Ptr < Line_Length and then Line_Buffer (Ptr .. Ptr + 1) = "--"); end At_End_Of_Line; ----------- -- Error -- ----------- procedure Error (Msg : String) is L : constant String := Natural'Image (Line_Num); C : constant String := Natural'Image (Ptr); begin Put (Standard_Error, Current_File_Name.all); Put (Standard_Error, ':'); Put (Standard_Error, L (2 .. L'Length)); Put (Standard_Error, ':'); Put (Standard_Error, C (2 .. C'Length)); Put (Standard_Error, ": "); Put_Line (Standard_Error, Msg); Num_Errors := Num_Errors + 1; end Error; -------------------- -- Eval_Condition -- -------------------- function Eval_Condition (Parenthesis : Natural := 0; Do_Eval : Boolean := True) return Boolean is Symbol_Is_True : Boolean := False; -- init to avoid warning K : Keyword; begin -- Find the next subexpression K := Scan_Keyword; case K is when K_None => Symbol_Is_True := Eval_Symbol (Do_Eval); when K_Not => -- Not applies to the next subexpression (either a simple -- evaluation like A or A'Defined, or a parenthesis expression) K := Scan_Keyword; if K = K_Open_Paren then Symbol_Is_True := not Eval_Condition (Parenthesis + 1, Do_Eval); elsif K = K_None then Symbol_Is_True := not Eval_Symbol (Do_Eval); else Ptr := Start_Sym; -- Puts the keyword back end if; when K_Open_Paren => Symbol_Is_True := Eval_Condition (Parenthesis + 1, Do_Eval); when others => Ptr := Start_Sym; Error ("invalid syntax in preprocessor line"); raise Expression_Error; end case; -- Do we have a compound expression with AND, OR, ... K := Scan_Keyword; case K is when K_None => if not At_End_Of_Line then Error ("Invalid Syntax at end of line"); raise Expression_Error; end if; if Parenthesis /= 0 then Error ("Unmatched opening parenthesis"); raise Expression_Error; end if; return Symbol_Is_True; when K_Then => if Parenthesis /= 0 then Error ("Unmatched opening parenthesis"); raise Expression_Error; end if; return Symbol_Is_True; when K_Close_Paren => if Parenthesis = 0 then Error ("Unmatched closing parenthesis"); raise Expression_Error; end if; return Symbol_Is_True; when K_And => return Symbol_Is_True and Eval_Condition (Parenthesis, Do_Eval); when K_Andthen => if not Symbol_Is_True then -- Just skip the symbols for the remaining part Symbol_Is_True := Eval_Condition (Parenthesis, False); return False; else return Eval_Condition (Parenthesis, Do_Eval); end if; when K_Or => return Symbol_Is_True or Eval_Condition (Parenthesis, Do_Eval); when K_Orelse => if Symbol_Is_True then -- Just skip the symbols for the remaining part Symbol_Is_True := Eval_Condition (Parenthesis, False); return True; else return Eval_Condition (Parenthesis, Do_Eval); end if; when others => Error ("invalid syntax in preprocessor line"); raise Expression_Error; end case; end Eval_Condition; ----------------- -- Eval_Symbol -- ----------------- function Eval_Symbol (Do_Eval : Boolean) return Boolean is Sym : constant String := Line_Buffer (Start_Sym .. End_Sym); K : Keyword; Index : Natural; Symbol_Defined : Boolean := False; Symbol_Is_True : Boolean := False; begin -- Read the symbol Skip_Spaces; Start_Sym := Ptr; if not Symbol_Scanned then Error ("invalid symbol name"); raise Expression_Error; end if; Ptr := End_Sym + 1; -- Test if we have a simple test (A) or a more complicated one -- (A'Defined) K := Scan_Keyword; if K /= K_Defined and then K /= K_Equal then Ptr := Start_Sym; -- Puts the keyword back end if; Index := Variable_Index (Sym); case K is when K_Defined => Symbol_Defined := Index /= Natural'Last; Symbol_Is_True := Symbol_Defined; when K_Equal => -- Read the second part of the statement Skip_Spaces; Start_Sym := Ptr; if not Symbol_Scanned and then End_Sym < Start_Sym then Error ("No right part for the equality test"); raise Expression_Error; end if; Ptr := End_Sym + 1; -- If the variable was not found if Do_Eval then if Index = Natural'Last then if not Undefined_Is_False then Error ("symbol name """ & Sym & """ is not defined in definitions file"); end if; else declare Right : constant String := Line_Buffer (Start_Sym .. End_Sym); Index_R : Natural; begin if Right (Right'First) = '"' then Symbol_Is_True := Matching_Strings (Values (Index).all, Right (Right'First + 1 .. Right'Last - 1)); else Index_R := Variable_Index (Right); if Index_R = Natural'Last then Error ("Variable " & Right & " in test is " & "not defined"); raise Expression_Error; else Symbol_Is_True := Matching_Strings (Values (Index).all, Values (Index_R).all); end if; end if; end; end if; end if; when others => if Index = Natural'Last then Symbol_Defined := False; if Do_Eval and then not Symbol_Defined then if Undefined_Is_False then Symbol_Defined := True; Symbol_Is_True := False; else Error ("symbol name """ & Sym & """ is not defined in definitions file"); end if; end if; elsif not Do_Eval then Symbol_Is_True := True; elsif Matching_Strings (Values (Index).all, "True") then Symbol_Is_True := True; elsif Matching_Strings (Values (Index).all, "False") then Symbol_Is_True := False; else Error ("symbol value is not True or False"); Symbol_Is_True := False; end if; end case; return Symbol_Is_True; end Eval_Symbol; --------------- -- Help_Page -- --------------- procedure Help_Page is begin Put_Line (Standard_Error, "GNAT Preprocessor Version " & Version_String (12 .. 15) & " Copyright 1996-2001 Free Software Foundation, Inc."); Put_Line (Standard_Error, "Usage: gnatprep [-bcrsu] [-Dsymbol=value] infile " & "outfile [deffile]"); New_Line (Standard_Error); Put_Line (Standard_Error, " infile Name of the input file"); Put_Line (Standard_Error, " outfile Name of the output file"); Put_Line (Standard_Error, " deffile Name of the definition file"); New_Line (Standard_Error); Put_Line (Standard_Error, "gnatprep switches:"); Put_Line (Standard_Error, " -b Replace preprocessor lines by " & "blank lines"); Put_Line (Standard_Error, " -c Keep preprocessor lines as comments"); Put_Line (Standard_Error, " -D Associate symbol with value"); Put_Line (Standard_Error, " -r Generate Source_Reference pragma"); Put_Line (Standard_Error, " -s Print a sorted list of symbol names " & "and values"); Put_Line (Standard_Error, " -u Treat undefined symbols as FALSE"); New_Line (Standard_Error); end Help_Page; -------------------------- -- Is_Preprocessor_Line -- -------------------------- function Is_Preprocessor_Line return Boolean is begin Ptr := 1; while Ptr <= Line_Length loop if Line_Buffer (Ptr) = '#' then Ptr := Ptr + 1; return True; elsif Line_Buffer (Ptr) > ' ' then return False; else Ptr := Ptr + 1; end if; end loop; return False; end Is_Preprocessor_Line; ---------------------- -- Matching_Strings -- ---------------------- function Matching_Strings (S1, S2 : String) return Boolean is S2_Index : Integer := S2'First; begin for S1_Index in S1'Range loop if To_Upper (S1 (S1_Index)) /= To_Upper (S2 (S2_Index)) then return False; else if S2 (S2_Index) = '"' and then S2_Index < S2'Last and then S2 (S2_Index + 1) = '"' then S2_Index := S2_Index + 2; else S2_Index := S2_Index + 1; end if; -- If S2 was too short then if S2_Index > S2'Last and then S1_Index < S1'Last then return False; end if; end if; end loop; return S2_Index = S2'Last + 1; end Matching_Strings; ------------- -- No_Junk -- ------------- procedure No_Junk is begin Skip_Spaces; if Ptr = Line_Length or else (Ptr < Line_Length and then Line_Buffer (Ptr .. Ptr + 1) /= "--") then Error ("extraneous text on preprocessor line ignored"); end if; end No_Junk; ------------------- -- OK_Identifier -- ------------------- function OK_Identifier (S : String) return Boolean is P : Natural := S'First; begin if S'Length /= 0 and then S (P) = Character'Val (39) then -- ''' P := P + 1; end if; if S'Length = 0 or else not Is_Letter (S (P)) then return False; else while P <= S'Last loop if Is_Letter (S (P)) or Is_Digit (S (P)) then null; elsif S (P) = '_' and then P < S'Last and then S (P + 1) /= '_' then null; else return False; end if; P := P + 1; end loop; return True; end if; end OK_Identifier; -------------------- -- Parse_Def_File -- -------------------- procedure Parse_Def_File is begin Open (Deffile, In_File, Deffile_Name.all); Line_Num := 0; Current_File_Name := Deffile_Name; -- Loop through lines in symbol definitions file while not End_Of_File (Deffile) loop Get_Line (Deffile, Line_Buffer, Line_Length); Line_Num := Line_Num + 1; Ptr := 1; Skip_Spaces; if Ptr > Line_Length or else (Ptr < Line_Length and then Line_Buffer (Ptr .. Ptr + 1) = "--") then goto Continue; end if; Start_Sym := Ptr; if not Symbol_Scanned then Error ("invalid symbol identifier """ & Line_Buffer (Start_Sym .. End_Sym) & '"'); goto Continue; end if; Ptr := End_Sym + 1; Skip_Spaces; if Ptr >= Line_Length or else Line_Buffer (Ptr .. Ptr + 1) /= ":=" then Error ("missing "":="" in symbol definition line"); goto Continue; end if; Ptr := Ptr + 2; Skip_Spaces; Num_Syms := Num_Syms + 1; Symbols (Num_Syms) := new String'(Line_Buffer (Start_Sym .. End_Sym)); Start_Sym := Ptr; End_Sym := Ptr - 1; if At_End_Of_Line then null; elsif Line_Buffer (Start_Sym) = '"' then End_Sym := End_Sym + 1; loop End_Sym := End_Sym + 1; if End_Sym > Line_Length then Error ("no closing quote for string constant"); goto Continue; elsif End_Sym < Line_Length and then Line_Buffer (End_Sym .. End_Sym + 1) = """""" then End_Sym := End_Sym + 1; elsif Line_Buffer (End_Sym) = '"' then exit; end if; end loop; else End_Sym := Ptr - 1; while End_Sym < Line_Length and then (Is_Alphanumeric (Line_Buffer (End_Sym + 1)) or else Line_Buffer (End_Sym + 1) = '_' or else Line_Buffer (End_Sym + 1) = '.') loop End_Sym := End_Sym + 1; end loop; Ptr := End_Sym + 1; if not At_End_Of_Line then Error ("incorrect symbol value syntax"); goto Continue; end if; end if; Values (Num_Syms) := new String'(Line_Buffer (Start_Sym .. End_Sym)); <<Continue>> null; end loop; exception -- Could not open the file when Name_Error => Put_Line (Standard_Error, "cannot open " & Deffile_Name.all); raise Fatal_Error; end Parse_Def_File; ------------------ -- Scan_Keyword -- ------------------ function Scan_Keyword return Keyword is Kptr : constant Natural := Ptr; begin Skip_Spaces; Start_Sym := Ptr; if Symbol_Scanned then -- If the symbol was the last thing on the line, End_Sym will -- point too far in Line_Buffer if End_Sym > Line_Length then End_Sym := Line_Length; end if; Ptr := End_Sym + 1; declare Sym : constant String := Line_Buffer (Start_Sym .. End_Sym); begin if Matching_Strings (Sym, "not") then return K_Not; elsif Matching_Strings (Sym, "then") then return K_Then; elsif Matching_Strings (Sym, "if") then return K_If; elsif Matching_Strings (Sym, "else") then return K_Else; elsif Matching_Strings (Sym, "end") then return K_End; elsif Matching_Strings (Sym, "elsif") then return K_Elsif; elsif Matching_Strings (Sym, "and") then if Scan_Keyword = K_Then then Start_Sym := Kptr; return K_Andthen; else Ptr := Start_Sym; -- Put back the last keyword read Start_Sym := Kptr; return K_And; end if; elsif Matching_Strings (Sym, "or") then if Scan_Keyword = K_Else then Start_Sym := Kptr; return K_Orelse; else Ptr := Start_Sym; -- Put back the last keyword read Start_Sym := Kptr; return K_Or; end if; elsif Matching_Strings (Sym, "'defined") then return K_Defined; elsif Sym = "(" then return K_Open_Paren; elsif Sym = ")" then return K_Close_Paren; elsif Sym = "=" then return K_Equal; end if; end; end if; Ptr := Kptr; return K_None; end Scan_Keyword; ----------------- -- Skip_Spaces -- ----------------- procedure Skip_Spaces is begin while Ptr <= Line_Length loop if Line_Buffer (Ptr) /= ' ' and then Line_Buffer (Ptr) /= ASCII.HT then return; else Ptr := Ptr + 1; end if; end loop; end Skip_Spaces; -------------------- -- Symbol_Scanned -- -------------------- function Symbol_Scanned return Boolean is begin End_Sym := Start_Sym - 1; case Line_Buffer (End_Sym + 1) is when '(' | ')' | '=' => End_Sym := End_Sym + 1; return True; when '"' => End_Sym := End_Sym + 1; while End_Sym < Line_Length loop if Line_Buffer (End_Sym + 1) = '"' then if End_Sym + 2 < Line_Length and then Line_Buffer (End_Sym + 2) = '"' then End_Sym := End_Sym + 2; else exit; end if; else End_Sym := End_Sym + 1; end if; end loop; if End_Sym >= Line_Length then Error ("Invalid string "); raise Expression_Error; end if; End_Sym := End_Sym + 1; return False; when ''' => End_Sym := End_Sym + 1; when others => null; end case; while End_Sym < Line_Length and then (Is_Alphanumeric (Line_Buffer (End_Sym + 1)) or else Line_Buffer (End_Sym + 1) = '_') loop End_Sym := End_Sym + 1; end loop; return OK_Identifier (Line_Buffer (Start_Sym .. End_Sym)); end Symbol_Scanned; -------------------- -- Variable_Index -- -------------------- function Variable_Index (Name : String) return Natural is begin for J in 1 .. Num_Syms loop if Matching_Strings (Symbols (J).all, Name) then return J; end if; end loop; return Natural'Last; end Variable_Index; -- Start of processing for GNATprep begin -- Parse the switches loop case GNAT.Command_Line.Getopt ("D: b c r s u") is when ASCII.NUL => exit; when 'D' => declare S : String := GNAT.Command_Line.Parameter; Index : Natural; begin Index := Ada.Strings.Fixed.Index (S, "="); if Index = 0 then Num_Syms := Num_Syms + 1; Symbols (Num_Syms) := new String'(S); Values (Num_Syms) := new String'("True"); else Num_Syms := Num_Syms + 1; Symbols (Num_Syms) := new String'(S (S'First .. Index - 1)); Values (Num_Syms) := new String'(S (Index + 1 .. S'Last)); end if; end; when 'b' => Blank_Deleted_Lines := True; when 'c' => Opt_Comment_Deleted_Lines := True; when 'r' => Source_Ref_Pragma := True; when 's' => List_Symbols := True; when 'u' => Undefined_Is_False := True; when others => raise Usage_Error; end case; end loop; -- Get the file names loop declare S : constant String := GNAT.Command_Line.Get_Argument; begin exit when S'Length = 0; if Infile_Name = null then Infile_Name := new String'(S); elsif Outfile_Name = null then Outfile_Name := new String'(S); elsif Deffile_Name = null then Deffile_Name := new String'(S); else raise Usage_Error; end if; end; end loop; -- Test we had all the arguments needed if Infile_Name = null or else Outfile_Name = null then raise Usage_Error; end if; if Source_Ref_Pragma and (not Opt_Comment_Deleted_Lines) then Blank_Deleted_Lines := True; end if; -- Get symbol definitions if Deffile_Name /= null then Parse_Def_File; end if; if Num_Errors > 0 then raise Fatal_Error; elsif List_Symbols and then Num_Syms > 0 then List_Symbols_Case : declare function Lt (Op1, Op2 : Natural) return Boolean; -- Comparison routine for sort call procedure Move (From : Natural; To : Natural); -- Move routine for sort call function Lt (Op1, Op2 : Natural) return Boolean is L1 : constant Natural := Symbols (Op1)'Length; L2 : constant Natural := Symbols (Op2)'Length; MinL : constant Natural := Natural'Min (L1, L2); C1, C2 : Character; begin for J in 0 .. MinL - 1 loop C1 := To_Upper (Symbols (Op1).all (Symbols (Op1)'First + J)); C2 := To_Upper (Symbols (Op2).all (Symbols (Op2)'First + J)); if C1 < C2 then return True; elsif C1 > C2 then return False; end if; end loop; return L1 < L2; end Lt; procedure Move (From : Natural; To : Natural) is begin Symbols (To) := Symbols (From); Values (To) := Values (From); end Move; package Sort_Syms is new GNAT.Heap_Sort_G (Move, Lt); Max_L : Natural; -- Maximum length of any symbol -- Start of processing for List_Symbols_Case begin Sort_Syms.Sort (Num_Syms); Max_L := 7; for J in 1 .. Num_Syms loop Max_L := Natural'Max (Max_L, Symbols (J)'Length); end loop; New_Line; Put ("Symbol"); for J in 1 .. Max_L - 5 loop Put (' '); end loop; Put_Line ("Value"); Put ("------"); for J in 1 .. Max_L - 5 loop Put (' '); end loop; Put_Line ("------"); for J in 1 .. Num_Syms loop Put (Symbols (J).all); for K in 1 .. Max_L - Symbols (J)'Length + 1 loop Put (' '); end loop; Put_Line (Values (J).all); end loop; New_Line; end List_Symbols_Case; end if; -- Open files and initialize preprocessing begin Open (Infile, In_File, Infile_Name.all); exception when Name_Error => Put_Line (Standard_Error, "cannot open " & Infile_Name.all); raise Fatal_Error; end; begin Create (Outfile, Out_File, Outfile_Name.all); exception when Name_Error => Put_Line (Standard_Error, "cannot create " & Outfile_Name.all); raise Fatal_Error; end; if Source_Ref_Pragma then Put_Line (Outfile, "pragma Source_Reference (1, """ & Infile_Name.all & """);"); end if; Line_Num := 0; Current_File_Name := Infile_Name; PP_Depth := 0; PP (0).Deleting := False; -- Loop through lines in input file while not End_Of_File (Infile) loop Get_Line (Infile, Line_Buffer, Line_Length); Line_Num := Line_Num + 1; -- Handle preprocessor line if Is_Preprocessor_Line then K := Scan_Keyword; case K is -- If/Elsif processing when K_If | K_Elsif => -- If differs from elsif only in that an initial stack entry -- must be made for the new if range. We set the match seen -- entry to a copy of the deleting status in the range above -- us. If we are deleting in the range above us, then we want -- all the branches of the nested #if to delete. if K = K_If then PP_Depth := PP_Depth + 1; PP (PP_Depth) := (If_Line => Line_Num, Else_Line => 0, Deleting => False, Match_Seen => PP (PP_Depth - 1).Deleting); elsif PP_Depth = 0 then Error ("no matching #if for this #elsif"); goto Output; end if; PP (PP_Depth).Deleting := True; if not PP (PP_Depth).Match_Seen and then Eval_Condition = True then -- Case of match and no match yet in this #if PP (PP_Depth).Deleting := False; PP (PP_Depth).Match_Seen := True; No_Junk; end if; -- Processing for #else when K_Else => if PP_Depth = 0 then Error ("no matching #if for this #else"); elsif PP (PP_Depth).Else_Line /= 0 then Error ("duplicate #else line (previous was on line" & Natural'Image (PP (PP_Depth).Else_Line) & ")"); else PP (PP_Depth).Else_Line := Line_Num; PP (PP_Depth).Deleting := PP (PP_Depth).Match_Seen; end if; No_Junk; -- Process for #end when K_End => if PP_Depth = 0 then Error ("no matching #if for this #end"); else Skip_Spaces; if Scan_Keyword /= K_If then Error ("expected if after #end"); Ptr := Line_Length + 1; end if; Skip_Spaces; if Ptr > Line_Length or else Line_Buffer (Ptr) /= ';' then Error ("missing semicolon after #end if"); else Ptr := Ptr + 1; end if; No_Junk; PP_Depth := PP_Depth - 1; end if; when others => Error ("invalid preprocessor keyword syntax"); end case; -- Handle symbol substitution -- Substitution is not allowed in string (which we simply skip), -- but is allowed inside character constants. The last case is -- because there is no way to know whether the user want to -- substitute the name of an attribute ('Min or 'Max for instance) -- or actually meant to substitue a character ('$name' is probably -- a character constant, but my_type'$name'Min is probably an -- attribute, with $name=Base) else Ptr := 1; while Ptr < Line_Length loop exit when At_End_Of_Line; case Line_Buffer (Ptr) is when ''' => -- Two special cases here: -- '"' => we don't want the " sign to appear as belonging -- to a string. -- '$' => this is obviously not a substitution, just skip it if Ptr < Line_Length - 1 and then Line_Buffer (Ptr + 1) = '"' then Ptr := Ptr + 2; elsif Ptr < Line_Length - 2 and then Line_Buffer (Ptr + 1 .. Ptr + 2) = "$'" then Ptr := Ptr + 2; end if; when '"' => -- The special case of "" inside the string is easy to -- handle: just ignore them. The second one will be seen -- as the beginning of a second string Ptr := Ptr + 1; while Ptr < Line_Length and then Line_Buffer (Ptr) /= '"' loop Ptr := Ptr + 1; end loop; when '$' => -- $ found, so scan out possible following symbol Start_Sym := Ptr + 1; if Symbol_Scanned then -- Look up symbol in table and if found do replacement for J in 1 .. Num_Syms loop if Matching_Strings (Symbols (J).all, Line_Buffer (Start_Sym .. End_Sym)) then declare OldL : constant Positive := End_Sym - Start_Sym + 2; NewL : constant Positive := Values (J)'Length; AdjL : constant Integer := NewL - OldL; NewP : constant Positive := Ptr + NewL - 1; begin Line_Buffer (NewP + 1 .. Line_Length + AdjL) := Line_Buffer (End_Sym + 1 .. Line_Length); Line_Buffer (Ptr .. NewP) := Values (J).all; Ptr := NewP; Line_Length := Line_Length + AdjL; end; exit; end if; end loop; end if; when others => null; end case; Ptr := Ptr + 1; end loop; end if; -- Here after dealing with preprocessor line, output current line <<Output>> if Is_Preprocessor_Line or else PP (PP_Depth).Deleting then if Blank_Deleted_Lines then New_Line (Outfile); elsif Opt_Comment_Deleted_Lines then if Line_Length = 0 then Put_Line (Outfile, "--!"); else Put (Outfile, "--! "); Put_Line (Outfile, Line_Buffer (1 .. Line_Length)); end if; end if; else Put_Line (Outfile, Line_Buffer (1 .. Line_Length)); end if; end loop; for J in 1 .. PP_Depth loop Error ("no matching #end for #if at line" & Natural'Image (PP (J).If_Line)); end loop; if Num_Errors = 0 then Close (Outfile); Set_Exit_Status (0); else Delete (Outfile); Set_Exit_Status (1); end if; exception when Usage_Error => Help_Page; Set_Exit_Status (1); when GNAT.Command_Line.Invalid_Parameter => Put_Line (Standard_Error, "No parameter given for -" & GNAT.Command_Line.Full_Switch); Help_Page; Set_Exit_Status (1); when GNAT.Command_Line.Invalid_Switch => Put_Line (Standard_Error, "Invalid Switch: -" & GNAT.Command_Line.Full_Switch); Help_Page; Set_Exit_Status (1); when Fatal_Error => Set_Exit_Status (1); when Expression_Error => Set_Exit_Status (1); end GNATprep;
with Dynamic_Elab_Pkg; use Dynamic_Elab_Pkg; package Dynamic_Elab2 is type Plot is record B : Boolean; Data : R; end record; pragma Pack (Plot); function Get_Plot return Plot; end Dynamic_Elab2;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 8 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Exp_Ch4; use Exp_Ch4; with Exp_Ch6; use Exp_Ch6; with Exp_Dbug; use Exp_Dbug; with Exp_Util; use Exp_Util; with Freeze; use Freeze; with Namet; use Namet; with Nmake; use Nmake; with Nlists; use Nlists; with Opt; use Opt; with Sem; use Sem; with Sem_Ch8; use Sem_Ch8; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Tbuild; use Tbuild; package body Exp_Ch8 is --------------------------------------------- -- Expand_N_Exception_Renaming_Declaration -- --------------------------------------------- procedure Expand_N_Exception_Renaming_Declaration (N : Node_Id) is Decl : Node_Id; begin Decl := Debug_Renaming_Declaration (N); if Present (Decl) then Insert_Action (N, Decl); end if; end Expand_N_Exception_Renaming_Declaration; ------------------------------------------ -- Expand_N_Object_Renaming_Declaration -- ------------------------------------------ -- Most object renaming cases can be done by just capturing the address -- of the renamed object. The cases in which this is not true are when -- this address is not computable, since it involves extraction of a -- packed array element, or of a record component to which a component -- clause applies (that can specify an arbitrary bit boundary), or where -- the enclosing record itself has a non-standard representation. -- In these two cases, we pre-evaluate the renaming expression, by -- extracting and freezing the values of any subscripts, and then we -- set the flag Is_Renaming_Of_Object which means that any reference -- to the object will be handled by macro substitution in the front -- end, and the back end will know to ignore the renaming declaration. -- An additional odd case that requires processing by expansion is -- the renaming of a discriminant of a mutable record type. The object -- is a constant because it renames something that cannot be assigned to, -- but in fact the underlying value can change and must be reevaluated -- at each reference. Gigi does have a notion of a "constant view" of -- an object, and therefore the front-end must perform the expansion. -- For simplicity, and to bypass some obscure code-generation problem, -- we use macro substitution for all renamed discriminants, whether the -- enclosing type is constrained or not. -- The other special processing required is for the case of renaming -- of an object of a class wide type, where it is necessary to build -- the appropriate subtype for the renamed object. -- More comments needed for this para ??? procedure Expand_N_Object_Renaming_Declaration (N : Node_Id) is Nam : constant Node_Id := Name (N); Decl : Node_Id; T : Entity_Id; function Evaluation_Required (Nam : Node_Id) return Boolean; -- Determines whether it is necessary to do static name evaluation for -- renaming of Nam. It is considered necessary if evaluating the name -- involves indexing a packed array, or extracting a component of a -- record to which a component clause applies. Note that we are only -- interested in these operations if they occur as part of the name -- itself, subscripts are just values that are computed as part of the -- evaluation, so their form is unimportant. -- In addition, always return True for Modify_Tree_For_C since the -- code generator doesn't know how to handle renamings. ------------------------- -- Evaluation_Required -- ------------------------- function Evaluation_Required (Nam : Node_Id) return Boolean is begin if Modify_Tree_For_C then return True; elsif Nkind_In (Nam, N_Indexed_Component, N_Slice) then if Is_Packed (Etype (Prefix (Nam))) then return True; else return Evaluation_Required (Prefix (Nam)); end if; elsif Nkind (Nam) = N_Selected_Component then declare Rec_Type : constant Entity_Id := Etype (Prefix (Nam)); begin if Present (Component_Clause (Entity (Selector_Name (Nam)))) or else Has_Non_Standard_Rep (Rec_Type) then return True; elsif Ekind (Entity (Selector_Name (Nam))) = E_Discriminant and then Is_Record_Type (Rec_Type) and then not Is_Concurrent_Record_Type (Rec_Type) then return True; else return Evaluation_Required (Prefix (Nam)); end if; end; else return False; end if; end Evaluation_Required; -- Start of processing for Expand_N_Object_Renaming_Declaration begin -- Perform name evaluation if required if Evaluation_Required (Nam) then Evaluate_Name (Nam); Set_Is_Renaming_Of_Object (Defining_Identifier (N)); end if; -- Deal with construction of subtype in class-wide case T := Etype (Defining_Identifier (N)); if Is_Class_Wide_Type (T) then Expand_Subtype_From_Expr (N, T, Subtype_Mark (N), Name (N)); Find_Type (Subtype_Mark (N)); Set_Etype (Defining_Identifier (N), Entity (Subtype_Mark (N))); -- Freeze the class-wide subtype here to ensure that the subtype -- and equivalent type are frozen before the renaming. Freeze_Before (N, Entity (Subtype_Mark (N))); end if; -- Ada 2005 (AI-318-02): If the renamed object is a call to a build-in- -- place function, then a temporary return object needs to be created -- and access to it must be passed to the function. Currently we limit -- such functions to those with inherently limited result subtypes, but -- eventually we plan to expand the functions that are treated as -- build-in-place to include other composite result types. if Ada_Version >= Ada_2005 and then Is_Build_In_Place_Function_Call (Nam) then Make_Build_In_Place_Call_In_Anonymous_Context (Nam); end if; -- Create renaming entry for debug information Decl := Debug_Renaming_Declaration (N); if Present (Decl) then Insert_Action (N, Decl); end if; end Expand_N_Object_Renaming_Declaration; ------------------------------------------- -- Expand_N_Package_Renaming_Declaration -- ------------------------------------------- procedure Expand_N_Package_Renaming_Declaration (N : Node_Id) is Decl : Node_Id; begin Decl := Debug_Renaming_Declaration (N); if Present (Decl) then -- If we are in a compilation unit, then this is an outer -- level declaration, and must have a scope of Standard if Nkind (Parent (N)) = N_Compilation_Unit then declare Aux : constant Node_Id := Aux_Decls_Node (Parent (N)); begin Push_Scope (Standard_Standard); if No (Actions (Aux)) then Set_Actions (Aux, New_List (Decl)); else Append (Decl, Actions (Aux)); end if; Analyze (Decl); -- Enter the debug variable in the qualification list, which -- must be done at this point because auxiliary declarations -- occur at the library level and aren't associated with a -- normal scope. Qualify_Entity_Names (Decl); Pop_Scope; end; -- Otherwise, just insert after the package declaration else Insert_Action (N, Decl); end if; end if; end Expand_N_Package_Renaming_Declaration; ---------------------------------------------- -- Expand_N_Subprogram_Renaming_Declaration -- ---------------------------------------------- procedure Expand_N_Subprogram_Renaming_Declaration (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Id : constant Entity_Id := Defining_Entity (N); function Build_Body_For_Renaming return Node_Id; -- Build and return the body for the renaming declaration of an equality -- or inequality operator. ----------------------------- -- Build_Body_For_Renaming -- ----------------------------- function Build_Body_For_Renaming return Node_Id is Body_Id : Entity_Id; Decl : Node_Id; begin Set_Alias (Id, Empty); Set_Has_Completion (Id, False); Rewrite (N, Make_Subprogram_Declaration (Sloc (N), Specification => Specification (N))); Set_Has_Delayed_Freeze (Id); Body_Id := Make_Defining_Identifier (Sloc (N), Chars (Id)); Set_Debug_Info_Needed (Body_Id); Decl := Make_Subprogram_Body (Loc, Specification => Make_Function_Specification (Loc, Defining_Unit_Name => Body_Id, Parameter_Specifications => Copy_Parameter_List (Id), Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)), Declarations => Empty_List, Handled_Statement_Sequence => Empty); return Decl; end Build_Body_For_Renaming; -- Local variables Nam : constant Node_Id := Name (N); -- Start of processing for Expand_N_Subprogram_Renaming_Declaration begin -- When the prefix of the name is a function call, we must force the -- call to be made by removing side effects from the call, since we -- must only call the function once. if Nkind (Nam) = N_Selected_Component and then Nkind (Prefix (Nam)) = N_Function_Call then Remove_Side_Effects (Prefix (Nam)); -- For an explicit dereference, the prefix must be captured to prevent -- reevaluation on calls through the renaming, which could result in -- calling the wrong subprogram if the access value were to be changed. elsif Nkind (Nam) = N_Explicit_Dereference then Force_Evaluation (Prefix (Nam)); end if; -- Handle cases where we build a body for a renamed equality if Is_Entity_Name (Nam) and then Chars (Entity (Nam)) = Name_Op_Eq and then Scope (Entity (Nam)) = Standard_Standard then declare Left : constant Entity_Id := First_Formal (Id); Right : constant Entity_Id := Next_Formal (Left); Typ : constant Entity_Id := Etype (Left); Decl : Node_Id; begin -- Check whether this is a renaming of a predefined equality on an -- untagged record type (AI05-0123). if Ada_Version >= Ada_2012 and then Is_Record_Type (Typ) and then not Is_Tagged_Type (Typ) and then not Is_Frozen (Typ) then -- Build body for renamed equality, to capture its current -- meaning. It may be redefined later, but the renaming is -- elaborated where it occurs. This is technically known as -- Squirreling semantics. Renaming is rewritten as a subprogram -- declaration, and the generated body is inserted into the -- freeze actions for the subprogram. Decl := Build_Body_For_Renaming; Set_Handled_Statement_Sequence (Decl, Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Simple_Return_Statement (Loc, Expression => Expand_Record_Equality (Id, Typ => Typ, Lhs => Make_Identifier (Loc, Chars (Left)), Rhs => Make_Identifier (Loc, Chars (Right)), Bodies => Declarations (Decl)))))); Append_Freeze_Action (Id, Decl); end if; end; end if; end Expand_N_Subprogram_Renaming_Declaration; end Exp_Ch8;
----------------------------------------------------------------------- -- secret-attributes -- Attribute list 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. ----------------------------------------------------------------------- package body Secret.Attributes is type Hash_Function is access function return Integer with Convention => C; function Str_Hash return Integer with Import => True, Convention => C, Link_Name => "g_str_hash"; type Free_Func is access procedure with Convention => C; procedure Str_Free with Import => True, Convention => C, Link_Name => "g_free"; type Compare_Function is access function return Integer with Convention => C; function Str_Compare return Integer with Import => True, Convention => C, Link_Name => "g_str_equal"; function Hash_Table_New_Full (Hash : in Hash_Function; Comp : in Compare_Function; R1 : in Free_Func; R2 : in Free_Func) return Opaque_Type with Import => True, Convention => C, Link_Name => "g_hash_table_new_full"; function Hash_Table_Ref (Object : in Opaque_Type) return Opaque_Type with Import => True, Convention => C, Link_Name => "g_hash_table_ref"; procedure Hash_Table_Unref (Object : in Opaque_Type) with Import => True, Convention => C, Link_Name => "g_hash_table_unref"; procedure Hash_Table_Insert (Object : in Opaque_Type; Name : in Chars_Ptr; Value : in Chars_Ptr) with Import => True, Convention => C, Link_Name => "g_hash_table_insert"; -- ------------------------------ -- Insert into the map the attribute with the given name and value. -- ------------------------------ procedure Insert (Into : in out Map; Name : in String; Value : in String) is begin if Into.Opaque = System.Null_Address then Into.Opaque := Hash_Table_New_Full (Str_Hash'Access, Str_Compare'Access, Str_Free'Access, Str_Free'Access); end if; Hash_Table_Insert (Into.Opaque, New_String (Name), New_String (Value)); end Insert; overriding procedure Adjust (Object : in out Map) is begin if Object.Opaque /= System.Null_Address then Object.Opaque := Hash_Table_Ref (Object.Opaque); end if; end Adjust; overriding procedure Finalize (Object : in out Map) is begin if Object.Opaque /= System.Null_Address then Hash_Table_Unref (Object.Opaque); end if; end Finalize; end Secret.Attributes;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- C L E A N -- -- -- -- B o d y -- -- -- -- Copyright (C) 2003-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. -- -- -- ------------------------------------------------------------------------------ with ALI; use ALI; with Make_Util; use Make_Util; with Namet; use Namet; with Opt; use Opt; with Osint; use Osint; with Osint.M; use Osint.M; with Switch; use Switch; with Table; with Targparm; with Types; use Types; with Ada.Command_Line; use Ada.Command_Line; with GNAT.Command_Line; use GNAT.Command_Line; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with GNAT.IO; use GNAT.IO; with GNAT.OS_Lib; use GNAT.OS_Lib; package body Clean is -- Suffixes of various files Assembly_Suffix : constant String := ".s"; Tree_Suffix : constant String := ".adt"; Object_Suffix : constant String := Get_Target_Object_Suffix.all; Debug_Suffix : constant String := ".dg"; Repinfo_Suffix : constant String := ".rep"; -- Suffix of representation info files B_Start : constant String := "b~"; -- Prefix of binder generated file, and number of actual characters used Object_Directory_Path : String_Access := null; -- The path name of the object directory, set with switch -D Force_Deletions : Boolean := False; -- Set to True by switch -f. When True, attempts to delete non writable -- files will be done. Do_Nothing : Boolean := False; -- Set to True when switch -n is specified. When True, no file is deleted. -- gnatclean only lists the files that would have been deleted if the -- switch -n had not been specified. File_Deleted : Boolean := False; -- Set to True if at least one file has been deleted Copyright_Displayed : Boolean := False; Usage_Displayed : Boolean := False; Project_File_Name : String_Access := null; package Sources is new Table.Table (Table_Component_Type => File_Name_Type, Table_Index_Type => Natural, Table_Low_Bound => 0, Table_Initial => 10, Table_Increment => 100, Table_Name => "Clean.Processed_Projects"); -- Table to store all the source files of a library unit: spec, body and -- subunits, to detect .dg files and delete them. ----------------------------- -- Other local subprograms -- ----------------------------- function Assembly_File_Name (Source : File_Name_Type) return String; -- Returns the assembly file name corresponding to Source procedure Clean_Executables; -- Do the cleaning work when no project file is specified function Debug_File_Name (Source : File_Name_Type) return String; -- Name of the expanded source file corresponding to Source procedure Delete (In_Directory : String; File : String); -- Delete one file, or list the file name if switch -n is specified procedure Delete_Binder_Generated_Files (Dir : String; Source : File_Name_Type); -- Delete the binder generated file in directory Dir for Source, if they -- exist: for Unix these are b~<source>.ads, b~<source>.adb, -- b~<source>.ali and b~<source>.o. procedure Display_Copyright; -- Display the Copyright notice. If called several times, display the -- Copyright notice only the first time. procedure Initialize; -- Call the necessary package initializations function Object_File_Name (Source : File_Name_Type) return String; -- Returns the object file name corresponding to Source procedure Parse_Cmd_Line; -- Parse the command line function Repinfo_File_Name (Source : File_Name_Type) return String; -- Returns the repinfo file name corresponding to Source function Tree_File_Name (Source : File_Name_Type) return String; -- Returns the tree file name corresponding to Source procedure Usage; -- Display the usage. If called several times, the usage is displayed only -- the first time. ------------------------ -- Assembly_File_Name -- ------------------------ function Assembly_File_Name (Source : File_Name_Type) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the assembly suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Assembly_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- assembly suffix. return Src & Assembly_Suffix; end Assembly_File_Name; ----------------------- -- Clean_Executables -- ----------------------- procedure Clean_Executables is Main_Source_File : File_Name_Type; -- Current main source Main_Lib_File : File_Name_Type; -- ALI file of the current main Lib_File : File_Name_Type; -- Current ALI file Full_Lib_File : File_Name_Type; -- Full name of the current ALI file Text : Text_Buffer_Ptr; The_ALI : ALI_Id; Found : Boolean; Source : Queue.Source_Info; begin Queue.Initialize; -- It does not really matter if there is or not an object file -- corresponding to an ALI file: if there is one, it will be deleted. Opt.Check_Object_Consistency := False; -- Proceed each executable one by one. Each source is marked as it is -- processed, so common sources between executables will not be -- processed several times. for N_File in 1 .. Osint.Number_Of_Files loop Main_Source_File := Next_Main_Source; Main_Lib_File := Osint.Lib_File_Name (Main_Source_File, Current_File_Index); if Main_Lib_File /= No_File then Queue.Insert ((File => Main_Lib_File, Unit => No_Unit_Name, Index => 0)); end if; while not Queue.Is_Empty loop Sources.Set_Last (0); Queue.Extract (Found, Source); pragma Assert (Found); pragma Assert (Source.File /= No_File); Lib_File := Source.File; Full_Lib_File := Osint.Full_Lib_File_Name (Lib_File); -- If we have existing ALI file that is not read-only, process it if Full_Lib_File /= No_File and then not Is_Readonly_Library (Full_Lib_File) then Text := Read_Library_Info (Lib_File); if Text /= null then The_ALI := Scan_ALI (Lib_File, Text, Ignore_ED => False, Err => True); Free (Text); -- If no error was produced while loading this ALI file, -- insert into the queue all the unmarked withed sources. if The_ALI /= No_ALI_Id then for J in ALIs.Table (The_ALI).First_Unit .. ALIs.Table (The_ALI).Last_Unit loop Sources.Increment_Last; Sources.Table (Sources.Last) := ALI.Units.Table (J).Sfile; for K in ALI.Units.Table (J).First_With .. ALI.Units.Table (J).Last_With loop if Withs.Table (K).Afile /= No_File then Queue.Insert ((File => Withs.Table (K).Afile, Unit => No_Unit_Name, Index => 0)); end if; end loop; end loop; -- Look for subunits and put them in the Sources table for J in ALIs.Table (The_ALI).First_Sdep .. ALIs.Table (The_ALI).Last_Sdep loop if Sdep.Table (J).Subunit_Name /= No_Name then Sources.Increment_Last; Sources.Table (Sources.Last) := Sdep.Table (J).Sfile; end if; end loop; end if; end if; -- Now delete all existing files corresponding to this ALI file declare Obj_Dir : constant String := Dir_Name (Get_Name_String (Full_Lib_File)); Obj : constant String := Object_File_Name (Lib_File); Adt : constant String := Tree_File_Name (Lib_File); Asm : constant String := Assembly_File_Name (Lib_File); begin Delete (Obj_Dir, Get_Name_String (Lib_File)); if Is_Regular_File (Obj_Dir & Dir_Separator & Obj) then Delete (Obj_Dir, Obj); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Adt) then Delete (Obj_Dir, Adt); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Asm) then Delete (Obj_Dir, Asm); end if; -- Delete expanded source files (.dg) and/or repinfo files -- (.rep) if any for J in 1 .. Sources.Last loop declare Deb : constant String := Debug_File_Name (Sources.Table (J)); Rep : constant String := Repinfo_File_Name (Sources.Table (J)); begin if Is_Regular_File (Obj_Dir & Dir_Separator & Deb) then Delete (Obj_Dir, Deb); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Rep) then Delete (Obj_Dir, Rep); end if; end; end loop; end; end if; end loop; -- Delete the executable, if it exists, and the binder generated -- files, if any. if not Compile_Only then declare Source : constant File_Name_Type := Strip_Suffix (Main_Lib_File); Executable : constant String := Get_Name_String (Executable_Name (Source)); begin if Is_Regular_File (Executable) then Delete ("", Executable); end if; Delete_Binder_Generated_Files (Get_Current_Dir, Source); end; end if; end loop; end Clean_Executables; --------------------- -- Debug_File_Name -- --------------------- function Debug_File_Name (Source : File_Name_Type) return String is begin return Get_Name_String (Source) & Debug_Suffix; end Debug_File_Name; ------------ -- Delete -- ------------ procedure Delete (In_Directory : String; File : String) is Full_Name : String (1 .. In_Directory'Length + File'Length + 1); Last : Natural := 0; Success : Boolean; begin -- Indicate that at least one file is deleted or is to be deleted File_Deleted := True; -- Build the path name of the file to delete Last := In_Directory'Length; Full_Name (1 .. Last) := In_Directory; if Last > 0 and then Full_Name (Last) /= Directory_Separator then Last := Last + 1; Full_Name (Last) := Directory_Separator; end if; Full_Name (Last + 1 .. Last + File'Length) := File; Last := Last + File'Length; -- If switch -n was used, simply output the path name if Do_Nothing then Put_Line (Full_Name (1 .. Last)); -- Otherwise, delete the file if it is writable else if Force_Deletions or else Is_Writable_File (Full_Name (1 .. Last)) or else Is_Symbolic_Link (Full_Name (1 .. Last)) then Delete_File (Full_Name (1 .. Last), Success); -- Here if no deletion required else Success := False; end if; if Verbose_Mode or else not Quiet_Output then if not Success then Put ("Warning: """); Put (Full_Name (1 .. Last)); Put_Line (""" could not be deleted"); else Put (""""); Put (Full_Name (1 .. Last)); Put_Line (""" has been deleted"); end if; end if; end if; end Delete; ----------------------------------- -- Delete_Binder_Generated_Files -- ----------------------------------- procedure Delete_Binder_Generated_Files (Dir : String; Source : File_Name_Type) is Source_Name : constant String := Get_Name_String (Source); Current : constant String := Get_Current_Dir; Last : constant Positive := B_Start'Length + Source_Name'Length; File_Name : String (1 .. Last + 4); begin Change_Dir (Dir); -- Build the file name (before the extension) File_Name (1 .. B_Start'Length) := B_Start; File_Name (B_Start'Length + 1 .. Last) := Source_Name; -- Spec File_Name (Last + 1 .. Last + 4) := ".ads"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- Body File_Name (Last + 1 .. Last + 4) := ".adb"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- ALI file File_Name (Last + 1 .. Last + 4) := ".ali"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- Object file File_Name (Last + 1 .. Last + Object_Suffix'Length) := Object_Suffix; if Is_Regular_File (File_Name (1 .. Last + Object_Suffix'Length)) then Delete (Dir, File_Name (1 .. Last + Object_Suffix'Length)); end if; -- Change back to previous directory Change_Dir (Current); end Delete_Binder_Generated_Files; ----------------------- -- Display_Copyright -- ----------------------- procedure Display_Copyright is begin if not Copyright_Displayed then Copyright_Displayed := True; Display_Version ("GNATCLEAN", "2003"); end if; end Display_Copyright; --------------- -- Gnatclean -- --------------- procedure Gnatclean is begin -- Do the necessary initializations Clean.Initialize; -- Parse the command line, getting the switches and the executable names Parse_Cmd_Line; if Verbose_Mode then Display_Copyright; end if; Osint.Add_Default_Search_Dirs; Targparm.Get_Target_Parameters; if Osint.Number_Of_Files = 0 then if Argument_Count = 0 then Usage; else Try_Help; end if; return; end if; if Verbose_Mode then New_Line; end if; if Project_File_Name /= null then declare Gprclean_Path : constant String_Access := Locate_Exec_On_Path ("gprclean"); Arg_Len : Natural := Argument_Count; Pos : Natural := 0; Target : String_Access := null; Success : Boolean := False; begin if Gprclean_Path = null then Fail_Program ("project files are no longer supported by gnatclean;" & " use gprclean instead"); end if; Find_Program_Name; if Name_Len > 10 and then Name_Buffer (Name_Len - 8 .. Name_Len) = "gnatclean" then Target := new String'(Name_Buffer (1 .. Name_Len - 9)); Arg_Len := Arg_Len + 1; end if; declare Args : Argument_List (1 .. Arg_Len); begin if Target /= null then Args (1) := new String'("--target=" & Target.all); Pos := 1; end if; for J in 1 .. Argument_Count loop Pos := Pos + 1; Args (Pos) := new String'(Argument (J)); end loop; Spawn (Gprclean_Path.all, Args, Success); if Success then Exit_Program (E_Success); else Exit_Program (E_Errors); end if; end; end; end if; Clean_Executables; -- In verbose mode, if Delete has not been called, indicate that no file -- needs to be deleted. if Verbose_Mode and (not File_Deleted) then New_Line; if Do_Nothing then Put_Line ("No file needs to be deleted"); else Put_Line ("No file has been deleted"); end if; end if; end Gnatclean; ---------------- -- Initialize -- ---------------- procedure Initialize is begin -- Reset global variables Free (Object_Directory_Path); Do_Nothing := False; File_Deleted := False; Copyright_Displayed := False; Usage_Displayed := False; end Initialize; ---------------------- -- Object_File_Name -- ---------------------- function Object_File_Name (Source : File_Name_Type) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the Object suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Object_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- ALI suffix. return Src & Object_Suffix; end Object_File_Name; -------------------- -- Parse_Cmd_Line -- -------------------- procedure Parse_Cmd_Line is Last : constant Natural := Argument_Count; Index : Positive; Source_Index : Int := 0; procedure Check_Version_And_Help is new Check_Version_And_Help_G (Usage); begin -- First, check for --version and --help Check_Version_And_Help ("GNATCLEAN", "2003"); -- First, check for switch -P and, if found and gprclean is available, -- silently invoke gprclean, with switch --target if not on a native -- platform. declare Arg_Len : Positive := Argument_Count; Call_Gprclean : Boolean := False; Gprclean : String_Access := null; Pos : Natural := 0; Success : Boolean; Target : String_Access := null; begin Find_Program_Name; if Name_Len >= 9 and then Name_Buffer (Name_Len - 8 .. Name_Len) = "gnatclean" then if Name_Len > 9 then Target := new String'(Name_Buffer (1 .. Name_Len - 10)); Arg_Len := Arg_Len + 1; end if; for J in 1 .. Argument_Count loop declare Arg : constant String := Argument (J); begin if Arg'Length >= 2 and then Arg (Arg'First .. Arg'First + 1) = "-P" then Call_Gprclean := True; exit; end if; end; end loop; if Call_Gprclean then Gprclean := Locate_Exec_On_Path (Exec_Name => "gprclean"); if Gprclean /= null then declare Args : Argument_List (1 .. Arg_Len); begin if Target /= null then Args (1) := new String'("--target=" & Target.all); Pos := 1; end if; for J in 1 .. Argument_Count loop Pos := Pos + 1; Args (Pos) := new String'(Argument (J)); end loop; Spawn (Gprclean.all, Args, Success); Free (Gprclean); if Success then Exit_Program (E_Success); else Exit_Program (E_Fatal); end if; end; end if; end if; end if; end; Index := 1; while Index <= Last loop declare Arg : constant String := Argument (Index); procedure Bad_Argument; pragma No_Return (Bad_Argument); -- Signal bad argument ------------------ -- Bad_Argument -- ------------------ procedure Bad_Argument is begin Fail ("invalid argument """ & Arg & """"); end Bad_Argument; begin if Arg'Length /= 0 then if Arg (1) = '-' then if Arg'Length = 1 then Bad_Argument; end if; case Arg (2) is when '-' => if Arg'Length > Subdirs_Option'Length and then Arg (1 .. Subdirs_Option'Length) = Subdirs_Option then null; -- Subdirs are only used in gprclean elsif Arg = Make_Util.Unchecked_Shared_Lib_Imports then Opt.Unchecked_Shared_Lib_Imports := True; else Bad_Argument; end if; when 'a' => if Arg'Length < 4 then Bad_Argument; end if; if Arg (3) = 'O' then Add_Lib_Search_Dir (Arg (4 .. Arg'Last)); elsif Arg (3) = 'P' then null; -- This is only for gprclean else Bad_Argument; end if; when 'c' => Compile_Only := True; when 'D' => if Object_Directory_Path /= null then Fail ("duplicate -D switch"); elsif Project_File_Name /= null then Fail ("-P and -D cannot be used simultaneously"); end if; if Arg'Length > 2 then declare Dir : constant String := Arg (3 .. Arg'Last); begin if not Is_Directory (Dir) then Fail (Dir & " is not a directory"); else Add_Lib_Search_Dir (Dir); end if; end; else if Index = Last then Fail ("no directory specified after -D"); end if; Index := Index + 1; declare Dir : constant String := Argument (Index); begin if not Is_Directory (Dir) then Fail (Dir & " is not a directory"); else Add_Lib_Search_Dir (Dir); end if; end; end if; when 'e' => if Arg = "-eL" then Follow_Links_For_Files := True; Follow_Links_For_Dirs := True; else Bad_Argument; end if; when 'f' => Force_Deletions := True; Directories_Must_Exist_In_Projects := False; when 'F' => Full_Path_Name_For_Brief_Errors := True; when 'h' => Usage; when 'i' => if Arg'Length = 2 then Bad_Argument; end if; Source_Index := 0; for J in 3 .. Arg'Last loop if Arg (J) not in '0' .. '9' then Bad_Argument; end if; Source_Index := (20 * Source_Index) + (Character'Pos (Arg (J)) - Character'Pos ('0')); end loop; when 'I' => if Arg = "-I-" then Opt.Look_In_Primary_Dir := False; else if Arg'Length = 2 then Bad_Argument; end if; Add_Lib_Search_Dir (Arg (3 .. Arg'Last)); end if; when 'n' => Do_Nothing := True; when 'P' => if Project_File_Name /= null then Fail ("multiple -P switches"); elsif Object_Directory_Path /= null then Fail ("-D and -P cannot be used simultaneously"); end if; if Arg'Length > 2 then declare Prj : constant String := Arg (3 .. Arg'Last); begin if Prj'Length > 1 and then Prj (Prj'First) = '=' then Project_File_Name := new String' (Prj (Prj'First + 1 .. Prj'Last)); else Project_File_Name := new String'(Prj); end if; end; else if Index = Last then Fail ("no project specified after -P"); end if; Index := Index + 1; Project_File_Name := new String'(Argument (Index)); end if; when 'q' => Quiet_Output := True; when 'r' => null; -- This is only for gprclean when 'v' => if Arg = "-v" then Verbose_Mode := True; elsif Arg = "-vP0" or else Arg = "-vP1" or else Arg = "-vP2" then null; -- This is only for gprclean else Bad_Argument; end if; when 'X' => if Arg'Length = 2 then Bad_Argument; end if; when others => Bad_Argument; end case; else Add_File (Arg, Source_Index); end if; end if; end; Index := Index + 1; end loop; end Parse_Cmd_Line; ----------------------- -- Repinfo_File_Name -- ----------------------- function Repinfo_File_Name (Source : File_Name_Type) return String is begin return Get_Name_String (Source) & Repinfo_Suffix; end Repinfo_File_Name; -------------------- -- Tree_File_Name -- -------------------- function Tree_File_Name (Source : File_Name_Type) return String is Src : constant String := Get_Name_String (Source); begin -- If source name has an extension, then replace it with the tree suffix for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Tree_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- tree suffix. return Src & Tree_Suffix; end Tree_File_Name; ----------- -- Usage -- ----------- procedure Usage is begin if not Usage_Displayed then Usage_Displayed := True; Display_Copyright; Put_Line ("Usage: gnatclean [switches] {[-innn] name}"); New_Line; Display_Usage_Version_And_Help; Put_Line (" names is one or more file names from which " & "the .adb or .ads suffix may be omitted"); Put_Line (" names may be omitted if -P<project> is specified"); New_Line; Put_Line (" --subdirs=dir real obj/lib/exec dirs are subdirs"); Put_Line (" " & Make_Util.Unchecked_Shared_Lib_Imports); Put_Line (" Allow shared libraries to import static libraries"); New_Line; Put_Line (" -c Only delete compiler generated files"); Put_Line (" -D dir Specify dir as the object library"); Put_Line (" -eL Follow symbolic links when processing " & "project files"); Put_Line (" -f Force deletions of unwritable files"); Put_Line (" -F Full project path name " & "in brief error messages"); Put_Line (" -h Display this message"); Put_Line (" -innn Index of unit in source for following names"); Put_Line (" -n Nothing to do: only list files to delete"); Put_Line (" -Pproj Use GNAT Project File proj"); Put_Line (" -q Be quiet/terse"); Put_Line (" -r Clean all projects recursively"); Put_Line (" -v Verbose mode"); Put_Line (" -vPx Specify verbosity when parsing " & "GNAT Project Files"); Put_Line (" -Xnm=val Specify an external reference " & "for GNAT Project Files"); New_Line; Put_Line (" -aPdir Add directory dir to project search path"); New_Line; Put_Line (" -aOdir Specify ALI/object files search path"); Put_Line (" -Idir Like -aOdir"); Put_Line (" -I- Don't look for source/library files " & "in the default directory"); New_Line; end if; end Usage; end Clean;
----------------------------------------------------------------------- -- awa_test_app - -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body AWA_Test_App is use AWA.Applications; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Adafr"); -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets..."); App.Self := App'Unchecked_Access; App.Set_Global ("contextPath", CONTEXT_PATH); AWA.Applications.Application (App).Initialize_Servlets; App.Add_Servlet (Name => "faces", Server => App.Self.Faces'Access); App.Add_Servlet (Name => "files", Server => App.Self.Files'Access); App.Add_Servlet (Name => "ajax", Server => App.Self.Ajax'Access); App.Add_Servlet (Name => "measures", Server => App.Self.Measures'Access); App.Add_Servlet (Name => "auth", Server => App.Self.Auth'Access); App.Add_Servlet (Name => "verify-auth", Server => App.Self.Verify_Auth'Access); end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters..."); AWA.Applications.Application (App).Initialize_Filters; App.Add_Filter (Name => "dump", Filter => App.Self.Dump'Access); App.Add_Filter (Name => "measures", Filter => App.Self.Measures'Access); App.Add_Filter (Name => "service", Filter => App.Self.Service_Filter'Access); App.Add_Filter (Name => "no-cache", Filter => App.Self.No_Cache'Access); end Initialize_Filters; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ overriding procedure Initialize_Modules (App : in out Application) is begin Log.Info ("Initializing application modules..."); App.Add_Converter (Name => "smartDateConverter", Converter => App.Self.Rel_Date_Converter'Access); App.Add_Converter (Name => "sizeConverter", Converter => App.Self.Size_Converter'Access); Register (App => App.Self.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => App.User_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Workspaces.Modules.NAME, URI => "workspaces", Module => App.Workspace_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Mail.Modules.NAME, URI => "mail", Module => App.Mail_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => App.Comment_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => App.Tag_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => App.Job_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => App.Storage_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => App.Image_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => App.Counter_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => App.Blog_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => App.Wiki_Module'Access); Register (App => App.Self.all'Access, Name => AWA.Wikis.Previews.NAME, URI => "wikis-preview", Module => App.Preview_Module'Access); end Initialize_Modules; end AWA_Test_App;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- ADA.CONTAINERS.BOUNDED_PRIORITY_QUEUES -- -- -- -- B o d y -- -- -- -- Copyright (C) 2011-2015, 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/>. -- -- -- -- This unit was originally developed by Matthew J Heaney. -- ------------------------------------------------------------------------------ package body Ada.Containers.Bounded_Priority_Queues is package body Implementation is ------------- -- Dequeue -- ------------- procedure Dequeue (List : in out List_Type; Element : out Queue_Interfaces.Element_Type) is begin Element := List.Container.First_Element; List.Container.Delete_First; end Dequeue; procedure Dequeue (List : in out List_Type; At_Least : Queue_Priority; Element : in out Queue_Interfaces.Element_Type; Success : out Boolean) is begin -- This operation dequeues a high priority item if it exists in the -- queue. By "high priority" we mean an item whose priority is equal -- or greater than the value At_Least. The generic formal operation -- Before has the meaning "has higher priority than". To dequeue an -- item (meaning that we return True as our Success value), we need -- as our predicate the equivalent of "has equal or higher priority -- than", but we cannot say that directly, so we require some logical -- gymnastics to make it so. -- If E is the element at the head of the queue, and symbol ">" -- refers to the "is higher priority than" function Before, then we -- derive our predicate as follows: -- original: P(E) >= At_Least -- same as: not (P(E) < At_Least) -- same as: not (At_Least > P(E)) -- same as: not Before (At_Least, P(E)) -- But that predicate needs to be true in order to successfully -- dequeue an item. If it's false, it means no item is dequeued, and -- we return False as the Success value. if List.Length = 0 or else Before (At_Least, Get_Priority (List.Container.First_Element)) then Success := False; return; end if; List.Dequeue (Element); Success := True; end Dequeue; ------------- -- Enqueue -- ------------- procedure Enqueue (List : in out List_Type; New_Item : Queue_Interfaces.Element_Type) is P : constant Queue_Priority := Get_Priority (New_Item); C : List_Types.Cursor; use List_Types; Count : Count_Type; begin C := List.Container.First; while Has_Element (C) loop -- ??? why is following commented out ??? -- if Before (P, Get_Priority (List.Constant_Reference (C))) then if Before (P, Get_Priority (Element (C))) then List.Container.Insert (C, New_Item); exit; end if; Next (C); end loop; if not Has_Element (C) then List.Container.Append (New_Item); end if; Count := List.Container.Length; if Count > List.Max_Length then List.Max_Length := Count; end if; end Enqueue; ------------------- -- First_Element -- ------------------- function First_Element (List : List_Type) return Queue_Interfaces.Element_Type is begin -- Use Constant_Reference for this. ??? return List.Container.First_Element; end First_Element; ------------ -- Length -- ------------ function Length (List : List_Type) return Count_Type is begin return List.Container.Length; end Length; ---------------- -- Max_Length -- ---------------- function Max_Length (List : List_Type) return Count_Type is begin return List.Max_Length; end Max_Length; end Implementation; protected body Queue is ------------------ -- Current_Use -- ------------------ function Current_Use return Count_Type is begin return List.Length; end Current_Use; -------------- -- Dequeue -- -------------- entry Dequeue (Element : out Queue_Interfaces.Element_Type) when List.Length > 0 is begin List.Dequeue (Element); end Dequeue; -------------------------------- -- Dequeue_Only_High_Priority -- -------------------------------- procedure Dequeue_Only_High_Priority (At_Least : Queue_Priority; Element : in out Queue_Interfaces.Element_Type; Success : out Boolean) is begin List.Dequeue (At_Least, Element, Success); end Dequeue_Only_High_Priority; -------------- -- Enqueue -- -------------- entry Enqueue (New_Item : Queue_Interfaces.Element_Type) when List.Length < Capacity is begin List.Enqueue (New_Item); end Enqueue; --------------- -- Peak_Use -- --------------- function Peak_Use return Count_Type is begin return List.Max_Length; end Peak_Use; end Queue; end Ada.Containers.Bounded_Priority_Queues;
-- Copyright 2017-2021 Bartek thindil Jasicki -- -- This file is part of Steam Sky. -- -- Steam Sky 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. -- -- Steam Sky 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 Steam Sky. If not, see <http://www.gnu.org/licenses/>. with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Directories; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Game; package body Log is --## rule off DIRECTLY_ACCESSED_GLOBALS -- ****iv* Log/Log.Log_File -- FUNCTION -- Debug log file -- SOURCE Log_File: File_Type; -- **** procedure Start_Logging is use Ada.Directories; use Game; begin if Debug_Mode = Default_Debug_Mode then return; end if; if Exists(Name => To_String(Source => Save_Directory) & "debug.log") then Open (File => Log_File, Mode => Append_File, Name => To_String(Source => Save_Directory) & "debug.log"); else Create (File => Log_File, Mode => Append_File, Name => To_String(Source => Save_Directory) & "debug.log"); end if; Log_Message (Message => "Start game in debug mode: " & Debug_Types'Image(Debug_Mode) & ".", Message_Type => Debug_Mode); end Start_Logging; procedure Log_Message (Message: String; Message_Type: Debug_Types; New_Line, Time_Stamp: Boolean := True) is use Ada.Calendar; New_Message: Unbounded_String; begin if Debug_Mode = Default_Debug_Mode or (Message_Type /= Debug_Mode and Debug_Mode /= EVERYTHING) then return; end if; if not Is_Open(File => Log_File) then return; end if; New_Message := (if Time_Stamp then To_Unbounded_String (Source => "[" & Ada.Calendar.Formatting.Image(Date => Clock) & "]:" & Message) else To_Unbounded_String(Source => Message)); if New_Line then Put_Line(File => Log_File, Item => To_String(Source => New_Message)); else Put(File => Log_File, Item => To_String(Source => New_Message)); end if; end Log_Message; procedure End_Logging is begin if Debug_Mode = Default_Debug_Mode or not Is_Open(File => Log_File) then return; end if; Log_Message (Message => "Ending game in debug mode: " & Debug_Types'Image(Debug_Mode) & ".", Message_Type => Debug_Mode); Close(File => Log_File); end End_Logging; --## rule on DIRECTLY_ACCESSED_GLOBALS end Log;
package Srv_Quit is procedure Detect_Quits (Irc_Dir : in String); -- TODO rename Handle_Quits? end Srv_Quit;
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type Name_T is array (1 .. 6) of Character; type Index_T is range 0 .. 1_000; type Queue_T is array (Index_T range 1 .. 1_000) of Name_T; -- type Fifo_Queue_T is ? -- Queue : Fifo_Queue_T; Choice : Integer; begin loop Put ("1 = add to queue | 2 = remove from queue | others => done: "); Choice := Integer'value (Get_Line); if Choice = 1 then Put ("Enter name: "); -- Use Ada.Text_IO.Get_Line to help put a name on the queue elsif Choice = 2 then -- Remove the appropriate item from the queue and print it Put_Line ("TBD"); else exit; end if; New_Line; end loop; Put_Line ("Remaining in line: "); -- Print the remaining items in the queue end Main;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.HSEM is pragma Preelaborate; --------------- -- Registers -- --------------- subtype HSEM_R_PROCID_Field is HAL.UInt8; subtype HSEM_R_MASTERID_Field is HAL.UInt8; -- HSEM register HSEM_R0 HSEM_R31 type HSEM_R_Register is record -- Semaphore ProcessID PROCID : HSEM_R_PROCID_Field := 16#0#; -- Semaphore MasterID MASTERID : HSEM_R_MASTERID_Field := 16#0#; -- unspecified Reserved_16_30 : HAL.UInt15 := 16#0#; -- Lock indication LOCK : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_R_Register use record PROCID at 0 range 0 .. 7; MASTERID at 0 range 8 .. 15; Reserved_16_30 at 0 range 16 .. 30; LOCK at 0 range 31 .. 31; end record; subtype HSEM_RLR_PROCID_Field is HAL.UInt8; subtype HSEM_RLR_MASTERID_Field is HAL.UInt8; -- HSEM Read lock register type HSEM_RLR_Register is record -- Read-only. Semaphore ProcessID PROCID : HSEM_RLR_PROCID_Field; -- Read-only. Semaphore MasterID MASTERID : HSEM_RLR_MASTERID_Field; -- unspecified Reserved_16_30 : HAL.UInt15; -- Read-only. Lock indication LOCK : Boolean; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_RLR_Register use record PROCID at 0 range 0 .. 7; MASTERID at 0 range 8 .. 15; Reserved_16_30 at 0 range 16 .. 30; LOCK at 0 range 31 .. 31; end record; -- HSEM_IER_ISEM array type HSEM_IER_ISEM_Field_Array is array (0 .. 31) of Boolean with Component_Size => 1, Size => 32; -- HSEM Interrupt enable register type HSEM_IER_Register (As_Array : Boolean := False) is record case As_Array is when False => -- ISEM as a value Val : HAL.UInt32; when True => -- ISEM as an array Arr : HSEM_IER_ISEM_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_IER_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- HSEM_ICR_ISEM array type HSEM_ICR_ISEM_Field_Array is array (0 .. 31) of Boolean with Component_Size => 1, Size => 32; -- HSEM Interrupt clear register type HSEM_ICR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- ISEM as a value Val : HAL.UInt32; when True => -- ISEM as an array Arr : HSEM_ICR_ISEM_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_ICR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- HSEM_ISR_ISEM array type HSEM_ISR_ISEM_Field_Array is array (0 .. 31) of Boolean with Component_Size => 1, Size => 32; -- HSEM Interrupt status register type HSEM_ISR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- ISEM as a value Val : HAL.UInt32; when True => -- ISEM as an array Arr : HSEM_ISR_ISEM_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_ISR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; -- HSEM_MISR_ISEM array type HSEM_MISR_ISEM_Field_Array is array (0 .. 31) of Boolean with Component_Size => 1, Size => 32; -- HSEM Masked interrupt status register type HSEM_MISR_Register (As_Array : Boolean := False) is record case As_Array is when False => -- ISEM as a value Val : HAL.UInt32; when True => -- ISEM as an array Arr : HSEM_MISR_ISEM_Field_Array; end case; end record with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_MISR_Register use record Val at 0 range 0 .. 31; Arr at 0 range 0 .. 31; end record; subtype HSEM_CR_MASTERID_Field is HAL.UInt8; subtype HSEM_CR_KEY_Field is HAL.UInt16; -- HSEM Clear register type HSEM_CR_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- MasterID of semaphores to be cleared MASTERID : HSEM_CR_MASTERID_Field := 16#0#; -- Semaphore clear Key KEY : HSEM_CR_KEY_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_CR_Register use record Reserved_0_7 at 0 range 0 .. 7; MASTERID at 0 range 8 .. 15; KEY at 0 range 16 .. 31; end record; subtype HSEM_KEYR_KEY_Field is HAL.UInt16; -- HSEM Interrupt clear register type HSEM_KEYR_Register is record -- unspecified Reserved_0_15 : HAL.UInt16 := 16#0#; -- Semaphore Clear Key KEY : HSEM_KEYR_KEY_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for HSEM_KEYR_Register use record Reserved_0_15 at 0 range 0 .. 15; KEY at 0 range 16 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- HSEM type HSEM_Peripheral is record -- HSEM register HSEM_R0 HSEM_R31 HSEM_R0 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R1 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R2 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R3 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R4 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R5 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R6 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R7 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R8 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R9 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R10 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R11 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R12 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R13 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R14 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R15 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R16 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R17 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R18 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R19 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R20 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R21 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R22 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R23 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R24 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R25 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R26 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R27 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R28 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R29 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R30 : aliased HSEM_R_Register; -- HSEM register HSEM_R0 HSEM_R31 HSEM_R31 : aliased HSEM_R_Register; -- HSEM Read lock register HSEM_RLR0 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR1 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR2 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR3 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR4 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR5 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR6 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR7 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR8 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR9 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR10 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR11 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR12 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR13 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR14 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR15 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR16 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR17 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR18 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR19 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR20 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR21 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR22 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR23 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR24 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR25 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR26 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR27 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR28 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR29 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR30 : aliased HSEM_RLR_Register; -- HSEM Read lock register HSEM_RLR31 : aliased HSEM_RLR_Register; -- HSEM Interrupt enable register HSEM_IER : aliased HSEM_IER_Register; -- HSEM Interrupt clear register HSEM_ICR : aliased HSEM_ICR_Register; -- HSEM Interrupt status register HSEM_ISR : aliased HSEM_ISR_Register; -- HSEM Masked interrupt status register HSEM_MISR : aliased HSEM_MISR_Register; -- HSEM Clear register HSEM_CR : aliased HSEM_CR_Register; -- HSEM Interrupt clear register HSEM_KEYR : aliased HSEM_KEYR_Register; end record with Volatile; for HSEM_Peripheral use record HSEM_R0 at 16#0# range 0 .. 31; HSEM_R1 at 16#4# range 0 .. 31; HSEM_R2 at 16#8# range 0 .. 31; HSEM_R3 at 16#C# range 0 .. 31; HSEM_R4 at 16#10# range 0 .. 31; HSEM_R5 at 16#14# range 0 .. 31; HSEM_R6 at 16#18# range 0 .. 31; HSEM_R7 at 16#1C# range 0 .. 31; HSEM_R8 at 16#20# range 0 .. 31; HSEM_R9 at 16#24# range 0 .. 31; HSEM_R10 at 16#28# range 0 .. 31; HSEM_R11 at 16#2C# range 0 .. 31; HSEM_R12 at 16#30# range 0 .. 31; HSEM_R13 at 16#34# range 0 .. 31; HSEM_R14 at 16#38# range 0 .. 31; HSEM_R15 at 16#3C# range 0 .. 31; HSEM_R16 at 16#40# range 0 .. 31; HSEM_R17 at 16#44# range 0 .. 31; HSEM_R18 at 16#48# range 0 .. 31; HSEM_R19 at 16#4C# range 0 .. 31; HSEM_R20 at 16#50# range 0 .. 31; HSEM_R21 at 16#54# range 0 .. 31; HSEM_R22 at 16#58# range 0 .. 31; HSEM_R23 at 16#5C# range 0 .. 31; HSEM_R24 at 16#60# range 0 .. 31; HSEM_R25 at 16#64# range 0 .. 31; HSEM_R26 at 16#68# range 0 .. 31; HSEM_R27 at 16#6C# range 0 .. 31; HSEM_R28 at 16#70# range 0 .. 31; HSEM_R29 at 16#74# range 0 .. 31; HSEM_R30 at 16#78# range 0 .. 31; HSEM_R31 at 16#7C# range 0 .. 31; HSEM_RLR0 at 16#80# range 0 .. 31; HSEM_RLR1 at 16#84# range 0 .. 31; HSEM_RLR2 at 16#88# range 0 .. 31; HSEM_RLR3 at 16#8C# range 0 .. 31; HSEM_RLR4 at 16#90# range 0 .. 31; HSEM_RLR5 at 16#94# range 0 .. 31; HSEM_RLR6 at 16#98# range 0 .. 31; HSEM_RLR7 at 16#9C# range 0 .. 31; HSEM_RLR8 at 16#A0# range 0 .. 31; HSEM_RLR9 at 16#A4# range 0 .. 31; HSEM_RLR10 at 16#A8# range 0 .. 31; HSEM_RLR11 at 16#AC# range 0 .. 31; HSEM_RLR12 at 16#B0# range 0 .. 31; HSEM_RLR13 at 16#B4# range 0 .. 31; HSEM_RLR14 at 16#B8# range 0 .. 31; HSEM_RLR15 at 16#BC# range 0 .. 31; HSEM_RLR16 at 16#C0# range 0 .. 31; HSEM_RLR17 at 16#C4# range 0 .. 31; HSEM_RLR18 at 16#C8# range 0 .. 31; HSEM_RLR19 at 16#CC# range 0 .. 31; HSEM_RLR20 at 16#D0# range 0 .. 31; HSEM_RLR21 at 16#D4# range 0 .. 31; HSEM_RLR22 at 16#D8# range 0 .. 31; HSEM_RLR23 at 16#DC# range 0 .. 31; HSEM_RLR24 at 16#E0# range 0 .. 31; HSEM_RLR25 at 16#E4# range 0 .. 31; HSEM_RLR26 at 16#E8# range 0 .. 31; HSEM_RLR27 at 16#EC# range 0 .. 31; HSEM_RLR28 at 16#F0# range 0 .. 31; HSEM_RLR29 at 16#F4# range 0 .. 31; HSEM_RLR30 at 16#F8# range 0 .. 31; HSEM_RLR31 at 16#FC# range 0 .. 31; HSEM_IER at 16#100# range 0 .. 31; HSEM_ICR at 16#104# range 0 .. 31; HSEM_ISR at 16#108# range 0 .. 31; HSEM_MISR at 16#10C# range 0 .. 31; HSEM_CR at 16#140# range 0 .. 31; HSEM_KEYR at 16#144# range 0 .. 31; end record; -- HSEM HSEM_Periph : aliased HSEM_Peripheral with Import, Address => HSEM_Base; end STM32_SVD.HSEM;
with openGL.Shader, openGL.Variable.uniform, openGL.Attribute, openGL.Light; private with GL; package openGL.Program -- -- Models an openGL program. -- is type Item is tagged limited private; type View is access all Item'Class; --------- --- Forge -- procedure define (Self : in out Item) is null; procedure define (Self : in out Item; use_vertex_Shader : in Shader.view; use_fragment_Shader : in Shader.view); procedure define (Self : in out Item; use_vertex_Shader_File : in String; use_fragment_Shader_File : in String); procedure destroy (Self : in out Item); ---------------------- -- Program Parameters -- -- These are used by individual visuals which require program Uniforms to vary from visual to visual. -- The Parmaters type is extended to contain the required varying data and 'enable' is overridden to -- apply the varying data to the programs Uniforms. 'enable' is called as part of the rendering process -- just prior to the visuals geometry being rendered. -- -- (See 'gel.Human' for an example of usage.) type Parameters is limited new openGL.Parameters with private; type Parameters_view is access all Parameters'Class; procedure Program_is (Self : in out Parameters; Now : in Program.view); function Program (Self : in Parameters) return Program.view; procedure enable (Self : in out Parameters) is null; -------------- -- Attributes -- function is_defined (Self : in Item'Class) return Boolean; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.bool; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.int; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.float; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.vec3; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.vec4; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.mat3; function uniform_Variable (Self : access Item'Class; Named : in String) return Variable.uniform.mat4; function Attribute (Self : access Item'Class; Named : in String) return Attribute.view; function attribute_Location (Self : access Item'Class; Named : in String) return gl.GLuint; function ProgramInfoLog (Self : in Item) return String; -- TODO: Better name. -------------- -- Operations -- procedure add (Self : in out Item; Attribute : in openGL.Attribute.view); procedure enable (Self : in out Item); procedure enable_Attributes (Self : in Item); ------------ -- Uniforms -- procedure mvp_Transform_is (Self : in out Item; Now : in Matrix_4x4); procedure camera_Site_is (Self : in out Item; Now : in Vector_3) is null; procedure model_Matrix_is (Self : in out Item; Now : in Matrix_4x4) is null; procedure Lights_are (Self : in out Item; Now : in Light.items) is null; procedure Scale_is (Self : in out Item; Now : in Vector_3); procedure set_Uniforms (Self : in Item); ---------- -- Privvy TODO: move this to privvy child package. -- subtype a_gl_Program is gl.GLuint; function gl_Program (Self : in Item) return a_gl_Program; private type Item is tagged limited record gl_Program : gl.GLuint := 0; vertex_Shader : Shader.view; fragment_Shader : Shader.view; Attributes : openGL.Attribute.views (1 .. 8); attribute_Count : Natural := 0; mvp_Transform : Matrix_4x4; Scale : Vector_3 := (1.0, 1.0, 1.0); end record; ------------- -- Parameters -- type Parameters is limited new openGL.Parameters with record Program : openGL.Program.view; end record; end openGL.Program;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . O S _ I N T E R F A C E -- -- -- -- S p e c -- -- -- -- Copyright (C) 1997-2016 Free Software Foundation, Inc. -- -- -- -- GNARL 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/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- -- The GNARL files that were developed for RTEMS are maintained by On-Line -- -- Applications Research Corporation (http://www.oarcorp.com) in coopera- -- -- tion with Ada Core Technologies Inc. and Florida State University. -- -- -- ------------------------------------------------------------------------------ -- This is the RTEMS version of this package. -- -- RTEMS target names are of the form CPU-rtems. -- This implementation is designed to work on ALL RTEMS targets. -- The RTEMS implementation is primarily based upon the POSIX threads -- API but there are also bindings to GNAT/RTEMS support routines -- to insulate this code from C API specific details and, in some -- cases, obtain target architecture and BSP specific information -- that is unavailable at the time this package is built. -- This package encapsulates all direct interfaces to OS services -- that are needed by children of System. -- PLEASE DO NOT add any with-clauses to this package -- or remove the pragma Preelaborate. -- It is designed to be a bottom-level (leaf) package. with Interfaces.C; with System.OS_Constants; package System.OS_Interface is pragma Preelaborate; -- This interface assumes that "unsigned" is a 32-bit entity. This -- will correspond to RTEMS object ids. subtype rtems_id is Interfaces.C.unsigned; subtype int is Interfaces.C.int; subtype char is Interfaces.C.char; subtype short is Interfaces.C.short; subtype long is Interfaces.C.long; subtype unsigned is Interfaces.C.unsigned; subtype unsigned_short is Interfaces.C.unsigned_short; subtype unsigned_long is Interfaces.C.unsigned_long; subtype unsigned_char is Interfaces.C.unsigned_char; subtype plain_char is Interfaces.C.plain_char; subtype size_t is Interfaces.C.size_t; ----------- -- Errno -- ----------- function errno return int; pragma Import (C, errno, "__get_errno"); EAGAIN : constant := System.OS_Constants.EAGAIN; EINTR : constant := System.OS_Constants.EINTR; EINVAL : constant := System.OS_Constants.EINVAL; ENOMEM : constant := System.OS_Constants.ENOMEM; ETIMEDOUT : constant := System.OS_Constants.ETIMEDOUT; ------------- -- Signals -- ------------- Num_HW_Interrupts : constant := 256; Max_HW_Interrupt : constant := Num_HW_Interrupts - 1; type HW_Interrupt is new int range 0 .. Max_HW_Interrupt; Max_Interrupt : constant := Max_HW_Interrupt; type Signal is new int range 0 .. Max_Interrupt; SIGXCPU : constant := 0; -- XCPU SIGHUP : constant := 1; -- hangup SIGINT : constant := 2; -- interrupt (rubout) SIGQUIT : constant := 3; -- quit (ASCD FS) SIGILL : constant := 4; -- illegal instruction (not reset) SIGTRAP : constant := 5; -- trace trap (not reset) SIGIOT : constant := 6; -- IOT instruction SIGABRT : constant := 6; -- used by abort, replace SIGIOT in the future SIGEMT : constant := 7; -- EMT instruction SIGFPE : constant := 8; -- floating point exception SIGKILL : constant := 9; -- kill (cannot be caught or ignored) SIGBUS : constant := 10; -- bus error SIGSEGV : constant := 11; -- segmentation violation SIGSYS : constant := 12; -- bad argument to system call SIGPIPE : constant := 13; -- write on a pipe with no one to read it SIGALRM : constant := 14; -- alarm clock SIGTERM : constant := 15; -- software termination signal from kill SIGUSR1 : constant := 16; -- user defined signal 1 SIGUSR2 : constant := 17; -- user defined signal 2 SIGADAABORT : constant := SIGABRT; type Signal_Set is array (Natural range <>) of Signal; Unmasked : constant Signal_Set := (SIGTRAP, SIGALRM, SIGEMT); Reserved : constant Signal_Set := (1 .. 1 => SIGKILL); type sigset_t is private; function sigaddset (set : access sigset_t; sig : Signal) return int; pragma Import (C, sigaddset, "sigaddset"); function sigdelset (set : access sigset_t; sig : Signal) return int; pragma Import (C, sigdelset, "sigdelset"); function sigfillset (set : access sigset_t) return int; pragma Import (C, sigfillset, "sigfillset"); function sigismember (set : access sigset_t; sig : Signal) return int; pragma Import (C, sigismember, "sigismember"); function sigemptyset (set : access sigset_t) return int; pragma Import (C, sigemptyset, "sigemptyset"); type struct_sigaction is record sa_flags : int; sa_mask : sigset_t; sa_handler : System.Address; end record; pragma Convention (C, struct_sigaction); type struct_sigaction_ptr is access all struct_sigaction; SA_SIGINFO : constant := 16#02#; SA_ONSTACK : constant := 16#00#; -- SA_ONSTACK is not defined on RTEMS, but it is referred to in the POSIX -- implementation of System.Interrupt_Management. Therefore we define a -- dummy value of zero here so that setting this flag is a nop. SIG_BLOCK : constant := 1; SIG_UNBLOCK : constant := 2; SIG_SETMASK : constant := 3; SIG_DFL : constant := 0; SIG_IGN : constant := 1; function sigaction (sig : Signal; act : struct_sigaction_ptr; oact : struct_sigaction_ptr) return int; pragma Import (C, sigaction, "sigaction"); ---------- -- Time -- ---------- Time_Slice_Supported : constant Boolean := True; -- Indicates whether time slicing is supported (i.e SCHED_RR is supported) type timespec is private; type clockid_t is new int; CLOCK_REALTIME : constant clockid_t; CLOCK_MONOTONIC : constant clockid_t; function clock_gettime (clock_id : clockid_t; tp : access timespec) return int; pragma Import (C, clock_gettime, "clock_gettime"); function clock_getres (clock_id : clockid_t; res : access timespec) return int; pragma Import (C, clock_getres, "clock_getres"); function To_Duration (TS : timespec) return Duration; pragma Inline (To_Duration); function To_Timespec (D : Duration) return timespec; pragma Inline (To_Timespec); ------------------------- -- Priority Scheduling -- ------------------------- SCHED_FIFO : constant := 1; SCHED_RR : constant := 2; SCHED_OTHER : constant := 0; function To_Target_Priority (Prio : System.Any_Priority) return Interfaces.C.int; -- Maps System.Any_Priority to a POSIX priority ------------- -- Process -- ------------- type pid_t is private; function kill (pid : pid_t; sig : Signal) return int; pragma Import (C, kill, "kill"); function getpid return pid_t; pragma Import (C, getpid, "getpid"); --------- -- LWP -- --------- function lwp_self return System.Address; -- lwp_self does not exist on this thread library, revert to pthread_self -- which is the closest approximation (with getpid). This function is -- needed to share 7staprop.adb across POSIX-like targets. pragma Import (C, lwp_self, "pthread_self"); ------------- -- Threads -- ------------- type Thread_Body is access function (arg : System.Address) return System.Address; pragma Convention (C, Thread_Body); type pthread_t is private; subtype Thread_Id is pthread_t; type pthread_mutex_t is limited private; type pthread_rwlock_t is limited private; type pthread_cond_t is limited private; type pthread_attr_t is limited private; type pthread_mutexattr_t is limited private; type pthread_rwlockattr_t is limited private; type pthread_condattr_t is limited private; type pthread_key_t is private; No_Key : constant pthread_key_t; PTHREAD_CREATE_DETACHED : constant := 0; PTHREAD_SCOPE_PROCESS : constant := 0; PTHREAD_SCOPE_SYSTEM : constant := 1; ----------- -- Stack -- ----------- type stack_t is record ss_sp : System.Address; ss_flags : int; ss_size : size_t; end record; pragma Convention (C, stack_t); function sigaltstack (ss : not null access stack_t; oss : access stack_t) return int; Alternate_Stack : aliased System.Address; -- This is a dummy definition, never used (Alternate_Stack_Size is null) Alternate_Stack_Size : constant := 0; -- No alternate signal stack is used on this platform Stack_Base_Available : constant Boolean := False; -- Indicates whether the stack base is available on this target. -- This allows us to share s-osinte.adb between all the FSU/RTEMS -- run time. -- Note that this value can only be true if pthread_t has a complete -- definition that corresponds exactly to the C header files. function Get_Stack_Base (thread : pthread_t) return Address; pragma Inline (Get_Stack_Base); -- returns the stack base of the specified thread. -- Only call this function when Stack_Base_Available is True. -- These two functions are only needed to share s-taprop.adb with -- FSU threads. function Get_Page_Size return int; pragma Import (C, Get_Page_Size, "getpagesize"); -- Returns the size of a page PROT_ON : constant := 0; PROT_OFF : constant := 0; function mprotect (addr : Address; len : size_t; prot : int) return int; pragma Import (C, mprotect); ----------------------------------------- -- Nonstandard Thread Initialization -- ----------------------------------------- procedure pthread_init; -- FSU_THREADS requires pthread_init, which is nonstandard -- and this should be invoked during the elaboration of s-taprop.adb -- -- RTEMS does not require this so we provide an empty Ada body. ------------------------- -- POSIX.1c Section 3 -- ------------------------- function sigwait (set : access sigset_t; sig : access Signal) return int; pragma Import (C, sigwait, "sigwait"); function pthread_kill (thread : pthread_t; sig : Signal) return int; pragma Import (C, pthread_kill, "pthread_kill"); function pthread_sigmask (how : int; set : access sigset_t; oset : access sigset_t) return int; pragma Import (C, pthread_sigmask, "pthread_sigmask"); ---------------------------- -- POSIX.1c Section 11 -- ---------------------------- function pthread_mutexattr_init (attr : access pthread_mutexattr_t) return int; pragma Import (C, pthread_mutexattr_init, "pthread_mutexattr_init"); function pthread_mutexattr_destroy (attr : access pthread_mutexattr_t) return int; pragma Import (C, pthread_mutexattr_destroy, "pthread_mutexattr_destroy"); function pthread_mutex_init (mutex : access pthread_mutex_t; attr : access pthread_mutexattr_t) return int; pragma Import (C, pthread_mutex_init, "pthread_mutex_init"); function pthread_mutex_destroy (mutex : access pthread_mutex_t) return int; pragma Import (C, pthread_mutex_destroy, "pthread_mutex_destroy"); function pthread_mutex_lock (mutex : access pthread_mutex_t) return int; pragma Import (C, pthread_mutex_lock, "pthread_mutex_lock"); function pthread_mutex_unlock (mutex : access pthread_mutex_t) return int; pragma Import (C, pthread_mutex_unlock, "pthread_mutex_unlock"); function pthread_rwlockattr_init (attr : access pthread_rwlockattr_t) return int; pragma Import (C, pthread_rwlockattr_init, "pthread_rwlockattr_init"); function pthread_rwlockattr_destroy (attr : access pthread_rwlockattr_t) return int; pragma Import (C, pthread_rwlockattr_destroy, "pthread_rwlockattr_destroy"); PTHREAD_RWLOCK_PREFER_READER_NP : constant := 0; PTHREAD_RWLOCK_PREFER_WRITER_NP : constant := 1; PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP : constant := 2; function pthread_rwlockattr_setkind_np (attr : access pthread_rwlockattr_t; pref : int) return int; function pthread_rwlock_init (mutex : access pthread_rwlock_t; attr : access pthread_rwlockattr_t) return int; pragma Import (C, pthread_rwlock_init, "pthread_rwlock_init"); function pthread_rwlock_destroy (mutex : access pthread_rwlock_t) return int; pragma Import (C, pthread_rwlock_destroy, "pthread_rwlock_destroy"); function pthread_rwlock_rdlock (mutex : access pthread_rwlock_t) return int; pragma Import (C, pthread_rwlock_rdlock, "pthread_rwlock_rdlock"); function pthread_rwlock_wrlock (mutex : access pthread_rwlock_t) return int; pragma Import (C, pthread_rwlock_wrlock, "pthread_rwlock_wrlock"); function pthread_rwlock_unlock (mutex : access pthread_rwlock_t) return int; pragma Import (C, pthread_rwlock_unlock, "pthread_rwlock_unlock"); function pthread_condattr_init (attr : access pthread_condattr_t) return int; pragma Import (C, pthread_condattr_init, "pthread_condattr_init"); function pthread_condattr_destroy (attr : access pthread_condattr_t) return int; pragma Import (C, pthread_condattr_destroy, "pthread_condattr_destroy"); function pthread_cond_init (cond : access pthread_cond_t; attr : access pthread_condattr_t) return int; pragma Import (C, pthread_cond_init, "pthread_cond_init"); function pthread_cond_destroy (cond : access pthread_cond_t) return int; pragma Import (C, pthread_cond_destroy, "pthread_cond_destroy"); function pthread_cond_signal (cond : access pthread_cond_t) return int; pragma Import (C, pthread_cond_signal, "pthread_cond_signal"); function pthread_cond_wait (cond : access pthread_cond_t; mutex : access pthread_mutex_t) return int; pragma Import (C, pthread_cond_wait, "pthread_cond_wait"); function pthread_cond_timedwait (cond : access pthread_cond_t; mutex : access pthread_mutex_t; abstime : access timespec) return int; pragma Import (C, pthread_cond_timedwait, "pthread_cond_timedwait"); Relative_Timed_Wait : constant Boolean := False; -- pthread_cond_timedwait requires an absolute delay time -------------------------- -- POSIX.1c Section 13 -- -------------------------- PTHREAD_PRIO_NONE : constant := 0; PTHREAD_PRIO_PROTECT : constant := 2; PTHREAD_PRIO_INHERIT : constant := 1; function pthread_mutexattr_setprotocol (attr : access pthread_mutexattr_t; protocol : int) return int; pragma Import (C, pthread_mutexattr_setprotocol); function pthread_mutexattr_setprioceiling (attr : access pthread_mutexattr_t; prioceiling : int) return int; pragma Import (C, pthread_mutexattr_setprioceiling, "pthread_mutexattr_setprioceiling"); type struct_sched_param is record sched_priority : int; ss_low_priority : int; ss_replenish_period : timespec; ss_initial_budget : timespec; sched_ss_max_repl : int; end record; pragma Convention (C, struct_sched_param); function pthread_setschedparam (thread : pthread_t; policy : int; param : access struct_sched_param) return int; pragma Import (C, pthread_setschedparam, "pthread_setschedparam"); function pthread_attr_setscope (attr : access pthread_attr_t; contentionscope : int) return int; pragma Import (C, pthread_attr_setscope, "pthread_attr_setscope"); function pthread_attr_setinheritsched (attr : access pthread_attr_t; inheritsched : int) return int; pragma Import (C, pthread_attr_setinheritsched); function pthread_attr_setschedpolicy (attr : access pthread_attr_t; policy : int) return int; pragma Import (C, pthread_attr_setschedpolicy); function pthread_attr_setschedparam (attr : access pthread_attr_t; sched_param : int) return int; pragma Import (C, pthread_attr_setschedparam); function sched_yield return int; pragma Import (C, sched_yield, "sched_yield"); --------------------------- -- P1003.1c - Section 16 -- --------------------------- function pthread_attr_init (attributes : access pthread_attr_t) return int; pragma Import (C, pthread_attr_init, "pthread_attr_init"); function pthread_attr_destroy (attributes : access pthread_attr_t) return int; pragma Import (C, pthread_attr_destroy, "pthread_attr_destroy"); function pthread_attr_setdetachstate (attr : access pthread_attr_t; detachstate : int) return int; pragma Import (C, pthread_attr_setdetachstate); function pthread_attr_setstacksize (attr : access pthread_attr_t; stacksize : size_t) return int; pragma Import (C, pthread_attr_setstacksize, "pthread_attr_setstacksize"); function pthread_create (thread : access pthread_t; attributes : access pthread_attr_t; start_routine : Thread_Body; arg : System.Address) return int; pragma Import (C, pthread_create, "pthread_create"); procedure pthread_exit (status : System.Address); pragma Import (C, pthread_exit, "pthread_exit"); function pthread_self return pthread_t; pragma Import (C, pthread_self, "pthread_self"); -------------------------- -- POSIX.1c Section 17 -- -------------------------- function pthread_setspecific (key : pthread_key_t; value : System.Address) return int; pragma Import (C, pthread_setspecific, "pthread_setspecific"); function pthread_getspecific (key : pthread_key_t) return System.Address; pragma Import (C, pthread_getspecific, "pthread_getspecific"); type destructor_pointer is access procedure (arg : System.Address); pragma Convention (C, destructor_pointer); function pthread_key_create (key : access pthread_key_t; destructor : destructor_pointer) return int; pragma Import (C, pthread_key_create, "pthread_key_create"); ------------------------------------------------------------ -- Binary Semaphore Wrapper to Support Interrupt Tasks -- ------------------------------------------------------------ type Binary_Semaphore_Id is new rtems_id; function Binary_Semaphore_Create return Binary_Semaphore_Id; pragma Import ( C, Binary_Semaphore_Create, "__gnat_binary_semaphore_create"); function Binary_Semaphore_Delete (ID : Binary_Semaphore_Id) return int; pragma Import ( C, Binary_Semaphore_Delete, "__gnat_binary_semaphore_delete"); function Binary_Semaphore_Obtain (ID : Binary_Semaphore_Id) return int; pragma Import ( C, Binary_Semaphore_Obtain, "__gnat_binary_semaphore_obtain"); function Binary_Semaphore_Release (ID : Binary_Semaphore_Id) return int; pragma Import ( C, Binary_Semaphore_Release, "__gnat_binary_semaphore_release"); function Binary_Semaphore_Flush (ID : Binary_Semaphore_Id) return int; pragma Import ( C, Binary_Semaphore_Flush, "__gnat_binary_semaphore_flush"); ------------------------------------------------------------ -- Hardware Interrupt Wrappers to Support Interrupt Tasks -- ------------------------------------------------------------ type Interrupt_Handler is access procedure (parameter : System.Address); pragma Convention (C, Interrupt_Handler); type Interrupt_Vector is new System.Address; function Interrupt_Connect (vector : Interrupt_Vector; handler : Interrupt_Handler; parameter : System.Address := System.Null_Address) return int; pragma Import (C, Interrupt_Connect, "__gnat_interrupt_connect"); -- Use this to set up an user handler. The routine installs a -- a user handler which is invoked after RTEMS has saved enough -- context for a high-level language routine to be safely invoked. function Interrupt_Vector_Get (Vector : Interrupt_Vector) return Interrupt_Handler; pragma Import (C, Interrupt_Vector_Get, "__gnat_interrupt_get"); -- Use this to get the existing handler for later restoral. procedure Interrupt_Vector_Set (Vector : Interrupt_Vector; Handler : Interrupt_Handler); pragma Import (C, Interrupt_Vector_Set, "__gnat_interrupt_set"); -- Use this to restore a handler obtained using Interrupt_Vector_Get. function Interrupt_Number_To_Vector (intNum : int) return Interrupt_Vector; -- Convert a logical interrupt number to the hardware interrupt vector -- number used to connect the interrupt. pragma Import ( C, Interrupt_Number_To_Vector, "__gnat_interrupt_number_to_vector" ); private type sigset_t is new int; type pid_t is new int; type time_t is new Long_Long_Integer; type timespec is record tv_sec : time_t; tv_nsec : long; end record; pragma Convention (C, timespec); CLOCK_REALTIME : constant clockid_t := System.OS_Constants.CLOCK_REALTIME; CLOCK_MONOTONIC : constant clockid_t := System.OS_Constants.CLOCK_MONOTONIC; subtype char_array is Interfaces.C.char_array; type pthread_attr_t is record Data : char_array (1 .. OS_Constants.PTHREAD_ATTR_SIZE); end record; pragma Convention (C, pthread_attr_t); for pthread_attr_t'Alignment use Interfaces.C.double'Alignment; type pthread_condattr_t is record Data : char_array (1 .. OS_Constants.PTHREAD_CONDATTR_SIZE); end record; pragma Convention (C, pthread_condattr_t); for pthread_condattr_t'Alignment use Interfaces.C.double'Alignment; type pthread_mutexattr_t is record Data : char_array (1 .. OS_Constants.PTHREAD_MUTEXATTR_SIZE); end record; pragma Convention (C, pthread_mutexattr_t); for pthread_mutexattr_t'Alignment use Interfaces.C.int'Alignment; type pthread_rwlockattr_t is record Data : char_array (1 .. OS_Constants.PTHREAD_RWLOCKATTR_SIZE); end record; pragma Convention (C, pthread_rwlockattr_t); for pthread_rwlockattr_t'Alignment use Interfaces.C.int'Alignment; type pthread_t is new rtems_id; type pthread_mutex_t is record Data : char_array (1 .. OS_Constants.PTHREAD_MUTEX_SIZE); end record; pragma Convention (C, pthread_mutex_t); for pthread_mutex_t'Alignment use Interfaces.C.double'Alignment; type pthread_rwlock_t is record Data : char_array (1 .. OS_Constants.PTHREAD_RWLOCK_SIZE); end record; pragma Convention (C, pthread_rwlock_t); for pthread_rwlock_t'Alignment use Interfaces.C.size_t'Alignment; type pthread_cond_t is record Data : char_array (1 .. OS_Constants.PTHREAD_COND_SIZE); end record; pragma Convention (C, pthread_cond_t); for pthread_cond_t'Alignment use Interfaces.C.size_t'Alignment; type pthread_key_t is new rtems_id; No_Key : constant pthread_key_t := 0; end System.OS_Interface;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T A S K _ A T T R I B U T E S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1991-1994, Florida State University -- -- Copyright (C) 1995-2006, AdaCore -- -- -- -- GNARL 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. GNARL 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 GNARL; 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. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ -- The following notes are provided in case someone decides the implementation -- of this package is too complicated, or too slow. Please read this before -- making any "simplifications". -- Correct implementation of this package is more difficult than one might -- expect. After considering (and coding) several alternatives, we settled on -- the present compromise. Things we do not like about this implementation -- include: -- - It is vulnerable to bad Task_Id values, to the extent of possibly -- trashing memory and crashing the runtime system. -- - It requires dynamic storage allocation for each new attribute value, -- except for types that happen to be the same size as System.Address, or -- shorter. -- - Instantiations at other than the library level rely on being able to -- do down-level calls to a procedure declared in the generic package body. -- This makes it potentially vulnerable to compiler changes. -- The main implementation issue here is that the connection from task to -- attribute is a potential source of dangling references. -- When a task goes away, we want to be able to recover all the storage -- associated with its attributes. The Ada mechanism for this is finalization, -- via controlled attribute types. For this reason, the ARM requires -- finalization of attribute values when the associated task terminates. -- This finalization must be triggered by the tasking runtime system, during -- termination of the task. Given the active set of instantiations of -- Ada.Task_Attributes is dynamic, the number and types of attributes -- belonging to a task will not be known until the task actually terminates. -- Some of these types may be controlled and some may not. The RTS must find -- some way to determine which of these attributes need finalization, and -- invoke the appropriate finalization on them. -- One way this might be done is to create a special finalization chain for -- each task, similar to the finalization chain that is used for controlled -- objects within the task. This would differ from the usual finalization -- chain in that it would not have a LIFO structure, since attributes may be -- added to a task at any time during its lifetime. This might be the right -- way to go for the longer term, but at present this approach is not open, -- since GNAT does not provide such special finalization support. -- Lacking special compiler support, the RTS is limited to the normal ways an -- application invokes finalization, i.e. -- a) Explicit call to the procedure Finalize, if we know the type has this -- operation defined on it. This is not sufficient, since we have no way -- of determining whether a given generic formal Attribute type is -- controlled, and no visibility of the associated Finalize procedure, in -- the generic body. -- b) Leaving the scope of a local object of a controlled type. This does not -- help, since the lifetime of an instantiation of Ada.Task_Attributes -- does not correspond to the lifetimes of the various tasks which may -- have that attribute. -- c) Assignment of another value to the object. This would not help, since -- we then have to finalize the new value of the object. -- d) Unchecked deallocation of an object of a controlled type. This seems to -- be the only mechanism available to the runtime system for finalization -- of task attributes. -- We considered two ways of using unchecked deallocation, both based on a -- linked list of that would hang from the task control block. -- In the first approach the objects on the attribute list are all derived -- from one controlled type, say T, and are linked using an access type to -- T'Class. The runtime system has an Unchecked_Deallocation for T'Class with -- access type T'Class, and uses this to deallocate and finalize all the -- items in the list. The limitation of this approach is that each -- instantiation of the package Ada.Task_Attributes derives a new record -- extension of T, and since T is controlled (RM 3.9.1 (3)), instantiation is -- only allowed at the library level. -- In the second approach the objects on the attribute list are of unrelated -- but structurally similar types. Unchecked conversion is used to circument -- Ada type checking. Each attribute-storage node contains not only the -- attribute value and a link for chaining, but also a pointer to descriptor -- for the corresponding instantiation of Task_Attributes. The instantiation -- descriptor contains pointer to a procedure that can do the correct -- deallocation and finalization for that type of attribute. On task -- termination, the runtime system uses the pointer to call the appropriate -- deallocator. -- While this gets around the limitation that instantations be at the library -- level, it relies on an implementation feature that may not always be safe, -- i.e. that it is safe to call the Deallocate procedure for an instantiation -- of Ada.Task_Attributes that no longer exists. In general, it seems this -- might result in dangling references. -- Another problem with instantiations deeper than the library level is that -- there is risk of storage leakage, or dangling references to reused -- storage. That is, if an instantiation of Ada.Task_Attributes is made -- within a procedure, what happens to the storage allocated for attributes, -- when the procedure call returns? Apparently (RM 7.6.1 (4)) any such -- objects must be finalized, since they will no longer be accessible, and in -- general one would expect that the storage they occupy would be recovered -- for later reuse. (If not, we would have a case of storage leakage.) -- Assuming the storage is recovered and later reused, we have potentially -- dangerous dangling references. When the procedure containing the -- instantiation of Ada.Task_Attributes returns, there may still be -- unterminated tasks with associated attribute values for that instantiation. -- When such tasks eventually terminate, the RTS will attempt to call the -- Deallocate procedure on them. If the corresponding storage has already -- been deallocated, when the master of the access type was left, we have a -- potential disaster. This disaster is compounded since the pointer to -- Deallocate is probably through a "trampoline" which will also have been -- destroyed. -- For this reason, we arrange to remove all dangling references before -- leaving the scope of an instantiation. This is ugly, since it requires -- traversing the list of all tasks, but it is no more ugly than a similar -- traversal that we must do at the point of instantiation in order to -- initialize the attributes of all tasks. At least we only need to do these -- traversals if the type is controlled. -- We chose to defer allocation of storage for attributes until the Reference -- function is called or the attribute is first set to a value different from -- the default initial one. This allows a potential savings in allocation, -- for attributes that are not used by all tasks. -- For efficiency, we reserve space in the TCB for a fixed number of -- direct-access attributes. These are required to be of a size that fits in -- the space of an object of type System.Address. Because we must use -- unchecked bitwise copy operations on these values, they cannot be of a -- controlled type, but that is covered automatically since controlled -- objects are too large to fit in the spaces. -- We originally deferred the initialization of these direct-access -- attributes, just as we do for the indirect-access attributes, and used a -- per-task bit vector to keep track of which attributes were currently -- defined for that task. We found that the overhead of maintaining this -- bit-vector seriously slowed down access to the attributes, and made the -- fetch operation non-atomic, so that even to read an attribute value -- required locking the TCB. Therefore, we now initialize such attributes for -- all existing tasks at the time of the attribute instantiation, and -- initialize existing attributes for each new task at the time it is -- created. -- The latter initialization requires a list of all the instantiation -- descriptors. Updates to this list, as well as the bit-vector that is used -- to reserve slots for attributes in the TCB, require mutual exclusion. That -- is provided by the Lock/Unlock_RTS. -- One special problem that added complexity to the design is that the -- per-task list of indirect attributes contains objects of different types. -- We use unchecked pointer conversion to link these nodes together and -- access them, but the records may not have identical internal structure. -- Initially, we thought it would be enough to allocate all the common -- components of the records at the front of each record, so that their -- positions would correspond. Unfortunately, GNAT adds "dope" information at -- the front of a record, if the record contains any controlled-type -- components. -- -- This means that the offset of the fields we use to link the nodes is at -- different positions on nodes of different types. To get around this, each -- attribute storage record consists of a core node and wrapper. The core -- nodes are all of the same type, and it is these that are linked together -- and generally "seen" by the RTS. Each core node contains a pointer to its -- own wrapper, which is a record that contains the core node along with an -- attribute value, approximately as follows: -- type Node; -- type Node_Access is access all Node; -- type Node_Access; -- type Access_Wrapper is access all Wrapper; -- type Node is record -- Next : Node_Access; -- ... -- Wrapper : Access_Wrapper; -- end record; -- type Wrapper is record -- Dummy_Node : aliased Node; -- Value : aliased Attribute; -- the generic formal type -- end record; -- Another interesting problem is with the initialization of the -- instantiation descriptors. Originally, we did this all via the Initialize -- procedure of the descriptor type and code in the package body. It turned -- out that the Initialize procedure needed quite a bit of information, -- including the size of the attribute type, the initial value of the -- attribute (if it fits in the TCB), and a pointer to the deallocator -- procedure. These needed to be "passed" in via access discriminants. GNAT -- was having trouble with access discriminants, so all this work was moved -- to the package body. with System.Error_Reporting; -- Used for Shutdown; with System.Storage_Elements; -- Used for Integer_Address with System.Task_Primitives.Operations; -- Used for Write_Lock -- Unlock -- Lock/Unlock_RTS with System.Tasking; -- Used for Access_Address -- Task_Id -- Direct_Index_Vector -- Direct_Index with System.Tasking.Initialization; -- Used for Defer_Abortion -- Undefer_Abortion -- Initialize_Attributes_Link -- Finalize_Attributes_Link with System.Tasking.Task_Attributes; -- Used for Access_Node -- Access_Dummy_Wrapper -- Deallocator -- Instance -- Node -- Access_Instance with Ada.Exceptions; -- Used for Raise_Exception with Unchecked_Conversion; with Unchecked_Deallocation; pragma Elaborate_All (System.Tasking.Task_Attributes); -- To ensure the initialization of object Local (below) will work package body Ada.Task_Attributes is use System.Error_Reporting, System.Tasking.Initialization, System.Tasking, System.Tasking.Task_Attributes, Ada.Exceptions; use type System.Tasking.Access_Address; package POP renames System.Task_Primitives.Operations; --------------------------- -- Unchecked Conversions -- --------------------------- -- The following type corresponds to Dummy_Wrapper, -- declared in System.Tasking.Task_Attributes. type Wrapper; type Access_Wrapper is access all Wrapper; pragma Warnings (Off); -- We turn warnings off for the following declarations of the -- To_Attribute_Handle conversions, since these are used only for small -- attributes where we know that there are no problems with alignment, but -- the compiler will generate warnings for the occurrences in the large -- attribute case, even though they will not actually be used. function To_Attribute_Handle is new Unchecked_Conversion (System.Address, Attribute_Handle); function To_Direct_Attribute_Element is new Unchecked_Conversion (System.Address, Direct_Attribute_Element); -- For reference to directly addressed task attributes type Access_Integer_Address is access all System.Storage_Elements.Integer_Address; function To_Attribute_Handle is new Unchecked_Conversion (Access_Integer_Address, Attribute_Handle); -- For reference to directly addressed task attributes pragma Warnings (On); -- End of warnings off region for directly addressed -- attribute conversion functions. function To_Access_Address is new Unchecked_Conversion (Access_Node, Access_Address); -- To store pointer to list of indirect attributes pragma Warnings (Off); function To_Access_Wrapper is new Unchecked_Conversion (Access_Dummy_Wrapper, Access_Wrapper); pragma Warnings (On); -- To fetch pointer to actual wrapper of attribute node. We turn off -- warnings since this may generate an alignment warning. The warning can -- be ignored since Dummy_Wrapper is only a non-generic standin for the -- real wrapper type (we never actually allocate objects of type -- Dummy_Wrapper). function To_Access_Dummy_Wrapper is new Unchecked_Conversion (Access_Wrapper, Access_Dummy_Wrapper); -- To store pointer to actual wrapper of attribute node function To_Task_Id is new Unchecked_Conversion (Task_Identification.Task_Id, Task_Id); -- To access TCB of identified task type Local_Deallocator is access procedure (P : in out Access_Node); function To_Lib_Level_Deallocator is new Unchecked_Conversion (Local_Deallocator, Deallocator); -- To defeat accessibility check pragma Warnings (On); ------------------------ -- Storage Management -- ------------------------ procedure Deallocate (P : in out Access_Node); -- Passed to the RTS via unchecked conversion of a pointer to -- permit finalization and deallocation of attribute storage nodes -------------------------- -- Instantiation Record -- -------------------------- Local : aliased Instance; -- Initialized in package body type Wrapper is record Dummy_Node : aliased Node; Value : aliased Attribute := Initial_Value; -- The generic formal type, may be controlled end record; -- A number of unchecked conversions involving Wrapper_Access sources -- are performed in this unit. We have to ensure that the designated -- object is always strictly enough aligned. for Wrapper'Alignment use Standard'Maximum_Alignment; procedure Free is new Unchecked_Deallocation (Wrapper, Access_Wrapper); procedure Deallocate (P : in out Access_Node) is T : Access_Wrapper := To_Access_Wrapper (P.Wrapper); begin Free (T); end Deallocate; --------------- -- Reference -- --------------- function Reference (T : Task_Identification.Task_Id := Task_Identification.Current_Task) return Attribute_Handle is TT : constant Task_Id := To_Task_Id (T); Error_Message : constant String := "Trying to get the reference of a "; begin if TT = null then Raise_Exception (Program_Error'Identity, Error_Message & "null task"); end if; if TT.Common.State = Terminated then Raise_Exception (Tasking_Error'Identity, Error_Message & "terminated task"); end if; -- Directly addressed case if Local.Index /= 0 then -- Return the attribute handle. Warnings off because this return -- statement generates alignment warnings for large attributes -- (but will never be executed in this case anyway). pragma Warnings (Off); return To_Attribute_Handle (TT.Direct_Attributes (Local.Index)'Address); pragma Warnings (On); -- Not directly addressed else declare P : Access_Node := To_Access_Node (TT.Indirect_Attributes); W : Access_Wrapper; Self_Id : constant Task_Id := POP.Self; begin Defer_Abort (Self_Id); POP.Lock_RTS; while P /= null loop if P.Instance = Access_Instance'(Local'Unchecked_Access) then POP.Unlock_RTS; Undefer_Abort (Self_Id); return To_Access_Wrapper (P.Wrapper).Value'Access; end if; P := P.Next; end loop; -- Unlock the RTS here to follow the lock ordering rule -- that prevent us from using new (i.e the Global_Lock) while -- holding any other lock. POP.Unlock_RTS; W := new Wrapper' ((null, Local'Unchecked_Access, null), Initial_Value); POP.Lock_RTS; P := W.Dummy_Node'Unchecked_Access; P.Wrapper := To_Access_Dummy_Wrapper (W); P.Next := To_Access_Node (TT.Indirect_Attributes); TT.Indirect_Attributes := To_Access_Address (P); POP.Unlock_RTS; Undefer_Abort (Self_Id); return W.Value'Access; exception when others => POP.Unlock_RTS; Undefer_Abort (Self_Id); raise; end; end if; pragma Assert (Shutdown ("Should never get here in Reference")); return null; exception when Tasking_Error | Program_Error => raise; when others => raise Program_Error; end Reference; ------------------ -- Reinitialize -- ------------------ procedure Reinitialize (T : Task_Identification.Task_Id := Task_Identification.Current_Task) is TT : constant Task_Id := To_Task_Id (T); Error_Message : constant String := "Trying to Reinitialize a "; begin if TT = null then Raise_Exception (Program_Error'Identity, Error_Message & "null task"); end if; if TT.Common.State = Terminated then Raise_Exception (Tasking_Error'Identity, Error_Message & "terminated task"); end if; if Local.Index /= 0 then Set_Value (Initial_Value, T); else declare P, Q : Access_Node; W : Access_Wrapper; Self_Id : constant Task_Id := POP.Self; begin Defer_Abort (Self_Id); POP.Lock_RTS; Q := To_Access_Node (TT.Indirect_Attributes); while Q /= null loop if Q.Instance = Access_Instance'(Local'Unchecked_Access) then if P = null then TT.Indirect_Attributes := To_Access_Address (Q.Next); else P.Next := Q.Next; end if; W := To_Access_Wrapper (Q.Wrapper); Free (W); POP.Unlock_RTS; Undefer_Abort (Self_Id); return; end if; P := Q; Q := Q.Next; end loop; POP.Unlock_RTS; Undefer_Abort (Self_Id); exception when others => POP.Unlock_RTS; Undefer_Abort (Self_Id); raise; end; end if; exception when Tasking_Error | Program_Error => raise; when others => raise Program_Error; end Reinitialize; --------------- -- Set_Value -- --------------- procedure Set_Value (Val : Attribute; T : Task_Identification.Task_Id := Task_Identification.Current_Task) is TT : constant Task_Id := To_Task_Id (T); Error_Message : constant String := "Trying to Set the Value of a "; begin if TT = null then Raise_Exception (Program_Error'Identity, Error_Message & "null task"); end if; if TT.Common.State = Terminated then Raise_Exception (Tasking_Error'Identity, Error_Message & "terminated task"); end if; -- Directly addressed case if Local.Index /= 0 then -- Set attribute handle, warnings off, because this code can generate -- alignment warnings with large attributes (but of course will not -- be executed in this case, since we never have direct addressing in -- such cases). pragma Warnings (Off); To_Attribute_Handle (TT.Direct_Attributes (Local.Index)'Address).all := Val; pragma Warnings (On); return; end if; -- Not directly addressed declare P : Access_Node := To_Access_Node (TT.Indirect_Attributes); W : Access_Wrapper; Self_Id : constant Task_Id := POP.Self; begin Defer_Abort (Self_Id); POP.Lock_RTS; while P /= null loop if P.Instance = Access_Instance'(Local'Unchecked_Access) then To_Access_Wrapper (P.Wrapper).Value := Val; POP.Unlock_RTS; Undefer_Abort (Self_Id); return; end if; P := P.Next; end loop; -- Unlock RTS here to follow the lock ordering rule that prevent us -- from using new (i.e the Global_Lock) while holding any other -- lock. POP.Unlock_RTS; W := new Wrapper'((null, Local'Unchecked_Access, null), Val); POP.Lock_RTS; P := W.Dummy_Node'Unchecked_Access; P.Wrapper := To_Access_Dummy_Wrapper (W); P.Next := To_Access_Node (TT.Indirect_Attributes); TT.Indirect_Attributes := To_Access_Address (P); POP.Unlock_RTS; Undefer_Abort (Self_Id); exception when others => POP.Unlock_RTS; Undefer_Abort (Self_Id); raise; end; exception when Tasking_Error | Program_Error => raise; when others => raise Program_Error; end Set_Value; ----------- -- Value -- ----------- function Value (T : Task_Identification.Task_Id := Task_Identification.Current_Task) return Attribute is TT : constant Task_Id := To_Task_Id (T); Error_Message : constant String := "Trying to get the Value of a "; begin if TT = null then Raise_Exception (Program_Error'Identity, Error_Message & "null task"); end if; if TT.Common.State = Terminated then Raise_Exception (Program_Error'Identity, Error_Message & "terminated task"); end if; -- Directly addressed case if Local.Index /= 0 then -- Get value of attribute. Warnings off, because for large -- attributes, this code can generate alignment warnings. But of -- course large attributes are never directly addressed so in fact -- we will never execute the code in this case. pragma Warnings (Off); return To_Attribute_Handle (TT.Direct_Attributes (Local.Index)'Address).all; pragma Warnings (On); end if; -- Not directly addressed declare P : Access_Node; Result : Attribute; Self_Id : constant Task_Id := POP.Self; begin Defer_Abort (Self_Id); POP.Lock_RTS; P := To_Access_Node (TT.Indirect_Attributes); while P /= null loop if P.Instance = Access_Instance'(Local'Unchecked_Access) then Result := To_Access_Wrapper (P.Wrapper).Value; POP.Unlock_RTS; Undefer_Abort (Self_Id); return Result; end if; P := P.Next; end loop; POP.Unlock_RTS; Undefer_Abort (Self_Id); return Initial_Value; exception when others => POP.Unlock_RTS; Undefer_Abort (Self_Id); raise; end; exception when Tasking_Error | Program_Error => raise; when others => raise Program_Error; end Value; -- Start of elaboration code for package Ada.Task_Attributes begin -- This unchecked conversion can give warnings when alignments -- are incorrect, but they will not be used in such cases anyway, -- so the warnings can be safely ignored. pragma Warnings (Off); Local.Deallocate := To_Lib_Level_Deallocator (Deallocate'Access); pragma Warnings (On); declare Two_To_J : Direct_Index_Vector; Self_Id : constant Task_Id := POP.Self; begin Defer_Abort (Self_Id); -- Need protection for updating links to per-task initialization and -- finalization routines, in case some task is being created or -- terminated concurrently. POP.Lock_RTS; -- Add this instantiation to the list of all instantiations Local.Next := System.Tasking.Task_Attributes.All_Attributes; System.Tasking.Task_Attributes.All_Attributes := Local'Unchecked_Access; -- Try to find space for the attribute in the TCB Local.Index := 0; Two_To_J := 1; if Attribute'Size <= System.Address'Size then for J in Direct_Index_Range loop if (Two_To_J and In_Use) = 0 then -- Reserve location J for this attribute In_Use := In_Use or Two_To_J; Local.Index := J; -- This unchecked conversions can give a warning when the the -- alignment is incorrect, but it will not be used in such a -- case anyway, so the warning can be safely ignored. pragma Warnings (Off); To_Attribute_Handle (Local.Initial_Value'Access).all := Initial_Value; pragma Warnings (On); exit; end if; Two_To_J := Two_To_J * 2; end loop; end if; -- Attribute goes directly in the TCB if Local.Index /= 0 then -- Replace stub for initialization routine that is called at task -- creation. Initialization.Initialize_Attributes_Link := System.Tasking.Task_Attributes.Initialize_Attributes'Access; -- Initialize the attribute, for all tasks declare C : System.Tasking.Task_Id := System.Tasking.All_Tasks_List; begin while C /= null loop C.Direct_Attributes (Local.Index) := To_Direct_Attribute_Element (System.Storage_Elements.To_Address (Local.Initial_Value)); C := C.Common.All_Tasks_Link; end loop; end; -- Attribute goes into a node onto a linked list else -- Replace stub for finalization routine that is called at task -- termination. Initialization.Finalize_Attributes_Link := System.Tasking.Task_Attributes.Finalize_Attributes'Access; end if; POP.Unlock_RTS; Undefer_Abort (Self_Id); end; end Ada.Task_Attributes;
with datos; use datos; with intercambiar; procedure Ordenar_Por_Burbuja (L : in out Lista_Enteros) is -- pre: -- post: L contiene los valores iniciales en orden ascendente I : Integer; J: Integer; Cuenta : Integer; begin I := L.Numeros'First; if L.Cont > 1 then loop Cuenta := 0; J := 1; loop exit when J > L.Cont-1; if L.Numeros(J) > L.Numeros(J+1) then Intercambiar(J, J+1, L); Cuenta := Cuenta+1; end if; J:= J+1; end loop; I := I+1; exit when I > L.Cont-1 or Cuenta = 0; -- Usamos esto como Boolean para comprobar si hay cambios end loop; end if; end Ordenar_Por_Burbuja;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- A D A . C O N T A I N E R S . G E N E R I C _ A R R A Y _ S O R T -- -- -- -- S p e c -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. In accordance with the copyright of that document, you can freely -- -- copy and modify this specification, provided that if you redistribute a -- -- modified version, any changes that you have made are clearly indicated. -- -- -- ------------------------------------------------------------------------------ generic type Index_Type is (<>); type Element_Type is private; type Array_Type is array (Index_Type range <>) of Element_Type; with function "<" (Left, Right : Element_Type) return Boolean is <>; procedure Ada.Containers.Generic_Array_Sort (Container : in out Array_Type); pragma Pure (Ada.Containers.Generic_Array_Sort); -- Reorders the elements of Container such that the elements are sorted -- smallest first as determined by the generic formal "<" operator provided. -- Any exception raised during evaluation of "<" is propagated. -- -- The actual function for the generic formal function "<" is expected to -- return the same value each time it is called with a particular pair of -- element values. It should not modify Container and it should define a -- strict weak ordering relationship: irreflexive, asymmetric, transitive, and -- in addition, if x < y for any values x and y, then for all other values z, -- (x < z) or (z < y). If the actual for "<" behaves in some other manner, -- the behavior of the instance of Generic_Array_Sort is unspecified. The -- number of times Generic_Array_Sort calls "<" is unspecified.
-- -*- Mode: Ada -*- -- Filename : ether.ads -- Description : Root of the Ether SCGI library. -- Author : Luke A. Guest -- Created On : Mon Mar 28 11:43:06 2011 with Ada.Strings.Unbounded; package Ether is Initialisation_Error : exception; -- Initialise the library with the max umber of bytes a request can have as content-type -- and the library's upload directory, i.e. where to save files to. procedure Initialise (Bytes : in Positive; Upload_Dir : in String; Temp_Dir : in String); -- Has the library been initialisied? function Is_Initialised return Boolean; -- Return the max number of bytes a request can have as it's content-type. function Max_Request_Size return Positive; -- Get the directory to where the uploaded files are saved to. function Upload_Dir return String; -- Get the directory where temporary files go. function Temp_Dir return String; private package US renames Ada.Strings.Unbounded; Initialised : Boolean := False; Max_Request_Bytes : Positive := 2000; Uploads : US.Unbounded_String := US.Null_Unbounded_String; Temps : US.Unbounded_String := US.Null_Unbounded_String; end Ether;
with Ada.Containers.Formal_Hashed_Maps; with Ada.Strings.Hash; with Ada.Directories; with DOM.Core.Documents; with DOM.Core.Elements; with Input_Sources.Strings; with DOM.Readers; with Sax.Encodings; with UxAS.Common.String_Constant; package body UxAS.Comms.LMCP_Net_Client.Service is function Hashed_Service_Type_Name (Element : Service_Type_Name) return Ada.Containers.Hash_Type is (Ada.Strings.Hash (Value (Element))); package Creation_Function_To_Service_Names is new Ada.Containers.Formal_Hashed_Maps (Element_Type => Service_Creation_Function_Pointer, Key_Type => Service_Type_Name, Hash => Hashed_Service_Type_Name, Equivalent_Keys => "="); Function_Map_Capacity : constant := 100; -- arbitrary subtype Creation_Function_Map is Creation_Function_To_Service_Names.Map (Function_Map_Capacity, Creation_Function_To_Service_Names.Default_Modulus (Function_Map_Capacity)); -------------------------------- -- Creation_Function_Registry -- -------------------------------- -- static -- std::unordered_map<std::string, ServiceBase::serviceCreationFunctionPointer>& -- createFunctionByServiceType() -- We implement createFunctionByServiceType via this simple decl Creation_Function_Registry : Creation_Function_Map; ------------------------------------------------- -- Register_Service_Creation_Function_Pointers -- ------------------------------------------------- procedure Register_Service_Creation_Function_Pointers (Service_Type_Names : Service_Type_Names_List; Associated_Creator : Service_Creation_Function_Pointer) is use Creation_Function_To_Service_Names; C : Cursor; begin for Name of Service_Type_Names loop C := Find (Creation_Function_Registry, Name); if C = No_Element then Insert (Creation_Function_Registry, Name, Associated_Creator); else -- note that the C++ version issues a warning here Replace_Element (Creation_Function_Registry, C, Associated_Creator); end if; end loop; end Register_Service_Creation_Function_Pointers; ----------------------- -- Construct_Service -- ----------------------- procedure Construct_Service (This : in out Service_Base; Service_Type : String; Work_Directory_Name : String) is begin This.Construct_Client; -- ServiceBase::ServiceBase(const std::string& serviceType, const std::string& workDirectoryName) -- : m_serviceType(serviceType), m_workDirectoryName(workDirectoryName) -- { -- m_serviceId = m_networkId; Copy (Service_Type, This.Service_Type); Copy (Work_Directory_Name, This.Work_Directory_Name); This.Service_Id := UInt32'Mod (This.Network_Id); This.Is_Constructed := True; end Construct_Service; ------------------------- -- Instantiate_Service -- ------------------------- function Instantiate_Service (Type_Name : String) return Any_Service is Result : Any_Service; Target : constant Service_Type_Name := Instance (Service_Type_Name_Max_Length, Type_Name); Creator : Service_Creation_Function_Pointer; use Creation_Function_To_Service_Names; C : Cursor; begin -- static -- std::unique_ptr<ServiceBase> -- instantiateService(const std::string& serviceType) -- { -- auto it = createFunctionByServiceType().find(serviceType); -- ServiceBase * newService(it == createFunctionByServiceType().end() ? nullptr : (it->second)()); -- std::unique_ptr<ServiceBase> service(newService); -- return (service); -- }; C := Find (Creation_Function_Registry, Target); if C = No_Element then return null; end if; Creator := Element (Creation_Function_Registry, C); -- get the creator function Result := Creator.all; -- call the function return Result; end Instantiate_Service; ----------------------- -- Configure_Service -- ----------------------- procedure Configure_Service (This : in out Service_Base; Parent_Of_Work_Directory : String; ServiceXml : String; Result : out Boolean) is use DOM.Core; use DOM.Readers; use Input_Sources.Strings; Input : String_Input; Reader : Tree_Reader; Doc : Document; begin Input_Sources.Strings.Open (ServiceXml, Sax.Encodings.Encoding, Input); Reader.Parse (Input); Close (Input); Doc := Get_Tree (Reader); Configure_Service (Service_Base'Class (This), Parent_Of_Work_Directory, Documents.Get_Element (Doc), This.Is_Configured); Result := This.Is_Configured; end Configure_Service; ----------------------- -- Configure_Service -- ----------------------- procedure Configure_Service (This : in out Service_Base; Parent_Of_Work_Directory : String; Service_XML_Node : DOM.Core.Element; Result : out Boolean) is function Slash_Appended (S : String) return String with Pre => S'Length > 0, Post => Slash_Appended'Result (Slash_Appended'Result'Last) = '/'; function Slash_Appended (S : String) return String is (if S (S'Last) = '/' then S else S & "/"); begin if This.Work_Directory_Name /= "" then Copy (Slash_Appended (Parent_Of_Work_Directory) & Slash_Appended (Value (This.Work_Directory_Name)), To => This.Work_Directory_Path); else Clear (This.Work_Directory_Path); end if; Configure_Network_Client (This, Subclass_Type_Name => Value (This.Service_Type), Processing_Kind => This.Processing_Type, Network_Client_XML_Node => Service_XML_Node, Result => Result); if Result then declare Group : constant DOM.Core.DOM_String := DOM.Core.Elements.Get_Attribute (Service_XML_Node, Name => UxAS.Common.String_Constant.MessageGroup); begin if Group /= "" then -- set source group value that will be assigned to source group field of sent messages Copy (Group, To => This.Message_Source_Group); -- subscribe to messages addressed to non-empty source group value This.Add_Subscription_Address (Group, Success => Result); end if; end; end if; This.Is_Configured := Result; end Configure_Service; ---------------------------------- -- Initialize_And_Start_Service -- ---------------------------------- procedure Initialize_And_Start_Service (This : in out Service_Base; Result : out Boolean) is begin Result := False; if This.Is_Configured then if not Empty (This.Work_Directory_Path) then begin Ada.Directories.Create_Path (Value (This.Work_Directory_Path)); exception -- TODO !!!!! when others => return; end; end if; Initialize_And_Start (This, Result); end if; end Initialize_And_Start_Service; --------------------------- -- Get_Unique_Service_Id -- --------------------------- function Get_Unique_Service_Id return Int64 is Result : Int64; begin Get_Unique_Network_Client_Id (Result); return Result; end Get_Unique_Service_Id; -------------------- -- Get_Service_Id -- -------------------- function Get_Service_Id (This : Service_Base) return UInt32 is (This.Service_Id); ---------------------- -- Get_Service_Type -- ---------------------- function Get_Service_Type (This : Service_Base) return String is (Value (This.Service_Type)); ----------------------------- -- Get_Work_Directory_Name -- ----------------------------- function Get_Work_Directory_Name (This : Service_Base) return String is (Value (This.Work_Directory_Name)); ---------------- -- Configured -- ---------------- function Configured (This : Service_Base) return Boolean is (This.Is_Configured); ----------------- -- Constructed -- ----------------- function Constructed (This : Service_Base) return Boolean is (This.Is_Constructed); end UxAS.Comms.LMCP_Net_Client.Service;
-- C74004A.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 OPERATIONS DEPENDING ON THE FULL DECLARATION OF A -- PRIVATE TYPE ARE AVAILABLE WITHIN THE PACKAGE BODY. -- HISTORY: -- BCB 04/05/88 CREATED ORIGINAL TEST. -- PWN 01/31/95 REMOVED INCONSISTENCIES WITH ADA 9X. WITH REPORT; USE REPORT; PROCEDURE C74004A IS PACKAGE P IS TYPE PR IS PRIVATE; TYPE ARR1 IS LIMITED PRIVATE; TYPE ARR2 IS PRIVATE; TYPE REC (D : INTEGER) IS PRIVATE; TYPE ACC IS PRIVATE; TYPE TSK IS LIMITED PRIVATE; TYPE FLT IS LIMITED PRIVATE; TYPE FIX IS LIMITED PRIVATE; TASK TYPE T IS ENTRY ONE(V : IN OUT INTEGER); END T; PROCEDURE CHECK (V : ARR2); PRIVATE TYPE PR IS NEW INTEGER; TYPE ARR1 IS ARRAY(1..5) OF INTEGER; TYPE ARR2 IS ARRAY(1..5) OF BOOLEAN; TYPE REC (D : INTEGER) IS RECORD COMP1 : INTEGER; COMP2 : BOOLEAN; END RECORD; TYPE ACC IS ACCESS INTEGER; TYPE TSK IS NEW T; TYPE FLT IS DIGITS 5; TYPE FIX IS DELTA 2.0**(-1) RANGE -100.0 .. 100.0; END P; PACKAGE BODY P IS X1, X2, X3 : PR; BOOL : BOOLEAN := IDENT_BOOL(FALSE); VAL : INTEGER := IDENT_INT(0); FVAL : FLOAT := 0.0; ST : STRING(1..2); O1 : ARR1 := (1,2,3,4,5); Y1 : ARR2 := (FALSE,TRUE,FALSE,TRUE,FALSE); Y2 : ARR2 := (OTHERS => TRUE); Y3 : ARR2 := (OTHERS => FALSE); Z1 : REC(0) := (0,1,FALSE); W1, W2 : ACC := NEW INTEGER'(0); V1 : TSK; TASK BODY T IS BEGIN ACCEPT ONE(V : IN OUT INTEGER) DO V := IDENT_INT(10); END ONE; END T; PROCEDURE CHECK (V : ARR2) IS BEGIN IF V /= (TRUE,FALSE,TRUE,FALSE,TRUE) THEN FAILED ("IMPROPER VALUE PASSED AS AGGREGATE"); END IF; END CHECK; BEGIN TEST ("C74004A", "CHECK THAT OPERATIONS DEPENDING ON THE " & "FULL DECLARATION OF A PRIVATE TYPE ARE " & "AVAILABLE WITHIN THE PACKAGE BODY"); X1 := 10; X2 := 5; X3 := X1 + X2; IF X3 /= 15 THEN FAILED ("IMPROPER RESULT FROM ADDITION OPERATOR"); END IF; X3 := X1 - X2; IF X3 /= 5 THEN FAILED ("IMPROPER RESULT FROM SUBTRACTION OPERATOR"); END IF; X3 := X1 * X2; IF X3 /= 50 THEN FAILED ("IMPROPER RESULT FROM MULTIPLICATION OPERATOR"); END IF; X3 := X1 / X2; IF X3 /= 2 THEN FAILED ("IMPROPER RESULT FROM DIVISION OPERATOR"); END IF; X3 := X1 ** 2; IF X3 /= 100 THEN FAILED ("IMPROPER RESULT FROM EXPONENTIATION OPERATOR"); END IF; BOOL := X1 < X2; IF BOOL THEN FAILED ("IMPROPER RESULT FROM LESS THAN OPERATOR"); END IF; BOOL := X1 > X2; IF NOT BOOL THEN FAILED ("IMPROPER RESULT FROM GREATER THAN OPERATOR"); END IF; BOOL := X1 <= X2; IF BOOL THEN FAILED ("IMPROPER RESULT FROM LESS THAN OR EQUAL TO " & "OPERATOR"); END IF; BOOL := X1 >= X2; IF NOT BOOL THEN FAILED ("IMPROPER RESULT FROM GREATER THAN OR EQUAL " & "TO OPERATOR"); END IF; X3 := X1 MOD X2; IF X3 /= 0 THEN FAILED ("IMPROPER RESULT FROM MOD OPERATOR"); END IF; X3 := X1 REM X2; IF X3 /= 0 THEN FAILED ("IMPROPER RESULT FROM REM OPERATOR"); END IF; X3 := ABS(X1); IF X3 /= 10 THEN FAILED ("IMPROPER RESULT FROM ABS OPERATOR - 1"); END IF; X1 := -10; X3 := ABS(X1); IF X3 /= 10 THEN FAILED ("IMPROPER RESULT FROM ABS OPERATOR - 2"); END IF; X3 := PR'BASE'FIRST; IF X3 /= PR(INTEGER'FIRST) THEN FAILED ("IMPROPER RESULT FROM 'BASE'FIRST"); END IF; X3 := PR'FIRST; IF X3 /= PR(INTEGER'FIRST) THEN FAILED ("IMPROPER RESULT FROM 'FIRST"); END IF; VAL := PR'WIDTH; IF NOT EQUAL(VAL,INTEGER'WIDTH) THEN FAILED ("IMPROPER RESULT FROM 'WIDTH"); END IF; VAL := PR'POS(X3); IF NOT EQUAL(VAL,INTEGER'FIRST) THEN FAILED ("IMPROPER RESULT FROM 'POS"); END IF; X3 := PR'VAL(VAL); IF X3 /= PR(INTEGER'FIRST) THEN FAILED ("IMPROPER RESULT FROM 'VAL"); END IF; X3 := PR'SUCC(X2); IF X3 /= 6 THEN FAILED ("IMPROPER RESULT FROM 'SUCC"); END IF; X3 := PR'PRED(X2); IF X3 /= 4 THEN FAILED ("IMPROPER RESULT FROM 'PRED"); END IF; ST := PR'IMAGE(X3); IF ST /= INTEGER'IMAGE(INTEGER(X3)) THEN FAILED ("IMPROPER RESULT FROM 'IMAGE"); END IF; X3 := PR'VALUE(ST); IF X3 /= PR(INTEGER'VALUE(ST)) THEN FAILED ("IMPROPER RESULT FROM 'VALUE"); END IF; CHECK ((TRUE,FALSE,TRUE,FALSE,TRUE)); IF O1(2) /= IDENT_INT(2) THEN FAILED ("IMPROPER VALUE FROM INDEXING"); END IF; IF O1(2..4) /= (2,3,4) THEN FAILED ("IMPROPER VALUES FROM SLICING"); END IF; IF VAL IN O1'RANGE THEN FAILED ("IMPROPER RESULT FROM 'RANGE"); END IF; VAL := O1'LENGTH; IF NOT EQUAL(VAL,5) THEN FAILED ("IMPROPER RESULT FROM 'LENGTH"); END IF; Y3 := Y1(1..2) & Y2(3..5); IF Y3 /= (FALSE,TRUE,TRUE,TRUE,TRUE) THEN FAILED ("IMPROPER RESULT FROM CATENATION"); END IF; Y3 := NOT Y1; IF Y3 /= (TRUE,FALSE,TRUE,FALSE,TRUE) THEN FAILED ("IMPROPER RESULT FROM NOT OPERATOR"); END IF; Y3 := Y1 AND Y2; IF Y3 /= (FALSE,TRUE,FALSE,TRUE,FALSE) THEN FAILED ("IMPROPER RESULT FROM AND OPERATOR"); END IF; Y3 := Y1 OR Y2; IF Y3 /= (TRUE,TRUE,TRUE,TRUE,TRUE) THEN FAILED ("IMPROPER RESULT FROM OR OPERATOR"); END IF; Y3 := Y1 XOR Y2; IF Y3 /= (TRUE,FALSE,TRUE,FALSE,TRUE) THEN FAILED ("IMPROPER RESULT FROM XOR OPERATOR"); END IF; VAL := Z1.COMP1; IF NOT EQUAL(VAL,1) THEN FAILED ("IMPROPER RESULT FROM SELECTION OF RECORD " & "COMPONENTS"); END IF; W1 := NEW INTEGER'(0); IF NOT EQUAL(W1.ALL,0) THEN FAILED ("IMPROPER RESULT FROM ALLOCATION"); END IF; W1 := NULL; IF W1 /= NULL THEN FAILED ("IMPROPER RESULT FROM NULL LITERAL"); END IF; VAL := W2.ALL; IF NOT EQUAL(VAL,0) THEN FAILED ("IMPROPER RESULT FROM SELECTED COMPONENT"); END IF; BOOL := V1'CALLABLE; IF NOT BOOL THEN FAILED ("IMPROPER RESULT FROM 'CALLABLE"); END IF; BOOL := V1'TERMINATED; IF BOOL THEN FAILED ("IMPROPER RESULT FROM 'TERMINATED"); END IF; V1.ONE(VAL); IF NOT EQUAL(VAL,10) THEN FAILED ("IMPROPER RESULT RETURNED FROM ENTRY SELECTION"); END IF; IF NOT (FLT(1.0) IN FLT) THEN FAILED ("IMPROPER RESULT FROM IMPLICIT CONVERSION"); END IF; VAL := FLT'DIGITS; IF NOT EQUAL(VAL,5) THEN FAILED ("IMPROPER RESULT FROM 'DIGITS"); END IF; BOOL := FLT'MACHINE_ROUNDS; BOOL := FLT'MACHINE_OVERFLOWS; VAL := FLT'MACHINE_RADIX; VAL := FLT'MACHINE_MANTISSA; VAL := FLT'MACHINE_EMAX; VAL := FLT'MACHINE_EMIN; FVAL := FIX'DELTA; IF FVAL /= 2.0**(-1) THEN FAILED ("IMPROPER RESULT FROM 'DELTA"); END IF; VAL := FIX'FORE; VAL := FIX'AFT; END P; USE P; BEGIN RESULT; END C74004A;
with Ada.Text_Io; use Ada.Text_Io; procedure Ver_Dar_La_Vuelta is -- salida: 6 strings(SE) -- post: corresponden a cada uno de los casos de pruebas dise�ados. -- pre: { True } function Dar_La_Vuelta ( S : String) return String is -- EJERCICIO 2- ESPECIFICA E IMPLEMENTA recursivamente el subprograma -- Dar_La_Vuelta que devuelve el string inverso de S. BEGIN -- Completar if S'Size <= 1 then return S; end if; return Dar_La_Vuelta(S(S'First + 1 .. S'Last)) & S(S'First); end Dar_La_Vuelta ; -- post: { } begin Put_Line("-------------------------------------"); Put("La palabra vacia dada la vuelta es la vacia: "); Put(Dar_La_Vuelta("")); New_Line; New_Line; New_Line; Put_Line("-------------------------------------"); Put("La palabra de 1 caracter 'a' dada la vuelta es la 'a': "); Put(Dar_La_Vuelta("a")); New_Line; New_Line; New_Line; Put_Line("-------------------------------------"); Put_Line("Palabras de varios caracteres"); Put("-- casaca dada la vuelta es acasac: "); Put(Dar_La_Vuelta("casaca")); New_Line; Put("-- baobab dada la vuelta es baboab: "); Put(Dar_La_Vuelta("baobab")); New_Line; Put("-- alejela dada la vuelta es alejela: "); Put (Dar_La_Vuelta("alejela")); New_Line; Put("-- reconocer dada la vuelta es reconocer: "); Put(Dar_La_Vuelta("reconocer")); New_Line; Put_Line("-------------------------------------"); end Ver_Dar_La_Vuelta;
--////////////////////////////////////////////////////////// -- SFML - Simple and Fast Multimedia Library -- Copyright (C) 2007-2015 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. --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// package Sf.Graphics.Color is --////////////////////////////////////////////////////////// --/ sfColor is an utility class for manipulating colors --////////////////////////////////////////////////////////// --////////////////////////////////////////////////////////// --/ @brief Utility class for manpulating RGBA colors --/ --////////////////////////////////////////////////////////// type sfColor is record r : aliased sfUint8; g : aliased sfUint8; b : aliased sfUint8; a : aliased sfUint8; end record; pragma Convention (C_Pass_By_Copy, sfColor); --////////////////////////////////////////////////////////// --/ Define some common colors --////////////////////////////////////////////////////////// sfBlack : constant sfColor := (0, 0, 0, 255); sfWhite : constant sfColor := (255, 255, 255, 255); sfRed : constant sfColor := (255, 0, 0, 255); sfGreen : constant sfColor := (0, 255, 0, 255); sfBlue : constant sfColor := (0, 0, 255, 255); sfYellow : constant sfColor := (255, 255, 0, 255); sfMagenta : constant sfColor := (255, 0, 255, 255); sfCyan : constant sfColor := (0, 255, 255, 255); sfTransparent : constant sfColor := (0, 0, 0, 0); --////////////////////////////////////////////////////////// --/ @brief Construct a color from its 3 RGB components --/ --/ @param red Red component (0 .. 255) --/ @param green Green component (0 .. 255) --/ @param blue Blue component (0 .. 255) --/ --/ @return sfColor constructed from the components --/ --////////////////////////////////////////////////////////// function fromRGB (red : sfUint8; green : sfUint8; blue : sfUint8) return sfColor; --////////////////////////////////////////////////////////// --/ @brief Construct a color from its 4 RGBA components --/ --/ @param red Red component (0 .. 255) --/ @param green Green component (0 .. 255) --/ @param blue Blue component (0 .. 255) --/ @param alpha Alpha component (0 .. 255) --/ --/ @return sfColor constructed from the components --/ --////////////////////////////////////////////////////////// function fromRGBA (red : sfUint8; green : sfUint8; blue : sfUint8; alpha : sfUint8) return sfColor; --////////////////////////////////////////////////////////// --/ @brief Construct the color from 32-bit unsigned integer --/ --/ @param color Number containing the RGBA components (in that order) --/ --/ @return sfColor constructed from the 32-bit unsigned integer --/ --////////////////////////////////////////////////////////// function fromInteger (color : sfUint32) return sfColor; --////////////////////////////////////////////////////////// --/ @brief Convert a color to a 32-bit unsigned integer --/ --/ @return Color represented as a 32-bit unsigned integer --/ --////////////////////////////////////////////////////////// function toInteger (Color : sfColor) return sfUint32; --////////////////////////////////////////////////////////// --/ @brief Add two colors --/ --/ @param color1 First color --/ @param color2 Second color --/ --/ @return Component-wise saturated addition of the two colors --/ --////////////////////////////////////////////////////////// function add (color1 : sfColor; color2 : sfColor) return sfColor; --////////////////////////////////////////////////////////// --/ @brief Subtract two colors --/ --/ @param color1 First color --/ @param color2 Second color --/ --/ @return Component-wise saturated subtraction of the two colors --/ --////////////////////////////////////////////////////////// function subtract (color1 : sfColor; color2 : sfColor) return sfColor; --////////////////////////////////////////////////////////// --/ @brief Modulate two colors --/ --/ @param color1 First color --/ @param color2 Second color --/ --/ @return Component-wise multiplication of the two colors --/ --////////////////////////////////////////////////////////// function modulate (color1 : sfColor; color2 : sfColor) return sfColor; private pragma Import (C, fromRGB, "sfColor_fromRGB"); pragma Import (C, fromRGBA, "sfColor_fromRGBA"); pragma Import (C, fromInteger, "sfColor_fromInteger"); pragma Import (C, toInteger, "sfColor_toInteger"); pragma Import (C, add, "sfColor_add"); pragma Import (C, subtract, "sfColor_subtract"); pragma Import (C, modulate, "sfColor_modulate"); end Sf.Graphics.Color;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- A D A . C O N T A I N E R S . M U L T I W A Y _ T R E E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2004-2021, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 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/>. -- -- -- -- This unit was originally developed by Matthew J Heaney. -- ------------------------------------------------------------------------------ with Ada.Iterator_Interfaces; with Ada.Containers.Helpers; private with Ada.Finalization; private with Ada.Streams; private with Ada.Strings.Text_Buffers; generic type Element_Type is private; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Ada.Containers.Multiway_Trees with SPARK_Mode => Off is pragma Annotate (CodePeer, Skip_Analysis); pragma Preelaborate; pragma Remote_Types; type Tree is tagged private with Constant_Indexing => Constant_Reference, Variable_Indexing => Reference, Default_Iterator => Iterate, Iterator_Element => Element_Type; pragma Preelaborable_Initialization (Tree); type Cursor is private; pragma Preelaborable_Initialization (Cursor); Empty_Tree : constant Tree; No_Element : constant Cursor; function Has_Element (Position : Cursor) return Boolean; package Tree_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element); function Equal_Subtree (Left_Position : Cursor; Right_Position : Cursor) return Boolean; function "=" (Left, Right : Tree) return Boolean; function Is_Empty (Container : Tree) return Boolean; function Node_Count (Container : Tree) return Count_Type; function Subtree_Node_Count (Position : Cursor) return Count_Type; function Depth (Position : Cursor) return Count_Type; function Is_Root (Position : Cursor) return Boolean; function Is_Leaf (Position : Cursor) return Boolean; function Root (Container : Tree) return Cursor; procedure Clear (Container : in out Tree); function Element (Position : Cursor) return Element_Type; procedure Replace_Element (Container : in out Tree; Position : Cursor; New_Item : Element_Type); procedure Query_Element (Position : Cursor; Process : not null access procedure (Element : Element_Type)); procedure Update_Element (Container : in out Tree; Position : Cursor; Process : not null access procedure (Element : in out Element_Type)); type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; type Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Constant_Reference (Container : aliased Tree; Position : Cursor) return Constant_Reference_Type; pragma Inline (Constant_Reference); function Reference (Container : aliased in out Tree; Position : Cursor) return Reference_Type; pragma Inline (Reference); procedure Assign (Target : in out Tree; Source : Tree); function Copy (Source : Tree) return Tree; procedure Move (Target : in out Tree; Source : in out Tree); procedure Delete_Leaf (Container : in out Tree; Position : in out Cursor); procedure Delete_Subtree (Container : in out Tree; Position : in out Cursor); procedure Swap (Container : in out Tree; I, J : Cursor); function Find (Container : Tree; Item : Element_Type) return Cursor; -- This version of the AI: -- 10-06-02 AI05-0136-1/07 -- declares Find_In_Subtree this way: -- -- function Find_In_Subtree -- (Container : Tree; -- Item : Element_Type; -- Position : Cursor) return Cursor; -- -- It seems that the Container parameter is there by mistake, but we need -- an official ruling from the ARG. ??? function Find_In_Subtree (Position : Cursor; Item : Element_Type) return Cursor; -- This version of the AI: -- 10-06-02 AI05-0136-1/07 -- declares Ancestor_Find this way: -- -- function Ancestor_Find -- (Container : Tree; -- Item : Element_Type; -- Position : Cursor) return Cursor; -- -- It seems that the Container parameter is there by mistake, but we need -- an official ruling from the ARG. ??? function Ancestor_Find (Position : Cursor; Item : Element_Type) return Cursor; function Contains (Container : Tree; Item : Element_Type) return Boolean; procedure Iterate (Container : Tree; Process : not null access procedure (Position : Cursor)); procedure Iterate_Subtree (Position : Cursor; Process : not null access procedure (Position : Cursor)); function Iterate (Container : Tree) return Tree_Iterator_Interfaces.Forward_Iterator'Class; function Iterate_Subtree (Position : Cursor) return Tree_Iterator_Interfaces.Forward_Iterator'Class; function Iterate_Children (Container : Tree; Parent : Cursor) return Tree_Iterator_Interfaces.Reversible_Iterator'Class; function Child_Count (Parent : Cursor) return Count_Type; function Child_Depth (Parent, Child : Cursor) return Count_Type; procedure Insert_Child (Container : in out Tree; Parent : Cursor; Before : Cursor; New_Item : Element_Type; Count : Count_Type := 1); procedure Insert_Child (Container : in out Tree; Parent : Cursor; Before : Cursor; New_Item : Element_Type; Position : out Cursor; Count : Count_Type := 1); procedure Insert_Child (Container : in out Tree; Parent : Cursor; Before : Cursor; Position : out Cursor; Count : Count_Type := 1); procedure Prepend_Child (Container : in out Tree; Parent : Cursor; New_Item : Element_Type; Count : Count_Type := 1); procedure Append_Child (Container : in out Tree; Parent : Cursor; New_Item : Element_Type; Count : Count_Type := 1); procedure Delete_Children (Container : in out Tree; Parent : Cursor); procedure Copy_Subtree (Target : in out Tree; Parent : Cursor; Before : Cursor; Source : Cursor); procedure Splice_Subtree (Target : in out Tree; Parent : Cursor; Before : Cursor; Source : in out Tree; Position : in out Cursor); procedure Splice_Subtree (Container : in out Tree; Parent : Cursor; Before : Cursor; Position : Cursor); procedure Splice_Children (Target : in out Tree; Target_Parent : Cursor; Before : Cursor; Source : in out Tree; Source_Parent : Cursor); procedure Splice_Children (Container : in out Tree; Target_Parent : Cursor; Before : Cursor; Source_Parent : Cursor); function Parent (Position : Cursor) return Cursor; function First_Child (Parent : Cursor) return Cursor; function First_Child_Element (Parent : Cursor) return Element_Type; function Last_Child (Parent : Cursor) return Cursor; function Last_Child_Element (Parent : Cursor) return Element_Type; function Next_Sibling (Position : Cursor) return Cursor; function Previous_Sibling (Position : Cursor) return Cursor; procedure Next_Sibling (Position : in out Cursor); procedure Previous_Sibling (Position : in out Cursor); -- This version of the AI: -- 10-06-02 AI05-0136-1/07 -- declares Iterate_Children this way: -- -- procedure Iterate_Children -- (Container : Tree; -- Parent : Cursor; -- Process : not null access procedure (Position : Cursor)); -- -- It seems that the Container parameter is there by mistake, but we need -- an official ruling from the ARG. ??? procedure Iterate_Children (Parent : Cursor; Process : not null access procedure (Position : Cursor)); procedure Reverse_Iterate_Children (Parent : Cursor; Process : not null access procedure (Position : Cursor)); private -- A node of this multiway tree comprises an element and a list of children -- (that are themselves trees). The root node is distinguished because it -- contains only children: it does not have an element itself. -- This design feature puts two design goals in tension with one another: -- (1) treat the root node the same as any other node -- (2) not declare any objects of type Element_Type unnecessarily -- To satisfy (1), we could simply declare the Root node of the tree -- using the normal Tree_Node_Type, but that would mean that (2) is not -- satisfied. To resolve the tension (in favor of (2)), we declare the -- component Root as having a different node type, without an Element -- component (thus satisfying goal (2)) but otherwise identical to a normal -- node, and then use Unchecked_Conversion to convert an access object -- designating the Root node component to the access type designating a -- normal, non-root node (thus satisfying goal (1)). We make an explicit -- check for Root when there is any attempt to manipulate the Element -- component of the node (a check required by the RM anyway). -- In order to be explicit about node (and pointer) representation, we -- specify that the respective node types have convention C, to ensure -- that the layout of the components of the node records is the same, -- thus guaranteeing that (unchecked) conversions between access types -- designating each kind of node type is a meaningful conversion. use Ada.Containers.Helpers; package Implementation is new Generic_Implementation; use Implementation; type Tree_Node_Type; type Tree_Node_Access is access all Tree_Node_Type; pragma Convention (C, Tree_Node_Access); pragma No_Strict_Aliasing (Tree_Node_Access); -- The above-mentioned Unchecked_Conversion is a violation of the normal -- aliasing rules. type Children_Type is record First : Tree_Node_Access; Last : Tree_Node_Access; end record; -- See the comment above. This declaration must exactly match the -- declaration of Root_Node_Type (except for the Element component). type Tree_Node_Type is record Parent : Tree_Node_Access; Prev : Tree_Node_Access; Next : Tree_Node_Access; Children : Children_Type; Element : aliased Element_Type; end record; pragma Convention (C, Tree_Node_Type); -- See the comment above. This declaration must match the declaration of -- Tree_Node_Type (except for the Element component). type Root_Node_Type is record Parent : Tree_Node_Access; Prev : Tree_Node_Access; Next : Tree_Node_Access; Children : Children_Type; end record; pragma Convention (C, Root_Node_Type); for Root_Node_Type'Alignment use Standard'Maximum_Alignment; -- The alignment has to be large enough to allow Root_Node to Tree_Node -- access value conversions, and Tree_Node_Type's alignment may be bumped -- up by the Element component. use Ada.Finalization; -- The Count component of type Tree represents the number of nodes that -- have been (dynamically) allocated. It does not include the root node -- itself. As implementors, we decide to cache this value, so that the -- selector function Node_Count can execute in O(1) time, in order to be -- consistent with the behavior of the Length selector function for other -- standard container library units. This does mean, however, that the -- two-container forms for Splice_XXX (that move subtrees across tree -- containers) will execute in O(n) time, because we must count the number -- of nodes in the subtree(s) that get moved. (We resolve the tension -- between Node_Count and Splice_XXX in favor of Node_Count, under the -- assumption that Node_Count is the more common operation). type Tree is new Controlled with record Root : aliased Root_Node_Type; TC : aliased Tamper_Counts; Count : Count_Type := 0; end record with Put_Image => Put_Image; procedure Put_Image (S : in out Ada.Strings.Text_Buffers.Root_Buffer_Type'Class; V : Tree); overriding procedure Adjust (Container : in out Tree); overriding procedure Finalize (Container : in out Tree) renames Clear; use Ada.Streams; procedure Write (Stream : not null access Root_Stream_Type'Class; Container : Tree); for Tree'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Container : out Tree); for Tree'Read use Read; type Tree_Access is access all Tree; for Tree_Access'Storage_Size use 0; type Cursor is record Container : Tree_Access; Node : Tree_Node_Access; end record; procedure Write (Stream : not null access Root_Stream_Type'Class; Position : Cursor); for Cursor'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Position : out Cursor); for Cursor'Read use Read; subtype Reference_Control_Type is Implementation.Reference_Control_Type; -- It is necessary to rename this here, so that the compiler can find it type Constant_Reference_Type (Element : not null access constant Element_Type) is record Control : Reference_Control_Type := raise Program_Error with "uninitialized reference"; -- The RM says, "The default initialization of an object of -- type Constant_Reference_Type or Reference_Type propagates -- Program_Error." end record; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Constant_Reference_Type); for Constant_Reference_Type'Read use Read; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Constant_Reference_Type); for Constant_Reference_Type'Write use Write; type Reference_Type (Element : not null access Element_Type) is record Control : Reference_Control_Type := raise Program_Error with "uninitialized reference"; -- The RM says, "The default initialization of an object of -- type Constant_Reference_Type or Reference_Type propagates -- Program_Error." end record; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Reference_Type); for Reference_Type'Read use Read; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Reference_Type); for Reference_Type'Write use Write; -- Three operations are used to optimize in the expansion of "for ... of" -- loops: the Next(Cursor) procedure in the visible part, and the following -- Pseudo_Reference and Get_Element_Access functions. See Exp_Ch5 for -- details. function Pseudo_Reference (Container : aliased Tree'Class) return Reference_Control_Type; pragma Inline (Pseudo_Reference); -- Creates an object of type Reference_Control_Type pointing to the -- container, and increments the Lock. Finalization of this object will -- decrement the Lock. type Element_Access is access all Element_Type with Storage_Size => 0; function Get_Element_Access (Position : Cursor) return not null Element_Access; -- Returns a pointer to the element designated by Position. Empty_Tree : constant Tree := (Controlled with others => <>); No_Element : constant Cursor := (others => <>); end Ada.Containers.Multiway_Trees;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K _ P R I M I T I V E S . O P E R A T I O N S -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001, Florida State University -- -- -- -- GNARL 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. GNARL 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 GNARL; 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. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. It is -- -- now maintained by Ada Core Technologies Inc. in cooperation with Florida -- -- State University (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- This is a OpenVMS/Alpha version of this package -- This package contains all the GNULL primitives that interface directly -- with the underlying OS. pragma Polling (Off); -- Turn off polling, we do not want ATC polling to take place during -- tasking operations. It causes infinite loops and other problems. with System.Tasking.Debug; -- used for Known_Tasks with Interfaces.C; -- used for int -- size_t with System.Parameters; -- used for Size_Type with System.Tasking; -- used for Ada_Task_Control_Block -- Task_ID with System.Soft_Links; -- used for Defer/Undefer_Abort -- Set_Exc_Stack_Addr -- Note that we do not use System.Tasking.Initialization directly since -- this is a higher level package that we shouldn't depend on. For example -- when using the restricted run time, it is replaced by -- System.Tasking.Restricted.Initialization with System.OS_Primitives; -- used for Delay_Modes with Unchecked_Conversion; with Unchecked_Deallocation; package body System.Task_Primitives.Operations is use System.Tasking.Debug; use System.Tasking; use Interfaces.C; use System.OS_Interface; use System.Parameters; use System.OS_Primitives; use type System.OS_Primitives.OS_Time; package SSL renames System.Soft_Links; ------------------ -- Local Data -- ------------------ -- The followings are logically constants, but need to be initialized -- at run time. ATCB_Key : aliased pthread_key_t; -- Key used to find the Ada Task_ID associated with a thread All_Tasks_L : aliased System.Task_Primitives.RTS_Lock; -- See comments on locking rules in System.Tasking (spec). Environment_Task_ID : Task_ID; -- A variable to hold Task_ID for the environment task. Time_Slice_Val : Integer; pragma Import (C, Time_Slice_Val, "__gl_time_slice_val"); Dispatching_Policy : Character; pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy"); FIFO_Within_Priorities : constant Boolean := Dispatching_Policy = 'F'; -- Indicates whether FIFO_Within_Priorities is set. ----------------------- -- Local Subprograms -- ----------------------- function To_Task_ID is new Unchecked_Conversion (System.Address, Task_ID); function To_Address is new Unchecked_Conversion (Task_ID, System.Address); procedure Timer_Sleep_AST (ID : Address); -- Signal the condition variable when AST fires. procedure Timer_Sleep_AST (ID : Address) is Result : Interfaces.C.int; Self_ID : Task_ID := To_Task_ID (ID); begin Self_ID.Common.LL.AST_Pending := False; Result := pthread_cond_signal_int_np (Self_ID.Common.LL.CV'Access); end Timer_Sleep_AST; ------------------- -- Stack_Guard -- ------------------- -- The underlying thread system sets a guard page at the -- bottom of a thread stack, so nothing is needed. -- ??? Check the comment above procedure Stack_Guard (T : ST.Task_ID; On : Boolean) is begin null; end Stack_Guard; -------------------- -- Get_Thread_Id -- -------------------- function Get_Thread_Id (T : ST.Task_ID) return OSI.Thread_Id is begin return T.Common.LL.Thread; end Get_Thread_Id; ---------- -- Self -- ---------- function Self return Task_ID is Result : System.Address; begin Result := pthread_getspecific (ATCB_Key); pragma Assert (Result /= System.Null_Address); return To_Task_ID (Result); end Self; --------------------- -- Initialize_Lock -- --------------------- -- Note: mutexes and cond_variables needed per-task basis are -- initialized in Initialize_TCB and the Storage_Error is -- handled. Other mutexes (such as All_Tasks_Lock, Memory_Lock...) -- used in RTS is initialized before any status change of RTS. -- Therefore rasing Storage_Error in the following routines -- should be able to be handled safely. procedure Initialize_Lock (Prio : System.Any_Priority; L : access Lock) is Attributes : aliased pthread_mutexattr_t; Result : Interfaces.C.int; begin Result := pthread_mutexattr_init (Attributes'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result = ENOMEM then raise Storage_Error; end if; L.Prio_Save := 0; L.Prio := Interfaces.C.int (Prio); Result := pthread_mutex_init (L.L'Access, Attributes'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result = ENOMEM then raise Storage_Error; end if; Result := pthread_mutexattr_destroy (Attributes'Access); pragma Assert (Result = 0); end Initialize_Lock; procedure Initialize_Lock (L : access RTS_Lock; Level : Lock_Level) is Attributes : aliased pthread_mutexattr_t; Result : Interfaces.C.int; begin Result := pthread_mutexattr_init (Attributes'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result = ENOMEM then raise Storage_Error; end if; -- Don't use, see comment in s-osinte.ads about ERRORCHECK mutexes. -- Result := pthread_mutexattr_settype_np -- (Attributes'Access, PTHREAD_MUTEX_ERRORCHECK_NP); -- pragma Assert (Result = 0); -- Result := pthread_mutexattr_setprotocol -- (Attributes'Access, PTHREAD_PRIO_PROTECT); -- pragma Assert (Result = 0); -- Result := pthread_mutexattr_setprioceiling -- (Attributes'Access, Interfaces.C.int (System.Any_Priority'Last)); -- pragma Assert (Result = 0); Result := pthread_mutex_init (L, Attributes'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result = ENOMEM then raise Storage_Error; end if; Result := pthread_mutexattr_destroy (Attributes'Access); pragma Assert (Result = 0); end Initialize_Lock; ------------------- -- Finalize_Lock -- ------------------- procedure Finalize_Lock (L : access Lock) is Result : Interfaces.C.int; begin Result := pthread_mutex_destroy (L.L'Access); pragma Assert (Result = 0); end Finalize_Lock; procedure Finalize_Lock (L : access RTS_Lock) is Result : Interfaces.C.int; begin Result := pthread_mutex_destroy (L); pragma Assert (Result = 0); end Finalize_Lock; ---------------- -- Write_Lock -- ---------------- procedure Write_Lock (L : access Lock; Ceiling_Violation : out Boolean) is Self_ID : constant Task_ID := Self; All_Tasks_Link : constant Task_ID := Self.Common.All_Tasks_Link; Current_Prio : System.Any_Priority; Result : Interfaces.C.int; begin Current_Prio := Get_Priority (Self_ID); -- If there is no other tasks, no need to check priorities. if All_Tasks_Link /= Null_Task and then L.Prio < Interfaces.C.int (Current_Prio) then Ceiling_Violation := True; return; end if; Result := pthread_mutex_lock (L.L'Access); pragma Assert (Result = 0); Ceiling_Violation := False; -- Why is this commented out ??? -- L.Prio_Save := Interfaces.C.int (Current_Prio); -- Set_Priority (Self_ID, System.Any_Priority (L.Prio)); end Write_Lock; procedure Write_Lock (L : access RTS_Lock) is Result : Interfaces.C.int; begin Result := pthread_mutex_lock (L); pragma Assert (Result = 0); end Write_Lock; procedure Write_Lock (T : Task_ID) is Result : Interfaces.C.int; begin Result := pthread_mutex_lock (T.Common.LL.L'Access); pragma Assert (Result = 0); end Write_Lock; --------------- -- Read_Lock -- --------------- procedure Read_Lock (L : access Lock; Ceiling_Violation : out Boolean) is begin Write_Lock (L, Ceiling_Violation); end Read_Lock; ------------ -- Unlock -- ------------ procedure Unlock (L : access Lock) is Result : Interfaces.C.int; begin Result := pthread_mutex_unlock (L.L'Access); pragma Assert (Result = 0); end Unlock; procedure Unlock (L : access RTS_Lock) is Result : Interfaces.C.int; begin Result := pthread_mutex_unlock (L); pragma Assert (Result = 0); end Unlock; procedure Unlock (T : Task_ID) is Result : Interfaces.C.int; begin Result := pthread_mutex_unlock (T.Common.LL.L'Access); pragma Assert (Result = 0); end Unlock; ------------- -- Sleep -- ------------- procedure Sleep (Self_ID : Task_ID; Reason : System.Tasking.Task_States) is Result : Interfaces.C.int; begin pragma Assert (Self_ID = Self); Result := pthread_cond_wait (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access); -- EINTR is not considered a failure. pragma Assert (Result = 0 or else Result = EINTR); if Self_ID.Deferral_Level = 0 and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level then Unlock (Self_ID); raise Standard'Abort_Signal; end if; end Sleep; ----------------- -- Timed_Sleep -- ----------------- -- This is for use within the run-time system, so abort is -- assumed to be already deferred, and the caller should be -- holding its own ATCB lock. procedure Timed_Sleep (Self_ID : Task_ID; Time : Duration; Mode : ST.Delay_Modes; Reason : System.Tasking.Task_States; Timedout : out Boolean; Yielded : out Boolean) is Sleep_Time : OS_Time; Result : Interfaces.C.int; Status : Cond_Value_Type; begin Timedout := False; Yielded := False; Sleep_Time := To_OS_Time (Time, Mode); if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level or else Self_ID.Pending_Priority_Change then return; end if; Self_ID.Common.LL.AST_Pending := True; Sys_Setimr (Status, 0, Sleep_Time, Timer_Sleep_AST'Access, To_Address (Self_ID), 0); if (Status and 1) /= 1 then raise Storage_Error; end if; Result := pthread_cond_wait (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access); if not Self_ID.Common.LL.AST_Pending then Timedout := True; else Sys_Cantim (Status, To_Address (Self_ID), 0); pragma Assert ((Status and 1) = 1); end if; end Timed_Sleep; ----------------- -- Timed_Delay -- ----------------- -- This is for use in implementing delay statements, so -- we assume the caller is abort-deferred but is holding -- no locks. procedure Timed_Delay (Self_ID : Task_ID; Time : Duration; Mode : ST.Delay_Modes) is Sleep_Time : OS_Time; Result : Interfaces.C.int; Status : Cond_Value_Type; begin -- Only the little window between deferring abort and -- locking Self_ID is the reason we need to -- check for pending abort and priority change below! :( SSL.Abort_Defer.all; Write_Lock (Self_ID); if not (Time = 0.0 and then Mode = Relative) then Sleep_Time := To_OS_Time (Time, Mode); if Mode = Relative or else OS_Clock < Sleep_Time then Self_ID.Common.State := Delay_Sleep; Self_ID.Common.LL.AST_Pending := True; Sys_Setimr (Status, 0, Sleep_Time, Timer_Sleep_AST'Access, To_Address (Self_ID), 0); if (Status and 1) /= 1 then raise Storage_Error; end if; loop if Self_ID.Pending_Priority_Change then Self_ID.Pending_Priority_Change := False; Self_ID.Common.Base_Priority := Self_ID.New_Base_Priority; Set_Priority (Self_ID, Self_ID.Common.Base_Priority); end if; if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level then Sys_Cantim (Status, To_Address (Self_ID), 0); pragma Assert ((Status and 1) = 1); exit; end if; Result := pthread_cond_wait (Self_ID.Common.LL.CV'Access, Self_ID.Common.LL.L'Access); exit when not Self_ID.Common.LL.AST_Pending; end loop; Self_ID.Common.State := Runnable; end if; end if; Unlock (Self_ID); Result := sched_yield; SSL.Abort_Undefer.all; end Timed_Delay; --------------------- -- Monotonic_Clock -- --------------------- function Monotonic_Clock return Duration renames System.OS_Primitives.Monotonic_Clock; ------------------- -- RT_Resolution -- ------------------- function RT_Resolution return Duration is begin return 10#1.0#E-3; end RT_Resolution; ------------ -- Wakeup -- ------------ procedure Wakeup (T : Task_ID; Reason : System.Tasking.Task_States) is Result : Interfaces.C.int; begin Result := pthread_cond_signal (T.Common.LL.CV'Access); pragma Assert (Result = 0); end Wakeup; ----------- -- Yield -- ----------- procedure Yield (Do_Yield : Boolean := True) is Result : Interfaces.C.int; begin if Do_Yield then Result := sched_yield; end if; end Yield; ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (T : Task_ID; Prio : System.Any_Priority; Loss_Of_Inheritance : Boolean := False) is Result : Interfaces.C.int; Param : aliased struct_sched_param; begin T.Common.Current_Priority := Prio; Param.sched_priority := Interfaces.C.int (Underlying_Priorities (Prio)); if Time_Slice_Val > 0 then Result := pthread_setschedparam (T.Common.LL.Thread, SCHED_RR, Param'Access); elsif FIFO_Within_Priorities or else Time_Slice_Val = 0 then Result := pthread_setschedparam (T.Common.LL.Thread, SCHED_FIFO, Param'Access); else Result := pthread_setschedparam (T.Common.LL.Thread, SCHED_OTHER, Param'Access); end if; pragma Assert (Result = 0); end Set_Priority; ------------------ -- Get_Priority -- ------------------ function Get_Priority (T : Task_ID) return System.Any_Priority is begin return T.Common.Current_Priority; end Get_Priority; ---------------- -- Enter_Task -- ---------------- procedure Enter_Task (Self_ID : Task_ID) is Result : Interfaces.C.int; begin Self_ID.Common.LL.Thread := pthread_self; -- It is not safe for the new task accept signals until it -- has bound its TCB pointer to the thread with pthread_setspecific (), -- since the handler wrappers use the TCB pointer -- to restore the stack limit. Result := pthread_setspecific (ATCB_Key, To_Address (Self_ID)); pragma Assert (Result = 0); Lock_All_Tasks_List; for I in Known_Tasks'Range loop if Known_Tasks (I) = null then Known_Tasks (I) := Self_ID; Self_ID.Known_Tasks_Index := I; exit; end if; end loop; Unlock_All_Tasks_List; end Enter_Task; -------------- -- New_ATCB -- -------------- function New_ATCB (Entry_Num : Task_Entry_Index) return Task_ID is begin return new Ada_Task_Control_Block (Entry_Num); end New_ATCB; ---------------------- -- Initialize_TCB -- ---------------------- procedure Initialize_TCB (Self_ID : Task_ID; Succeeded : out Boolean) is Mutex_Attr : aliased pthread_mutexattr_t; Result : Interfaces.C.int; Cond_Attr : aliased pthread_condattr_t; begin Result := pthread_mutexattr_init (Mutex_Attr'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result /= 0 then Succeeded := False; return; end if; -- Don't use, see comment in s-osinte.ads about ERRORCHECK mutexes. -- Result := pthread_mutexattr_settype_np -- (Mutex_Attr'Access, PTHREAD_MUTEX_ERRORCHECK_NP); -- pragma Assert (Result = 0); -- Result := pthread_mutexattr_setprotocol -- (Mutex_Attr'Access, PTHREAD_PRIO_PROTECT); -- pragma Assert (Result = 0); -- Result := pthread_mutexattr_setprioceiling -- (Mutex_Attr'Access, Interfaces.C.int (System.Any_Priority'Last)); -- pragma Assert (Result = 0); Result := pthread_mutex_init (Self_ID.Common.LL.L'Access, Mutex_Attr'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result /= 0 then Succeeded := False; return; end if; Result := pthread_mutexattr_destroy (Mutex_Attr'Access); pragma Assert (Result = 0); Result := pthread_condattr_init (Cond_Attr'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result /= 0 then Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access); pragma Assert (Result = 0); Succeeded := False; return; end if; Result := pthread_cond_init (Self_ID.Common.LL.CV'Access, Cond_Attr'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result = 0 then Succeeded := True; Self_ID.Common.LL.Exc_Stack_Ptr := new Exc_Stack_T; SSL.Set_Exc_Stack_Addr (To_Address (Self_ID), Self_ID.Common.LL.Exc_Stack_Ptr (Exc_Stack_T'Last)'Address); else Result := pthread_mutex_destroy (Self_ID.Common.LL.L'Access); pragma Assert (Result = 0); Succeeded := False; end if; Result := pthread_condattr_destroy (Cond_Attr'Access); pragma Assert (Result = 0); end Initialize_TCB; ----------------- -- Create_Task -- ----------------- procedure Create_Task (T : Task_ID; Wrapper : System.Address; Stack_Size : System.Parameters.Size_Type; Priority : System.Any_Priority; Succeeded : out Boolean) is Attributes : aliased pthread_attr_t; Adjusted_Stack_Size : Interfaces.C.size_t; Result : Interfaces.C.int; function Thread_Body_Access is new Unchecked_Conversion (System.Address, Thread_Body); begin if Stack_Size = Unspecified_Size then Adjusted_Stack_Size := Interfaces.C.size_t (Default_Stack_Size); elsif Stack_Size < Minimum_Stack_Size then Adjusted_Stack_Size := Interfaces.C.size_t (Minimum_Stack_Size); else Adjusted_Stack_Size := Interfaces.C.size_t (Stack_Size); end if; -- Since the initial signal mask of a thread is inherited from the -- creator, we need to set our local signal mask mask all signals -- during the creation operation, to make sure the new thread is -- not disturbed by signals before it has set its own Task_ID. Result := pthread_attr_init (Attributes'Access); pragma Assert (Result = 0 or else Result = ENOMEM); if Result /= 0 then Succeeded := False; return; end if; Result := pthread_attr_setdetachstate (Attributes'Access, PTHREAD_CREATE_DETACHED); pragma Assert (Result = 0); Result := pthread_attr_setstacksize (Attributes'Access, Adjusted_Stack_Size); pragma Assert (Result = 0); -- This call may be unnecessary, not sure. ??? Result := pthread_attr_setinheritsched (Attributes'Access, PTHREAD_EXPLICIT_SCHED); pragma Assert (Result = 0); Result := pthread_create (T.Common.LL.Thread'Access, Attributes'Access, Thread_Body_Access (Wrapper), To_Address (T)); -- ENOMEM is a valid run-time error. Don't shut down. pragma Assert (Result = 0 or else Result = EAGAIN or else Result = ENOMEM); Succeeded := Result = 0; Result := pthread_attr_destroy (Attributes'Access); pragma Assert (Result = 0); if Succeeded then Set_Priority (T, Priority); end if; end Create_Task; ------------------ -- Finalize_TCB -- ------------------ procedure Finalize_TCB (T : Task_ID) is Result : Interfaces.C.int; Tmp : Task_ID := T; procedure Free is new Unchecked_Deallocation (Ada_Task_Control_Block, Task_ID); procedure Free is new Unchecked_Deallocation (Exc_Stack_T, Exc_Stack_Ptr_T); begin Result := pthread_mutex_destroy (T.Common.LL.L'Access); pragma Assert (Result = 0); Result := pthread_cond_destroy (T.Common.LL.CV'Access); pragma Assert (Result = 0); if T.Known_Tasks_Index /= -1 then Known_Tasks (T.Known_Tasks_Index) := null; end if; Free (T.Common.LL.Exc_Stack_Ptr); Free (Tmp); end Finalize_TCB; --------------- -- Exit_Task -- --------------- procedure Exit_Task is begin pthread_exit (System.Null_Address); end Exit_Task; ---------------- -- Abort_Task -- ---------------- procedure Abort_Task (T : Task_ID) is begin -- Why is this commented out ??? -- if T = Self and then T.Deferral_Level = 0 -- and then T.Pending_ATC_Level < T.ATC_Nesting_Level -- then -- raise Standard'Abort_Signal; -- end if; -- -- Interrupt Server_Tasks may be waiting on an event flag -- if T.Common.State = Interrupt_Server_Blocked_On_Event_Flag then Wakeup (T, Interrupt_Server_Blocked_On_Event_Flag); end if; end Abort_Task; ---------------- -- Check_Exit -- ---------------- -- Dummy versions. The only currently working versions is for solaris -- (native). function Check_Exit (Self_ID : ST.Task_ID) return Boolean is begin return True; end Check_Exit; -------------------- -- Check_No_Locks -- -------------------- function Check_No_Locks (Self_ID : ST.Task_ID) return Boolean is begin return True; end Check_No_Locks; ---------------------- -- Environment_Task -- ---------------------- function Environment_Task return Task_ID is begin return Environment_Task_ID; end Environment_Task; ------------------------- -- Lock_All_Tasks_List -- ------------------------- procedure Lock_All_Tasks_List is begin Write_Lock (All_Tasks_L'Access); end Lock_All_Tasks_List; --------------------------- -- Unlock_All_Tasks_List -- --------------------------- procedure Unlock_All_Tasks_List is begin Unlock (All_Tasks_L'Access); end Unlock_All_Tasks_List; ------------------ -- Suspend_Task -- ------------------ function Suspend_Task (T : ST.Task_ID; Thread_Self : Thread_Id) return Boolean is begin return False; end Suspend_Task; ----------------- -- Resume_Task -- ----------------- function Resume_Task (T : ST.Task_ID; Thread_Self : Thread_Id) return Boolean is begin return False; end Resume_Task; ---------------- -- Initialize -- ---------------- procedure Initialize (Environment_Task : Task_ID) is begin Environment_Task_ID := Environment_Task; Initialize_Lock (All_Tasks_L'Access, All_Tasks_Level); -- Initialize the lock used to synchronize chain of all ATCBs. Enter_Task (Environment_Task); end Initialize; begin declare Result : Interfaces.C.int; begin Result := pthread_key_create (ATCB_Key'Access, null); pragma Assert (Result = 0); end; end System.Task_Primitives.Operations;
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; package MAT.Events.Tools is Not_Found : exception; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event_Type); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type; type Event_Info_Type is record First_Event : Target_Event_Type; Last_Event : Target_Event_Type; Count : Natural := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; -- Collect statistics information about events. procedure Collect_Info (Into : in out Event_Info_Type; Event : in MAT.Events.Target_Event_Type); package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; -- The frame key is composed of the frame address and the frame level. type Frame_Key_Type is record Addr : MAT.Types.Target_Addr; Level : Natural; end record; function "<" (Left, Right : in Frame_Key_Type) return Boolean; -- Ordered map to collect event info statistics by <frame, level> pair. package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Key_Type, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Frame_Info_Type is record Key : Frame_Key_Type; Info : Event_Info_Type; end record; package Frame_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Frame_Info_Type); subtype Frame_Info_Vector is Frame_Info_Vectors.Vector; subtype Frame_Info_Cursor is Frame_Info_Vectors.Cursor; -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector); end MAT.Events.Tools;
-- -- Copyright 2022 (C) Nicolas Pinault (aka DrPi) -- -- SPDX-License-Identifier: BSD-3-Clause -- with Ada.Command_Line; use Ada.Command_Line; with Ada.Streams.Stream_IO; package elf2uf2 is package SIO renames Ada.Streams.Stream_IO; use SIO; type Verbosity_Level is range 0 .. 2; procedure Set_Verbosity (Level : Verbosity_Level); function Run (In_File : SIO.File_Type; Out_File : in out SIO.File_Type) return Exit_Status; private Verbosity : Verbosity_Level := 0; end elf2uf2;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- I N T E R F A C E S . C O B O L -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2021, 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. -- -- -- ------------------------------------------------------------------------------ -- The body of Interfaces.COBOL is implementation independent (i.e. the same -- version is used with all versions of GNAT). The specialization to a -- particular COBOL format is completely contained in the private part of -- the spec. with Interfaces; use Interfaces; with System; use System; with Ada.Unchecked_Conversion; package body Interfaces.COBOL is ----------------------------------------------- -- Declarations for External Binary Handling -- ----------------------------------------------- subtype B1 is Byte_Array (1 .. 1); subtype B2 is Byte_Array (1 .. 2); subtype B4 is Byte_Array (1 .. 4); subtype B8 is Byte_Array (1 .. 8); -- Representations for 1,2,4,8 byte binary values function To_B1 is new Ada.Unchecked_Conversion (Integer_8, B1); function To_B2 is new Ada.Unchecked_Conversion (Integer_16, B2); function To_B4 is new Ada.Unchecked_Conversion (Integer_32, B4); function To_B8 is new Ada.Unchecked_Conversion (Integer_64, B8); -- Conversions from native binary to external binary function From_B1 is new Ada.Unchecked_Conversion (B1, Integer_8); function From_B2 is new Ada.Unchecked_Conversion (B2, Integer_16); function From_B4 is new Ada.Unchecked_Conversion (B4, Integer_32); function From_B8 is new Ada.Unchecked_Conversion (B8, Integer_64); -- Conversions from external binary to signed native binary function From_B1U is new Ada.Unchecked_Conversion (B1, Unsigned_8); function From_B2U is new Ada.Unchecked_Conversion (B2, Unsigned_16); function From_B4U is new Ada.Unchecked_Conversion (B4, Unsigned_32); function From_B8U is new Ada.Unchecked_Conversion (B8, Unsigned_64); -- Conversions from external binary to unsigned native binary ----------------------- -- Local Subprograms -- ----------------------- function Binary_To_Decimal (Item : Byte_Array; Format : Binary_Format) return Integer_64; -- This function converts a numeric value in the given format to its -- corresponding integer value. This is the non-generic implementation -- of Decimal_Conversions.To_Decimal. The generic routine does the -- final conversion to the fixed-point format. function Numeric_To_Decimal (Item : Numeric; Format : Display_Format) return Integer_64; -- This function converts a numeric value in the given format to its -- corresponding integer value. This is the non-generic implementation -- of Decimal_Conversions.To_Decimal. The generic routine does the -- final conversion to the fixed-point format. function Packed_To_Decimal (Item : Packed_Decimal; Format : Packed_Format) return Integer_64; -- This function converts a packed value in the given format to its -- corresponding integer value. This is the non-generic implementation -- of Decimal_Conversions.To_Decimal. The generic routine does the -- final conversion to the fixed-point format. procedure Swap (B : in out Byte_Array; F : Binary_Format); -- Swaps the bytes if required by the binary format F function To_Display (Item : Integer_64; Format : Display_Format; Length : Natural) return Numeric; -- This function converts the given integer value into display format, -- using the given format, with the length in bytes of the result given -- by the last parameter. This is the non-generic implementation of -- Decimal_Conversions.To_Display. The conversion of the item from its -- original decimal format to Integer_64 is done by the generic routine. function To_Packed (Item : Integer_64; Format : Packed_Format; Length : Natural) return Packed_Decimal; -- This function converts the given integer value into packed format, -- using the given format, with the length in digits of the result given -- by the last parameter. This is the non-generic implementation of -- Decimal_Conversions.To_Display. The conversion of the item from its -- original decimal format to Integer_64 is done by the generic routine. function Valid_Numeric (Item : Numeric; Format : Display_Format) return Boolean; -- This is the non-generic implementation of Decimal_Conversions.Valid -- for the display case. function Valid_Packed (Item : Packed_Decimal; Format : Packed_Format) return Boolean; -- This is the non-generic implementation of Decimal_Conversions.Valid -- for the packed case. ----------------------- -- Binary_To_Decimal -- ----------------------- function Binary_To_Decimal (Item : Byte_Array; Format : Binary_Format) return Integer_64 is Len : constant Natural := Item'Length; begin if Len = 1 then if Format in Binary_Unsigned_Format then return Integer_64 (From_B1U (Item)); else return Integer_64 (From_B1 (Item)); end if; elsif Len = 2 then declare R : B2 := Item; begin Swap (R, Format); if Format in Binary_Unsigned_Format then return Integer_64 (From_B2U (R)); else return Integer_64 (From_B2 (R)); end if; end; elsif Len = 4 then declare R : B4 := Item; begin Swap (R, Format); if Format in Binary_Unsigned_Format then return Integer_64 (From_B4U (R)); else return Integer_64 (From_B4 (R)); end if; end; elsif Len = 8 then declare R : B8 := Item; begin Swap (R, Format); if Format in Binary_Unsigned_Format then return Integer_64 (From_B8U (R)); else return Integer_64 (From_B8 (R)); end if; end; -- Length is not 1, 2, 4 or 8 else raise Conversion_Error; end if; end Binary_To_Decimal; ------------------------ -- Numeric_To_Decimal -- ------------------------ -- The following assumptions are made in the coding of this routine: -- The range of COBOL_Digits is compact and the ten values -- represent the digits 0-9 in sequence -- The range of COBOL_Plus_Digits is compact and the ten values -- represent the digits 0-9 in sequence with a plus sign. -- The range of COBOL_Minus_Digits is compact and the ten values -- represent the digits 0-9 in sequence with a minus sign. -- The COBOL_Minus_Digits set is disjoint from COBOL_Digits -- These assumptions are true for all COBOL representations we know of function Numeric_To_Decimal (Item : Numeric; Format : Display_Format) return Integer_64 is pragma Unsuppress (Range_Check); Sign : COBOL_Character := COBOL_Plus; Result : Integer_64 := 0; begin if not Valid_Numeric (Item, Format) then raise Conversion_Error; end if; for J in Item'Range loop declare K : constant COBOL_Character := Item (J); begin if K in COBOL_Digits then Result := Result * 10 + (COBOL_Character'Pos (K) - COBOL_Character'Pos (COBOL_Digits'First)); elsif K in COBOL_Minus_Digits then Result := Result * 10 + (COBOL_Character'Pos (K) - COBOL_Character'Pos (COBOL_Minus_Digits'First)); Sign := COBOL_Minus; -- Only remaining possibility is COBOL_Plus or COBOL_Minus else Sign := K; end if; end; end loop; if Sign = COBOL_Plus then return Result; else return -Result; end if; exception when Constraint_Error => raise Conversion_Error; end Numeric_To_Decimal; ----------------------- -- Packed_To_Decimal -- ----------------------- function Packed_To_Decimal (Item : Packed_Decimal; Format : Packed_Format) return Integer_64 is pragma Unsuppress (Range_Check); Result : Integer_64 := 0; Sign : constant Decimal_Element := Item (Item'Last); begin if not Valid_Packed (Item, Format) then raise Conversion_Error; end if; case Packed_Representation is when IBM => for J in Item'First .. Item'Last - 1 loop Result := Result * 10 + Integer_64 (Item (J)); end loop; if Sign = 16#0B# or else Sign = 16#0D# then return -Result; else return +Result; end if; end case; exception when Constraint_Error => raise Conversion_Error; end Packed_To_Decimal; ---------- -- Swap -- ---------- procedure Swap (B : in out Byte_Array; F : Binary_Format) is Little_Endian : constant Boolean := System.Default_Bit_Order = System.Low_Order_First; begin -- Return if no swap needed case F is when H | HU => if not Little_Endian then return; end if; when L | LU => if Little_Endian then return; end if; when N | NU => return; end case; -- Here a swap is needed declare Len : constant Natural := B'Length; begin for J in 1 .. Len / 2 loop declare Temp : constant Byte := B (J); begin B (J) := B (Len + 1 - J); B (Len + 1 - J) := Temp; end; end loop; end; end Swap; ----------------------- -- To_Ada (function) -- ----------------------- function To_Ada (Item : Alphanumeric) return String is Result : String (Item'Range); begin for J in Item'Range loop Result (J) := COBOL_To_Ada (Item (J)); end loop; return Result; end To_Ada; ------------------------ -- To_Ada (procedure) -- ------------------------ procedure To_Ada (Item : Alphanumeric; Target : out String; Last : out Natural) is Last_Val : Integer; begin if Item'Length > Target'Length then raise Constraint_Error; end if; Last_Val := Target'First - 1; for J in Item'Range loop Last_Val := Last_Val + 1; Target (Last_Val) := COBOL_To_Ada (Item (J)); end loop; Last := Last_Val; end To_Ada; ------------------------- -- To_COBOL (function) -- ------------------------- function To_COBOL (Item : String) return Alphanumeric is Result : Alphanumeric (Item'Range); begin for J in Item'Range loop Result (J) := Ada_To_COBOL (Item (J)); end loop; return Result; end To_COBOL; -------------------------- -- To_COBOL (procedure) -- -------------------------- procedure To_COBOL (Item : String; Target : out Alphanumeric; Last : out Natural) is Last_Val : Integer; begin if Item'Length > Target'Length then raise Constraint_Error; end if; Last_Val := Target'First - 1; for J in Item'Range loop Last_Val := Last_Val + 1; Target (Last_Val) := Ada_To_COBOL (Item (J)); end loop; Last := Last_Val; end To_COBOL; ---------------- -- To_Display -- ---------------- function To_Display (Item : Integer_64; Format : Display_Format; Length : Natural) return Numeric is Result : Numeric (1 .. Length); Val : Integer_64 := Item; procedure Convert (First, Last : Natural); -- Convert the number in Val into COBOL_Digits, storing the result -- in Result (First .. Last). Raise Conversion_Error if too large. procedure Embed_Sign (Loc : Natural); -- Used for the nonseparate formats to embed the appropriate sign -- at the specified location (i.e. at Result (Loc)) ------------- -- Convert -- ------------- procedure Convert (First, Last : Natural) is J : Natural; begin J := Last; while J >= First loop Result (J) := COBOL_Character'Val (COBOL_Character'Pos (COBOL_Digits'First) + Integer (Val mod 10)); Val := Val / 10; if Val = 0 then for K in First .. J - 1 loop Result (J) := COBOL_Digits'First; end loop; return; else J := J - 1; end if; end loop; raise Conversion_Error; end Convert; ---------------- -- Embed_Sign -- ---------------- procedure Embed_Sign (Loc : Natural) is Digit : Natural range 0 .. 9; begin Digit := COBOL_Character'Pos (Result (Loc)) - COBOL_Character'Pos (COBOL_Digits'First); if Item >= 0 then Result (Loc) := COBOL_Character'Val (COBOL_Character'Pos (COBOL_Plus_Digits'First) + Digit); else Result (Loc) := COBOL_Character'Val (COBOL_Character'Pos (COBOL_Minus_Digits'First) + Digit); end if; end Embed_Sign; -- Start of processing for To_Display begin case Format is when Unsigned => if Val < 0 then raise Conversion_Error; else Convert (1, Length); end if; when Leading_Separate => if Val < 0 then Result (1) := COBOL_Minus; Val := -Val; else Result (1) := COBOL_Plus; end if; Convert (2, Length); when Trailing_Separate => if Val < 0 then Result (Length) := COBOL_Minus; Val := -Val; else Result (Length) := COBOL_Plus; end if; Convert (1, Length - 1); when Leading_Nonseparate => Val := abs Val; Convert (1, Length); Embed_Sign (1); when Trailing_Nonseparate => Val := abs Val; Convert (1, Length); Embed_Sign (Length); end case; return Result; end To_Display; --------------- -- To_Packed -- --------------- function To_Packed (Item : Integer_64; Format : Packed_Format; Length : Natural) return Packed_Decimal is Result : Packed_Decimal (1 .. Length); Val : Integer_64; procedure Convert (First, Last : Natural); -- Convert the number in Val into a sequence of Decimal_Element values, -- storing the result in Result (First .. Last). Raise Conversion_Error -- if the value is too large to fit. ------------- -- Convert -- ------------- procedure Convert (First, Last : Natural) is J : Natural := Last; begin while J >= First loop Result (J) := Decimal_Element (Val mod 10); Val := Val / 10; if Val = 0 then for K in First .. J - 1 loop Result (K) := 0; end loop; return; else J := J - 1; end if; end loop; raise Conversion_Error; end Convert; -- Start of processing for To_Packed begin case Packed_Representation is when IBM => if Format = Packed_Unsigned then if Item < 0 then raise Conversion_Error; else Result (Length) := 16#F#; Val := Item; end if; elsif Item >= 0 then Result (Length) := 16#C#; Val := Item; else -- Item < 0 Result (Length) := 16#D#; Val := -Item; end if; Convert (1, Length - 1); return Result; end case; end To_Packed; ------------------- -- Valid_Numeric -- ------------------- function Valid_Numeric (Item : Numeric; Format : Display_Format) return Boolean is begin if Item'Length = 0 then return False; end if; -- All character positions except first and last must be Digits. -- This is true for all the formats. for J in Item'First + 1 .. Item'Last - 1 loop if Item (J) not in COBOL_Digits then return False; end if; end loop; case Format is when Unsigned => return Item (Item'First) in COBOL_Digits and then Item (Item'Last) in COBOL_Digits; when Leading_Separate => return (Item (Item'First) = COBOL_Plus or else Item (Item'First) = COBOL_Minus) and then Item (Item'Last) in COBOL_Digits; when Trailing_Separate => return Item (Item'First) in COBOL_Digits and then (Item (Item'Last) = COBOL_Plus or else Item (Item'Last) = COBOL_Minus); when Leading_Nonseparate => return (Item (Item'First) in COBOL_Plus_Digits or else Item (Item'First) in COBOL_Minus_Digits) and then Item (Item'Last) in COBOL_Digits; when Trailing_Nonseparate => return Item (Item'First) in COBOL_Digits and then (Item (Item'Last) in COBOL_Plus_Digits or else Item (Item'Last) in COBOL_Minus_Digits); end case; end Valid_Numeric; ------------------ -- Valid_Packed -- ------------------ function Valid_Packed (Item : Packed_Decimal; Format : Packed_Format) return Boolean is begin case Packed_Representation is when IBM => for J in Item'First .. Item'Last - 1 loop if Item (J) > 9 then return False; end if; end loop; -- For unsigned, sign digit must be F if Format = Packed_Unsigned then return Item (Item'Last) = 16#F#; -- For signed, accept all standard and non-standard signs else return Item (Item'Last) >= 16#A#; end if; end case; end Valid_Packed; ------------------------- -- Decimal_Conversions -- ------------------------- package body Decimal_Conversions is --------------------- -- Length (binary) -- --------------------- -- Note that the tests here are all compile time tests function Length (Format : Binary_Format) return Natural is pragma Unreferenced (Format); begin if Num'Digits <= 2 then return 1; elsif Num'Digits <= 4 then return 2; elsif Num'Digits <= 9 then return 4; else -- Num'Digits in 10 .. 18 return 8; end if; end Length; ---------------------- -- Length (display) -- ---------------------- function Length (Format : Display_Format) return Natural is begin if Format = Leading_Separate or else Format = Trailing_Separate then return Num'Digits + 1; else return Num'Digits; end if; end Length; --------------------- -- Length (packed) -- --------------------- -- Note that the tests here are all compile time checks function Length (Format : Packed_Format) return Natural is pragma Unreferenced (Format); begin case Packed_Representation is when IBM => return (Num'Digits + 2) / 2 * 2; end case; end Length; --------------- -- To_Binary -- --------------- function To_Binary (Item : Num; Format : Binary_Format) return Byte_Array is begin -- Note: all these tests are compile time tests if Num'Digits <= 2 then return To_B1 (Integer_8'Integer_Value (Item)); elsif Num'Digits <= 4 then declare R : B2 := To_B2 (Integer_16'Integer_Value (Item)); begin Swap (R, Format); return R; end; elsif Num'Digits <= 9 then declare R : B4 := To_B4 (Integer_32'Integer_Value (Item)); begin Swap (R, Format); return R; end; else -- Num'Digits in 10 .. 18 declare R : B8 := To_B8 (Integer_64'Integer_Value (Item)); begin Swap (R, Format); return R; end; end if; exception when Constraint_Error => raise Conversion_Error; end To_Binary; --------------------------------- -- To_Binary (internal binary) -- --------------------------------- function To_Binary (Item : Num) return Binary is pragma Unsuppress (Range_Check); begin return Binary'Integer_Value (Item); exception when Constraint_Error => raise Conversion_Error; end To_Binary; ------------------------- -- To_Decimal (binary) -- ------------------------- function To_Decimal (Item : Byte_Array; Format : Binary_Format) return Num is pragma Unsuppress (Range_Check); begin return Num'Fixed_Value (Binary_To_Decimal (Item, Format)); exception when Constraint_Error => raise Conversion_Error; end To_Decimal; ---------------------------------- -- To_Decimal (internal binary) -- ---------------------------------- function To_Decimal (Item : Binary) return Num is pragma Unsuppress (Range_Check); begin return Num'Fixed_Value (Item); exception when Constraint_Error => raise Conversion_Error; end To_Decimal; -------------------------- -- To_Decimal (display) -- -------------------------- function To_Decimal (Item : Numeric; Format : Display_Format) return Num is pragma Unsuppress (Range_Check); begin return Num'Fixed_Value (Numeric_To_Decimal (Item, Format)); exception when Constraint_Error => raise Conversion_Error; end To_Decimal; --------------------------------------- -- To_Decimal (internal long binary) -- --------------------------------------- function To_Decimal (Item : Long_Binary) return Num is pragma Unsuppress (Range_Check); begin return Num'Fixed_Value (Item); exception when Constraint_Error => raise Conversion_Error; end To_Decimal; ------------------------- -- To_Decimal (packed) -- ------------------------- function To_Decimal (Item : Packed_Decimal; Format : Packed_Format) return Num is pragma Unsuppress (Range_Check); begin return Num'Fixed_Value (Packed_To_Decimal (Item, Format)); exception when Constraint_Error => raise Conversion_Error; end To_Decimal; ---------------- -- To_Display -- ---------------- function To_Display (Item : Num; Format : Display_Format) return Numeric is pragma Unsuppress (Range_Check); begin return To_Display (Integer_64'Integer_Value (Item), Format, Length (Format)); exception when Constraint_Error => raise Conversion_Error; end To_Display; -------------------- -- To_Long_Binary -- -------------------- function To_Long_Binary (Item : Num) return Long_Binary is pragma Unsuppress (Range_Check); begin return Long_Binary'Integer_Value (Item); exception when Constraint_Error => raise Conversion_Error; end To_Long_Binary; --------------- -- To_Packed -- --------------- function To_Packed (Item : Num; Format : Packed_Format) return Packed_Decimal is pragma Unsuppress (Range_Check); begin return To_Packed (Integer_64'Integer_Value (Item), Format, Length (Format)); exception when Constraint_Error => raise Conversion_Error; end To_Packed; -------------------- -- Valid (binary) -- -------------------- function Valid (Item : Byte_Array; Format : Binary_Format) return Boolean is Val : Num; pragma Unreferenced (Val); begin Val := To_Decimal (Item, Format); return True; exception when Conversion_Error => return False; end Valid; --------------------- -- Valid (display) -- --------------------- function Valid (Item : Numeric; Format : Display_Format) return Boolean is begin return Valid_Numeric (Item, Format); end Valid; -------------------- -- Valid (packed) -- -------------------- function Valid (Item : Packed_Decimal; Format : Packed_Format) return Boolean is begin return Valid_Packed (Item, Format); end Valid; end Decimal_Conversions; end Interfaces.COBOL;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Schemas; with ADO.Sessions; with ASF.Helpers.Beans; with AWA.Comments.Models; with AWA.Comments.Modules; -- == Comment Beans == -- Several bean types are provided to represent and manage a list of tags. -- The tag module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. -- -- === Comment_List_Bean === -- The <tt>Comment_List_Bean</tt> holds a list of comments and provides operations used by the -- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component. -- A bean can be declared and configured as follows in the XML application configuration file: -- -- <managed-bean> -- <managed-bean-name>postCommentList</managed-bean-name> -- <managed-bean-class>AWA.Comments.Beans.Comment_List_Bean</managed-bean-class> -- <managed-bean-scope>request</managed-bean-scope> -- <managed-property> -- <property-name>entity_type</property-name> -- <property-class>String</property-class> -- <value>awa_post</value> -- </managed-property> -- <managed-property> -- <property-name>permission</property-name> -- <property-class>String</property-class> -- <value>blog-comment-post</value> -- </managed-property> -- </managed-bean> -- -- The <tt>entity_type</tt> property defines the name of the database table to which the comments -- are assigned. The <tt>permission</tt> property defines the permission name that must be used -- to verify that the user has the permission do add or remove the comment. -- package AWA.Comments.Beans is type Comment_Bean is new AWA.Comments.Models.Comment_Bean with record Module : Modules.Comment_Module_Access := null; Entity_Type : Ada.Strings.Unbounded.Unbounded_String; Permission : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Bean_Access is access all Comment_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the comment. overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Save the comment. overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Publish or not the comment. overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the comment. overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create a new comment bean instance. function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Comment_List_Bean is new AWA.Comments.Models.Comment_Info_List_Bean and Util.Beans.Basic.Bean with record Module : AWA.Comments.Modules.Comment_Module_Access; Entity_Type : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Permission : Ada.Strings.Unbounded.Unbounded_String; Current : Natural := 0; end record; type Comment_List_Bean_Access is access all Comment_List_Bean'Class; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Set the entity type (database table) with which the comments are associated. procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access); -- Set the permission to check before removing or adding a comment on the entity. procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String); -- Load the comments associated with the given database identifier. procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier); -- Load the comments associated with the given database identifier. procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier); -- Create the comment list bean instance. function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Comment_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_Bean, Element_Access => Comment_Bean_Access); function Get_Comment_List_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Comment_List_Bean, Element_Access => Comment_List_Bean_Access); end AWA.Comments.Beans;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . B B . B O A R D _ S U P P O R T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1999-2002 Universidad Politecnica de Madrid -- -- Copyright (C) 2003-2005 The European Space Agency -- -- Copyright (C) 2003-2018, 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. -- -- -- -- The port of GNARL to bare board targets was initially developed by the -- -- Real-Time Systems Group at the Technical University of Madrid. -- -- -- ------------------------------------------------------------------------------ with System.Machine_Code; with System.BB.CPU_Primitives; with System.BB.Board_Parameters; with Interfaces.NRF51; use Interfaces.NRF51; with Interfaces.NRF51.RTC; use Interfaces.NRF51.RTC; with Interfaces.NRF51.CLOCK; use Interfaces.NRF51.CLOCK; package body System.BB.Board_Support is use CPU_Primitives, BB.Interrupts, Machine_Code, Time; package BBOPA renames System.BB.Board_Parameters; Interrupt_Request_Vector : constant Vector_Id := 16; -- See vector definitions in ARMv7-M version of System.BB.CPU_Primitives. -- Defined by ARMv7-M specifications. Alarm_Time : Time.Timer_Interval; pragma Volatile (Alarm_Time); pragma Export (C, Alarm_Time, "__gnat_alarm_time"); Alarm_Interrupt_ID : constant Interrupt_ID := 11; ------------------- -- RTC0 Handling -- ------------------- Tick_Period : constant Time.Timer_Interval := BBOPA.Clock_Frequency / (32_768 / (BBOPA.RTC_Prescaler + 1)); Next_Tick_Time : Timer_Interval with Volatile; -- Time when systick will expire. This gives the high digits of the time ---------------------------------------------- -- New Vectored Interrupt Controller (NVIC) -- ---------------------------------------------- NVIC_Base : constant := 16#E000_E000#; -- Nested Vectored Interrupt Controller (NVIC) base. NVIC_ISER0 : constant Address := NVIC_Base + 16#100#; -- Writing a bit mask to this register enables the corresponding interrupts type PRI is mod 2**8; -- Type for ARMv7-M interrupt priorities. Note that 0 is the highest -- priority, which is reserved for the kernel and has no corresponding -- Interrupt_Priority value, and 255 is the lowest. We assume the PRIGROUP -- setting is such that the 4 most significant bits determine the priority -- group used for preemption. However, if less bits are implemented, this -- should still work. function To_PRI (P : Integer) return PRI is (if P not in Interrupt_Priority then 0 else PRI (Interrupt_Priority'Last - P + 1) * 16); -- Return the BASEPRI mask for the given Ada priority. Note that the zero -- value here means no mask, so no interrupts are masked. function To_Priority (P : PRI) return Interrupt_Priority is (if P = 0 then Interrupt_Priority'Last else (Interrupt_Priority'Last - Any_Priority'Base (P / 16) + 1)); -- Given an ARM interrupt priority (PRI value), determine the Ada priority -- While the value 0 is reserved for the kernel and has no Ada priority -- that represents it, Interrupt_Priority'Last is closest. IP : array (0 .. Interrupt_ID'Last) of PRI with Volatile, Address => 16#E000_E400#; -- Local utility functions procedure Enable_Interrupt_Request (Interrupt : Interrupt_ID; Prio : Interrupt_Priority); -- Enable interrupt requests for the given interrupt procedure Interrupt_Handler; -- Low-level interrupt handlers ---------------------- -- Initialize_Board -- ---------------------- procedure Initialize_Board is begin -- Mask interrupts Disable_Interrupts; -- Timer -- -- Configure the low frequency clock required for RTC0 CLOCK_Periph.LFCLKSRC.SRC := Rc; -- Use internal RC oscillator -- Start the low frequency clock CLOCK_Periph.TASKS_LFCLKSTART := 1; -- Wait until the low frequency clock is started while CLOCK_Periph.EVENTS_LFCLKSTARTED = 0 loop null; end loop; -- We run the counter at 32.768KHz RTC0_Periph.PRESCALER.PRESCALER := BBOPA.RTC_Prescaler; RTC0_Periph.INTENSET.TICK := Set; RTC0_Periph.EVTENSET.TICK := Set; Next_Tick_Time := Tick_Period; Time.Set_Alarm (Timer_Interval'Last); Time.Clear_Alarm_Interrupt; -- We do not start the timer until the handler is ready to receive the -- interrupt, i.e. in Install_Alarm_Handler. -- Interrupts -- Install_Trap_Handler (Interrupt_Handler'Address, Interrupt_Request_Vector); end Initialize_Board; package body Time is Upper_Alarm_Handler : BB.Interrupts.Interrupt_Handler := null; procedure Pre_Alarm_Handler (Id : Interrupt_ID); ----------------------- -- Pre_Alarm_Handler -- ----------------------- procedure Pre_Alarm_Handler (Id : Interrupt_ID) is begin Next_Tick_Time := Next_Tick_Time + Tick_Period; pragma Assert (Upper_Alarm_Handler /= null); Upper_Alarm_Handler (Id); end Pre_Alarm_Handler; ------------------------ -- Max_Timer_Interval -- ------------------------ function Max_Timer_Interval return Timer_Interval is (2**32 - 1); ---------------- -- Read_Clock -- ---------------- function Read_Clock return BB.Time.Time is PRIMASK : Word; Res : Timer_Interval; begin -- As several registers and variables need to be read or modified, do -- it atomically. Asm ("mrs %0, PRIMASK", Outputs => Word'Asm_Output ("=&r", PRIMASK), Volatile => True); Asm ("msr PRIMASK, %0", Inputs => Word'Asm_Input ("r", 1), Volatile => True); Res := Next_Tick_Time; -- Restore interrupt mask Asm ("msr PRIMASK, %0", Inputs => Word'Asm_Input ("r", PRIMASK), Volatile => True); return BB.Time.Time (Res); end Read_Clock; --------------------------- -- Clear_Alarm_Interrupt -- --------------------------- procedure Clear_Alarm_Interrupt is begin RTC0_Periph.EVENTS_TICK := 0; end Clear_Alarm_Interrupt; --------------- -- Set_Alarm -- --------------- procedure Set_Alarm (Ticks : Timer_Interval) is Now : constant Timer_Interval := Timer_Interval (Read_Clock); begin -- As we will have periodic interrupts for alarms regardless, the -- only thing to do is force an interrupt if the alarm has already -- expired. Alarm_Time := Now + Timer_Interval'Min (Timer_Interval'Last / 2, Ticks); -- FIXME: We can't do that with RTC0 -- if Ticks = 0 then -- ICSR := ICSR_Pend_ST_Set; -- end if; end Set_Alarm; --------------------------- -- Install_Alarm_Handler -- --------------------------- procedure Install_Alarm_Handler (Handler : BB.Interrupts.Interrupt_Handler) is begin pragma Assert (Upper_Alarm_Handler = null); Upper_Alarm_Handler := Handler; BB.Interrupts.Attach_Handler (Pre_Alarm_Handler'Access, Alarm_Interrupt_ID, Interrupt_Priority'Last); -- Clear pending timer interrupt if any Time.Clear_Alarm_Interrupt; -- Now that the interrupt handler is attached, we can start the timer RTC0_Periph.TASKS_START := 1; end Install_Alarm_Handler; end Time; package body Multiprocessors is separate; ----------------------- -- Interrupt_Handler -- ----------------------- procedure Interrupt_Handler is Id : Interrupt_ID; Res : Word; PRIMASK : Word; begin Asm ("mrs %0, PRIMASK", Outputs => Word'Asm_Output ("=&r", PRIMASK), Volatile => True); Asm ("msr PRIMASK, %0", Inputs => Word'Asm_Input ("r", 1), Volatile => True); -- The exception number is read from the IPSR Asm ("mrs %0, ipsr", Word'Asm_Output ("=r", Res), Volatile => True); Res := Res and 16#FF#; -- Convert it to IRQ number by substracting 16 (number of cpu -- exceptions). Id := Interrupt_ID'Base (Res) - 16; Interrupt_Wrapper (Id); -- Restore interrupt mask Asm ("msr PRIMASK, %0", Inputs => Word'Asm_Input ("r", PRIMASK), Volatile => True); end Interrupt_Handler; ------------------------------ -- Enable_Interrupt_Request -- ------------------------------ procedure Enable_Interrupt_Request (Interrupt : Interrupt_ID; Prio : Interrupt_Priority) is begin if Interrupt = Alarm_Interrupt_ID then -- Consistency check with Priority_Of_Interrupt pragma Assert (Prio = Interrupt_Priority'Last); Time.Clear_Alarm_Interrupt; end if; declare pragma Assert (Interrupt >= 0); IRQ : constant Natural := Interrupt; Regofs : constant Natural := IRQ / 32; Regbit : constant Word := 2** (IRQ mod 32); NVIC_ISER : array (0 .. 15) of Word with Volatile, Address => NVIC_ISER0; -- Many NVIC registers use 16 words of 32 bits each to serve as a -- bitmap for all interrupt channels. Regofs indicates register -- offset (0 .. 15), and Regbit indicates the mask required for -- addressing the bit. begin NVIC_ISER (Regofs) := Regbit; end; end Enable_Interrupt_Request; package body Interrupts is ------------------------------- -- Install_Interrupt_Handler -- ------------------------------- procedure Install_Interrupt_Handler (Interrupt : Interrupt_ID; Prio : Interrupt_Priority) is begin if Interrupt /= Alarm_Interrupt_ID then IP (Interrupt) := To_PRI (Prio); end if; Enable_Interrupt_Request (Interrupt, Prio); end Install_Interrupt_Handler; --------------------------- -- Priority_Of_Interrupt -- --------------------------- function Priority_Of_Interrupt (Interrupt : Interrupt_ID) return Any_Priority is (if Interrupt = Alarm_Interrupt_ID then Interrupt_Priority'Last else To_Priority (IP (Interrupt))); ---------------- -- Power_Down -- ---------------- procedure Power_Down is begin Asm ("wfi", Volatile => True); end Power_Down; -------------------------- -- Set_Current_Priority -- -------------------------- procedure Set_Current_Priority (Priority : Integer) is begin -- Writing a 0 to BASEPRI disables interrupt masking, while values -- 15 .. 1 correspond to interrupt priorities 255 .. 241 in that -- order. Asm ("msr BASEPRI, %0", Inputs => PRI'Asm_Input ("r", To_PRI (Priority)), Volatile => True); end Set_Current_Priority; end Interrupts; end System.BB.Board_Support;
with Ada.Text_IO; use Ada.Text_IO; procedure Test is X : Integer; begin X := 1 + 'a'; end;
-- Copyright © by Jeff Foley 2022. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. -- SPDX-License-Identifier: Apache-2.0 local json = require("json") name = "BGPTools" type = "misc" local bgptoolsWhoisAddress = "" -- bgptoolsWhoisURL is the URL for the BGP.Tools whois server. local bgptoolsWhoisURL = "bgp.tools" -- bgptoolsTableFile is the path to the file containing ASN prefixes. local bgptoolsTableFile = "" function start() set_rate_limit(1) end function asn(ctx, addr, asn) if (bgptoolsWhoisAddress == "" and not get_whois_addr(ctx)) then return end -- Check if the table file containing ASN prefixes needs to be acquired if (bgptoolsTableFile == "" and need_table_file(ctx) and not get_table_file(ctx)) then return end local result if (asn == 0) then if (addr == "") then return end result = origin(ctx, addr) if (result == nil) then return end local cidrs = netblocks(ctx, result.asn) if (cidrs == nil or #cidrs == 0) then return end result['netblocks'] = cidrs else local cidrs = netblocks(ctx, asn) if (cidrs == nil or #cidrs == 0) then return end if (addr == "") then local parts = split(cidrs[1], "/") if (#parts < 2) then return end addr = parts[1] end result = origin(ctx, addr) if (result == nil) then return end result['netblocks'] = cidrs end table.insert(result['netblocks'], result['prefix']) new_asn(ctx, result) end function origin(ctx, addr) local conn, err = socket.connect(ctx, bgptoolsWhoisAddress, 43, "tcp") if (err ~= nil and err ~= "") then log(ctx, "failed to connect to the whois server: " .. err) return nil end _, err = conn:send("begin\n" .. addr .. "\nend") if (err ~= nil and err ~= "") then log(ctx, "failed to send the whois server request: " .. err) conn:close() return nil end local data data, err = conn:recv_all() conn:close() if (err ~= nil and err ~= "") then log(ctx, "failed to read the whois server response: " .. err) return nil end local fields = split(data, "|") return { ['addr']=addr, ['asn']=tonumber(trim_space(fields[1])), ['prefix']=trim_space(fields[3]), ['cc']=trim_space(fields[4]), ['registry']=trim_space(fields[5]), ['desc']=trim_space(fields[7]), } end function netblocks(ctx, asn) local prefixes = io.open(bgptoolsTableFile, "r") local netblocks = {} for line in prefixes:lines() do local j = json.decode(line) if (j ~= nil and j['ASN'] ~= nil and j['ASN'] == asn) then table.insert(netblocks, j['CIDR']) end end prefixes:close() return netblocks end function need_table_file(ctx) bgptoolsTableFile = output_dir(ctx) .. "/bgptools.jsonl" local modified = mtime(bgptoolsTableFile) if (modified == 0) then return true end hoursfrom = os.difftime(os.time(), modified) / (60 * 60) wholehours = math.floor(hoursfrom) if (wholehours > 5) then return true end return false end function get_table_file(ctx) local resp, err = request(ctx, {['url']="https://bgp.tools/table.jsonl"}) if (err ~= nil and err ~= "") then log(ctx, "failed to obtain the table.jsonl file: " .. err) return false end local prefixes = io.open(bgptoolsTableFile, "w") if (prefixes == nil) then log(ctx, "failed to write the table.jsonl file") return false end prefixes:write(resp) prefixes:close() return true end function split(str, delim) local result = {} local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return result end for _, match in pairs(matches) do table.insert(result, match) end return result end function get_whois_addr(ctx) local resp, err = resolve(ctx, bgptoolsWhoisURL, "A", false) if ((err ~= nil and err ~= "") or #resp == 0) then log(ctx, "failed to resolve the whois server address: " .. err) return false end bgptoolsWhoisAddress = resp[1].rrdata return true end function trim_space(s) if (s == nil) then return "" end return s:match( "^%s*(.-)%s*$" ) end
with Ada.Exception_Identification.From_Here; with System.Zero_Terminated_Strings; with C.dlfcn; package body System.Program.Dynamic_Linking is use Ada.Exception_Identification.From_Here; use type C.signed_int; use type C.size_t; procedure Open (Handle : out C.void_ptr; Name : String); procedure Open (Handle : out C.void_ptr; Name : String) is C_Name : C.char_array ( 0 .. Name'Length * Zero_Terminated_Strings.Expanding); begin Zero_Terminated_Strings.To_C (Name, C_Name (0)'Access); Handle := C.dlfcn.dlopen (C_Name (0)'Access, 0); if Address (Handle) = Null_Address then Raise_Exception (Name_Error'Identity); end if; end Open; procedure Close (Handle : C.void_ptr; Raise_On_Error : Boolean); procedure Close (Handle : C.void_ptr; Raise_On_Error : Boolean) is R : C.signed_int; begin if Address (Handle) /= Null_Address then R := C.dlfcn.dlclose (Handle); if R < 0 and then Raise_On_Error then Raise_Exception (Use_Error'Identity); end if; end if; end Close; -- implementation function Is_Open (Lib : Library) return Boolean is Handle : C.void_ptr renames Controlled.Reference (Lib).all; begin return Address (Handle) /= Null_Address; end Is_Open; procedure Open (Lib : in out Library; Name : String) is pragma Check (Pre, Check => not Is_Open (Lib) or else raise Status_Error); Handle : C.void_ptr renames Controlled.Reference (Lib).all; begin Open (Handle, Name); end Open; function Open (Name : String) return Library is begin return Result : Library do declare Handle : C.void_ptr renames Controlled.Reference (Result).all; begin Open (Handle, Name); end; end return; end Open; procedure Close (Lib : in out Library) is pragma Check (Pre, Check => Is_Open (Lib) or else raise Status_Error); Handle : C.void_ptr renames Controlled.Reference (Lib).all; Freeing_Handle : constant C.void_ptr := Handle; begin Handle := C.void_ptr (Null_Address); Close (Freeing_Handle, Raise_On_Error => True); end Close; function Import ( Lib : Library; Symbol : String) return Address is pragma Check (Dynamic_Predicate, Check => Is_Open (Lib) or else raise Status_Error); Handle : C.void_ptr renames Controlled.Reference (Lib).all; C_Symbol : C.char_array ( 0 .. Symbol'Length * Zero_Terminated_Strings.Expanding); Result : C.void_ptr; begin Zero_Terminated_Strings.To_C (Symbol, C_Symbol (0)'Access); Result := C.dlfcn.dlsym (Handle, C_Symbol (0)'Access); if Address (Result) = Null_Address then Raise_Exception (Data_Error'Identity); else return Address (Result); end if; end Import; package body Controlled is function Reference (Lib : Dynamic_Linking.Library) return not null access C.void_ptr is begin return Library (Lib).Handle'Unrestricted_Access; end Reference; overriding procedure Finalize (Object : in out Library) is begin Close (Object.Handle, Raise_On_Error => False); end Finalize; end Controlled; end System.Program.Dynamic_Linking;
-- This package provides support for creating and printing graphs in the -- DOT language, described at www.graphviz.org. From the website: -- -- The following is an abstract grammar defining the DOT language. Literal -- characters and keywords are given in single quotes. Parentheses ( and ) -- indicate grouping when needed. Square brackets [ and ] enclose optional items. -- Vertical bars | separate alternatives. -- -- graph : ['strict'] ('graph'|'digraph') [ID] '{' stmt_list '}' -- stmt_list : [stmt [';'] stmt_list] -- stmt : node_stmt -- | edge_stmt -- | attr_stmt -- | ID '=' ID -- | subgraph -- attr_stmt : ('graph'|'node'|'edge') attr_list -- attr_list : '[' [ a_list] ']' [attr_list] -- a_list : ID '=' ID [(';'|',')] [a_list] -- edge_stmt : (node_id | subgraph) edgeRHS [attr_list] -- edgeRHS : edgeop (node_id | subgraph) [edgeRHS] -- node_stmt : node_id [attr_list] -- node_id : ID [port] -- port : ':' ID [':'compass_pt] -- | ':' compass_pt -- subgraph : ['subgraph' [ID]] '{' stmt_list '}' -- compass_pt : ('n'|'ne'|'e'|'se'|'s'|'sw'|'w'|'nw'|'c'|'_') -- -- The keywords node, edge, graph, digraph, subgraph, and strict are -- case-independent. Note also that the allowed compass point values are not -- keywords, so these strings can be used elsewhere as ordinary identifiers and, -- conversely, the parser will actually accept any identifier. -- -- An ID is one of the following: -- - Any string of alphabetic ([a-zA-Z\200-\377]) characters, underscores ('_') -- or digits ([0-9]), not beginning with a digit -- - a numeral [-]?(.[0-9]+ | [0-9]+(.[0-9]*)? ) -- - any double-quoted string ("...") possibly containing escaped quotes ("\"") -- - an HTML string (<...>) -- -- An ID is just a string; the lack of quote characters in the first two forms -- is just for simplicity. There is no semantic difference between abc_2 and -- "abc_2", or between 2.34 and "2.34". To use a keyword as an ID, it must be -- quoted. with Ada.Containers.Doubly_Linked_Lists; with Ada.Strings.Unbounded; with Ada.Text_IO; package Dot is -- For convenience: package ATI renames Ada.Text_IO; -- Using the exact spellings from the grammar for the record components -- instead of spelling things out: type Compass_Pt_Type is (N, NE, E, SE, S, SW, W, NW, C, Underscore); type ID_Type is new Ada.Strings.Unbounded.Unbounded_String; function To_ID_Type (Item : in String) return ID_Type renames To_Unbounded_String; -- function To_ID_Type (Item : in Wide_String) return ID_Type; ----------------------------------------------------------------------------- package Stmt is type Class is abstract tagged null record; type Access_All_Class is access all Class'Class; procedure Put (This : in Class; File : in ATI.File_Type) is abstract; package Lists is new Ada.Containers.Doubly_Linked_Lists (Access_All_Class); -- Make primitive operations like "=" visible: type List_Of_Access_All_Class is new Lists.List with null record; procedure Put (These : in List_Of_Access_All_Class; File : in ATI.File_Type); end Stmt; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Zero or more assigns: package Assign is type Class is tagged -- Initialized record L : ID_Type; -- Initialized R : ID_Type; -- Initialized end record; procedure Put (This : in Class; File : in ATI.File_Type); package Lists is new Ada.Containers.Doubly_Linked_Lists (Class); -- Make primitive operations like "=" visible: type List_Of_Class is new Lists.List with null record; -- Initialized procedure Put (These : in List_Of_Class; File : in ATI.File_Type); -- Convenience: converts L, R to ID_Type and appends a Class to the list. -- Allows this: -- Assign_List.Append ("Today", "Thursday"); -- Instead of this: -- Assign_List.Append ((L => Dot.To_ID_Type ("Today"), -- R => Dot.To_ID_Type ("Thursday"))); not overriding procedure Append (These : in out List_Of_Class; L, R : in String); function Empty_List return List_Of_Class; end Assign; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Zero or more bracketed lists of assigns: package Attr is type Class is tagged -- Initialized record A_List : Assign.List_Of_Class; -- Initialized end record; Null_Class : constant Class; procedure Put (This : in Class; File : in ATI.File_Type); package Lists is new Ada.Containers.Doubly_Linked_Lists (Class); -- Make primitive operations like "=" visible: type List_Of_Class is new Lists.List with null record; procedure Put (These : in List_Of_Class; File : in ATI.File_Type); -- Add an assign to the first attr of the list. If there is no first attr, -- add one: procedure Add_Assign_To_First_Attr (Attr_List : in out List_Of_Class; Name : in String; Value : in String); Empty_List : constant List_Of_Class := List_Of_Class'(Lists.Empty_List with null record); private Default_Class : Class; Null_Class : constant Class := Default_Class; end Attr; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Attr_Stmt is type Kind_Type is (Graph, Node, Edge); type Class is new Stmt.Class with record -- Initialized Kind : Kind_Type := Node; Attr_List : Dot.Attr.List_Of_Class; -- Initialized end record; overriding procedure Put (This : in Class; File : in ATI.File_Type); -- Creates a Class object on the heap: procedure Append_To (This : in Class; Stmt_List : in out Stmt.List_Of_Access_All_Class); end Attr_Stmt; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Node_ID is type Port_Class is tagged record -- Initialized Has_ID : Boolean := False; ID : ID_Type; -- Initialized Has_Compass_Pt : Boolean := False; Compass_Pt : Compass_Pt_Type := C; end record; procedure Put (This : in Port_Class; File : in ATI.File_Type); Null_Port_Class : constant Port_Class; type Class is tagged record -- Initialized ID : ID_Type; -- Initialized Port : Port_Class; -- Initialized end record; procedure Put (This : in Class; File : in ATI.File_Type); private Default_Port_Class : Port_Class; Null_Port_Class : constant Port_Class := Default_Port_Class; end Node_ID; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package HTML_Like_Labels is -- GraphViz HTML-Like Labels support variously formatted nodes, especially -- tables. This package supports node formatting with "this = that" table -- rows. type Class is tagged private; -- Initialized procedure Add_Eq_Row (This : in out Class; L, R : in String); procedure Add_3_Col_Cell (This : in out Class; Text : in String); function To_String (This : in Class) return String; private use Ada.Strings.Unbounded; type LR_Pair is array (1 .. 2) Of Unbounded_String; function To_TR (This : in LR_Pair) return Unbounded_String; package LR_Pair_Lists is new Ada.Containers.Doubly_Linked_Lists (LR_Pair); -- Make primitive operations like "=" visible: type LR_Pair_List is new LR_Pair_Lists.List with null record; -- Initialized function To_Unbounded_String (This : in LR_Pair_List) return Unbounded_String; type Class is tagged record -- Initialized Rows : LR_Pair_List; -- Initialized end record; end HTML_Like_Labels; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Node_Stmt is type Class is new Stmt.Class with record -- Initialized Node_ID : Dot.Node_ID.Class; -- Initialized Attr_List : Dot.Attr.List_Of_Class; -- Initialized end record; overriding procedure Put (This : in Class; File : in ATI.File_Type); -- Creates a Class object on the heap: procedure Append_To (This : in Class; Stmt_List : in out Stmt.List_Of_Access_All_Class); procedure Add_Label (This : in out Class; HL_Label : in HTML_Like_Labels.Class); end Node_Stmt; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Subgraphs is type Class is tagged record -- Initialized Stmt_List : Stmt.List_Of_Access_All_Class; ID : ID_Type; end record; procedure Put (This : in Class; File : in ATI.File_Type); end Subgraphs; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Edges is package Terminals is type Kind_Type is (Node_Kind, Subgraph_Kind); type Class (Kind : Kind_Type := Node_Kind) is record -- Initialized case Kind is when Node_Kind => Node_Id : Dot.Node_ID.Class; -- Initialized when Subgraph_Kind => Subgraph : Subgraphs.Class; -- Initialized end case; end record; procedure Put (This : in Class; File : in ATI.File_Type); package Lists is new Ada.Containers.Doubly_Linked_Lists (Class); -- Make primitive operations like "=" visible: type List_Of_Class is new Lists.List with null record; procedure Put (These : in List_Of_Class; File : in ATI.File_Type); end Terminals; package Stmts is -- There must be at least one RHS: type Class is new Stmt.Class with record -- Initialized LHS : Terminals.Class; -- Initialized RHS : Terminals.Class; -- Initialized RHSs : Terminals.List_Of_Class; -- Initialized Attr_List : Dot.Attr.List_Of_Class; -- Initialized end record; overriding procedure Put (This : in Class; File : in ATI.File_Type); -- Creates a Class object on the heap: procedure Append_To (This : in Class; Stmt_List : in out Stmt.List_Of_Access_All_Class); end Stmts; end Edges; ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- package Graphs is type Class is tagged private; -- Initialized type Access_Class is access Class; function Create (Is_Digraph : in Boolean; Is_Strict : in Boolean) return Access_Class; procedure Set_Is_Digraph (This : access Class; To : in Boolean); procedure Set_Is_Strict (This : access Class; To : in Boolean); procedure Set_ID (This : access Class; To : in String); procedure Append_Stmt (This : access Class; The_Stmt : in Stmt.Access_All_Class); function Stmt_Count (This : access Class) return Natural; procedure Put (This : access Class; File : in ATI.File_Type); -- Writes a file <Name>.dot. If Overwrite is true, overwrites an existing -- file. If it is not and the file exists, raises Usage_Error: procedure Write_File (This : access Class; Name : in String; Overwrite : in Boolean := False); Usage_Error : Exception; private type Class is tagged -- Initialized record Digraph : Boolean := True; Strict : Boolean := True; ID : ID_Type; -- Initialized Stmt_List : Stmt.List_Of_Access_All_Class; -- Initialized end record; end Graphs; ----------------------------------------------------------------------------- private package ASU renames Ada.Strings.Unbounded; package Indented is procedure Indent; procedure Dedent; procedure Put (File : in ATI.File_Type; Item : in String); procedure New_Line (File : in ATI.File_Type); -- Calls New_Line if the current col is greater than the indent col: procedure End_Line_If_Needed (File : in ATI.File_Type); -- Put nothing if Item is empty, else Put it with a trailing space: procedure Put_Spaced (File : in ATI.File_Type; Item : in String); private -- If the indent is increased in the middle of a line, this will ensure -- that the next put is at that indent or better: procedure Put_Indent (File : in ATI.File_Type); end Indented; function To_String (Item : in Compass_Pt_Type) return String; -- Returns a quoted string (in case ID is a reserved word), or an empty -- string if the ID is empty: function To_String (Item : in ID_Type) return String; procedure Put (This : in ID_Type; File : in ATI.File_Type); end Dot;
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014, 2015, 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 Interfaces; package MAT.Types is subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_64; subtype Target_Size is Interfaces.Unsigned_64; subtype Target_Offset is Interfaces.Unsigned_64; type Target_Tick_Ref is new Uint64; type Target_Thread_Ref is new Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Target_Tick_Ref; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String; -- Format the target time to a printable representation. function Tick_Image (Value : in Target_Tick_Ref) return String; -- Convert the string in the form NN.MM into a tick value. function Tick_Value (Value : in String) return Target_Tick_Ref; -- Convert the hexadecimal string into an unsigned integer. function Hex_Value (Value : in String) return Uint64; end MAT.Types;
-- -- (c) Copyright 1993,1994,1995,1996 Silicon Graphics, Inc. -- ALL RIGHTS RESERVED -- Permission to use, copy, modify, and distribute this software for -- any purpose and without fee is hereby granted, provided that the above -- copyright notice appear in all copies and that both the copyright notice -- and this permission notice appear in supporting documentation, and that -- the name of Silicon Graphics, Inc. not be used in advertising -- or publicity pertaining to distribution of the software without specific, -- written prior permission. -- -- THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" -- AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, -- INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR -- FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON -- GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, -- SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY -- KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, -- LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF -- THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN -- ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON -- ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE -- POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. -- -- US Government Users Restricted Rights -- Use, duplication, or disclosure by the Government is subject to -- restrictions set forth in FAR 52.227.19(c)(2) or subparagraph -- (c)(1)(ii) of the Rights in Technical Data and Computer Software -- clause at DFARS 252.227-7013 and/or in similar or successor -- clauses in the FAR or the DOD or NASA FAR Supplement. -- Unpublished-- rights reserved under the copyright laws of the -- United States. Contractor/manufacturer is Silicon Graphics, -- Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. -- -- OpenGL(TM) is a trademark of Silicon Graphics, Inc. -- with GL; use GL; with Glut; use Glut; with Jitter; with Ada.Numerics; with Ada.Numerics.Generic_Elementary_Functions; package body Dof_Procs is package Num renames Ada.Numerics; package GLdouble_GEF is new Num.Generic_Elementary_Functions (GLdouble); use GLdouble_GEF; procedure accFrustum (left : GLdouble; right : GLdouble; bottom : GLdouble; top : GLdouble; near : GLdouble; far : GLdouble; pixdx : GLdouble; pixdy : GLdouble; eyedx : GLdouble; eyedy : GLdouble; focus : GLdouble) is xwsize, ywsize : GLdouble; dx, dy : GLdouble; viewport : array (0 .. 3) of aliased GLint; begin glGetIntegerv (GL_VIEWPORT, viewport (0)'Access); xwsize := right - left; ywsize := top - bottom; dx := -(pixdx * xwsize / GLdouble (viewport (2)) + eyedx * near / focus); dy := -(pixdy * ywsize / GLdouble (viewport (3)) + eyedy * near / focus); glMatrixMode (GL_PROJECTION); glLoadIdentity; glFrustum (left + dx, right + dx, bottom + dy, top + dy, near, far); glMatrixMode (GL_MODELVIEW); glLoadIdentity; glTranslated (-eyedx, -eyedy, 0.0); end accFrustum; procedure accPerspective (fovy : GLdouble; aspect : GLdouble; near : GLdouble; far : GLdouble; pixdx : GLdouble; pixdy : GLdouble; eyedx : GLdouble; eyedy : GLdouble; focus : GLdouble) is fov2, left, right, bottom, top : GLdouble; begin fov2 := ((fovy * Num.Pi) / 180.0) / 2.0; top := near / (Cos (fov2) / Sin (fov2)); bottom := -top; right := top * aspect; left := -right; accFrustum (left, right, bottom, top, near, far, pixdx, pixdy, eyedx, eyedy, focus); end accPerspective; procedure DoInit is ambient : array (0 .. 3) of aliased GLfloat := (0.0, 0.0, 0.0, 1.0); diffuse : array (0 .. 3) of aliased GLfloat := (1.0, 1.0, 1.0, 1.0); position : array (0 .. 3) of aliased GLfloat := (0.0, 3.0, 3.0, 0.0); lmodel_ambient : array (0 .. 3) of aliased GLfloat := (0.2, 0.2, 0.2, 1.0); local_view : aliased GLfloat := 0.0; begin glLightfv (GL_LIGHT0, GL_AMBIENT, ambient (0)'Access); glLightfv (GL_LIGHT0, GL_DIFFUSE, diffuse (0)'Access); glLightfv (GL_LIGHT0, GL_POSITION, position (0)'Access); glLightModelfv (GL_LIGHT_MODEL_AMBIENT, lmodel_ambient (0)'Access); glLightModelfv (GL_LIGHT_MODEL_LOCAL_VIEWER, local_view'Access); glFrontFace (GL_CW); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_AUTO_NORMAL); glEnable (GL_NORMALIZE); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LESS); glMatrixMode (GL_MODELVIEW); glLoadIdentity; glClearColor (0.0, 0.0, 0.0, 0.0); glClearAccum (0.0, 0.0, 0.0, 0.0); end DoInit; procedure renderTeapot (x : GLfloat; y : GLfloat; z : GLfloat; ambr : GLfloat; ambg : GLfloat; ambb : GLfloat; difr : GLfloat; difg : GLfloat; difb : GLfloat; specr : GLfloat; specg : GLfloat; specb : GLfloat; shine : GLfloat) is mat : array (0 .. 3) of aliased GLfloat; begin glPushMatrix; glTranslatef (x, y, z); mat (0) := ambr; mat (1) := ambg; mat (2) := ambb; mat (3) := 1.0; glMaterialfv (GL_FRONT, GL_AMBIENT, mat (0)'Access); mat (0) := difr; mat (1) := difg; mat (2) := difb; glMaterialfv (GL_FRONT, GL_DIFFUSE, mat (0)'Access); mat (0) := specr; mat (1) := specg; mat (2) := specb; glMaterialfv (GL_FRONT, GL_SPECULAR, mat (0)'Access); glMaterialf (GL_FRONT, GL_SHININESS, shine * 128.0); glutSolidTeapot (0.5); glPopMatrix; end renderTeapot; procedure DoDisplay is viewport : array (0 .. 3) of aliased GLint; begin glGetIntegerv (GL_VIEWPORT, viewport (0)'Access); glClear (GL_ACCUM_BUFFER_BIT); for jitval in 1 .. 8 loop glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); accPerspective (45.0, GLdouble (viewport (2)) / GLdouble (viewport (3)), 1.0, 15.0, 0.0, 0.0, GLdouble (0.33 * Jitter.j8 (jitval).x), GLdouble (0.33 * Jitter.j8 (jitval).y), 5.0); renderTeapot (-1.1, -0.5, -4.5, 0.1745, 0.01175, 0.01175, 0.61424, 0.04136, 0.04136, 0.727811, 0.626959, 0.626959, 0.6); renderTeapot (-0.5, -0.5, -5.0, 0.24725, 0.1995, 0.0745, 0.75164, 0.60648, 0.22648, 0.628281, 0.555802, 0.366065, 0.4); renderTeapot (0.2, -0.5, -5.5, 0.19225, 0.19225, 0.19225, 0.50754, 0.50754, 0.50754, 0.508273, 0.508273, 0.508273, 0.4); renderTeapot (1.0, -0.5, -6.0, 0.0215, 0.1745, 0.0215, 0.07568, 0.61424, 0.07568, 0.633, 0.727811, 0.633, 0.6); renderTeapot (1.8, -0.5, -6.5, 0.0, 0.1, 0.06, 0.0, 0.50980392, 0.50980392, 0.50196078, 0.50196078, 0.50196078, 0.25); glAccum (GL_ACCUM, 0.125); end loop; glAccum (GL_RETURN, 1.0); glFlush; end DoDisplay; procedure ReshapeCallback (w : Integer; h : Integer) is begin glViewport (0, 0, GLsizei(w), GLsizei(h)); end ReshapeCallback; end Dof_Procs;
with Ada.Text_IO, Ada.Integer_Text_IO; use Ada.Text_IO, Ada.Integer_Text_IO; procedure Multiply is Number_Of_Cases, A, B : Integer; begin Put("Integer range: "); Put(Integer'First); Put(" .. "); Put(Integer'Last); New_Line; Put_Line("How many cases? "); Flush; Get(Number_Of_Cases); for I in 1 .. Number_Of_Cases loop Put_Line("Enter two numbers."); Flush; Get(A); Get(B); Put("The product is "); Put(A*B); Put_Line("."); end loop; end Multiply;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Wide_Wide_Text_IO; with League.IRIs; with Matreshka.XML_Catalogs.Normalization; package body Matreshka.XML_Catalogs.Handlers is use Matreshka.XML_Catalogs.Entry_Files; use type League.Strings.Universal_String; XML_Catalogs_Namespace : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("urn:oasis:names:tc:entity:xmlns:xml:catalog"); XML_Catalogs_1_0_Public_Id : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN"); XML_Catalogs_1_1_Public_Id : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("-//OASIS//DTD XML Catalogs V1.1//EN"); -- Tags names Catalog_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("catalog"); Delegate_Public_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("delegatePublic"); Delegate_System_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("delegateSystem"); Delegate_URI_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("delegateURI"); Group_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("group"); Next_Catalog_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("nextCatalog"); Public_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("public"); Rewrite_System_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("rewriteSystem"); Rewrite_URI_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("rewriteURI"); System_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("system"); System_Suffix_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("systemSuffix"); URI_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uri"); URI_Suffix_Tag_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uriSuffix"); -- Attributes names Catalog_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("catalog"); Name_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("name"); Prefer_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("prefer"); Public_Id_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("publicId"); Public_Id_Start_String_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("publicIdStartString"); Rewrite_Prefix_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("rewritePrefix"); System_Id_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("systemId"); System_Id_Start_String_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("systemIdStartString"); System_Id_Suffix_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("systemIdSuffix"); URI_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uri"); URI_Start_String_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uriStartString"); URI_Suffix_Attribute_Name : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("uriSuffix"); -- Attribute values images System_Image : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("system"); Public_Image : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("public"); procedure Error (Self : in out XML_Catalog_Handler'Class; Message : League.Strings.Universal_String; Success : out Boolean); -- Sets Success to False and save Message as last error message. procedure Error (Self : in out XML_Catalog_Handler'Class; Message : Wide_Wide_String; Success : out Boolean); -- Sets Success to False and save Message as last error message. procedure Check_No_Fragment_Identifier (Self : in out XML_Catalog_Handler'Class; URI : League.Strings.Universal_String; Success : in out Boolean); -- Check that URI is not include fragment identifier. procedure Process_Catalog_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "catalog" element. procedure Process_Group_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "group" element. procedure Process_Group_End_Element (Self : in out XML_Catalog_Handler'Class; Success : in out Boolean); -- Processes end of "group" element. procedure Process_Public_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "public" element. procedure Process_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "system" element. procedure Process_Rewrite_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "rewriteSystem" element. procedure Process_System_Suffix_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "systemSuffix" element. procedure Process_Delegate_Public_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "delegatePublic" element. procedure Process_Delegate_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "delegateSystem" element. procedure Process_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "uri" element. procedure Process_Rewrite_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "rewriteURI" element. procedure Process_URI_Suffix_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "uriSuffix" element. procedure Process_Delegate_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "delegateURI" element. procedure Process_Next_Catalog_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean); -- Processes start of "nextCatalog" element. ---------------------------------- -- Check_No_Fragment_Identifier -- ---------------------------------- procedure Check_No_Fragment_Identifier (Self : in out XML_Catalog_Handler'Class; URI : League.Strings.Universal_String; Success : in out Boolean) is begin if URI.Index ('#') /= 0 then Error (Self, "URI reference should not include a fragment identifier", Success); end if; end Check_No_Fragment_Identifier; ----------------- -- End_Element -- ----------------- overriding procedure End_Element (Self : in out XML_Catalog_Handler; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Success : in out Boolean) is begin if Namespace_URI = XML_Catalogs_Namespace and Local_Name = Group_Tag_Name then Process_Group_End_Element (Self, Success); end if; end End_Element; ----------- -- Error -- ----------- procedure Error (Self : in out XML_Catalog_Handler'Class; Message : Wide_Wide_String; Success : out Boolean) is begin Self.Diagnosis := League.Strings.To_Universal_String (Message); Success := False; end Error; ----------- -- Error -- ----------- procedure Error (Self : in out XML_Catalog_Handler'Class; Message : League.Strings.Universal_String; Success : out Boolean) is begin Self.Diagnosis := Message; Success := False; end Error; ----------- -- Error -- ----------- overriding procedure Error (Self : in out XML_Catalog_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception; Success : in out Boolean) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(error) " & Occurrence.Message.To_Wide_Wide_String); end Error; ------------------ -- Error_String -- ------------------ overriding function Error_String (Self : XML_Catalog_Handler) return League.Strings.Universal_String is begin return Self.Diagnosis; end Error_String; ----------------- -- Fatal_Error -- ----------------- overriding procedure Fatal_Error (Self : in out XML_Catalog_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(fatal) " & Occurrence.Message.To_Wide_Wide_String); end Fatal_Error; ---------------------------- -- Get_Catalog_Entry_File -- ---------------------------- function Get_Catalog_Entry_File (Self : XML_Catalog_Handler) return Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File_Access is begin return Self.Entry_File; end Get_Catalog_Entry_File; ----------------------------------- -- Process_Catalog_Start_Element -- ----------------------------------- procedure Process_Catalog_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.1. The catalog Entry -- -- "Each XML Catalog entry file consists of a single catalog element. -- This element may set the global prefer value and global base URI. It -- is otherwise just a container for the other elements. -- -- <catalog -- id = id -- prefer = "system" | "public" -- xml:base = uri-reference > -- <!-- Content: (group | public | system | rewriteSystem -- | systemSuffix | delegatePublic | delegateSystem | uri -- | rewriteURI | uriSuffix | delegateURI | nextCatalog)+ --> -- </catalog>" Prefer_Index : constant Natural := Attributes.Index (Prefer_Attribute_Name); begin -- Analyze 'prefer' attribute when present. if Prefer_Index /= 0 then if Attributes.Value (Prefer_Index) = Public_Image then Self.Current_Prefer_Mode := Public; elsif Attributes.Value (Prefer_Index) = System_Image then Self.Current_Prefer_Mode := System; else Self.Error ("Invalid value of 'prefer' attribute", Success); end if; end if; -- Create new catalog entry file object. Self.Entry_File := new Matreshka.XML_Catalogs.Entry_Files.Catalog_Entry_File; Self.Entry_File.Default_Prefer_Mode := Self.Default_Prefer_Mode; end Process_Catalog_Start_Element; ------------------------------------------- -- Process_Delegate_Public_Start_Element -- ------------------------------------------- procedure Process_Delegate_Public_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.7. The delegatePublic Element -- -- "The delegatePublic element associates an alternate catalog with a -- partial public identifier. -- -- <delegatePublic -- id = id -- publicIdStartString = public-identifier-prefix -- catalog = uri-reference -- xml:base = uri-reference /> -- -- A delegatePublic entry matches a public identifier if the normalized -- value (Section 6.2, “Public Identifier Normalization”) of the public -- identifier begins precisely with the normalized value of the -- publicIdStartString attribute of the entry." -- -- "If the value of the catalog attribute is relative, it must be made -- absolute with respect to the base URI currently in effect." Public_Id : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_Public_Identifier (Attributes.Value (Public_Id_Start_String_Attribute_Name)); Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute_Name))).To_Universal_String; begin -- Check that 'publicIdStartString' is not empty. if Public_Id.Is_Empty then Error (Self, "publicIdStartString is empty", Success); return; end if; Self.Entry_File.Append (new Delegate_Public_Entry' (Public_Id, Catalog, Self.Current_Prefer_Mode)); end Process_Delegate_Public_Start_Element; ------------------------------------------- -- Process_Delegate_System_Start_Element -- ------------------------------------------- procedure Process_Delegate_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.8. The delegateSystem Element -- -- "The delegateSystem element associates an alternate catalog with a -- partial system identifier. -- -- <delegateSystem -- id = id -- systemIdStartString = string -- catalog = uri-reference -- xml:base = uri-reference /> -- -- A delegateSystem entry matches a system identifier if the normalized -- value (Section 6.3, “System Identifier and URI Normalization”) of the -- system identifier begins precisely with the normalized value of the -- systemIdStartString attribute of the entry." -- -- "If the value of the catalog attribute is relative, it must be made -- absolute with respect to the base URI currently in effect." System_Id : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_System_Identifier (Attributes.Value (System_Id_Start_String_Attribute_Name)); Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute_Name))).To_Universal_String; begin -- Check that 'systemIdStartString' is not empty. if System_Id.Is_Empty then Error (Self, "systemIdStartString is empty", Success); return; end if; Self.Entry_File.Append (new Delegate_System_Entry'(System_Id, Catalog)); end Process_Delegate_System_Start_Element; ---------------------------------------- -- Process_Delegate_URI_Start_Element -- ---------------------------------------- procedure Process_Delegate_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.12. The delegateURI Element -- -- "The delegateURI element associates an alternate catalog with a -- partial URI reference. -- -- <delegateURI -- id = id -- uriStartString = string -- catalog = uri-reference -- xml:base = uri-reference /> -- -- A delegateURI entry matches a URI reference if the normalized value -- (Section 6.3, “System Identifier and URI Normalization”) of the URI -- reference begins precisely with the normalized value of the -- uriStartString attribute of the entry. -- -- If the value of the catalog attribute is relative, it must be made -- absolute with respect to the base URI currently in effect." URI : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_URI (Attributes.Value (URI_Start_String_Attribute_Name)); Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute_Name))).To_Universal_String; begin -- Check that 'uriStartString' is not empty. if URI.Is_Empty then Error (Self, "uriStartString is empty", Success); return; end if; Self.Entry_File.Append (new Delegate_URI_Entry'(URI, Catalog)); end Process_Delegate_URI_Start_Element; ------------------------------- -- Process_Group_End_Element -- ------------------------------- procedure Process_Group_End_Element (Self : in out XML_Catalog_Handler'Class; Success : in out Boolean) is begin -- Restore preference mode on leave of "group" element. Self.Current_Prefer_Mode := Self.Previous_Prefer_Mode; end Process_Group_End_Element; --------------------------------- -- Process_Group_Start_Element -- --------------------------------- procedure Process_Group_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.2. The group Entry -- -- "The group element is a convenience wrapper for specifying a prefer -- setting or base URI for a set of catalog entries. It has no -- semantics other than scoping these settings. -- -- <group -- id = id -- prefer = "system" | "public" -- xml:base = uri-reference > -- <!-- Content: (public | system | rewriteSystem | systemSuffix | -- delegatePublic | delegateSystem | uri | rewriteURI | uriSuffix | -- delegateURI | nextCatalog)+ --> -- </group>" Prefer_Index : constant Natural := Attributes.Index (Prefer_Attribute_Name); begin -- Save current preference mode, analyze 'prefer' attribute when -- present, otherwise preserve current mode. Self.Previous_Prefer_Mode := Self.Current_Prefer_Mode; if Prefer_Index /= 0 then if Attributes.Value (Prefer_Index) = Public_Image then Self.Current_Prefer_Mode := Public; elsif Attributes.Value (Prefer_Index) = System_Image then Self.Current_Prefer_Mode := System; else Self.Error ("Invalid value of 'prefer' attribute", Success); end if; end if; end Process_Group_Start_Element; ---------------------------------------- -- Process_Next_Catalog_Start_Element -- ---------------------------------------- procedure Process_Next_Catalog_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.13. The nextCatalog Element -- -- "The nextCatalog elements indicate additional catalog entry file(s) -- to be considered during the process of resolution. -- -- <nextCatalog -- id = id -- catalog = uri-reference -- xml:base = uri-reference /> -- -- If the value of the catalog attribute is relative, it must be made -- absolute with respect to the base URI currently in effect. -- -- Catalogs loaded due to a nextCatalog directive have an initial base -- URI that is dependent on the location of the loaded catalog entry -- file. No xml:base information is inherited from the originating -- catalog. Catalog : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Catalog_Attribute_Name))).To_Universal_String; begin Self.Entry_File.Append (new Next_Catalog_Entry'(Catalog, Self.Default_Prefer_Mode, null)); end Process_Next_Catalog_Start_Element; ---------------------------------- -- Process_Public_Start_Element -- ---------------------------------- procedure Process_Public_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.3. The public Entry -- -- "The public element associates a URI reference with the public -- identifier portion of an external identifier. -- -- <public -- id = id -- publicId = public-identifier -- uri = uri-reference -- xml:base = uri-reference /> -- -- A public entry matches a public identifier if the normalized value -- (Section 6.2, “Public Identifier Normalization”) of the public -- identifier is lexically identical to the normalized value of the -- publicId attribute of the entry. -- -- If the value of the uri attribute is relative, it must be made -- absolute with respect to the base URI currently in effect. The URI -- reference should not include a fragment identifier." Public_Id : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_Public_Identifier (Attributes.Value (Public_Id_Attribute_Name)); URI : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (URI_Attribute_Name))).To_Universal_String; begin -- Check that 'publicId' is not empty. if Public_Id.Is_Empty then Error (Self, "publicId is empty", Success); return; end if; -- Check that URI is not include a fragment identifier. Check_No_Fragment_Identifier (Self, URI, Success); if not Success then return; end if; Self.Entry_File.Append (new Public_Entry'(Public_Id, URI, Self.Current_Prefer_Mode)); end Process_Public_Start_Element; ------------------------------------------ -- Process_Rewrite_System_Start_Element -- ------------------------------------------ procedure Process_Rewrite_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.5. The rewriteSystem Element -- -- The rewriteSystem element rewrites the beginning of a system -- identifier. -- -- <rewriteSystem -- id = id -- systemIdStartString = string -- rewritePrefix = uri-reference /> -- -- A rewriteSystem entry matches a system identifier if the normalized -- value (Section 6.3, “System Identifier and URI Normalization”) of the -- system identifier begins precisely with the normalized value of the -- systemIdStartString attribute of the entry. -- -- If the value of the rewritePrefix attribute is relative, it must be -- made absolute with respect to the base URI currently in effect. System_Id_Start_String : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_System_Identifier (Attributes.Value (System_Id_Start_String_Attribute_Name)); Rewrite_Prefix : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Rewrite_Prefix_Attribute_Name))).To_Universal_String; begin -- Check that 'systemIdStartString' is not empty. if System_Id_Start_String.Is_Empty then Error (Self, "'systemIdStartString' is empty", Success); return; end if; Self.Entry_File.Append (new Rewrite_System_Entry'(System_Id_Start_String, Rewrite_Prefix)); end Process_Rewrite_System_Start_Element; --------------------------------------- -- Process_Rewrite_URI_Start_Element -- --------------------------------------- procedure Process_Rewrite_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.10. The rewriteURI Element -- -- The rewriteURI element rewrites the beginning of a URI reference that -- is not part of an external identifier. -- -- <rewriteURI -- id = id -- uriStartString = string -- rewritePrefix = uri-reference /> -- -- A rewriteURI entry matches a URI reference if the normalized value -- (Section 6.3, “System Identifier and URI Normalization”) of the URI -- reference begins precisely with the normalized value of the -- uriStartString attribute of the entry. -- -- If the value of the rewritePrefix attribute is relative, it must be -- made absolute with respect to the base URI currently in effect. URI_Start_String : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_URI (Attributes.Value (URI_Start_String_Attribute_Name)); Rewrite_Prefix : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (Rewrite_Prefix_Attribute_Name))).To_Universal_String; begin -- Check that 'uriStartString' is not empty. if URI_Start_String.Is_Empty then Error (Self, "'uriStartString' is empty", Success); return; end if; Self.Entry_File.Append (new Rewrite_URI_Entry'(URI_Start_String, Rewrite_Prefix)); end Process_Rewrite_URI_Start_Element; ---------------------------------- -- Process_System_Start_Element -- ---------------------------------- procedure Process_System_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.4. The system Element -- -- "The system element associates a URI reference with the system -- identifier portion of an external identifier. -- -- <system -- id = id -- systemId = string -- uri = uri-reference -- xml:base = uri-reference /> -- -- A system entry matches a system identifier if the normalized value -- (Section 6.3, “System Identifier and URI Normalization”) of the -- system identifier is lexically identical to the normalized value of -- the systemId attribute of the entry. -- -- If the value of the uri attribute is relative, it must be made -- absolute with respect to the base URI currently in effect. The URI -- reference should not include a fragment identifier." System_Id : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_System_Identifier (Attributes.Value (System_Id_Attribute_Name)); URI : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (URI_Attribute_Name))).To_Universal_String; begin -- Check that 'systemId' is not empty. if System_Id.Is_Empty then Error (Self, "systemId is empty", Success); return; end if; -- Check that URI is not include a fragment identifier. Check_No_Fragment_Identifier (Self, URI, Success); if not Success then return; end if; Self.Entry_File.Append (new System_Entry'(System_Id, URI)); end Process_System_Start_Element; ----------------------------------------- -- Process_System_Suffix_Start_Element -- ----------------------------------------- procedure Process_System_Suffix_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.6. The systemSuffix Element -- -- "The systemSuffix element associates a URI reference with the suffix -- portion of a system identifier. -- -- <systemSuffix -- id = id -- systemIdSuffix = string -- uri = uri-reference -- xml:base = uri-reference /> -- -- A systemSuffix entry matches a system identifier if the normalized -- value (Section 6.3, “System Identifier and URI Normalization”) of the -- system identifier ends precisely with the normalized value of the -- systemIdSuffix attribute of the entry. -- -- If the value of the uri attribute is relative, it must be made -- absolute with respect to the base URI currently in effect. The URI -- reference should not include a fragment identifier." System_Id_Suffix : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_System_Identifier (Attributes.Value (System_Id_Suffix_Attribute_Name)); URI : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (URI_Attribute_Name))).To_Universal_String; begin -- Check that 'systemIdSuffix' is not empty. if System_Id_Suffix.Is_Empty then Error (Self, "systemIdSuffix is empty", Success); return; end if; -- Check that URI is not include a fragment identifier. Check_No_Fragment_Identifier (Self, URI, Success); if not Success then return; end if; Self.Entry_File.Append (new System_Suffix_Entry'(System_Id_Suffix, URI)); end Process_System_Suffix_Start_Element; ------------------------------- -- Process_URI_Start_Element -- ------------------------------- procedure Process_URI_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.9. The uri Element -- -- The uri element associates an alternate URI reference with a URI -- reference that is not part of an external identifier. -- -- <uri -- id = id -- name = string -- uri = uri-reference -- xml:base = uri-reference /> -- -- A uri entry matches a URI reference if the normalized value (Section -- 6.3, “System Identifier and URI Normalization”) of the URI reference -- is lexically identical to the normalized value of the name attribute -- of the entry." -- -- "If the value of the uri attribute is relative, it must be made -- absolute with respect to the base URI currently in effect." Name : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_URI (Attributes.Value (Name_Attribute_Name)); URI : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (URI_Attribute_Name))).To_Universal_String; begin -- Check that 'name' is not empty. if Name.Is_Empty then Error (Self, "name is empty", Success); return; end if; Self.Entry_File.Append (new URI_Entry'(Name, URI)); end Process_URI_Start_Element; -------------------------------------- -- Process_URI_Suffix_Start_Element -- -------------------------------------- procedure Process_URI_Suffix_Start_Element (Self : in out XML_Catalog_Handler'Class; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is -- [XML Catalogs] 6.5.11. The uriSuffix Element -- -- "The uriSuffix element associates a URI reference with the suffix -- portion of a URI reference that is not part of an external -- identifier. -- -- <uriSuffix -- id = id -- uriSuffix = string -- uri = uri-reference -- xml:base = uri-reference /> -- -- A uriSuffix entry matches a URI if the normalized value (Section 6.3, -- “System Identifier and URI Normalization”) of the URI ends precisely -- with the normalized value of the uriSuffix attribute of the entry. -- -- If the value of the uri attribute is relative, it must be made -- absolute with respect to the base URI currently in effect. URI_Suffix : constant League.Strings.Universal_String := Matreshka.XML_Catalogs.Normalization.Normalize_URI (Attributes.Value (URI_Suffix_Attribute_Name)); URI : constant League.Strings.Universal_String := Self.Locator.Base_URI.Resolve (League.IRIs.From_Universal_String (Attributes.Value (URI_Attribute_Name))).To_Universal_String; begin -- Check that 'uriSuffix' is not empty. if URI_Suffix.Is_Empty then Error (Self, "uriSuffix is empty", Success); return; end if; Self.Entry_File.Append (new URI_Suffix_Entry'(URI_Suffix, URI)); end Process_URI_Suffix_Start_Element; ----------------------------- -- Set_Default_Prefer_Mode -- ----------------------------- procedure Set_Default_Prefer_Mode (Self : in out XML_Catalog_Handler'Class; Mode : Matreshka.XML_Catalogs.Entry_Files.Prefer_Mode) is begin Self.Default_Prefer_Mode := Mode; end Set_Default_Prefer_Mode; -------------------------- -- Set_Document_Locator -- -------------------------- overriding procedure Set_Document_Locator (Self : in out XML_Catalog_Handler; Locator : XML.SAX.Locators.SAX_Locator) is begin Self.Locator := Locator; end Set_Document_Locator; -------------------- -- Start_Document -- -------------------- overriding procedure Start_Document (Self : in out XML_Catalog_Handler; Success : in out Boolean) is begin Self.Diagnosis := League.Strings.Empty_Universal_String; Self.Current_Prefer_Mode := Self.Default_Prefer_Mode; end Start_Document; --------------- -- Start_DTD -- --------------- overriding procedure Start_DTD (Self : in out XML_Catalog_Handler; Name : League.Strings.Universal_String; Public_Id : League.Strings.Universal_String; System_Id : League.Strings.Universal_String; Success : in out Boolean) is begin -- Check whether processed document is XML Catalogs entry file. if Public_Id /= XML_Catalogs_1_0_Public_Id and Public_Id /= XML_Catalogs_1_1_Public_Id then Self.Error ("Unknown XML Catalogs DTD", Success); end if; end Start_DTD; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out XML_Catalog_Handler; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is begin if Namespace_URI /= XML_Catalogs_Namespace then -- Ignore all non-XML Catalogs elements. return; end if; if Local_Name = Catalog_Tag_Name then Process_Catalog_Start_Element (Self, Attributes, Success); elsif Local_Name = Delegate_Public_Tag_Name then Process_Delegate_Public_Start_Element (Self, Attributes, Success); elsif Local_Name = Delegate_System_Tag_Name then Process_Delegate_System_Start_Element (Self, Attributes, Success); elsif Local_Name = Delegate_URI_Tag_Name then Process_Delegate_URI_Start_Element (Self, Attributes, Success); elsif Local_Name = Group_Tag_Name then Process_Group_Start_Element (Self, Attributes, Success); elsif Local_Name = Next_Catalog_Tag_Name then Process_Next_Catalog_Start_Element (Self, Attributes, Success); elsif Local_Name = Public_Tag_Name then Process_Public_Start_Element (Self, Attributes, Success); elsif Local_Name = Rewrite_System_Tag_Name then Process_Rewrite_System_Start_Element (Self, Attributes, Success); elsif Local_Name = Rewrite_URI_Tag_Name then Process_Rewrite_URI_Start_Element (Self, Attributes, Success); elsif Local_Name = System_Tag_Name then Process_System_Start_Element (Self, Attributes, Success); elsif Local_Name = System_Suffix_Tag_Name then Process_System_Suffix_Start_Element (Self, Attributes, Success); elsif Local_Name = URI_Tag_Name then Process_URI_Start_Element (Self, Attributes, Success); elsif Local_Name = URI_Suffix_Tag_Name then Process_URI_Suffix_Start_Element (Self, Attributes, Success); end if; end Start_Element; ------------- -- Warning -- ------------- overriding procedure Warning (Self : in out XML_Catalog_Handler; Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception; Success : in out Boolean) is begin Ada.Wide_Wide_Text_IO.Put_Line (Ada.Wide_Wide_Text_IO.Standard_Error, "(warning) " & Occurrence.Message.To_Wide_Wide_String); end Warning; end Matreshka.XML_Catalogs.Handlers;
package body agar.gui.widget.radio is use type c.int; package cbinds is function allocate (parent : widget_access_t; flags : flags_t; items : agar.core.types.void_ptr_t) return radio_access_t; pragma import (c, allocate, "AG_RadioNew"); function add_item (radio : radio_access_t; text : cs.chars_ptr) return c.int; pragma import (c, add_item, "AG_RadioAddItemS"); function add_item_hotkey (radio : radio_access_t; key : c.int; text : cs.chars_ptr) return c.int; pragma import (c, add_item_hotkey, "AG_RadioAddItemHKS"); end cbinds; function allocate (parent : widget_access_t; flags : flags_t) return radio_access_t is begin return cbinds.allocate (parent => parent, flags => flags, items => agar.core.types.null_ptr); end allocate; function add_item (radio : radio_access_t; text : string) return boolean is c_txt : aliased c.char_array := c.to_c (text); begin return cbinds.add_item (radio => radio, text => cs.to_chars_ptr (c_txt'unchecked_access)) = 0; end add_item; function add_item_hotkey (radio : radio_access_t; key : c.int; text : string) return boolean is c_txt : aliased c.char_array := c.to_c (text); begin return cbinds.add_item_hotkey (radio => radio, key => key, text => cs.to_chars_ptr (c_txt'unchecked_access)) = 0; end add_item_hotkey; function widget (radio : radio_access_t) return widget_access_t is begin return radio.widget'access; end widget; end agar.gui.widget.radio;
------------------------------------------------------------------------------ -- Copyright (C) 2020 by Heisenbug Ltd. (gh+spat@heisenbug.eu) -- -- This work is free. You can redistribute it and/or modify it under the -- terms of the Do What The Fuck You Want To Public License, Version 2, -- as published by Sam Hocevar. See the LICENSE file for more details. ------------------------------------------------------------------------------ pragma License (Unrestricted); ------------------------------------------------------------------------------ -- -- SPARK Proof Analysis Tool -- -- S.P.A.T. - Collection of checks that should succeed before creating -- objects from the JSON data. -- ------------------------------------------------------------------------------ package SPAT.Preconditions is type Accepted_Value_Types is array (JSON_Value_Type) of Boolean with Pack => True; Number_Kind : constant Accepted_Value_Types; --------------------------------------------------------------------------- -- Ensure_Field -- -- Check that the given JSON object contains an object named Field with -- type of Kind. -- If the field is not found or the type is different from the expected -- one, a warning is issued, unless Is_Optional is True. -- Returns True if so, False otherwise. --------------------------------------------------------------------------- function Ensure_Field (Object : in JSON_Value; Field : in UTF8_String; Kind : in JSON_Value_Type; Is_Optional : in Boolean := False) return Boolean; --------------------------------------------------------------------------- -- Ensure_Field -- -- Check that the given JSON object contains an object named Field with -- on of the types in Kind. -- Returns True if so, False otherwise. --------------------------------------------------------------------------- function Ensure_Field (Object : in JSON_Value; Field : in UTF8_String; Kinds_Allowed : in Accepted_Value_Types) return Boolean; --------------------------------------------------------------------------- -- Ensure_Rule_Severity -- -- Checks that the given JSON object contains a rule and a severity object. -- Returns True if so, False otherwise. --------------------------------------------------------------------------- function Ensure_Rule_Severity (Object : in JSON_Value) return Boolean; private -- Make JSON type enumeration literals directly visible. use all type JSON_Value_Type; Number_Kind : constant Accepted_Value_Types := Accepted_Value_Types'(JSON_Int_Type | JSON_Float_Type => True, others => False); end SPAT.Preconditions;
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal; procedure Triangle is Number_Of_Rows: Positive := Integer'Value(Ada.Command_Line.Argument(1)); Row: Pascal.Row := First_Row(Number_Of_Rows); begin loop -- print one row for J in 1 .. Length(Row) loop Ada.Integer_Text_IO.Put(Row(J), 5); end loop; Ada.Text_IO.New_Line; exit when Length(Row) >= Number_Of_Rows; Row := Next_Row(Row); end loop; end Triangle;
with Ada.Calendar; with Ada.Text_IO; with System.Address_To_Access_Conversions; with Lumen.Window; with Lumen.Image; with Lumen.Events.Animate; with GL; with Noise; procedure Test_Noise is package Float_IO is new Ada.Text_IO.Float_IO (Float); Program_End : exception; Win : Lumen.Window.Handle; Image : Lumen.Image.Descriptor; Tx_Name : aliased GL.GLuint; Wide : Natural := 320; High : Natural := 240; First_Frame : Ada.Calendar.Time; Frame_Count : Natural := 0; -- Create a texture and bind a 2D image to it procedure Create_Texture is use GL; package GLB is new System.Address_To_Access_Conversions (GLubyte); IP : GLpointer; begin -- Create_Texture -- Allocate a texture name glGenTextures (1, Tx_Name'Unchecked_Access); -- Bind texture operations to the newly-created texture name glBindTexture (GL_TEXTURE_2D, Tx_Name); -- Select modulate to mix texture with color for shading glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -- Wrap textures at both edges glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -- How the texture behaves when minified and magnified glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -- Create a pointer to the image. This sort of horror show is going to -- be disappearing once Lumen includes its own OpenGL bindings. IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access; -- Build our texture from the image we loaded earlier glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, IP); end Create_Texture; -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; begin -- Set_View GL.glEnable (GL.GL_TEXTURE_2D); glClearColor (0.8, 0.8, 0.8, 1.0); glMatrixMode (GL_PROJECTION); glLoadIdentity; glViewport (0, 0, GLsizei (W), GLsizei (H)); glOrtho (0.0, GLdouble (W), GLdouble (H), 0.0, -1.0, 1.0); glMatrixMode (GL_MODELVIEW); glLoadIdentity; end Set_View; -- Draw our scene procedure Draw is use GL; begin -- Draw -- clear the screen glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name); -- fill with a single textured quad glBegin (GL_QUADS); begin glTexCoord2f (1.0, 0.0); glVertex2i (GLint (Wide), 0); glTexCoord2f (0.0, 0.0); glVertex2i (0, 0); glTexCoord2f (0.0, 1.0); glVertex2i (0, GLint (High)); glTexCoord2f (1.0, 1.0); glVertex2i (GLint (Wide), GLint (High)); end; glEnd; -- flush rendering pipeline glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_End; end Quit_Handler; -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is pragma Unreferenced (Event); begin -- Expose_Handler Draw; end Expose_Handler; -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; procedure Next_Frame (Frame_Delta : in Duration) is pragma Unreferenced (Frame_Delta); use type Ada.Calendar.Time; begin Frame_Count := Frame_Count + 1; if Ada.Calendar.Clock >= First_Frame + 1.0 then Ada.Text_IO.Put ("FPS: "); Float_IO.Put (Float (Frame_Count), 5, 1, 0); Ada.Text_IO.New_Line; First_Frame := Ada.Calendar.Clock; Frame_Count := 0; end if; Image := Noise.Create_Image (Width => Wide, Height => High); Create_Texture; Draw; end Next_Frame; begin -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Lumen.Window.Create (Win => Win, Name => "Noise fractal", Width => Wide, Height => High, Events => (Lumen.Window.Want_Exposure => True, Lumen.Window.Want_Key_Press => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Now create the texture and set up to use it Image := Noise.Create_Image (Width => Wide, Height => High); Create_Texture; First_Frame := Ada.Calendar.Clock; -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Animate.Flat_Out, Frame => Next_Frame'Unrestricted_Access); end; exception when Program_End => null; end Test_Noise;
with Controller_Quit; use Controller_Quit; with Controller_Internet; use Controller_Internet; with Controller_Bugz; use Controller_Bugz; with Controller_Choices; use Controller_Choices; with Controller_Help; use Controller_Help; with Controller_MainWindow; use Controller_MainWindow; with Controller_DataMenu; use Controller_DataMenu; with Controller_Error; use Controller_Error; with Controller_Dummy; use Controller_Dummy; with AcronymList; use AcronymList; with Ada.Exceptions; with Reporter; with Text_IO; with RASCAL.MessageTrans; use RASCAL.MessageTrans; with RASCAL.Error; use RASCAL.Error; with RASCAL.FileInternal; use RASCAL.FileInternal; with RASCAL.Heap; use RASCAL.Heap; with RASCAL.FileExternal; use RASCAL.FileExternal; with RASCAL.Toolbox; use RASCAL.Toolbox; with RASCAL.ToolboxProgInfo; package body Main is -- package MessageTrans renames RASCAL.MessageTrans; package Error renames RASCAL.Error; package FileInternal renames RASCAL.FileInternal; package Heap renames RASCAL.Heap; package FileExternal renames RASCAL.FileExternal; package Toolbox renames RASCAL.Toolbox; package ToolboxProgInfo renames RASCAL.ToolboxProgInfo; package WimpTask renames RASCAL.WimpTask; package Utility renames RASCAL.Utility; package Variable renames RASCAL.Variable; package OS renames RASCAL.OS; -- procedure Report_Error (Token : in String; Info : in String) is E : Error_Pointer := Get_Error (Main_Task); M : Error_Message_Pointer := new Error_Message_Type; Result : Error_Return_Type := XButton1; begin if Get_Status (Main_task) then M.all.Token(1..Token'Length) := Token; M.all.Param1(1..Info'Length) := Info; M.all.Category := Warning; M.all.Flags := Error_Flag_OK; Result := Error.Show_Message (E,M); else Text_IO.Put_Line(MessageTrans.Lookup(Token,E.all.Msg_Handle,Info)); end if; end Report_Error; -- procedure Discard_Acronyms is Start : AcronymList.Position; i : AcronymList.Position; Meaning : Meaning_Pointer; begin if not IsEmpty(Acronym_List.all) then i := First (Acronym_List.all); loop -- For each file loop.. Meaning := Retrieve (Acronym_List.all,i); Heap.Free(Meaning.all.Buffer.all); Delete (Acronym_List.all, i); i := First (Acronym_List.all); if IsEmpty(Acronym_List.all) then exit; end if; end loop; end if; exception when e: others => Report_Error("DISCARDING",Ada.Exceptions.Exception_Information (e)); end Discard_Acronyms; -- procedure Read_Acronyms is Path : String := "Choices:Meaning.Data"; Dir_List : Directory_Type := Get_Directory_List(Path); begin for i in Dir_List'Range loop declare FileName : String := S(Dir_List(i)); FilePath : String := Path & "." & FileName; FileSize : constant natural := Get_Size(FilePath); FileBuffer : Heap_Block_Pointer := new Heap.Heap_block_Type(FileSize); Offset : natural := 0; begin Load_File(FilePath,Heap.Get_Address(FileBuffer.all)); AddToRear(Acronym_List.all,new Meaning_Type'(U(FileName),FileBuffer,FileSize)); end; end loop; exception when e: others => Report_Error("READING",Ada.Exceptions.Exception_Information (e)); end Read_Acronyms; -- procedure Main is ProgInfo_Window : Object_ID; Misc : Messages_Handle_Type; begin -- Messages Add_Listener (Main_Task,new MEL_Message_Bugz_Query); Add_Listener (Main_Task,new MEL_Message_Quit); -- React upon quit from taskmanager -- Toolbox Events Add_Listener (Main_Task,new TEL_Quit_Quit); Add_Listener (Main_Task,new TEL_ViewManual_Type); Add_Listener (Main_Task,new TEL_ViewSection_Type); Add_Listener (Main_Task,new TEL_ViewIHelp_Type); Add_Listener (Main_Task,new TEL_ViewHomePage_Type); Add_Listener (Main_Task,new TEL_SendEmail_Type); Add_Listener (Main_Task,new TEL_CreateReport_Type); Add_Listener (Main_Task,new TEL_OKButtonPressed_Type); Add_Listener (Main_Task,new TEL_EscapeButtonPressed_Type); Add_Listener (Main_Task,new TEL_ViewDataDir_Type); Add_Listener (Main_Task,new TEL_RenewSelected_Type); Add_Listener (Main_Task,new TEL_DataMenuOpen_Type); Add_Listener (Main_Task,new TEL_DataEntrySelected_Type); Add_Listener (Main_Task,new TEL_Toolbox_Error); Add_Listener (Main_Task,new TEL_OpenWindow_Type); Add_Listener (Main_Task,new TEL_Dummy); -- Start task WimpTask.Set_Resources_Path(Main_Task,"<MeaningRes$Dir>"); WimpTask.Initialise(Main_Task); if FileExternal.Exists("Choices:Meaning.Misc") then Misc := MessageTrans.Open_File("Choices:Meaning.Misc"); begin Read_Integer ("XPOS",x_pos,Misc); Read_Integer ("YPOS",y_pos,Misc); exception when others => null; end; end if; ProgInfo_Window := Toolbox.Create_Object("ProgInfo",From_Template); ToolboxProgInfo.Set_Version(ProgInfo_Window,MessageTrans.Lookup("VERS",Get_Message_Block(Main_Task))); Not_Found_Message := U(MessageTrans.Lookup("NOTFOUND",Get_Message_Block(Main_Task))); Untitled_String := U(MessageTrans.Lookup("UNTITLED",Get_Message_Block(Main_Task))); if Length(Untitled_String) = 0 then Untitled_String := U("Untitled"); end if; -- Choices directory if FileExternal.Exists(Choices_Write) /=true then Create_Directory(Choices_Write); end if; if FileExternal.Exists(Choices_Write & ".Data") /=true then FileExternal.Copy("<Meaning$Dir>.Resources.Data",Choices_Write & ".Data"); end if; Read_Acronyms; main_objectid := Toolbox.Create_Object ("Main"); -- Start polling WimpTask.Poll(Main_Task); exception when e: others => Text_IO.Put_Line (Ada.Exceptions.Exception_Information (e)); end Main; -- end Main;
package collada.Library.controllers -- -- Models a collada 'controllers' library, which is a collection of controllers. -- is type Inputs_view is access all Library.Inputs; type int_Array_view is access all int_Array; ---------- --- Joints -- type Joints is record Inputs : Inputs_view; end record; ------------------ --- vertex_Weights -- type vertex_Weights is record Count : Natural; Inputs : Inputs_view; v_Count : int_Array_view; v : int_Array_view; end record; function joint_Offset_of (Self : in vertex_Weights) return math.Index; function weight_Offset_of (Self : in vertex_Weights) return math.Index; -------- --- Skin -- type Skin is record main_Source : Text; bind_shape_Matrix : float_Array (1 .. 16); Sources : access library.Sources; Joints : controllers.Joints; vertex_weights : controllers.vertex_Weights; end record; function Weights_of (Self : in Skin) return access float_Array; function bind_shape_Matrix_of (Self : in Skin) return Matrix_4x4; function bind_Poses_of (Self : in Skin) return Matrix_4x4_array; function joint_Names_of (Self : in Skin) return Text_array; -------------- --- Controller -- type Controller is record Name : Text; Id : Text; Skin : controllers.Skin; end record; type Controller_array is array (Positive range <>) of Controller; ---------------- --- Library Item -- type Item is record Contents : access Controller_array; end record; end collada.Library.controllers;
with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings; use Ada.Strings; with Ada.Strings.Hash; package Rejuvenation.Match_Patterns is type Match_Pattern is tagged private; -- The class Match_Pattern represents a single occurrence of an AST pattern -- in an AST instance. An AST pattern or AST instance is a list of physical -- AST nodes from Libadalang. -- -- AST patterns are expressed as code snippets that can contain -- placeholders that can be mapped to AST nodes from the AST instance. -- If a placeholder occurs multiple times, then the string values of the -- mapped AST nodes must be identical. -- -- To show diagnosis information about non-matches on the console, use: -- Rejuvenation.Match_Pattern.DIAGNOSE := True; -- Externally-visible data structures ------- Inconsistent_Placeholder_Values_Exception : exception; -- Exception that indicates that a placeholder is assigned -- two different values. Unsupported_Placeholder_Exception : exception; -- Exception that indicates that an unsupported placeholder was observed. Invalid_Multiple_Placeholder_Status_Exception : exception; -- Internal programming error; this should not happen. DIAGNOSE : Boolean := False; -- Flag that indicates whether diagnosis information about non-matches is -- displayed on the console. -- Create match -------- -- TODO: should order of parameters be in line with similar functions -- in Finder interface? function Match_Full (MP : out Match_Pattern; Pattern : Ada_Node; Instance : Ada_Node) return Boolean; -- Return whether the single-node AST pattern fully matches -- the single-node AST instance. -- If succesful, then the match attributes can afterwards be inspected. function Match_Full (MP : out Match_Pattern; Pattern : Ada_Node_Array; Instance : Ada_Node_Array) return Boolean; -- Return whether the node-array AST pattern fully matches -- the node-array AST instance. -- If succesful, then the match attributes can afterwards be inspected. function Match_Prefix (MP : out Match_Pattern; Pattern : Ada_Node_Array; Instance : Ada_Node_Array; Instance_Start_Index : Integer) return Boolean with Pre => Instance_Start_Index in Instance'Range; -- Return whether the node-array AST pattern matches -- a prefix of the node-array AST instance. -- If succesful, then the match attributes can afterwards be inspected. function Are_Identical (Node1 : Ada_Node'Class; Node2 : Ada_Node'Class) return Boolean; -- Return whether the ASTs of the two nodes match. -- Raises an exception if a placeholder pattern occurs. -- Inspect match -------- function Get_Nodes (MP : Match_Pattern) return Node_List.Vector; -- Return the AST instance nodes that match with the AST pattern. -- TODO: Should we add an Is_Valid_Placeholder_Name function? function Has_Single (MP : Match_Pattern; Placeholder_Name : String) return Boolean; -- Return whether the "single" placeholder name is mapped -- to any AST node from the AST instance. function Get_Single_As_Node (MP : Match_Pattern; Placeholder_Name : String) return Ada_Node with Pre => Has_Single (MP, Placeholder_Name); -- Return the mapped AST node from the AST instance -- for the given "single" placeholder name. function Get_Single_As_Raw_Signature (MP : Match_Pattern; Placeholder_Name : String) return String with Pre => Has_Single (MP, Placeholder_Name); -- Return the mapped raw signature from the AST instance -- for the given "single" placeholder name. function Has_Multiple (MP : Match_Pattern; Placeholder_Name : String) return Boolean; -- Return whether the "multiple" placeholder name is mapped -- to any AST node from the AST instance. function Get_Multiple_As_Nodes (MP : Match_Pattern; Placeholder_Name : String) return Node_List.Vector with Pre => Has_Multiple (MP, Placeholder_Name); -- Return the mapped AST nodes from the AST instance -- for the given "multiple" placeholder name. function Get_Multiple_As_Raw_Signature (MP : Match_Pattern; Placeholder_Name : String) return String with Pre => Has_Multiple (MP, Placeholder_Name); -- Return the mapped raw signature from the AST instance -- for the given "multiple" placeholder name. -- Note this includes the separators and trivia (white spaces and comments) -- between the multiple nodes. function Get_Placeholder_As_Nodes (MP : Match_Pattern; Placeholder_Name : String) return Node_List.Vector; -- Return the mapped AST nodes from the AST instance -- for the given placeholder name (both single and multiple). function Get_Placeholder_As_Raw_Signature (MP : Match_Pattern; Placeholder_Name : String) return String; -- Return the mapped raw signature from the AST instance -- for the given placeholder name (both single and multiple). private -- Create match -------- function Has_Nested_Match_Full (MP : Match_Pattern; Pattern : Ada_Node; Instance : Ada_Node) return Boolean; function Match (MP : in out Match_Pattern; Pattern : Ada_Node'Class; Instance : Ada_Node'Class) return Boolean; function Match (MP : in out Match_Pattern; Pattern : Ada_Node_Array; Instance : Ada_Node_Array; Instance_Start_Index : Integer; Pattern_Must_Cover_End_Of_Instance : Boolean; Store_Nodes : Boolean) return Boolean with Pre => Instance'Last < Instance'First or else Instance_Start_Index in Instance'Range; function Match_Multiple_Placeholder (MP : in out Match_Pattern; Pattern : Ada_Node'Class; Instance : Ada_Node'Class) return Boolean; function Match_Single_Placeholder (MP : in out Match_Pattern; Pattern : Ada_Node'Class; Instance : Ada_Node'Class) return Boolean; function Match_Specific (MP : in out Match_Pattern; Pattern : Ada_Node'Class; Instance : Ada_Node'Class) return Boolean; procedure Dump_Partial_Match (MP : Match_Pattern); -- Internal data structures ------- function Equivalent_Key (Left, Right : String) return Boolean; function Equivalent_Element (Left, Right : Ada_Node) return Boolean; function Equivalent_Element (Left, Right : Node_List.Vector) return Boolean; package Mapping_Single_Map is new Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Ada_Node, Hash => Ada.Strings.Hash, Equivalent_Keys => Equivalent_Key, "=" => Equivalent_Element); package Mapping_Multiple_Map is new Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Node_List.Vector, Hash => Ada.Strings.Hash, Equivalent_Keys => Equivalent_Key, "=" => Equivalent_Element); type Match_Pattern is tagged record Nodes : Node_List.Vector; -- The AST instance nodes that match with the AST pattern. Mapping_Single : Mapping_Single_Map.Map; -- Mapping from "single" placeholder name to AST node. Mapping_Multiple : Mapping_Multiple_Map.Map; -- Mapping from "multiple" placeholder name to AST nodes. end record; type Multiple_Placeholder_Status is record Ongoing_Multiple : Boolean := False; Multiple_PlaceHolder_Name : Ada_Node := No_Ada_Node; -- TODO: Why called name and not node? Multiple_Placeholder_Nodes : Node_List.Vector; Has_Earlier_Multiple_Placeholder_Nodes : Boolean := False; Earlier_Multiple_Placeholder_Nodes : Node_List.Vector; end record; function Is_Open (MPS : Multiple_Placeholder_Status) return Boolean; procedure Open (MPS : in out Multiple_Placeholder_Status; MP : Match_Pattern; Placeholder_Node : Ada_Node); procedure Close (MPS : in out Multiple_Placeholder_Status; MP : in out Match_Pattern); procedure Update (MPS : in out Multiple_Placeholder_Status; Instance_Node : Ada_Node); end Rejuvenation.Match_Patterns;
-- Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited -- -- Most of the documentation has been copied from opus.h and opus_defines.h -- and is licensed under the license of those files; the Simplified BSD License. -- -- Copyright (c) 2014 onox <denkpadje@gmail.com> -- -- 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 Interfaces.C; package Opus is -- The Opus codec is designed for interactive speech and audio -- transmission over the Internet. It is designed by the IETF Codec -- Working Group and incorporates technology from Skype's SILK codec -- and Xiph.Org's CELT codec. -- -- The Opus codec is designed to handle a wide range of interactive -- audio applications, including Voice over IP, videoconferencing, -- in-game chat, and even remote live music performances. It can scale -- from low bit-rate narrowband speech to very high quality stereo -- music. Its main features are: -- -- * Sampling rates from 8 to 48 kHz -- * Bit-rates from 6 kb/s to 510 kb/s -- * Support for both constant bit-rate (CBR) and variable bit-rate (VBR) -- * Audio bandwidth from narrowband to full-band -- * Support for speech and music -- * Support for mono and stereo -- * Support for multichannel (up to 255 channels) -- * Frame sizes from 2.5 ms to 60 ms -- * Good loss robustness and packet loss concealment (PLC) -- * Floating point and fixed-point implementation type Channel_Type is (Mono, Stereo); type Application_Type is (VoIP, Audio, Restricted_Low_Delay) with Convention => C; -- 1. VOIP gives best quality at a given bitrate for voice signals. It -- enhances the input signal by high-pass filtering and forward error -- correction to protect against packet loss. Use this mode for typical -- VoIP applications. Because of the enhancement, even at high bitrates -- the output may sound different from the input. -- -- 2. Audio gives best quality at a given bitrate for most non-voice -- signals like music. Use this mode for music and mixed (music/voice) -- content, broadcast, and applications requiring less than 15 ms of -- coding delay. -- -- 3. Restricted_Low_Delay configures low-delay mode that disables the -- speech-optimized mode in exchange for slightly reduced delay. This -- mode can only be set on an newly initialized or freshly reset encoder -- because it changes the codec delay. This is useful when the caller knows -- that the speech-optimized modes will not be needed (use with caution). type Sampling_Rate is (Rate_8_kHz, Rate_12_kHz, Rate_16_kHz, Rate_24_kHz, Rate_48_kHz) with Convention => C; type Bandwidth is (Auto, Narrow_Band, Medium_Band, Wide_Band, Super_Wide_Band, Full_Band) with Convention => C; type Opus_Int16 is new Interfaces.C.short; subtype PCM_Range is Natural range 0 .. 5760; -- 8 kHz with 2.5 ms/frame mono = 20 samples/frame -- 48 kHz with 60 ms/frame stereo = 5760 samples/frame use type Interfaces.C.int; type PCM_Buffer is array (PCM_Range range <>) of Opus_Int16 with Convention => C; type Byte_Array is array (Natural range <>) of Interfaces.C.unsigned_char with Convention => C; function Get_Version return String; Bad_Argument : exception; Buffer_Too_Small : exception; Internal_Error : exception; Invalid_Packet : exception; Unimplemented : exception; Invalid_State : exception; Allocation_Fail : exception; Invalid_Result : exception; private type C_Boolean is new Boolean with Convention => C; for Channel_Type use (Mono => 1, Stereo => 2); for Application_Type use (VoIP => 2048, Audio => 2049, Restricted_Low_Delay => 2051); for Sampling_Rate use (Rate_8_kHz => 8000, Rate_12_kHz => 12000, Rate_16_kHz => 16000, Rate_24_kHz => 24000, Rate_48_kHz => 48000); for Bandwidth use (Auto => -1000, Narrow_Band => 1101, Medium_Band => 1102, Wide_Band => 1103, Super_Wide_Band => 1104, Full_Band => 1105); procedure Check_Error (Error : in Interfaces.C.int); end Opus;
-- C64201C.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 INITIALIZATION OF IN PARAMETERS OF A COMPOSITE -- TYPE HAVING AT LEAST ONE COMPONENT (INCLUDING COMPONENTS -- OF COMPONENTS) OF A TASK TYPE IS PERMITTED. -- (SEE ALSO 7.4.4/T2 FOR TESTS OF LIMITED PRIVATE TYPES.) -- CVP 5/14/81 -- ABW 7/1/82 -- BHS 7/9/84 WITH REPORT; USE REPORT; PROCEDURE C64201C IS GLOBAL : INTEGER := 10; TASK TYPE T IS ENTRY E (X : IN OUT INTEGER); END; TYPE REC_T IS RECORD TT : T; BB : BOOLEAN := TRUE; END RECORD; TYPE REC_REC_T IS RECORD RR : REC_T; END RECORD; TYPE ARR_T IS ARRAY (1 .. 2) OF T; TYPE ARR_REC_T IS ARRAY (1 .. 2) OF REC_T; RT1, RT2 : REC_T; RRT1, RRT2 : REC_REC_T; AT1, AT2 : ARR_T; ART1, ART2 : ARR_REC_T; TASK BODY T IS BEGIN ACCEPT E (X : IN OUT INTEGER) DO X := X - 1; END E; ACCEPT E (X : IN OUT INTEGER) DO X := X + 1; END E; END T; PROCEDURE PROC1A (P1X : REC_T := RT1) IS BEGIN IF P1X.BB THEN -- EXPECT RT2 PASSED. FAILED( "RECORD OF TASK NOT PASSED, DEFAULT EMPLOYED" ); END IF; END PROC1A; PROCEDURE PROC1B (P1X : REC_T := RT1) IS BEGIN IF NOT P1X.BB THEN -- EXPECT DEFAULT USED. FAILED( "DEFAULT RECORD OF TASK NOT EMPLOYED" ); END IF; END PROC1B; PROCEDURE PROC2A (P2X : REC_REC_T := RRT1) IS BEGIN IF P2X.RR.BB THEN -- EXPECT RRT2 PASSED. FAILED( "RECORD OF RECORD OF TASK NOT PASSED, " & "DEFAULT EMPLOYED" ); END IF; END PROC2A; PROCEDURE PROC2B (P2X : REC_REC_T := RRT1) IS BEGIN IF NOT P2X.RR.BB THEN -- EXPECT DEFAULT USED. FAILED( "DEFAULT RECORD OF RECORD OF TASK " & "NOT EMPLOYED" ); END IF; END PROC2B; PROCEDURE PROC3 (P3X : ARR_T := AT1) IS BEGIN P3X(1).E (X => GLOBAL); -- CALL TO AT2(1).E, -- GLOBAL => GLOBAL - 1. END PROC3; PROCEDURE PROC4 (P4X : ARR_T := AT1) IS BEGIN P4X(1).E (X => GLOBAL); -- CALL TO DEFAULT AT1(1).E, -- GLOBAL => GLOBAL - 1. IF GLOBAL /= IDENT_INT(8) THEN FAILED( "ARRAY OF TASKS NOT PASSED " & "CORRECTLY IN PROC3" ); END IF; END PROC4; PROCEDURE PROC5 (P5X : ARR_REC_T := ART1) IS BEGIN P5X(1).TT.E (X => GLOBAL); -- CALL TO ART2(1).TT.E, -- GLOBAL => GLOBAL - 1. END PROC5; PROCEDURE PROC6 (P6X : ARR_REC_T := ART1) IS BEGIN P6X(1).TT.E (X => GLOBAL); -- CALL DEFAULT ART1(1).TT.E, -- GLOBAL => GLOBAL - 1. IF GLOBAL /= IDENT_INT(8) THEN FAILED( "ARRAY OF RECORDS OF TASKS NOT " & "PASSED IN PROC5" ); END IF; END PROC6; PROCEDURE TERM (TSK : T; NUM : CHARACTER) IS BEGIN IF NOT TSK'TERMINATED THEN ABORT TSK; COMMENT ("ABORTING TASK " & NUM); END IF; END TERM; BEGIN TEST( "C64201C" , "CHECK THAT INITIALIZATION OF IN " & "PARAMETERS OF A COMPOSITE TYPE " & "IS PERMITTED" ); RT2.BB := FALSE; RRT2.RR.BB := FALSE; PROC1A(RT2); -- NO ENTRY CALL PROC1B; -- NO ENTRY CALL PROC2A(RRT2); -- NO ENTRY CALL PROC2B; -- NO ENTRY CALL PROC3(AT2); -- CALL AT2(1).E IF GLOBAL /= 9 THEN FAILED ("INCORRECT GLOBAL VALUE AFTER PROC3"); ELSE PROC4; -- CALL AT1(1).E END IF; GLOBAL := 10; PROC5(ART2); -- CALL ART2(1).TT.E IF GLOBAL /= 9 THEN FAILED ("INCORRECT GLOBAL VALUE AFTER PROC5"); ELSE PROC6; -- CALL ART1(1).TT.E END IF; -- MAKE SURE ALL TASKS TERMINATED TERM (RT1.TT, '1'); TERM (RT2.TT, '2'); TERM (RRT1.RR.TT, '3'); TERM (RRT2.RR.TT, '4'); TERM (AT1(1), '5'); TERM (AT2(1), '6'); TERM (AT1(2), '7'); TERM (AT2(2), '8'); TERM (ART1(1).TT, '9'); TERM (ART2(1).TT, 'A'); TERM (ART1(2).TT, 'B'); TERM (ART2(2).TT, 'C'); RESULT; END C64201C;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Abstract_Early_Test_Case; use Apsepp.Abstract_Early_Test_Case; package Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case is -- TODOC: This test case uses the same fixture as -- Apsepp_Test_Node_Class_Early_Test_Case.Apsepp_Test_Node_Class_E_T_C -- (simulation test cases run concurrently thanks to a special blocking test -- reporter using a "test node barrier") to benefit from the already coded -- traces. The test case could have been designed differently with a direct -- exercising of an instance of -- Apsepp.Test_Reporter_Class.Struct_Builder.Test_Reporter_Struct_Builder -- and in this case would have been a "normal" test case (not an "early" -- test case). <2019-09-08> type Apsepp_Test_Reporter_Class_Struct_Builder_E_T_C is limited new Early_Test_Case with null record; overriding function Early_Routine (Obj : Apsepp_Test_Reporter_Class_Struct_Builder_E_T_C) return Test_Routine; end Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case;
procedure Unit_1 is begin null; end;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Sf.System.Clock; use Sf.System.Clock; with Sf.System.Sleep; use Sf.System.Sleep; with Sf.System.Types; use Sf.System.Types; procedure Main is My_Clock : sfClock_Ptr; begin My_Clock := sfClock_Create; sfSleep (0.05); Put ("Time elapsed(s): "); Put (sfClock_GetTime (My_Clock), 0, 3, 0); New_Line; sfClock_Reset (My_Clock); sfClock_Destroy (My_Clock); end Main;
-- -- for the Mandelbrot part, see -- https://github.com/shintakezou/adaplayground/blob/master/src/mandel_utf.adb -- -- Usage example: -- ./mandelpng -2 -2 2 2 -- -- To build, gprbuild. It works on my machine! You need libpng lib and -- headers. -- -- Messy withs and uses; no idea if there's a better more idiomatic -- way. -- with Ada.Numerics.Elementary_Functions, Ada.Numerics.Generic_Complex_Types, Ada.Unchecked_Deallocation; use Ada.Numerics.Elementary_Functions; with Interfaces.C, Interfaces.C.Strings, Interfaces.C.Pointers; with PNGFunc_C; with stdint_h; use stdint_h; with Ada.Text_IO; use Ada.Text_IO; with Ada.Command_Line; procedure MandelPNG is package C renames Interfaces.C; package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Float); use Complex_Types; -- Configuration constants. Width : constant := 800; Height : constant := 600; Max_Iterations : constant := 32; -- Returns the intensity of a single point in the Mandelbrot set. function Render_Pixel (C : Complex) return Float is Z : Complex := Complex'(0.0, 0.0); begin for N in Integer range 0 .. Max_Iterations loop Z := Z*Z + C; if (abs Z > 2.0) then return Float (N) / Float (Max_Iterations); end if; end loop; return 0.0; end; type Bitmap is array(Integer range <>, Integer range <>) of Float; type Bitmap_Ref is access Bitmap; procedure Free_Bitmap is new Ada.Unchecked_Deallocation (Object => Bitmap, Name => Bitmap_Ref); procedure Mandelbrot (Data : Bitmap_Ref; R1, I1, R2, I2 : Float) is Width : Integer := Data'Length (1); Height : Integer := Data'Length (2); Xdelta : Float := (R2-R1) / Float (Width); Ydelta : Float := (I2-I1) / Float (Height); I : Float; C : Complex; begin Put_Line ("Width: " & Integer'Image (Width)); Put_Line ("Height: " & Integer'Image (Height)); Put_Line ("Xdelta: " & Float'Image (Xdelta)); Put_Line ("Ydelta: " & Float'Image (Ydelta)); for Y in Data'Range (2) loop I := I1 + Float (Y) * Ydelta; for X in Data'Range (1) loop C := Complex'(R1 + Float (X) * Xdelta, I); Data (X, Y) := Render_Pixel (C); end loop; end loop; end; procedure Dump_Bitmap(Data : Bitmap_Ref) is subtype Buffer_Index is Integer range 0 .. 3 * Width * Height - 1; type Buffer is array (Buffer_Index range <>) of aliased uint8_t with Component_Size => 8, Convention => C; type Buffer_Access is access all Buffer; type RGB is record Red, Green, Blue : uint8_t; end record; procedure To_RGB (V : in Float; D : out RGB) is RR, GG, BB : Float; begin RR := 255.0 * V; GG := 255.0 * V; BB := 255.0 * V; D.Red := uint8_t (RR); D.Green := uint8_t (GG); D.Blue := uint8_t (BB); end To_RGB; package Im is new C.Pointers (Index => Buffer_Index, Element => uint8_t, Element_Array => Buffer, Default_Terminator => uint8_t'First); R : C.int; Image : aliased Buffer (Buffer_Index'Range); The_Image : Im.Pointer := Image (0)'Access; Vals : RGB; begin for Y in Data'Range (2) loop for X in Data'Range (1) loop To_RGB (Data (X, Y), Vals); Image (3 * (Y * Width + X) + 0) := Vals.Red; Image (3 * (Y * Width + X) + 1) := Vals.Green; Image (3 * (Y * Width + X) + 2) := Vals.Blue; end loop; end loop; R := PNGFunc_C.create_image (C.Strings.New_String ("out.png"), Width, Height, The_Image); if Integer (R) < 0 then Put_Line (Standard_Error, "error writing image to file"); else Put_Line ("file written"); end if; end; Image : Bitmap_Ref; use Ada.Command_Line; begin if Argument_Count < 4 then Put_Line (Standard_Error, "Usage: " & Command_Name & " R1 I1 R2 I2"); else declare R1 : Float := Float'Value (Argument (1)); R2 : Float := Float'Value (Argument (3)); I1 : Float := Float'Value (Argument (2)); I2 : Float := Float'Value (Argument (4)); begin Image := new Bitmap (0 .. Width - 1, 0 .. Height - 1); Mandelbrot (Image, R1, I1, R2, I2); Dump_Bitmap (Image); Free_Bitmap (Image); end; end if; end;
-- 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 Tk.Widget; use Tk.Widget; with Tk.TtkWidget; use Tk.TtkWidget; -- ****h* Tk/TtkFrame -- FUNCTION -- Provides code for manipulate Tk widget ttk::frame -- SOURCE package Tk.TtkFrame is -- **** --## rule off REDUCEABLE_SCOPE -- ****t* TtkFrame/TtkFrame.Tk_Frame -- FUNCTION -- The Tk identifier of the ttk::frame -- HISTORY -- 8.6.0 - Added -- SOURCE subtype Ttk_Frame is Ttk_Widget; -- **** -- ****s* TtkFrame/TtkFrame.Ttk_Frame_Options -- FUNCTION -- Data structure for all available options for the Tk ttk::frame which can -- be changed after creation of a widget -- OPTIONS -- Border_Width - The width of the ttk::frame's border -- Height - Height of the ttk::frame. -- Padding - Amount of extra space to allocate for the ttk::frame. If some -- elemets are empty then, bottom defaults to top, right defaults -- to left, and top defaults to left. Order of the elements: -- left, top, right, bottom -- Relief - 3-D effect desired for the ttk::frame -- Width - Width of the ttk::frame -- HISTORY -- 8.6.0 - Added -- SOURCE type Ttk_Frame_Options is new Ttk_Widget_Options with record Border_Width: Pixel_Data; Height: Pixel_Data; Padding: Padding_Data; Relief: Relief_Type; Width: Pixel_Data; end record; -- **** -- ****f* TtkFrame/TtkFrame.Configure -- FUNCTION -- Set the selected options for the selected ttk::frame -- PARAMETERS -- Frame_Widget - Ttk_Frame which options will be set -- Options - The record with new values for the ttk::frame options -- HISTORY -- 8.6.0 - Added -- EXAMPLE -- -- Set background to black for ttk::frame My_Frame -- Configure(My_Frame, (Background => To_Tcl_String("black"), others => <>)); -- SEE ALSO -- TtkFrame.Get_Options -- COMMANDS -- Widget configure Options -- SOURCE procedure Configure (Frame_Widget: Ttk_Frame; Options: Ttk_Frame_Options) with Pre'Class => Frame_Widget /= Null_Widget, Test_Case => (Name => "Test_Configure_Frame", Mode => Nominal); -- **** -- ****f* TtkFrame/TtkFrame.Create_(function) -- FUNCTION -- Create a new Tk ttk::frame widget with the selected pathname and options -- PARAMETERS -- Path_Name - Tk pathname for the newly created ttk::frame -- Options - Options for the newly created ttk::frame -- Interpreter - Tcl interpreter on which the ttk::frame will be created. Can -- be empty. Default value is the default Tcl interpreter -- RESULT -- The Tk identifier of the newly created ttk::frame widget -- HISTORY -- 8.6.0 - Added -- EXAMPLE -- -- Create the ttk::frame with pathname .myframe and black background -- My_Frame: constant Ttk_Frame := Create(".myframe", (Background => To_Tcl_String("black"), -- others => <>)); -- SEE ALSO -- TtkFrame.Create_(procedure) -- COMMANDS -- ttk::frame Path_Name Options -- SOURCE function Create (Path_Name: Tk_Path_String; Options: Ttk_Frame_Options; Interpreter: Tcl_Interpreter := Get_Interpreter) return Ttk_Frame with Pre'Class => Path_Name'Length > 0 and Interpreter /= Null_Interpreter, Test_Case => (Name => "Test_Create_Frame1", Mode => Nominal); -- **** -- ****f* TtkFrame/TtkFrame.Create_(procedure) -- FUNCTION -- Create a new Tk ttk:frame widget with the selected pathname and options -- PARAMETERS -- Frame_Widget - Ttk_Frame identifier which will be returned -- Path_Name - Tk pathname for the newly created ttk::frame -- Options - Options for the newly created ttk::frame -- Interpreter - Tcl interpreter on which the ttk::frame will be created. Can -- be empty. Default value is the default Tcl interpreter -- OUTPUT -- The Widget parameter as Tk identifier of the newly created ttk::frame widget -- HISTORY -- 8.6.0 - Added -- EXAMPLE -- -- Create the ttk::frame with pathname .myframe -- declare -- My_Frame: Ttk_Frame; -- begin -- Create(My_Frame, ".myframe", Default_Ttk_Frame_Create_Options); -- end; -- SEE ALSO -- TtkFrame.Create_(function) -- COMMANDS -- ttk::frame Path_Name Options -- SOURCE procedure Create (Frame_Widget: out Ttk_Frame; Path_Name: Tk_Path_String; Options: Ttk_Frame_Options; Interpreter: Tcl_Interpreter := Get_Interpreter) with Pre'Class => Path_Name'Length > 0 and Interpreter /= Null_Interpreter, Test_Case => (Name => "Test_Create_Frame2", Mode => Nominal); -- **** -- ****f* TtkFrame/TtkFrame.Get_Options -- FUNCTION -- Get all values of Tk options of the selected ttk::frame -- PARAMETERS -- Frame_Widget - Ttk_Frame which options' values will be taken -- RESULT -- Ttk_Frame_Options record with values of the selected ttk::frame -- options -- HISTORY -- 8.6.0 - Added -- EXAMPLE -- -- Get all values of option of ttk::frame with pathname .myframe -- My_Frame_Options: constant Ttk_Frame_Options := Get_Options(Get_Widget(".myframe")); -- COMMANDS -- Widget configure -- SOURCE function Get_Options(Frame_Widget: Ttk_Frame) return Ttk_Frame_Options with Pre'Class => Frame_Widget /= Null_Widget, Test_Case => (Name => "Test_Get_Options_Frame", Mode => Nominal); -- **** -- ****d* TtkFrame/TtkFrame.Default_Ttk_Frame_Options -- FUNCTION -- Default options for ttk::frame widget -- HISTORY -- 8.6.0 - Added -- SOURCE Default_Ttk_Frame_Options: constant Ttk_Frame_Options := Ttk_Frame_Options'(others => <>); -- **** --## rule on REDUCEABLE_SCOPE end Tk.TtkFrame;
-- Example_Adafunctions -- A example of using the Ada 2012 interface to Lua for functions / closures etc -- Copyright (c) 2015, James Humphry - see LICENSE for terms with Ada.Text_IO; use Ada.Text_IO; package body Example_AdaFunctions is function FooBar (L : Lua_State'Class) return Natural is x : constant Long_Float := L.ToNumber(-1); begin Put_Line("* In Ada function foobar(" & Long_Float'Image(x) & ")"); L.Pop(1); L.PushNumber(x*x); return 1; end FooBar; function Multret (L : Lua_State'Class) return Natural is X : constant Long_Long_Integer := L.ToInteger(-1); begin Put_Line("* In Ada function multret(" & Long_Long_Integer'Image(X) & ")"); L.Pop(1); for I in reverse Long_Long_Integer range 1..X loop L.PushInteger(I); end loop; return Integer(X); end Multret; function Closure (L : Lua_State'Class) return Natural is p : constant Long_Float := L.ToNumber(UpvalueIndex(1)); x : constant Long_Float := L.ToNumber(-1); begin Put_Line("* In Ada closure foobar" & "<" & Long_Float'Image(p) & ">" & "(" & Long_Float'Image(x) & ")"); L.Pop(1); L.PushNumber(x*p); return 1; end Closure; end Example_AdaFunctions;
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- private package Ada_Pretty.Definitions is type Access_Definition is new Node with private; function New_Access (Modifier : Access_Modifier; Target : not null Node_Access) return Node'Class; type Derived is new Node with private; function New_Derived (Parent : not null Node_Access) return Node'Class; type Null_Exclusion is new Node with private; function New_Null_Exclusion (Definition : not null Node_Access; Exclude : Boolean) return Node'Class; type Interface_Type is new Node with private; function New_Interface (Is_Limited : Boolean; Parents : Node_Access) return Node'Class; type Private_Record is new Node with private; function New_Private_Record (Is_Tagged : Boolean; Is_Limited : Boolean; Parents : Node_Access) return Node'Class; type Record_Definition is new Node with private; function New_Record (Parent : Node_Access := null; Components : Node_Access; Is_Abstract : Boolean; Is_Tagged : Boolean; Is_Limited : Boolean) return Node'Class; type Array_Definition is new Node with private; function New_Array (Indexes : not null Node_Access; Component : not null Node_Access) return Node'Class; type Subprogram is new Node with private; function Name (Self : Subprogram) return Node_Access; function New_Subprogram (Is_Overriding : Trilean; Name : Node_Access; Parameters : Node_Access; Result : Node_Access) return Node'Class; private type Access_Definition is new Node with record Modifier : Access_Modifier; Target : not null Node_Access; end record; overriding function Document (Self : Access_Definition; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Derived is new Node with record Parent : not null Node_Access; end record; overriding function Document (Self : Derived; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Null_Exclusion is new Node with record Definition : not null Node_Access; Exclude : Boolean; end record; overriding function Document (Self : Null_Exclusion; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Interface_Type is new Node with record Is_Limited : Boolean; Parents : Node_Access; end record; overriding function Document (Self : Interface_Type; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Private_Record is new Node with record Is_Tagged : Boolean; Is_Limited : Boolean; Parents : Node_Access := null; end record; overriding function Document (Self : Private_Record; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Record_Definition is new Node with record Parent : Node_Access; Components : Node_Access; Is_Abstract : Boolean; Is_Tagged : Boolean; Is_Limited : Boolean; end record; overriding function Document (Self : Record_Definition; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Array_Definition is new Node with record Indexes : not null Node_Access; Component : not null Node_Access; end record; overriding function Document (Self : Array_Definition; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; type Subprogram is new Node with record Is_Overriding : Trilean; Name : Node_Access; Parameters : Node_Access; Result : Node_Access; end record; overriding function Document (Self : Subprogram; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; end Ada_Pretty.Definitions;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- A D A . C O N T A I N E R S . B O U N D E D _ H A S H E D _ S E T S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2004-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 contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 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/>. -- -- -- -- This unit was originally developed by Matthew J Heaney. -- ------------------------------------------------------------------------------ with Ada.Iterator_Interfaces; private with Ada.Containers.Hash_Tables; private with Ada.Streams; generic type Element_Type is private; with function Hash (Element : Element_Type) return Hash_Type; with function Equivalent_Elements (Left, Right : Element_Type) return Boolean; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Ada.Containers.Bounded_Hashed_Sets is pragma Pure; pragma Remote_Types; type Set (Capacity : Count_Type; Modulus : Hash_Type) is tagged private with Constant_Indexing => Constant_Reference, Default_Iterator => Iterate, Iterator_Element => Element_Type; pragma Preelaborable_Initialization (Set); type Cursor is private; pragma Preelaborable_Initialization (Cursor); Empty_Set : constant Set; -- Set objects declared without an initialization expression are -- initialized to the value Empty_Set. No_Element : constant Cursor; -- Cursor objects declared without an initialization expression are -- initialized to the value No_Element. function Has_Element (Position : Cursor) return Boolean; -- Equivalent to Position /= No_Element package Set_Iterator_Interfaces is new Ada.Iterator_Interfaces (Cursor, Has_Element); function "=" (Left, Right : Set) return Boolean; -- For each element in Left, set equality attempts to find the equal -- element in Right; if a search fails, then set equality immediately -- returns False. The search works by calling Hash to find the bucket in -- the Right set that corresponds to the Left element. If the bucket is -- non-empty, the search calls the generic formal element equality operator -- to compare the element (in Left) to the element of each node in the -- bucket (in Right); the search terminates when a matching node in the -- bucket is found, or the nodes in the bucket are exhausted. (Note that -- element equality is called here, not Equivalent_Elements. Set equality -- is the only operation in which element equality is used. Compare set -- equality to Equivalent_Sets, which does call Equivalent_Elements.) function Equivalent_Sets (Left, Right : Set) return Boolean; -- Similar to set equality, with the difference that the element in Left is -- compared to the elements in Right using the generic formal -- Equivalent_Elements operation instead of element equality. function To_Set (New_Item : Element_Type) return Set; -- Constructs a singleton set comprising New_Element. To_Set calls Hash to -- determine the bucket for New_Item. function Capacity (Container : Set) return Count_Type; -- Returns the current capacity of the set. Capacity is the maximum length -- before which rehashing in guaranteed not to occur. procedure Reserve_Capacity (Container : in out Set; Capacity : Count_Type); -- If the value of the Capacity actual parameter is less or equal to -- Container.Capacity, then the operation has no effect. Otherwise it -- raises Capacity_Error (as no expansion of capacity is possible for a -- bounded form). function Default_Modulus (Capacity : Count_Type) return Hash_Type; -- Returns a modulus value (hash table size) which is optimal for the -- specified capacity (which corresponds to the maximum number of items). function Length (Container : Set) return Count_Type; -- Returns the number of items in the set function Is_Empty (Container : Set) return Boolean; -- Equivalent to Length (Container) = 0 procedure Clear (Container : in out Set); -- Removes all of the items from the set function Element (Position : Cursor) return Element_Type; -- Returns the element of the node designated by the cursor procedure Replace_Element (Container : in out Set; Position : Cursor; New_Item : Element_Type); -- If New_Item is equivalent (as determined by calling Equivalent_Elements) -- to the element of the node designated by Position, then New_Element is -- assigned to that element. Otherwise, it calls Hash to determine the -- bucket for New_Item. If the bucket is not empty, then it calls -- Equivalent_Elements for each node in that bucket to determine whether -- New_Item is equivalent to an element in that bucket. If -- Equivalent_Elements returns True then Program_Error is raised (because -- an element may appear only once in the set); otherwise, New_Item is -- assigned to the node designated by Position, and the node is moved to -- its new bucket. procedure Query_Element (Position : Cursor; Process : not null access procedure (Element : Element_Type)); -- Calls Process with the element (having only a constant view) of the node -- designated by the cursor. type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; function Constant_Reference (Container : aliased Set; Position : Cursor) return Constant_Reference_Type; procedure Assign (Target : in out Set; Source : Set); -- If Target denotes the same object as Source, then the operation has no -- effect. If the Target capacity is less than the Source length, then -- Assign raises Capacity_Error. Otherwise, Assign clears Target and then -- copies the (active) elements from Source to Target. function Copy (Source : Set; Capacity : Count_Type := 0; Modulus : Hash_Type := 0) return Set; -- Constructs a new set object whose elements correspond to Source. If the -- Capacity parameter is 0, then the capacity of the result is the same as -- the length of Source. If the Capacity parameter is equal or greater than -- the length of Source, then the capacity of the result is the specified -- value. Otherwise, Copy raises Capacity_Error. If the Modulus parameter -- is 0, then the modulus of the result is the value returned by a call to -- Default_Modulus with the capacity parameter determined as above; -- otherwise the modulus of the result is the specified value. procedure Move (Target : in out Set; Source : in out Set); -- Clears Target (if it's not empty), and then moves (not copies) the -- buckets array and nodes from Source to Target. procedure Insert (Container : in out Set; New_Item : Element_Type; Position : out Cursor; Inserted : out Boolean); -- Conditionally inserts New_Item into the set. If New_Item is already in -- the set, then Inserted returns False and Position designates the node -- containing the existing element (which is not modified). If New_Item is -- not already in the set, then Inserted returns True and Position -- designates the newly-inserted node containing New_Item. The search for -- an existing element works as follows. Hash is called to determine -- New_Item's bucket; if the bucket is non-empty, then Equivalent_Elements -- is called to compare New_Item to the element of each node in that -- bucket. If the bucket is empty, or there were no equivalent elements in -- the bucket, the search "fails" and the New_Item is inserted in the set -- (and Inserted returns True); otherwise, the search "succeeds" (and -- Inserted returns False). procedure Insert (Container : in out Set; New_Item : Element_Type); -- Attempts to insert New_Item into the set, performing the usual insertion -- search (which involves calling both Hash and Equivalent_Elements); if -- the search succeeds (New_Item is equivalent to an element already in the -- set, and so was not inserted), then this operation raises -- Constraint_Error. (This version of Insert is similar to Replace, but -- having the opposite exception behavior. It is intended for use when you -- want to assert that the item is not already in the set.) procedure Include (Container : in out Set; New_Item : Element_Type); -- Attempts to insert New_Item into the set. If an element equivalent to -- New_Item is already in the set (the insertion search succeeded, and -- hence New_Item was not inserted), then the value of New_Item is assigned -- to the existing element. (This insertion operation only raises an -- exception if cursor tampering occurs. It is intended for use when you -- want to insert the item in the set, and you don't care whether an -- equivalent element is already present.) procedure Replace (Container : in out Set; New_Item : Element_Type); -- Searches for New_Item in the set; if the search fails (because an -- equivalent element was not in the set), then it raises -- Constraint_Error. Otherwise, the existing element is assigned the value -- New_Item. (This is similar to Insert, but with the opposite exception -- behavior. It is intended for use when you want to assert that the item -- is already in the set.) procedure Exclude (Container : in out Set; Item : Element_Type); -- Searches for Item in the set, and if found, removes its node from the -- set and then deallocates it. The search works as follows. The operation -- calls Hash to determine the item's bucket; if the bucket is not empty, -- it calls Equivalent_Elements to compare Item to the element of each node -- in the bucket. (This is the deletion analog of Include. It is intended -- for use when you want to remove the item from the set, but don't care -- whether the item is already in the set.) procedure Delete (Container : in out Set; Item : Element_Type); -- Searches for Item in the set (which involves calling both Hash and -- Equivalent_Elements). If the search fails, then the operation raises -- Constraint_Error. Otherwise it removes the node from the set and then -- deallocates it. (This is the deletion analog of non-conditional -- Insert. It is intended for use when you want to assert that the item is -- already in the set.) procedure Delete (Container : in out Set; Position : in out Cursor); -- Removes the node designated by Position from the set, and then -- deallocates the node. The operation calls Hash to determine the bucket, -- and then compares Position to each node in the bucket until there's a -- match (it does not call Equivalent_Elements). procedure Union (Target : in out Set; Source : Set); -- Iterates over the Source set, and conditionally inserts each element -- into Target. function Union (Left, Right : Set) return Set; -- The operation first copies the Left set to the result, and then iterates -- over the Right set to conditionally insert each element into the result. function "or" (Left, Right : Set) return Set renames Union; procedure Intersection (Target : in out Set; Source : Set); -- Iterates over the Target set (calling First and Next), calling Find to -- determine whether the element is in Source. If an equivalent element is -- not found in Source, the element is deleted from Target. function Intersection (Left, Right : Set) return Set; -- Iterates over the Left set, calling Find to determine whether the -- element is in Right. If an equivalent element is found, it is inserted -- into the result set. function "and" (Left, Right : Set) return Set renames Intersection; procedure Difference (Target : in out Set; Source : Set); -- Iterates over the Source (calling First and Next), calling Find to -- determine whether the element is in Target. If an equivalent element is -- found, it is deleted from Target. function Difference (Left, Right : Set) return Set; -- Iterates over the Left set, calling Find to determine whether the -- element is in the Right set. If an equivalent element is not found, the -- element is inserted into the result set. function "-" (Left, Right : Set) return Set renames Difference; procedure Symmetric_Difference (Target : in out Set; Source : Set); -- The operation iterates over the Source set, searching for the element -- in Target (calling Hash and Equivalent_Elements). If an equivalent -- element is found, it is removed from Target; otherwise it is inserted -- into Target. function Symmetric_Difference (Left, Right : Set) return Set; -- The operation first iterates over the Left set. It calls Find to -- determine whether the element is in the Right set. If no equivalent -- element is found, the element from Left is inserted into the result. The -- operation then iterates over the Right set, to determine whether the -- element is in the Left set. If no equivalent element is found, the Right -- element is inserted into the result. function "xor" (Left, Right : Set) return Set renames Symmetric_Difference; function Overlap (Left, Right : Set) return Boolean; -- Iterates over the Left set (calling First and Next), calling Find to -- determine whether the element is in the Right set. If an equivalent -- element is found, the operation immediately returns True. The operation -- returns False if the iteration over Left terminates without finding any -- equivalent element in Right. function Is_Subset (Subset : Set; Of_Set : Set) return Boolean; -- Iterates over Subset (calling First and Next), calling Find to determine -- whether the element is in Of_Set. If no equivalent element is found in -- Of_Set, the operation immediately returns False. The operation returns -- True if the iteration over Subset terminates without finding an element -- not in Of_Set (that is, every element in Subset is equivalent to an -- element in Of_Set). function First (Container : Set) return Cursor; -- Returns a cursor that designates the first non-empty bucket, by -- searching from the beginning of the buckets array. function Next (Position : Cursor) return Cursor; -- Returns a cursor that designates the node that follows the current one -- designated by Position. If Position designates the last node in its -- bucket, the operation calls Hash to compute the index of this bucket, -- and searches the buckets array for the first non-empty bucket, starting -- from that index; otherwise, it simply follows the link to the next node -- in the same bucket. procedure Next (Position : in out Cursor); -- Equivalent to Position := Next (Position) function Find (Container : Set; Item : Element_Type) return Cursor; -- Searches for Item in the set. Find calls Hash to determine the item's -- bucket; if the bucket is not empty, it calls Equivalent_Elements to -- compare Item to each element in the bucket. If the search succeeds, Find -- returns a cursor designating the node containing the equivalent element; -- otherwise, it returns No_Element. function Contains (Container : Set; Item : Element_Type) return Boolean; -- Equivalent to Find (Container, Item) /= No_Element function Equivalent_Elements (Left, Right : Cursor) return Boolean; -- Returns the result of calling Equivalent_Elements with the elements of -- the nodes designated by cursors Left and Right. function Equivalent_Elements (Left : Cursor; Right : Element_Type) return Boolean; -- Returns the result of calling Equivalent_Elements with element of the -- node designated by Left and element Right. function Equivalent_Elements (Left : Element_Type; Right : Cursor) return Boolean; -- Returns the result of calling Equivalent_Elements with element Left and -- the element of the node designated by Right. procedure Iterate (Container : Set; Process : not null access procedure (Position : Cursor)); -- Calls Process for each node in the set function Iterate (Container : Set) return Set_Iterator_Interfaces.Forward_Iterator'Class; generic type Key_Type (<>) is private; with function Key (Element : Element_Type) return Key_Type; with function Hash (Key : Key_Type) return Hash_Type; with function Equivalent_Keys (Left, Right : Key_Type) return Boolean; package Generic_Keys is function Key (Position : Cursor) return Key_Type; -- Applies generic formal operation Key to the element of the node -- designated by Position. function Element (Container : Set; Key : Key_Type) return Element_Type; -- Searches (as per the key-based Find) for the node containing Key, and -- returns the associated element. procedure Replace (Container : in out Set; Key : Key_Type; New_Item : Element_Type); -- Searches (as per the key-based Find) for the node containing Key, and -- then replaces the element of that node (as per the element-based -- Replace_Element). procedure Exclude (Container : in out Set; Key : Key_Type); -- Searches for Key in the set, and if found, removes its node from the -- set and then deallocates it. The search works by first calling Hash -- (on Key) to determine the bucket; if the bucket is not empty, it -- calls Equivalent_Keys to compare parameter Key to the value of -- generic formal operation Key applied to element of each node in the -- bucket. procedure Delete (Container : in out Set; Key : Key_Type); -- Deletes the node containing Key as per Exclude, with the difference -- that Constraint_Error is raised if Key is not found. function Find (Container : Set; Key : Key_Type) return Cursor; -- Searches for the node containing Key, and returns a cursor -- designating the node. The search works by first calling Hash (on Key) -- to determine the bucket. If the bucket is not empty, the search -- compares Key to the element of each node in the bucket, and returns -- the matching node. The comparison itself works by applying the -- generic formal Key operation to the element of the node, and then -- calling generic formal operation Equivalent_Keys. function Contains (Container : Set; Key : Key_Type) return Boolean; -- Equivalent to Find (Container, Key) /= No_Element procedure Update_Element_Preserving_Key (Container : in out Set; Position : Cursor; Process : not null access procedure (Element : in out Element_Type)); -- Calls Process with the element of the node designated by Position, -- but with the restriction that the key-value of the element is not -- modified. The operation first makes a copy of the value returned by -- applying generic formal operation Key on the element of the node, and -- then calls Process with the element. The operation verifies that the -- key-part has not been modified by calling generic formal operation -- Equivalent_Keys to compare the saved key-value to the value returned -- by applying generic formal operation Key to the post-Process value of -- element. If the key values compare equal then the operation -- completes. Otherwise, the node is removed from the map and -- Program_Error is raised. type Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Reference_Preserving_Key (Container : aliased in out Set; Position : Cursor) return Reference_Type; function Constant_Reference (Container : aliased Set; Key : Key_Type) return Constant_Reference_Type; function Reference_Preserving_Key (Container : aliased in out Set; Key : Key_Type) return Reference_Type; private type Reference_Type (Element : not null access Element_Type) is null record; use Ada.Streams; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Reference_Type); for Reference_Type'Read use Read; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Reference_Type); for Reference_Type'Write use Write; end Generic_Keys; private pragma Inline (Next); type Node_Type is record Element : aliased Element_Type; Next : Count_Type; end record; package HT_Types is new Hash_Tables.Generic_Bounded_Hash_Table_Types (Node_Type); type Set (Capacity : Count_Type; Modulus : Hash_Type) is new HT_Types.Hash_Table_Type (Capacity, Modulus) with null record; use HT_Types; use Ada.Streams; procedure Write (Stream : not null access Root_Stream_Type'Class; Container : Set); for Set'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Container : out Set); for Set'Read use Read; type Set_Access is access all Set; for Set_Access'Storage_Size use 0; -- Note: If a Cursor object has no explicit initialization expression, -- it must default initialize to the same value as constant No_Element. -- The Node component of type Cursor has scalar type Count_Type, so it -- requires an explicit initialization expression of its own declaration, -- in order for objects of record type Cursor to properly initialize. type Cursor is record Container : Set_Access; Node : Count_Type := 0; end record; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Cursor); for Cursor'Write use Write; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Cursor); for Cursor'Read use Read; type Constant_Reference_Type (Element : not null access constant Element_Type) is null record; procedure Read (Stream : not null access Root_Stream_Type'Class; Item : out Constant_Reference_Type); for Constant_Reference_Type'Read use Read; procedure Write (Stream : not null access Root_Stream_Type'Class; Item : Constant_Reference_Type); for Constant_Reference_Type'Write use Write; Empty_Set : constant Set := (Hash_Table_Type with Capacity => 0, Modulus => 0); No_Element : constant Cursor := (Container => null, Node => 0); end Ada.Containers.Bounded_Hashed_Sets;
-- { dg-do run } with elim1; procedure elim2 is begin null; end;
-- Copyright 2015,2017 Steven Stewart-Gallus -- -- 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 Libc.Signal.GNU; with Libc.Time.GNU; package Libc.Sys.Poll with Spark_Mode => Off is subtype nfds_t is unsigned_long; -- /usr/include/sys/poll.h:36 type pollfd is record fd : int; -- /usr/include/sys/poll.h:41 events : short; -- /usr/include/sys/poll.h:42 revents : short; -- /usr/include/sys/poll.h:43 end record; function poll (fds : in out pollfd; nfds : nfds_t; timeout : int) return int; -- /usr/include/sys/poll.h:57 pragma Import (C, poll, "poll"); function ppoll (fds : in out pollfd; nfds : nfds_t; timeout : access constant Libc.Time.GNU.timespec; ss : access constant Libc.Signal.GNU.sigset_t) return int; -- /usr/include/sys/poll.h:66 pragma Import (C, ppoll, "ppoll"); POLLIN : constant := 16#001#; POLLPRI : constant := 16#002#; POLLOUT : constant := 16#004#; POLLERR : constant := 16#008#; POLLHUP : constant := 16#010#; POLLNVAL : constant := 16#020#; end Libc.Sys.Poll;
with Ada.Text_IO; use Ada.Text_IO; with Railway; use Railway; procedure Main is OK : Boolean; -- change TRYB to check for different possibilities of crash situation: -- TRYB = 0 => From Left to Right - no crash. -- TRYB = 1 => From Right to Left - no crash. -- TRYB = 2 => Simulated crash in the middle, RightTrain waits on middle for LeftTrain. -- TRYB = 3 => Train starts from Left, moves to the Middle, then back to Left, -- and then to the Middle, next to the Right, back to the Middle, -- and then again to the Right and at last Leaves at the right side the segments. TRYB : Integer := 3; begin if TRYB = 0 then --Od lewej do prawej Put_Line("Normal -> Left -> Middle -> Right:"); Open_Route ( Route_Enter_Left, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Enter_Left, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Middle_Right, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Middle_Right, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Leave_Right, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Leave_Right, OK ); Put_Line(Boolean'Image(OK)); elsif TRYB = 1 then -- A teraz w druga strone Put_Line("Normal -> Right -> Middle -> Left:"); Open_Route ( Route_Enter_Right, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Enter_Right, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Right_Middle, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Right_Middle, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Middle_Left, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Middle_Left, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Leave_Left, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Leave_Left, OK ); Put_Line(Boolean'Image(OK)); elsif TRYB = 2 then -- A teraz wymuszone zderzenie Put_Line("Simulated crash -> Right -> Middle"); Put_Line("----------with-- -> Left -> Middle:"); Open_Route ( Route_Enter_Right, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Enter_Right, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Enter_Left, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Enter_Left, OK ); Put_Line(Boolean'Image(OK)); Open_Route ( Route_Right_Middle, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Right_Middle, OK ); Put_Line(Boolean'Image(OK)); Put_Line("RightTrain is now on Middle. LeftTrain aproaching Middle. Has trains crashed?"); Open_Route ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); Move_Train ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); if OK=True then Put_Line("CRASH!"); else Put_Line("TRAFFIC STOPPED, possibility of crash"); end if; elsif TRYB = 3 then -- teraz kilka szybkich testow dwójkami Put_Line("Back and forth:"); Put_Line("-> Left -> Middle"); Train ( Route_Enter_Left, OK ); Put_Line(Boolean'Image(OK)); Train ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); Put_Line(" Left <- Middle "); Train ( Route_Middle_Left, OK ); Put_Line(Boolean'Image(OK)); Put_Line(" Left -> Middle -> Right"); Train ( Route_Left_Middle, OK ); Put_Line(Boolean'Image(OK)); Train ( Route_Middle_Right, OK ); Put_Line(Boolean'Image(OK)); Put_Line(" Middle <- Right"); Train ( Route_Right_Middle, OK ); Put_Line(Boolean'Image(OK)); Put_Line(" Middle -> Right -> "); Train ( Route_Middle_Right, OK ); Put_Line(Boolean'Image(OK)); Train ( Route_Leave_Right, OK ); Put_Line(Boolean'Image(OK)); if OK = True then Put_Line("Train exited segments successfuly!"); else Put_Line("Train met some problems"); end if; elsif TRYB = 4 then null; else Put_Line("Podany tryb jest niepoprawny"); end if; end Main;
-- This spec has been automatically generated from STM32WL5x_CM0P.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.IPCC is pragma Preelaborate; --------------- -- Registers -- --------------- -- IPCC Processor 1 control register type IPCC_C1CR_Register is record -- RXOIE RXOIE : Boolean := False; -- unspecified Reserved_1_15 : HAL.UInt15 := 16#0#; -- TXFIE TXFIE : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C1CR_Register use record RXOIE at 0 range 0 .. 0; Reserved_1_15 at 0 range 1 .. 15; TXFIE at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; -- IPCC Processor 1 mask register type IPCC_C1MR_Register is record -- CH1OM CH1OM : Boolean := True; -- CH2OM CH2OM : Boolean := True; -- CH3OM CH3OM : Boolean := True; -- CH4OM CH4OM : Boolean := True; -- CH5OM CH5OM : Boolean := True; -- CH6OM CH6OM : Boolean := True; -- unspecified Reserved_6_15 : HAL.UInt10 := 16#3FF#; -- CH1FM CH1FM : Boolean := True; -- CH2FM CH2FM : Boolean := True; -- CH3FM CH3FM : Boolean := True; -- CH4FM CH4FM : Boolean := True; -- CH5FM CH5FM : Boolean := True; -- CH6FM CH6FM : Boolean := True; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#3FF#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C1MR_Register use record CH1OM at 0 range 0 .. 0; CH2OM at 0 range 1 .. 1; CH3OM at 0 range 2 .. 2; CH4OM at 0 range 3 .. 3; CH5OM at 0 range 4 .. 4; CH6OM at 0 range 5 .. 5; Reserved_6_15 at 0 range 6 .. 15; CH1FM at 0 range 16 .. 16; CH2FM at 0 range 17 .. 17; CH3FM at 0 range 18 .. 18; CH4FM at 0 range 19 .. 19; CH5FM at 0 range 20 .. 20; CH6FM at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; -- Reading this register will always return 0x0000 0000. type IPCC_C1SCR_Register is record -- CH1C CH1C : Boolean := False; -- CH2C CH2C : Boolean := False; -- CH3C CH3C : Boolean := False; -- CH4C CH4C : Boolean := False; -- CH5C CH5C : Boolean := False; -- CH6C CH6C : Boolean := False; -- unspecified Reserved_6_15 : HAL.UInt10 := 16#0#; -- CH1S CH1S : Boolean := False; -- CH2S CH2S : Boolean := False; -- CH3S CH3S : Boolean := False; -- CH4S CH4S : Boolean := False; -- CH5S CH5S : Boolean := False; -- CH6S CH6S : Boolean := False; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C1SCR_Register use record CH1C at 0 range 0 .. 0; CH2C at 0 range 1 .. 1; CH3C at 0 range 2 .. 2; CH4C at 0 range 3 .. 3; CH5C at 0 range 4 .. 4; CH6C at 0 range 5 .. 5; Reserved_6_15 at 0 range 6 .. 15; CH1S at 0 range 16 .. 16; CH2S at 0 range 17 .. 17; CH3S at 0 range 18 .. 18; CH4S at 0 range 19 .. 19; CH5S at 0 range 20 .. 20; CH6S at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; -- IPCC processor 1 to processor 2 status register type IPCC_C1TOC2SR_Register is record -- Read-only. CH1F CH1F : Boolean; -- Read-only. CH2F CH2F : Boolean; -- Read-only. CH3F CH3F : Boolean; -- Read-only. CH4F CH4F : Boolean; -- Read-only. CH5F CH5F : Boolean; -- Read-only. CH6F CH6F : Boolean; -- unspecified Reserved_6_31 : HAL.UInt26; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C1TOC2SR_Register use record CH1F at 0 range 0 .. 0; CH2F at 0 range 1 .. 1; CH3F at 0 range 2 .. 2; CH4F at 0 range 3 .. 3; CH5F at 0 range 4 .. 4; CH6F at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; -- IPCC Processor 2 control register type IPCC_C2CR_Register is record -- RXOIE RXOIE : Boolean := False; -- unspecified Reserved_1_15 : HAL.UInt15 := 16#0#; -- TXFIE TXFIE : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C2CR_Register use record RXOIE at 0 range 0 .. 0; Reserved_1_15 at 0 range 1 .. 15; TXFIE at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; -- IPCC Processor 2 mask register type IPCC_C2MR_Register is record -- CH1OM CH1OM : Boolean := True; -- CH2OM CH2OM : Boolean := True; -- CH3OM CH3OM : Boolean := True; -- CH4OM CH4OM : Boolean := True; -- CH5OM CH5OM : Boolean := True; -- CH6OM CH6OM : Boolean := True; -- unspecified Reserved_6_15 : HAL.UInt10 := 16#3FF#; -- CH1FM CH1FM : Boolean := True; -- CH2FM CH2FM : Boolean := True; -- CH3FM CH3FM : Boolean := True; -- CH4FM CH4FM : Boolean := True; -- CH5FM CH5FM : Boolean := True; -- CH6FM CH6FM : Boolean := True; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#3FF#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C2MR_Register use record CH1OM at 0 range 0 .. 0; CH2OM at 0 range 1 .. 1; CH3OM at 0 range 2 .. 2; CH4OM at 0 range 3 .. 3; CH5OM at 0 range 4 .. 4; CH6OM at 0 range 5 .. 5; Reserved_6_15 at 0 range 6 .. 15; CH1FM at 0 range 16 .. 16; CH2FM at 0 range 17 .. 17; CH3FM at 0 range 18 .. 18; CH4FM at 0 range 19 .. 19; CH5FM at 0 range 20 .. 20; CH6FM at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; -- Reading this register will always return 0x0000 0000. type IPCC_C2SCR_Register is record -- CH1C CH1C : Boolean := False; -- CH2C CH2C : Boolean := False; -- CH3C CH3C : Boolean := False; -- CH4C CH4C : Boolean := False; -- CH5C CH5C : Boolean := False; -- CH6C CH6C : Boolean := False; -- unspecified Reserved_6_15 : HAL.UInt10 := 16#0#; -- CH1S CH1S : Boolean := False; -- CH2S CH2S : Boolean := False; -- CH3S CH3S : Boolean := False; -- CH4S CH4S : Boolean := False; -- CH5S CH5S : Boolean := False; -- CH6S CH6S : Boolean := False; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C2SCR_Register use record CH1C at 0 range 0 .. 0; CH2C at 0 range 1 .. 1; CH3C at 0 range 2 .. 2; CH4C at 0 range 3 .. 3; CH5C at 0 range 4 .. 4; CH6C at 0 range 5 .. 5; Reserved_6_15 at 0 range 6 .. 15; CH1S at 0 range 16 .. 16; CH2S at 0 range 17 .. 17; CH3S at 0 range 18 .. 18; CH4S at 0 range 19 .. 19; CH5S at 0 range 20 .. 20; CH6S at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; -- IPCC processor 2 to processor 1 status register type IPCC_C2TOC1SR_Register is record -- Read-only. CH1F CH1F : Boolean; -- Read-only. CH2F CH2F : Boolean; -- Read-only. CH3F CH3F : Boolean; -- Read-only. CH4F CH4F : Boolean; -- Read-only. CH5F CH5F : Boolean; -- Read-only. CH6F CH6F : Boolean; -- unspecified Reserved_6_31 : HAL.UInt26; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_C2TOC1SR_Register use record CH1F at 0 range 0 .. 0; CH2F at 0 range 1 .. 1; CH3F at 0 range 2 .. 2; CH4F at 0 range 3 .. 3; CH5F at 0 range 4 .. 4; CH6F at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; subtype IPCC_HWCFGR_CHANNELS_Field is HAL.UInt8; -- IPCC Hardware configuration register type IPCC_HWCFGR_Register is record -- Read-only. CHANNELS CHANNELS : IPCC_HWCFGR_CHANNELS_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_HWCFGR_Register use record CHANNELS at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype IPCC_VERR_MINREV_Field is HAL.UInt4; subtype IPCC_VERR_MAJREV_Field is HAL.UInt4; -- IPCC IP Version register type IPCC_VERR_Register is record -- Read-only. MINREV MINREV : IPCC_VERR_MINREV_Field; -- Read-only. MAJREV MAJREV : IPCC_VERR_MAJREV_Field; -- unspecified Reserved_8_31 : HAL.UInt24; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IPCC_VERR_Register use record MINREV at 0 range 0 .. 3; MAJREV at 0 range 4 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Inter Processor communication controller type IPCC_Peripheral is record -- IPCC Processor 1 control register IPCC_C1CR : aliased IPCC_C1CR_Register; -- IPCC Processor 1 mask register IPCC_C1MR : aliased IPCC_C1MR_Register; -- Reading this register will always return 0x0000 0000. IPCC_C1SCR : aliased IPCC_C1SCR_Register; -- IPCC processor 1 to processor 2 status register IPCC_C1TOC2SR : aliased IPCC_C1TOC2SR_Register; -- IPCC Processor 2 control register IPCC_C2CR : aliased IPCC_C2CR_Register; -- IPCC Processor 2 mask register IPCC_C2MR : aliased IPCC_C2MR_Register; -- Reading this register will always return 0x0000 0000. IPCC_C2SCR : aliased IPCC_C2SCR_Register; -- IPCC processor 2 to processor 1 status register IPCC_C2TOC1SR : aliased IPCC_C2TOC1SR_Register; -- IPCC Hardware configuration register IPCC_HWCFGR : aliased IPCC_HWCFGR_Register; -- IPCC IP Version register IPCC_VERR : aliased IPCC_VERR_Register; -- IPCC IP Identification register IPCC_IPIDR : aliased HAL.UInt32; -- IPCC Size ID register IPCC_SIDR : aliased HAL.UInt32; end record with Volatile; for IPCC_Peripheral use record IPCC_C1CR at 16#0# range 0 .. 31; IPCC_C1MR at 16#4# range 0 .. 31; IPCC_C1SCR at 16#8# range 0 .. 31; IPCC_C1TOC2SR at 16#C# range 0 .. 31; IPCC_C2CR at 16#10# range 0 .. 31; IPCC_C2MR at 16#14# range 0 .. 31; IPCC_C2SCR at 16#18# range 0 .. 31; IPCC_C2TOC1SR at 16#1C# range 0 .. 31; IPCC_HWCFGR at 16#3F0# range 0 .. 31; IPCC_VERR at 16#3F4# range 0 .. 31; IPCC_IPIDR at 16#3F8# range 0 .. 31; IPCC_SIDR at 16#3FC# range 0 .. 31; end record; -- Inter Processor communication controller IPCC_Periph : aliased IPCC_Peripheral with Import, Address => IPCC_Base; end STM32_SVD.IPCC;