max_stars_repo_path
stringlengths
4
261
max_stars_repo_name
stringlengths
6
106
max_stars_count
int64
0
38.8k
id
stringlengths
1
6
text
stringlengths
7
1.05M
programs/oeis/133/A133825.asm
neoneye/loda
22
171502
<reponame>neoneye/loda ; A133825: Triangle whose rows are sequences of increasing and decreasing triangular numbers: 1; 1,3,1; 1,3,6,3,1; ... . ; 1,1,3,1,1,3,6,3,1,1,3,6,10,6,3,1,1,3,6,10,15,10,6,3,1,1,3,6,10,15,21,15,10,6,3,1,1,3,6,10,15,21,28,21,15,10,6,3,1,1,3,6,10,15,21,28,36,28,21,15,10,6,3,1,1,3,6,10,15,21,28,36,45,36,28,21,15,10,6,3,1,1,3,6,10,15,21,28,36,45,55,45,36,28,21,15,10,6,3,1 seq $0,4737 ; Concatenation of sequences (1,2,...,n-1,n,n-1,...,1) for n >= 1. sub $1,$0 bin $1,2 mov $0,$1
programs/oeis/077/A077430.asm
karttu/loda
1
171096
<gh_stars>1-10 ; A077430: a(n) = floor(log_10(2*n^2)) + 1. ; 1,1,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 add $0,1 pow $0,2 mov $1,$0 mul $1,2 log $1,10 add $1,1
examples/song/play-song.asm
toshipiazza/iCreate-Assembler
0
88235
song 0 ; note, you don't need to include the size of the song! ; song start 60 64 67
projects/08/ProgramFlow/FibonacciSeries/FibonacciSeries.asm
nadavWeisler/Nand2Tetris
0
245424
<reponame>nadavWeisler/Nand2Tetris<gh_stars>0 @1 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @1 D=A @THIS D=D+A @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @0 D=A @SP A=M M=D @SP M=M+1 @0 D=A @THAT D=D+M @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @1 D=A @SP A=M M=D @SP M=M+1 @1 D=A @THAT D=D+M @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @2 D=A @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 M=M-D @0 D=A @ARG D=D+M @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D (MAIN_LOOP_START) @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 @COMPUTE_ELEMENT D;JNE @END_PROGRAM 0;JMP (COMPUTE_ELEMENT) @0 D=A @THAT A=M+D D=M @SP A=M M=D @SP M=M+1 @1 D=A @THAT A=M+D D=M @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 M=M+D @2 D=A @THAT D=D+M @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @1 D=A @THIS A=A+D D=M @SP A=M M=D @SP M=M+1 @1 D=A @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 M=M+D @1 D=A @THIS D=D+A @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @1 D=A @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 M=M-D @0 D=A @ARG D=D+M @13 M=D @SP M=M-1 A=M D=M @13 A=M M=D @MAIN_LOOP_START 0;JMP (END_PROGRAM)
data/jpred4/jp_batch_1613899824__OtwSqMq/jp_batch_1613899824__OtwSqMq.als
jonriege/predict-protein-structure
0
4275
SILENT_MODE BLOCK_FILE jp_batch_1613899824__OtwSqMq.concise.blc MAX_NSEQ 50 MAX_INPUT_LEN 50 OUTPUT_FILE jp_batch_1613899824__OtwSqMq.concise.ps PORTRAIT POINTSIZE 8 IDENT_WIDTH 12 X_OFFSET 2 Y_OFFSET 2 DEFINE_FONT 0 Helvetica DEFAULT DEFINE_FONT 1 Helvetica REL 0.75 DEFINE_FONT 7 Helvetica REL 0.6 DEFINE_FONT 3 Helvetica-Bold DEFAULT DEFINE_FONT 4 Times-Bold DEFAULT DEFINE_FONT 5 Helvetica-BoldOblique DEFAULT # DEFINE_COLOUR 3 1 0.62 0.67 # Turquiose DEFINE_COLOUR 4 1 1 0 # Yellow DEFINE_COLOUR 5 1 0 0 # Red DEFINE_COLOUR 7 1 0 1 # Purple DEFINE_COLOUR 8 0 0 1 # Blue DEFINE_COLOUR 9 0 1 0 # Green DEFINE_COLOUR 10 0.41 0.64 1.00 # Pale blue DEFINE_COLOUR 11 0.41 0.82 0.67 # Pale green DEFINE_COLOUR 50 0.69 0.18 0.37 # Pink (helix) DEFINE_COLOUR 51 1.00 0.89 0.00 # Gold (strand) NUMBER_INT 10 SETUP # # Highlight specific residues. # Avoid highlighting Lupas 'C' predictions by # limiting the highlighting to the alignments Scol_CHARS C 1 1 112 20 4 Ccol_CHARS H ALL 5 Ccol_CHARS P ALL 8 SURROUND_CHARS LIV ALL # # Replace known structure types with whitespace SUB_CHARS 1 21 112 30 H SPACE SUB_CHARS 1 21 112 30 E SPACE SUB_CHARS 1 21 112 30 - SPACE STRAND 16 24 21 COLOUR_TEXT_REGION 16 24 21 24 51 STRAND 26 24 31 COLOUR_TEXT_REGION 26 24 31 24 51 STRAND 38 24 44 COLOUR_TEXT_REGION 38 24 44 24 51 STRAND 57 24 61 COLOUR_TEXT_REGION 57 24 61 24 51 STRAND 76 24 80 COLOUR_TEXT_REGION 76 24 80 24 51 STRAND 86 24 92 COLOUR_TEXT_REGION 86 24 92 24 51 STRAND 97 24 104 COLOUR_TEXT_REGION 97 24 104 24 51 HELIX 36 24 37 COLOUR_TEXT_REGION 36 24 37 24 50 HELIX 72 24 75 COLOUR_TEXT_REGION 72 24 75 24 50 STRAND 16 29 21 COLOUR_TEXT_REGION 16 29 21 29 51 STRAND 25 29 31 COLOUR_TEXT_REGION 25 29 31 29 51 STRAND 37 29 44 COLOUR_TEXT_REGION 37 29 44 29 51 STRAND 57 29 61 COLOUR_TEXT_REGION 57 29 61 29 51 STRAND 76 29 80 COLOUR_TEXT_REGION 76 29 80 29 51 STRAND 86 29 92 COLOUR_TEXT_REGION 86 29 92 29 51 STRAND 99 29 104 COLOUR_TEXT_REGION 99 29 104 29 51 HELIX 62 29 65 COLOUR_TEXT_REGION 62 29 65 29 50 HELIX 70 29 75 COLOUR_TEXT_REGION 70 29 75 29 50 HELIX 93 29 98 COLOUR_TEXT_REGION 93 29 98 29 50 STRAND 17 30 21 COLOUR_TEXT_REGION 17 30 21 30 51 STRAND 26 30 31 COLOUR_TEXT_REGION 26 30 31 30 51 STRAND 49 30 52 COLOUR_TEXT_REGION 49 30 52 30 51 STRAND 57 30 61 COLOUR_TEXT_REGION 57 30 61 30 51 STRAND 75 30 81 COLOUR_TEXT_REGION 75 30 81 30 51 STRAND 86 30 92 COLOUR_TEXT_REGION 86 30 92 30 51 STRAND 97 30 103 COLOUR_TEXT_REGION 97 30 103 30 51 HELIX 36 30 44 COLOUR_TEXT_REGION 36 30 44 30 50 HELIX 74 30 74 COLOUR_TEXT_REGION 74 30 74 30 50
programs/oeis/268/A268615.asm
neoneye/loda
22
80963
; A268615: Lucas numbers mod 40. ; 2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4,7,11,18,29,7,36,3,39,2,1,3,4 seq $0,32 ; Lucas numbers beginning at 2: L(n) = L(n-1) + L(n-2), L(0) = 2, L(1) = 1. mod $0,40
Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.ada
djgoku/RosettaCodeData
1
28705
<filename>Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.ada with Ada.Text_IO; with Ada.Strings.Unbounded; procedure Knapsack_Continuous is package US renames Ada.Strings.Unbounded; type Item is record Name : US.Unbounded_String; Weight : Float; Value : Positive; Taken : Float; end record; function "<" (Left, Right : Item) return Boolean is begin return Float (Left.Value) / Left.Weight < Float (Right.Value) / Right.Weight; end "<"; type Item_Array is array (Positive range <>) of Item; function Total_Weight (Items : Item_Array) return Float is Sum : Float := 0.0; begin for I in Items'Range loop Sum := Sum + Items (I).Weight * Items (I).Taken; end loop; return Sum; end Total_Weight; function Total_Value (Items : Item_Array) return Float is Sum : Float := 0.0; begin for I in Items'Range loop Sum := Sum + Float (Items (I).Value) * Items (I).Taken; end loop; return Sum; end Total_Value; procedure Solve_Knapsack_Continuous (Items : in out Item_Array; Weight_Limit : Float) is begin -- order items by value per weight unit Sorting : declare An_Item : Item; J : Natural; begin for I in Items'First + 1 .. Items'Last loop An_Item := Items (I); J := I - 1; while J in Items'Range and then Items (J) < An_Item loop Items (J + 1) := Items (J); J := J - 1; end loop; Items (J + 1) := An_Item; end loop; end Sorting; declare Rest : Float := Weight_Limit; begin for I in Items'Range loop if Items (I).Weight <= Rest then Items (I).Taken := Items (I).Weight; else Items (I).Taken := Rest; end if; Rest := Rest - Items (I).Taken; exit when Rest <= 0.0; end loop; end; end Solve_Knapsack_Continuous; All_Items : Item_Array := ((US.To_Unbounded_String ("beef"), 3.8, 36, 0.0), (US.To_Unbounded_String ("pork"), 5.4, 43, 0.0), (US.To_Unbounded_String ("ham"), 3.6, 90, 0.0), (US.To_Unbounded_String ("greaves"), 2.4, 45, 0.0), (US.To_Unbounded_String ("flitch"), 4.0, 30, 0.0), (US.To_Unbounded_String ("brawn"), 2.5, 56, 0.0), (US.To_Unbounded_String ("welt"), 3.7, 67, 0.0), (US.To_Unbounded_String ("salami"), 3.0, 95, 0.0), (US.To_Unbounded_String ("sausage"), 5.9, 98, 0.0)); begin Solve_Knapsack_Continuous (All_Items, 15.0); Ada.Text_IO.Put_Line ("Total Weight: " & Float'Image (Total_Weight (All_Items))); Ada.Text_IO.Put_Line ("Total Value: " & Float'Image (Total_Value (All_Items))); Ada.Text_IO.Put_Line ("Items:"); for I in All_Items'Range loop if All_Items (I).Taken > 0.0 then Ada.Text_IO.Put_Line (" " & Float'Image (All_Items (I).Taken) & " of " & US.To_String (All_Items (I).Name)); end if; end loop; end Knapsack_Continuous;
source/streams/a-ststio.ads
ytomino/drake
33
9897
<filename>source/streams/a-ststio.ads<gh_stars>10-100 pragma License (Unrestricted); with Ada.IO_Exceptions; with Ada.IO_Modes; private with Ada.Finalization; private with Ada.Streams.Naked_Stream_IO; package Ada.Streams.Stream_IO is pragma Preelaborate; type Stream_Access is access all Root_Stream_Type'Class; for Stream_Access'Storage_Size use 0; type File_Type is limited private; pragma Preelaborable_Initialization (File_Type); -- AI12-0102-1 -- Similar to Text_IO in AI12-0054-2: -- subtype Open_File_Type is File_Type -- with -- Dynamic_Predicate => Is_Open (Open_File_Type), -- Predicate_Failure => raise Status_Error with "File not open"; -- subtype Input_File_Type is Open_File_Type -- with -- Dynamic_Predicate => Is_Readable (Input_File_Type), -- Predicate_Failure => -- raise Mode_Error with -- "Cannot read file: " & Name (Input_File_Type); -- subtype Output_File_Type is Open_File_Type -- with -- Dynamic_Predicate => Mode (Output_File_Type) /= In_File, -- Predicate_Failure => -- raise Mode_Error with -- "Cannot write file: " & Name (Output_File_Type); -- type File_Mode is (In_File, Out_File, Append_File); type File_Mode is new IO_Modes.File_Mode; -- for conversion -- modified -- Count is essentially same as Stream_Element_Count. -- type Count is range 0 .. implementation-defined; subtype Count is Stream_Element_Count; subtype Positive_Count is Count range 1 .. Count'Last; -- Index into file, in stream elements -- modified procedure Create ( File : in out File_Type; Mode : File_Mode := Out_File; Name : String := ""; Form : String); -- removed default procedure Create ( File : in out File_Type; Mode : File_Mode := Out_File; Name : String := ""; Shared : IO_Modes.File_Shared_Spec := IO_Modes.By_Mode; Wait : Boolean := False; Overwrite : Boolean := True); -- extended function Create ( Mode : File_Mode := Out_File; Name : String := ""; Shared : IO_Modes.File_Shared_Spec := IO_Modes.By_Mode; Wait : Boolean := False; Overwrite : Boolean := True) return File_Type; -- modified procedure Open ( File : in out File_Type; Mode : File_Mode; Name : String; Form : String); -- removed default procedure Open ( File : in out File_Type; Mode : File_Mode; Name : String; Shared : IO_Modes.File_Shared_Spec := IO_Modes.By_Mode; Wait : Boolean := False; Overwrite : Boolean := True); -- extended function Open ( Mode : File_Mode; Name : String; Shared : IO_Modes.File_Shared_Spec := IO_Modes.By_Mode; Wait : Boolean := False; Overwrite : Boolean := True) return File_Type; procedure Close (File : in out File_Type); procedure Delete (File : in out File_Type); procedure Reset (File : in out File_Type; Mode : File_Mode); procedure Reset (File : in out File_Type); function Mode ( File : File_Type) -- Open_File_Type return File_Mode; function Name ( File : File_Type) -- Open_File_Type return String; function Form ( File : File_Type) -- Open_File_Type return String; pragma Inline (Mode); pragma Inline (Name); function Is_Open (File : File_Type) return Boolean; function End_Of_File ( File : File_Type) -- Open_File_Type return Boolean; pragma Inline (Is_Open); pragma Inline (End_Of_File); function Stream ( File : File_Type) -- Open_File_Type return Stream_Access; -- Return stream access for use with T'Input and T'Output pragma Inline (Stream); -- Read array of stream elements from file procedure Read ( File : File_Type; -- Input_File_Type Item : out Stream_Element_Array; Last : out Stream_Element_Offset; From : Positive_Count); procedure Read ( File : File_Type; -- Input_File_Type Item : out Stream_Element_Array; Last : out Stream_Element_Offset); -- Write array of stream elements into file procedure Write ( File : File_Type; -- Output_File_Type Item : Stream_Element_Array; To : Positive_Count); procedure Write ( File : File_Type; -- Output_File_Type Item : Stream_Element_Array); -- Operations on position within file procedure Set_Index ( File : File_Type; -- Open_File_Type To : Positive_Count); function Index ( File : File_Type) -- Open_File_Type return Positive_Count; function Size ( File : File_Type) -- Open_File_Type return Count; pragma Inline (Index); pragma Inline (Size); procedure Set_Mode (File : in out File_Type; Mode : File_Mode); procedure Flush ( File : File_Type); -- Output_File_Type -- exceptions Status_Error : exception renames IO_Exceptions.Status_Error; Mode_Error : exception renames IO_Exceptions.Mode_Error; Name_Error : exception renames IO_Exceptions.Name_Error; Use_Error : exception renames IO_Exceptions.Use_Error; Device_Error : exception renames IO_Exceptions.Device_Error; End_Error : exception renames IO_Exceptions.End_Error; Data_Error : exception renames IO_Exceptions.Data_Error; private -- "Dynamic_Predicate => Mode (File) = In_File" is unsuitable for -- Input_File_Type, because Mode (File) returns Append_File for that -- opened as Inout_File by Direct_IO or Storage_Mapped_IO. function Is_Readable (File : File_Type) return Boolean; package Controlled is type File_Type is limited private; function Reference (File : Stream_IO.File_Type) return not null access Naked_Stream_IO.Non_Controlled_File_Type; pragma Inline (Reference); private type File_Type is limited new Finalization.Limited_Controlled with record Stream : aliased Naked_Stream_IO.Non_Controlled_File_Type; end record; overriding procedure Finalize (Object : in out File_Type); end Controlled; type File_Type is new Controlled.File_Type; end Ada.Streams.Stream_IO;
source/nodes/program-nodes-variant_vectors.ads
reznikmm/gela
0
23833
<gh_stars>0 -- SPDX-FileCopyrightText: 2019 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Nodes.Generic_Vectors; with Program.Elements.Variants; package Program.Nodes.Variant_Vectors is new Program.Nodes.Generic_Vectors (Program.Elements.Variants.Variant_Vector); pragma Preelaborate (Program.Nodes.Variant_Vectors);
oeis/126/A126986.asm
neoneye/loda-programs
11
244424
; A126986: Expansion of 1/(1+4*x*c(x)), c(x) the g.f. of Catalan numbers A000108. ; Submitted by <NAME> ; 1,-4,12,-40,124,-408,1272,-4176,13020,-42808,133096,-439344,1358872,-4514800,13853040,-46469280,140945820,-479312760,1430085000,-4958382960,14453014920,-51500944080,145230007440,-537922074720,1446902948184,-5662012752048,14228883685392,-60226310250976,137097352070320,-649709888025312,1277277868359904,-7139278380425536,11209981985980188,-80299194256775160,87088517291886024,-929038489053819888,479894769046382632,-11103501969636787216,-1229437156859674800,-137452891327654401760 mov $4,$0 add $0,1 lpb $0 sub $0,1 mov $3,$4 bin $3,$1 add $1,1 add $3,$2 mul $2,2 mul $3,6 sub $2,$3 add $4,1 lpe mov $0,$3 div $0,6
test/Succeed/Issue3666.agda
cruhland/agda
1,989
12004
<gh_stars>1000+ data Unit : Set where unit : Unit F : Unit → Set₁ F unit = Set data D (u : Unit) (f : F u) : Set where variable u : Unit f : F u d : D u f postulate P : {u : Unit} {f : F u} → D u f → Set p : P d p' : (u : Unit) (f : F u) (d : D u f) → P d p' u f d = p {u} {f} {d}
Driver/Socket/IRLAP/irlapStrings.asm
steakknife/pcgeos
504
14801
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved PROJECT: MODULE: FILE: irlapStrings.asm AUTHOR: <NAME>, Sep 29, 1994 REVISION HISTORY: Name Date Description ---- ---- ----------- SJ 9/29/94 Initial revision DESCRIPTION: This file contains strings for IRLAP driver. $Id: irlapStrings.asm,v 1.1 97/04/18 11:57:00 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ IrlapStrings segment lmem LMEM_TYPE_GENERAL ; ; Notifications ; mediaBusyStr chunk.char \ "Operation failed because there are other traffic in media", 0 primaryConflictStr chunk.char \ "Connection failed because there is another primary out there", 0 connectFailed chunk.char \ "Aim your gun straight!", 0 ; ; Driver name ; EC< serialDriverName chunk.TCHAR "serialec.geo", 0 > NEC< serialDriverName chunk.TCHAR "serial.geo", 0 > ; ; Temp strings ; irlapDomainName chunk.char \ "irlap", 0 ; ; Address dialog ; irlapConnectionAddressDialog chunk.char \ "Select new address for CONNECTION",0 irlapDatagramAddressDialog chunk.char \ "Select new address for DATAGRAM",0 ; ; .INI file categories and keywords ; irlapCategory chunk.char \ "irlap ", 0 if _SOCKET_INTERFACE addressKeyword chunk.char \ "address", 0 defaultAddressStr chunk.char \ "UNKNOWN", 0 endif portKeyword chunk.char \ "port", 0 ; ; Connection parameters ; baudrateKeyword chunk.char \ "baudRate", 0 maxTurnaroundKeyword chunk.char \ "maxTurnaround", 0 dataSizeKeyword chunk.char \ "dataSize", 0 windowSizeKeyword chunk.char \ "windowSize", 0 numBOFsKeyword chunk.char \ "numBOFs", 0 minTurnaroundKeyword chunk.char \ "minTurnaround", 0 linkDisconnectKeyword chunk.char \ "linkDisconnect", 0 IrlapStrings ends
week_08/ProgramFlow/FibonacciSeries/FibonacciSeries.asm
DaviNakamuraCardoso/nand2tetris
0
164387
<gh_stars>0 @256 D=A @SP M=D @300 D=A @LCL M=D @400 D=A @ARG M=D @3000 D=A @THIS M=D @3010 D=A @THAT M=D // // This file is part of www.nand2tetris.org // // and the book "The Elements of Computing Systems" // // by <NAME> Schocken, MIT Press. // // File name: projects/08/ProgramFlow/FibonacciSeries/FibonacciSeries.vm // // // Puts the first argument[0] elements of the Fibonacci series // // in the memory, starting in the address given in argument[1]. // // Argument[0] and argument[1] are initialized by the test script // // before this code starts running. // // push argument 1 @1 D=A @ARG A=D+M D=M @SP A=M M=D @SP M=M+1 // pop pointer 1 // that = argument[1] @SP M=M-1 A=M D=M @THAT M=D // // push constant 0 @0 D=A @SP A=M M=D @SP M=M+1 // pop that 0 // first element in the series = 0 @0 D=A @THAT D=M+D @temp M=D @SP M=M-1 A=M D=M @temp A=M M=D // push constant 1 @1 D=A @SP A=M M=D @SP M=M+1 // pop that 1 // second element in the series = 1 @1 D=A @THAT D=M+D @temp M=D @SP M=M-1 A=M D=M @temp A=M M=D // // push argument 0 @0 D=A @ARG A=D+M D=M @SP A=M M=D @SP M=M+1 // push constant 2 @2 D=A @SP A=M M=D @SP M=M+1 // sub @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M-D @SP M=M+1 // pop argument 0 // num_of_elements -= 2 (first 2 elements are set) @0 D=A @ARG D=M+D @temp M=D @SP M=M-1 A=M D=M @temp A=M M=D // // label MAIN_LOOP_START (MAIN_LOOP_START) // // push argument 0 @0 D=A @ARG A=D+M D=M @SP A=M M=D @SP M=M+1 // if-goto COMPUTE_ELEMENT // if num_of_elements > 0, goto COMPUTE_ELEMENT @SP M=M-1 A=M D=M @COMPUTE_ELEMENT D;JNE // goto END_PROGRAM // otherwise, goto END_PROGRAM @END_PROGRAM 0;JMP // // label COMPUTE_ELEMENT (COMPUTE_ELEMENT) // // push that 0 @0 D=A @THAT A=D+M D=M @SP A=M M=D @SP M=M+1 // push that 1 @1 D=A @THAT A=D+M D=M @SP A=M M=D @SP M=M+1 // add @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M+D @SP M=M+1 // pop that 2 // that[2] = that[0] + that[1] @2 D=A @THAT D=M+D @temp M=D @SP M=M-1 A=M D=M @temp A=M M=D // // push pointer 1 @THAT D=M @SP A=M M=D @SP M=M+1 // push constant 1 @1 D=A @SP A=M M=D @SP M=M+1 // add @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M+D @SP M=M+1 // pop pointer 1 // that += 1 @SP M=M-1 A=M D=M @THAT M=D // // push argument 0 @0 D=A @ARG A=D+M D=M @SP A=M M=D @SP M=M+1 // push constant 1 @1 D=A @SP A=M M=D @SP M=M+1 // sub @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M-D @SP M=M+1 // pop argument 0 // num_of_elements-- @0 D=A @ARG D=M+D @temp M=D @SP M=M-1 A=M D=M @temp A=M M=D // // goto MAIN_LOOP_START @MAIN_LOOP_START 0;JMP // // label END_PROGRAM (END_PROGRAM) (END) @END 0;JMP
test/Compiler/simple/ModuleArgs.agda
shlevy/agda
7
4322
<filename>test/Compiler/simple/ModuleArgs.agda module ModuleArgs where open import Common.Nat open import Common.IO open import Common.Unit module X (y : Nat) where addTo : Nat -> Nat addTo x = y + x open X 23 -- should return 35 main : IO Unit main = printNat (addTo 12)
ExtendedGCD/main.adb
oddek/DCS3101-1_Cybersecurity
0
4131
<filename>ExtendedGCD/main.adb with Ada.Text_IO; use ADA.Text_IO; procedure main is procedure extended_gcd(a : Integer; b : Integer) is old_r : Integer := a; r : Integer := b; old_s : Integer := 1; s : Integer := 0; old_t : Integer := 0; t : Integer := 1; quotient : Integer; temp : Integer; begin while r /= 0 loop quotient := old_r / r; temp := r; r := old_r - quotient * temp; old_r := temp; temp := s; s := old_s - quotient * temp; old_s := temp; temp := t; t := old_t - quotient * temp; old_t := temp; end loop; Put_Line("Bezuouts Coefficients: " & Integer'Image(old_s) & ", " &Integer'Image(old_t)); Put_Line("GCD: " & Integer'Image(old_r)); Put_Line("Quotients by the GCD: " & Integer'Image(t) & ", " &Integer'Image(s)); end extended_gcd; begin extended_gcd(35,6); end main;
arch/ARM/Nordic/svd/nrf51/nrf51_svd-aar.ads
bosepchuk/Ada_Drivers_Library
6
19988
<reponame>bosepchuk/Ada_Drivers_Library -- Copyright (c) 2013, Nordic Semiconductor ASA -- 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 Nordic Semiconductor ASA 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. -- -- This spec has been automatically generated from nrf51.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NRF51_SVD.AAR is pragma Preelaborate; --------------- -- Registers -- --------------- -- Enable interrupt on END event. type INTENSET_END_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENSET_END_Field use (Disabled => 0, Enabled => 1); -- Enable interrupt on END event. type INTENSET_END_Field_1 is ( -- Reset value for the field Intenset_End_Field_Reset, -- Enable interrupt on write. Set) with Size => 1; for INTENSET_END_Field_1 use (Intenset_End_Field_Reset => 0, Set => 1); -- Enable interrupt on RESOLVED event. type INTENSET_RESOLVED_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENSET_RESOLVED_Field use (Disabled => 0, Enabled => 1); -- Enable interrupt on RESOLVED event. type INTENSET_RESOLVED_Field_1 is ( -- Reset value for the field Intenset_Resolved_Field_Reset, -- Enable interrupt on write. Set) with Size => 1; for INTENSET_RESOLVED_Field_1 use (Intenset_Resolved_Field_Reset => 0, Set => 1); -- Enable interrupt on NOTRESOLVED event. type INTENSET_NOTRESOLVED_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENSET_NOTRESOLVED_Field use (Disabled => 0, Enabled => 1); -- Enable interrupt on NOTRESOLVED event. type INTENSET_NOTRESOLVED_Field_1 is ( -- Reset value for the field Intenset_Notresolved_Field_Reset, -- Enable interrupt on write. Set) with Size => 1; for INTENSET_NOTRESOLVED_Field_1 use (Intenset_Notresolved_Field_Reset => 0, Set => 1); -- Interrupt enable set register. type INTENSET_Register is record -- Enable interrupt on END event. END_k : INTENSET_END_Field_1 := Intenset_End_Field_Reset; -- Enable interrupt on RESOLVED event. RESOLVED : INTENSET_RESOLVED_Field_1 := Intenset_Resolved_Field_Reset; -- Enable interrupt on NOTRESOLVED event. NOTRESOLVED : INTENSET_NOTRESOLVED_Field_1 := Intenset_Notresolved_Field_Reset; -- unspecified Reserved_3_31 : HAL.UInt29 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for INTENSET_Register use record END_k at 0 range 0 .. 0; RESOLVED at 0 range 1 .. 1; NOTRESOLVED at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; -- Disable interrupt on ENDKSGEN event. type INTENCLR_END_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENCLR_END_Field use (Disabled => 0, Enabled => 1); -- Disable interrupt on ENDKSGEN event. type INTENCLR_END_Field_1 is ( -- Reset value for the field Intenclr_End_Field_Reset, -- Disable interrupt on write. Clear) with Size => 1; for INTENCLR_END_Field_1 use (Intenclr_End_Field_Reset => 0, Clear => 1); -- Disable interrupt on RESOLVED event. type INTENCLR_RESOLVED_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENCLR_RESOLVED_Field use (Disabled => 0, Enabled => 1); -- Disable interrupt on RESOLVED event. type INTENCLR_RESOLVED_Field_1 is ( -- Reset value for the field Intenclr_Resolved_Field_Reset, -- Disable interrupt on write. Clear) with Size => 1; for INTENCLR_RESOLVED_Field_1 use (Intenclr_Resolved_Field_Reset => 0, Clear => 1); -- Disable interrupt on NOTRESOLVED event. type INTENCLR_NOTRESOLVED_Field is ( -- Interrupt disabled. Disabled, -- Interrupt enabled. Enabled) with Size => 1; for INTENCLR_NOTRESOLVED_Field use (Disabled => 0, Enabled => 1); -- Disable interrupt on NOTRESOLVED event. type INTENCLR_NOTRESOLVED_Field_1 is ( -- Reset value for the field Intenclr_Notresolved_Field_Reset, -- Disable interrupt on write. Clear) with Size => 1; for INTENCLR_NOTRESOLVED_Field_1 use (Intenclr_Notresolved_Field_Reset => 0, Clear => 1); -- Interrupt enable clear register. type INTENCLR_Register is record -- Disable interrupt on ENDKSGEN event. END_k : INTENCLR_END_Field_1 := Intenclr_End_Field_Reset; -- Disable interrupt on RESOLVED event. RESOLVED : INTENCLR_RESOLVED_Field_1 := Intenclr_Resolved_Field_Reset; -- Disable interrupt on NOTRESOLVED event. NOTRESOLVED : INTENCLR_NOTRESOLVED_Field_1 := Intenclr_Notresolved_Field_Reset; -- unspecified Reserved_3_31 : HAL.UInt29 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for INTENCLR_Register use record END_k at 0 range 0 .. 0; RESOLVED at 0 range 1 .. 1; NOTRESOLVED at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; subtype STATUS_STATUS_Field is HAL.UInt4; -- Resolution status. type STATUS_Register is record -- Read-only. The IRK used last time an address was resolved. STATUS : STATUS_STATUS_Field; -- unspecified Reserved_4_31 : HAL.UInt28; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for STATUS_Register use record STATUS at 0 range 0 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; -- Enable AAR. type ENABLE_ENABLE_Field is ( -- Disabled AAR. Disabled, -- Enable AAR. Enabled) with Size => 2; for ENABLE_ENABLE_Field use (Disabled => 0, Enabled => 3); -- Enable AAR. type ENABLE_Register is record -- Enable AAR. ENABLE : ENABLE_ENABLE_Field := NRF51_SVD.AAR.Disabled; -- unspecified Reserved_2_31 : HAL.UInt30 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for ENABLE_Register use record ENABLE at 0 range 0 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype NIRK_NIRK_Field is HAL.UInt5; -- Number of Identity root Keys in the IRK data structure. type NIRK_Register is record -- Number of Identity root Keys in the IRK data structure. NIRK : NIRK_NIRK_Field := 16#1#; -- unspecified Reserved_5_31 : HAL.UInt27 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for NIRK_Register use record NIRK at 0 range 0 .. 4; Reserved_5_31 at 0 range 5 .. 31; end record; -- Peripheral power control. type POWER_POWER_Field is ( -- Module power disabled. Disabled, -- Module power enabled. Enabled) with Size => 1; for POWER_POWER_Field use (Disabled => 0, Enabled => 1); -- Peripheral power control. type POWER_Register is record -- Peripheral power control. POWER : POWER_POWER_Field := NRF51_SVD.AAR.Disabled; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for POWER_Register use record POWER at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Accelerated Address Resolver. type AAR_Peripheral is record -- Start resolving addresses based on IRKs specified in the IRK data -- structure. TASKS_START : aliased HAL.UInt32; -- Stop resolving addresses. TASKS_STOP : aliased HAL.UInt32; -- Address resolution procedure completed. EVENTS_END : aliased HAL.UInt32; -- Address resolved. EVENTS_RESOLVED : aliased HAL.UInt32; -- Address not resolved. EVENTS_NOTRESOLVED : aliased HAL.UInt32; -- Interrupt enable set register. INTENSET : aliased INTENSET_Register; -- Interrupt enable clear register. INTENCLR : aliased INTENCLR_Register; -- Resolution status. STATUS : aliased STATUS_Register; -- Enable AAR. ENABLE : aliased ENABLE_Register; -- Number of Identity root Keys in the IRK data structure. NIRK : aliased NIRK_Register; -- Pointer to the IRK data structure. IRKPTR : aliased HAL.UInt32; -- Pointer to the resolvable address (6 bytes). ADDRPTR : aliased HAL.UInt32; -- Pointer to a "scratch" data area used for temporary storage during -- resolution. A minimum of 3 bytes must be reserved. SCRATCHPTR : aliased HAL.UInt32; -- Peripheral power control. POWER : aliased POWER_Register; end record with Volatile; for AAR_Peripheral use record TASKS_START at 16#0# range 0 .. 31; TASKS_STOP at 16#8# range 0 .. 31; EVENTS_END at 16#100# range 0 .. 31; EVENTS_RESOLVED at 16#104# range 0 .. 31; EVENTS_NOTRESOLVED at 16#108# range 0 .. 31; INTENSET at 16#304# range 0 .. 31; INTENCLR at 16#308# range 0 .. 31; STATUS at 16#400# range 0 .. 31; ENABLE at 16#500# range 0 .. 31; NIRK at 16#504# range 0 .. 31; IRKPTR at 16#508# range 0 .. 31; ADDRPTR at 16#510# range 0 .. 31; SCRATCHPTR at 16#514# range 0 .. 31; POWER at 16#FFC# range 0 .. 31; end record; -- Accelerated Address Resolver. AAR_Periph : aliased AAR_Peripheral with Import, Address => System'To_Address (16#4000F000#); end NRF51_SVD.AAR;
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/assert1.adb
best08618/asylo
7
6805
<filename>gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/assert1.adb -- { dg-do run } -- { dg-options "-gnatws" } pragma Assertion_Policy (Check); with Text_IO; use Text_IO; procedure assert1 is type p1 is array (1 .. 113) of Boolean; pragma Pack (p1); type p2 is array (1 .. 13) of Boolean; pragma Pack (p2); type p3 is array (1 .. 113) of Boolean; pragma Pack (p3); for p3'size use 113; type p4 is array (1 .. 13) of Boolean; pragma Pack (p4); for p4'size use 13; v1 : p1; v2 : p2; v3 : p3; v4 : p4; begin pragma Assert (p1'Size = 120); pragma Assert (p2'Size = 13); pragma Assert (p3'Size = 113); pragma Assert (p4'Size = 13); pragma Assert (p1'Value_Size = 120); pragma Assert (p2'Value_Size = 13); pragma Assert (p3'Value_Size = 113); pragma Assert (p4'Value_Size = 13); pragma Assert (p1'Object_Size = 120); pragma Assert (p2'Object_Size = 16); pragma Assert (p3'Object_Size = 120); pragma Assert (p4'Object_Size = 16); pragma Assert (v1'Size = 120); pragma Assert (v2'Size = 16); pragma Assert (v3'Size = 120); pragma Assert (v4'Size = 16); null; end;
programs/oeis/288/A288998.asm
neoneye/loda
22
167918
<filename>programs/oeis/288/A288998.asm<gh_stars>10-100 ; A288998: Positions of 0 in A288997; complement of A288999. ; 1,2,4,5,6,8,9,11,12,13,15,16,18,19,21,22,23,25,26,28,29,30,32,33,35,36,38,39,40,42,43,45,46,47,49,50,52,53,54,56,57,59,60,62,63,64,66,67,69,70,71,73,74,76,77,79,80,81,83,84,86,87,88,90,91,93,94,95,97,98,100,101,103,104,105,107,108,110,111,112,114,115,117,118,120,121,122,124,125,127,128,129,131,132,134,135,137,138,139,141 add $0,3 mov $1,$0 pow $1,2 lpb $1 sub $1,$0 add $0,1 sub $1,$0 lpe sub $0,3
programs/oeis/302/A302405.asm
karttu/loda
0
176310
<reponame>karttu/loda ; A302405: Total domination number of the n-prism graph. ; 0,1,2,2,4,4,4,5,6,6,8,8,8,9,10,10,12,12,12,13,14,14,16,16,16,17,18,18,20,20,20,21,22,22,24,24,24,25,26,26,28,28,28,29,30,30,32,32,32,33,34,34,36,36,36,37,38,38,40,40,40,41,42,42,44,44,44,45,46,46,48,48,48,49,50,50,52,52,52,53,54,54,56,56,56,57,58,58,60,60,60,61,62,62,64,64,64,65,66,66,68,68,68,69,70,70,72,72,72,73,74,74,76,76,76,77,78,78,80,80,80,81,82,82,84,84,84,85,86,86,88,88,88,89,90,90,92,92,92,93,94,94,96,96,96,97,98,98,100,100,100,101,102,102,104,104,104,105,106,106,108,108,108,109,110,110,112,112,112,113,114,114,116,116,116,117,118,118,120,120,120,121,122,122,124,124,124,125,126,126,128,128,128,129,130,130,132,132,132,133,134,134,136,136,136,137,138,138,140,140,140,141,142,142,144,144,144,145,146,146,148,148,148,149,150,150,152,152,152,153,154,154,156,156,156,157,158,158,160,160,160,161,162,162,164,164,164,165,166,166 mov $4,$0 lpb $0,1 add $1,4 mov $2,$4 trn $2,6 mov $3,2 trn $3,$4 add $5,2 sub $4,$5 mov $0,$4 trn $0,1 mov $4,$2 mov $5,0 add $6,$3 lpe sub $1,2 trn $1,$6
oeis/070/A070333.asm
neoneye/loda-programs
11
25602
; A070333: Expansion of (1+x)*(1-x+x^2)/( (1-x)^4*(1+x+x^2) ). ; 1,3,6,12,21,33,50,72,99,133,174,222,279,345,420,506,603,711,832,966,1113,1275,1452,1644,1853,2079,2322,2584,2865,3165,3486,3828,4191,4577,4986,5418,5875,6357,6864,7398,7959,8547,9164,9810,10485,11191,11928,12696,13497,14331,15198,16100,17037,18009,19018,20064,21147,22269,23430,24630,25871,27153,28476,29842,31251,32703,34200,35742,37329,38963,40644,42372,44149,45975,47850,49776,51753,53781,55862,57996,60183,62425,64722,67074,69483,71949,74472,77054,79695,82395,85156,87978,90861,93807,96816,99888 lpb $0 mov $2,$0 seq $2,183859 ; a(n) = n - 1 + ceiling((n^2)/3); complement of A183858. sub $2,$0 sub $0,1 add $1,$2 lpe add $1,1 mov $0,$1
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca_notsx.log_21829_1029.asm
ljhsiun2/medusa
9
178651
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x1cf51, %rsi nop nop inc %r13 mov $0x6162636465666768, %r11 movq %r11, (%rsi) nop nop nop nop nop xor %r13, %r13 lea addresses_WT_ht+0x17e9, %rdx clflush (%rdx) add $48050, %r15 movw $0x6162, (%rdx) nop nop nop xor %rdx, %rdx lea addresses_normal_ht+0x28b1, %rsi lea addresses_WT_ht+0x150e9, %rdi nop dec %rax mov $106, %rcx rep movsw nop and %r15, %r15 lea addresses_WT_ht+0x32e9, %rsi lea addresses_WT_ht+0x1218a, %rdi nop nop dec %rdx mov $56, %rcx rep movsb nop nop nop nop nop and $13072, %rsi lea addresses_WT_ht+0xc69, %rsi nop and %rax, %rax movl $0x61626364, (%rsi) nop nop nop nop nop xor %r11, %r11 lea addresses_A_ht+0x15221, %rsi lea addresses_normal_ht+0x9ef, %rdi nop nop sub $50441, %r11 mov $93, %rcx rep movsl nop nop nop nop cmp $3970, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r9 push %rax push %rcx push %rdi // Faulty Load lea addresses_WC+0x12fe9, %rax sub $19533, %r9 movb (%rax), %r11b lea oracles, %rax and $0xff, %r11 shlq $12, %r11 mov (%rax,%r11,1), %r11 pop %rdi pop %rcx pop %rax pop %r9 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_WC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'38': 21829} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
arbitrary/extended_real.adb
jscparker/math_packages
30
16183
<gh_stars>10-100 ----------------------------------------------------------------------- -- package body Extended_Real, extended precision floating point arithmetic -- Copyright (C) 2008-2018 <NAME> -- -- 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. --------------------------------------------------------------------------- -- Internally the extended numbers are stored in such a way that the -- value of e_Real number X is -- -- Max -- X = Radix**Exp * SUM {Radix**(-I) * Digit(I)}. -- I=0 -- -- Externally, the user sees e_Real (via the Exponent, and Fraction -- attribute functions) as tho' it were normalized. In other words, the -- value of X is -- -- Max -- X = Radix**Exp_n * SUM {Radix**(-I-1) * Digit(I)} -- I=0 -- -- Exp_n is called the "normalized" exponent. If Exp_n is the normalized exponent -- then, say, a binary number would be written: -- -- 0.111011010001 * 2**(Exp_n). -- -- In other words the first binary digit in the mantissa is of power 2**(-1). -- It is important to know this because the function Real'Exponent(x) returns -- the *normalized* exponent, and the function Real'Fraction(x) returns -- x * 2**(-Exp_n) where Exp_n is the normalized exponent. So in the above case, -- 'Fraction would return 0.111011010001. -- Also, in normalized form, the first binary digit of the mantissa is always -- non-zero. package body Extended_Real is Disable_Program_Error_Tests : constant Boolean := False; -- A few assertions and the like. ---------------------------------------- -- Shift_Right_2x_No_of_Bits_in_Radix -- ---------------------------------------- function Shift_Right_2x_No_of_Bits_in_Radix (Digit : in Digit_Type) return Digit_Type is begin -- Works in general, but use only for flt types: --return Digit_Type (Real'Floor (Real (Digit) * Inverse_Radix_Squared)); return Digit / 2**(2*No_of_Bits_in_Radix); end Shift_Right_2x_No_of_Bits_in_Radix; pragma Inline (Shift_Right_2x_No_of_Bits_in_Radix); ------------------------------------- -- Shift_Right_No_of_Bits_in_Radix -- ------------------------------------- function Shift_Right_No_of_Bits_in_Radix (Digit : in Digit_Type) return Digit_Type is begin -- Works in general, but use only for flt types: --return Digit_Type (Real'Floor (Real (Digit) * Inverse_Radix)); return Digit / 2**No_of_Bits_in_Radix; end Shift_Right_No_of_Bits_in_Radix; pragma Inline (Shift_Right_No_of_Bits_in_Radix); ----------------- -- Digit_Floor -- ----------------- -- Used by "/" and Make_Extended: function Digit_Floor (X : Real) return Digit_Type is begin return Digit_Type (Real'Floor (X)); end Digit_Floor; pragma Assert (Real'Machine_Mantissa > No_Of_Bits_In_Radix); -- ie 53 > 30 pragma Inline (Digit_Floor); ---------------------------------- -- Minimum_No_Of_Digits_Allowed -- ---------------------------------- -- Return setting of the constant Min_No_Of_Digits. -- function Minimum_No_Of_Digits_Allowed return e_Integer is begin return Min_No_Of_Digits; end Minimum_No_Of_Digits_Allowed; ---------------------------- -- Number_Of_Guard_Digits -- ---------------------------- -- Return setting of the constant No_Of_Guard_Digits. -- function Number_Of_Guard_Digits return e_Integer is begin return No_Of_Guard_Digits; end Number_Of_Guard_Digits; -- SECTION IV. -- -- Ada94 attributes. More information on the machine model is given -- above in the introduction. --------------------------- -- e_Real_Machine_Rounds -- --------------------------- function e_Real_Machine_Rounds return Boolean is begin return False; end e_Real_Machine_Rounds; ------------------------------ -- e_Real_Machine_Overflows -- ------------------------------ function e_Real_Machine_Overflows return Boolean is begin return False; end e_Real_Machine_Overflows; ------------------------- -- e_Real_Signed_Zeros -- ------------------------- function e_Real_Signed_Zeros return Boolean is begin return False; end e_Real_Signed_Zeros; ------------------- -- e_Real_Denorm -- ------------------- function e_Real_Denorm return Boolean is begin return False; end e_Real_Denorm; ------------------------- -- e_Real_Machine_Emax -- ------------------------- function e_Real_Machine_Emax return e_Integer is begin return Max_Exponent; end e_Real_Machine_Emax; ------------------------- -- e_Real_Machine_Emin -- ------------------------- function e_Real_Machine_Emin return e_Integer is begin return Min_Exponent; end e_Real_Machine_Emin; ----------------------------- -- e_Real_Machine_Mantissa -- ----------------------------- -- Number of digits in machine mantissa. function e_Real_Machine_Mantissa return e_Integer is begin return Mantissa'Length; end e_Real_Machine_Mantissa; -------------------------- -- e_Real_Machine_Radix -- -------------------------- function e_Real_Machine_Radix return Real is begin return Real_Radix; end e_Real_Machine_Radix; ---------------------------- -- e_Real_Machine_Epsilon -- ---------------------------- function e_Real_Machine_Epsilon return e_Real is begin return e_Real_Model_Epsilon_1; end e_Real_Machine_Epsilon; -------------------------- -- e_Real_Model_Epsilon -- -------------------------- function e_Real_Model_Epsilon return e_Real is begin return e_Real_Model_Epsilon_2; end e_Real_Model_Epsilon; ---------------------------- -- e_Real_Model_Epsilon_1 -- ---------------------------- -- 1 unit in the larger of the 2 guard digits. function e_Real_Model_Epsilon_1 return e_Real is Result : e_Real; -- equals Zero begin Result.Is_Zero := False; Result.Digit (0) := Digit_One; -- 1 here with Exp=0 => Eps=radix**(-1) Result.Exp := -(e_Real_Machine_Mantissa-1); return Result; end e_Real_Model_Epsilon_1; ---------------------------- -- e_Real_Model_Epsilon_2 -- ---------------------------- -- Guard_Digits = 2 always; assume neither of them is correct. -- if there's 3 digits of Radix 2^30 then eps is 2^(-30). -- if there's 4 digits of Radix 2^30 then eps is 2^(-60). -- if there's 5 digits of Radix 2^30 then eps is 2^(-90) or ~ 10**(-30). function e_Real_Model_Epsilon_2 return e_Real is Result : e_Real; -- equals Zero begin Result.Is_Zero := False; Result.Digit (0) := Digit_One; -- 1 here with Exp=0 => Eps=radix**(-1) Result.Exp := -(e_Real_Machine_Mantissa-2); return Result; end e_Real_Model_Epsilon_2; -------------- -- Exponent -- -------------- -- For every value x of a floating point type T, the normalized exponent -- of x is defined as follows: -- - the normalized exponent of zero is (by convention) zero; -- - for nonzero x, the normalized exponent of x is the unique -- -- k-1 k -- integer k such that T'Machine_Radix <= |x| < T'Machine_Radix . -- -- For example, if x = 0.1101011 * 2**1 then k = 1 since -- 2**0 <= x < 2**1. If X = 0.100000 * 2**1 then 2**0 = x < 2**1. -- -- BY CONVENTION, the normalized exponent of 0 is 0. (Internally it ain't.) function Exponent (X : e_Real) return e_Integer is Normalized_Exponent : constant e_Integer := X.Exp + 1; begin if X.Is_Zero then return 0; else return Normalized_Exponent; end if; -- proper choice because internal form of e_Real is not -- normalized; internally, Exp is smaller than the normalized exp -- by 1, because the internal mantissa is larger by a factor -- of Radix than the normalized mantissa. end Exponent; ------------------ -- Leading_Part -- ------------------ -- Let k be the normalized exponent of x. The function Leading_Part(x) -- yields the value -- -- k-r k-r -- - |x/T'Machine_Radix |*T'Machine_Radix , -- when x is nonnegative and r is positive; -- k-r k-r -- - |x/T'Machine_Radix |*T'Machine_Radix , -- when x is negative and r is positive. -- -- Constraint_Error is raised when r is zero or negative. -- A zero result, which can only occur when x is zero, has -- the sign of X. -- Returns the leading digits of X in the range 0..Radix_Digits-1, -- regardless of sign of X. Other digits are set to 0.0. The exponent -- is unchanged. Only X = Zero returns Zero. Not sure about infinity. -- Makes sense that Leading_Part of inf is inf. -- Notice assume Digit_Index'Last = Ultimate digit. The results are -- consistant with a dynamic Digit_Index'Last, just a little slower. -- function Leading_Part (X : e_Real; Radix_Digits : e_Integer) return e_Real is No_Of_Digits : constant e_Integer := Ultimate_Digit + 1; Result : e_Real := X; begin -- By convention: if Radix_Digits <= 0 then raise Constraint_Error with "Must have Radix_Digits > 0."; end if; if X.Is_Zero then return Zero; end if; if X.Is_Infinite then return X; end if; if Radix_Digits >= No_Of_Digits then return X; end if; -- So now Radix_Digits < No_Of_Digits which implies that -- Radix_Digits <= Ultimate_Digit for I in Digit_Index range Radix_Digits .. Ultimate_Digit loop Result.Digit (I) := Digit_Zero; end loop; -- The above uses the fact that Digit_Index starts at 0. return Result; end Leading_Part; -------------- -- Fraction -- -------------- -- -k -- The function yields the value x*T'Machine_Radix , where -- k is the normalized exponent of x. A zero result, which -- can only occur when x is zero, has the sign of X. -- Not sure about inf, so raise contraint error, because the -- user may make assumptions about the size of the exponent returned -- by Exponent. -- function Fraction (X : e_Real) return e_Real is X2 : e_Real := X; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then raise Constraint_Error with "Cannot take Fraction of inf."; end if; X2.Exp := -1; -- Proper choice because format of e_Real -- is not normalized. The effect of the -1 is -- to shift the internal format down to the normalized format. return X2; end Fraction; ------------- -- Compose -- ------------- -- S'Compose (X, Exp) = Fraction (X) * Machine_Radix ** Exp -- -- e-k -- Let v be the value X*T'Machine_Radix , where k is the -- normalized exponent of X. If v is a machine number of -- the type T, or if |v|GT'Model_Small, the function yields -- v; otherwise, it yields either one of the machine -- numbers of the type T adjacent to v. Constraint_Error -- is optionally raised if v is outside the base range of -- S. A zero result has the sign of Fraction when S'Signed_ -- Zeros is True. -- function Compose (Fraction : e_Real; Exponent : e_Integer) return e_Real is X2 : e_Real := Fraction; begin if Fraction.Is_Zero then return Zero; end if; if Fraction.Is_Infinite then raise Constraint_Error with "Cannot compose inf."; end if; X2.Exp := Exponent - 1; -- The minus 1 comes from the Fraction(X) operation. if X2.Exp < Min_Exponent or else X2.Exp > Max_Exponent then raise Constraint_Error with "Exponent out of range in Compose operation."; end if; return X2; end Compose; ------------- -- Scaling -- ------------- -- S'Scaling (X, Exp) -- Exp -- Let v be the value X*T'Machine_Radix . If v is a -- machine number of the type T, or if |v|GT'Model_Small, -- the function yields v; otherwise, it yields either one -- of the machine numbers of the type T adjacent to v. -- Constraint_Error is optionally raised if v is outside -- the base range of S. A zero result has the sign of X -- when S'Signed_Zeros is True. -- function Scaling (X : e_Real; Adjustment : e_Integer) return e_Real is X2 : e_Real := X; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then raise Constraint_Error with "Cannot scale inf."; end if; X2.Exp := X.Exp + Adjustment; if X2.Exp < Min_Exponent or else X2.Exp > Max_Exponent then raise Constraint_Error with "Exp out of range in Scaling operation."; end if; return X2; end Scaling; ---------------- -- Truncation -- ---------------- -- Strip off fraction for both + and - numbers. -- This sets all digits beyond the decimal point to 0.0. -- The function yields the value [x] when X > 0.0. ([x] by defn -- is floor: largest int less than or equal to x.) When x is zero, -- the result has the sign of X; a zero result otherwise has a -- positive sign. When X < 0.0, then it's [x]+1 unless [x] = x. -- Notice assume Digit_Index'Last = Ultimate_Digit. function Truncation (X : e_Real) return e_Real is Result : e_Real; First_Zeroed_Out_Digit : Digit_Index; No_Of_Digits : constant e_Integer := Ultimate_Digit + 1; No_Of_Digits_To_Keep : constant e_Integer := X.Exp + 1; -- Normalized Exponent of X. Remember, if X.Exp = 0,then X has one -- non-zero digit that's >= 1.0. So (Exp + 1)=1 means keep 1 digit begin if X.Is_Zero then return Zero; end if; if No_Of_Digits_To_Keep < 1 then return Zero; end if; -- According to the internal format of X, X.Exp = 0 means X >= 1.0. -- If X.Exp < 0 then X < 1.0. if X.Is_Infinite then return X; --Print_Text ("Cannot truncate inf."); --raise Constraint_Error; end if; if No_Of_Digits_To_Keep >= No_Of_Digits then return X; end if; -- So now No_Of_Digits_To_keep < No_Of_Digits which implies that -- No_Of_Digits_To_keep <= Ultimate_Digit -- Remember, Digit_Index starts at 0, and is a subtype of e_Integer. Result := X; First_Zeroed_Out_Digit := Digit_Index'First + No_Of_Digits_To_keep; for I in First_Zeroed_Out_Digit .. Ultimate_Digit loop Result.Digit (I) := Digit_Zero; end loop; return Result; end Truncation; ------------- -- Ceiling -- ------------- -- Let [x] = floor(x). -- Function yields the value [x]+1, unless [x] = x, in which case, -- function returns x. When x is zero, the -- result has the sign of x; a zero result otherwise has a -- negative sign when S'Signed_Zeros is True. function Ceiling (X : e_Real) return e_Real is Result : e_Real; Lowest_Order_Digit : e_Integer; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then return X; end if; -- Step 1. -- Special case, X.Exp < 0 so X < 1.0. Have to round 0.0 up to 1.0. -- We know X /= 0.0. if X.Exp < 0, then know |X| < 1.0. If -- X > 0.0, then result must be 1.0; if X < 0.0 then result -- is 0.0. So can save some time: if X.Exp < 0 then if X.Is_Positive then return One; else return Zero; end if; end if; -- Step 2. -- Now know that X.Exp >= 0. Have to do some work: Result := Truncation (X); if not X.Is_Positive then -- we're done by defn: Ceiling = Trunc. return Result; end if; -- Now know that X is positive. Must add one if Trunc(x) /= x. -- We also know that Result.Exp >= 0, by defn of Trunc. Lowest_Order_Digit := Result.Exp; if (Lowest_Order_Digit <= Ultimate_Digit) and then Result < X then if Result.Digit (Lowest_Order_Digit) < Digit_Radix_Minus_1 then Result.Digit (Lowest_Order_Digit) := Result.Digit (Lowest_Order_Digit) + Digit_One; else Result := Result - One; end if; end if; return Result; end Ceiling; ----------- -- Floor -- ----------- -- Function yields the value [x]. ([x] by defn is floor: largest int -- less than or equal to x.) This equals trunc(x) when x > 0.0, -- and = trunc(x)-1, when X < 0.0, unless Trunc(x) = x. When x = 0.0, -- result has the sign of x; a zero result otherwise has a -- negative sign when S'Signed_Zeros is True. function Floor (X : e_Real) return e_Real is Result : e_Real; Lowest_Order_Digit : e_Integer; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then return X; end if; -- Step 1. -- Special case, X.Exp < 0. -- Know X /= 0.0. if X.Exp < 0, then know |X| < 1.0. If then -- X > 0.0, then result must be 0.0; if X < 0.0 then result -- is -1.0. So can save some time: if X.Exp < 0 then if X.Is_Positive then return Zero; else return -One; end if; end if; -- Step 2. -- Now know that X.Exp >= 0. Have to do some work: Result := Truncation (X); if X.Is_Positive then -- we're done by defn: Floor = Trunc. return Result; end if; -- Now know that X is negative. Must subtract one if Trunc(x) > x. -- We also know that Result.Exp >= 0, by defn of Trunc, unless trunc -- returned Zero. (But it didn't cause X.Exp started out >= 0). Lowest_Order_Digit := Result.Exp; if (Lowest_Order_Digit <= Ultimate_Digit) and then Result > X then if Result.Digit (Lowest_Order_Digit) > Digit_Zero then Result.Digit (Lowest_Order_Digit) := Result.Digit (Lowest_Order_Digit) - Digit_One; else Result := Result - One; end if; end if; return Result; end Floor; ------------------------------------- -- Round_Away_Smallest_Guard_Digit -- ------------------------------------- -- Round away Digit_Index'Last function Round_Away_Smallest_Guard_Digit (X : e_Real) return e_Real is Result : e_Real := X; Penultimate : constant Digit_Index := Digit_Index'Last-1; begin if X.Digit(Digit_Index'Last) <= Half_Radix then Result.Digit (Digit_Index'Last) := Digit_Zero; else -- X is not Zero. Result.Digit (Digit_Index'Last) := Digit_Zero; if X.Digit(Penultimate) < Digit_Radix_Minus_1 then Result.Digit(Penultimate) := Result.Digit(Penultimate) + Digit_One; else if Result.Is_Positive then Result := Result + e_Real_Model_Epsilon_1; --1 unit in penultimate digit. else Result := Result - e_Real_Model_Epsilon_1; end if; end if; end if; return Result; end Round_Away_Smallest_Guard_Digit; ------------- -- Machine -- ------------- -- Rounds away smallest of the 2 guard digits of X. function Machine (X : e_Real) return e_Real is Y : e_Real; begin Y := Round_Away_Smallest_Guard_Digit (X); return Y; end Machine; --------------- -- Copy_Sign -- --------------- -- S'Copy_Sign denotes a function with the following specification: -- function S'Copy_Sign (Value, Sign : T) return T -- If the value of Value is nonzero, the function yields a -- result whose magnitude is that of Value and whose sign -- is that of Sign; otherwise, it yields the value zero. -- Constraint_Error is optionally raised if the result is -- outside the base range of S. A zero result has the sign -- of Sign when S'Signed_Zeros is True. -- function Copy_Sign (Value, Sign : e_Real) return e_Real is Result : e_Real := Value; begin if Value.Is_Zero then return Zero; end if; -- following holds even if Value is inf: Result.Is_Positive := Sign.Is_Positive; return Result; end Copy_Sign; -------------- -- Adjacent -- -------------- -- If t=x, the function yields x; otherwise, it yields the -- machine number of the type T adjacent to x in the -- direction of t, if that machine number exists. If the -- result would be outside the base range of S, Constraint_ -- Error is raised. When T'Signed_Zeros is True, a zero -- result has the sign of X. When t is zero, its sign has -- no bearing on the result. -- --function Adjacent (X, Towards : e_Real) return e_Real is --begin --end Adjacent; -------------- -- Rounding -- -------------- -- The function yields the integral value nearest to x, -- rounding away from zero if x lies exactly halfway -- between two integers. A zero result has the sign of X -- when S'Signed_Zeros is True. -- function Rounding (X : e_Real) return e_Real is Result : e_Real; Half : constant e_Real := +0.5; Del : e_Real; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then return X; end if; Result := Truncation (X); Del := Abs (X - Result); if not (Del < Half) then if X.Is_Positive then Result := Result + One; -- because Trunc chopped it toward zero else Result := Result - One; end if; end if; return Result; end Rounding; ----------------------- -- Unbiased_Rounding -- ----------------------- -- The function yields the integral value nearest to x, -- rounding toward the even integer if x lies exactly -- halfway between two integers. A zero result has the -- sign of X when S'Signed_Zeros is True. -- function Unbiased_Rounding (X : e_Real) return e_Real is Result : e_Real; Half : constant e_Real := +0.5; Del : e_Real; Least_Significant_Digit : e_Integer; begin if X.Is_Zero then return Zero; end if; if X.Is_Infinite then return X; end if; Result := Truncation (X); Del := Abs (X - Result); --if Del < Half then -- result is unmodified if Del > Half then if X.Is_Positive then Result := Result + One; -- because Trunc chopped it toward zero else Result := Result - One; end if; end if; if Are_Equal (Del, Half) then -- Must find out if Result (= Truncation (X) = int) is even or not. -- If it's not even, then add (or subtract) One as above. -- To find out, must examine lowest order bit of least significant -- digit. Least_Significant_Digit := Exponent (Result) - 1; -- If Least_Significant_Digit = 0 then Exponent (Result) = +1 cause -- it returns the normalized Exp. if (Least_Significant_Digit REM 2 = 1) then -- it's odd if X.Is_Positive then Result := Result + One; -- because Trunc chopped it toward zero else Result := Result - One; end if; end if; end if; return Result; end Unbiased_Rounding; --------------- -- Remainder -- --------------- -- Code, algorithm and comments from <NAME>. (Ada 9X Language study note.) -- Modified to use e_Real's, so errors my own. -- It does seem to work well .. much more accurate than the simple alternatives -- I tried for Sin, Cos arguments, (but that is all the testing I've done.) -- For nonzero y, let v be the value x-n*y, where n is the -- integer nearest to the exact value of x/y; if -- |n-x/y|=1/2, then n is chosen to be even. If v is a -- machine number of the type T, the function yields v; -- otherwise, it yields zero. Constraint_Error is raised -- if y is zero. A zero result always has a positive sign. function Remainder (X, Y : e_Real) return e_Real is Residue, Temp, Reducer, Reducer_Head, Reducer_Tail, N : e_Real; Abs_Y : constant e_Real := Abs (Y); -- See comments above about the possibility of overflow here on -- radix-complement machines. Scaled_Up, Negated : Boolean; CONST1 : constant e_Real := Scaling (One, e_Real_Machine_Emin + e_Real_Machine_Mantissa - 2); CONST2 : constant e_Real := Scaling (One, e_Real_Machine_Emin + e_Real_Machine_Mantissa - 1); begin if Y.Is_Zero then raise Constraint_Error with "Must have Y /= 0 in function Remainder."; end if; Residue := X; Negated := False; loop -- This loop is executed at most once more than the difference between -- the exponents of X and Y. if Copy_Sign (One, Residue) < Zero then -- The following two statements are to be executed when the sign of -- Residue is negative, that is, when Residue is less than zero or is -- a negative zero. Simply comparing Residue to zero is not good -- enough when T'Signed_Zeros is True. An actual implementation might -- instead examine the sign bit. In an implementation in which -- T'Signed_Zeros is False, the condition above can be simplified to -- Residue < 0.0. Residue := -Residue; Negated := not Negated; end if; -- At this point, Residue has a positive sign, and Negated records the -- parity of sign flippings that Residue has undergone. exit when Residue < Abs_Y; -- At this point, Residue is greater than or equal to Abs_Y. Its -- exponent is the same as, or greater than, that of Abs_Y. Reducer := Compose (Abs_Y, Exponent(Residue)); -- Reducer now has the fraction of Abs_Y and the exponent of Residue. -- Thus, it is a (possibly large) exact multiple of Abs_Y. if Reducer > Residue then -- Reducer is greater than Residue only when -- T'Fraction(Abs_Y) is greater than T'Fraction(Residue). -- Reduce its exponent by one. Reducer := Scaling(Reducer, -1); -- It can be proved that underflow cannot occur in the above scaling. -- At this point, 1.0 < Residue/Reducer < e_Real(T'Machine_Radix). N := Unbiased_Rounding (Residue / Reducer); -- Thus, 1.0 <= N <= e_Real (Machine_Radix). -- Now basically want to subtract N*Reducer from Residue exactly, -- but the product may have one too many digits to be represented -- exactly. That occurs when the exponent of N*Reducer exceeds that -- of Reducer; in the present case, that can happen for N as small as -- two. -- The following almost works: -- Reducer_Head := T'Leading_Part(Reducer, 1); -- Reducer_Tail := Reducer - Reducer_Head; -- Residue := (Residue - N*Reducer_Head) - N*Reducer_Tail; -- It fails only when Reducer is so small that underflow occurs when -- subtracting Reducer_Head from it. Note that this is only a problem -- when T'Denorm is False; when T'Denorm is True, the above suffices. if Reducer < CONST1 then -- Reducer is near the underflow threshold, and of course Residue -- is near Reducer. Scale both of them up by a sufficient amount -- to prevent underflow when subtracting Reducer_Head from Reducer; -- scale back down later. Residue := Scaling(Residue, e_Real_Machine_Mantissa); Reducer := Scaling(Reducer, e_Real_Machine_Mantissa); Scaled_Up := True; else Scaled_Up := False; end if; Reducer_Head := Leading_Part (Reducer, 1); Reducer_Tail := Reducer - Reducer_Head; -- Because cancellation occurs in the above subtraction, the result is -- exact. -- Now the subtraction can be performed in two stages. Residue := (Residue - N*Reducer_Head) - N*Reducer_Tail; -- In the present case, although N*Reducer can have too many digits to -- be representable, it cannot overflow. if Scaled_Up then -- Scale back down. Note that underflow can occur in rare -- circumstances here (i.e., when T'Denorm is False and the -- remainder is less than the underflow threshold, which requires -- that Y be near the underflow threshold and X be near a multiple -- of Y). The specification calls for zero to be returned, but -- T'Scaling might not return a zero when it underflows. If it -- does, and the zero is properly signed, the if-then-else below -- can be replaced by the else part (or by the equivalent -- multiplication or division, if it yields a properly signed -- zero on underflow). if Abs (Residue) < CONST2 then Residue := Copy_Sign (Zero, Residue); else Residue := Scaling (Residue, -E_Real_Machine_Mantissa); end if; end if; else -- This case is for Reducer <= Residue. -- At this point, 1.0 <= Residue/Reducer < e_Real(T'Machine_Radix). N := Unbiased_Rounding (Residue / Reducer); -- Thus, 1.0 <= N <= e_Real(T'Machine_Radix). -- Here, the technique for subtracting N*Reducer exactly from Residue -- is different. In the present case, N*Reducer may have one too many -- digits to be represented exactly only when the rounding was upward, -- hence (N-1.0)*Reducer must necessarily be representable. Also, -- N*Reducer could even overflow, but (N-1.0)*Reducer cannot. if N > One then -- The optimization represented by the above test is probably -- worthwhile. Residue := Residue - (N - One) * Reducer; end if; Residue := Residue - Reducer; -- The above subtraction can underflow when T'Denorm is False, in -- which case the desired result is zero. It is assumed that when -- subtraction underflows, it underflows to zero. end if; -- Residue may now be negative, but its absolute value is less than or -- equal to half of Reducer. end loop; -- At this point, Residue has a positive sign and a magnitude less than that -- of Abs_Y. If Residue is greater than half of Abs_Y, correct it by -- subtracting Abs_Y one more time. We do this without computing half of -- Abs_Y, which could underflow or be inexact. Temp := Residue - Abs_Y; -- The above can underflow. It is assumed here that underflow produces a -- zero result. Note that Temp now has a negative sign (a zero produced on -- underflow is presumably a negative zero when T'Signed_Zeros is True). if Temp + Residue > Zero then -- True only if Residue is greater than half of Abs_Y, or if the -- computation of Temp underflowed to zero. Note that the condition -- might, on some machines, be more efficiently evaluated as -- -Temp < Residue, or even as abs Temp < Residue. Residue := Temp; end if; -- The above step might even be slightly more efficiently evaluated as -- follows (here Temp is the negation of the value computed above and -- hence always has a positive sign): -- Temp := Abs_Y - Residue; -- if Temp < Residue then -- Residue := -Temp; -- end if; -- This version, which is clearly equivalent but harder to motivate, is -- used in the binary case at the end of this LSN. -- The desired remainder is now Residue, with a possible sign flip -- (i.e., if Negated is True at this point). if Negated then return -Residue; else return Residue; end if; end Remainder; -- SECTION III. -- -- Routines for conversion from Real to e_Real and back again. No_Of_Usable_Bits_In_Real : constant := 52; pragma Assert (Real'Machine_Mantissa >= No_Of_Usable_Bits_In_Real); No_Of_e_Digits_Per_Real : constant := (No_Of_Usable_Bits_In_Real-1) / No_Of_Bits_In_Radix + 1; -- Used only by: Make_Extended to convert a Real object into an e_Real. -- Equals: Ceiling (No_Of_Usable_Bits_In_Digit / No_Of_Bits_In_Radix) ------------------- -- Make_Extended -- ------------------- function Make_Extended (X : Real) return e_Real is Result : e_Real; -- Initialized to zero (important). Abs_X : Real := Abs (X); Exponent : e_Integer := 0; begin if not X'Valid then raise Constraint_Error with "Failure in routine Make_Real: Input is inf or NaN."; end if; if X = 0.0 then return Zero; elsif X = -0.0 then return Zero; else Result.Is_Zero := False; end if; -- Abs_X = Abs(X): if Abs_X > X then Result.Is_Positive := False; else Result.Is_Positive := True; end if; -- Get power of 2 exponent and 1st digit. This is not usually in an -- inner loop, so do it the brute force way. If Abs(X) < 1.0 -- then keep multiplying by Radix until 1.0 <= X <= Radix-1. -- Strip off the fraction to get the first digit. if Abs_X < Real_One then -- mult. by Radix until >= 1.0: for I in e_Integer loop Abs_X := Abs_X * Real_Radix; Exponent := Exponent - 1; if Abs_X >= Real_One then exit; end if; end loop; -- Abs_X is now 1.0 <= Abs_X < Radix. When strip off the fractional -- part with Real_Floor, then Abs_X will be in 1.0..Radix-1. elsif Abs_X >= Real_Radix then -- divide by Radix until just right: for I in e_Integer loop Abs_X := Abs_X * Inverse_Radix; Exponent := Exponent + 1; if Abs_X < Real_Radix then exit; end if; end loop; -- Abs_X is now 1.0 <= Abs_X < Radix. When strip off the fractional -- part with Real_Floor, then Abs_X will be in 1.0..Radix-1. else -- Abs_X is in desired range: Exponent := 0; end if; Result.Exp := Exponent; -- Now we've got Result.Exp, Result.Is_Positive, Result.Is_Zero all set. -- Is_Infinite is initialized to False. Next get the first digit: Result.Digit(0) := Digit_Floor (Abs_X); Abs_X := Abs_X - Real (Result.Digit(0)); -- Now just the Abs_X < 1.0 fraction remains in Abs_X. -- Optimization: if Abs_X = 0.0 then return early. Result is -- already initialized to zero...no need to get next digits. if Abs_X = 0.0 then return Result; end if; -- Get subsequent digits. These digits are in the range -- 0.0 <= X <= Radix-1. (Run the loop longer by 1 for safety.) for I in Digit_Index range Digit_Index'First+1..No_Of_e_Digits_Per_Real loop Abs_X := Abs_X * Real_Radix; Result.Digit(I) := Digit_Floor (Abs_X); Abs_X := Abs_X - Real (Result.Digit(I)); end loop; if Abs_X > Real_One then raise Constraint_Error with "Error in Make_Extended. Probably bad input."; end if; return Result; end Make_Extended; --------- -- "+" -- --------- -- Only works in range of Real (15 digits usually). -- So X = 2**62 raises Constraint_Error if Real'Digits = 15. function "+" (X : Integer) return e_Real is X_Real : constant Real := Real (X); begin if Abs X_Real > 2.0**(Real'Machine_Mantissa-1) then raise Constraint_Error with "Can't make extended. Argument too large."; end if; return Make_Extended (X_Real); end "+"; ------------------ -- Make_e_Digit -- ------------------ function Make_e_Digit (X : Real) return e_Digit is Ext_Result : e_Real; -- Initialized to zero. Result : e_Digit; -- Initialized to zero. begin Ext_Result := Make_Extended (X); if Ext_Result.Digit(1) /= Digit_Zero or Ext_Result.Digit(2) /= Digit_Zero then raise Constraint_Error with "Error in Make_e_Digit: arg not in range."; end if; if Ext_Result.Is_Zero then return Result; end if; Result.Exp := Ext_Result.Exp; Result.Is_Positive := Ext_Result.Is_Positive; Result.Is_Zero := Ext_Result.Is_Zero; Result.Digit := Ext_Result.Digit(0); return Result; end Make_e_Digit; --------- -- "-" -- --------- -- Same as Make_Extended, but changes the sign. function "-" (X : Real) return e_Real is Z : e_Real := Make_Extended (X); begin Z.Is_Positive := not Z.Is_Positive; if Z.Is_Zero then -- get sign right again Z.Is_Positive := True; end if; return Z; end; --------------- -- Make_Real -- --------------- -- Most of the arithmetic here is between powers of the machine_radix. -- Results should be exact out to the last place of Real. But -- can't be guaranteed. function Make_Real (X : e_Real) return Real is Result : Real := Real_Zero; Mantissa : Real := Real_Zero; begin if X.Is_Zero then return Real_Zero; end if; if X.Is_Infinite then raise Constraint_Error with "Failure in routine Make_Real: Number is infinite."; end if; -- Here is the general case. It produces a Mantissa that is a Factor -- of Radix larger than the Normalized Fraction that appears in -- Value_Of_Real = Normalized Fraction * Radix**Normalized_Exponent. -- --Power_Of_Radix := 1.0; --Result := Real (X.Digit(0)); --for I in Digit_Index range 1..No_Of_e_Digits_Per_Real-1 loop --Power_Of_Radix := Power_Of_Radix * Inverse_Radix; --Result := Result + Power_Of_Radix * Real (X.Digit(I)); --end loop; -- -- The following is the usual case. This is the inner product form. -- This sometimes gives the best results because it is more often -- done in the machine's extended arithmetic, if that's available. -- The following produces a Mantissa that is a Factor -- of Radix larger than the Normalized_Fraction that appears in -- Value_Of_Real = Normalized_Fraction * Radix**Normalized_Exponent. -- Recall that X.Exp is less than the Normalized exponents by 1. Mantissa := Real (X.Digit(0)) + Real (X.Digit(1)) * Inverse_Radix + Real (X.Digit(2)) * Inverse_Radix_Squared + Real (X.Digit(3)) * Inverse_Radix_Squared * Inverse_Radix + Real (X.Digit(4)) * Inverse_Radix_Squared * Inverse_Radix_Squared; -- Possible overflows are left to the external float package to raise. -- underflows to Zero are done explicitly. if Integer(X.Exp) * No_Of_Bits_In_Radix < Real'Machine_Emin then Result := 0.0; else Result := Mantissa * Real_Radix**Integer(X.Exp); end if; -- Here is the Ada94 way: -- --Real_Exponent_Shift := No_Of_Bits_In_Radix * Integer (X.Exp - 1.0); --Result := Real_Scaling (Mantissa, Real_Exponent_Shift); -- The scaling function multiplies -- Mantissa by Real'Machine_Radix ** Real_Exponent_Shift. -- At present leave it up to Real floating point to raise the -- constraint errors if they exist. if X.Is_Positive then null; else Result := -Result; end if; return Result; end Make_Real; -- SECTION II. -- -- Standard arithmetic operators. --------- -- Abs -- --------- function "Abs" (X : e_Real) return e_Real is X2 : e_Real := X; begin X2.Is_Positive := True; return X2; end "Abs"; --------- -- "-" -- --------- function "-" (X : e_Real) return e_Real is X2 : e_Real := X; begin X2.Is_Positive := not X2.Is_Positive; if X2.Is_Zero then X2 := Zero; end if; return X2; end "-"; ------------------- -- Abs_Is_Lesser -- ------------------- -- Is Abs(X) less than Abs(Y)? -- This performs the comparison for all digits: 0..Digit_Index'Last. -- The user is epected to call "Round" first if he wants the comparison -- in the range 0..Last_Correct_Digit == 0..Digit_Index'Last-No_Of_Guard_Digits. function Abs_Is_Lesser (X, Y : e_Real) return Boolean is begin -- Step 0. Handle the infinities. inf < inf raises c.e. but not here. if X.Is_Infinite and not Y.Is_Infinite then return False; -- |X| > |Y| elsif not X.Is_Infinite and Y.Is_Infinite then return True; -- |X| < |Y| end if; -- Step 0b. Handle the Zeros. Another case where the Exp does not tell -- us the magnitude of the number. if X.Is_Zero and not Y.Is_Zero then return True; -- |X| < |Y| elsif not X.Is_Zero and Y.Is_Zero then return False; -- |X| > |Y| elsif X.Is_Zero and Y.Is_Zero then return False; -- |X| = |Y| end if; -- Step 1. Find the lesser number, Exponent-wise. Must have the -- number normalized or the following is false. Also must have filtered -- out the special cases in which Exp is unrelated to the size of -- numbers: Zero and Infinity. if X.Exp < Y.Exp then return True; elsif X.Exp > Y.Exp then return False; end if; -- Step 2. If got this far, then the Exponents are equal. Find the -- the first unequal digit. The following makes use of the fact that -- the digits are essentially INTEGER values (all zeros beyond the -- the decimal point.) for I in Digit_Index'First .. Digit_Index'Last loop if X.Digit(I) < Y.Digit(I) then return True; elsif X.Digit(I) > Y.Digit(I) then return False; end if; -- if got this far, then the digits are equal -- so continue on to the next digit and try again. end loop; -- If got this far, then the numbers are equal. return False; end Abs_Is_Lesser; -------------------- -- Abs_Is_Greater -- -------------------- -- Is Abs(X) greater than Abs(Y)? function Abs_Is_Greater (X, Y : e_Real) return Boolean is begin -- Step 0. Handle the infinities. if X.Is_Infinite and not Y.Is_Infinite then return True; -- |X| > |Y| elsif not X.Is_Infinite and Y.Is_Infinite then return False; -- |Y| > |X| end if; -- Step 0b. Handle the Zeros. Another case where the Exp does not tell -- us the magnitude of the number. if X.Is_Zero and not Y.Is_Zero then return False; -- |X| < |Y| elsif not X.Is_Zero and Y.Is_Zero then return True; -- |X| > |Y| elsif X.Is_Zero and Y.Is_Zero then return False; -- |X| = |Y| end if; -- Step 1b. Find the larger number, Exponent-wise. Must have the -- number normalized or the following is false. if X.Exp > Y.Exp then return True; elsif X.Exp < Y.Exp then return False; end if; -- Step 2. If got this far, then the Exponents are equal. Find the -- the first unequal digit. The following makes use of the fact that -- the digits are essentially INTEGER valued (all zeros beyond the -- the decimal point.) for I in Digit_Index'First .. Digit_Index'Last loop if X.Digit(I) > Y.Digit(I) then return True; elsif X.Digit(I) < Y.Digit(I) then return False; end if; -- if got this far, then the digits are equal -- so continue on to the next digit and try again. end loop; -- If got this far, then the numbers are equal up to Digit_Index'Last. return False; end Abs_Is_Greater; --------------- -- Are_Equal -- --------------- -- X equals Y? Checks all digits except the digits beyond Digit_Index'Last. -- No rounding is performed. -- Can use this routine recognize Positive_Infinity and Zero. function Are_Equal (X, Y : e_Real) return Boolean is begin -- both zero, go home early: if X.Is_Zero AND Y.Is_Zero then return True; end if; -- one is zero and the other isn't go home early: if X.Is_Zero XOR Y.Is_Zero then return False; end if; -- Check signs. Return False if they have different signs. -- We've already checked for Zero's. if X.Is_Positive XOR Y.Is_Positive then return False; end if; -- both infinite but have different signs, then -- the above step already returned false. -- Make inf = inf so one can use this functions to recognize inf. -- Another reasonable option would be to make it false. if X.Is_Infinite AND Y.Is_Infinite then return True; end if; -- One is infinite, the other not: if X.Is_Infinite XOR Y.Is_Infinite then return False; end if; -- ANDing and XORing Is_Zero and Is_Infinite now know -- that the neither of the numbers is Zero or Infinite. -- Check equality, Exponent-wise. Must have both -- numbers normalized or the following doesn't work. Remember that the -- the only unnormalized nums are Zero, and the 2 infinities. If got -- this far then neither X nor Y is one of those three. if X.Exp /= Y.Exp then return False; end if; -- got this far, then the Exponents are equal. Find the -- the first unequal digit. Makes use of the fact that the digits are -- essentially integer valued. for I in Digit_Index loop if X.Digit(I) /= Y.Digit(I) then return False; end if; -- if got this far, then the digits are equal -- so continue onto the next digit and try again. end loop; --If got this far, then digits, exponent, and sign are equal. return True; end Are_Equal; ------------------- -- Are_Not_Equal -- ------------------- function Are_Not_Equal (X, Y : e_Real) return Boolean is begin return NOT Are_Equal (X, Y); end Are_Not_Equal; --------- -- ">" -- --------- -- Is X > Y? function ">" (X, Y : e_Real) return Boolean is begin -- Step 0. Check Zeros. if X.Is_Zero AND Y.Is_Zero then return False; end if; -- Step 0b. Need some optimizations for the common case in which one -- attempts to determine Positivity by X > Zero or signs by Zero > Y. -- The following lets infinities through for the non-zero part. if (not X.Is_Zero) AND Y.Is_Zero then if X.Is_Positive then return True; -- X is pos. but not zero, then (X > Zero). else return False; -- X is neg. but not zero, then not (X > Zero). end if; end if; if X.Is_Zero AND (not Y.Is_Zero) then if Y.Is_Positive then return False; -- Y is pos. but not zero, then not (Zero > Y). else return True; -- Y is neg. but not zero, then (Zero > Y). end if; end if; -- Step 1. Now do things more systematically. -- Check signs. Notice that these give us efficient way to -- check sign of a number. If X is negative, this is fast because -- Zero is classified as positive. So go home early if: if X.Is_Positive and not Y.Is_Positive then return True; elsif not X.Is_Positive and Y.Is_Positive then return False; end if; -- Step 1b. Now they are either both positive or both negative. -- If they are both inf, then raise ce, since don't know: if X.Is_Infinite AND Y.Is_Infinite then raise Constraint_Error with "Constraint_Error in routine >. Arguments are inf."; end if; -- Step 2. Now they are either both positive or both negative. -- If they are both neg. return true if Abs X < Abs Y. if X.Is_Positive and Y.Is_Positive then return Abs_Is_Greater (X, Y); -- Abs X > Abs Y else return Abs_Is_Lesser (X, Y); -- Abs X < Abs Y end if; end ">"; --------- -- "<" -- --------- function "<" (X, Y : e_Real) return Boolean is begin -- Step 0. Check Zeros. if X.Is_Zero AND Y.Is_Zero then return False; end if; -- Step 0b. Need some optimizations for the common case in which one -- attempts to determine signs by X < Zero or positivity by Zero < Y. -- The following lets infinities through for the non-zero part. if (not X.Is_Zero) AND Y.Is_Zero then if X.Is_Positive then return False; -- X is pos. but not zero, then not (X < Zero). else return True; -- X is neg. but not zero, then (X < Zero). end if; end if; if X.Is_Zero AND (not Y.Is_Zero) then if Y.Is_Positive then return True; -- Y is pos. but not zero, then (Zero < Y). else return False; -- Y is neg. but not zero, then not (Zero < Y). end if; end if; -- Step 1. Now do things more sytematically. -- Check signs. Notice that these give us efficient way to -- check sign of a number. If X is negative, this is fast because -- Zero is classified as positive. (If want to find if it's Pos., use -- not (X < Zero). Since they aren't both 0 go home early if: if X.Is_Positive and not Y.Is_Positive then return False; elsif not X.Is_Positive and Y.Is_Positive then return True; end if; -- Step 1b. Now they are either both positive or both negative. -- If they are both inf, then raise ce: if X.Is_Infinite AND Y.Is_Infinite then raise Constraint_Error with "Error in routine <. Arguments are inf."; end if; -- Step 2. Now they are either both positive or both negative. -- If they are both neg. return true if Abs X > Abs Y. if X.Is_Positive and Y.Is_Positive then return Abs_Is_Lesser (X, Y); -- Abs X < Abs Y else return Abs_Is_Greater (X, Y); -- Abs X > Abs Y end if; end "<"; ---------- -- ">=" -- ---------- function ">=" (X, Y : e_Real) return Boolean is begin return (not (X < Y)); end ">="; ---------- -- "<=" -- ---------- function "<=" (X, Y : e_Real) return Boolean is begin return (not (X > Y)); end "<="; ---------- -- Add -- ---------- -- Add the numbers. The individual digits may overflow the 0..Radix-1 range -- but not the range of the base floating point number used to represent the -- digit. Carrying is done later. function Add (Larger : e_Real; Smaller : e_Real; Digit_Shift : Digit_Index) return e_Real is Z : e_Real; begin if Digit_Shift > Digit_Index'First then for I in Digit_Index'First .. Digit_Shift-1 loop Z.Digit(I) := Larger.Digit(I); end loop; end if; for I in Digit_Shift .. Digit_Index'Last loop Z.Digit(I) := Larger.Digit(I) + Smaller.Digit(I - Digit_Shift); end loop; return Z; end Add; --pragma Inline (Add); -------------- -- Subtract -- -------------- -- Subtract the smaller from the larger. If they have the same -- exponent, (ie Digit_Shift = 0), -- then use the quantity "First_Unequal_Digit" to optimize -- the subtraction, by inserting zeros for all of the equal digits. -- We already verified that Larger and Smaller are not equal. procedure Subtract (Larger : in e_Real; Smaller : in e_Real; Digit_Shift : in Digit_Index; First_Unequal_Digit : in Digit_Index; Result : out e_Real; Extra_Guard_Digit : out Digit_Type) is I : Digits_Base; begin if Digit_Shift = 0 then -- We can make use of First_Unequal_Digit. if First_Unequal_Digit > 0 then for I in 0 .. First_Unequal_Digit-1 loop Result.Digit(I) := Digit_Zero; end loop; end if; for I in First_Unequal_Digit .. Digit_Index'Last loop Result.Digit(I) := Larger.Digit(I) - Smaller.Digit(I); end loop; Extra_Guard_Digit := Digit_Zero; -- important initialization. else for I in 0 .. Digit_Shift-1 loop Result.Digit(I) := Larger.Digit(I); end loop; for I in Digit_Shift .. Digit_Index'Last loop Result.Digit(I) := Larger.Digit(I) - Smaller.Digit(I - Digit_Shift); end loop; I := Digit_Index'Last + 1; Extra_Guard_Digit := -Smaller.Digit(I - Digit_Shift); -- Here the Larger.Digit(I) = 0.0 because it ran out of digits. end if; end Subtract; --pragma Inline (Subtract); ---------------------------- -- Borrow_For_Subtraction -- ---------------------------- -- Do the Borrowing. This can have much overhead in "-" or "+", so some -- optimizations are performed. If the digits have become less than zero -- then must borrow from the next higher order digit: subtract 1 from that -- digit, and add Radix to digit in question. Start -- at the least significant digit, Digit_Index'Last, work up to point at which -- the subtraction began: Digit_Shift. Digit_Shift is the first digit of -- Z on which a subtraction was performed. After that, unless a borrow is -- performed, the process may end. Borrowing should be extremely -- rare, so don't do unless necessary. -- The Extra_Guard_Digit is a virtual digit at index Digit_Index'Last+1. Very -- important in improving precision in some cases: particularly subtracting -- a small number from 1.0. procedure Borrow_For_Subtraction (Z : in out e_Real; Extra_Guard_Digit : in Digit_Type; Digit_Shift : in Digit_Index) is First_Nonzero_Digit : Digits_Base := Digit_Index'Last+1; All_The_Digits_Are_Zero : Boolean := True; Borrow : constant Digit_Type := -Digit_One; Guard_Digit : Digit_Type := Extra_Guard_Digit; I : Digits_Base; begin -- This is the general case in which many numbers were subtracted: -- Here it is possible that Borrow > 1.0. -- if Digit_Shift < Digit_Index'Last then -- for I in reverse Digit_Shift+1..Digit_Index'Last loop -- if Z.Digit(I) < 0.0 then -- Borrow := Real_Floor (Z.Digit(I) * Inverse_Radix); -- Z.Digit(I) := Z.Digit(I) - Borrow * Radix; -- Borrow is < 0.0. -- Z.Digit(I-1) := Z.Digit(I-1) + Borrow; -- end if; -- end loop; -- end if; -- We are subtracting only 2 numbers, so borrow at most 1 digit. -- Special case: the extra guard digit at Digit_Index'Last+1: --Borrow := -Digit_One; I := Digit_Index'Last+1; if Guard_Digit < Digit_Zero then Guard_Digit := Guard_Digit + Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Borrow; end if; if Digit_Shift < Digit_Index'Last then --Borrow := -Digit_One; for I in reverse Digit_Shift+1 .. Digit_Index'Last loop if Z.Digit(I) < Digit_Zero then Z.Digit(I) := Z.Digit(I) + Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Borrow; end if; end loop; end if; -- Step 1. Do everything between the 2nd digit and Digit_Shift. -- If no borrowing is performed, then are done, since these are the -- digits on which no subtractions were performed initially. (With the -- exception of digit Digit_Shift: still must check that it -- is not < 0.0.) -- The general case: -- Borrow_Loop: -- for I in reverse Digit_Index'First+1 .. Digit_Shift loop -- if Z.Digit(I) < 0.0 then -- Borrow := Real_Floor (Z.Digit(I) * Inverse_Radix); -- Z.Digit(I) := Z.Digit(I) - Borrow * Radix; -- Z.Digit(I-1) := Z.Digit(I-1) + Borrow; -- else -- exit Borrow_Loop; -- end if; -- end loop Borrow_Loop; -- We are subtracting only 2 numbers, so borrow at most 1 digit. --Borrow := -Digit_One; Borrow_Loop: for I in reverse Digit_Index'First+1..Digit_Shift loop if Z.Digit(I) < Digit_Zero then Z.Digit(I) := Z.Digit(I) + Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Borrow; else exit Borrow_Loop; end if; end loop Borrow_Loop; -- Step 2. If Z.Digit(0) < 0.0 then the result is < 0.0, which means -- a failure in the "+" or "-" routines below. if not Disable_Program_Error_Tests then if Z.Digit(0) < Digit_Zero then raise Program_Error with "Some error in Borrow_For_Subtraction."; end if; end if; -- Step 3. Normalize the result if the highest order Digit is zero. -- Shift the exponent accordingly. Recall that Z should not be Zero; -- checked for that possibility before subtracting. -- So shift the entire mantissa left by the number of leading zeros, -- and decrement the exponent by the same amount. If do any left-shifts, -- then put at the end of the mantissa the extra guard digit dragged -- along just for this event. First_Nonzero_Digit := Digit_Index'Last + 1; All_The_Digits_Are_Zero := True; for I in Digit_Index loop if Z.Digit(I) /= Digit_Zero then First_Nonzero_Digit := I; All_The_Digits_Are_Zero := False; exit; end if; end loop; if All_The_Digits_Are_Zero then if Guard_Digit = Digit_Zero then -- But we checked equality of X and Y. -- Only time this happened it was a compiler bug. -- but maybe not an err? Z := Zero; if not Disable_Program_Error_Tests then raise Program_Error with "Might be a bug in Borrow_For_Subtraction."; end if; else -- This is certainly possible: Z.Digit(0) := Guard_Digit; Z.Exp := Z.Exp - e_Integer (First_Nonzero_Digit); end if; end if; if not All_The_Digits_Are_Zero then -- First_Nonzero_Digit < Max_Index+1 if First_Nonzero_Digit > 0 then -- shift the mantissa left by this amount for I in 0 .. Digit_Index'Last-First_Nonzero_Digit loop Z.Digit(I) := Z.Digit(I + First_Nonzero_Digit); end loop; -- Shift the mantissa left by this amount. for I in Digit_Index'Last-First_Nonzero_Digit+1 .. Digit_Index'Last loop Z.Digit(I) := Digit_Zero; end loop; -- Set the rest of the mantissa to 0.0. Z.Digit(Digit_Index'Last-First_Nonzero_Digit+1) := Guard_Digit; -- Even tho' set Digit to 0.0 above, set it right now. Z.Exp := Z.Exp - e_Integer (First_Nonzero_Digit); end if; end if; -- If First_Nonzero_Digit = 0, the usual case, then are done. end Borrow_For_Subtraction; --pragma Inline (Borrow_For_Subtraction); ------------------------ -- Carry_For_Addition -- ------------------------ -- Do the carrying. This can have much overhead, so some -- optimizations are performed. If the digits have become larger -- than Radix-1 then must break the digit into 2 parts and add the larger -- to a higher order digit. This carry distance is at most one digit, -- rather than the 2 possible in the multiplication routine. Start -- at the least significant digit, Digit_Index'Last, work up to point at which -- the addition began: Digit_Shift. Digit_Shift is the first digit of -- Z on which an addition was performed. After that, unless a carry is -- performed, the process may be ended. Carrying should be extremely -- rare, so don't do unless necessary. procedure Carry_For_Addition (Z : in out e_Real; Digit_Shift : in Digit_Index) is Digit_Minus_1 : Digit_Type := Digit_Zero; We_Are_Finished : Boolean := False; Must_Normalize : Boolean := False; Carry : constant Digit_Type := Digit_One; begin -- Step 1. Do the carrying among the digits that have been added to each -- other (Digit_ID in Digit_Shift+1..Digit_Index'Last). Actually, -- Digit_ID = Digit_Shift had an addition performed to it also..that's -- dealt with in step 2. -- -- This is the general case. Useful for an optimized Sum(many numbers). -- if Digit_Shift < Digit_Index'Last then -- for I in reverse Digit_Shift+1..Digit_Index'Last loop -- if Z.Digit(I) > Radix_Minus_1 then -- Carry := Real_Floor (Z.Digit(I) * Inverse_Radix); -- Z.Digit(I) := Z.Digit(I) - Carry * Radix; -- Z.Digit(I-1) := Z.Digit(I-1) + Carry; -- end if; -- end loop; -- end if; -- -- We're summing at most 2 numbers, so Carry is at most 1.0. if Digit_Shift < Digit_Index'Last then for I in reverse Digit_Shift+1 .. Digit_Index'Last loop if Z.Digit(I) > Digit_Radix_Minus_1 then --Carry := Digit_One; Z.Digit(I) := Z.Digit(I) - Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Carry; end if; end loop; end if; We_Are_Finished := False; -- We have at least Digit(Digit_Shift) to check. -- Step 2. Do everything between the 2nd digit and Digit_Shift. -- If no carry is performed, then we're done, since these are the -- digits on which no additions were performed initially. (With the -- exception of digit Digit_Shift: still must check that it -- is not larger than Radix-1.) -- -- Carry_Loop: -- for I in reverse Digit_Index'First+1 .. Digit_Shift loop -- if Z.Digit(I) > Radix_Minus_1 then -- Carry := Real_Floor (Z.Digit(I) * Inverse_Radix); -- Z.Digit(I) := Z.Digit(I) - Carry * Radix; -- Z.Digit(I-1) := Z.Digit(I-1) + Carry; -- else -- We_Are_Finished := True; -- exit Carry_Loop; -- end if; -- end loop Carry_Loop; -- When summing at most 2 numbers: Carry_Loop: for I in reverse Digit_Index'First+1..Digit_Shift loop if Z.Digit(I) > Digit_Radix_Minus_1 then --Carry := Digit_One; Z.Digit(I) := Z.Digit(I) - Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Carry; else We_Are_Finished := True; exit Carry_Loop; end if; end loop Carry_Loop; -- Step 3. If left the carry_loop early, then go home now. -- No need to normalize the result (i.e. make sure that the first -- digit is not 0). No need to increment Z.Exp. This should be the usual -- case. First however, a debugging test: if We_Are_Finished then if not Disable_Program_Error_Tests then if Z.Digit(0) <= Digit_Zero then raise Program_Error with "Some error in Carrying for + operator."; end if; end if; return; end if; -- Step 4. Perform the final carry if Z.Digit(0) > Radix-1 (to a digit -- that doesn't exist yet, called Digit_Minus_1.) -- Must_Normalize := False; -- if Z.Digit(0) > Radix_Minus_1 then -- Carry := Real_Floor (Z.Digit(0) * Inverse_Radix); -- Z.Digit(0) := Z.Digit(0) - Carry * Radix; -- Digit_Minus_1 := Carry; -- Must_Normalize := True; -- end if; Must_Normalize := False; if Z.Digit(0) > Digit_Radix_Minus_1 then --Carry := Digit_One; Z.Digit(0) := Z.Digit(0) - Digit_Radix; Digit_Minus_1 := Carry; -- Digit_Minus_1 is initially 0.0. Must_Normalize := True; end if; -- Step 5. Normalize the result if Digit(0) was > Radix-1, -- hence a carry occurred to a larger digit. -- Is it possible that Digit(0) is 0 and Digit_minus_1 is also 0? -- No. To get Digit(0) to zero, it would have to = Radix..then a -- carry to Digit_Minus_1 would make it zero. But then Digit_Minus_1 -- would be non-zero. if Must_Normalize then Z.Exp := Z.Exp + 1; for I in reverse Digit_Index'First+1 .. Digit_Index'Last loop Z.Digit(I) := Z.Digit(I-1); end loop; Z.Digit(0) := Digit_Minus_1; end if; -- Test for failure in algorithm: if not Disable_Program_Error_Tests then if Z.Digit(0) <= Digit_Zero then raise Program_Error with "Some error in Carrying for + operator."; end if; end if; end Carry_For_Addition; --pragma Inline (Carry_For_Addition); --------- -- "+" -- --------- -- Just the identity operator, so you can type A := +1.23E+02 -- and the statement will be accepted whether or not A is e_Real. function "+" (X : e_Real) return e_Real is begin return X; end "+"; --------- -- "+" -- --------- -- Surprizingly complicated. function "+"(X, Y : e_Real) return e_Real is Z : e_Real; Delta_Exp : e_Integer; Digit_Shift : Digit_Index := 0; First_Unequal_Digit : Digit_Index := 0; Extra_Guard_Digit : Digit_Type := Digit_Zero; -- Important init. (for subtraction) Final_Sign_Is_Positive : Boolean; Mantissas_Are_Equal : Boolean; type Max_Info is (X_Is_Max, Y_Is_Max); Max_Num_ID : Max_Info := X_Is_Max; type Add_Choice is (Add_Them, Subtract_Y_From_X, Subtract_X_From_Y); Add_Code : Add_Choice; begin -- Step 0. If Either of the numbers is 0.0, then return the other. if Y.Is_Zero then return X; elsif X.Is_Zero then return Y; end if; -- Step 0b. If one is infinite, but not the other, return the infinity, -- sign of the inf unchanged. If both are inf, say inf + inf = +inf. -- And say inf - inf raises c.e., because don't know what it is. if Y.Is_Infinite and not X.Is_Infinite then return Y; elsif not Y.Is_Infinite and X.Is_Infinite then return X; end if; if Y.Is_Infinite and X.Is_Infinite then if not X.Is_Positive and not Y.Is_Positive then return Negative_Infinity; elsif X.Is_Positive and Y.Is_Positive then return Positive_Infinity; else raise Constraint_Error with "Subtraction of inf by inf is undefined."; end if; end if; -- Step 1. Find the larger number, Exponent-wise, and return it if it is -- so much larger than the other that there is no addition to be done. -- If they are equal, exponent-wise, then say X is the larger. if Y.Exp > X.Exp then Max_Num_ID := Y_Is_Max; else Max_Num_ID := X_Is_Max; end if; Delta_Exp := Abs (X.Exp - Y.Exp); if Delta_Exp > e_Integer(Digit_Index'Last) then -- ie, Delta_Exp >= No_Of_Digits case Max_Num_ID is when X_Is_Max => return X; when Y_Is_Max => return Y; end case; end if; -- Step 2. When the exponents are equal, and subtraction is going to be -- done (ie, one of the numbers is negative, the other pos., X>0 XOR Y>0), -- need more information about which number is smaller. -- Now correctly find the larger (Abs-wise) even if the Exp's are equal. -- Only do this in the subtraction case; if then the numbers turn -- out to be equal, then return Zero. It is important to handle that -- special case here. First_Unequal_Digit := Digit_Index'First; if (X.Is_Positive XOR Y.Is_Positive) and then X.Exp = Y.Exp then -- Find the first non-equal word in the mantissas: Mantissas_Are_Equal := True; for I in Digit_Index'First .. Digit_Index'Last loop if X.Digit(I) /= Y.Digit(I) then Mantissas_Are_Equal := False; First_Unequal_Digit := I; exit; end if; end loop; -- We're finished if the Exp's are equal, the Mantissas are equal -- and we're subtracting one from the other: if Mantissas_Are_Equal then return Zero; end if; -- Find the larger of the Two (Absolute values of course): if X.Digit(First_Unequal_Digit) > Y.Digit(First_Unequal_Digit) then Max_Num_ID := X_Is_Max; else Max_Num_ID := Y_Is_Max; end if; end if; -- Step 3. Do add or subtract? Depends on their signs. if X.Is_Positive and Y.Is_Positive then Add_Code := Add_Them; Final_Sign_Is_Positive := True; end if; if (not X.Is_Positive) and (not Y.Is_Positive) then Add_Code := Add_Them; -- add 2 neg nums as tho they were pos. Final_Sign_Is_Positive := False; end if; if (not X.Is_Positive) and Y.Is_Positive then case Max_Num_ID is when X_Is_Max => Add_Code := Subtract_Y_From_X; -- I mean Abs(X) - Abs(Y) Final_Sign_Is_Positive := False; when Y_Is_Max => Add_Code := Subtract_X_From_Y; Final_Sign_Is_Positive := True; end case; end if; if X.Is_Positive and (not Y.Is_Positive) then case Max_Num_ID is when X_Is_Max => Add_Code := Subtract_Y_From_X; -- I mean Abs(X) - Abs(Y) Final_Sign_Is_Positive := True; when Y_Is_Max => Add_Code := Subtract_X_From_Y; -- I mean Abs(Y) - Abs(X) Final_Sign_Is_Positive := False; end case; end if; -- Step 4. We're now ready to do the adding (or subtracting). -- The adding and subtracting are separated from the -- carrying/borrowing/normalizing process, because i) the -- adding can then be vectorized or otherwise optimized and -- ii) in other versions many numbers will be summed (not just X and Y), -- in which case it really pays off to do the normalizing -- and carrying just once, after many additions, because the -- overhead of carrying can be higher than summing. Digit_Shift := Digit_Index (Delta_Exp); case Add_Code is when Add_Them => case Max_Num_ID is when X_Is_Max => Z := Add (Larger => X, Smaller => Y, Digit_Shift => Digit_Shift); when Y_Is_Max => Z := Add (Larger => Y, Smaller => X, Digit_Shift => Digit_Shift); end case; when Subtract_Y_From_X => Subtract (Larger => X, Smaller => Y, Digit_Shift => Digit_Shift, First_Unequal_Digit => First_Unequal_Digit, Result => Z, Extra_Guard_Digit => Extra_Guard_Digit); when Subtract_X_From_Y => Subtract (Larger => Y, Smaller => X, Digit_Shift => Digit_Shift, First_Unequal_Digit => First_Unequal_Digit, Result => Z, Extra_Guard_Digit => Extra_Guard_Digit); end case; -- Step 5. Do everything except the carrying or borrowing. -- We were careful about subtracting the smaller from the larger, so -- the following steps can be done before or after the carrying, (provided -- only 2 numbers are being summed). if Final_Sign_Is_Positive then Z.Is_Positive := True; else Z.Is_Positive := False; end if; -- Set Z.Exp but remember it still may be raised by 1 (if carrying occurs), -- or lowered by 1 if borrowing occurs. case Max_Num_ID is when X_Is_Max => Z.Exp := X.Exp; when Y_Is_Max => Z.Exp := Y.Exp; end case; -- The Z = 0 case has already been considered. Z.Is_Zero := False; -- Do the carrying or borrowing, as the case may be. These also -- normalize the number, and produce an additional correction to the Exp. case Add_Code is when Add_Them => Carry_For_Addition (Z, Digit_Shift); when Subtract_Y_From_X | Subtract_X_From_Y => Borrow_For_Subtraction (Z, Extra_Guard_Digit, Digit_Shift); end case; -- Step 6. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. This analysis is all isolated to the end -- of the arithmetic routines so that it is more easily modified to -- raise exceptions if that is what is desired. In order to do it -- here, must assume that the parmeters Min_Exponent and Max_Exponent -- limit the dynamic range of the Exp to about 1/4 of that allowed -- by the base type used to represent the exponent. This is -- checked in the spec with an assertion. (The reason is, the above -- code will go outside the accepted range of Exp with out being -- checked till down here.) This limit is OK because the base type -- allows excessively large exponents anyway. if Z.Exp < Min_Exponent then Z := Zero; end if; if Z.Exp > Max_Exponent then if Z.Is_Positive then Z := Positive_Infinity; else Z := Negative_Infinity; end if; end if; return Z; end "+"; --------- -- "-" -- --------- -- Subtract Y from X: function "-"(X, Y : e_Real) return e_Real is Y2 : e_Real := Y; begin Y2.Is_Positive := not Y.Is_Positive; return X + Y2; end "-"; ------------------------------------ -- Do_Carrying_For_Multiplication -- ------------------------------------ -- The digits have probably overflowed their allotted range of 0..Radix-1. -- Break the digits into three parts: -- digit = d2 * 2**(Radix*2) + d1 * 2**(Radix*1) + d0 * 2**(Radix*0) -- where d_n is in the range 0..Radix-1. -- Carry d2 to two digits to the left of Digit; carry d1 one digit to the -- left of Digit. So Carry_Minus_1 = d1, Carry_Minus_2 = d2. procedure Do_Carrying_For_Multiplication (Z : in out e_Real; Digit_Minus_1 : in out Digit_Type; Digit_Minus_2 : in out Digit_Type) is Carry_Minus_1, Carry_Minus_2 : Digit_Type := Digit_Zero; -- Essential init. The_Digit : Digit_Type; I : Digit_Index; begin --******************************************************************* -- The real valued digits are effectively integers in the range -- 0..2**63-1. (Std. vers.) Break them into three words: 1st 30 bits (d0), -- 2nd 30 bits (d1), and last 3 bits (d2). (If Radix is 2**29, then these -- will be 29 bit, 29 bit, 5 bit word repectively.) The 3rd (5 bit) word -- will be Carried 2 digits to the left (Carry_Minus_2). The second -- 29 bit word will be carried 1 digit to the left. The remaining -- lowest order 29 bit word will be the desired digit. -- -- Overhead is large from carrying so don't calculate and -- carry the 3rd (5 bit) word unless necessary. This carry's usually -- not necessary for the lowest order digits, because usually -- the bits in the words are random, so half the time the word is -- > Radix/2, half smaller. Or, <X> = Radix / 2. -- Assume <X*Y> = <X><Y> (assume independence). Then -- < SUM(X*Y) > = SUM <(X*Y)> = SUM <X><Y> = SUM <X>**2. So after -- 4 sums (I = 3), you break the Radix**2 barrier, on the average. -- So the optimization matters when the total number of digits is -- small. When there are many digits, then it doesn't help much -- but the overhead from trying is small enough that might as well -- optimize for the common case: relatively small number of total -- digits. --******************************************************************* for I in reverse Digit_Index'First+2 .. Digit_Index'Last loop The_Digit := Z.Digit(I); if The_Digit >= Digit_Radix_Squared then Carry_Minus_2 := Shift_Right_2x_No_of_Bits_in_Radix (The_Digit); The_Digit := The_Digit - Carry_Minus_2 * Digit_Radix_Squared; Z.Digit(I-2) := Z.Digit(I-2) + Carry_Minus_2; end if; Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (The_Digit); Z.Digit(I) := The_Digit - Carry_Minus_1 * Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Carry_Minus_1; end loop; -- Special case I = Digit_Index'First + 1 = 1. I := Digit_Index'First + 1; The_Digit := Z.Digit(I); if The_Digit >= Digit_Radix_Squared then Carry_Minus_2 := Shift_Right_2x_No_of_Bits_in_Radix (The_Digit); The_Digit := The_Digit - Carry_Minus_2 * Digit_Radix_Squared; Digit_Minus_1 := Digit_Minus_1 + Carry_Minus_2; end if; Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (The_Digit); Z.Digit(I) := The_Digit - Carry_Minus_1 * Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Carry_Minus_1; -- Special case I = Digit_Index'First = 0 I := Digit_Index'First; The_Digit := Z.Digit(I); if The_Digit >= Digit_Radix_Squared then Carry_Minus_2 := Shift_Right_2x_No_of_Bits_in_Radix (The_Digit); The_Digit := The_Digit - Carry_Minus_2 * Digit_Radix_Squared; Digit_Minus_2 := Digit_Minus_2 + Carry_Minus_2; end if; Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (The_Digit); Z.Digit(I) := The_Digit - Carry_Minus_1 * Digit_Radix; Digit_Minus_1 := Digit_Minus_1 + Carry_Minus_1; -- Special case I = Digit_Index'First - 1 if Digit_Minus_1 > Digit_Radix_minus_1 then Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (Digit_Minus_1); Digit_Minus_1 := Digit_Minus_1 - Carry_Minus_1 * Digit_Radix; Digit_Minus_2 := Digit_Minus_2 + Carry_Minus_1; end if; end Do_Carrying_For_Multiplication; --pragma Inline (Do_Carrying_For_Multiplication); --------------- -- Normalize -- --------------- -- Normalize the result if the highest order (negative Index) digits are -- non-zero. (The usual case.) -- Shift Mantissa and the exponent accordingly. (The canonical form -- requires that the first digit is non-zero.) procedure Normalize (Z : in out e_Real; Digit_Minus_1 : in Digit_Type; Digit_Minus_2 : in Digit_Type) is First_Nonzero_Digit : Digit_Index := Digit_Index'First; -- Init. essential First_Nonzero_Digit_Is_Minus_1 : Boolean := False; -- Init. essential First_Nonzero_Digit_Is_Minus_2 : Boolean := False; -- Init. essential All_Digits_Are_Zero : Boolean := False; -- Init. essential begin -- Step 0. Infinities and Zero. if Z.Is_Infinite then return; end if; Z.Is_Zero := False; -- Will be toggled if all digits 0. -- Step 1. Find the first non-zero digit: if Digit_Minus_2 > Digit_Zero then First_Nonzero_Digit_Is_Minus_2 := True; elsif Digit_Minus_1 > Digit_Zero then First_Nonzero_Digit_Is_Minus_1 := True; else All_Digits_Are_Zero := True; for I in Digit_Index loop if Z.Digit(I) /= Digit_Zero then First_Nonzero_Digit := I; -- So First_Nonzero_Digit <= Digit_Index'Last. All_Digits_Are_Zero := False; exit; end if; end loop; end if; if All_Digits_Are_Zero then Z := Zero; return; end if; -- Step 2. Shift the array to the right if the Minus_N digits are -- non Zero. Shift the array to the left if necessary (shouldn't be). if First_Nonzero_Digit_Is_Minus_2 then -- Shift right by 2: for I in reverse Digit_Index'First+2 .. Digit_Index'Last loop Z.Digit(I) := Z.Digit(I - 2); end loop; Z.Digit(1) := Digit_Minus_1; Z.Digit(0) := Digit_Minus_2; Z.Exp := Z.Exp + 2; elsif First_Nonzero_Digit_Is_Minus_1 then -- Shift right by 1: for I in reverse Digit_Index'First+1 .. Digit_Index'Last loop Z.Digit(I) := Z.Digit(I - 1); end loop; Z.Digit(0) := Digit_Minus_1; Z.Exp := Z.Exp + 1; elsif First_Nonzero_Digit > Digit_Index'First then -- Shift left by val of First_Non...: for I in 0 .. Digit_Index'Last-First_Nonzero_Digit loop Z.Digit(I) := Z.Digit(I + First_Nonzero_Digit); end loop; for I in Digit_Index'Last-First_Nonzero_Digit+1 .. Digit_Index'Last loop Z.Digit(I) := Digit_Zero; end loop; Z.Exp := Z.Exp - e_Integer (First_Nonzero_Digit); --assumes Digit_Index'First=0 end if; -- Test for failure in algorithm: if not Disable_Program_Error_Tests then if Z.Digit(0) > Digit_Radix_Minus_1 or Z.Digit(0) <= Digit_Zero then raise Program_Error with "Some error in Normalization for * operator."; end if; end if; end Normalize; --pragma Inline (Normalize); ---------------------------- -- General_Multiplication -- ---------------------------- function General_Multiplication (X, Y : e_Real) return e_Real is Z : e_Real; Digit_Minus_1, Digit_Minus_2 : Digit_Type := Digit_Zero; -- Essential init Sum : Digit_Type := Digit_Zero; No_Of_Digits, No_Of_Segments, Remaining_Sums : Digits_Base; Starting_Digit, Ending_k : Digit_Index; Start_Sum, End_Sum : Digit_Index; Allowed_Digits_Per_Carry : constant := Sums_per_Carry + 1; -- If you sum 9 numbers you only do 8 sums. begin -- Step 0. Handle the Zeros. We'll say 0 * infinity is 0, since inf is -- really just a large finite number. if X.Is_Zero or Y.Is_Zero then return Zero; end if; Z.Is_Zero := False; -- toggled below if underflow. -- Step 1. If one or more is infinite..Notice inf * inf = inf here. if Y.Is_Infinite or X.Is_Infinite then if X.Is_Positive xor Y.Is_Positive then -- opposite signs. return Negative_Infinity; else return Positive_Infinity; end if; end if; -- Step 2. Handle the signs and exponents: Z.Is_Positive := not (X.Is_Positive XOR Y.Is_Positive); Z.Exp := X.Exp + Y.Exp; -- Will be further adjusted by Carry/Normalize. No_Of_Digits := Digit_Index'Last + 1; No_Of_Segments := No_Of_Digits / Allowed_Digits_Per_Carry; Remaining_Sums := No_Of_Digits REM Allowed_Digits_Per_Carry; -- Z has been initialized to Zero: essential if Remaining_Sums = 0 -- First do the stragglers, digits of index (k in 0..Remaining_Sums-1): if Remaining_Sums > 0 then for Digit_ID in Digit_Index loop Ending_k := Digit_Index'Min (Digit_ID, Remaining_Sums-1); Sum := Digit_Zero; for k in Digit_Index'First .. Ending_k loop Sum := Sum + X.Digit(k) * Y.Digit(Digit_ID - k); end loop; Z.Digit(Digit_ID) := Sum; -- init Z. end loop; Do_Carrying_For_Multiplication (Z, Digit_Minus_1, Digit_Minus_2); end if; -- Now do the segments of length (up to) (usually) 32: if No_Of_Segments > 0 then for Segment in 0 .. No_Of_Segments-1 loop Start_Sum := (Segment+0) * Allowed_Digits_Per_Carry + Remaining_Sums; End_Sum := (Segment+1) * Allowed_Digits_Per_Carry + Remaining_Sums - 1; --End_Sum := Start_Sum + (Allowed_Digits_Per_Carry - 1); Starting_Digit := Start_Sum; for Digit_ID in Starting_Digit .. Digit_Index'Last loop Ending_k := Digit_Index'Min (Digit_ID, End_Sum); Sum := Digit_Zero; for k in Start_Sum .. Ending_k loop Sum := Sum + X.Digit(k) * Y.Digit(Digit_ID - k); end loop; Z.Digit(Digit_ID) := Z.Digit(Digit_ID) + Sum; -- Z.Digit(Digit_ID) is close enough to 0 (ie, < Radix-1) that this -- does not count as a sum in the Sums_Per_Carry rule. -- That's why Allowed_Sums_Per_Carry = Sums_Per_Carry+1 here. end loop; Do_Carrying_For_Multiplication (Z, Digit_Minus_1, Digit_Minus_2); end loop; end if; -- Must Normalize: shift digit array to make sure that the first digit -- is non-zero: if Infinity or Zero gets this far, then problem occurs. -- Should catch in normalize. Normalize (Z, Digit_Minus_1, Digit_Minus_2); -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. In order to do it -- here, must assume that the parmeters Min_Exponent and Max_Exponent -- limit the dynamic range of the Exp to about 1/4 of that allowed -- by the base type used to represent the exponent. This is -- checked in the spec with an assertion. (The reason is, the above -- code will go well outside the accepted range of Exp with out being -- checked till down here.) This limit is OK because the base type -- allows excessively large exponents anyway, up to 2**31-1. if Z.Exp < Min_Exponent then Z := Zero; end if; if Z.Exp > Max_Exponent then if Z.Is_Positive then Z := Positive_Infinity; else Z := Negative_Infinity; end if; end if; return Z; end General_Multiplication; ------------ -- Square -- ------------ -- Suppose Z, and X are composed of n digits 0..n-1. Then X*X is -- -- Xn-1 := X0*Xn-1 + X1*Xn-2 + .. + Xn-1*X0 -- ... -- X2 := X0*X2 + X1*X1 + X2*X0 -- X1 := X0*X1 + X1*X0 -- X0 := X0*X0 -- -- Now follows the upper half of the table, which produces words beyond -- the precision of the two number X and X that are being multiplied. These -- don't calculate. (Just make N larger if more precision is needed). -- procedure Square (X : in out e_Real) is Digit_Minus_1, Digit_Minus_2 : Digit_Type := Digit_Zero; -- Essential init Ultimate_No_of_Digits : constant := Ultimate_Digit + 1; -- equals: Digit_Index'Last - Digit_Index'First + 1 = Mantissa'Length ------------------------------------- -- Product_if_digits_fewer_than_17 -- ------------------------------------- procedure Product_if_digits_fewer_than_17 is pragma Assert (Ultimate_No_of_Digits >= 5); --because no if-then for 1st 5. pragma Assert (Ultimate_No_of_Digits < 17); pragma Assert (No_Of_Bits_In_Radix <= 30); -- (not a) or b is same as a implies b. -- no need to carry until the end if following evaluate to true: pragma Assert (not (No_Of_Bits_In_Radix = 30) or Ultimate_No_of_Digits <= 8); pragma Assert (not (No_Of_Bits_In_Radix = 29) or Ultimate_No_of_Digits <= 32); pragma Suppress (Index_Check); A : Mantissa renames X.Digit; S : constant Digit_Index := Digit_Index'First; begin -- Ultimate_No_of_Digits is named number, so optimizer should -- eliminate unused blocks of code below...not that it matters. -- need to do intermediate carrying if No_Of_Bits_In_Radix >= 30 -- and more than 8 digits. -- ! Must be done in the following order ! if Ultimate_No_of_Digits >= 16 then A (S+15) :=(A(S+0)*A(S+15) + A(S+1)*A(S+14) + A(S+2)*A(S+13) + A(S+3)*A(S+12) + A(S+4)*A(S+11) + A(S+5)*A(S+10) + A(S+6)*A(S+9) + A(S+7)*A(S+8))*Digit_Two; end if; if Ultimate_No_of_Digits >= 15 then A (S+14) :=(A(S+0)*A(S+14) + A(S+1)*A(S+13) + A(S+2)*A(S+12) + A(S+3)*A(S+11) + A(S+4)*A(S+10) + A(S+5)*A(S+9) + A(S+6)*A(S+8))*Digit_Two + A(S+7)*A(S+7); end if; if Ultimate_No_of_Digits >= 14 then A (S+13) :=(A(S+0)*A(S+13) + A(S+1)*A(S+12) + A(S+2)*A(S+11) + A(S+3)*A(S+10) + A(S+4)*A(S+9) + A(S+5)*A(S+8) + A(S+6)*A(S+7))*Digit_Two; end if; if Ultimate_No_of_Digits >= 13 then A (S+12) :=(A(S+0)*A(S+12) + A(S+1)*A(S+11) + A(S+2)*A(S+10) + A(S+3)*A(S+9) + A(S+4)*A(S+8) + A(S+5)*A(S+7))*Digit_Two + A(S+6)*A(S+6); end if; if Ultimate_No_of_Digits >= 12 then A (S+11) :=(A(S+0)*A(S+11) + A(S+1)*A(S+10) + A(S+2)*A(S+9) + A(S+3)*A(S+8) + A(S+4)*A(S+7) + A(S+5)*A(S+6))*Digit_Two; end if; if Ultimate_No_of_Digits >= 11 then A (S+10) := (A(S+0)*A(S+10) + A(S+1)*A(S+9) + A(S+2)*A(S+8) + A(S+3)*A(S+7) + A(S+4)*A(S+6)) * Digit_Two + A(S+5)*A(S+5); end if; if Ultimate_No_of_Digits >= 10 then A (S+9) := (A(S+0)*A(S+9) + A(S+1)*A(S+8) + A(S+2)*A(S+7) + A(S+3)*A(S+6) + A(S+4)*A(S+5)) * Digit_Two; end if; if Ultimate_No_of_Digits >= 9 then A (S+8) := (A(S+0)*A(S+8) + A(S+1)*A(S+7) + A(S+2)*A(S+6) + A(S+3)*A(S+5)) * Digit_Two + A(S+4)*A(S+4); end if; if Ultimate_No_of_Digits >= 8 then A (S+7) := (A(S+0)*A(S+7) + A(S+1)*A(S+6) + A(S+2)*A(S+5) + A(S+3)*A(S+4)) * Digit_Two; end if; if Ultimate_No_of_Digits >= 7 then A (S+6) := (A(S+0)*A(S+6) + A(S+1)*A(S+5) + A(S+2)*A(S+4)) * Digit_Two + A(S+3)*A(S+3); end if; if Ultimate_No_of_Digits >= 6 then A (S+5) := (A(S+0)*A(S+5) + A(S+1)*A(S+4) + A(S+2)*A(S+3)) * Digit_Two; end if; A (S+4) := A(S+2)*A(S+2) + (A(S+0)*A(S+4) + A(S+1)*A(S+3)) * Digit_Two; A (S+3) :=(A(S+0)*A(S+3) + A(S+1)*A(S+2)) * Digit_Two; A (S+2) := A(S+1)*A(S+1) + A(S+0)*A(S+2) * Digit_Two; A (S+1) := A(S+0)*A(S+1) * Digit_Two; A (S+0) := A(S+0)*A(S+0); end Product_if_digits_fewer_than_17; begin -- Step 0. Handle the Zeros. We'll say 0 * infinity is 0, since inf is -- really just a large finite number. if X.Is_Zero then return; end if; -- Step 2. Do the multiplication. We can only sum 32 elements of the sum -- before the carrys must be done (in one stnd setting). -- We use the inner product version (inner loop is an -- dot-product.) To get the outer product version (BLAS routine DAXPY), -- interchange the order of the loops. -- -- Here's the idea: -- for Digit_ID in Digit_Index loop -- Sum := 0.0; -- for k in 0..Digit_ID loop -- Sum := Sum + X(k) * Y(Digit_ID-k); -- end loop; -- Z(Digit_ID) := Sum; -- end loop; -- -- Break sum into segments of 32 each in index k. Perform a carry -- after each sum of 32 elements. if (Ultimate_No_of_Digits < 9 and then No_Of_Bits_In_Radix <= 30) or (Ultimate_No_of_Digits < 17 and then No_Of_Bits_In_Radix <= 29) then Product_if_digits_fewer_than_17; X.Exp := X.Exp + X.Exp; -- Will be further adjusted by "Normalize.." routine. Do_Carrying_For_Multiplication (X, Digit_Minus_1, Digit_Minus_2); -- Must Normalize: shift digit array to make sure that the first digit -- is non-zero: if Infinity or Zero gets this far, then problem occurs. -- Should catch in normalize. Normalize (X, Digit_Minus_1, Digit_Minus_2); X.Is_Positive := True; else X := General_Multiplication (X, X); return; end if; -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. This is all isolated to the end -- of the arithmetic routines so that it is easily modified to -- raise exceptions if that's what is desired. In order to do it -- here, must assume that the parmeters Min_Exponent and Max_Exponent -- limit the dynamic range of the Exp to about 1/4 of that allowed -- by the base type used to represent the exponent. This is -- checked in the spec with an assertion. (The reason is, the above -- code will go well outside the accepted range of Exp with out being -- checked till down here.) This limit is OK because the base type -- allows excessively large exponents anyway, up to 2**31-1. if X.Exp < Min_Exponent then X := Zero; end if; if X.Exp > Max_Exponent then X := Positive_Infinity; end if; end Square; ------------------- -- Multiply_Stnd -- ------------------- -- Suppose Z, X, and Y are composed of n digits 0..n-1. Then X*Y is -- -- Z0 := X0*Y0 -- Z1 := X0*Y1 + X1*Y0 -- Z2 := X0*Y2 + X1*Y1 + X2*Y0 -- ... -- Zn-1 := X0*Yn-1 + X1*Yn-2 + .. + Xn-1*Y0 -- -- Now follows the upper half of the table, which produces words beyond -- the precision of the two number X and Y that are being multiplied. These -- don't calculate. (Just make N larger if more precision is needed). -- If n is minimal for efficiency reasons, then it would be more efficient -- in some calculations to make use the following instead of increasing the -- number of digits to get the required precision. -- -- Zn := Xn-1*Y1 + ... + X1*Yn-1 -- ... -- Z2n-2 := Xn-1*Yn-1 -- function Multiply_Stnd (X, Y : e_Real) return e_Real is Z : e_Real := X; Digit_Minus_1, Digit_Minus_2 : Digit_Type := Digit_Zero; -- Essential init Ultimate_No_of_Digits : constant := Ultimate_Digit + 1; -- equals: Digit_Index'Last - Digit_Index'First + 1 = Mantissa'Length ------------------------------------- -- Product_if_digits_fewer_than_17 -- ------------------------------------- procedure Product_if_digits_fewer_than_17 is pragma Assert (Ultimate_No_of_Digits >= 5); --because no if-then's for 1st 5. pragma Assert (Ultimate_No_of_Digits < 17); pragma Assert (No_Of_Bits_In_Radix <= 30); -- (not a) or b is same as a implies b. -- no need to carry until the end if following evaluate to true: pragma Assert (not (No_Of_Bits_In_Radix = 30) or Ultimate_No_of_Digits <= 8); pragma Assert (not (No_Of_Bits_In_Radix = 29) or Ultimate_No_of_Digits <= 32); pragma Suppress (Index_Check); A : Mantissa renames Z.Digit; B : Mantissa renames Y.Digit; S : constant Digit_Index := Digit_Index'First; begin -- would need to do intermediate carrying if -- No_Of_Bits_In_Radix >= 30 and Ultimate_No_of_Digits > 5. -- Ultimate_No_of_Digits is named number, so optimizer should -- eliminate unused blocks of code below... if Ultimate_No_of_Digits >= 16 then A(S+15) := A(S+0)*B(S+15) + A(S+1)*B(S+14) + A(S+2)*B(S+13) + A(S+3)*B(S+12) + A(S+4)*B(S+11) + A(S+5)*B(S+10) + A(S+6)*B(S+9) + A(S+7)*B(S+8) + A(S+8)*B(S+7) + A(S+9)*B(S+6) + A(S+10)*B(S+5) + A(S+11)*B(S+4) + A(S+12)*B(S+3) + A(S+13)*B(S+2) + A(S+14)*B(S+1) + A(S+15)*B(S+0); end if; if Ultimate_No_of_Digits >= 15 then A(S+14) := A(S+0)*B(S+14) + A(S+1)*B(S+13) + A(S+2)*B(S+12) + A(S+3)*B(S+11) + A(S+4)*B(S+10) + A(S+5)*B(S+9) + A(S+6)*B(S+8) + A(S+7)*B(S+7) + A(S+8)*B(S+6) + A(S+9)*B(S+5) + A(S+10)*B(S+4) + A(S+11)*B(S+3) + A(S+12)*B(S+2) + A(S+13)*B(S+1) + A(S+14)*B(S+0); end if; if Ultimate_No_of_Digits >= 14 then A(S+13) := A(S+0)*B(S+13) + A(S+1)*B(S+12) + A(S+2)*B(S+11) + A(S+3)*B(S+10) + A(S+4)*B(S+9) + A(S+5)*B(S+8) + A(S+6)*B(S+7) + A(S+7)*B(S+6) + A(S+8)*B(S+5) + A(S+9)*B(S+4) + A(S+10)*B(S+3) + A(S+11)*B(S+2) + A(S+12)*B(S+1) + A(S+13)*B(S+0); end if; if Ultimate_No_of_Digits >= 13 then A(S+12) := A(S+0)*B(S+12) + A(S+1)*B(S+11) + A(S+2)*B(S+10) + A(S+3)*B(S+9) + A(S+4)*B(S+8) + A(S+5)*B(S+7) + A(S+6)*B(S+6) + A(S+7)*B(S+5) + A(S+8)*B(S+4) + A(S+9)*B(S+3) + A(S+10)*B(S+2) + A(S+11)*B(S+1) + A(S+12)*B(S+0); end if; if Ultimate_No_of_Digits >= 12 then A(S+11) := A(S+0)*B(S+11) + A(S+1)*B(S+10) + A(S+2)*B(S+9) + A(S+3)*B(S+8) + A(S+4)*B(S+7) + A(S+5)*B(S+6) + A(S+6)*B(S+5) + A(S+7)*B(S+4) + A(S+8)*B(S+3) + A(S+9)*B(S+2) + A(S+10)*B(S+1) + A(S+11)*B(S+0); end if; if Ultimate_No_of_Digits >= 11 then A(S+10) := A(S+0)*B(S+10) + A(S+1)*B(S+9) + A(S+2)*B(S+8) + A(S+3)*B(S+7) + A(S+4)*B(S+6) + A(S+5)*B(S+5) + A(S+6)*B(S+4) + A(S+7)*B(S+3) + A(S+8)*B(S+2) + A(S+9)*B(S+1) + A(S+10)*B(S+0); end if; if Ultimate_No_of_Digits >= 10 then A(S+9) := A(S+0)*B(S+9) + A(S+1)*B(S+8) + A(S+2)*B(S+7) + A(S+3)*B(S+6) + A(S+4)*B(S+5) + A(S+5)*B(S+4) + A(S+6)*B(S+3) + A(S+7)*B(S+2) + A(S+8)*B(S+1) + A(S+9)*B(S+0); end if; if Ultimate_No_of_Digits >= 9 then A(S+8) := A(S+0)*B(S+8) + A(S+1)*B(S+7) + A(S+2)*B(S+6) + A(S+3)*B(S+5) + A(S+4)*B(S+4) + A(S+5)*B(S+3) + A(S+6)*B(S+2) + A(S+7)*B(S+1) + A(S+8)*B(S+0); end if; if Ultimate_No_of_Digits >= 8 then A(S+7) := A(S+0)*B(S+7) + A(S+1)*B(S+6) + A(S+2)*B(S+5) + A(S+3)*B(S+4) + A(S+4)*B(S+3) + A(S+5)*B(S+2) + A(S+6)*B(S+1) + A(S+7)*B(S+0); end if; if Ultimate_No_of_Digits >= 7 then A(S+6) := A(S+0)*B(S+6) + A(S+1)*B(S+5) + A(S+2)*B(S+4) + A(S+3)*B(S+3) + A(S+4)*B(S+2) + A(S+5)*B(S+1) + A(S+6)*B(S+0); end if; if Ultimate_No_of_Digits >= 6 then A(S+5) := A(S+0)*B(S+5) + A(S+1)*B(S+4) + A(S+2)*B(S+3) + A(S+3)*B(S+2) + A(S+4)*B(S+1) + A(S+5)*B(S+0); end if; A(S+4) := A(S+0)*B(S+4) + A(S+1)*B(S+3) + A(S+2)*B(S+2) + A(S+3)*B(S+1) + A(S+4)*B(S+0); A(S+3) := A(S+0)*B(S+3) + A(S+1)*B(S+2) + A(S+2)*B(S+1) + A(S+3)*B(S+0); A(S+2) := A(S+0)*B(S+2) + A(S+1)*B(S+1) + A(S+2)*B(S+0); A(S+1) := A(S+0)*B(S+1) + A(S+1)*B(S+0); A(S+0) := A(S+0)*B(S+0); end Product_if_digits_fewer_than_17; begin -- Step 0. Handle the Zeros. We'll say 0 * infinity is 0, since inf is -- really just a large finite number. if X.Is_Zero or Y.Is_Zero then return Zero; end if; Z.Is_Zero := False; -- toggled below if underflow. -- Step 1. If one or more is infinite..Notice inf * inf = inf here. if Y.Is_Infinite or X.Is_Infinite then if X.Is_Positive xor Y.Is_Positive then -- opposite signs. return Negative_Infinity; else return Positive_Infinity; end if; end if; -- Step 2. Handle the signs and exponents: Z.Is_Positive := not (X.Is_Positive XOR Y.Is_Positive); Z.Exp := X.Exp + Y.Exp; -- Will be further adjusted by "Carry.." routine. -- Step 3. Do the multiplication. Can only sum (say) 32 elements of -- the sum before the carrys must be done. -- We use the inner product version (inner loop is an -- dot-product.) To get the outer product version (BLAS routine DAXPY), -- interchange the order of the loops. -- -- Here's the idea: -- for Digit_ID in Digit_Index loop -- Sum := 0.0; -- for k in 0..Digit_ID loop -- Sum := Sum + X(k) * Y(Digit_ID-k); -- end loop; -- Z(Digit_ID) := Sum; -- end loop; -- -- Break sum into segments of 32 each in index k. Perform a carry -- after each sum of 32 elements. if (Ultimate_No_of_Digits < 9 and then No_Of_Bits_In_Radix <= 30) or (Ultimate_No_of_Digits < 17 and then No_Of_Bits_In_Radix <= 29) then Product_if_digits_fewer_than_17; -- Z = Z * Y (Z has been initialized to X). Do_Carrying_For_Multiplication (Z, Digit_Minus_1, Digit_Minus_2); -- the procedure requires initialized (0) Digit_Minus_1, ... else Z := General_Multiplication (X, Y); return Z; end if; -- Must Normalize: shift digit array to make sure that the first digit -- is non-zero: if Infinity or Zero gets this far, then problem occurs. -- Should catch in normalize. Normalize (Z, Digit_Minus_1, Digit_Minus_2); -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. In order to do it -- here, must assume that the parmeters Min_Exponent and Max_Exponent -- limit the dynamic range of the Exp to about 1/4 of that allowed -- by the base type used to represent the exponent. This is -- checked in the spec with an assertion. (The reason is, the above -- code will go well outside the accepted range of Exp with out being -- checked till down here.) This limit is OK because the base type -- allows excessively large exponents anyway, up to 2**31-1. if Z.Exp < Min_Exponent then Z := Zero; end if; if Z.Exp > Max_Exponent then if Z.Is_Positive then Z := Positive_Infinity; else Z := Negative_Infinity; end if; end if; return Z; end Multiply_Stnd; pragma Inline (Multiply_Stnd); ---------- -- Mult -- ---------- -- Suppose Z, X, and Y are composed of n digits 0..n-1. Then X*Y is -- -- Z0 := X0*Y0 -- Z1 := X0*Y1 + X1*Y0 -- Z2 := X0*Y2 + X1*Y1 + X2*Y0 -- ... -- Zn-1 := X0*Yn-1 + X1*Yn-2 + .. + Xn-1*Y0 -- -- Now follows the upper half of the table, which produces words beyond -- the precision of the two number X and Y that are being multiplied. These -- don't calculate. (Just make N larger if more precision is needed). -- If n is minimal for efficiency reasons, then it would be more efficient -- in some calculations to make use the following instead of increasing the -- number of digits to get the required precision. -- -- Zn := Xn-1*Y1 + ... + X1*Yn-1 -- ... -- Z2n-2 := Xn-1*Yn-1 -- procedure Mult (X : in out e_Real; Y : in e_Real) is Digit_Minus_1, Digit_Minus_2 : Digit_Type := Digit_Zero; -- Essential init Ultimate_No_of_Digits : constant := Ultimate_Digit + 1; -- equals: Digit_Index'Last - Digit_Index'First + 1 = Mantissa'Length ------------------------------------- -- Product_if_digits_fewer_than_17 -- ------------------------------------- procedure Product_if_digits_fewer_than_17 is pragma Assert (Ultimate_No_of_Digits >= 5); --because no if-then's for 1st 5. pragma Assert (Ultimate_No_of_Digits < 17); pragma Assert (No_Of_Bits_In_Radix <= 30); -- (not a) or b is same as a implies b. -- no need to carry until the end if following evaluate to true: pragma Assert (not (No_Of_Bits_In_Radix = 30) or Ultimate_No_of_Digits <= 8); pragma Assert (not (No_Of_Bits_In_Radix = 29) or Ultimate_No_of_Digits <= 32); pragma Suppress (Index_Check); A : Mantissa renames X.Digit; B : Mantissa renames Y.Digit; S : constant Digit_Index := Digit_Index'First; --Result : Mantissa; begin -- would need to do intermediate carrying if -- No_Of_Bits_In_Radix >= 30 and Ultimate_No_of_Digits > 5. -- Ultimate_No_of_Digits is named number, so optimizer should -- eliminate unused blocks of code below... -- ! Must be done in the following order ! if Ultimate_No_of_Digits >= 16 then A (S+15) := A(S+0)*B(S+15) + A(S+1)*B(S+14) + A(S+2)*B(S+13) + A(S+3)*B(S+12) + A(S+4)*B(S+11) + A(S+5)*B(S+10) + A(S+6)*B(S+9) + A(S+7)*B(S+8) + A(S+8)*B(S+7) + A(S+9)*B(S+6) + A(S+10)*B(S+5) + A(S+11)*B(S+4) + A(S+12)*B(S+3) + A(S+13)*B(S+2) + A(S+14)*B(S+1) + A(S+15)*B(S+0); end if; if Ultimate_No_of_Digits >= 15 then A (S+14) := A(S+0)*B(S+14) + A(S+1)*B(S+13) + A(S+2)*B(S+12) + A(S+3)*B(S+11) + A(S+4)*B(S+10) + A(S+5)*B(S+9) + A(S+6)*B(S+8) + A(S+7)*B(S+7) + A(S+8)*B(S+6) + A(S+9)*B(S+5) + A(S+10)*B(S+4) + A(S+11)*B(S+3) + A(S+12)*B(S+2) + A(S+13)*B(S+1) + A(S+14)*B(S+0); end if; if Ultimate_No_of_Digits >= 14 then A (S+13) := A(S+0)*B(S+13) + A(S+1)*B(S+12) + A(S+2)*B(S+11) + A(S+3)*B(S+10) + A(S+4)*B(S+9) + A(S+5)*B(S+8) + A(S+6)*B(S+7) + A(S+7)*B(S+6) + A(S+8)*B(S+5) + A(S+9)*B(S+4) + A(S+10)*B(S+3) + A(S+11)*B(S+2) + A(S+12)*B(S+1) + A(S+13)*B(S+0); end if; if Ultimate_No_of_Digits >= 13 then A (S+12) := A(S+0)*B(S+12) + A(S+1)*B(S+11) + A(S+2)*B(S+10) + A(S+3)*B(S+9) + A(S+4)*B(S+8) + A(S+5)*B(S+7) + A(S+6)*B(S+6) + A(S+7)*B(S+5) + A(S+8)*B(S+4) + A(S+9)*B(S+3) + A(S+10)*B(S+2) + A(S+11)*B(S+1) + A(S+12)*B(S+0); end if; if Ultimate_No_of_Digits >= 12 then A (S+11) := A(S+0)*B(S+11) + A(S+1)*B(S+10) + A(S+2)*B(S+9) + A(S+3)*B(S+8) + A(S+4)*B(S+7) + A(S+5)*B(S+6) + A(S+6)*B(S+5) + A(S+7)*B(S+4) + A(S+8)*B(S+3) + A(S+9)*B(S+2) + A(S+10)*B(S+1) + A(S+11)*B(S+0); end if; if Ultimate_No_of_Digits >= 11 then A (S+10) := A(S+0)*B(S+10) + A(S+1)*B(S+9) + A(S+2)*B(S+8) + A(S+3)*B(S+7) + A(S+4)*B(S+6) + A(S+5)*B(S+5) + A(S+6)*B(S+4) + A(S+7)*B(S+3) + A(S+8)*B(S+2) + A(S+9)*B(S+1) + A(S+10)*B(S+0); end if; if Ultimate_No_of_Digits >= 10 then A (S+9) := A(S+0)*B(S+9) + A(S+1)*B(S+8) + A(S+2)*B(S+7) + A(S+3)*B(S+6) + A(S+4)*B(S+5) + A(S+5)*B(S+4) + A(S+6)*B(S+3) + A(S+7)*B(S+2) + A(S+8)*B(S+1) + A(S+9)*B(S+0); end if; if Ultimate_No_of_Digits >= 9 then A (S+8) := A(S+0)*B(S+8) + A(S+1)*B(S+7) + A(S+2)*B(S+6) + A(S+3)*B(S+5) + A(S+4)*B(S+4) + A(S+5)*B(S+3) + A(S+6)*B(S+2) + A(S+7)*B(S+1) + A(S+8)*B(S+0); end if; if Ultimate_No_of_Digits >= 8 then A (S+7) := A(S+0)*B(S+7) + A(S+1)*B(S+6) + A(S+2)*B(S+5) + A(S+3)*B(S+4) + A(S+4)*B(S+3) + A(S+5)*B(S+2) + A(S+6)*B(S+1) + A(S+7)*B(S+0); end if; if Ultimate_No_of_Digits >= 7 then A (S+6) := A(S+0)*B(S+6) + A(S+1)*B(S+5) + A(S+2)*B(S+4) + A(S+3)*B(S+3) + A(S+4)*B(S+2) + A(S+5)*B(S+1) + A(S+6)*B(S+0); end if; if Ultimate_No_of_Digits >= 6 then A (S+5) := A(S+0)*B(S+5) + A(S+1)*B(S+4) + A(S+2)*B(S+3) + A(S+3)*B(S+2) + A(S+4)*B(S+1) + A(S+5)*B(S+0); end if; A (S+4) := A(S+0)*B(S+4) + A(S+1)*B(S+3) + A(S+2)*B(S+2) + A(S+3)*B(S+1) + A(S+4)*B(S+0); A (S+3) := A(S+0)*B(S+3) + A(S+1)*B(S+2) + A(S+2)*B(S+1) + A(S+3)*B(S+0); A (S+2) := A(S+0)*B(S+2) + A(S+1)*B(S+1) + A(S+2)*B(S+0); A (S+1) := A(S+0)*B(S+1) + A(S+1)*B(S+0); A (S+0) := A(S+0)*B(S+0); end Product_if_digits_fewer_than_17; begin -- Step 0. Handle the Zeros. We'll say 0 * infinity is 0, since inf is -- really just a large finite number. if X.Is_Zero or Y.Is_Zero then X := Zero; return; end if; -- Step 1. If one or more is infinite..Notice inf * inf = inf here. if Y.Is_Infinite or X.Is_Infinite then if X.Is_Positive xor Y.Is_Positive then -- opposite signs. X := Negative_Infinity; else X := Positive_Infinity; end if; return; end if; -- Step 3. Do the multiplication. We can only sum 32 elements of the sum -- before the carrys must be done. -- We use the inner product version (inner loop is an -- dot-product.) To get the outer product version (BLAS routine DAXPY), -- interchange the order of the loops. -- -- Here's the idea: -- for Digit_ID in Digit_Index loop -- Sum := 0.0; -- for k in 0..Digit_ID loop -- Sum := Sum + X(k) * Y(Digit_ID-k); -- end loop; -- Z(Digit_ID) := Sum; -- end loop; -- -- Break sum into segments of 32 each in index k. Perform a carry -- after each sum of 32 elements. if (Ultimate_No_of_Digits < 9 and then No_Of_Bits_In_Radix <= 30) or (Ultimate_No_of_Digits < 17 and then No_Of_Bits_In_Radix <= 29) then -- Notice we only change X here, not above, in case the else is used. X.Is_Positive := not (X.Is_Positive XOR Y.Is_Positive); X.Exp := X.Exp + Y.Exp; -- Will be further adjusted by "Normalize.." routine. Product_if_digits_fewer_than_17; Do_Carrying_For_Multiplication (X, Digit_Minus_1, Digit_Minus_2); else X := General_Multiplication (X, Y); return; end if; Normalize (X, Digit_Minus_1, Digit_Minus_2); -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. This analysis is all isolated to the end -- of the arithmetic routines so that it is more easily modified to -- raise exceptions if that's what is desired. In order to do it -- here, must assume that the parmeters Min_Exponent and Max_Exponent -- limit the dynamic range of the Exp to about 1/4 of that allowed -- by the base type used to represent the exponent. This is -- checked in the spec with an assertion. (The reason is, the above -- code will go well outside the accepted range of Exp with out being -- checked till down here.) This limit is OK because the base type -- allows excessively large exponents anyway, up to 2**31-1. if X.Exp < Min_Exponent then X := Zero; end if; if X.Exp > Max_Exponent then if X.Is_Positive then X := Positive_Infinity; else X := Negative_Infinity; end if; end if; end Mult; ----------------------- -- Multiply_In_Place -- ----------------------- function Multiply_In_Place (X, Y : e_Real) return e_Real is Z : e_Real := X; begin Mult (Z, Y); return Z; end Multiply_In_Place; function "*" (X : e_Real; Y : e_Real) return e_Real renames Multiply_In_Place; --function "*" (X : e_Real; Y : e_Real) return e_Real renames Multiply_stnd; -- These 2 about the same. Multiply_In_Place calls procedure Mult. --------- -- "*" -- --------- -- Multiply the first and only digit of X by Y. function "*"(X : e_Digit; Y : e_Real) return e_Real is Z : e_Real; Digit_Minus_1 : Digit_Type := Digit_Zero; --Essential init Digit_Minus_2 : constant Digit_Type := Digit_Zero; --Essential init Carry_Minus_1 : Digit_Type := Digit_Zero; --Essential init I : Digit_Index; begin -- Step 0. Sign etc. -- Notice this assumes 0 * inf = 0. if X.Is_Zero or Y.Is_Zero then return Zero; end if; -- Step 1. Infinities. Digit can't be inf. Z.Is_Positive := not (X.Is_Positive XOR Y.Is_Positive); if Y.Is_Infinite then if Z.Is_Positive then return Positive_Infinity; else return Negative_Infinity; end if; end if; Z.Is_Zero := False; Z.Exp := X.Exp + Y.Exp; for I in Digit_Index'First .. Digit_Index'Last loop Z.Digit(I) := X.Digit * Y.Digit(I); end loop; -- Step 2. Do the carries. This is simpler than the more general version -- because you carry at most one digit. (The Max is of Digit*Digit is -- Radix**2 - 2*Radix + 1. This results in a carry of approx. Radix. Add -- this the the next higher order digit to get a max of Radix**2 - Radix. -- So still don't overflow the Range over which a single carry is -- all that's needed: 0..Radix**2 - 1.) -- Carry_Minus_2 is always zero, and Digit_Minus_2 is always 0. for I in reverse Digit_Index'First+1 .. Digit_Index'Last loop Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (Z.Digit(I)); Z.Digit(I) := Z.Digit(I) - Carry_Minus_1 * Digit_Radix; Z.Digit(I-1) := Z.Digit(I-1) + Carry_Minus_1; end loop; -- Special case I = Digit_Index'First = 0 I := 0; Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (Z.Digit(I)); Z.Digit(I) := Z.Digit(I) - Carry_Minus_1 * Digit_Radix; Digit_Minus_1 := Carry_Minus_1; -- Step 3. Must Normalize: shift digit array to make sure that the first -- digit is non-zero. Normalize (Z, Digit_Minus_1, Digit_Minus_2); -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. if Z.Exp < Min_Exponent then Z := Zero; end if; if Z.Exp > Max_Exponent then if Z.Is_Positive then Z := Positive_Infinity; else Z := Negative_Infinity; end if; end if; return Z; end "*"; ------------- -- Scaling -- ------------- -- S'Scaling (X, Exp) -- Exp -- Let v be the value X*T'Machine_Radix . If v is a -- machine number of the type T, or if |v|GT'Model_Small, -- the function yields v; otherwise, it yields either one -- of the machine numbers of the type T adjacent to v. -- Constraint_Error is optionally raised if v is outside -- the base range of S. A zero result has the sign of X -- when S'Signed_Zeros is True. -- function Scaling (X : e_Digit; Adjustment : e_Integer) return e_Digit is X2 : e_Digit := X; begin if X.Is_Zero then return X2; end if; X2.Exp := X.Exp + Adjustment; if X2.Exp < Min_Exponent or else X2.Exp > Max_Exponent then raise Constraint_Error with "Exp out of range in Scaling e_Digit operation."; end if; return X2; end Scaling; ------------------- -- Make_Extended -- ------------------- -- Turn Digit into Extended: function Make_Extended (X : e_Digit) return e_Real is Z : e_Real; -- initialized to Zero. Import. begin Z.Digit(0) := X.digit; Z.Is_Positive := X.Is_Positive; Z.Exp := X.Exp; Z.Is_Zero := X.Is_Zero; Z.Is_Infinite := False; return Z; end Make_Extended; ------------ -- Sum_Of -- ------------ -- Optimized SUM routine for e_Digit + e_Real -> e_Real. function Sum_Of (X : e_Digit; Y : e_Real) return e_Real is Z : e_Real := Y; Delta_Exp : e_Integer; New_Digit_1 : Digit_Type := Digit_Zero; New_Digit_2 : Digit_Type := Digit_Zero; Need_To_Carry : Boolean := False; type Max_Info is (X_Is_Max, Y_Is_Max); Max_Num_ID : Max_Info := X_Is_Max; begin -- Step 0. If Either of the numbers is 0.0, then return the other. if X.Is_Zero then return Y; elsif Y.Is_Zero then return Make_Extended (X); end if; -- Step 0b. If X is infinite, it doesn't matter what do. if Y.Is_Infinite then return Y; end if; -- Step 0c. If one is positive and the other neg., then are lazy. -- Do it the slow way. if X.Is_Positive XOR Y.Is_Positive then return (Y + Make_Extended (X)); end if; -- Step 1. Now they either both Positive or both Neg. Sum them if it's -- easy and return with the right sign. Start by finding the larger -- number, Exponent-wise. *Notice Y.Exp = X.Exp is classified as Y_Is_Max.* if X.Exp > Y.Exp then Max_Num_ID := X_Is_Max; else Max_Num_ID := Y_Is_Max; end if; Delta_Exp := Abs (X.Exp - Y.Exp); if Delta_Exp > e_Integer(Digit_Index'Last) then -- ie, Delta_Exp >= No_Of_Digits case Max_Num_ID is when Y_Is_Max => return Y; when X_Is_Max => return Make_Extended (X); end case; end if; -- Step 2. If the digit X has the smaller exponent, then try -- an optimization. Otherwise just use the full scale "+". -- We verified above that Delta_Exp is in range of index of X.Digit. -- The optimization covers the most common case by far in the "/" routine -- and most other uses of this function: Y > X, and same sign. -- We allow at most one carry..if more are required, give up trying. if Max_Num_ID = Y_Is_Max then New_Digit_1 := X.digit + Y.Digit(Delta_Exp); if New_Digit_1 > Digit_Radix_Minus_1 then Need_To_Carry := True; end if; if Need_To_Carry and then (Delta_Exp = 0) then -- would have to normalize. goto Abort_Optimization; end if; if Need_To_Carry then New_Digit_1 := New_Digit_1 - Digit_Radix; New_Digit_2 := Y.Digit(Delta_Exp-1) + Digit_One; -- Carry. if New_Digit_2 > Digit_Radix_Minus_1 then -- give up trying. goto Abort_Optimization; end if; end if; -- If got this far, then are going through with it. -- just change the 1 or 2 digits of X, call it Z, and return it: -- Z := Y; -- Z is initialized to Y: Z.Digit(Delta_Exp) := New_Digit_1; if Need_To_Carry then Z.Digit(Delta_Exp-1) := New_Digit_2; end if; -- Recall that X and Y have same sign. This must be the -- sign of Z. OK, the Z := Y establishes this. return Z; end if; <<Abort_Optimization>> -- Step 3. If got this far, the optimization failed. Do it the -- slow way. return (Y + Make_Extended (X)); end Sum_Of; --------- -- "/" -- --------- -- Calculate Quotient = X / Y. -- Schoolboy algorithm. Not fast. Get Quotient a digit at a time. -- Estimate trial Next_Digit by dividing first few digits of X by first few -- digits of Y. Make this ratio into the proper range for a digit. -- Multiply this Next_Digit by Y to get Product. (This step is why do it -- a digit at a time. The above multiplication by Y can be highly optimized -- then.) Subtract Product from X to get Remainder. Increment Quotient -- by Next_Digit. Repeat the above steps with X replaced by Remainder. -- Continue until Remainder has an exponent so small that subsequent -- Next_Digit's are too small to contribute to Quotient. -- -- Few remarks: Next_Digit may not really be the next digit in Quotient. -- It should usually be, but sometimes it's too small, and very rarely, it's -- too large. Nevertheless, you increment Quotient by Next_Digit and -- converge on the answer. Also, when Next_Digit is too large, Remainder -- becomes negative, and one *subtracts* the next Next_Digit from quotient, -- and *adds* the next Product to Remainder, and continues doing this as -- long as Remainder is negative. In other words can converge on the -- quotient from either above or below. So are calculating each -- iteration another pseudo-digit, DigitJ, such that, for example. -- -- Y * (Digit0 + Digit1 + Digit3 - Digit4 + Digit5 ...) = X, -- -- Add up the digits to get the approximation of X / Y. -- Some are negative (rare), some positive, but they add up to Quotient. -- More precisely, -- -- X - Y * (Digit0 + Digit1 + Digit3 - Digit4 + Digit5 ...) = Remainder, -- -- where X.Exp - Remainder.Exp > Digit_Index'Last. Further -- Digits contribute negligably to Quotient when this inequality holds. -- For example, if there are 2 digits, then Digit_Index'Lasts = 1, so that if -- X.Exp - Remainder.Exp > Digit_Index'Last = 1 then the difference in -- exponents guarantees that subsequent iterations contribute to digits -- beyond Digit_Index'Last in the Quotient. function "/" (X, Y : e_Real) return e_Real is Delta_Remainder : e_Real; Remainder_Of_X : e_Real := X; -- init important. Quotient : e_Real; -- Initialized to zero (important). Next_Digit : e_Digit; -- Initialized to zero (important). Next_Digit_Val : Digit_Type; Real_Next_Digit_Val : Real; Real_Y, Inverse_Real_Y, Real_Remainder_Of_X : Real; Decrement_Digit_Exp : Boolean := False; Count : e_Integer := 0; Max_Allowed_Iterations : constant e_Integer := Digit_Index'Last * 2; begin -- Step 0. Handle Zeros and Infinities. Do signs at very end. Until -- the very end pretend that Quotient is positive. if Y.Is_Zero then raise Constraint_Error with "Division by zero."; end if; if X.Is_Zero then return Zero; end if; if X.Is_Infinite and Y.Is_Infinite then raise Constraint_Error with "Division of inf by inf is undefined."; end if; if X.Is_Infinite then if (X.Is_Positive xor Y.Is_Positive) then return Negative_Infinity; else return Positive_Infinity; end if; end if; if Y.Is_Infinite and (not X.Is_Infinite) then return Zero; end if; -- Step 1. We initialized Remainder_Of_X to X. Below make it positive, -- and assume all quantities are positive. Signs are set at end. -- Inverse_Real_Y is in range [1.0/(Radix-Eps) .. 1.0]. -- Real_Remainder_Of_X is in range [1.0 .. (Radix-Eps)]. -- Next_Digit is Real_Floor (Real_Remainder_Of_X*Inverse_Real_Y) where -- the product has been multiplied by Radix if it's less than 1.0. -- Possible range of Next_Digit: Max is Floor (Radix-eps / 1.0), which -- is Radix-1. Min is Floor (Radix * (1.0 / (Radix-eps))) = 1.0. Real_Y := Real (Y.Digit(0)) + Real (Y.Digit(1)) * Inverse_Radix + Real (Y.Digit(2)) * Inverse_Radix_Squared; Inverse_Real_Y := Real_One / Real_Y; -- Pretend all quantities are positive till end. Quotient.Is_Positive := True; Remainder_Of_X.Is_Positive := True; -- This may go negative. -- Iterate until the remainder is small enough: Iteration: for Iter in e_Integer range 1..Max_Allowed_Iterations loop -- Initialized to X, so it's not zero. Must lead with a nonzero digit. -- Important here to sum ALL three leading digits of Remainder_Of_X. Real_Remainder_Of_X := Real (Remainder_Of_X.Digit(0)) + Real (Remainder_Of_X.Digit(1))*Inverse_Radix + Real (Remainder_Of_X.Digit(2))*Inverse_Radix_Squared; Real_Next_Digit_Val := Real_Remainder_Of_X * Inverse_Real_Y; -- Need Next_Digit in proper range for Mult_For_Div fctn: 1..Radix-1: Decrement_Digit_Exp := False; if Real_Next_Digit_Val < Real_One then Real_Next_Digit_Val := Real_Next_Digit_Val * Real_Radix; Decrement_Digit_Exp := True; end if; Next_Digit_Val := Digit_Floor (Real_Next_Digit_Val); if Next_Digit_Val > Digit_Radix_Minus_1 then Next_Digit_Val := Digit_Radix_Minus_1; end if; --if Next_Digit_Val < Digit_One then -- Should never happen, but test it. -- Next_Digit_Val := Digit_One; --end if; -- Step 2. We now have Next_Digit, which is approx. Remainder_Of_X / Y. -- We are ready to make Next_Digit an e_Digit number. -- (so "*" can be optimized.) It must be in -- the range 1..Radix-1, so truncate first. It has the exponent of -- the Remainder_Of_X.Exp - Y.Exp, but decremented by 1.0 if multiplied -- Next_Digit by Radix above. -- Below remember that Next_Digit was initialized to Zero above, -- and all that is changed in this loop is the digit value, and the Exp. -- Also want the product of Next_Digit and Y to be >0, regardless of Y. -- The conversion from Real to e_Digit could be done by the -- function Make_e_Digit, but lets optimize: Next_Digit.Digit := Next_Digit_val; Next_Digit.Exp := Remainder_Of_X.Exp - Y.Exp; Next_Digit.Is_Zero := False; Next_Digit.Is_Positive := True; if Decrement_Digit_Exp then Next_Digit.Exp := Next_Digit.Exp - 1; end if; -- Step 3. Make the trial product of the next digit with the divisor.. -- this will be subtracted from the remainder. Delta_Remainder := Next_Digit * Y; Delta_Remainder.Is_Positive := True; -- Step 3. Calculate the new "Quotient" and the new "Remainder_Of_X". -- Add Extended_Next_Digit to Quotient, if Old Remainder was > 0. -- Subtract Extended_Next_Digit from Quotient if Old Remainder was < 0. -- If the Old Remainder = 0 then are done; that was checked on -- previous pass of loop by line below. It was checked initially by -- by checking if X = 0. (Remainder was initialized to X, and then made -- positive). if Remainder_Of_X.Is_Positive then -- Add Next_Digit to Quotient, and subtract Delta_Remainder from Remainder. Delta_Remainder.Is_Positive := False; Next_Digit.Is_Positive := True; else -- Subtract Next_Digit from Quotient, and add Delta_Remainder to Remainder. Delta_Remainder.Is_Positive := True; Next_Digit.Is_Positive := False; end if; Remainder_Of_X := Remainder_Of_X + Delta_Remainder; Quotient := Sum_Of (Next_Digit, Quotient); -- Step 4. Are finished? -- Remainder_Of_X.Exp started at X.Exp. Have made it small enough? -- Remember that the calls above may have returned Infinity. Or if they -- returned Zero, then the Exponent is 0. (None of these should happen tho.) if Remainder_Of_X.Is_Zero then exit Iteration; end if; if Remainder_Of_X.Is_Infinite then exit Iteration; end if; if (X.Exp-Remainder_Of_X.Exp) > Digit_Index'Last then exit Iteration; end if; Count := Iter; end loop Iteration; -- Max_Allowed_Iterations is twice the number usually required. I've -- never seen it happen, but just in case: if Count = Max_Allowed_Iterations then -- Should raise error? raise Program_Error with "Convergence problem in division routine."; end if; --Print_Text (Integer'Image(Count)); --Print_Text (" Iterations."); --text_io.new_line; -- Step 5. Set Sign of Quotient. Handle over and under flow. -- Here underflow goes to Zero, overflow to Infinity. -- We can do this here because allowed room to maneuver in range of Exp. Quotient.Is_Positive := not (X.Is_Positive xor Y.Is_Positive); if Quotient.Exp < Min_Exponent then Quotient := Zero; end if; if Quotient.Exp > Max_Exponent then if Quotient.Is_Positive then Quotient := Positive_Infinity; else Quotient := Negative_Infinity; end if; end if; return Quotient; end "/"; --------- -- "*" -- --------- -- Multiply the first and only digit of X by the first and only digit -- of Y. the reduction in Carrying is the big win here. function "*"(X : e_Digit; Y : e_Digit) return e_Real is Z : e_Real; -- Init important. Digit_Minus_1 : Digit_Type := Digit_Zero; -- Init important. Digit_Minus_2 : constant Digit_Type := Digit_Zero; -- Init important. Carry_Minus_1 : Digit_Type := Digit_Zero; -- Init important. I : Digit_Index; begin -- Step 0. Zeros. if X.Is_Zero or Y.Is_Zero then return Zero; end if; Z.Is_Zero := False; -- Step 1. Sign and Infinities. Digits can't be inf. Z.Is_Positive := not (X.Is_Positive XOR Y.Is_Positive); Z.Exp := X.Exp + Y.Exp; Z.Digit(0) := X.Digit * Y.Digit; -- Step 2. Do the carries. This is simpler than the more general version -- because you carry at most one digit. (The Max is of Digit*Digit is -- Radix**2 - 2*Radix + 1. This results in a carry of approx. Radix. Add -- this the the next higher order digit to get a max of Radix**2 - Radix. -- So still don't overflow the Range over which a single carry is -- all that's needed: 0..Radix**2 - 1.) -- Carry_Minus_2 is always zero, and Digit_Minus_2 is always 0. I := 0; Carry_Minus_1 := Shift_Right_No_of_Bits_in_Radix (Z.Digit(I)); Z.Digit(I) := Z.Digit(I) - Carry_Minus_1 * Digit_Radix; Digit_Minus_1 := Carry_Minus_1; -- Step 3. Must Normalize: shift digit array to make sure that the first -- digit is non-zero. Normalize (Z, Digit_Minus_1, Digit_Minus_2); -- Step 4. Handle over and under flow. Here underflow goes to Zero, -- overflow to Infinity. if Z.Exp < Min_Exponent then Z := Zero; end if; if Z.Exp > Max_Exponent then if Z.Is_Positive then Z := Positive_Infinity; else Z := Negative_Infinity; end if; end if; return Z; end "*"; --------- -- "/" -- --------- -- The only difference between this "/" and the general "/" is that -- the (e_Digit * e_Real) operation has been replaced -- with an (e_Digit * e_Digit) operation. This produces -- big savings in time. This is used in elementary math function -- routines, where the efficiency is important. function "/" (X : e_Real; Y : e_Digit) return e_Real is Delta_Remainder : e_Real; Remainder_Of_X : e_Real := X; -- init important. Quotient : e_Real; -- Initialized to zero (important). Next_Digit : e_Digit; -- Initialized to zero (important). Real_Next_Digit_Val : Real; Next_Digit_Val : Digit_Type; Real_Y, Inverse_Real_Y, Real_Remainder_Of_X : Real; Decrement_Digit_Exp : Boolean := False; Count : e_Integer := 0; Max_Allowed_Iterations : constant e_Integer := Digit_Index'Last * 2; begin -- Step 0. Handle Zeros and Infinities. Do signs at very end. Until -- the very end pretend that Quotient is positive. if Y.Is_Zero then raise Constraint_Error with "Division by zero."; end if; if X.Is_Zero then return Zero; end if; if X.Is_Infinite then if (X.Is_Positive xor Y.Is_Positive) then return Negative_Infinity; else return Positive_Infinity; end if; end if; -- Step 1. We initialized Remainder_Of_X to X. Below make it positive, -- and assume all quantities are positive. Signs are set at end. -- Possible range of Next_Digit: Max is Floor (Radix-eps / 1.0), which -- is Radix-1. Min is Floor (Radix * (1.0 / (Radix-eps))) = 1.0. -- Remember, X and Y are normalized and we've tested for 0's, so -- both are in the range 1..Radix-1. Real_Y := Real (Y.Digit); -- >= 1.0, since it's quantized. Inverse_Real_Y := Real_One / Real_Y; -- Pretend all quantities are positive till end. Quotient.Is_Positive := True; Remainder_Of_X.Is_Positive := True; -- This may go negative. -- Iterate until the remainder is small enough. Iteration: for Iter in e_Integer range 1..Max_Allowed_Iterations loop Real_Remainder_Of_X := Real (Remainder_Of_X.Digit(0)) + Real (Remainder_Of_X.Digit(1))*Inverse_Radix + Real (Remainder_Of_X.Digit(1))*Inverse_Radix_Squared; Real_Next_Digit_Val := Real_Remainder_Of_X * Inverse_Real_Y; -- Need Next_Digit in proper range for Mult_For_Div fctn: 1..Radix-1: Decrement_Digit_Exp := False; if Real_Next_Digit_Val < Real_One then Real_Next_Digit_Val := Real_Next_Digit_Val * Real_Radix; Decrement_Digit_Exp := True; end if; Next_Digit_Val := Digit_Floor (Real_Next_Digit_Val); if Next_Digit_Val > Digit_Radix_Minus_1 then Next_Digit_Val := Digit_Radix_Minus_1; end if; --if Next_Digit_Val < Digit_One then -- Should never happen. Perform tests w/o -- Next_Digit_Val := Digit_One; --end if; -- Step 2. We now have Next_Digit, which is approx. Remainder_Of_X / Y. -- We are ready to make Next_Digit an e_Digit number. -- (so "*" can be optimized.) It must be in -- the range 1..Radix-1, so truncate first. It has the exponent of -- the Remainder_Of_X.Exp - Y.Exp, but decremented by 1.0 if multiplied -- Next_Digit by Radix above. -- Below remember that Next_Digit was initialized to Zero above, -- and all that is changed in this loop is the digit value, and the Exp. -- Also want the product of Next_Digit and Y to be >0, regardless of Y. -- The conversion from Real to e_Digit could be done by the -- function Make_e_Digit, but lets optimize: Next_Digit.Digit := Next_Digit_Val; Next_Digit.Exp := Remainder_Of_X.Exp - Y.Exp; Next_Digit.Is_Zero := False; -- Is this always true? Next_Digit.Is_Positive := True; if Decrement_Digit_Exp then Next_Digit.Exp := Next_Digit.Exp - 1; end if; -- Step 3. Make the trial product of the next digit with the divisor.. -- this will be subtracted from the remainder. Delta_Remainder := Next_Digit * Y; Delta_Remainder.Is_Positive := True; -- Step 3. Calculate the new "Quotient" and the new "Remainder_Of_X". -- Add Extended_Next_Digit to Quotient, if Old Remainder was > 0. -- Subtract Extended_Next_Digit from Quotient if Old Remainder was < 0. -- If the Old Remainder = 0 then are done; that was checked on -- previous pass of loop by line below. It was checked initially by -- by checking if X = 0. (Remainder was initialized to X, and then made -- positive). if Remainder_Of_X.Is_Positive then -- Add Next_Digit to Quotient, and -- subtract Delta_Remainder from Remainder. Delta_Remainder.Is_Positive := False; Next_Digit.Is_Positive := True; else -- Subtract Next_Digit from Quotient, and -- add Delta_Remainder to Remainder. Delta_Remainder.Is_Positive := True; Next_Digit.Is_Positive := False; end if; Remainder_Of_X := Remainder_Of_X + Delta_Remainder; Quotient := Sum_Of (Next_Digit, Quotient); -- Step 4. Are finished? -- Remainder_Of_X.Exp started at X.Exp. Have made it small enough? -- Remember that the calls above may have returned Infinity. Or if they -- returned Zero, then the Exponent is 0. (None of these should happen tho.) if Remainder_Of_X.Is_Zero then exit Iteration; end if; if Remainder_Of_X.Is_Infinite then exit Iteration; end if; if (X.Exp-Remainder_Of_X.Exp) > Digit_Index'Last then exit Iteration; end if; Count := Iter; end loop Iteration; -- Max_Allowed_Iterations is twice the number usually required. I've -- never seen it happen, but just in case: if Count = Max_Allowed_Iterations then -- Should raise error? raise Program_Error with "Convergence problem in division routine."; end if; --Print_Text (Integer'Image(Count)); --Print_Text (" Iterations."); --text_io.new_line; -- Step 4. Set Sign of Quotient. Handle over and under flow. -- Here underflow goes to Zero, overflow to Infinity. Quotient.Is_Positive := not (X.Is_Positive xor Y.Is_Positive); if Quotient.Exp < Min_Exponent then Quotient := Zero; end if; if Quotient.Exp > Max_Exponent then if Quotient.Is_Positive then Quotient := Positive_Infinity; else Quotient := Negative_Infinity; end if; end if; return Quotient; end "/"; ---------- -- "**" -- ---------- -- Standard algorithm. Write N in binary form: -- -- N = 2**m0 + 2**m1 + 2**m2 + ... + 2**mn, -- -- where the m0, m1, m2...are the indices of the nonzero binary digits of N. -- Then -- -- X**N = X**(2**m0) * X**(2**m1) * X**(2**m2) * ... * X**(2**mn). -- -- We have written X as product of Powers of X. -- Powers of X are obtained by squaring X, squaring the square of X, -- etc. -- -- 0.0**0 is defined to be 1.0. Anything to the 0 is defined to be 1. -- function "**" (X : e_Real; N : Integer) return e_Real is Power_Of_X, Product : e_Real; Last_Bit_ID : constant Integer := Integer'Size - 2; subtype Bit_Index is Integer range 0..Last_Bit_ID; type Bit_Array is array(Bit_Index) of Integer; Bit : Bit_Array := (others => 0); Exp : Integer := Abs (N); Final_Bit : Bit_Index; Exp_Is_Even : Boolean; begin -- The following seems to be what the lrm implies, even if X=0.0: -- If the exponent N is zero then return 1. (If X is inf this makes -- sense since inf is really just a large finite number.) if N = 0 then return One; end if; -- Next, if the argument X is zero, set the result to zero. -- If the Exponent is negative then raise constraint error. if X.Is_Zero then if N > 0 then return Zero; else raise Constraint_Error with "Error in ** operation, division by 0.0."; end if; end if; -- If the argument X is inf, set the result to inf, or 0 if N < 0. -- If X < 0 then sign depends on whether Exp is even or odd. -- (IS THIS TRUE if N=0? Will assume NO.) if X.Is_Infinite then Exp_Is_Even := ((Exp rem 2) = 0); if X.Is_Positive then Product := Positive_Infinity; else if Exp_Is_Even then Product := Positive_Infinity; else Product := Negative_Infinity; end if; end if; if N < 0 then return Zero; else return Product; end if; end if; -- Should try to avoid possible run-time errors (if, for example, -- N * X.Exp > Max_Exponent)? No: the following -- algorithm uses extended precision "*", which will overflow to -- inf and short-circuit the process efficiently. -- -- Get binary form of the exponent Exp = Abs(N) for I in Bit_Index loop Bit(I) := Exp REM 2; Exp := Exp / 2; Final_Bit := I; if Exp = 0 then exit; end if; end loop; -- Do the arithmetic. Product := One; -- X**0 Power_Of_X := X; -- X**(2**0). Preserves sign of X if N is odd. if Bit(Bit_Index'First) /= 0 then --Product := Product * Power_Of_X; Mult (Product, Power_Of_X); end if; for I in Bit_Index'First+1 .. Final_Bit loop --Power_Of_X := Power_Of_X * Power_Of_X; -- X**(2**I) Square (Power_Of_X); -- X**(2**I), good speed-up if Bit(I) = 1 then --Product := Product * Power_Of_X; Mult (Product, Power_Of_X); end if; end loop; -- Under flow to zero. THe "/" operator should correctly do this, but -- it's important to other routines, so make sure it's done right here: if Product.Is_Infinite and N < 0 then return Zero; end if; if N < 0 then Product := One / Product; -- notice we've already checked for X=0. end if; -- need to do the final over/under flow check? No. The "/" and -- "*" did that for us above. return Product; end "**"; end Extended_Real;
regtests/wiki-parsers-tests.adb
jquorning/ada-wiki
18
24201
----------------------------------------------------------------------- -- wiki-parsers-tests -- Unit tests for wiki parsing -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2017, 2021 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.UTF_Encoding.Wide_Wide_Strings; with Util.Test_Caller; with Wiki.Utils; with Wiki.Helpers; with Wiki.Streams.Builders; with Wiki.Render.Text; package body Wiki.Parsers.Tests is use Wiki.Helpers; package Caller is new Util.Test_Caller (Test, "Wikis.Parsers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)", Test_Wiki_Bold'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)", Test_Wiki_Italic'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)", Test_Wiki_Formats'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)", Test_Wiki_Section'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)", Test_Wiki_List'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)", Test_Wiki_Link'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)", Test_Wiki_Quote'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)", Test_Wiki_Line_Break'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)", Test_Wiki_Image'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)", Test_Wiki_Preformatted'Access); Caller.Add_Test (Suite, "Test Wiki.Text.Renderer", Test_Wiki_Text_Renderer'Access); Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (String UTF-8)", Test_Wiki_UTF_8'Access); end Add_Tests; -- ------------------------------ -- Test bold rendering. -- ------------------------------ procedure Test_Wiki_Bold (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>", Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>", Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX), "Bold rendering invalid (MIX)"); Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>", Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR), "Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>", Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR), "No bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>", Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB), "Bold rendering invalid (PHPBB)"); end Test_Wiki_Bold; -- ------------------------------ -- Test italic rendering. -- ------------------------------ procedure Test_Wiki_Italic (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>item</i></p>", Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>", Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>", Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB), "Italic rendering invalid"); end Test_Wiki_Italic; -- ------------------------------ -- Test various format rendering. -- ------------------------------ procedure Test_Wiki_Formats (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>", Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE), "Italic+Bold rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>", Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE), "Italic rendering invalid"); Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>", Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE), "Italic rendering invalid"); end Test_Wiki_Formats; -- ------------------------------ -- Test heading rendering. -- ------------------------------ procedure Test_Wiki_Section (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<h1>item</h1>", Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h2>item</h2>", Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE), "H2 rendering invalid"); Util.Tests.Assert_Equals (T, "<h3>item</h3>", Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE), "H3 rendering invalid"); Util.Tests.Assert_Equals (T, "<h4>item</h4>", Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE), "H4 rendering invalid"); Util.Tests.Assert_Equals (T, "<h5>item</h5>", Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE), "H5 rendering invalid"); Util.Tests.Assert_Equals (T, "<h6>item</h6>", Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE), "H6 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>", Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE), "H1 rendering invalid"); end Test_Wiki_Section; -- ------------------------------ -- Test list rendering. -- ------------------------------ procedure Test_Wiki_List (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>", Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE), "Ordered list rendering invalid"); Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF & "</li><li>item2 item2" & ASCII.LF & "</li><li><ol>item3</li></ol></ol>", Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3", SYNTAX_GOOGLE), "Ordered rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE), "Bullet list rendering invalid"); Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>", Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR), "Bullet list rendering invalid"); end Test_Wiki_List; -- ------------------------------ -- Test link rendering. -- ------------------------------ procedure Test_Wiki_Link (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""http://www.joe.com/item"" " & "lang=""en"" title=""some""" & ">name</a></p>", Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p>[d</p>", Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE), "No link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a " & "href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>", Wiki.Utils.To_Html ("[http://www.joe.com/item]", SYNTAX_DOTCLEAR), "Link rendering invalid"); Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>", Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI), "Link rendering invalid"); end Test_Wiki_Link; -- ------------------------------ -- Test quote rendering. -- ------------------------------ procedure Test_Wiki_Quote (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>", Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p><q cite=""http://www.sun.com"" lang=""en"">quote</q></p>", Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}", SYNTAX_DOTCLEAR), "Quote rendering invalid"); Util.Tests.Assert_Equals (T, "<p>{quote}}</p>", Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR), "No quote rendering invalid"); end Test_Wiki_Quote; -- ------------------------------ -- Test line break rendering. -- ------------------------------ procedure Test_Wiki_Line_Break (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p>a<br>b</p>", Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a<br>b</p>", Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE), "Line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%%b</p>", Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); Util.Tests.Assert_Equals (T, "<p>a%b</p>", Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR), "No line break rendering invalid"); end Test_Wiki_Line_Break; -- ------------------------------ -- Test image rendering. -- ------------------------------ procedure Test_Wiki_Image (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>", Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" alt=""title"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR), "Image rendering invalid"); Util.Tests.Assert_Equals (T, "<p><img " & "src=""/image/t.png"" longdesc=""describe"" alt=""title"" /></p>", Wiki.Utils.To_Html ("((/image/t.png|title|x|describe))", SYNTAX_DOTCLEAR), "Image rendering invalid"); end Test_Wiki_Image; -- ------------------------------ -- Test preformatted rendering. -- ------------------------------ procedure Test_Wiki_Preformatted (T : in out Test) is begin Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>", Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>", Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x" & ASCII.LF & "</pre>", Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x" & CR & LF & " item3 x", SYNTAX_DOTCLEAR), "Preformat rendering invalid"); end Test_Wiki_Preformatted; -- ------------------------------ -- Test the text renderer. -- ------------------------------ procedure Test_Wiki_Text_Renderer (T : in out Test) is begin Util.Tests.Assert_Equals (T, ASCII.LF & "code", Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE), "Preformat rendering invalid"); Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF, Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE), "Preformat rendering invalid"); end Test_Wiki_Text_Renderer; -- ------------------------------ -- Test the string parser with UTF-8 support. -- ------------------------------ procedure Test_Wiki_UTF_8 (T : in out Test) is procedure Check (Text : in Wiki.Strings.WString); Test_Chars : constant array (Natural range <>) of Wiki.Strings.WChar := (Wiki.Strings.WChar'Val (16#7f#), Wiki.Strings.WChar'Val (16#80#), Wiki.Strings.WChar'Val (16#AE#), Wiki.Strings.WChar'Val (16#1ff#), Wiki.Strings.WChar'Val (16#1fff#), Wiki.Strings.WChar'Val (16#1ffff#), Wiki.Strings.WChar'Val (16#0fffff#)); procedure Check (Text : in Wiki.Strings.WString) is procedure Get (Value : in Wiki.Strings.WString); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Renderer : aliased Wiki.Render.Text.Text_Renderer; Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream; Content : constant String := Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Text); procedure Get (Value : in Wiki.Strings.WString) is begin -- Verify that we got the expected characters. T.Assert (Wiki.Helpers.LF & Text = Value, "Invalid parsing for [" & Content & "]"); end Get; begin Engine.Set_Syntax (SYNTAX_MEDIA_WIKI); Engine.Parse (Content, Doc); Renderer.Set_Output_Stream (Stream'Unchecked_Access); Renderer.Render (Doc); Stream.Iterate (Get'Access); end Check; begin for I in Test_Chars'Range loop Check (Test_Chars (I) & ""); end loop; for J in Test_Chars'Range loop for I in Test_Chars'Range loop Check (Test_Chars (I) & Test_Chars (J) & ""); end loop; end loop; end Test_Wiki_UTF_8; end Wiki.Parsers.Tests;
scripts/.unmute.applescript
looking-for-a-job/mac-volume
1
567
#!/usr/bin/osascript set volume without output muted
xx-web/src/test/java/com/fantasy/xxtest/antlr4/demo02/ArrayInit.g4
xxhome/xx-fanstansy
0
1992
// {1, 2, 3,{5, 8}, 4} grammar ArrayInit; init : '{' value (',' value)* '}'; value : init | INT ; INT : [0-9]+; WS : [ \n\r\t]+ -> skip;
alloy4fun_models/trashltl/models/9/AHQWgfyRCv75CbNNs.als
Kaixi26/org.alloytools.alloy
0
1812
open main pred idAHQWgfyRCv75CbNNs_prop10 { (all f:File | f in Protected implies( always f in Protected)) } pred __repair { idAHQWgfyRCv75CbNNs_prop10 } check __repair { idAHQWgfyRCv75CbNNs_prop10 <=> prop10o }
Cubical/Categories/Constructions/Free.agda
thomas-lamiaux/cubical
1
1902
-- Free category over a directed graph/quiver {-# OPTIONS --safe #-} module Cubical.Categories.Constructions.Free where open import Cubical.Categories.Category.Base open import Cubical.Data.Graph.Base open import Cubical.Data.Graph.Path open import Cubical.Foundations.Prelude hiding (Path) module _ {ℓv ℓe : Level} where module _ (G : Graph ℓv ℓe) (isSetNode : isSet (Node G)) (isSetEdge : ∀ v w → isSet (Edge G v w)) where open Category FreeCategory : Category ℓv (ℓ-max ℓv ℓe) FreeCategory .ob = Node G FreeCategory .Hom[_,_] = Path G FreeCategory .id = pnil FreeCategory ._⋆_ = ccat G FreeCategory .⋆IdL = pnil++ G FreeCategory .⋆IdR P = refl FreeCategory .⋆Assoc = ++assoc G FreeCategory .isSetHom = isSetPath G isSetNode isSetEdge _ _
LCD Slave/Sources/main.asm
Mammothskier/EELE465
0
88564
;Main.s by <NAME>, <NAME> ;1/30/19 ;Slave_LCD INCLUDE 'derivative.inc' XDEF _Startup, main, _Viic XREF __SEG_END_SSTACK ; symbol defined by the linker for the end of the stack ORG $0060 ;----I2C-VARIBLES----------------------------- IIC_addr: DS.B 1 IIC_msg: DS.B 6 ; enable 32 bit transmission msgLength: DS.B 1 current: DS.B 1 current_replacement_position: DS.B 1 write_position: DS.B 1 time_write_position: DS.B 1 screen_write_position: DS.B 1 tens_char: DS.B 1 ones_char: DS.B 1 state: DS.B 1 t92: DS.B 2 seconds: DS.B 1 state_char: DS.B 6 t92_char: DS.B 3 seconds_char: DS.B 3 TIME_FLAG: DS.B 1 IIC_FLAG: DS.B 1 screen: DS.B 32 ORG $E000 E EQU 0 ;PORTA BIT 0 RS EQU 1 ;PORTA BIT 1 chars DC.B '0123456789ABCDEF' cool DC.B ' cool' heat DC.B ' heat' off DC.B ' off' state_replacement DC.B $A, $B, $C, $D, $E, $F t92_replacement DC.B $14, $15, $16 seconds_replacement DC.B $1B, $1C, $1D base DC.B 'TEC state: T92: K@T= s ' main: _Startup: LDHX #__SEG_END_SSTACK ;INITIALZE THE STACK POINTER TXS CLI LDA SOPT1 ;DIABLE WATCHDOG AND #$7E STA SOPT1 ;PTA PINS FOR SDA/SC; LDA SOPT2 AND #%11111101 ;ORA #%00000010 ; STA SOPT2 JSR IIC_Startup_slave ;-----------LCD INITI------------------------------------------------------- ;SET PTBD TO OUTPUT LDA #%11111111 STA PTBDD ;SET PTAD 1:0 TO OUTPUT, LEAVE THE REST ALONE LDA PTADD ORA #%00000011 STA PTADD ;INTIALIZE PORTS CLR PTAD CLR PTBD JSR resetScreen LDA #0 STA IIC_FLAG STA current_replacement_position STA TIME_FLAG STA time_write_position STA state STA seconds STA t92 STA screen_write_position JSR LCD_Startup JSR writeToScreen ;--------------------------------------------------------------------------- mainLoop: LDA IIC_FLAG ADD #$0 CMP #3 ; if this doesn't work, use current instead? BLS mainLoop ; no i2c change CLR IIC_FLAG JSR DELAYLOOP JSR DELAYLOOP JSR DELAYLOOP JSR resetScreen CLRX CLRH LDA IIC_msg,X STA state INCX LDA IIC_msg,X DECX STA t92,X INCX INCX LDA IIC_msg,X DECX STA t92,X INCX INCX LDA IIC_msg,X STA seconds JSR writeToScreen LDA seconds CMP #0 BEQ mainLoop NOP NOP BRA mainLoop resetScreen: CLRH ;shift the base screen into ram to be modified CLRX ;for some reason, this is required if not in debug mode ;when base message is stored in RAM and not in debug, it prints garbage ;this fixes that loadRAM: LDA base,X STA screen,X INCX CPX #$20 BNE loadRAM RTS writeToScreen: JSR resetScreen JSR makeCharArrays CLRX CLRH STX current_replacement_position replace_state_loop: LDX current_replacement_position LDA state_char,X LDX state_replacement,X STA screen,X INC current_replacement_position LDX current_replacement_position CPX #$6 BNE replace_state_loop CLR current_replacement_position BRA replace_t92_loop replace_t92_loop: LDX current_replacement_position LDA t92_char,X LDX t92_replacement,X STA screen,X INC current_replacement_position LDX current_replacement_position CPX #$3 BNE replace_t92_loop CLR current_replacement_position BRA replace_seconds_loop replace_seconds_loop: LDX current_replacement_position LDA seconds_char,X LDX seconds_replacement,X STA screen,X INC current_replacement_position LDX current_replacement_position CPX #$3 BNE replace_seconds_loop CLR current_replacement_position JSR LCD_Write_Time_Screen RTS makeCharArrays: CLRX CLRH state_loop: LDA state CMP #0 BEQ setOff CMP #1 BEQ setHeat CMP #2 BEQ setCool RTS ; should never hit because then we are in an invalid state setState: STA state_char,X INCX CPX #6 BNE state_loop CLRX CLRH BRA t92_loop setCool: LDA cool,X BRA setState setHeat: LDA heat,X BRA setState setOff: LDA off,X BRA setState t92_loop: CLRX CLRH LDA t92,X STA t92_char,X INCX LDA t92,X STA t92_char,X INCX LDA #$20 STA t92_char,X seconds_loop: LDA seconds JSR convertDecimalAsHexToChars CLRX CLRH LDA tens_char STA seconds_char,X INCX LDA ones_char STA seconds_char,X LDA #$20 INCX STA seconds_char,X RTS convertDecimalAsHexToChars: STA tens_char ; store values for now STA ones_char CLRH AND #%11110000 LSRA LSRA LSRA LSRA TAX ; store A in X LDA chars,X ;actually convert to the char STA tens_char LDA ones_char AND #%00001111 TAX ; store A in X LDA chars,X STA ones_char RTS RETURN: RTS Write_Line: LDX write_position LDA screen,X JSR LCD_WRITE INCX STX write_position CPX #$10 BEQ RETURN CPX #$20 BEQ RETURN BRA Write_Line LCD_Write_Time_Screen: CLR write_position LDA #$80 JSR LCD_ADDR CLRH CLRX JSR Write_Line ;Next_Line: LDA #$C0 JSR LCD_ADDR CLRH CLRX JSR Write_Line RTS LCD_Startup: ;SEND INTIAL COMMAND LDA #$30 JSR LCD_WRITE JSR LCD_WRITE JSR LCD_WRITE ;send function set command ;8-bit bus, 2 rows, 5x7 dots LDA #$38 JSR LCD_WRITE ;SEND DISPLAY COMMAND ;DISPLAY ON, CURSOR OFF, NO BLINKING LDA #$0F ;DISPLAY CTRL COMMAND MSB JSR LCD_WRITE ;SEND CLEAR DISPLAY COMMAND LDA #$01 JSR LCD_WRITE ;SEND ENTRY MODE COMMAND LDA #$06 JSR LCD_WRITE LDA #$80 JSR LCD_ADDR LDA #$10 STA $120 RTS ;----------LCD SUBROUTINES------------------------------------------- LCD_WRITE: STA PTBD NOP BCLR E, PTAD NOP BSET E, PTAD JSR DELAYLOOP RTS LCD_ADDR: BCLR RS, PTAD ;LCD IN COMMAND MODE JSR LCD_WRITE BSET RS, PTAD RTS LCD_CLEAR: BCLR RS, PTAD ;SEND CLEAR DISPLAY COMMAND LDA #$01 JSR LCD_WRITE BSET RS, PTAD LDA #$80 JSR LCD_ADDR RTS ;------------------I2C CODE--------------------------------------------- IIC_Startup_slave: ;set baud rate 50kbps LDA #%10000111 STA IICF ;set slave address LDA #$20 STA IICA ;Enable IIC and Interrupts BSET IICC_IICEN, IICC BSET IICC_IICIE, IICC BCLR IICC_MST, IICC RTS _Viic: ;clear interrupt BSET IICS_IICIF, IICS ;master mode? LDA IICC AND #%00100000 BEQ _Viic_slave ; yes ;no RTI _Viic_slave: ;Arbitration lost? LDA IICS AND #%00010000 BEQ _Viic_slave_iaas ;No BCLR 4, IICS;if yes, clear arbitration lost bit BRA _Viic_slave_iaas2 _Viic_slave_iaas: ;Adressed as Slave? LDA IICS AND #%01000000 BNE _Viic_slave_srw ;yes BRA _Viic_slave_txRx ;no _Viic_slave_iaas2: ;Adressed as Slave? LDA IICS AND #%01000000 BNE _Viic_slave_srw ;yes RTI ;if no exit _Viic_slave_srw: ;Slave read/write LDA IICS AND #%00000100 BEQ _Viic_slave_setRx ;slave reads BRA _Viic_slave_setTx ;slave writes _Viic_slave_setTx: ;transmits data BSET 4, IICC ;transmit mode select LDX current LDA IIC_msg, X ;selects current byte of message to send STA IICD ; sends message INCX STX current ; increments current RTI _Viic_slave_setRx: ;makes slave ready to receive data BCLR 4, IICC ;recieve mode select LDA #0 STA current LDA IICD ;dummy read RTI _Viic_slave_txRx: ;Check if device is in transmit or receive mode LDA IICC AND #%00010000 BEQ _Viic_slave_read ;receive BRA _Viic_slave_ack ;transmit _Viic_slave_ack: ;check if master has acnowledged LDA IICS AND #%00000001 BEQ _Viic_slave_setTx ;yes, transmit next byte BRA _Viic_slave_setRx ;no, switch to receive mode _Viic_slave_read: CLRH LDX current LDA IICD STA IIC_msg, X ;store recieved data in IIC_MSG INCX STX current ; increment current LDA IIC_FLAG INCA STA IIC_FLAG RTI ;-------------- ;80 ms delay DELAYLOOP: LDA #1 ;load highest decimal value into accumulator for outer loop STA $125 LOOP0: LDA #50 STA $126 LOOP1: LDA #255 STA $127 LOOP2: LDA $127 DECA STA $127 CMP #$0 BNE LOOP2 LDA $126 DECA STA $126 CMP #$0 BNE LOOP1 STA SRS LDA $125 DECA STA $125 CMP #$0 BNE LOOP0 RTS
asm/integerArithmetic/sportCourt.main.asm
IronHeart7334/AssemblyPrograms
0
21663
; general comments ; Assignment: ; Write a console32 Assembly Language program to calculate the perimeter of a rectangular sports court in meters. ; Assume the largest size will be a regulation Bundesliga (German professional league) soccer field. ; Justify the size and unsigned/signed you choose for this problem. ; Do the problem using only registers and hard-coded data. ; In other words, no user input. ; Each execution will be for a fixed set of initial data. ; You may use named memory if that makes sense to you. ; preprocessor directives .586 .MODEL FLAT ; external files to link with ; stack configuration .STACK 4096 ; named memory allocation and initialization ; https://www.bundesliga.com/en/faq/all-you-need-to-know-about-soccer/all-you-need-to-know-about-a-soccer-field-10572 ; The largest dimensions of a soccer field are 105m by 68m ; dimensions are lengths, so they cannot be negative, so therefore, I will use all unsigned values ; The largest perimeter possible is 105m + 105m + 68m + 68m = 346m, which goes beyond the size of a BYTE ; as such, I must store all the data as the next size up, a WORD .DATA court_width WORD 105d ; apparently, "width" is a reserved word court_length WORD 68d court_perimeter WORD 0d ; names of procedures defined in other *.asm files in the project ; procedure code .CODE main PROC ; I will store intermediate values in the A register as an arbitrary choice. mov AX, 0d ; initialize the last WORD sized part of A to 0. add AX, court_width ; AX = court_width add AX, court_width ; AX = 2*court_width add AX, court_length ; AX = 2*court_width + court_length add AX, court_length ; AX = 2*court_width + 2*court_length = the perimeter mov court_perimeter, AX ; done with calculating, so store the value. mov EAX, 0 ret main ENDP END
tools/aflex/src/scanner-dfa.ads
svn2github/matreshka
24
144
package scanner.DFA is Aflex_Debug : Boolean := False; YYText_Ptr : Integer; -- points to start of yytext in buffer -- yy_ch_buf has to be 2 characters longer than YY_BUF_SIZE because we -- need to put in 2 end-of-buffer characters (this is explained where -- it is done) at the end of yy_ch_buf YY_READ_BUF_SIZE : constant Integer := 8192; YY_BUF_SIZE : constant Integer := YY_READ_BUF_SIZE * 2; -- Size of input buffer type Unbounded_Character_Array is array (Integer range <>) of Wide_Wide_Character; type Ch_Buf_Type is record Data : Unbounded_Character_Array (0 .. YY_BUF_SIZE + 1); end record; function Previous (Data : Ch_Buf_Type; Index : Integer) return Wide_Wide_Character; procedure Next (Data : Ch_Buf_Type; Index : in out Integer; Code : out Wide_Wide_Character); YY_Ch_Buf : Ch_Buf_Type; YY_CP : Integer; YY_BP : Integer; YY_C_Buf_P : Integer; -- Points to current character in buffer function YYText return Wide_Wide_String; function YYLength return Integer; procedure YY_DO_BEFORE_ACTION; -- These variables are needed between calls to YYLex. YY_Init : Boolean := True; -- do we need to initialize YYLex? YY_Start : Integer := 0; -- current start state number subtype YY_State_Type is Integer; YY_Last_Accepting_State : YY_State_Type; YY_Last_Accepting_Cpos : Integer; end scanner.DFA;
misc/mul_div.asm
a1393323447/x86-Assambely
3
16219
; 8 位乘法 ; 结果储存在 ax mov al, 0xf0 mov ah, 0x02 mul ah ; 16 位乘法 ; 结果储存在 dx:ax mov ax, 0xf000 mov bx, 0x0002 mul bx ; 16 位除法 ; 商存在 al 里, 余数存在 ah 里 mov ax, 0x0004 mov bl, 0x02 div bl ; 32 位除法 ; 商存在 ax 里, 余数存在 mov dx, 0x0008 mov ax, 0x0006 mov cx, 0x0002 div cx jmp $ times 510-($-$$) db 0 db 0x55, 0xaa
Engine Hacks/Poison Rework/Hooks.asm
sme23/Christmas2
0
3743
.macro SET_FUNC name, value .global \name .type \name, %function .set \name, \value .endm SET_FUNC SetPoisonWeapon, (0x080178D8+1) SET_FUNC SetPoisonDamage, (0x08025A2C+1)
src/lv-objx-keyboard.ads
Fabien-Chouteau/ada-lvlg
3
20463
<filename>src/lv-objx-keyboard.ads<gh_stars>1-10 with System; with Lv.Style; with Lv.Objx.Textarea; package Lv.Objx.Keyboard is subtype Instance is Obj_T; type Mode_T is (Mode_Text, Mode_Num); type Style_T is (Style_Bg, Style_Btn_Rel, Style_Btn_Pr, Style_Btn_Tgl_Rel, Style_Btn_Tgl_Pr, Style_Btn_Ina); -- Create a keyboard objects -- @param par pointer to an object, it will be the parent of the new keyboard -- @param copy pointer to a keyboard object, if not NULL then the new object will be copied from it -- @return pointer to the created keyboard function Create (Par : Obj_T; Copy : Instance) return Instance; ---------------------- -- Setter functions -- ---------------------- -- Assign a Text Area to the Keyboard. The pressed characters will be put there. -- @param self pointer to a Keyboard object -- @param ta pointer to a Text Area object to write there procedure Set_Textarea (Self : Instance; Ta : Textarea.Instance); -- Set a new a mode (text or number map) -- @param self pointer to a Keyboard object -- @param mode the mode from 'lv_kb_mode_t' procedure Set_Mode (Self : Instance; Mode : Mode_T); -- Automatically hide or show the cursor of the current Text Area -- @param self pointer to a Keyboard object -- @param en true: show cursor on the current text area, false: hide cursor procedure Set_Cursor_Manage (Self : Instance; En : U_Bool); -- Set call back to call when the "Ok" button is pressed -- @param self pointer to Keyboard object -- @param action a callback with 'lv_action_t' type procedure Set_Ok_Action (Self : Instance; Action : Action_Func_T); -- Set call back to call when the "Hide" button is pressed -- @param self pointer to Keyboard object -- @param action a callback with 'lv_action_t' type procedure Set_Hide_Action (Self : Instance; Action : Action_Func_T); -- Set a new map for the keyboard -- @param self pointer to a Keyboard object -- @param map pointer to a string array to describe the map. -- See 'lv_btnm_set_map()' for more info. procedure Set_Map (Self : Instance; Map : System.Address); -- Set a style of a keyboard -- @param self pointer to a keyboard object -- @param type which style should be set -- @param style pointer to a style procedure Set_Style (Self : Instance; Type_P : Style_T; Style : access Lv.Style.Style); ---------------------- -- Getter functions -- ---------------------- -- Assign a Text Area to the Keyboard. The pressed characters will be put there. -- @param self pointer to a Keyboard object -- @return pointer to the assigned Text Area object function Textarea (Self : Instance) return Textarea.Instance; -- Set a new a mode (text or number map) -- @param self pointer to a Keyboard object -- @return the current mode from 'lv_kb_mode_t' function Mode (Self : Instance) return Mode_T; -- Get the current cursor manage mode. -- @param self pointer to a Keyboard object -- @return true: show cursor on the current text area, false: hide cursor function Cursor_Manage (Self : Instance) return U_Bool; -- Get the callback to call when the "Ok" button is pressed -- @param self pointer to Keyboard object -- @return the ok callback function Ok_Action (Self : Instance) return Action_Func_T; -- Get the callback to call when the "Hide" button is pressed -- @param self pointer to Keyboard object -- @return the close callback function Hide_Action (Self : Instance) return Action_Func_T; -- Get a style of a keyboard -- @param self pointer to a keyboard object -- @param type which style should be get -- @return style pointer to a style function Style (Self : Instance; Type_P : Style_T) return access Lv.Style.Style; ------------- -- Imports -- ------------- pragma Import (C, Create, "lv_kb_create"); pragma Import (C, Set_Textarea, "lv_kb_set_ta"); pragma Import (C, Set_Mode, "lv_kb_set_mode"); pragma Import (C, Set_Cursor_Manage, "lv_kb_set_cursor_manage"); pragma Import (C, Set_Ok_Action, "lv_kb_set_ok_action"); pragma Import (C, Set_Hide_Action, "lv_kb_set_hide_action"); pragma Import (C, Set_Map, "lv_kb_set_map_inline"); pragma Import (C, Set_Style, "lv_kb_set_style"); pragma Import (C, Textarea, "lv_kb_get_ta"); pragma Import (C, Mode, "lv_kb_get_mode"); pragma Import (C, Cursor_Manage, "lv_kb_get_cursor_manage"); pragma Import (C, Ok_Action, "lv_kb_get_ok_action"); pragma Import (C, Hide_Action, "lv_kb_get_hide_action"); pragma Import (C, Style, "lv_kb_get_style"); for Mode_T'Size use 8; for Mode_T use (Mode_Text => 0, Mode_Num => 1); for Style_T'Size use 8; for Style_T use (Style_Bg => 0, Style_Btn_Rel => 1, Style_Btn_Pr => 2, Style_Btn_Tgl_Rel => 3, Style_Btn_Tgl_Pr => 4, Style_Btn_Ina => 5); end Lv.Objx.Keyboard;
tests/asm/02-headers1.asm
earwig/crater
16
18812
;; Copyright (C) 2016 <NAME> <<EMAIL>> ;; Released under the terms of the MIT License. See LICENSE for details. ; ----- CRATER UNIT TESTING SUITE --------------------------------------------- ; 02-headers1.asm ; Basic test for headers and other directives, mostly using default values .rom_size auto .rom_header auto .rom_product 0 .rom_version 0 .rom_region "GG Export" .rom_checksum off .rom_declsize auto .cross_blocks auto
src/x86writer.adb
patrickf2000/ada-asm
0
11843
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Parser; use Parser; package body X86Writer is -- The main X86 assembly function procedure assemble(instr_list : Instr_Vector.Vector; writer : Stream_Access) is -- Our types type Byte is mod 2 ** 8; -- Utility functions -- TODO: This is also in the X86Parser, we should move this elsewhere function Is_Number(Input : String) return Boolean is Number : Integer; begin Number := Integer'Value(Input); return true; exception when others => return false; end Is_Number; -- Checks if a string is a register function Is_Register(input : String) return Boolean is begin -- The 8-bit registers if input = "al" or input = "cl" or input = "dl" or input = "bl" or input = "ah" or input = "ch" or input = "dh" or input = "bh" then return true; -- The 16-bit registers elsif input = "ax" or input = "cx" or input = "dx" or input = "bx" or input = "sp" or input = "bp" or input = "si" or input = "di" then return true; -- The 32-bit registers elsif input = "eax" or input = "ecx" or input = "edx" or input = "ebx" or input = "esp" or input = "ebp" or input = "esi" or input = "edi" then return true; end if; return false; end Is_Register; -- The encode function for the mov instruction -- This can get rather complicated... procedure encode_mov(op1, op2 : String) is imm : Integer := 0; begin if Is_Register(op1) and Is_Number(op2) then if op1 = "eax" then Byte'Write(writer, 16#B8#); elsif op1 = "ecx" then Byte'Write(writer, 16#B9#); elsif op1 = "edx" then Byte'Write(writer, 16#BA#); elsif op1 = "ebx" then Byte'Write(writer, 16#BB#); elsif op1 = "esp" then Byte'Write(writer, 16#BC#); elsif op1 = "ebp" then Byte'Write(writer, 16#BD#); elsif op1 = "esi" then Byte'Write(writer, 16#BE#); elsif op1 = "edi" then Byte'Write(writer, 16#BF#); end if; imm := Integer'Value(op2); Integer'Write(writer, imm); end if; end encode_mov; -- The main encode function procedure encode(ln : Parts) is token1 : String := To_String(ln(0)); token2 : String := To_String(ln(1)); token3 : String := To_String(ln(2)); begin -- Syscall if token1 = "syscall" then Byte'Write(writer, 16#0F#); Byte'Write(writer, 16#05#); -- Mov elsif token1 = "mov" then encode_mov(token2, token3); end if; end encode; begin for Ln of instr_list loop encode(Ln.line); end loop; end assemble; end X86Writer;
oeis/335/A335334.asm
neoneye/loda-programs
11
84746
<gh_stars>10-100 ; A335334: Sum of the integers in the reduced residue system of A002110(n). ; Submitted by <NAME>(m3a) ; 1,6,120,5040,554400,86486400,23524300800,8045310873600,4070927302041600,3305592969257779200,3074201461409734656000,4094836346597766561792000,6715531608420337161338880000,12128250084807128913378017280000,26221276683353012710723273359360000,72265838539320903030753341378396160000,247293699481556130171237934196871659520000,905094940102495436426730839160550273843200000,4002329825133234819879003770767953310934630400000,19891579230912177054798648740716727955345113088000000 add $0,1 mov $1,1 mov $2,1 lpb $0 mov $3,$2 lpb $3 add $2,1 mov $4,$1 gcd $4,$2 cmp $4,1 cmp $4,0 sub $3,$4 lpe sub $0,1 mul $1,$2 add $2,1 mul $1,$2 lpe mov $0,$1 div $0,2
src/main/fragment/mega45gs02-common/vdum1=vdum1_plus_vdum2.asm
jbrandwood/kickc
2
175802
<filename>src/main/fragment/mega45gs02-common/vdum1=vdum1_plus_vdum2.asm clc ldq {m1} adcq {m2} stq {m1}
assembler/test5.asm
dpolad/dlx
1
168904
myloop: addi r1, r0, 4 lw r2, 4(r1) sb 20(r1), r2 ; should forward lh r3, 8(r1) addi r4, r3, 15 ; should stall addi r7, r0, myloop ;move label into r7 jalr r7 ;jump
libsrc/_DEVELOPMENT/arch/zx/misc/z80/asm_zx_scroll_wc_up_noexx.asm
meesokim/z88dk
0
15069
SECTION code_arch PUBLIC asm_zx_scroll_wc_up_noexx EXTERN asm_zx_scroll_wc_up asm_zx_scroll_wc_up_noexx: ; alternate entry point to asm_zx_scroll_up_wc that does ; not alter the exx set ; ; enter : de = number of rows to scroll upward by ; l = attr ; ix = rect * ; ; uses : af, bc, de, hl exx push bc push de push hl exx call asm_zx_scroll_wc_up pop hl pop de pop bc exx ret
agda/Function/Isomorphism.agda
oisdk/combinatorics-paper
0
11593
<filename>agda/Function/Isomorphism.agda {-# OPTIONS --cubical --safe #-} module Function.Isomorphism where open import Cubical.Foundations.Equiv using (isoToEquiv) public open import Cubical.Foundations.Isomorphism using (Iso; section; retract; isoToPath; iso) public open import Level open import Path open import Function open import Data.Sigma open import Relation.Binary open Iso public infix 4 _⇔_ _⇔_ = Iso sym-⇔ : (A ⇔ B) → (B ⇔ A) fun (sym-⇔ A⇔B) = inv A⇔B inv (sym-⇔ A⇔B) = fun A⇔B leftInv (sym-⇔ A⇔B) = rightInv A⇔B rightInv (sym-⇔ A⇔B) = leftInv A⇔B refl-⇔ : A ⇔ A fun refl-⇔ x = x inv refl-⇔ x = x leftInv refl-⇔ x = refl rightInv refl-⇔ x = refl trans-⇔ : A ⇔ B → B ⇔ C → A ⇔ C fun (trans-⇔ A⇔B B⇔C) = fun B⇔C ∘ fun A⇔B inv (trans-⇔ A⇔B B⇔C) = inv A⇔B ∘ inv B⇔C leftInv (trans-⇔ A⇔B B⇔C) x = cong (inv A⇔B) (leftInv B⇔C _) ; leftInv A⇔B _ rightInv (trans-⇔ A⇔B B⇔C) x = cong (fun B⇔C) (rightInv A⇔B _) ; rightInv B⇔C _ iso-Σ : {B : A → Type b} {C : A → Type c} → (∀ x → B x ⇔ C x) → Σ A B ⇔ Σ A C iso-Σ B⇔C .fun (x , xs) = x , B⇔C x .fun xs iso-Σ B⇔C .inv (x , xs) = x , B⇔C x .inv xs iso-Σ B⇔C .rightInv (x , xs) i .fst = x iso-Σ B⇔C .rightInv (x , xs) i .snd = B⇔C x .rightInv xs i iso-Σ B⇔C .leftInv (x , xs) i .fst = x iso-Σ B⇔C .leftInv (x , xs) i .snd = B⇔C x .leftInv xs i ⇔-equiv : Equivalence (Type a) a Equivalence._≋_ ⇔-equiv = _⇔_ Equivalence.sym ⇔-equiv = sym-⇔ Equivalence.refl ⇔-equiv = refl-⇔ Equivalence.trans ⇔-equiv = trans-⇔ open import HLevels open import Equiv iso⇔equiv : isSet A → (A ⇔ B) ⇔ (A ≃ B) iso⇔equiv isSetA .fun = isoToEquiv iso⇔equiv isSetA .inv = equivToIso iso⇔equiv isSetA .rightInv x i .fst = x .fst iso⇔equiv isSetA .rightInv x i .snd = isPropIsEquiv (x .fst) (isoToEquiv (equivToIso x) .snd) (x .snd) i iso⇔equiv isSetA .leftInv x i .fun = x .fun iso⇔equiv isSetA .leftInv x i .inv = x .inv iso⇔equiv isSetA .leftInv x i .rightInv = x .rightInv iso⇔equiv isSetA .leftInv x i .leftInv y = isSetA _ y (equivToIso (isoToEquiv x) .leftInv y) (x .leftInv y) i
archive/agda-2/Oscar/Instance.agda
m0davis/oscar
0
6483
module Oscar.Instance where open import Oscar.Class.Associativity open import Oscar.Class.Congruity open import Oscar.Class.Equivalence open import Oscar.Class.Extensionality open import Oscar.Class.Injectivity open import Oscar.Class.Preservativity open import Oscar.Class.Reflexivity open import Oscar.Class.Semifunctor open import Oscar.Class.Semigroup open import Oscar.Class.Symmetry open import Oscar.Class.Transitivity open import Oscar.Data.Equality open import Oscar.Data.Fin open import Oscar.Data.Nat open import Oscar.Function open import Oscar.Relation open import Oscar.Data.Equality.properties using (≡̇-sym; ≡̇-trans) renaming (sym to ≡-sym ;trans to ≡-trans) instance InjectivityFinSuc : ∀ {n} → Injectivity _≡_ _≡_ (Fin.suc {n}) suc Injectivity.injectivity InjectivityFinSuc refl = refl data D : Set where d1 : Nat → D d2 : Nat → Nat → D pattern d2l r l = d2 l r instance InjectivityDd1 : Injectivity _≡_ _≡_ d1 d1 Injectivity.injectivity InjectivityDd1 refl = refl instance InjectivityD2l : ∀ {r1 r2} → Injectivity _≡_ _≡_ (d2l r1) (flip d2 r2) Injectivity.injectivity InjectivityD2l refl = refl instance InjectivityoidD2l : ∀ {r1} {r2} → Injectivityoid _ _ _ _ _ Injectivityoid.A InjectivityoidD2l = D Injectivityoid.B InjectivityoidD2l = D Injectivityoid._≋₁_ InjectivityoidD2l = _≡_ Injectivityoid.I InjectivityoidD2l = Nat Injectivityoid._≋₂_ InjectivityoidD2l = _≡_ Injectivityoid.μₗ (InjectivityoidD2l {r1} {r2}) = d2l r1 Injectivityoid.μᵣ (InjectivityoidD2l {r1} {r2}) = flip d2 r2 Injectivityoid.`injectivity InjectivityoidD2l refl = refl instance InjectivityoidD2r : ∀ {r1} {r2} → Injectivityoid _ _ _ _ _ Injectivityoid.A InjectivityoidD2r = D Injectivityoid.B InjectivityoidD2r = D Injectivityoid._≋₁_ InjectivityoidD2r = _≡_ Injectivityoid.I InjectivityoidD2r = Nat Injectivityoid._≋₂_ InjectivityoidD2r = _≡_ Injectivityoid.μₗ (InjectivityoidD2r {r1} {r2}) = d2 r1 Injectivityoid.μᵣ (InjectivityoidD2r {r1} {r2}) = d2 r2 Injectivityoid.`injectivity InjectivityoidD2r refl = refl open Injectivityoid ⦃ … ⦄ using (`injectivity) instance InjectivityD2r : ∀ {l1 l2} → Injectivity _≡_ _≡_ (d2 l1) (d2 l2) Injectivity.injectivity InjectivityD2r refl = refl pattern d2' {l} r = d2 l r injectivity-test : (k l m n : Nat) → (d2 k m ≡ d2 l n) → (d1 k ≡ d1 l) → Set injectivity-test k l m n eq1 eq2 with injectivity {_≋₁_ = _≡_} {_≋₂_ = _≡_} {f = d2'} eq1 injectivity-test k l m n eq1 eq2 | ref with injectivity {_≋₁_ = _≡_} {_≋₂_ = _≡_} {f = d1} eq2 … | ref2 = {!!} -- with `injectivity ⦃ ? ⦄ eq2 -- … | ref3 = {!ref!} instance ≡-Reflexivity : ∀ {a} {A : Set a} → Reflexivity (_≡_ {A = A}) Reflexivity.reflexivity ≡-Reflexivity = refl ≡̇-Reflexivity : ∀ {a} {A : Set a} {b} {B : A → Set b} → Reflexivity (_≡̇_ {B = B}) Reflexivity.reflexivity ≡̇-Reflexivity _ = refl ≡-flip≡-Extensionality : ∀ {a} {A : Set a} → Extensionality {B = const A} _≡_ (λ ⋆ → flip _≡_ ⋆) id id Extensionality.extensionality ≡-flip≡-Extensionality = ≡-sym ≡̇-flip≡̇-Extensionality : ∀ {a} {A : Set a} {b} {B : A → Set b} → Extensionality {B = const ((x : A) → B x)} _≡̇_ (λ ⋆ → flip _≡̇_ ⋆) id id Extensionality.extensionality ≡̇-flip≡̇-Extensionality = ≡̇-sym ≡-Transitivity : ∀ {a} {A : Set a} → Transitivity {A = A} _≡_ Transitivity.transitivity ≡-Transitivity = λ ⋆ → ≡-trans ⋆ ≡̇-Transitivity : ∀ {a} {A : Set a} {b} {B : A → Set b} → Transitivity {A = (x : A) → B x} _≡̇_ Transitivity.transitivity ≡̇-Transitivity = ≡̇-trans ≡-Congruity : ∀ {a} {A : Set a} {b} {B : Set b} {ℓ₂} {_≋₂_ : B → B → Set ℓ₂} ⦃ _ : Reflexivity _≋₂_ ⦄ → Congruity (_≡_ {A = A}) _≋₂_ Congruity.congruity ≡-Congruity μ refl = reflexivity module Term {𝔣} (FunctionName : Set 𝔣) where open import Oscar.Data.Term FunctionName open import Oscar.Data.Term.internal.SubstituteAndSubstitution FunctionName as ⋆ instance ◇-≡̇-Associativity : Associativity _◇_ _≡̇_ Associativity.associativity ◇-≡̇-Associativity = ◇-associativity ∘-≡̇-Associativity : ∀ {a} {A : Set a} {b} {B : A → Set b} → Associativity {_►_ = _⟨ B ⟩→_} (λ ⋆ → _∘_ ⋆) _≡̇_ Associativity.associativity ∘-≡̇-Associativity _ _ _ _ = refl ◇-∘-≡̇-◃-◃-◃-Preservativity : ∀ {l m n} → Preservativity (λ ⋆ → _◇_ (m ⊸ n ∋ ⋆)) (_∘′_ {A = Term l}) _≡̇_ _◃_ _◃_ _◃_ Preservativity.preservativity ◇-∘-≡̇-◃-◃-◃-Preservativity g f τ = symmetry (◃-associativity τ f g) ≡̇-≡̇-◃-◃-Extensionality : ∀ {m n} → Extensionality _≡̇_ (λ ⋆ → _≡̇_ ⋆) (_◃_ {m} {n}) (λ ⋆ → _◃_ ⋆) Extensionality.extensionality ≡̇-≡̇-◃-◃-Extensionality = ◃-extensionality semifunctor-◃ : Semifunctor _◇_ _≡̇_ (λ ⋆ → _∘_ ⋆) _≡̇_ id _◃_ semifunctor-◃ = it open import Oscar.Data.AList FunctionName postulate _++_ : ∀ {m n} → AList m n → ∀ {l} → AList l m → AList l n sub : ∀ {m n} → AList m n → m ⊸ n ++-assoc : ∀ {l m n o} (ρ : AList l m) (σ : AList n _) (τ : AList o _) → ρ ++ (σ ++ τ) ≡ (ρ ++ σ) ++ τ subfact1 : ∀ {l m n} (ρ : AList m n) (σ : AList l m) → sub (ρ ++ σ) ≡̇ (sub ρ ◇ sub σ) instance ++-≡-Associativity : Associativity _++_ _≡_ Associativity.associativity ++-≡-Associativity f g h = ++-assoc h g f ++-◇-sub-sub-sub : ∀ {l m n} → Preservativity (λ ⋆ → _++_ (AList m n ∋ ⋆)) (λ ⋆ → _◇_ ⋆ {l = l}) _≡̇_ sub sub sub Preservativity.preservativity ++-◇-sub-sub-sub = subfact1 semifunctor-sub : Semifunctor _++_ _≡_ _◇_ _≡̇_ id sub semifunctor-sub = it -- ≡̇-extension : ∀ -- {a} {A : Set a} {b} {B : A → Set b} -- {ℓ₁} {_≤₁_ : (x : A) → B x → Set ℓ₁} -- {c} {C : Set c} -- {d} {D : C → Set d} -- {μ₁ : A → (z : C) → D z} -- {μ₂ : ∀ {x} → B x → (z : C) → D z} -- ⦃ _ : Extensionality _≤₁_ (λ ⋆ → _≡̇_ ⋆) μ₁ μ₂ ⦄ -- {x} {y : B x} -- → x ≤₁ y → μ₁ x ≡̇ μ₂ y -- ≡̇-extension = extension (λ ⋆ → _≡̇_ ⋆) -- test-◃-extensionality : ∀ {m n} {f g : m ⊸ n} → f ≡̇ g → f ◃_ ≡̇ g ◃_ -- test-◃-extensionality = ≡̇-extension -- ≡̇-extension -- ⦃ ? ⦄ -- extension (λ ⋆ → _≡̇_ ⋆) -- postulate -- R : Set -- S : Set -- _◀_ : ∀ {m n} → m ⊸ n → R → S -- _◀'_ : ∀ {m n} → m ⊸ n → R → S -- _◆_ : ∀ {m n} → m ⊸ n → ∀ {l} → l ⊸ m → l ⊸ n -- instance ≡̇-≡̇-◀-◀'-Extensionality : ∀ {m n} → Extensionality _≡̇_ (λ ⋆ → _≡̇_ ⋆) ((m ⊸ n → _) ∋ _◀_) _◀'_ -- instance ≡̇-≡̇-◀-◀-Extensionality : ∀ {m n} → Extensionality _≡̇_ (λ ⋆ → _≡̇_ ⋆) ((m ⊸ n → _) ∋ _◀_) _◀_ -- instance ◆-◇-≡̇-Associativity : ∀ {k} → Associativity _◆_ (λ ⋆ → _◇_ ⋆) ((k ⊸ _ → _) ∋ _≡̇_) -- instance ◆-◇-≡̇-Associativity' : ∀ {k} → Associativity _◇_ (λ ⋆ → _◆_ ⋆) ((k ⊸ _ → _) ∋ _≡̇_) -- test-◀-extensionality : ∀ {m n} {f g : m ⊸ n} → f ≡̇ g → f ◀_ ≡̇ g ◀_ -- test-◀-extensionality {m} {n} = ≡̇-extension -- -- extensionality {_≤₁_ = _≡̇_} {μ₁ = ((m ⊸ n → _) ∋ _◀_)} {μ₂ = _◀_} -- test-◀'-extensionality : ∀ {m n} {f g : m ⊸ n} → f ≡̇ g → f ◀_ ≡̇ g ◀'_ -- test-◀'-extensionality = ≡̇-extension -- test-◃-associativity : ∀ {l} (t : Term l) {m} (f : l ⊸ m) {n} (g : m ⊸ n) → g ◃ (f ◃ t) ≡ (g ◇ f) ◃ t -- test-◃-associativity = association _◇_ _≡_ -- test-◇-associativity : ∀ {k l} (f : k ⊸ l) {m} (g : l ⊸ m) {n} (h : m ⊸ n) → h ◇ (g ◇ f) ≡̇ (h ◇ g) ◇ f -- test-◇-associativity = association _◇_ _≡̇_ -- test-◆-associativity : ∀ {k l} (f : k ⊸ l) {m} (g : l ⊸ m) {n} (h : m ⊸ n) → h ◇ (g ◇ f) ≡̇ (h ◆ g) ◇ f -- test-◆-associativity = association _◆_ _≡̇_ -- test-◆-associativity' : ∀ {k l} (f : k ⊸ l) {m} (g : l ⊸ m) {n} (h : m ⊸ n) → h ◆ (g ◆ f) ≡̇ (h ◇ g) ◆ f -- test-◆-associativity' = association _◇_ _≡̇_
examples/version.adb
ytomino/boehmgc-ada
3
29115
with Ada.Text_IO; with GC; procedure version is begin Ada.Text_IO.Put_Line (GC.Version); end version;
Lab05/Task01.asm
PrabalChowdhury/CSE-341-MICROPROCESSOR
0
179769
.MODEL SMALL .STACK 100H .DATA .CODE MAIN PROC mov AX,@DATA mov DS,AX mov ah,1 int 21H mov cl,al SUB cl,30H mov ch,0 mov ah,2 mov dl,0DH int 21H mov dl,0ah int 21H mov ah,1 int 21H mov bl,al sub bl,30H mov ah,2 mov dl,0dh int 21H mov dl,0ah int 21H SRT: cmp cl,bl jg EXT mov ax,cx mov bh,2 div bh cmp ah,0 je AB add cl,1 jmp SRT AB: mov dl,cl add dl,30h mov ah,2 int 21H add cl,1 mov ch,0 cmp cl,bl jmp SRT EXT: MOV AX,4C00H INT 21H MAIN ENDP END MAIN
examples/intf.adb
ytomino/drake
33
24503
with Ada; with Interfaces.C.Char_Pointers; with Interfaces.C.Pointers; with Interfaces.C.Strings; with Interfaces.C.Wide_WStrings; procedure intf is begin -- Import declare type Unsigned_Long_Long is mod 2 ** Long_Long_Integer'Size; type P is access all Character; function strtoll (str : String; endptr : access P; base : Integer) return Long_Long_Integer with Import, Convention => C; function strtoull (str : String; endptr : access P; base : Integer) return Unsigned_Long_Long with Import, Convention => C; N : aliased Long_Long_Integer := -1; U : aliased Unsigned_Long_Long := -1; begin N := strtoll ("100" & ASCII.NUL, null, 10); pragma Assert (N = 100); U := strtoull ("100" & ASCII.NUL, null, 10); pragma Assert (U = 100); end; -- Interfaces.C declare use type Interfaces.C.size_t; use type Interfaces.C.char_array; use type Interfaces.C.wchar_array; use type Interfaces.C.char16_array; use type Interfaces.C.char32_array; begin pragma Assert (Interfaces.C.To_C (String'("")) = Interfaces.C.char_array'(0 => Interfaces.C.nul)); pragma Assert (Interfaces.C.To_Ada (Interfaces.C.char_array'(0 => Interfaces.C.nul)) = String'("")); pragma Assert (Interfaces.C.To_C (Wide_String'("")) = Interfaces.C.wchar_array'(0 => Interfaces.C.wide_nul)); pragma Assert (Interfaces.C.To_Ada (Interfaces.C.wchar_array'(0 => Interfaces.C.wide_nul)) = Wide_String'("")); pragma Assert (Interfaces.C.To_C (Wide_String'("")) = Interfaces.C.char16_array'(0 => Interfaces.C.char16_nul)); pragma Assert (Interfaces.C.To_Ada (Interfaces.C.char16_array'(0 => Interfaces.C.char16_nul)) = Wide_String'("")); pragma Assert (Interfaces.C.To_C (Wide_Wide_String'("")) = Interfaces.C.char32_array'(0 => Interfaces.C.char32_nul)); pragma Assert (Interfaces.C.To_Ada (Interfaces.C.char32_array'(0 => Interfaces.C.char32_nul)) = Wide_Wide_String'("")); -- contains nul pragma Assert (Interfaces.C.To_Ada (Interfaces.C.char_array'(0 => Interfaces.C.nul), Trim_Nul => False) = String'(1 => Character'Val (0))); -- substitute if Interfaces.C.wchar_t'Size /= Wide_Character'Size then pragma Assert (Interfaces.C.To_Wide_String (Interfaces.C.wchar_array'(16#d800#, Interfaces.C.wide_nul), Substitute => "ILSEQ") = "ILSEQ"); null; else pragma Assert (Interfaces.C.To_Wide_Wide_String (Interfaces.C.wchar_array'(16#d800#, Interfaces.C.wide_nul), Substitute => "ILSEQ") = "ILSEQ"); null; end if; end; -- Interfaces.C.Pointers declare use type Interfaces.C.ptrdiff_t; use type Interfaces.C.size_t; type A is array (Positive range <>) of aliased Integer; package Ps is new Interfaces.C.Pointers ( Positive, Integer, A, Default_Terminator => 0); AO : aliased A (1 .. 10); E1 : not null Ps.Pointer := AO (3)'Access; E2 : not null Ps.Pointer := AO (7)'Access; ZSTR : aliased Interfaces.C.char_array (0 .. 0) := (0 => Interfaces.C.nul); Empty_ZSTR : constant Interfaces.C.char_array := Interfaces.C.Char_Pointers.Value (ZSTR (0)'Access, 0); begin pragma Assert (Ps."-" (E2, E1) = 4); pragma Assert (Empty_ZSTR'First = 1 and then Empty_ZSTR'Last = 0); null; end; -- Interfaces.C.Strings declare use type Interfaces.C.char_array; C_Str : aliased Interfaces.C.char_array (1 .. 5) := "12345"; C_Sub_Str : Interfaces.C.char_array renames C_Str (3 .. 5); p : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String ("ABC"); begin pragma Assert (Interfaces.C.Strings.Value (p) = String'("ABC")); Interfaces.C.Strings.Update (p, 1, Interfaces.C.char_array'("Z")); pragma Assert (Interfaces.C.Strings.Value (p) = String'("AZC")); pragma Assert (Interfaces.C.Strings.Value (p, 1, Append_Nul => True) = ('A', Interfaces.C.nul)); Interfaces.C.Strings.Free (p); pragma Assert (Interfaces.C.Strings.Value (Interfaces.C.Strings.To_Const_Chars_Ptr (C_Sub_Str'Unrestricted_Access), 3) = String'("345")); end; -- Interfaces.C.Wide_WStrings declare use type Interfaces.C.wchar_array; C_Str : aliased Interfaces.C.wchar_array (1 .. 5) := Interfaces.C.To_C ("12345", Append_Nul => False); C_Sub_Str : Interfaces.C.wchar_array renames C_Str (3 .. 5); p : Interfaces.C.Wide_WStrings.chars_ptr := Interfaces.C.Wide_WStrings.New_String ("ABC"); begin pragma Assert (Interfaces.C.Wide_WStrings.Value (p) = Wide_String'("ABC")); Interfaces.C.Wide_WStrings.Update (p, 1, Interfaces.C.wchar_array'(0 => Interfaces.C.wchar_t'Val (Character'Pos ('Z')))); pragma Assert (Interfaces.C.Wide_WStrings.Value (p) = Wide_String'("AZC")); pragma Assert (Interfaces.C.Wide_WStrings.Value (p, 1, Append_Nul => True) = (Interfaces.C.wchar_t'Val (Character'Pos ('A')), Interfaces.C.wide_nul)); Interfaces.C.Wide_WStrings.Free (p); pragma Assert (Interfaces.C.Wide_WStrings.Value (Interfaces.C.Wide_WStrings.To_Const_Chars_Ptr (C_Sub_Str'Unrestricted_Access), 3) = Wide_String'("345")); p := Interfaces.C.Wide_WStrings.New_Strcat ( Interfaces.C.Wide_WStrings.const_chars_ptr_With_Length_array'( (C_Str (1)'Unchecked_Access, 2), (C_Str (4)'Unchecked_Access, 2))); pragma Assert (Interfaces.C.Wide_WStrings.Value (p) = "1245"); Interfaces.C.Wide_WStrings.Free (p); end; pragma Debug (Ada.Debug.Put ("OK")); end intf;
Userland/SampleCodeModule/asm/lib64.asm
pdomins/2020Q2_Arqui_TPE
3
99819
<reponame>pdomins/2020Q2_Arqui_TPE GLOBAL sysTime GLOBAL sysRead GLOBAL sysWrite GLOBAL _syscall GLOBAL invalidOpCode ;------------------------------------------------------------ ; USERLAND ;------------------------------------------------------------ section .text ;------------------------------------------------------------ ; syscall recibe argumentos variables. ;------------------------------------------------------------ _syscall: int 80h; ret ;------------------------------------------------------------ invalidOpCode: UD2 ret
test/Fail/Issue2906.agda
cruhland/agda
1,989
15148
<reponame>cruhland/agda data D : Set where zero : D suc : D → D postulate f : D → D {-# COMPILE GHC f = \ x -> x #-}
sycadas/src/main/antlr/org/genevaers/sycadas/grammar/FormatFilter.g4
venkateshprasad123/wb
3
4331
<filename>sycadas/src/main/antlr/org/genevaers/sycadas/grammar/FormatFilter.g4<gh_stars>1-10 grammar FormatFilter; /* * Copyright Contributors to the GenevaERS Project. * (c) Copyright IBM Corporation 2020. * SPDX-License-Identifier: Apache-2.0 * * 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. */ import FormatParser; goal : (stmt)? EOF ; stmt : ( IF predicate THEN stmtThenSelect ) | SKIPIF LPAREN predicate RPAREN | SELECTIF LPAREN predicate RPAREN | stmtIfSkip ; stmtIfSelect : IF predicate THEN stmtThenSelect ( ELSE stmtIfSelect )? ENDIF ; stmtIfSkip : IF predicate THEN stmtThenSkip ( ELSE stmtIfSkip )? ENDIF ; stmtThenSelect : SELECT | stmtIfSelect ; stmtThenSkip : SKIPF | stmtIfSkip ;
exercises/practice/isogram/isogram.asm
jonboland/x86-64-assembly
21
178741
section .text global is_isogram is_isogram: ; Provide your implementation here ret
source/receiver/main/locations.adb
reznikmm/gps-tracker
0
18743
<filename>source/receiver/main/locations.adb -- SPDX-FileCopyrightText: 2022 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Locations is task body Bluetooth_Runner is Supported : constant := Location_Supported + UTC_Time_Supported; begin Peripheral_Device.Write (Battery_Level, (1 => 100)); Peripheral_Device.Write (LN_Feature, (Supported, 0)); Peripheral_Device.Run; -- Locations.Peripheral_Device.Write -- (Location_and_Speed, -- Locations.Location_Present -- & Locations.Cast (Latitude) -- & Locations.Cast (351859000)); end Bluetooth_Runner; end Locations;
src/compiling/ANTLR/grammar/ProgramItems.g4
jecassis/VSCode-SystemVerilog
75
3776
grammar ProgramItems; import CheckerItems; program_item : port_declaration ';' | non_port_program_item ; non_port_program_item : ( attribute_instance )* continuous_assign | ( attribute_instance )* module_or_generate_item_declaration | ( attribute_instance )* initial_construct | ( attribute_instance )* final_construct | ( attribute_instance )* concurrent_assertion_item | timeunits_declaration | program_generate_item ; program_generate_item : loop_generate_construct | conditional_generate_construct | generate_region | elaboration_system_task | simulation_control_task ;
Tests/BTTest.applescript
VulcanRobotics/VulcanScoutingApp2018
0
3539
<gh_stars>0 activate application "SystemUIServer" tell application "System Events" tell process "SystemUIServer" -- Working CONNECT Script. Goes through the following: -- Clicks on Bluetooth Menu (OSX Top Menu Bar) -- => Clicks on jliu-2018 Item -- => Clicks on Connect Item set btMenu to (menu bar item 1 of menu bar 1 where description is "bluetooth") tell btMenu click tell (menu item "jliu-2018" of menu 1) click if exists menu item "Connect" of menu 1 click menu item "Connect" of menu 1 return "Connecting..." else click btMenu -- Close main BT drop down if Connect wasn't present return "Connect menu was not found, are you already connected?" end if end tell end tell end tell end tell
test/Succeed/Issue1039.agda
cruhland/agda
1,989
16190
<reponame>cruhland/agda module Issue1039 where open import Common.Level Test : ∀ {a b} → Set a → Set (a ⊔ b) → Set a Test X Y = X test : Set (lsuc lzero) test = Test Set (Set (lsuc lzero)) test₂ : ∀ {l} → Set (lsuc l) test₂ {l} = Test (Set l) (Set (lsuc l))
Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0xca_notsx.log_21829_1755.asm
ljhsiun2/medusa
9
174327
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x1e402, %rsi lea addresses_UC_ht+0x16982, %rdi nop nop nop nop nop sub $65080, %r11 mov $84, %rcx rep movsw nop add $20838, %r11 lea addresses_normal_ht+0xafe, %r9 nop nop nop nop nop and $50314, %rbx mov $0x6162636465666768, %r14 movq %r14, %xmm7 movups %xmm7, (%r9) nop nop nop nop and $9642, %rcx lea addresses_A_ht+0x11a6e, %rcx and $43906, %r9 movw $0x6162, (%rcx) nop nop nop nop dec %r11 lea addresses_normal_ht+0x160ca, %rsi lea addresses_normal_ht+0xd812, %rdi nop nop nop nop and %r15, %r15 mov $45, %rcx rep movsq nop nop add $10707, %r14 lea addresses_WT_ht+0x5982, %rdi xor %r14, %r14 vmovups (%rdi), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $1, %xmm5, %rbx nop cmp %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %r9 push %rdi push %rdx // Faulty Load lea addresses_WT+0x10982, %r13 xor $30203, %r9 mov (%r13), %edi lea oracles, %r13 and $0xff, %rdi shlq $12, %rdi mov (%r13,%rdi,1), %rdi pop %rdx pop %rdi pop %r9 pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'STOR'} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
test/Fail/Issue719.agda
shlevy/agda
2
14691
-- Andreas, 2012-10-19 issue #719 blame correct module -- Andreas, 2017-07-28 point to correct binding site ("as A") module Issue719 where import Common.Size as A module M where private open module A = M -- WAS: -- Duplicate definition of module A. Previous definition of module A -- at .../Common/Size.agda:7,15-19 -- when scope checking the declaration -- open module A = M -- EXPECTED: -- Duplicate definition of module A. Previous definition of module A -- at .../Issue719.agda:6,25-26 -- when scope checking the declaration -- open module A = M
sharding-core/src/main/antlr4/imports/MySQLDropIndex.g4
chuanandongxu/sharding-sphere
0
4856
<reponame>chuanandongxu/sharding-sphere grammar MySQLDropIndex; import MySQLKeyword, Keyword, BaseRule; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ;
lib/macros.asm
stoneface86/tbengine
6
99918
<reponame>stoneface86/tbengine<filename>lib/macros.asm ; 2's complement negation neg: MACRO cpl inc a ENDM ; negate word _negw: MACRO ld a, HIGH(\1) cpl ld HIGH(\1), a ld a, LOW(\1) cpl ld LOW(\1), a inc \1 ENDM ; add sign-extended byte to word. the value of register a gets sign-extended into ; the given 16-bit register and is then added to hl ; hl: word ; \1: r16 temporary register _addsw: MACRO ld LOW(\1), a add a, a sbc a, a ld HIGH(\1), a add hl, \1 ENDM ; ; Seek Struct (SeekS): Seek to a field in a struct pointer using the "this-in-de" pattern ; \1: offset to seek to ; ; depending on the offset, the code emitted will have different cycle counts ; ; offset bytes cycles description ; 0 2 2 hl = de ; 1 3 4 hl = de, increment hl ; >1 4 5 hl = \1, hl += de ; seeks: MACRO IF \1 < 2 ; 2 bytes, 2 cycles ld h, d ld l, e IF \1 == 1 inc hl ENDC ELSE ld hl, \1 add hl, de ENDC ENDM ; ; Jump table logic for b = channel id (0-3) ; b is set to 0 on finish ; chjumptable: MACRO ; not actually a jump table ; if-else-branch is actually faster and smaller than a jump table ; branching: 5-11 cycles and 10 bytes ; jumptable: 13 cycles and 16 bytes inc b ; set zero flag on b dec b jr z, .ch1 ; b = 0: CH1 dec b jr z, .ch2 ; b = 1: CH2 dec b jr z, .ch3 ; b = 2: CH3 ; for b > 2: CH4 ; jumptable version ; ld hl, .jumptable ; ld b, 0 ; add hl, bc ; add hl, bc ; jp hl ; .jumptable: ; jr .ch1 ; jr .ch2 ; jr .ch3 ; jr .ch4 ; ENDM ; ; Retrigger a channel whilst keeping frequency data unchanged ; For CH3 you should disable/enable NR30 before invoking this macro! ; \1: channel id (1-4) ; retrigger: MACRO IF \1 == 4 ld a, $80 ELSE ld a, [tbe_wFreq\1 + 1] ; current frequency (upper bits) set 7, a ; set bit 7 to restart channel ENDC ld [rNR\14], a ENDM ; ; Write envelope setting for a channel, channel is retriggered ; \1: channel id (1-4) ; writeEnvelope: MACRO IF \1 == 3 call _tbe_writeWave ELSE ld [rNR\12], a ENDC retrigger \1 ENDM ; ; Writes timbre setting for a channel ; \1: channel id (1-4) ; writeTimbre: MACRO IF \1 == 1 || \1 == 2 ld [rNR\11], a ELIF \1 == 3 ld [rNR32], a ELSE ld d, a ; d = timbre ld a, [rNR43] ; get current setting res 3, a ; reset bit 3 (step-width) or a, d ; or with timbre ld [rNR43], a ; write back ENDC ENDM ; ; Reload a channel with music settings ; reload: MACRO ; low frequency IF \1 == 4 ld a, [tbe_wTimbre4] ld b, a ENDC ld a, [tbe_wFreq\1] IF \1 == 4 or a, b ENDC ld [rNR\13], a IF \1 != 4 ld a, [tbe_wTimbre\1] writeTimbre \1 ENDC ld a, [tbe_wEnvelope\1] writeEnvelope \1 ; TODO panning ENDM
loader_wsock32_proxy/wsock32.asm
r-ex/NorthstarLauncher
186
172308
.data extern PA : qword .code RunASM proc jmp qword ptr [PA] RunASM endp end
08/FunctionCalls_tests/NestedCall/NestedCall.asm
ashiroji/Nand2Tetris
0
100815
@256 D=A //D = 256 @SP M=D //M[SP] = 256 //push returnAddress @returnAddress0 D=A //D=returnAddress0 @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push LCL @LCL D=M //D=LCL @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push ARG @ARG D=M //D=ARG @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THIS @THIS D=M //D=THIS @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THAT @THAT D=M //D=THAT @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //ARG = SP - nArgs - 5 @SP D=M //D=SP @0 D=D-A //D = SP-nArgs @5 D=D-A //D=SP-5 @ARG M=D //ARG= SP - nArgs -5 //LCL = SP @SP D=M //D=SP @LCL M=D //LCL = SP //goto Sys.init @Sys.init//label to go to 0;JMP //unconditional jump //label returnAddress0 (returnAddress0) //label declaration (Sys.init) //function name //push constant 4000 @4000 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @3 //A = RAM @3 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 5000 @5000 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 1 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @4 //A = RAM @4 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push returnAddress @returnAddress1 D=A //D=returnAddress1 @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push LCL @LCL D=M //D=LCL @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push ARG @ARG D=M //D=ARG @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THIS @THIS D=M //D=THIS @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THAT @THAT D=M //D=THAT @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //ARG = SP - nArgs - 5 @SP D=M //D=SP @0 D=D-A //D = SP-nArgs @5 D=D-A //D=SP-5 @ARG M=D //ARG= SP - nArgs -5 //LCL = SP @SP D=M //D=SP @LCL M=D //LCL = SP //goto Sys.main @Sys.main//label to go to 0;JMP //unconditional jump //label returnAddress1 (returnAddress1) //label declaration //pop temp 1 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @R6 //A = RAM @ D=A //D is now @static + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //label LOOP (LOOP) //label declaration //goto LOOP @LOOP//label to go to 0;JMP //unconditional jump (Sys.main) //function name //push constant 0 @0 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 0 @0 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 0 @0 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 0 @0 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 0 @0 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 4001 @4001 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @3 //A = RAM @3 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 5001 @5001 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 1 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @4 //A = RAM @4 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 200 @200 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop local 1 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @LCL //A=LCL D=M //save M[local] in D @1 //A = index D=D+A //D is now @(local + index) @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 40 @40 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop local 2 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @LCL //A=LCL D=M //save M[local] in D @2 //A = index D=D+A //D is now @(local + index) @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 6 @6 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop local 3 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @LCL //A=LCL D=M //save M[local] in D @3 //A = index D=D+A //D is now @(local + index) @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 123 @123 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push returnAddress @returnAddress2 D=A //D=returnAddress2 @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push LCL @LCL D=M //D=LCL @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push ARG @ARG D=M //D=ARG @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THIS @THIS D=M //D=THIS @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push THAT @THAT D=M //D=THAT @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //ARG = SP - nArgs - 5 @SP D=M //D=SP @1 D=D-A //D = SP-nArgs @5 D=D-A //D=SP-5 @ARG M=D //ARG= SP - nArgs -5 //LCL = SP @SP D=M //D=SP @LCL M=D //LCL = SP //goto Sys.add12 @Sys.add12//label to go to 0;JMP //unconditional jump //label returnAddress2 (returnAddress2) //label declaration //pop temp 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @R5 //A = RAM @ D=A //D is now @static + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push local 0 @LCL //A=LCL D=M //save M[local] in D @0 //A = index D=D+A //D is now @(local + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push local 1 @LCL //A=LCL D=M //save M[local] in D @1 //A = index D=D+A //D is now @(local + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push local 2 @LCL //A=LCL D=M //save M[local] in D @2 //A = index D=D+A //D is now @(local + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push local 3 @LCL //A=LCL D=M //save M[local] in D @3 //A = index D=D+A //D is now @(local + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push local 4 @LCL //A=LCL D=M //save M[local] in D @4 //A = index D=D+A //D is now @(local + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //add @SP AM=M-1 //AM[SP] = M[SP] - 1 e.g @y D=M //D=M[A] e.g y A=A-1 //A = @y - 1 e.g @x M=D+M //M[@x] = y + M[@x] //add @SP AM=M-1 //AM[SP] = M[SP] - 1 e.g @y D=M //D=M[A] e.g y A=A-1 //A = @y - 1 e.g @x M=D+M //M[@x] = y + M[@x] //add @SP AM=M-1 //AM[SP] = M[SP] - 1 e.g @y D=M //D=M[A] e.g y A=A-1 //A = @y - 1 e.g @x M=D+M //M[@x] = y + M[@x] //add @SP AM=M-1 //AM[SP] = M[SP] - 1 e.g @y D=M //D=M[A] e.g y A=A-1 //A = @y - 1 e.g @x M=D+M //M[@x] = y + M[@x] //return instruction //frame = LCL @LCL //A=LCL D=M //D=LCL @frame //frame is a variable M=D //frame = LCL //retAddr = *(frame - 5) @5 //A=5 D=D-A //D = frame - 5 A=D //A = D = @retAddr D=M //D=M[A] = retAddr @retAddr //retAddr is a variable M=D //retAddr = frame - 5 //*ARG = pop argument 0 //pop argument 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @ARG //A=ARG D=M //save M[argument] in D @0 //A = index D=D+A //D is now @(argument + index) @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //SP = ARG-1 @ARG D=M // D = ARG @SP M=D+1 //SP=ARG+1 //THAT = *(frame-1) @frame A=M-1 //A = frame-1 D=M //D=M[frame-1] @THAT M=D //THAT = *(frame-1) //THIS = *(frame-2) @frame D=M //D=frame @2 A=D-A //A=frame-2 D=M //D = M[frame-2] @THIS M=D //THIS = *(frame-2) //ARG = *(frame-3) @frame D=M //D=frame @3 A=D-A //A=frame-3 D=M //D = M[frame-3] @ARG M=D //ARG = frame-3 //LCL = *(frame-4) @frame D=M //D=frame @4 A=D-A //A=frame-4 D=M //D = M[frame-4] @LCL M=D //LCL = frame-4 //goto retAddr @retAddr A=M //A = *retAddr 0;JMP //jmp to retAddr (Sys.add12) //function name //push constant 4002 @4002 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @3 //A = RAM @3 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push constant 5002 @5002 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //pop pointer 1 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @4 //A = RAM @4 D=A //D is now @pointer + index @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //push argument 0 @ARG //A=ARG D=M //save M[argument] in D @0 //A = index D=D+A //D is now @(argument + index) A=D //A = @ contained in D D=M//D=M[A], value to push @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //push constant 12 @12 //A=index D=A //D is now the constant @SP A=M //A = @SP M=D //M[A] = value to push @SP M=M+1 //sp+1 //add @SP AM=M-1 //AM[SP] = M[SP] - 1 e.g @y D=M //D=M[A] e.g y A=A-1 //A = @y - 1 e.g @x M=D+M //M[@x] = y + M[@x] //return instruction //frame = LCL @LCL //A=LCL D=M //D=LCL @frame //frame is a variable M=D //frame = LCL //retAddr = *(frame - 5) @5 //A=5 D=D-A //D = frame - 5 A=D //A = D = @retAddr D=M //D=M[A] = retAddr @retAddr //retAddr is a variable M=D //retAddr = frame - 5 //*ARG = pop argument 0 //pop argument 0 @SP AM=M-1 //AM = M[SP] - 1 D=M //D = the value to pop @R13 M=D //save the value in R13 @ARG //A=ARG D=M //save M[argument] in D @0 //A = index D=D+A //D is now @(argument + index) @R14 M=D //save D value @R13 D=M //D= value to pop @R14 A=M //A = (segmentBase+index) M=D //M[A] = value to pop //SP = ARG-1 @ARG D=M // D = ARG @SP M=D+1 //SP=ARG+1 //THAT = *(frame-1) @frame A=M-1 //A = frame-1 D=M //D=M[frame-1] @THAT M=D //THAT = *(frame-1) //THIS = *(frame-2) @frame D=M //D=frame @2 A=D-A //A=frame-2 D=M //D = M[frame-2] @THIS M=D //THIS = *(frame-2) //ARG = *(frame-3) @frame D=M //D=frame @3 A=D-A //A=frame-3 D=M //D = M[frame-3] @ARG M=D //ARG = frame-3 //LCL = *(frame-4) @frame D=M //D=frame @4 A=D-A //A=frame-4 D=M //D = M[frame-4] @LCL M=D //LCL = frame-4 //goto retAddr @retAddr A=M //A = *retAddr 0;JMP //jmp to retAddr
src/audio-wavefiles.adb
Ada-Audio/wavefiles
10
1806
<filename>src/audio-wavefiles.adb ------------------------------------------------------------------------------ -- -- -- WAVEFILES -- -- -- -- Main package -- -- -- -- The MIT License (MIT) -- -- -- -- Copyright (c) 2015 -- 2021 <NAME> -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining -- -- a copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and / or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be -- -- included in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ------------------------------------------------------------------------------ with Audio.Wavefiles.Read; with Audio.Wavefiles.Write; with Audio.Wavefiles.Internals; with Audio.RIFF.Wav.GUIDs; use Audio.RIFF.Wav.GUIDs; package body Audio.Wavefiles is procedure Init_Data_For_File_Opening (WF : in out Wavefile); procedure Check_Consistency (WF : in out Wavefile); procedure Reset_RIFF_Info (Info : out RIFF_Information); --------------- -- No_Errors -- --------------- function No_Errors (WF : in out Wavefile) return Boolean is (for all Error of WF.Errors => Error = False); -------------------------------- -- Init_Data_For_File_Opening -- -------------------------------- procedure Init_Data_For_File_Opening (WF : in out Wavefile) is begin WF.Sample_Pos := (Current => First_Sample_Count, Total => 0); Reset_RIFF_Info (WF.RIFF_Info); end Init_Data_For_File_Opening; ----------------------- -- Check_Consistency -- ----------------------- procedure Check_Consistency (WF : in out Wavefile) is begin if not Is_Consistent (Channel_Config => WF.Wave_Format.Channel_Config, Number_Of_Channels => Positive (WF.Wave_Format.Channels)) then WF.Set_Warning (Wavefile_Warning_Inconsistent_Channel_Mask); end if; end Check_Consistency; ------------ -- Create -- ------------ procedure Create (WF : in out Wavefile; Mode : File_Mode := Out_File; Name : String := ""; Form : String := "") is pragma Unreferenced (Form); begin WF.Reset_Errors; WF.Reset_Warnings; Init_Data_For_File_Opening (WF); if Mode in In_File | Append_File then WF.Wave_Format := Default; end if; Check_Consistency (WF); Create_Wavefile : declare Stream_Mode : constant Ada.Streams.Stream_IO.File_Mode := Ada.Streams.Stream_IO.File_Mode (Mode); begin Ada.Streams.Stream_IO.Create (WF.File, Stream_Mode, Name); WF.File_Access := Ada.Streams.Stream_IO.Stream (WF.File); end Create_Wavefile; case Mode is when In_File | Append_File => Audio.Wavefiles.Read.Read_Until_Data_Start (WF); when Out_File => Audio.Wavefiles.Write.Write_Until_Data_Start (WF); end case; WF.Is_Opened := WF.No_Errors; end Create; ---------- -- Open -- ---------- procedure Open (WF : in out Wavefile; Mode : File_Mode; Name : String; Form : String := "") is pragma Unreferenced (Form); begin WF.Reset_Errors; WF.Reset_Warnings; if WF.Is_Opened then WF.Set_Error (Wavefile_Error_File_Already_Open); return; end if; Init_Data_For_File_Opening (WF); case Mode is when In_File => WF.Wave_Format := Default; when Append_File => Parse_Wavefile : declare use Ada.Streams.Stream_IO; Stream_Mode : constant Ada.Streams.Stream_IO.File_Mode := Ada.Streams.Stream_IO.File_Mode'(In_File); begin Open (WF.File, Stream_Mode, Name); WF.File_Access := Stream (WF.File); Audio.Wavefiles.Read.Read_Until_Data_Start (WF); Close (WF.File); end Parse_Wavefile; when Out_File => null; end case; Open_Wavefile : declare Stream_Mode : constant Ada.Streams.Stream_IO.File_Mode := Ada.Streams.Stream_IO.File_Mode (Mode); begin Ada.Streams.Stream_IO.Open (WF.File, Stream_Mode, Name); WF.File_Access := Ada.Streams.Stream_IO.Stream (WF.File); end Open_Wavefile; case Mode is when In_File => Audio.Wavefiles.Read.Read_Until_Data_Start (WF); when Append_File => null; when Out_File => Audio.Wavefiles.Write.Write_Until_Data_Start (WF); end case; WF.Is_Opened := WF.No_Errors; if WF.Is_Opened then Check_Consistency (WF); else -- -- Close file in case of error -- if Ada.Streams.Stream_IO.Is_Open (WF.File) then Ada.Streams.Stream_IO.Close (WF.File); end if; end if; end Open; ----------------- -- End_Of_File -- ----------------- function End_Of_File (Sample_Pos : Sample_Info) return Boolean is (Sample_Pos.Current > (Sample_Pos.Total - Total_To_Last_Diff)); ----------------- -- End_Of_File -- ----------------- function End_Of_File (WF : in out Wavefile) return Boolean is begin if End_Of_File (WF.Sample_Pos) or Ada.Streams.Stream_IO.End_Of_File (WF.File) then return True; else return False; end if; end End_Of_File; ----------- -- Close -- ----------- procedure Close (WF : in out Wavefile) is use Ada.Streams.Stream_IO; begin WF.Reset_Errors; if not WF.Is_Opened then WF.Set_Error (Wavefile_Error_File_Not_Open); return; end if; if Mode (WF) = Out_File then Audio.Wavefiles.Write.Update_Data_Size (WF); end if; Close (WF.File); WF.Is_Opened := False; end Close; ---------------------------- -- Set_Format_Of_Wavefile -- ---------------------------- procedure Set_Format_Of_Wavefile (WF : in out Wavefile; Format : Wave_Format_Extensible) is begin WF.Wave_Format := Format; end Set_Format_Of_Wavefile; ------------------------ -- Format_Of_Wavefile -- ------------------------ function Format_Of_Wavefile (W : Wavefile) return Wave_Format_Extensible is begin return W.Wave_Format; end Format_Of_Wavefile; ------------------------ -- Number_Of_Channels -- ------------------------ function Number_Of_Channels (W : Wavefile) return Positive is (Positive (W.Wave_Format.Channels)); --------------- -- Bit_Depth -- --------------- function Bit_Depth (W : Wavefile) return Wav_Bit_Depth is (W.Wave_Format.Bits_Per_Sample); ----------------- -- Sample_Rate -- ----------------- function Sample_Rate (W : Wavefile) return Wav_Sample_Rate is (W.Wave_Format.Samples_Per_Sec); ---------- -- Mode -- ---------- function Mode (W : Wavefile) return File_Mode is (if Mode (W.File) = In_File then In_File else Out_File); ---------- -- Name -- ---------- function Name (W : Wavefile) return String is (Ada.Streams.Stream_IO.Name (W.File)); ------------------------- -- Is_Supported_Format -- ------------------------- function Is_Supported_Format (W : Wave_Format_Extensible) return Boolean is begin if not (W.Sub_Format = GUID_Undefined or W.Sub_Format = GUID_PCM or W.Sub_Format = GUID_IEEE_Float) then return False; end if; return True; end Is_Supported_Format; ------------------- -- Get_RIFF_Info -- ------------------- procedure Get_RIFF_Info (WF : in out Wavefile; Info : out RIFF_Information) is begin if WF.RIFF_Info.Chunks.Is_Empty then Audio.Wavefiles.Read.Parse_Wav_Chunks (WF); end if; Info := WF.RIFF_Info; end Get_RIFF_Info; --------------------- -- Reset_RIFF_Info -- --------------------- procedure Reset_RIFF_Info (Info : out RIFF_Information) is begin Info.Format := RIFF_Format_Unknown; Info.Id := RIFF_Identifier_Unknown; Info.Chunks.Clear; end Reset_RIFF_Info; ------------------------ -- Chunk_Element_Data -- ------------------------ function Chunk_Element_Data (WF : Wavefile; Chunk_Element : Wav_Chunk_Element) return Byte_Array is subtype Bounded_Byte_Array is Byte_Array (1 .. Chunk_Element.Size); Data : Bounded_Byte_Array; Prev_File_Index : constant Ada.Streams.Stream_IO.Positive_Count := Ada.Streams.Stream_IO.Index (WF.File); use Audio.Wavefiles.Internals; begin Set_File_Index_To_Chunk_Data_Start (WF.File, Chunk_Element.Start_Index); Bounded_Byte_Array'Read (WF.File_Access, Data); -- Set index to previous position Ada.Streams.Stream_IO.Set_Index (WF.File, Prev_File_Index); return Data; end Chunk_Element_Data; ---------------------- -- Find_First_Chunk -- ---------------------- procedure Find_First_Chunk (Chunks : Wav_Chunk_Elements; Chunk_Tag : Wav_Chunk_Tag; Found : out Wav_Chunk_Element_Found) is begin Found := (Success => False); for C of Chunks loop if C.Chunk_Tag = Chunk_Tag then Found := (Success => True, Chunk_Element => C); exit; end if; end loop; end Find_First_Chunk; -------------------- -- Current_Sample -- -------------------- function Current_Sample (WF : Wavefile) return Sample_Count is (WF.Sample_Pos.Current); ----------------- -- Last_Sample -- ----------------- function Last_Sample (WF : Wavefile) return Sample_Count is (WF.Sample_Pos.Total - Total_To_Last_Diff); ------------------------ -- Total_Sample_Count -- ------------------------ function Total_Sample_Count (WF : Wavefile) return Sample_Count is (WF.Sample_Pos.Total); ------------------------ -- Set_Current_Sample -- ------------------------ procedure Set_Current_Sample (WF : in out Wavefile; Position : Sample_Count) is begin Wavefiles.Read.Set_Current_Sample (WF, Position); end Set_Current_Sample; --------------------------------- -- To_Wavefile_Time_In_Seconds -- --------------------------------- function To_Wavefile_Time_In_Seconds (WF : Wavefile; Sample : Sample_Count) return Wavefile_Time_In_Seconds is (Wavefile_Time_In_Seconds (Sample) / Wavefile_Time_In_Seconds (To_Positive (WF.Wave_Format.Samples_Per_Sec))); --------------------- -- To_Sample_Count -- --------------------- function To_Sample_Count (WF : Wavefile; At_Time : Wavefile_Time_In_Seconds) return Sample_Count is (Sample_Count (At_Time * Wavefile_Time_In_Seconds (To_Positive (WF.Wave_Format.Samples_Per_Sec))) + WF.First_Sample); ------------------ -- Current_Time -- ------------------ function Current_Time (WF : Wavefile) return Wavefile_Time_In_Seconds is (To_Wavefile_Time_In_Seconds (WF, WF.Sample_Pos.Current - WF.First_Sample)); -------------- -- End_Time -- -------------- function End_Time (WF : Wavefile) return Wavefile_Time_In_Seconds is (To_Wavefile_Time_In_Seconds (WF, WF.Sample_Pos.Total)); ---------------------- -- Set_Current_Time -- ---------------------- procedure Set_Current_Time (WF : in out Wavefile; At_Time : Wavefile_Time_In_Seconds) is Position : constant Sample_Count := To_Sample_Count (WF, At_Time); begin Set_Current_Sample (WF, Position); end Set_Current_Time; --------------- -- Set_Error -- --------------- procedure Set_Error (WF : in out Wavefile; Error_Code : Wavefile_Error_Code) is begin WF.Errors (Error_Code) := True; end Set_Error; ------------------ -- Reset_Errors -- ------------------ procedure Reset_Errors (WF : in out Wavefile) is begin WF.Errors := (others => False); end Reset_Errors; ----------------- -- Set_Warning -- ----------------- procedure Set_Warning (WF : in out Wavefile; Warning_Code : Wavefile_Warning_Code) is begin WF.Warnings (Warning_Code) := True; end Set_Warning; -------------------- -- Reset_Warnings -- -------------------- procedure Reset_Warnings (WF : in out Wavefile) is begin WF.Warnings := (others => False); end Reset_Warnings; end Audio.Wavefiles;
Miei-sorgenti/old/Settima lezione/pop.asm
DigiOhhh/LabArchitettura2-2017-2018
1
100108
<filename>Miei-sorgenti/old/Settima lezione/pop.asm # Si implementi una struttura dati di tipo stack (LIFO) che permetta di salvare in memoria dinamicamente strutture del tipo: # struct { # int x; # int y; # int angle; # int *next; # } # # Si implementino in particolare le funzioni: # stack_push(x,y,angle) che inserisca un elemento nello stack # stack_pop() che rimuova un elemento dallo stack e lo restituisca all'utente (si restituisca 0 nel caso di stack vuoto) # stack_print() che stampi l'intero contenuto dello stack # # Suggerimento: si utilizzi la syscall sbrk per l'allocazione dinamica della memoria. .text .globl stack_pop stack_pop: move $t0, $a0 # $t0 <-- puntatore alla cima dello stack move $t1, $a1 # $t1 <-- numero degli elemento nello stack move $t2, $a2 # $t2 <-- base address dell'array in cui memorizzare valori di ritorno bnez $t1, for1 # if (len(stack) == 0) then return 0 li $v0, 0 li $v1, 0 jr $ra # Lo stack dovrebbe essere organizzato così: # int *next; # int angle; # int y; # int x; # E l'indirizzo di ogni elemento dovrebbe puntare a int x, quindi l'offset da usare per ottenere il puntatore # al prossimo elemento è 12. lw $t3, 12($t0) move $t4, $t0 for1: lw $t3, 12($t4) beqz $t3, return move $t4, $t3 j for1 # Arrivato qui, ho zero in $t3 e l'indirizzo dell'ultimo elemento dello stack in $t4 return: lw $t7, ($t0) # $t7 <-- x lw $t8, 4($t0) # $t8 <-- y lw $t9, 8($t0) # $t9 <-- angle # Devo fare in modo che adesso l'ultimo elemento abbia zero nel campo int *next: non penso possa evitare di utilizzare # un altro ciclo. La condizione è basata su $t0, perché lì c'è l'indirizzo contenuto nell'ultimo elemento dello stack move $t5, $t0 for2: lw $t6, 12($t5) beq $t6, $t4, reset move $t5, $t6 j for2 # Arrivato qui, ho l'indirizzo da rimpiazzare con zero in $t6 e l'indirizzo dell'elemento dello stack in $t5 reset: sw $zero, ($t5) sw $t7, ($t2) sw $t8, 4($t2) sw $t9, 8($t2) move $v0, $t2 # Restituisco il base address dell'array jr $ra
programs/oeis/340/A340084.asm
neoneye/loda
22
94151
<reponame>neoneye/loda ; A340084: a(n) = gcd(n-1, A336466(n)); Odd part of A340081(n). ; 1,1,1,1,1,1,3,1,1,1,5,1,3,1,1,1,1,1,9,1,1,1,11,1,1,1,1,3,7,1,15,1,1,1,1,1,9,1,1,1,5,1,21,1,1,1,23,1,3,1,1,3,13,1,1,1,1,1,29,1,15,1,1,1,1,5,33,1,1,3,35,1,9,1,1,3,1,1,39,1,1,1,41,1,1,1,1,1,11,1,9,1,1,1,1,1,3,1,1,1 seq $0,340081 ; a(n) = gcd(n-1, A003958(n)). lpb $0 dif $0,2 lpe
other.7z/SFC.7z/SFC/ソースデータ/ヨッシーアイランド/日本_Ver1/chip/Gdefchr.asm
prismotizm/gigaleak
0
83151
Name: Gdefchr.asm Type: file Size: 7232 Last-Modified: '2016-05-13T04:51:15Z' SHA-1: 457E3DC57EF4CCCB514540D39808F0CD672DB75F Description: null
theorems/cw/cohomology/grid/LongExactSequence.agda
timjb/HoTT-Agda
0
7021
<filename>theorems/cw/cohomology/grid/LongExactSequence.agda {-# OPTIONS --without-K --rewriting #-} open import HoTT open import cohomology.Theory open import groups.ExactSequence open import groups.HomSequence module cw.cohomology.grid.LongExactSequence {i} (CT : CohomologyTheory i) {X Y Z : Ptd i} (n : ℤ) (f : X ⊙→ Y) (g : Y ⊙→ Z) where open CohomologyTheory CT open import cohomology.PtdMapSequence CT open import cw.cohomology.grid.CofiberSplit (fst f) (fst g) open import cw.cohomology.grid.PtdMap f g {- X --> Y ----> Z | | | v v v 1 -> Y/X --> Z/X | this | v one v 1 ---> Z/Y -} private ⊙D-span : ⊙Span ⊙D-span = ⊙span Y/X Z Y (⊙cfcod' f) g ⊙D : Ptd i ⊙D = ⊙Pushout ⊙D-span Y/X-to-D : Y/X ⊙→ ⊙D Y/X-to-D = B/A-to-D , idp open import cohomology.LongExactSequence CT n Y/X-to-D ⊙E : Ptd i ⊙E = ⊙Cofiber (⊙left ⊙D-span) Z/Y-to-E : Z/Y ⊙→ ⊙E Z/Y-to-E = C/B-to-E , idp Z/X-to-D : Z/X ⊙→ ⊙D Z/X-to-D = C/A-to-D , idp grid-co∂ : C n Y/X →ᴳ C (succ n) Z/Y grid-co∂ = record {f = CEl-fmap (succ n) Z/Y-to-E ∘ GroupHom.f co∂ ; pres-comp = lemma} where abstract lemma = ∘ᴳ-pres-comp (C-fmap (succ n) Z/Y-to-E) co∂ grid-∂-before-Susp : C/B → Susp B/A grid-∂-before-Susp = extract-glue ∘ C/B-to-E ⊙grid-∂-before-Susp : Z/Y ⊙→ ⊙Susp Y/X ⊙grid-∂-before-Susp = grid-∂-before-Susp , lemma where abstract lemma = snd (⊙extract-glue ⊙∘ Z/Y-to-E) abstract grid-co∂-β : GroupHom.f grid-co∂ ∼ CEl-fmap (succ n) ⊙grid-∂-before-Susp ∘ <– (CEl-Susp n Y/X) grid-co∂-β x = ∘-CEl-fmap (succ n) Z/Y-to-E ⊙extract-glue _ abstract grid-∂-before-Susp-glue-β : ∀ x → ap (fst ⊙grid-∂-before-Susp) (glue x) == merid (cfcod x) grid-∂-before-Susp-glue-β x = ap-∘ extract-glue C/B-to-E (glue x) ∙ ap (ap extract-glue) (C/B-to-E-glue-β x) ∙ ap-∙' extract-glue (glue (cfcod x)) (ap cfcod (glue x)) ∙ ap2 _∙'_ (ExtractGlue.glue-β (cfcod x)) (∘-ap extract-glue cfcod (glue x) ∙ ap-cst south (glue x)) C-grid-cofiber-seq : HomSequence (C n Z/X) (C (succ n) Y/X) C-grid-cofiber-seq = C n Z/X →⟨ C-fmap n Y/X-to-Z/X ⟩ᴳ C n Y/X →⟨ grid-co∂ ⟩ᴳ C (succ n) Z/Y →⟨ C-fmap (succ n) Z/X-to-Z/Y ⟩ᴳ C (succ n) Z/X →⟨ C-fmap (succ n) Y/X-to-Z/X ⟩ᴳ C (succ n) Y/X ⊣|ᴳ private C-cofiber-seq-to-C-grid-cofiber-seq : HomSeqMap C-cofiber-seq C-grid-cofiber-seq (C-fmap n Z/X-to-D) (idhom _) C-cofiber-seq-to-C-grid-cofiber-seq = C-fmap n Z/X-to-D ↓⟨ comm-sqrᴳ (λ d → ! (C-fmap-idf n _) ∙ (C-comm-square n B/A-to-C/A-comm-square □$ᴳ d)) ⟩ᴳ idhom _ ↓⟨ comm-sqrᴳ (λ _ → idp) ⟩ᴳ C-fmap (succ n) Z/Y-to-E ↓⟨ C-comm-square (succ n) C/A-to-C/B-comm-square ⟩ᴳ C-fmap (succ n) Z/X-to-D ↓⟨ comm-sqrᴳ (λ d → ! (C-fmap-idf (succ n) _) ∙ (C-comm-square (succ n) B/A-to-C/A-comm-square □$ᴳ d)) ⟩ᴳ idhom _ ↓|ᴳ C-cofiber-seq-equiv-C-grid-cofiber-seq : HomSeqEquiv C-cofiber-seq C-grid-cofiber-seq (C-fmap n Z/X-to-D) (idhom _) C-cofiber-seq-equiv-C-grid-cofiber-seq = C-cofiber-seq-to-C-grid-cofiber-seq , CEl-isemap n Z/X-to-D C/A-to-D-is-equiv , idf-is-equiv _ , CEl-isemap (succ n) Z/Y-to-E C/B-to-E-is-equiv , CEl-isemap (succ n) Z/X-to-D C/A-to-D-is-equiv , idf-is-equiv _ abstract C-grid-cofiber-seq-is-exact : is-exact-seq C-grid-cofiber-seq C-grid-cofiber-seq-is-exact = seq-equiv-preserves-exact C-cofiber-seq-equiv-C-grid-cofiber-seq C-cofiber-seq-is-exact C-grid-cofiber-exact-seq : ExactSequence (C n Z/X) (C (succ n) Y/X) C-grid-cofiber-exact-seq = C-grid-cofiber-seq , C-grid-cofiber-seq-is-exact
oeis/017/A017158.asm
neoneye/loda-programs
11
24035
<reponame>neoneye/loda-programs ; A017158: a(n) = (8*n + 7)^10. ; 282475249,576650390625,41426511213649,819628286980801,8140406085191601,52599132235830049,253295162119140625,984930291881790849,3255243551009881201,9468276082626847201,24842341419143568849,59873693923837890625,134391637934412192049,283942098606901565601,569468379011812486801,1091533853073393531649,2010655586861806640625,3575694237941010577249,6162677950336718514001,10326930237613180030401,16871927924929095158449,26938938999176025390625,42122185590781554706449,64615048177878503606401 mul $0,8 add $0,7 pow $0,10
programs/oeis/074/A074400.asm
neoneye/loda
22
16206
; A074400: Sum of the even divisors of 2n. ; 2,6,8,14,12,24,16,30,26,36,24,56,28,48,48,62,36,78,40,84,64,72,48,120,62,84,80,112,60,144,64,126,96,108,96,182,76,120,112,180,84,192,88,168,156,144,96,248,114,186,144,196,108,240,144,240,160,180,120,336,124,192,208,254,168,288,136,252,192,288,144,390,148,228,248,280,192,336,160,372,242,252,168,448,216,264,240,360,180,468,224,336,256,288,240,504,196,342,312,434 seq $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n). mul $0,2
3-mid/impact/source/3d/collision/dispatch/impact-d3-union_find.adb
charlie5/lace
20
18511
package body impact.d3.union_Find is --- Forge -- procedure destruct (Self : in out Item) is begin Self.Free; end destruct; --- Attributes -- function getNumElements (Self : in Item) return Natural is begin return Natural (Self.m_elements.Length); end getNumElements; function isRoot (Self : in Item; x : in Integer) return Boolean is begin return x = Self.m_elements.Element (x).m_id; end isRoot; function getElement (Self : in Item; index : in Integer) return access btElement is begin return Self.m_elements.Element (index); end getElement; function find (Self : in Item; p, q : in Integer) return Boolean is begin return Self.find (p) = Self.find (q); end find; function find (Self : in Item; index : in Integer) return Integer -- nb: index is 0 based island index (atm) is -- btAssert(x < m_N); -- btAssert(x >= 0); x : Integer := index; elementPtr : btElement_view; -- kkk : Integer := Self.m_elements.Element (x+1).m_id; begin while x /= Self.m_elements.Element (x).m_id loop -- Not really a reason not to use path compression, and it flattens the trees/improves find performance dramatically. if USE_PATH_COMPRESSION then -- put_Line ("KKK: " & integer'Image (Self.m_elements.Element (x).m_id)); elementPtr := Self.m_elements.Element (Self.m_elements.Element (x).m_id); Self.m_elements.Element (x).m_id := elementPtr.m_id; x := elementPtr.m_id; else x := Self.m_elements.Element (x).m_id; end if; -- btAssert(x < m_N); -- btAssert(x >= 0); end loop; return x; end find; --- Operations -- -- This is a special operation, destroying the content of impact.d3.union_Find. -- -- It sorts the elements, based on island id, in order to make it easy to iterate over islands. -- procedure sortIslands (Self : in out Item) is numElements : constant Integer := Integer (Self.m_elements.Length); -- First store the original body index, and islandId. function "<" (L, R : in btElement_view) return Boolean is begin return l.m_id < r.m_id; end; package Sorter is new btElement_Vectors.Generic_Sorting ("<"); begin -- for i in 1 .. numElements for i in 0 .. numElements - 1 loop Self.m_elements.Element (i).m_id := Self.find (i); if not STATIC_SIMULATION_ISLAND_OPTIMIZATION then Self.m_elements.Element (i).m_sz := i; end if; end loop; -- Sort the vector using predicate and std::sort -- Sorter.sort (Self.m_elements); -- .quickSort (impact.d3.union_FindElementSortPredicate); end sortIslands; procedure reset (Self : in out Item; N : in Integer) is begin Self.allocate (N + 0); -- for i in 1 .. N for i in 0 .. N - 1 loop Self.m_elements.Element (i).m_id := i; Self.m_elements.Element (i).m_sz := 1; end loop; end reset; procedure allocate (Self : in out Item; N : in Integer) is use ada.Containers; begin Self.Free; -- Self.m_elements.set_Length (Count_type (N)); for i in 1 .. N loop Self.m_elements.append (new btElement); end loop; end allocate; procedure Free (Self : in out Item) is the_Element : btElement_view; begin for Each in 0 .. Integer (Self.m_elements.Length) - 1 loop the_Element := Self.m_elements.Element (Each); free (the_Element); end loop; Self.m_elements.clear; end Free; procedure unite (Self : in out Item; p, q : in Integer) is i : constant Integer := Self.find (p); j : constant Integer := Self.find (q); begin if i = j then return; end if; if not USE_PATH_COMPRESSION then -- weighted quick union, this keeps the 'trees' balanced, and keeps performance of unite O( log(n) ) if Self.m_elements.Element (i).m_sz < Self.m_elements.Element (j).m_sz then Self.m_elements.Element (i).m_id := j; Self.m_elements.Element (j).m_sz := Self.m_elements.Element (j).m_sz + Self.m_elements.Element (i).m_sz - 0; else Self.m_elements.Element (j).m_id := i; Self.m_elements.Element (i).m_sz := Self.m_elements.Element (i).m_sz + Self.m_elements.Element (j).m_sz - 0; end if; else Self.m_elements.Element (i).m_id := j; Self.m_elements.Element (j).m_sz := Self.m_elements.Element (j).m_sz + Self.m_elements.Element (i).m_sz - 0; end if; end unite; end impact.d3.union_Find;
oeis/040/A040766.asm
neoneye/loda-programs
11
171066
<reponame>neoneye/loda-programs ; A040766: Continued fraction for sqrt(795). ; 28,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5,56,5,9,5 seq $0,40204 ; Continued fraction for sqrt(219). add $1,$0 add $0,$1 div $1,12 lpb $1 sub $0,3 trn $1,8 lpe add $0,3
setoid-cats/Equality/Eq.agda
heades/AUGL
0
16273
--------------------------------------------------------------------- -- This file contains the definition of heterogenous equality and -- -- related facts. A lot of this code is old, and could be written -- -- better. This equality is mainly used for object equivalence. -- -- -- -- Some of it came from the paper: -- -- "Monads Need Not Be Endofunctors" by Altenkirch et al. -- -- -- -- See: http://www.cs.nott.ac.uk/~txa/publ/Relative_Monads.pdf -- --------------------------------------------------------------------- module Equality.Eq where open import Level open import Relation.Relation open import Relation.Binary.PropositionalEquality public renaming (sym to prop-sym ; trans to prop-trans; refl to prop-refl) data _≅_ {l : Level} {A : Set l} (a : A) : {A' : Set l} → A' → Set l where refl : a ≅ a postulate ext : ∀{i j}{A : Set i}{B B' : A → Set j}{f : ∀ a → B a}{g : ∀ a → B' a} → (∀ a → f a ≅ g a) → f ≅ g postulate prop-ext : ∀{i j}{A : Set i}{B : A → Set j}{f : ∀ a → B a}{g : ∀ a → B a} → (∀ a → f a ≡ g a) → f ≡ g ≅-to-≡ : ∀{l : Level}{A : Set l}{a b : A} → a ≅ b → a ≡ b ≅-to-≡ refl = prop-refl -- this could just be derived from ext postulate iext : ∀{i j}{A : Set i}{B B' : A → Set j}{f : ∀ {a} → B a}{g : ∀{a} → B' a} → (∀ a → f {a} ≅ g {a}) → _≅_ {_}{ {a : A} → B a} f { {a : A} → B' a} g sym : ∀{l : Level}{A : Set l }{a b : A} → a ≅ b → b ≅ a sym refl = refl trans : ∀{l : Level}{A : Set l}{a b c : A} → a ≅ b → b ≅ c → a ≅ c trans refl refl = refl isEqRel : ∀{l : Level}{A : Set l} → EqRel {A = A} (λ x y → x ≅ y) isEqRel {l} {A} = record { parEqPf = record { symPf = sym; transPf = trans }; refPf = refl } ir : ∀{l : Level}{A A' : Set l}{a : A}{a' : A'}{p q : a ≅ a'} → p ≅ q ir {p = refl}{q = refl} = refl eqApp : ∀{l l' : Level}{A : Set l}{B : Set l'}{f : A → B}{b c : A} → b ≅ c → (f b) ≅ (f c) eqApp refl = refl subst≅ : {l l' : Level}{A : Set l}{a b : A}{P : A → Set l'} → a ≅ b → P a → P b subst≅ refl x = x -- Cite from relative monads paper. deqApp : ∀{l : Level}{A : Set l}{B : A → Set l}(f : ∀ a → B a){a a' : A} → a ≅ a' → f a ≅ f a' deqApp f refl = refl feqApp : ∀{l l' : Level}{A : Set l}{B : Set l'}{f f' : A → B}{b c : A} → f ≅ f' → b ≅ c → (f b) ≅ (f' c) feqApp refl refl = refl ifeqApp : ∀{i j}{A : Set i}{B : A → Set j}{f f' : {x : A} → B x}(a : A) → _≅_ {_}{ {a : A} → B a} f { {a : A} → B a} f' → f {a} ≅ f' {a} ifeqApp a refl = refl ieqApp : ∀{x y}{A : Set x}{B : A → Set y}(f : ∀ {a} → B a){a a' : A} → a ≅ a' → f {a} ≅ f {a'} ieqApp f refl = refl -- Cite from relative monads paper. eqApp2 : ∀{i j k}{A : Set i}{B : A → Set j}{C : Set k}{a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → (f : (a : A) → B a → C) → f a b ≅ f a' b' eqApp2 refl refl f = refl eqApp3 : ∀{x y z w}{A : Set x}{B : A → Set y}{C : (a : A) → B a → Set z}{E : Set w} (f : (a : A)(b : B a)(c : C a b) → E) → {a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → {c : C a b}{c' : C a' b'} → c ≅ c' → f a b c ≅ f a' b' c' eqApp3 f refl refl refl = refl depfeqApp3a : ∀{l}{A : Set l}{B : Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B)(z : C x) → D) → (f' : (x : A)(y : B)(z : C x) → D) → f ≅ f' → {a : A}{b : B} {c : C a} → f a b c ≅ f' a b c depfeqApp3a {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3b : ∀{l}{A : Set l}{B : A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x)(z : C x) → D) → (f' : (x : A)(y : B x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a} {c : C a} → f a b c ≅ f' a b c depfeqApp3b {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3c : ∀{l}{A : Set l}{B : A → A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x x)(z : C x) → D) → (f' : (x : A)(y : B x x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a a} {c : C a} → f a b c ≅ f' a b c depfeqApp3c {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3d : ∀{l}{A : Set l}{B : A → A → Set (suc l)}{C : A → A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x x)(z : C x x) → D) → (f' : (x : A)(y : B x x)(z : C x x) → D) → f ≅ f' → {a : A}{b : B a a} {c : C a a} → f a b c ≅ f' a b c depfeqApp3d {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqApp3e : ∀{l}{A : Set l}{B : Set (suc l)}{C : A → A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B)(z : C x x) → D) → (f' : (x : A)(y : B)(z : C x x) → D) → f ≅ f' → {a : A}{b : B} {c : C a a} → f a b c ≅ f' a b c depfeqApp3e {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl depfeqAppa : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''}{a : A} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D x y) → f ≅ f' → f a ≅ f' a depfeqAppa {l}{l'}{l''}{l'''}{A}{B}{C}{D}{a} f f' p = eqApp {f = λ h → h a} p depfeqApp2a : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''}{a : A} (f : (y : B)(z : C a y) → D a y) → (f' : (y : B)(z : C a y) → D a y) → f ≅ f' → {b : B} {c : C a b} → f b c ≅ f' b c depfeqApp2a f f' p {b} {c} = feqApp {f = f b} {f' = f' b} (eqApp {f = λ h → h b} p) refl depfeqApp3f : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D : A → B → Set l'''} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D x y) → f ≅ f' → {a : A}{b : B} {c : C a b} → f a b c ≅ f' a b c depfeqApp3f {_}{_}{_}{_}{A}{B}{C}{D} f f' p {a}{b}{c} = depfeqApp2a {A = A} {B = B}{C = λ o1 o2 → C o1 o2} {D = λ o1₁ o2₁ → D o1₁ o2₁} (f a) (f' a) (eqApp {f = λ h → h a} p) {b} {c} depfeqApp3g : ∀{l l' l'' l'''}{A : Set l}{B : Set l'}{C : A → B → Set l''}{D D' : A → B → Set l'''} (f : (x : A)(y : B)(z : C x y) → D x y) → (f' : (x : A)(y : B)(z : C x y) → D' x y) → D ≅ D' → f ≅ f' → {a : A}{b : B} {c : C a b} → f a b c ≅ f' a b c depfeqApp3g {_}{_}{_}{_}{A}{B}{C}{D} f f' refl p {a}{b}{c} = depfeqApp2a {A = A} {B = B} {C = λ o1₁ o2₁ → C o1₁ o2₁} {D = λ o1 o2 → D o1 o2} (f a) (f' a) (eqApp {f = λ h → h a} p) {b} {c} idepfeqApp2a : ∀{l l' l'' l''' l''''}{A : Set l}{B : Set l'}{C : Set l''}{D : A → B → C → Set l'''}{E : A → B → C → Set l''''}{a : A} (f : {x : B}{y : C}(z : D a x y) → E a x y) → (f' : {x : B}{y : C}(z : D a x y) → E a x y) → (∀{x y} → f {x}{y} ≅ f' {x}{y}) → {b : B}{c : C}{m : D a b c} → f {b}{c} m ≅ f' {b} {c} m idepfeqApp2a {l}{l'}{l''}{l'''}{l''''}{A}{B}{C}{D}{E}{a} f f' p {b}{c}{m} = feqApp {f = f {b} {c}} {f' = f' {b} {c}} {m} {m} (ext (λ h → feqApp {f = f {b} {c}} {f' = f' {b} {c}} {h} {h} (p {b}{c}) refl)) refl depfeqApp2b : ∀{l l' l''}{A : Set l}{D : A → A → Set l'}{E E' : A → A → Set l''} (f : (x : A)(y : A)(z : A) → (m1 : D y z) → (m2 : D x y) → E x z) → {f' : (x : A)(y : A)(z : A) → (m1 : D y z) → (m2 : D x y) → E' x z} → E ≅ E' → f ≅ f' → {a a' b b' c c' : A}{m1 : D b c}{m2 : D a b}{m1' : D b' c'}{m2' : D a' b'} → a ≅ a' → b ≅ b' → c ≅ c' → m1 ≅ m1' → m2 ≅ m2' → f a b c m1 m2 ≅ f' a' b' c' m1' m2' depfeqApp2b {_}{_}{_}{A}{D}{E} f refl refl {a = a}{b = b}{c = c}{m1 = m1}{m2 = m2} refl refl refl refl refl = eqApp {f = f a b c m1} {m2}{m2} refl feqApp3 : ∀{l}{A : Set l}{B : A → Set (suc l)}{C : A → Set (suc l)}{D : Set (suc l)} (f : (x : A)(y : B x)(z : C x) → D) → (f' : (x : A)(y : B x)(z : C x) → D) → f ≅ f' → {a : A}{b : B a} {c : C a} → f a b c ≅ f' a b c feqApp3 {_}{A}{B}{C} f f' p {a}{b}{c} = feqApp {f = f a b} {f' = f' a b} (feqApp {f = f a} {f' = f' a} (eqApp {f = λ h → h a} p) refl) refl coerce : ∀{l}{A B : Set l} → A ≅ B → A → B coerce refl a = a p : ∀{m}{A B : Set m}{a : A}{b : B} → (q : B ≅ A) → _≅_ {m} {A} a {A} (coerce q b) → _≅_ {m} {A} a {B} b p refl refl = refl eqApp4 : ∀{x y z v w}{A : Set x}{B : A → Set y}{C : (a : A) → B a → Set z}{D : (a : A)(b : B a) → C a b → Set v}{E : Set w} (f : (a : A)(b : B a)(c : C a b) → D a b c → E) → {a a' : A} → a ≅ a' → {b : B a}{b' : B a'} → b ≅ b' → {c : C a b}{c' : C a' b'} → c ≅ c' → {d : D a b c}{d' : D a' b' c'} → d ≅ d' → f a b c d ≅ f a' b' c' d' eqApp4 f refl refl refl refl = refl funCong : ∀{l m : Level}{A : Set l}{B : Set m}{f g : A → B}{a : A}{b : B} → (p : f ≅ g) → (q : f a ≅ b) → (w : g a ≅ b) → q ≅ w funCong refl q w = ir funCong2 : ∀{l : Level}{A B B' X Y : Set l}{f : ∀{X Y} → A → B}{g : ∀{X Y} → A → B'}{a : A}{b : B} → (r : B ≅ B') → (p : (λ {X}{Y} → f {X}{Y}) ≅ (λ {X}{Y} → g {X}{Y})) → (q : f {X}{Y} a ≅ b) → (w : g {X}{Y} a ≅ b) → q ≅ w funCong2 refl refl q w = ir fixtypes : ∀{x}{A A' : Set x}{a a' : A}{a'' a''' : A'}{p : a ≅ a'}{q : a'' ≅ a'''} → a ≅ a'' → a' ≅ a''' → p ≅ q fixtypes refl refl = ir
tests/covered/ImplArg.agda
andrejtokarcik/agda-semantics
3
12129
-- https://github.com/bitonic/tog/wiki/Implicit-Arguments -- aj s popisom checkingu od <NAME> module ImplArg where data Nat : Set where zero : Nat suc : Nat -> Nat data Vec (A : Set) : Nat -> Set where vnil : Vec A zero vcons : {n : Nat} -> A -> Vec A n -> Vec A (suc n) Cons = {A : Set} (a : A) {n : Nat} -> Vec A n -> Vec A (suc n) cons : Cons cons a = vcons a
utils/puts.asm
pchynoweth/cx16-utils
0
240391
<reponame>pchynoweth/cx16-utils .export puts .include "cx16.inc" .include "cbm_kernal.inc" .include "utils/reg.inc" .code ; invalidates a,y .proc puts ldy #0 @loop: lda (REG::r0), y beq @done jsr CHROUT iny bra @loop @done: rts .endproc
src/wavefiles_gtk-wavefile_manager.adb
silentTeee/ada_wavefiles_gtk_app
0
303
------------------------------------------------------------------------------- -- -- WAVEFILES GTK APPLICATION -- -- Wavefile Manager -- -- The MIT License (MIT) -- -- Copyright (c) 2017 <NAME> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and / -- or sell copies of the Software, and to permit persons to whom the Software -- is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. ------------------------------------------------------------------------------- with Interfaces; with Ada.Characters.Latin_1; with Audio.Wavefiles; with Audio.RIFF.Wav.Formats; with Audio.RIFF.Wav.GUIDs; package body WaveFiles_Gtk.Wavefile_Manager is -------------- -- Get_Info -- -------------- function Get_Info (Wavefile : String) return String is WF_In : Audio.Wavefiles.Wavefile; RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible; function Get_RIFF_GUID_String (Sub_Format : Audio.RIFF.Wav.Formats.GUID) return String; function Get_RIFF_Extended (RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible) return String; package Wav_Read renames Audio.Wavefiles; use Interfaces; function Get_RIFF_GUID_String (Sub_Format : Audio.RIFF.Wav.Formats.GUID) return String is use type Audio.RIFF.Wav.Formats.GUID; begin if Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_Undefined then return "Subformat: undefined"; elsif Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_PCM then return "Subformat: KSDATAFORMAT_SUBTYPE_PCM (IEC 60958 PCM)"; elsif Sub_Format = Audio.RIFF.Wav.GUIDs.GUID_IEEE_Float then return "Subformat: KSDATAFORMAT_SUBTYPE_IEEE_FLOAT " & "(IEEE Floating-Point PCM)"; else return "Subformat: unknown"; end if; end Get_RIFF_GUID_String; function Get_RIFF_Extended (RIFF_Data : Audio.RIFF.Wav.Formats.Wave_Format_Extensible) return String is S : constant String := ("Valid bits per sample: " & Unsigned_16'Image (RIFF_Data.Valid_Bits_Per_Sample)); begin if RIFF_Data.Size > 0 then return (S & Ada.Characters.Latin_1.LF & Get_RIFF_GUID_String (RIFF_Data.Sub_Format)); else return ""; end if; end Get_RIFF_Extended; begin Wav_Read.Open (WF_In, Wav_Read.In_File, Wavefile); RIFF_Data := Wav_Read.Format_Of_Wavefile (WF_In); Wav_Read.Close (WF_In); declare S_Wav_1 : constant String := ("Bits per sample: " & Audio.RIFF.Wav.Formats.Wav_Bit_Depth'Image (RIFF_Data.Bits_Per_Sample) & Ada.Characters.Latin_1.LF & "Channels: " & Unsigned_16'Image (RIFF_Data.Channels) & Ada.Characters.Latin_1.LF & "Samples per second: " & Audio.RIFF.Wav.Formats.Wav_Sample_Rate'Image (RIFF_Data.Samples_Per_Sec) & Ada.Characters.Latin_1.LF & "Extended size: " & Unsigned_16'Image (RIFF_Data.Size) & Ada.Characters.Latin_1.LF); S_Wav_2 : constant String := Get_RIFF_Extended (RIFF_Data); begin return "File: " & Wavefile & Ada.Characters.Latin_1.LF & S_Wav_1 & S_Wav_2; end; end Get_Info; end WaveFiles_Gtk.Wavefile_Manager;
test/demangle-cases/bug-978.asm
OfekShilon/compiler-explorer
4,668
25795
<filename>test/demangle-cases/bug-978.asm _ZN1D1aEv: push rbp mov rbp, rsp mov QWORD PTR [rbp-8], rdi mov eax, 1 pop rbp ret _ZN1D3abcEv: push rbp mov rbp, rsp mov QWORD PTR [rbp-8], rdi mov eax, 1 pop rbp ret _ZN1C1aEv: push rbp mov rbp, rsp mov QWORD PTR [rbp-8], rdi mov eax, 1 pop rbp ret
monitor/sd_library.asm
mfkiwl/QNICE-FPGA-hyperRAM
53
25532
; ;;============================================================================= ;; The collection of SD Card related functions starts here ;;============================================================================= ; ; ;***************************************************************************** ;* SD$RESET resets the SD Card ;* ;* R8: 0, if everything went OK, otherwise the error code ;***************************************************************************** ; SD$RESET INCRB MOVE IO$SD_CSR, R0 MOVE SD$CMD_RESET, @R0 RSUB SD$WAIT_BUSY, 1 DECRB RET ; ;***************************************************************************** ;* SD$READ_BLOCK reads a 512 byte block from the SD Card ;* ;* INPUT: R8/R9 = LO/HI words of the 32-bit block address ;* OUTPUT: R8 = 0 (no error), or error code ;* ;* The read data is stored inside 512 byte buffer of the the SD controller ;* memory that can then be accessed via SD$READ_BYTE. ;* ;* IMPORTANT: 512-byte block addressing is used always, i.e. independent of ;* the SD Card type. Address #0 means 0..511, address #1 means 512..1023, .. ;***************************************************************************** ; SD$READ_BLOCK INCRB MOVE R8, R1 ; save R8 due to WAIT_BUSY RSUB SD$WAIT_BUSY, 1 ; wait to be ready CMP R8, 0 ; error? RBRA _SD$RB_END, !Z ; yes: return MOVE IO$SD_ADDR_LO, R0 ; lo word of 32-bit address MOVE R1, @R0 MOVE IO$SD_ADDR_HI, R0 ; hi word of 32-bit address MOVE R9, @R0 MOVE IO$SD_CSR, R0 MOVE SD$CMD_READ, @R0 ; issue block read command RSUB SD$WAIT_BUSY, 1 ; wait until finished _SD$RB_END DECRB RET ; ;***************************************************************************** ;* SD$WRITE_BLOCK writes a 512 byte block to the SD Card ;* ;* @TODO: Implement and document ;***************************************************************************** ; SD$WRITE_BLOCK INCRB DECRB RET ; ;***************************************************************************** ;* SD$READ_BYTE reads a byte from the read buffer memory of the controller ;* ;* INPUT: R8 = address between 0 .. 511 ;* OUTPUT: R8 = byte ;* ;* No boundary checks are performed. ;***************************************************************************** ; SD$READ_BYTE INCRB MOVE IO$SD_DATA_POS, R0 MOVE R8, @R0 MOVE IO$SD_DATA, R0 MOVE @R0, R8 DECRB RET ; ;***************************************************************************** ;* SD$WRITE_BYTE writes a byte to the write memory buffer of the controller ;* ;* @TODO: Implement and document ;***************************************************************************** ; SD$WRITE_BYTE INCRB DECRB RET ; ;***************************************************************************** ;* SD$WAIT_BUSY waits, while the SD Card is executing any command ;* ;* R8: 0, if everything went OK, otherwise the error code ;* ;* Side effect: Starts the cycle counter (if it was stopped), but does not ;* reset the value, so that other countings are not influenced. ;***************************************************************************** ; SD$WAIT_BUSY INCRB ; Make sure that the cycle counter is running for being ; able to measure the timeout. Do not reset it, but find ; the target value via addition (wrap around is OK), so that ; other running cycle counting processes are not disturbed ; by this MOVE IO$CYC_STATE, R0 ; make sure, the cycle counter OR CYC$RUN, @R0 ; is running MOVE IO$CYC_MID, R3 MOVE @R3, R7 ADD SD$TIMEOUT_MID, R7 ; check busy status of SD card and timeout MOVE IO$SD_CSR, R0 ; SD Card Command & Status MOVE IO$SD_ERROR, R2 ; SD Card Errors _SD$WAIT_BUSY_L MOVE @R3, R1 ; check for timeout CMP R1, R7 ; timeout reached RBRA _SD$WAIT_TO, Z ; yes: return timeout MOVE @R0, R1 ; read CSR register AND SD$BIT_BUSY, R1 ; check busy flag RBRA _SD$WAIT_BUSY_L, !Z ; loop if busy flag is set XOR R8, R8 ; assume no error, but did an MOVE @R0, R1 ; read CSR register AND SD$BIT_ERROR, R1 ; error flag? RBRA _SD$WAIT_END, Z ; no error _SD$WAIT_ERR MOVE @R2, R8 ; return error value RBRA _SD$WAIT_END, 1 _SD$WAIT_TO MOVE SD$ERR_TIMEOUT, R8 _SD$WAIT_END DECRB RET
examples/tactics/ac/Logic.agda
cruhland/agda
1,989
12874
<filename>examples/tactics/ac/Logic.agda module Logic where data True : Set where tt : True data False : Set where
src/base/dates/util-dates-formats.adb
RREE/ada-util
60
20897
----------------------------------------------------------------------- -- util-dates-formats -- Date Format ala strftime -- Copyright (C) 2011, 2018, 2020 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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; with Ada.Calendar; with Ada.Characters.Handling; with Ada.Calendar.Formatting; with GNAT.Calendar; with Util.Strings.Vectors; with Util.Strings.Transforms; package body Util.Dates.Formats is use Ada.Strings.Unbounded; type String_Array is array (Positive range <>) of Util.Strings.Name_Access; -- Week day names (long and short). Monday_Name : aliased constant String := "Monday"; Monday_Short_Name : aliased constant String := "Mon"; Tuesday_Name : aliased constant String := "Tuesday"; Tuesday_Short_Name : aliased constant String := "Tue"; Wednesday_Name : aliased constant String := "Wednesday"; Wednesday_Short_Name : aliased constant String := "Wed"; Thursday_Name : aliased constant String := "Thursday"; Thursday_Short_Name : aliased constant String := "Thu"; Friday_Name : aliased constant String := "Friday"; Friday_Short_Name : aliased constant String := "Fri"; Saturday_Name : aliased constant String := "Saturday"; Saturday_Short_Name : aliased constant String := "Sat"; Sunday_Name : aliased constant String := "Sunday"; Sunday_Short_Name : aliased constant String := "Sun"; -- Month names (long and short). January_Name : aliased constant String := "January"; January_Short_Name : aliased constant String := "Jan"; February_Name : aliased constant String := "February"; February_Short_Name : aliased constant String := "Feb"; March_Name : aliased constant String := "March"; March_Short_Name : aliased constant String := "Mar"; April_Name : aliased constant String := "April"; April_Short_Name : aliased constant String := "Apr"; May_Name : aliased constant String := "May"; May_Short_Name : aliased constant String := "May"; June_Name : aliased constant String := "June"; June_Short_Name : aliased constant String := "Jun"; July_Name : aliased constant String := "July"; July_Short_Name : aliased constant String := "Jul"; August_Name : aliased constant String := "August"; August_Short_Name : aliased constant String := "Aug"; September_Name : aliased constant String := "September"; September_Short_Name : aliased constant String := "Sep"; October_Name : aliased constant String := "October"; October_Short_Name : aliased constant String := "Oct"; November_Name : aliased constant String := "November"; November_Short_Name : aliased constant String := "Nov"; December_Name : aliased constant String := "December"; December_Short_Name : aliased constant String := "Dec"; Day_Names : constant String_Array (1 .. 7) := (Monday_Name'Access, Tuesday_Name'Access, Wednesday_Name'Access, Thursday_Name'Access, Friday_Name'Access, Saturday_Name'Access, Sunday_Name'Access); Day_Short_Names : constant String_Array (1 .. 7) := (Monday_Short_Name'Access, Tuesday_Short_Name'Access, Wednesday_Short_Name'Access, Thursday_Short_Name'Access, Friday_Short_Name'Access, Saturday_Short_Name'Access, Sunday_Short_Name'Access); Month_Names : constant String_Array (1 .. 12) := (January_Name'Access, February_Name'Access, March_Name'Access, April_Name'Access, May_Name'Access, June_Name'Access, July_Name'Access, August_Name'Access, September_Name'Access, October_Name'Access, November_Name'Access, December_Name'Access); Month_Short_Names : constant String_Array (1 .. 12) := (January_Short_Name'Access, February_Short_Name'Access, March_Short_Name'Access, April_Short_Name'Access, May_Short_Name'Access, June_Short_Name'Access, July_Short_Name'Access, August_Short_Name'Access, September_Short_Name'Access, October_Short_Name'Access, November_Short_Name'Access, December_Short_Name'Access); function Get_Label (Bundle : in Util.Properties.Manager'Class; Prefix : in String; Index : in Natural; Short : in Boolean) return String; function Get_Label (Bundle : in Util.Properties.Manager'Class; Prefix : in String; Index : in Natural; Short : in Boolean) return String is Num : constant String := Natural'Image (Index); Name : constant String := Prefix & Num (Num'First + 1 .. Num'Last); begin if Short then return Bundle.Get (Name & SHORT_SUFFIX, ""); else return Bundle.Get (Name & LONG_SUFFIX, ""); end if; end Get_Label; -- ------------------------------ -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. -- ------------------------------ procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String; Month : in Ada.Calendar.Month_Number; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True) is Value : constant String := Get_Label (Bundle, MONTH_NAME_PREFIX, Natural (Month), Short); begin if Value'Length > 0 then Append (Into, Value); elsif Short then Append (Into, Month_Short_Names (Month).all); else -- If the resource bundle is empty, fallback to hard-coded English values. Append (Into, Month_Names (Month).all); end if; end Append_Month; -- ------------------------------ -- Append the localized month string in the <b>Into</b> string. -- The month string is found in the resource bundle under the name: -- util.month<month number>.short -- util.month<month number>.long -- If the month string is not found, the month is displayed as a number. -- ------------------------------ procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String; Day : in Ada.Calendar.Formatting.Day_Name; Bundle : in Util.Properties.Manager'Class; Short : in Boolean := True) is use Ada.Calendar.Formatting; Value : constant String := Get_Label (Bundle, DAY_NAME_PREFIX, Day_Name'Pos (Day), Short); begin if Value'Length > 0 then Append (Into, Value); elsif Short then -- If the resource bundle is empty, fallback to hard-coded English values. Append (Into, Day_Short_Names (Day_Name'Pos (Day)).all); else Append (Into, Day_Names (Day_Name'Pos (Day)).all); end if; end Append_Day; -- ------------------------------ -- Append a number with padding if necessary -- ------------------------------ procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String; Value : in Natural; Padding : in Character; Length : in Natural := 2) is N : constant String := Natural'Image (Value); begin if Length = 0 or (Padding /= ' ' and Padding /= '0') then Append (Into, N (N'First + 1 .. N'Last)); elsif N'Length <= Length then Append (Into, Padding); Append (Into, N (N'First + 1 .. N'Last)); else Append (Into, N (N'Last - Length + 1 .. N'Last)); end if; end Append_Number; -- ------------------------------ -- Append the timezone offset -- ------------------------------ procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String; Offset : in Ada.Calendar.Time_Zones.Time_Offset) is use type Ada.Calendar.Time_Zones.Time_Offset; Value : Natural; begin if Offset < 0 then Append (Into, '-'); Value := Natural (-Offset); else Value := Natural (Offset); end if; Append_Number (Into, Value / 60, '0'); Append (Into, ':'); Append_Number (Into, Value mod 60, '0'); end Append_Time_Offset; -- ------------------------------ -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Returns the formatted date in the stream. -- ------------------------------ procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) is TM : Date_Record; begin Split (TM, Date); Format (Into, Pattern, TM, Bundle); end Format; -- ------------------------------ -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Returns the formatted date in the stream. -- ------------------------------ procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String; Pattern : in String; Date : in Date_Record; Bundle : in Util.Properties.Manager'Class) is use Ada.Calendar; use Ada.Calendar.Formatting; use Util.Strings.Transforms; use type Ada.Calendar.Time_Zones.Time_Offset; Pos : Positive := Pattern'First; Pad : Character := '0'; C : Character; begin while Pos <= Pattern'Last loop C := Pattern (Pos); if C /= '%' then Append (Into, C); Pos := Pos + 1; else Pos := Pos + 1; exit when Pos > Pattern'Last; C := Pattern (Pos); Pad := '0'; if C = '_' or C = '-' or C = 'E' or C = 'O' or C = '^' then exit when Pos = Pattern'Last; if C = '-' then Pad := '-'; elsif C = '_' then Pad := ' '; end if; Pos := Pos + 1; C := Pattern (Pos); end if; case C is when '%' => Append (Into, '%'); -- %a The abbreviated weekday name according to the current locale. when 'a' => Append_Day (Into, Date.Day, Bundle, True); -- %A The full weekday name according to the current locale. when 'A' => Append_Day (Into, Date.Day, Bundle, False); -- %b The abbreviated month name according to the current locale. -- %h Equivalent to %b. (SU) when 'b' | 'h' => Append_Month (Into, Date.Month, Bundle, True); -- %B The full month name according to the current locale. when 'B' => Append_Month (Into, Date.Month, Bundle, False); -- %c The preferred date and time representation for the current locale. when 'c' => Format (Into, Bundle.Get (DATE_TIME_LOCALE_NAME, DATE_TIME_DEFAULT_PATTERN), Date, Bundle); -- %C The century number (year/100) as a 2-digit integer. (SU) when 'C' => Append_Number (Into, Natural (Date.Year / 100), Pad); -- %d The day of the month as a decimal number (range 01 to 31). when 'd' => Append_Number (Into, Natural (Date.Month_Day), Pad); -- %D Equivalent to %m/%d/%y when 'D' => Format (Into, "%m/%d/%y", Date, Bundle); -- %e Like %d, the day of the month as a decimal number, -- but a leading zero is replaced by a space. (SU) when 'e' => Append_Number (Into, Natural (Date.Month), ' '); -- %F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99) when 'F' => Format (Into, "%Y-%m-%d", Date, Bundle); -- %G The ISO 8601 week-based year when 'G' => Append_Number (Into, Natural (Date.Year), Pad, 4); Append (Into, 'W'); Append_Number (Into, Natural (GNAT.Calendar.Week_In_Year (Date.Date)), Pad); -- %g Like %G, but without century, that is, -- with a 2-digit year (00-99). (TZ) when 'g' => Append_Number (Into, Natural (Date.Year mod 100), Pad, 2); Append (Into, 'W'); Append_Number (Into, Natural (GNAT.Calendar.Week_In_Year (Date.Date)), Pad); -- %H The hour as a decimal number using a 24-hour clock (range 00 to 23). when 'H' => Append_Number (Into, Natural (Date.Hour), Pad); -- %I The hour as a decimal number using a 12-hour clock (range 01 to 12). when 'I' => Append_Number (Into, Natural (Date.Hour mod 12), Pad); -- %j The day of the year as a decimal number (range 001 to 366). when 'j' => Append_Number (Into, Natural (GNAT.Calendar.Day_In_Year (Date.Date)), Pad, 3); -- %k The hour (24-hour clock) as a decimal number (range 0 to 23); when 'k' => Append_Number (Into, Natural (Date.Hour), ' '); -- %l The hour (12-hour clock) as a decimal number (range 1 to 12); when 'l' => Append_Number (Into, Natural (Date.Hour mod 12), ' '); -- %m The month as a decimal number (range 01 to 12). when 'm' => Append_Number (Into, Natural (Date.Month), Pad); -- %M The minute as a decimal number (range 00 to 59). when 'M' => Append_Number (Into, Natural (Date.Minute), Pad); -- %n A newline character. (SU) when 'n' => Append (Into, ASCII.LF); -- %p Either "AM" or "PM" when 'p' => if Date.Hour >= 12 then Append (Into, Bundle.Get (PM_NAME, PM_DEFAULT)); else Append (Into, Bundle.Get (AM_NAME, AM_DEFAULT)); end if; -- %P Like %p but in lowercase: "am" or "pm" when 'P' => -- SCz 2011-10-01: the To_Lower_Case will not work for UTF-8 strings. if Date.Hour >= 12 then Append (Into, To_Lower_Case (Bundle.Get (PM_NAME, PM_DEFAULT))); else Append (Into, To_Lower_Case (Bundle.Get (AM_NAME, AM_DEFAULT))); end if; -- %r The time in a.m. or p.m. notation. -- In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) when 'r' => Format (Into, "%I:%M:%S %p", Date, Bundle); -- %R The time in 24-hour notation (%H:%M). when 'R' => Format (Into, "%H:%M", Date, Bundle); -- %s The number of seconds since the Epoch, that is, -- since 1970-01-01 00:00:00 UTC. (TZ) when 's' => null; -- %S The second as a decimal number (range 00 to 60). when 'S' => Append_Number (Into, Natural (Date.Second), Pad); -- %t A tab character. (SU) when 't' => Append (Into, ASCII.HT); -- %T The time in 24-hour notation (%H:%M:%S). (SU) when 'T' => Format (Into, "%H:%M:%S", Date, Bundle); -- %u The day of the week as a decimal, range 1 to 7, -- Monday being 1. See also %w. (SU) when 'u' => Append_Number (Into, Day_Name'Pos (Date.Day), Pad); -- %U The week number of the current year as a decimal number, -- range 00 to 53 when 'U' => Append_Number (Into, Natural (GNAT.Calendar.Week_In_Year (Date.Date)), Pad); -- %V The ISO 8601 week number when 'V' => Append_Number (Into, Natural (GNAT.Calendar.Week_In_Year (Date.Date)), Pad); -- %w The day of the week as a decimal, range 0 to 6, Sunday being 0. -- See also %u. when 'w' => if Date.Day = Sunday then Append_Number (Into, 0, Pad); else Append_Number (Into, Day_Name'Pos (Date.Day) + 1, Pad); end if; -- %W The week number of the current year as a decimal number, -- range 00 to 53 when 'W' => Append_Number (Into, Natural (GNAT.Calendar.Week_In_Year (Date.Date)), Pad); -- %x The preferred date representation for the current locale without -- the time. when 'x' => Format (Into, Bundle.Get (DATE_LOCALE_NAME, DATE_DEFAULT_PATTERN), Date, Bundle); -- %X The preferred time representation for the current locale without -- the date. when 'X' => Format (Into, Bundle.Get (TIME_LOCALE_NAME, TIME_DEFAULT_PATTERN), Date, Bundle); -- %y The year as a decimal number without a century (range 00 to 99). when 'y' => Append_Number (Into, Natural (Date.Year mod 100), Pad); -- %Y The year as a decimal number including the century. when 'Y' => Append_Number (Into, Natural (Date.Year), Pad, 4); -- %z The time-zone as hour offset from GMT. when 'z' => Append_Time_Offset (Into, Date.Time_Zone); -- %Z The timezone or name or abbreviation. when 'Z' => Append (Into, "UTC"); if Date.Time_Zone > 0 then Append (Into, '+'); Append_Time_Offset (Into, Date.Time_Zone); elsif Date.Time_Zone < 0 then Append_Time_Offset (Into, Date.Time_Zone); end if; when others => Append (Into, '%'); Append (Into, Pattern (Pos)); end case; Pos := Pos + 1; end if; end loop; end Format; function Format (Pattern : in String; Date : in Ada.Calendar.Time; Bundle : in Util.Properties.Manager'Class) return String is Result : Unbounded_String; begin Format (Result, Pattern, Date, Bundle); return To_String (Result); end Format; procedure Parse (Date : in String; Pattern : in String; Bundle : in Util.Properties.Manager'Class; Result : in out Date_Record; Last : out Positive); function Parse (Date : in String; Pattern : in String; Bundle : in Util.Properties.Manager'Class) return Date_Record is Last : Positive; Result : Date_Record; begin Parse (Date, Pattern, Bundle, Result, Last); if Last <= Date'Last then raise Constraint_Error with "Invalid date format"; end if; Result.Date := Time_Of (Result); return Result; end Parse; -- ------------------------------ -- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>. -- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>. -- Returns the formatted date in the stream. -- ------------------------------ procedure Parse (Date : in String; Pattern : in String; Bundle : in Util.Properties.Manager'Class; Result : in out Date_Record; Last : out Positive) is use Ada.Calendar; use Ada.Calendar.Formatting; use Ada.Calendar.Time_Zones; use Util.Strings.Transforms; use type Ada.Containers.Count_Type; procedure Expect (C : in Character); function Expect (List : in Util.Strings.Vectors.Vector) return Natural; function Parse_Number (Min : in Natural; Max : in Natural) return Natural; procedure Load (List : in out Util.Strings.Vectors.Vector; First : in Natural; Last : in Natural; Prefix : in String; Short : in Boolean; Default : in String_Array); function Parse_Short_Day return Formatting.Day_Name; function Parse_Long_Day return Formatting.Day_Name; function Parse_Short_Month return Month_Number; function Parse_Long_Month return Month_Number; function Check_Match (Value : in String; Upper : in Boolean) return Boolean; procedure Parse_AM_PM (Upper : in Boolean); Pattern_Pos : Positive := Pattern'First; Pos : Natural := Date'First; C : Character; Short_Months : Util.Strings.Vectors.Vector; Long_Months : Util.Strings.Vectors.Vector; Short_Days : Util.Strings.Vectors.Vector; Long_Days : Util.Strings.Vectors.Vector; procedure Expect (C : in Character) is begin if Date (Pos) /= C then raise Constraint_Error with "Invalid date format at" & Natural'Image (Pos); end if; Pos := Pos + 1; end Expect; function Expect (List : in Util.Strings.Vectors.Vector) return Natural is Index : Natural := 0; begin for S of List loop if Pos + S'Length - 1 <= Date'Last and then S = Date (Pos .. Pos + S'Length - 1) then Pos := Pos + S'Length; return Index; end if; Index := Index + 1; end loop; raise Constraint_Error with "Invalid date format at" & Natural'Image (Pos); end Expect; procedure Load (List : in out Util.Strings.Vectors.Vector; First : in Natural; Last : in Natural; Prefix : in String; Short : in Boolean; Default : in String_Array) is Offset : constant Natural := Default'First - First; begin if List.Length = 0 then for I in First .. Last loop declare Name : constant String := Get_Label (Bundle, Prefix, I, Short); begin if Name'Length = 0 then List.Append (Default (I + Offset).all); else List.Append (Name); end if; end; end loop; end if; end Load; function Parse_Short_Day return Formatting.Day_Name is begin Load (Short_Days, 0, 6, DAY_NAME_PREFIX, True, Day_Short_Names); return Formatting.Day_Name'Val (Expect (Short_Days)); end Parse_Short_Day; function Parse_Long_Day return Formatting.Day_Name is begin Load (Long_Days, 0, 6, DAY_NAME_PREFIX, False, Day_Names); return Formatting.Day_Name'Val (Expect (Long_Days)); end Parse_Long_Day; function Parse_Short_Month return Month_Number is begin Load (Short_Months, 1, 12, MONTH_NAME_PREFIX, True, Month_Short_Names); return Month_Number (Expect (Short_Months) + 1); end Parse_Short_Month; function Parse_Long_Month return Month_Number is begin Load (Long_Months, 1, 12, MONTH_NAME_PREFIX, False, Month_Names); return Month_Number (Expect (Long_Months) + 1); end Parse_Long_Month; function Parse_Number (Min : in Natural; Max : in Natural) return Natural is Value : Natural := 0; begin if Date (Pos) < '0' or Date (Pos) > '9' then raise Constraint_Error with "Invalid date format: expecting integer"; end if; while (10 * Value) < Max and then Pos <= Date'Last and then Date (Pos) >= '0' and then Date (Pos) <= '9' loop Value := Value * 10; Value := Value + Character'Pos (Date (Pos)) - Character'Pos ('0'); Pos := Pos + 1; end loop; if Value < Min or Value > Max then raise Constraint_Error with "Invalid date format: out of range"; end if; return Value; end Parse_Number; function Check_Match (Value : in String; Upper : in Boolean) return Boolean is begin if Pos + Value'Length - 1 > Date'Last then return False; elsif Upper then return Date (Pos .. Pos + Value'Length - 1) = Value; else return Date (Pos .. Pos + Value'Length - 1) = To_Lower_Case (Value); end if; end Check_Match; procedure Parse_AM_PM (Upper : in Boolean) is AM : constant String := Bundle.Get (AM_NAME, AM_DEFAULT); begin if Check_Match (AM, Upper) then Pos := Pos + AM'Length; else declare PM : constant String := Bundle.Get (PM_NAME, PM_DEFAULT); begin if Check_Match (PM, Upper) then Pos := Pos + PM'Length; Result.Hour := Result.Hour + 12; else raise Constraint_Error with "Invalid date format: expecting am or pm"; end if; end; end if; end Parse_AM_PM; Century : Integer := -1; Value : Integer; Week_Number : Integer := -1; pragma Unreferenced (Week_Number, Century); begin while Pattern_Pos <= Pattern'Last and Pos <= Date'Last loop C := Pattern (Pattern_Pos); if C = ' ' then Pattern_Pos := Pattern_Pos + 1; while Pos <= Date'Last and then Ada.Characters.Handling.Is_Space (Date (Pos)) loop Pos := Pos + 1; end loop; elsif C /= '%' then Expect (C); Pattern_Pos := Pattern_Pos + 1; else Pattern_Pos := Pattern_Pos + 1; exit when Pattern_Pos > Pattern'Last; C := Pattern (Pattern_Pos); if C = '_' or C = '-' or C = 'E' or C = 'O' or C = '^' then exit when Pattern_Pos = Pattern'Last; Pattern_Pos := Pattern_Pos + 1; C := Pattern (Pattern_Pos); end if; case C is when '%' => Expect ('%'); -- %a The abbreviated weekday name according to the current locale. when 'a' => Result.Day := Parse_Short_Day; -- %A The full weekday name according to the current locale. when 'A' => Result.Day := Parse_Long_Day; -- %b The abbreviated month name according to the current locale. -- %h Equivalent to %b. (SU) when 'b' | 'h' => Result.Month := Parse_Short_Month; -- %B The full month name according to the current locale. when 'B' => Result.Month := Parse_Long_Month; -- %c The preferred date and time representation for the current locale. when 'c' => Parse (Date (Pos .. Date'Last), Bundle.Get (DATE_TIME_LOCALE_NAME, DATE_TIME_DEFAULT_PATTERN), Bundle, Result, Pos); -- %C The century number (year/100) as a 2-digit integer. (SU) when 'C' => Century := 100 * Parse_Number (Min => 1, Max => 99); -- %d The day of the month as a decimal number (range 01 to 31). when 'd' => Result.Month_Day := Day_Number (Parse_Number (Min => 1, Max => 31)); -- %D Equivalent to %m/%d/%y when 'D' => Parse (Date (Pos .. Date'Last), "%m/%d/%y", Bundle, Result, Pos); -- %e Like %d, the day of the month as a decimal number, -- but a leading zero is replaced by a space. (SU) when 'e' => Result.Month := Month_Number (Parse_Number (Min => 1, Max => 31)); -- %F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99) when 'F' => Parse (Date (Pos .. Date'Last), "%Y-%m-%d", Bundle, Result, Pos); -- %G The ISO 8601 week-based year when 'G' => Parse (Date (Pos .. Date'Last), "%YW%W", Bundle, Result, Pos); -- %g Like %G, but without century, that is, -- with a 2-digit year (00-99). (TZ) when 'g' => Parse (Date (Pos .. Date'Last), "%yW%W", Bundle, Result, Pos); -- %H The hour as a decimal number using a 24-hour clock (range 00 to 23). when 'H' => Result.Hour := Formatting.Hour_Number (Parse_Number (Min => 1, Max => 23)); -- %I The hour as a decimal number using a 12-hour clock (range 01 to 12). when 'I' => Result.Hour := Formatting.Hour_Number (Parse_Number (Min => 1, Max => 12)); -- %j The day of the year as a decimal number (range 001 to 366). when 'j' => Value := Parse_Number (Min => 1, Max => 366); -- %k The hour (24-hour clock) as a decimal number (range 0 to 23); when 'k' => Result.Hour := Hour_Number (Parse_Number (Min => 0, Max => 23)); -- %l The hour (12-hour clock) as a decimal number (range 1 to 12); when 'l' => Result.Hour := Parse_Number (Min => 1, Max => 12); -- %m The month as a decimal number (range 01 to 12). when 'm' => Result.Month := Month_Number (Parse_Number (Min => 1, Max => 12)); -- %M The minute as a decimal number (range 00 to 59). when 'M' => Result.Minute := Minute_Number (Parse_Number (Min => 0, Max => 59)); -- %n A newline character. (SU) when 'n' => Expect (ASCII.LF); -- %p Either "AM" or "PM" when 'p' => Parse_AM_PM (Upper => True); -- %P Like %p but in lowercase: "am" or "pm" when 'P' => Parse_AM_PM (Upper => False); -- %r The time in a.m. or p.m. notation. -- In the POSIX locale this is equivalent to %I:%M:%S %p. (SU) when 'r' => Parse (Date (Pos .. Date'Last), "%I:%M:%S %p", Bundle, Result, Pos); -- %R The time in 24-hour notation (%H:%M). when 'R' => Parse (Date (Pos .. Date'Last), "%H:%M", Bundle, Result, Pos); -- %s The number of seconds since the Epoch, that is, -- since 1970-01-01 00:00:00 UTC. (TZ) when 's' => null; -- %S The second as a decimal number (range 00 to 60). when 'S' => Result.Second := Formatting.Second_Number (Parse_Number (Min => 0, Max => 59)); -- %t A tab character. (SU) when 't' => Expect (ASCII.HT); -- %T The time in 24-hour notation (%H:%M:%S). (SU) when 'T' => Parse (Date (Pos .. Date'Last), "%H:%M:%S", Bundle, Result, Pos); -- %u The day of the week as a decimal, range 1 to 7, -- Monday being 1. See also %w. (SU) when 'u' => Result.Day := Day_Name'Val (Parse_Number (Min => 1, Max => 7)); -- %U The week number of the current year as a decimal number, -- range 00 to 53 when 'U' => Week_Number := Parse_Number (Min => 0, Max => 53); -- %V The ISO 8601 week number when 'V' => Week_Number := Parse_Number (Min => 0, Max => 53); -- %w The day of the week as a decimal, range 0 to 6, Sunday being 0. -- See also %u. when 'w' => Value := Parse_Number (Min => 0, Max => 6); if Value = 0 then Result.Day := Sunday; else Result.Day := Day_Name'Val (Value - 1); end if; -- %W The week number of the current year as a decimal number, -- range 00 to 53 when 'W' => Week_Number := Parse_Number (Min => 0, Max => 53); -- %x The preferred date representation for the current locale without -- the time. when 'x' => Parse (Date (Pos .. Date'Last), Bundle.Get (DATE_LOCALE_NAME, DATE_DEFAULT_PATTERN), Bundle, Result, Pos); -- %X The preferred time representation for the current locale without -- the date. when 'X' => Parse (Date (Pos .. Date'Last), Bundle.Get (TIME_LOCALE_NAME, TIME_DEFAULT_PATTERN), Bundle, Result, Pos); -- %y The year as a decimal number without a century (range 00 to 99). when 'y' => Value := Parse_Number (Min => 0, Max => 99); Value := Value + (Natural (Result.Year) / 100) * 100; Result.Year := Year_Number (Value); -- %Y The year as a decimal number including the century. when 'Y' => Result.Year := Parse_Number (Min => 1900, Max => 9999); -- %z The time-zone as hour offset from GMT. when 'z' => if Date (Pos) = '+' then Pos := Pos + 1; Value := Parse_Number (Min => 0, Max => 12); Result.Time_Zone := Time_Offset (Value * 60); Expect (':'); Value := Parse_Number (Min => 0, Max => 59); Result.Time_Zone := Result.Time_Zone + Time_Offset (Value); elsif Date (Pos) = '-' then Pos := Pos + 1; Value := Parse_Number (Min => 0, Max => 12); Result.Time_Zone := -Time_Offset (Value * 60); Expect (':'); Value := Parse_Number (Min => 0, Max => 59); Result.Time_Zone := Result.Time_Zone - Time_Offset (Value); else raise Constraint_Error with "Invalid date format"; end if; -- %Z The timezone or name or abbreviation. when 'Z' => Expect ('U'); Expect ('T'); Expect ('C'); if Date (Pos) = '+' then Pos := Pos + 1; Value := Parse_Number (Min => 0, Max => 12); Result.Time_Zone := Time_Offset (Value * 60); Expect (':'); Value := Parse_Number (Min => 0, Max => 59); Result.Time_Zone := Result.Time_Zone + Time_Offset (Value); elsif Date (Pos) = '-' then Pos := Pos + 1; Value := Parse_Number (Min => 0, Max => 12); Result.Time_Zone := -Time_Offset (Value * 60); Expect (':'); Value := Parse_Number (Min => 0, Max => 59); Result.Time_Zone := Result.Time_Zone - Time_Offset (Value); else Result.Time_Zone := 0; end if; when others => Expect ('%'); Expect (Pattern (Pattern_Pos)); end case; Pattern_Pos := Pattern_Pos + 1; end if; end loop; Last := Pos; if Pattern_Pos <= Pattern'Last then raise Constraint_Error with "Invalid date format: incomplete date"; end if; end Parse; end Util.Dates.Formats;
alloy4fun_models/trainstlt/models/13/vGQFaMi6ZL2bpxv6d.als
Kaixi26/org.alloytools.alloy
0
4867
open main pred idvGQFaMi6ZL2bpxv6d_prop14 { always ( all t:Train | ( one (t.pos.signal :>Green) )implies (t.pos.signal in Signal-Green) ) } pred __repair { idvGQFaMi6ZL2bpxv6d_prop14 } check __repair { idvGQFaMi6ZL2bpxv6d_prop14 <=> prop14o }
Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-4.applescript
LaudateCorpus1/RosettaCodeData
1
3323
<gh_stars>1-10 tell application "Finder" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with "pdf"
1-base/lace/source/text/lace-text.ads
charlie5/lace-alire
1
23432
with ada.Containers, ada.Streams; package lace.Text -- -- Models a string of text characters. -- is pragma Pure; type Item (Capacity : Natural) is private; function Image (Self : in Item) return String; Error : exception; -------------- -- Stock Items -- subtype Item_2 is Item (Capacity => 2); subtype Item_4 is Item (Capacity => 4); subtype Item_8 is Item (Capacity => 8); subtype Item_16 is Item (Capacity => 16); subtype Item_32 is Item (Capacity => 32); subtype Item_64 is Item (Capacity => 64); subtype Item_128 is Item (Capacity => 128); subtype Item_256 is Item (Capacity => 256); subtype Item_512 is Item (Capacity => 512); subtype Item_1k is Item (Capacity => 1024); subtype Item_2k is Item (Capacity => 2 * 1024); subtype Item_4k is Item (Capacity => 4 * 1024); subtype Item_8k is Item (Capacity => 8 * 1024); subtype Item_16k is Item (Capacity => 16 * 1024); subtype Item_32k is Item (Capacity => 32 * 1024); subtype Item_64k is Item (Capacity => 64 * 1024); subtype Item_128k is Item (Capacity => 128 * 1024); subtype Item_256k is Item (Capacity => 256 * 1024); subtype Item_512k is Item (Capacity => 512 * 1024); subtype Item_1m is Item (Capacity => 1024 * 1024); subtype Item_2m is Item (Capacity => 2 * 1024 * 1024); subtype Item_4m is Item (Capacity => 4 * 1024 * 1024); subtype Item_8m is Item (Capacity => 8 * 1024 * 1024); subtype Item_16m is Item (Capacity => 16 * 1024 * 1024); subtype Item_32m is Item (Capacity => 32 * 1024 * 1024); subtype Item_64m is Item (Capacity => 64 * 1024 * 1024); subtype Item_128m is Item (Capacity => 128 * 1024 * 1024); subtype Item_256m is Item (Capacity => 256 * 1024 * 1024); subtype Item_512m is Item (Capacity => 512 * 1024 * 1024); --------------- -- Stock Arrays -- type Items_2 is array (Positive range <>) of aliased Item_2; type Items_4 is array (Positive range <>) of aliased Item_4; type Items_8 is array (Positive range <>) of aliased Item_8; type Items_16 is array (Positive range <>) of aliased Item_16; type Items_32 is array (Positive range <>) of aliased Item_32; type Items_64 is array (Positive range <>) of aliased Item_64; type Items_128 is array (Positive range <>) of aliased Item_128; type Items_256 is array (Positive range <>) of aliased Item_256; type Items_512 is array (Positive range <>) of aliased Item_512; type Items_1k is array (Positive range <>) of aliased Item_1k; type Items_2k is array (Positive range <>) of aliased Item_2k; type Items_4k is array (Positive range <>) of aliased Item_4k; type Items_8k is array (Positive range <>) of aliased Item_8k; type Items_16k is array (Positive range <>) of aliased Item_16k; type Items_32k is array (Positive range <>) of aliased Item_32k; type Items_64k is array (Positive range <>) of aliased Item_64k; type Items_128k is array (Positive range <>) of aliased Item_128k; type Items_256k is array (Positive range <>) of aliased Item_256k; type Items_512k is array (Positive range <>) of aliased Item_512k; type Items_1m is array (Positive range <>) of aliased Item_1m; type Items_2m is array (Positive range <>) of aliased Item_2m; type Items_4m is array (Positive range <>) of aliased Item_4m; type Items_8m is array (Positive range <>) of aliased Item_8m; type Items_16m is array (Positive range <>) of aliased Item_16m; type Items_32m is array (Positive range <>) of aliased Item_32m; type Items_64m is array (Positive range <>) of aliased Item_64m; type Items_128m is array (Positive range <>) of aliased Item_128m; type Items_256m is array (Positive range <>) of aliased Item_256m; type Items_512m is array (Positive range <>) of aliased Item_512m; --------------- -- Construction -- function to_Text (From : in String; Trim : in Boolean := False) return Item; function to_Text (From : in String; Capacity : in Natural; Trim : in Boolean := False) return Item; function "+" (From : in String) return Item; ------------- -- Attributes -- procedure String_is (Self : in out Item; Now : in String); function to_String (Self : in Item) return String; function "+" (Self : in Item) return String renames to_String; function is_Empty (Self : in Item) return Boolean; function Length (Self : in Item) return Natural; function Hashed (Self : in Item) return ada.Containers.Hash_type; overriding function "=" (Left, Right : in Item) return Boolean; function to_Lowercase (Self : in Item) return Item; function mono_Spaced (Self : in Item) return Item; private type Item (Capacity : Natural) is record Length : Natural := 0; Data : String (1 .. Capacity); end record; ---------- -- Streams -- function Item_input (Stream : access ada.Streams.root_Stream_type'Class) return Item; procedure Item_output (Stream : access ada.Streams.root_Stream_type'Class; the_Item : in Item); procedure read (Stream : access ada.Streams.root_Stream_type'Class; Self : out Item); procedure write (Stream : access ada.Streams.root_Stream_type'Class; Self : in Item); for Item'input use Item_input; for Item'output use Item_output; for Item'write use write; for Item'read use read; end lace.Text;
src/spat-gpr_support.ads
yannickmoy/spat
0
492
<gh_stars>0 ------------------------------------------------------------------------------ -- Copyright (C) 2020 by Heisenbug Ltd. (<EMAIL>) -- -- 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. - GNAT project file (.gpr) support. -- ------------------------------------------------------------------------------ limited with SPAT.Strings; limited with GNATCOLL.VFS; package SPAT.GPR_Support is --------------------------------------------------------------------------- -- Get_SPARK_Files -- -- Retrieve all (existing) .spark files from the project. --------------------------------------------------------------------------- function Get_SPARK_Files (GPR_File : GNATCOLL.VFS.Filesystem_String) return Strings.File_Names; end SPAT.GPR_Support;
tasks/arithmetic/dec.asm
yds12/x86-roadmap
15
80760
<gh_stars>10-100 ; This program makes some decrements and returns. global asm_func section .text asm_func: xor rax, rax ; zeroes RAX inc rax ; increments RAX 4 times inc rax inc rax inc rax dec rax ; decrements RAX 2 times dec rax ret
patches/koala/code/disasm/koala_fix_magnifier.asm
fcatrin/a8tools
3
89066
<gh_stars>1-10 ; fix magnifier coordinates calculation when using a joystick org $51F2 nop nop nop nop nop nop nop nop
src/ada/src/services/route_aggregator/route_aggregator.adb
VVCAS-Sean/OpenUxAS
88
4501
<gh_stars>10-100 with Ada.Text_IO; use Ada.Text_IO; package body Route_Aggregator with SPARK_Mode is pragma Unevaluated_Use_Of_Old (Allow); pragma Assertion_Policy (Ignore); -- Lemmas used to factor out reasonning about the redefined model of -- Int64_Formal_Set_Maps ------------------- -- Model_Include -- ------------------- procedure Model_Include (M1, M2 : Int64_Formal_Set_Maps.Formal_Model.M.Map; N1, N2 : Int_Set_Maps_M.Map) -- Lemma: Inclusion of old models implies inclusion of redefined models with Ghost, Global => null, Pre => Same_Mappings (M1, N1) and Same_Mappings (M2, N2) and M1 <= M2, Post => N1 <= N2; procedure Model_Include (M1, M2 : Int64_Formal_Set_Maps.Formal_Model.M.Map; N1, N2 : Int_Set_Maps_M.Map) is begin null; end Model_Include; ----------------------------- -- Lift_From_Keys_To_Model -- ----------------------------- procedure Lift_From_Keys_To_Model (PendingRoute : Int64_Formal_Set_Map) -- Lemma: Lift quantification done on Keys of the pending route map to its -- model. with Ghost, Global => null, Post => (for all Key of Model (PendingRoute) => (Find (Keys (PendingRoute), Key) > 0 and then Int_Set_Maps_K.Get (Keys (PendingRoute), Find (Keys (PendingRoute), Key)) = Key)); procedure Lift_From_Keys_To_Model (PendingRoute : Int64_Formal_Set_Map) is begin null; end Lift_From_Keys_To_Model; -- Subprograms wraping insertion and deletion in m_pendingRoute. They -- restate part of the postcondition of the callee, but also reestablish -- the predicate of Route_Aggregator_State and compute the effect of the -- modification on Plan_To_Route. ----------------------- -- Local subprograms -- ----------------------- procedure Check_All_Route_Plans_PendingAutoReq (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State) with -- General invariants Pre => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans) and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans) and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses) and (for all K in 1 .. Length (State.m_pendingRoute) => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))) -- History invariants and Valid_Events (State.m_routeRequestId) and No_RouteRequest_Lost (State.m_pendingRoute) and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses) and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses), -- General invariants Post => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans) and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans) and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses) and No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses) -- History invariants and History'Old <= History and Valid_Events (State.m_routeRequestId) and No_RouteRequest_Lost (State.m_pendingRoute) and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses) and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses); procedure Check_All_Route_Plans_PendingRoute (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State) with -- General invariants Pre => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans) and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans) and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses) -- History invariants and Valid_Events (State.m_routeRequestId) and No_RouteRequest_Lost (State.m_pendingRoute) and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses) and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses), -- General invariants Post => All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans) and Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans) and Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses) and (for all K in 1 .. Length (State.m_pendingRoute) => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))) -- History invariants and History'Old <= History and Valid_Events (State.m_routeRequestId) and No_RouteRequest_Lost (State.m_pendingRoute) and No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses) and All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses); procedure Delete_PendingRequest (m_pendingRequest : in out Int64_Formal_Set_Map; otherPending : Int64_Formal_Set_Map; m_routeRequestId : Int64; Position : in out Int64_Formal_Set_Maps.Cursor) with Pre => Has_Element (m_pendingRequest, Position) and All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId) and No_Overlaps (Model (m_pendingRequest)) and No_Overlaps (Model (m_pendingRequest), Model (otherPending)), Post => -- Predicate of State All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId) and No_Overlaps (Model (m_pendingRequest)) and No_Overlaps (Model (m_pendingRequest), Model (otherPending)) -- Postcondition copied from Int64_Formal_Set_Maps.Delete and Length (m_pendingRequest) = Length (m_pendingRequest)'Old - 1 and not Int_Set_Maps_M.Has_Key (Model (m_pendingRequest), Key (m_pendingRequest, Position)'Old) and not Int_Set_Maps_P.Has_Key (Positions (m_pendingRequest), Position'Old) and Model (m_pendingRequest) <= Model (m_pendingRequest)'Old and Int_Set_Maps_M.Keys_Included_Except (Model (m_pendingRequest)'Old, Model (m_pendingRequest), Key (m_pendingRequest, Position)'Old) and Int_Set_Maps_K.Range_Equal (Left => Keys (m_pendingRequest)'Old, Right => Keys (m_pendingRequest), Fst => 1, Lst => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old) - 1) and Int_Set_Maps_K.Range_Shifted (Left => Keys (m_pendingRequest), Right => Keys (m_pendingRequest)'Old, Fst => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old), Lst => Length (m_pendingRequest), Offset => 1) and P_Positions_Shifted (Positions (m_pendingRequest), Positions (m_pendingRequest)'Old, Cut => Int_Set_Maps_P.Get (Positions (m_pendingRequest)'Old, Position'Old)) -- Effect on Plan_To_Route and Plan_To_Route (m_pendingRequest) <= Plan_To_Route (m_pendingRequest)'Old and (for all I of Plan_To_Route (m_pendingRequest)'Old => Has_Key (Plan_To_Route (m_pendingRequest), I) or else Get (Plan_To_Route (m_pendingRequest)'Old, I) = Key (m_pendingRequest, Position)'Old); procedure Insert_PendingRequest (m_pendingRequest : in out Int64_Formal_Set_Map; otherPending : Int64_Formal_Set_Map; m_routeRequestId : Int64; RequestID : Int64; PlanRequests : Int64_Formal_Set) with Pre => not Int_Set_Maps_M.Has_Key (Model (m_pendingRequest), RequestID) and Length (m_pendingRequest) < m_pendingRequest.Capacity and All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId) and No_Overlaps (Model (m_pendingRequest)) and No_Overlaps (Model (m_pendingRequest), Model (otherPending)) and (for all Id of PlanRequests => Id <= m_routeRequestId) and (for all R_Id of Model (m_pendingRequest) => (for all E of Int_Set_Maps_M.Get (Model (m_pendingRequest), R_Id) => not Contains (PlanRequests, E))) and (for all R_Id of Model (otherPending) => (for all E of Int_Set_Maps_M.Get (Model (otherPending), R_Id) => not Contains (PlanRequests, E))), Post => -- Predicate of State All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId) and No_Overlaps (Model (m_pendingRequest)) and No_Overlaps (Model (m_pendingRequest), Model (otherPending)) -- Part of the postcondition copied from Int64_Formal_Set_Maps.Insert and Model (m_pendingRequest)'Old <= Model (m_pendingRequest) and Contains (Model (m_pendingRequest), RequestID) and (for all E of Int_Set_Maps_M.Get (Model (m_pendingRequest), RequestID) => Contains (PlanRequests, E)) and (for all E of PlanRequests => Contains (Int_Set_Maps_M.Get (Model (m_pendingRequest), RequestID), E)) and (for all K of Model (m_pendingRequest) => Int_Set_Maps_M.Has_Key (Model (m_pendingRequest)'Old, K) or K = RequestID) -- Effect on Plan_To_Route and Plan_To_Route (m_pendingRequest)'Old <= Plan_To_Route (m_pendingRequest) and (for all I of PlanRequests => Has_Key (Plan_To_Route (m_pendingRequest), I) and then Get (Plan_To_Route (m_pendingRequest), I) = RequestID) and (for all I of Plan_To_Route (m_pendingRequest) => Contains (PlanRequests, I) or Has_Key (Plan_To_Route (m_pendingRequest)'Old, I)); --------------------------- -- Build_Matrix_Requests -- --------------------------- procedure Build_Matrix_Requests (Mailbox : in out Route_Aggregator_Mailbox; Data : Route_Aggregator_Configuration_Data; State : in out Route_Aggregator_State; ReqId : Int64) with SPARK_Mode => Off is sendAirPlanRequest : RPReq_Seq; sendGroundPlanRequest : RPReq_Seq; Empty_Formal_Set : Int64_Formal_Set; begin Insert (State.m_pendingAutoReq, ReqId, Empty_Formal_Set); if Length (Element (State.m_uniqueAutomationRequests, ReqId).EntityList) = 0 then declare AReq : UniqueAutomationRequest := Element (State.m_uniqueAutomationRequests, ReqId); begin AReq.EntityList := Data.m_entityStates; Replace (State.m_uniqueAutomationRequests, ReqId, AReq); end; end if; declare AReq : constant UniqueAutomationRequest := Element (State.m_uniqueAutomationRequests, ReqId); begin For_Each_Vehicle : for VehicleId of AReq.EntityList loop Make_Request : declare StartHeading_Deg : Real32 := 0.0; StartLocation : Location3D; FoundPlanningState : Boolean := False; Vehicle : EntityState; begin for PlanningState of AReq.PlanningStates loop if PlanningState.EntityID = VehicleId then StartLocation := PlanningState.PlanningPosition; StartHeading_Deg := PlanningState.PlanningHeading; FoundPlanningState := True; exit; end if; end loop; if FoundPlanningState or else (for some EntityId of Data.m_entityStates => (EntityId = VehicleId)) then Build_Eligible_Task_Options : declare TaskOptionList : TaskOption_Seq; Found_Elig : Boolean := False; PlanRequest : RoutePlanRequest; Set : Int64_Formal_Set := Element (State.m_pendingAutoReq, ReqId); begin for TaskId of AReq.TaskList loop if Contains (State.m_taskOptions, TaskId) then for Option of Element (State.m_taskOptions, TaskId).Options loop Found_Elig := False; for V of Option.EligibleEntities loop if V = VehicleId then Found_Elig := True; exit; end if; end loop; if Length (Option.EligibleEntities) = 0 or else Found_Elig then TaskOptionList := Add (TaskOptionList, Option); end if; end loop; end if; end loop; PlanRequest.AssociatedTaskID := 0; PlanRequest.IsCostOnlyRequest := False; PlanRequest.OperatingRegion := AReq.OperatingRegion; PlanRequest.VehicleID := VehicleId; State.m_routeRequestId := State.m_routeRequestId + 1; PlanRequest.RequestID := State.m_routeRequestId; Insert (Set, State.m_routeRequestId); Replace (State.m_pendingAutoReq, ReqId, Set); if not FoundPlanningState then Vehicle := ES_Maps.Get (Data.m_entityStatesInfo, VehicleId); StartLocation := Vehicle.Location; StartHeading_Deg := Vehicle.Heading; end if; for Option of TaskOptionList loop declare TOP : constant TaskOptionPair := (VehicleId, 0, 0, Option.TaskID, Option.OptionID); R : RouteConstraints; begin Insert (State.m_routeTaskPairing, State.m_routeId + 1, TOP); R.StartLocation := StartLocation; R.StartHeading := StartHeading_Deg; R.EndLocation := Option.StartLocation; R.EndHeading := Option.StartHeading; R.RouteID := State.m_routeId + 1; PlanRequest.RouteRequests := Add (PlanRequest.RouteRequests, R); State.m_routeId := State.m_routeId + 1; end; end loop; for T1 in TaskOptionList loop for T2 in TaskOptionList loop if T1 /= T2 then declare O1 : constant TaskOption := Get (TaskOptionList, T1); O2 : constant TaskOption := Get (TaskOptionList, T2); TOP : constant TaskOptionPair := (VehicleId, O1.TaskID, O1.OptionID, O2.TaskID, O2.OptionID); R : RouteConstraints; begin Insert (State.m_routeTaskPairing, State.m_routeId + 1, TOP); R.StartLocation := O1.EndLocation; R.StartHeading := O1.EndHeading; R.EndLocation := O2.StartLocation; R.EndHeading := O2.StartHeading; R.RouteID := State.m_routeId + 1; PlanRequest.RouteRequests := Add (PlanRequest.RouteRequests, R); State.m_routeId := State.m_routeId + 1; end; end if; end loop; end loop; if Contains (Data.m_groundVehicles, VehicleId) then sendGroundPlanRequest := Add (sendGroundPlanRequest, PlanRequest); else sendAirPlanRequest := Add (sendAirPlanRequest, PlanRequest); end if; end Build_Eligible_Task_Options; end if; end Make_Request; end loop For_Each_Vehicle; for RPReq of sendAirPlanRequest loop sendLimitedCastMessage (Mailbox, AircraftPathPlanner, RPReq); end loop; for RPReq of sendGroundPlanRequest loop if Data.m_fastPlan then Euclidean_Plan (Data, State.m_routePlanResponses, State.m_routePlans, RPReq); else sendLimitedCastMessage (Mailbox, GroundPathPlanner, RPReq); end if; end loop; if Data.m_fastPlan then Check_All_Route_Plans (Mailbox, State); end if; end; end Build_Matrix_Requests; --------------------------- -- Check_All_Route_Plans -- --------------------------- procedure Check_All_Route_Plans (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State) is begin Check_All_Route_Plans_PendingRoute (Mailbox, State); Check_All_Route_Plans_PendingAutoReq (Mailbox, State); end Check_All_Route_Plans; ------------------------------------------ -- Check_All_Route_Plans_PendingAutoReq -- ------------------------------------------ procedure Check_All_Route_Plans_PendingAutoReq (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State) is i : Int64_Formal_Set_Maps.Cursor := First (State.m_pendingAutoReq); D : Count_Type := 0 with Ghost; -- Number of removed elements begin -- Check pending automation requests while Has_Element (State.m_pendingAutoReq, i) loop pragma Loop_Invariant (Has_Element (State.m_pendingAutoReq, i)); pragma Loop_Invariant (D = Length (State.m_pendingAutoReq)'Loop_Entry - Length (State.m_pendingAutoReq)); pragma Loop_Invariant (Model (State.m_pendingAutoReq) <= Int_Set_Maps_M.Map'(Model (State.m_pendingAutoReq))'Loop_Entry); pragma Loop_Invariant (for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 => (for some L in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 + D => Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq)'Loop_Entry, L))); pragma Loop_Invariant (for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) - 1 => Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K))); pragma Loop_Invariant (for all K in Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) .. Length (State.m_pendingAutoReq) => Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq)'Loop_Entry, K + D)); -- General invariants pragma Loop_Invariant (All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); pragma Loop_Invariant (for all K in 1 .. Length (State.m_pendingRoute) => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))); -- History invariants pragma Loop_Invariant (History'Loop_Entry <= History); pragma Loop_Invariant (Valid_Events (State.m_routeRequestId)); pragma Loop_Invariant (No_RouteRequest_Lost (State.m_pendingRoute)); pragma Loop_Invariant (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); pragma Loop_Invariant (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); declare isFulfilled : constant Boolean := (for all J of Element (State.m_pendingAutoReq, i) => Contains (State.m_routePlanResponses, J)); begin if isFulfilled then SendMatrix (Mailbox, State.m_uniqueAutomationRequests, State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlans, State.m_routeTaskPairing, State.m_routePlanResponses, State.m_taskOptions, Key (State.m_pendingAutoReq, i)); declare Dummy : Int64_Formal_Set_Maps.Cursor := i; UAR_Key : constant Int64 := Key (State.m_pendingAutoReq, i); Pos : constant Count_Type := Int_Set_Maps_P.Get (Positions (State.m_pendingAutoReq), i) with Ghost; begin Next (State.m_pendingAutoReq, i); Delete_PendingRequest (State.m_pendingAutoReq, State.m_pendingRoute, State.m_routeRequestId, Dummy); Delete (State.m_uniqueAutomationRequests, UAR_Key); D := D + 1; pragma Assert (for all K in 1 .. Pos - 1 => Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K))); end; else Next (State.m_pendingAutoReq, i); end if; end; end loop; -- Restablish No_Finished_Request pragma Assert (for all K in 1 .. Length (State.m_pendingRoute) => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))); Lift_From_Keys_To_Model (State.m_pendingRoute); pragma Assert (for all K in 1 .. Length (State.m_pendingAutoReq) => Is_Pending (Model (State.m_pendingAutoReq), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingAutoReq), K))); Lift_From_Keys_To_Model (State.m_pendingAutoReq); end Check_All_Route_Plans_PendingAutoReq; ---------------------------------------- -- Check_All_Route_Plans_PendingRoute -- ---------------------------------------- procedure Check_All_Route_Plans_PendingRoute (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State) is i : Int64_Formal_Set_Maps.Cursor := First (State.m_pendingRoute); D : Count_Type := 0 with Ghost; -- Number of removed elements begin -- check pending route requests while Has_Element (State.m_pendingRoute, i) loop pragma Loop_Invariant (Has_Element (State.m_pendingRoute, i)); pragma Loop_Invariant (D = Length (State.m_pendingRoute)'Loop_Entry - Length (State.m_pendingRoute)); pragma Loop_Invariant (Model (State.m_pendingRoute) <= Int_Set_Maps_M.Map'(Model (State.m_pendingRoute))'Loop_Entry); pragma Loop_Invariant (for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 => (for some L in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 + D => Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingRoute)'Loop_Entry, L))); pragma Loop_Invariant (for all K in 1 .. Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) - 1 => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))); pragma Loop_Invariant (for all K in Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) .. Length (State.m_pendingRoute) => Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K) = Int_Set_Maps_K.Get (Keys (State.m_pendingRoute)'Loop_Entry, K + D)); -- General invariants pragma Loop_Invariant (All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); -- History invariants pragma Loop_Invariant (History'Loop_Entry <= History); pragma Loop_Invariant (Valid_Events (State.m_routeRequestId)); pragma Loop_Invariant (No_RouteRequest_Lost (State.m_pendingRoute)); pragma Loop_Invariant (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); pragma Loop_Invariant (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); declare isFulfilled : constant Boolean := (for all J of Element (State.m_pendingRoute, i) => Contains (State.m_routePlanResponses, J)); begin if isFulfilled then SendRouteResponse (Mailbox, State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses, State.m_routePlans, Key (State.m_pendingRoute, i)); declare Dummy : Int64_Formal_Set_Maps.Cursor := i; Pos : constant Count_Type := Int_Set_Maps_P.Get (Positions (State.m_pendingRoute), i) with Ghost; begin Next (State.m_pendingRoute, i); Delete_PendingRequest (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routeRequestId, Dummy); D := D + 1; pragma Assert (for all K in 1 .. Pos - 1 => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))); end; pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); else Next (State.m_pendingRoute, i); end if; end; end loop; pragma Assert (for all K in 1 .. Length (State.m_pendingRoute) => Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Int_Set_Maps_K.Get (Keys (State.m_pendingRoute), K))); end Check_All_Route_Plans_PendingRoute; ------------------------------------- -- Check_All_Task_Options_Received -- ------------------------------------- procedure Check_All_Task_Options_Received (Mailbox : in out Route_Aggregator_Mailbox; Data : Route_Aggregator_Configuration_Data; State : in out Route_Aggregator_State) with SPARK_Mode => Off is C : UAR_Maps.Cursor := First (State.m_uniqueAutomationRequests); begin while Has_Element (State.m_uniqueAutomationRequests, C) loop declare Areq : constant UniqueAutomationRequest := Element (State.m_uniqueAutomationRequests, C); AllReceived : constant Boolean := (for all TaskId of Areq.TaskList => Contains (State.m_taskOptions, TaskId)); begin if AllReceived then Build_Matrix_Requests (Mailbox, Data, State, Key (State.m_uniqueAutomationRequests, C)); end if; end; Next (State.m_uniqueAutomationRequests, C); end loop; end Check_All_Task_Options_Received; --------------------------- -- Delete_PendingRequest -- --------------------------- procedure Delete_PendingRequest (m_pendingRequest : in out Int64_Formal_Set_Map; otherPending : Int64_Formal_Set_Map; m_routeRequestId : Int64; Position : in out Int64_Formal_Set_Maps.Cursor) is pragma Unreferenced (otherPending, m_routeRequestId); Old_pendingRoute_M : constant Int64_Formal_Set_Maps.Formal_Model.M.Map := Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest) with Ghost; Old_pendingRoute : constant Int_Set_Maps_M.Map := Model (m_pendingRequest) with Ghost; begin Delete (m_pendingRequest, Position); -- Establish the effect on the redefined Model of maps of formal sets Model_Include (Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest), Old_pendingRoute_M, Model (m_pendingRequest), Old_pendingRoute); end Delete_PendingRequest; -------------------- -- Euclidean_Plan -- -------------------- procedure Euclidean_Plan (Data : Route_Aggregator_Configuration_Data; routePlanResponses : in out Int64_RouteResponse_Map; routePlans : in out Int64_IdPlanPair_Map; Request : RoutePlanRequest) is pragma Unreferenced (Data, routePlans, routePlanResponses, Request); -- -- UxAS::common::utilities::CUnitConversions flatEarth; -- FlatEarth : Conversions.Unit_Converter; -- -- int64_t regionId = request->getOperatingRegion(); -- RegionId : Int64 := Request.OperatingRegion; -- -- int64_t vehicleId = request->getVehicleID(); -- VehicleId : Int64 := Request.VehicleID; -- -- int64_t taskId = request->getAssociatedTaskID(); -- TaskId : Int64 := Request.AssociatedTaskID; -- -- double speed = 1.0; // default if no speed available -- Speed : Real64 := 1.0; begin raise Program_Error with "Euclidean_Plan is unimplemented"; -- if (m_entityConfigurations.find(vehicleId) != m_entityConfigurations.end()) -- { -- double speed = m_entityConfigurations[vehicleId]->getNominalSpeed(); -- if (speed < 1e-2) -- { -- speed = 1.0; // default to 1 if too small for division -- } -- } -- auto response = std::shared_ptr<UxAS::messages::route::RoutePlanResponse>(new UxAS::messages::route::RoutePlanResponse); -- response->setAssociatedTaskID(taskId); -- response->setOperatingRegion(regionId); -- response->setVehicleID(vehicleId); -- response->setResponseID(request->getRequestID()); -- -- for (size_t k = 0; k < request->getRouteRequests().size(); k++) -- { -- UxAS::messages::route::RouteConstraints* routeRequest = request->getRouteRequests().at(k); -- int64_t routeId = routeRequest->getRouteID(); -- VisiLibity::Point startPt, endPt; -- double north, east; -- -- UxAS::messages::route::RoutePlan* plan = new UxAS::messages::route::RoutePlan; -- plan->setRouteID(routeId); -- -- flatEarth.ConvertLatLong_degToNorthEast_m(routeRequest->getStartLocation()->getLatitude(), routeRequest->getStartLocation()->getLongitude(), north, east); -- startPt.set_x(east); -- startPt.set_y(north); -- -- flatEarth.ConvertLatLong_degToNorthEast_m(routeRequest->getEndLocation()->getLatitude(), routeRequest->getEndLocation()->getLongitude(), north, east); -- endPt.set_x(east); -- endPt.set_y(north); -- -- double linedist = VisiLibity::distance(startPt, endPt); -- plan->setRouteCost(linedist / speed * 1000); // milliseconds to arrive -- m_routePlans[routeId] = std::make_pair(request->getRequestID(), std::shared_ptr<UxAS::messages::route::RoutePlan>(plan)); -- } -- m_routePlanResponses[response->getResponseID()] = response; end Euclidean_Plan; -------------------------------- -- Handle_Route_Plan_Response -- -------------------------------- procedure Handle_Route_Plan_Response (Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State; Response : RoutePlanResponse) is begin pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History"); History := Add (History, (Kind => Receive_PlanResponse, Id => Response.ResponseID)); pragma Assert (No_RouteRequest_Lost (State.m_pendingRoute)); pragma Assume (Length (State.m_routePlanResponses) < State.m_routePlanResponses.Capacity, "We have some room for a new plan response"); Insert (State.m_routePlanResponses, Response.ResponseID, Response); pragma Assert (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); pragma Assert (Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)); for p in 1 .. Last (Response.RouteResponses) loop -- All plans are registered up to p pragma Loop_Invariant (for all RP of Model (State.m_routePlanResponses) => (if RP /= Response.ResponseID then (for all Pl of Element (State.m_routePlanResponses, RP).RouteResponses => Contains (State.m_routePlans, Pl.RouteID) and then Element (State.m_routePlans, Pl.RouteID).Id = RP))); pragma Loop_Invariant (for all K in 1 .. p - 1 => Contains (State.m_routePlans, Get (Response.RouteResponses, K).RouteID) and then Element (State.m_routePlans, Get (Response.RouteResponses, K).RouteID).Id = Response.ResponseID); pragma Loop_Invariant (for all K in p .. Last (Response.RouteResponses) => not Contains (State.m_routePlans, Get (Response.RouteResponses, K).RouteID)); -- Invariants pragma Loop_Invariant (Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)); pragma Assume (Length (State.m_routePlans) < State.m_routePlans.Capacity, "We have enough room for all route plans"); declare ID : constant Int64 := Get (Response.RouteResponses, p).RouteID; Plan : constant RoutePlan := Get (Response.RouteResponses, p); begin Insert (State.m_routePlans, ID, IdPlanPair'(Id => Response.ResponseID, Plan => Plan, Cost => Get (Response.RouteResponses, p).RouteCost)); end; pragma Assert (Contains (Element (State.m_routePlanResponses, Response.ResponseID).RouteResponses, Get (Response.RouteResponses, p).RouteID)); end loop; pragma Assert (No_RouteRequest_Lost (State.m_pendingRoute)); pragma Assert (for all Pl of Element (State.m_routePlanResponses, Response.ResponseID).RouteResponses => Contains (State.m_routePlans, Pl.RouteID) and then Element (State.m_routePlans, Pl.RouteID).Id = Response.ResponseID); pragma Assert (for all RP of Model (State.m_routePlanResponses) => (for all Pl of Element (State.m_routePlanResponses, RP).RouteResponses => Contains (State.m_routePlans, Pl.RouteID) and then Element (State.m_routePlans, Pl.RouteID).Id = RP)); Check_All_Route_Plans (Mailbox, State); end Handle_Route_Plan_Response; -------------------------- -- Handle_Route_Request -- -------------------------- procedure Handle_Route_Request (Data : Route_Aggregator_Configuration_Data; Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State; Request : RouteRequest) is use all type History_Type; Vehicle_Ids : Int64_Seq := Request.VehicleID; PlanRequests : Int64_Formal_Set; begin pragma Assert (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History"); History := Add (History, (Kind => Receive_RouteRequest, Id => Request.RequestID)); pragma Assert (for all Pos in Event_Sequences.First .. Last (History) - 1 => (if Get (History, Pos).Kind = Receive_PlanResponse and Has_Key (Plan_To_Route (State.m_pendingRoute), Get (History, Pos).Id) then Contains (State.m_routePlanResponses, Get (History, Pos).Id))); pragma Assert (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); --------------------------------------------------------------------------------------------------------------- -- this doesn't match the C++ exactly, because it doesn't put the new vehicle -- ids into the message parameter (which is "by reference" via pointer in C++) -- but that seems to be OK because only EuclidianPlan would use it, apparently if Length (Vehicle_Ids) = 0 then Vehicle_Ids := Data.m_entityStates; end if; --------------------------------------------------------------------------------------------------------------- -- We only have route plan responses with Ids smaller than State.m_routeRequestId pragma Assert (for all K of Model (State.m_routePlanResponses) => K <= State.m_routeRequestId); pragma Assert (for all E of History => (if E.Kind = Receive_PlanResponse then E.Id <= State.m_routeRequestId)); for K in 1 .. Last (Vehicle_Ids) loop -- We are only adding to planrequests new request ids pragma Loop_Invariant (State.m_routeRequestId'Loop_Entry <= State.m_routeRequestId); pragma Loop_Invariant (for all Id of Model (PlanRequests) => Id > State.m_routeRequestId'Loop_Entry and Id <= State.m_routeRequestId); pragma Loop_Invariant (for all Id of Model (State.m_pendingRoute) => (for all K of Int_Set_Maps_M.Get (Model (State.m_pendingRoute), Id) => K <= State.m_routeRequestId'Loop_Entry)); pragma Loop_Invariant (Length (PlanRequests) <= Count_Type (K - 1)); -- If fast planning is used, we may already have some responses for the -- new plan requests. pragma Loop_Invariant (for all K of Model (State.m_routePlanResponses) => Contains (Model (State.m_routePlanResponses)'Loop_Entry, K) or else (Data.m_fastPlan and then Contains (PlanRequests, K))); -- General Invariants pragma Loop_Invariant (All_Plans_Registered (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (Only_Pending_Plans (State.m_routePlanResponses, State.m_routePlans)); pragma Loop_Invariant (No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); -- Update of the history, it may contain new plan requests pragma Loop_Invariant (History'Loop_Entry <= History); pragma Loop_Invariant (for all I in 1 .. Last (History) => (if I > Last (History)'Loop_Entry then Get (History, I).Kind = Send_PlanRequest)); -- History Invariants pragma Loop_Invariant (Valid_Events (State.m_routeRequestId)); pragma Loop_Invariant (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); pragma Loop_Invariant (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); pragma Loop_Invariant (for all Id of Model (PlanRequests) => PlanRequest_Processed (State.m_routePlanResponses, Id)); declare Vehicle_Id : Int64 renames Get (Vehicle_Ids, K); -- create a new route plan request pragma Assume (State.m_routeRequestId < Int64'Last, "The request ID does not overflow"); planRequest : constant RoutePlanRequest := (AssociatedTaskID => Request.AssociatedTaskID, IsCostOnlyRequest => Request.IsCostOnlyRequest, OperatingRegion => Request.OperatingRegion, VehicleID => Vehicle_Id, RequestID => State.m_routeRequestId + 1, RouteRequests => Request.RouteRequests); begin State.m_routeRequestId := State.m_routeRequestId + 1; pragma Assume (Length (PlanRequests) < PlanRequests.Capacity, "We have enough room for all vehicles in planRequests"); Insert (PlanRequests, planRequest.RequestID); if Contains (Data.m_groundVehicles, Vehicle_Id) then if Data.m_fastPlan then -- short-circuit and just plan with straight line planner Euclidean_Plan (Data, State.m_routePlanResponses, State.m_routePlans, planRequest); else -- send externally sendLimitedCastMessage (Mailbox, GroundPathPlanner, planRequest); pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History"); History := Add (History, (Kind => Send_PlanRequest, Id => planRequest.RequestID)); pragma Assert (PlanRequest_Sent (planRequest.RequestID)); end if; else pragma Assert (Contains (Data.m_airVehicles, Vehicle_Id) or else Contains (Data.m_surfaceVehicles, Vehicle_Id)); -- send to aircraft planner sendLimitedCastMessage (Mailbox, AircraftPathPlanner, planRequest); pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History"); History := Add (History, (Kind => Send_PlanRequest, Id => planRequest.RequestID)); pragma Assert (PlanRequest_Sent (planRequest.RequestID)); end if; end; pragma Assert (for all Id of Model (PlanRequests) => PlanRequest_Processed (State.m_routePlanResponses, Id)); pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); end loop; -- Restate part of the loop invariants after the loop pragma Assert (for all E of History => (if E.Kind = Receive_PlanResponse then not Contains (PlanRequests, E.Id))); pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); pragma Assert (No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); pragma Assert (for all R_Id of Model (State.m_pendingRoute) => (for all E of Int_Set_Maps_M.Get (Model (State.m_pendingRoute), R_Id) => not Contains (PlanRequests, E))); pragma Assume (Length (State.m_pendingRoute) < State.m_pendingRoute.Capacity, "We have enough room for a new pending route request"); Insert_PendingRequest (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routeRequestId, Request.RequestID, PlanRequests); -- System invariants have been reestablished pragma Assert (All_Pending_Plans_Sent (State.m_pendingRoute, State.m_routePlanResponses)); pragma Assert (Valid_Plan_Responses (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); pragma Assert (No_PlanResponse_Lost (State.m_pendingRoute, State.m_routePlanResponses)); -- if fast planning, then all routes should be complete; kick off response if Data.m_fastPlan then Check_All_Route_Plans (Mailbox, State); else pragma Assert (Is_Pending (Model (State.m_pendingRoute), Model (State.m_routePlanResponses), Request.RequestID)); pragma Assert (No_Finished_Request (State.m_pendingRoute, State.m_pendingAutoReq, State.m_routePlanResponses)); end if; end Handle_Route_Request; ------------------------------ -- Handle_Task_Plan_Options -- ------------------------------ procedure Handle_Task_Plan_Options (Mailbox : in out Route_Aggregator_Mailbox; Data : Route_Aggregator_Configuration_Data; State : in out Route_Aggregator_State; Options : TaskPlanOptions) with SPARK_Mode => Off is Id : constant Int64 := Options.TaskID; begin Insert (State.m_taskOptions, Id, Options); Check_All_Task_Options_Received (Mailbox, Data, State); end Handle_Task_Plan_Options; -------------------------------------- -- Handle_Unique_Automation_Request -- -------------------------------------- procedure Handle_Unique_Automation_Request (Data : Route_Aggregator_Configuration_Data; Mailbox : in out Route_Aggregator_Mailbox; State : in out Route_Aggregator_State; Areq : UniqueAutomationRequest) is begin Insert (State.m_uniqueAutomationRequests, State.m_autoRequestId + 1, Areq); State.m_autoRequestId := State.m_autoRequestId + 1; Check_All_Task_Options_Received (Mailbox, Data, State); end Handle_Unique_Automation_Request; --------------------------- -- Insert_PendingRequest -- --------------------------- procedure Insert_PendingRequest (m_pendingRequest : in out Int64_Formal_Set_Map; otherPending : Int64_Formal_Set_Map; m_routeRequestId : Int64; RequestID : Int64; PlanRequests : Int64_Formal_Set) is pragma Unreferenced (otherPending); Old_pendingRequest : constant Int_Set_Maps_M.Map := Model (m_pendingRequest) with Ghost; Old_pendingRequest_M : constant Int64_Formal_Set_Maps.Formal_Model.M.Map := Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest) with Ghost; begin Insert (m_pendingRequest, RequestID, PlanRequests); -- Establish the effect on the redefined Model of maps of formal sets Model_Include (Old_pendingRequest_M, Int64_Formal_Set_Maps.Formal_Model.Model (m_pendingRequest), Old_pendingRequest, Model (m_pendingRequest)); pragma Assert (No_Overlaps (Model (m_pendingRequest))); pragma Assert (All_Pending_Requests_Seen (Model (m_pendingRequest), m_routeRequestId)); end Insert_PendingRequest; -- Model functions used in contracts ----------- -- Model -- ----------- function Model (M : Int64_Formal_Set_Map) return Int_Set_Maps_M.Map is function Model (S : Int64_Formal_Set) return Int64_Set with Post => (for all E of Model'Result => Contains (S, E)) and (for all E of S => Contains (Model'Result, E)); function Model (S : Int64_Formal_Set) return Int64_Set is Res : Int64_Set; begin for C in S loop pragma Loop_Variant (Increases => Int_Set_P.Get (Positions (S), C)); pragma Loop_Invariant (Length (Res) = Int_Set_P.Get (Positions (S), C) - 1); pragma Loop_Invariant (for all E of Res => Contains (S, E)); pragma Loop_Invariant (for all K in 1 .. Int_Set_P.Get (Positions (S), C) - 1 => Contains (Res, Int_Set_E.Get (Elements (S), K))); pragma Loop_Invariant (for all K in Int_Set_P.Get (Positions (S), C) .. Length (S) => not Contains (Res, Int_Set_E.Get (Elements (S), K))); Res := Add (Res, Element (S, C)); end loop; return Res; end Model; Res : Int_Set_Maps_M.Map; begin for C in M loop pragma Loop_Variant (Increases => Int_Set_Maps_P.Get (Positions (M), C)); pragma Loop_Invariant (Int_Set_Maps_M.Length (Res) = Int_Set_Maps_P.Get (Positions (M), C) - 1); pragma Loop_Invariant (for all I of Res => Contains (M, I)); pragma Loop_Invariant (for all I of Res => (for all E of Int_Set_Maps_M.Get (Res, I) => Contains (Element (M, I), E))); pragma Loop_Invariant (for all I of Res => (for all E of Element (M, I) => Contains (Int_Set_Maps_M.Get (Res, I), E))); pragma Loop_Invariant (for all K in 1 .. Int_Set_Maps_P.Get (Positions (M), C) - 1 => Int_Set_Maps_M.Has_Key (Res, Int_Set_Maps_K.Get (Keys (M), K))); pragma Loop_Invariant (for all K in Int_Set_Maps_P.Get (Positions (M), C) .. Length (M) => not Int_Set_Maps_M.Has_Key (Res, Int_Set_Maps_K.Get (Keys (M), K))); Res := Int_Set_Maps_M.Add (Res, Key (M, C), Model (Element (M, C))); end loop; return Res; end Model; ---------------- -- SendMatrix -- ---------------- procedure SendMatrix (Mailbox : in out Route_Aggregator_Mailbox; m_uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map; m_pendingRoute : Int64_Formal_Set_Map; m_pendingAutoReq : Int64_Formal_Set_Map; m_routePlans : in out Int64_IdPlanPair_Map; m_routeTaskPairing : in out Int64_TaskOptionPair_Map; m_routePlanResponses : in out Int64_RouteResponse_Map; m_taskOptions : in out Int64_TaskPlanOptions_Map; autoKey : Int64) is areq : constant UniqueAutomationRequest := Element (m_uniqueAutomationRequests, autoKey); matrix : AssignmentCostMatrix; pendingRequests : Int64_Formal_Set renames Element (m_pendingAutoReq, autoKey); Old_routePlanResponses : constant Int64_RouteResponse_Map := m_routePlanResponses with Ghost; begin matrix.CorrespondingAutomationRequestID := areq.RequestID; matrix.OperatingRegion := areq.OperatingRegion; matrix.TaskList := areq.TaskList; for Cu in pendingRequests loop pragma Loop_Invariant (for all I in 1 .. Int_Set_P.Get (Positions (pendingRequests), Cu) - 1 => not Contains (m_routePlanResponses, Int_Set_E.Get (Elements (pendingRequests), I))); pragma Loop_Invariant (for all I in Int_Set_P.Get (Positions (pendingRequests), Cu) .. Length (pendingRequests) => Contains (m_routePlanResponses, Int_Set_E.Get (Elements (pendingRequests), I))); pragma Loop_Invariant (for all Id of Old_routePlanResponses => (if not Contains (pendingRequests, Id) then Contains (m_routePlanResponses, Id))); pragma Loop_Invariant (for all Id of Model (m_routePlanResponses) => Contains (Old_routePlanResponses, Id)); -- Invariants pragma Loop_Invariant (Valid_Plan_Responses (m_pendingRoute, m_pendingAutoReq, m_routePlanResponses)); pragma Loop_Invariant (All_Plans_Registered (m_routePlanResponses, m_routePlans)); pragma Loop_Invariant (Only_Pending_Plans (m_routePlanResponses, m_routePlans)); -- History invariants pragma Loop_Invariant (No_RouteRequest_Lost (m_pendingRoute)); pragma Loop_Invariant (No_PlanResponse_Lost (m_pendingRoute, m_routePlanResponses)); pragma Loop_Invariant (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses)); declare rId : constant Int64 := Element (pendingRequests, Cu); pragma Assert (Contains (m_routePlanResponses, rId)); begin declare plan : Int64_RouteResponse_Maps.Cursor := Find (m_routePlanResponses, rId); -- NB. The if statement checking whether rId is in -- routePlanResponses was removed as SendRouteResponse is only -- called when all plan responses have been received. pragma Assert (Has_Element (m_routePlanResponses, plan)); resps : RP_Seq renames Element (m_routePlanResponses, plan).RouteResponses; begin -- delete all individual routes from storage for i in 1 .. Last (resps) loop -- We have removed all elements of resps from routePlans -- up to i. pragma Loop_Invariant (for all RP of Model (m_routePlanResponses) => (if RP /= rId then (for all Pl of Element (m_routePlanResponses, RP).RouteResponses => Contains (m_routePlans, Pl.RouteID) and then Element (m_routePlans, Pl.RouteID).Id = RP))); pragma Loop_Invariant (Only_Pending_Plans (m_routePlanResponses, m_routePlans)); pragma Loop_Invariant (for all Pl of Model (m_routePlans) => (if Element (m_routePlans, Pl).Id = rId then (for some K in i .. Last (resps) => Get (resps, K).RouteID = Pl))); pragma Loop_Invariant (for all K in i .. Last (resps) => Contains (m_routePlans, Get (resps, K).RouteID) and then Element (m_routePlans, Get (resps, K).RouteID).Id = rId); if Contains (m_routeTaskPairing, Get (resps, i).RouteID) then declare routeplan : constant IdPlanPair := Element (m_routePlans, Get (resps, i).RouteID); taskpair : constant TaskOptionPair := Element (m_routeTaskPairing, Get (resps, i).RouteID); toc : TaskOptionCost; begin if routeplan.Cost < 0 then Put_Line ("Route not found: V[" & taskpair.vehicleId'Image & "](" & taskpair.prevTaskId'Image & "," & taskpair.prevTaskOption'Image & ")-(" & taskpair.taskId'Image & "," & taskpair.taskOption'Image & ")"); end if; toc.DestinationTaskID := taskpair.taskId; toc.DestinationTaskOption := taskpair.taskOption; toc.InitialTaskID := taskpair.prevTaskId; toc.InitialTaskOption := taskpair.prevTaskOption; toc.TimeToGo := routeplan.Cost; toc.VehicleID := taskpair.vehicleId; pragma Assume (Length (matrix.CostMatrix) < Count_Type'Last, "we still have room in the matrix"); matrix.CostMatrix := Add (matrix.CostMatrix, toc); end; Delete (m_routeTaskPairing, Get (resps, i).RouteID); end if; -- We only delete plans associated to rId pragma Assert (Element (m_routePlans, Get (resps, i).RouteID).Id = rId); Delete (m_routePlans, Get (resps, i).RouteID); end loop; pragma Assert (for all Pl of Model (m_routePlans) => Element (m_routePlans, Pl).Id /= rId); pragma Assert (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses)); pragma Assert (No_Overlaps (Model (m_pendingRoute), Model (m_pendingAutoReq))); pragma Assert (for all Id of Plan_To_Route (m_pendingRoute) => Id /= Key (m_routePlanResponses, plan)); Delete (m_routePlanResponses, plan); pragma Assert (All_Pending_Plans_Sent (m_pendingRoute, m_routePlanResponses)); pragma Assert (Only_Pending_Plans (m_routePlanResponses, m_routePlans)); end; end; end loop; sendBroadcastMessage (Mailbox, matrix); Clear (m_taskOptions); end SendMatrix; ----------------------- -- SendRouteResponse -- ----------------------- procedure SendRouteResponse (Mailbox : in out Route_Aggregator_Mailbox; pendingRoute : Int64_Formal_Set_Map; pendingAutoReq : Int64_Formal_Set_Map; routePlanResponses : in out Int64_RouteResponse_Map; routePlans : in out Int64_IdPlanPair_Map; routeKey : Int64) is Response : RouteResponse; PlanResponses : Int64_Formal_Set renames Element (pendingRoute, routeKey); Old_routePlanResponses : constant RR_Maps_M.Map := Model (routePlanResponses) with Ghost; begin Response.ResponseID := routeKey; for Cu in PlanResponses loop -- Number of elements added to response.Routes pragma Loop_Invariant (Length (Response.Routes) < Int_Set_P.Get (Positions (PlanResponses), Cu)); -- We have removed all elements of PlanResponses from routePlanResponses -- up to Cu. pragma Loop_Invariant (for all I in 1 .. Int_Set_P.Get (Positions (PlanResponses), Cu) - 1 => not Contains (routePlanResponses, Int_Set_E.Get (Elements (PlanResponses), I))); pragma Loop_Invariant (for all I in Int_Set_P.Get (Positions (PlanResponses), Cu) .. Length (PlanResponses) => Contains (routePlanResponses, Int_Set_E.Get (Elements (PlanResponses), I))); pragma Loop_Invariant (for all Id of Old_routePlanResponses => (if not Contains (PlanResponses, Id) then Contains (routePlanResponses, Id))); pragma Loop_Invariant (for all Id of Model (routePlanResponses) => Contains (Old_routePlanResponses, Id)); -- Invariants pragma Loop_Invariant (Valid_Plan_Responses (pendingRoute, pendingAutoReq, routePlanResponses)); pragma Loop_Invariant (All_Plans_Registered (routePlanResponses, routePlans)); pragma Loop_Invariant (Only_Pending_Plans (routePlanResponses, routePlans)); -- History invariants: -- We have only removed responses associated to routeKey pragma Loop_Invariant (for all Id of Plan_To_Route (pendingRoute) => (if Get (Plan_To_Route (pendingRoute), Id) /= routeKey then Contains (routePlanResponses, Id) or else PlanRequest_Sent (Id))); pragma Loop_Invariant (for all E of History => (if E.Kind = Receive_PlanResponse and then Has_Key (Plan_To_Route (pendingRoute), E.Id) and then Get (Plan_To_Route (pendingRoute), E.Id) /= routeKey then Contains (routePlanResponses, E.Id))); declare rId : Int64 renames Element (PlanResponses, Cu); begin declare plan : Int64_RouteResponse_Maps.Cursor := Find (routePlanResponses, rId); -- NB. The if statement checking whether rId is in -- routePlanResponses was removed as SendRouteResponse is only -- called when all plan responses have been received. pragma Assert (Has_Element (routePlanResponses, plan)); resps : RP_Seq renames Element (routePlanResponses, plan).RouteResponses; begin Response.Routes := Add (Response.Routes, Element (routePlanResponses, plan)); -- delete all individual routes from storage for i in 1 .. Last (resps) loop -- We have removed all elements of resps from routePlans -- up to i. pragma Loop_Invariant (for all RP of Model (routePlanResponses) => (if RP /= rId then (for all Pl of Element (routePlanResponses, RP).RouteResponses => Contains (routePlans, Pl.RouteID) and then Element (routePlans, Pl.RouteID).Id = RP))); pragma Loop_Invariant (Only_Pending_Plans (routePlanResponses, routePlans)); pragma Loop_Invariant (for all Pl of Model (routePlans) => (if Element (routePlans, Pl).Id = rId then (for some K in i .. Last (resps) => Get (resps, K).RouteID = Pl))); pragma Loop_Invariant (for all K in i .. Last (resps) => Contains (routePlans, Get (resps, K).RouteID) and then Element (routePlans, Get (resps, K).RouteID).Id = rId); -- We only delete plans associated to rId pragma Assert (Element (routePlans, Get (resps, i).RouteID).Id = rId); Delete (routePlans, Get (resps, i).RouteID); end loop; pragma Assert (Only_Pending_Plans (routePlanResponses, routePlans)); pragma Assert (plan = Find (routePlanResponses, rId)); Delete (routePlanResponses, plan); end; end; end loop; pragma Assert (All_Plans_Registered (routePlanResponses, routePlans)); pragma Assert (for all Id of Plan_To_Route (pendingRoute) => (if Get (Plan_To_Route (pendingRoute), Id) /= routeKey then Contains (routePlanResponses, Id) or else PlanRequest_Sent (Id))); -- send the results of the query sendBroadcastMessage (Mailbox, Response); pragma Assume (Length (History) < Count_Type'Last, "We still have room for a new event in History"); History := Add (History, (Kind => Send_RouteResponse, Id => Response.ResponseID)); end SendRouteResponse; ----------------- -- Plan_To_Route -- ----------------- function Plan_To_Route (pendingRoute : Int64_Formal_Set_Map) return Int64_Map is Res : Int64_Map; begin for C in pendingRoute loop pragma Loop_Variant (Increases => Int_Set_Maps_P.Get (Positions (pendingRoute), C)); pragma Loop_Invariant (for all I of Res => Int_Set_Maps_M.Has_Key (Model (pendingRoute), Get (Res, I)) and then Contains (Int_Set_Maps_M.Get (Model (pendingRoute), Get (Res, I)), I)); pragma Loop_Invariant (for all J in 1 .. Int_Set_Maps_P.Get (Positions (pendingRoute), C) - 1 => (for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) => Has_Key (Res, K) and then Get (Res, K) = Int_Set_Maps_K.Get (Keys (pendingRoute), J))); pragma Loop_Invariant (for all J in Int_Set_Maps_P.Get (Positions (pendingRoute), C) .. Length (pendingRoute) => (for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) => not Has_Key (Res, K))); declare routePlans : Int64_Formal_Set renames Element (pendingRoute, C); begin for C2 in routePlans loop pragma Loop_Variant (Increases => Int_Set_P.Get (Positions (routePlans), C2)); pragma Loop_Invariant (for all I of Res => Int_Set_Maps_M.Has_Key (Model (pendingRoute), Get (Res, I)) and then Contains (Int_Set_Maps_M.Get (Model (pendingRoute), Get (Res, I)), I)); pragma Loop_Invariant (for all J in 1 .. Int_Set_Maps_P.Get (Positions (pendingRoute), C) - 1 => (for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) => Has_Key (Res, K) and then Get (Res, K) = Int_Set_Maps_K.Get (Keys (pendingRoute), J))); pragma Loop_Invariant (for all J in Int_Set_Maps_P.Get (Positions (pendingRoute), C) + 1 .. Length (pendingRoute) => (for all K of Int_Set_Maps_M.Get (Model (pendingRoute), Int_Set_Maps_K.Get (Keys (pendingRoute), J)) => not Has_Key (Res, K))); pragma Loop_Invariant (for all J in 1 .. Int_Set_P.Get (Positions (routePlans), C2) - 1 => Has_Key (Res, Int_Set_E.Get (Elements (routePlans), J)) and then Get (Res, Int_Set_E.Get (Elements (routePlans), J)) = Key (pendingRoute, C)); pragma Loop_Invariant (for all J in Int_Set_P.Get (Positions (routePlans), C2) .. Length (routePlans) => not Has_Key (Res, Int_Set_E.Get (Elements (routePlans), J))); pragma Assume (Length (Res) < Count_Type'Last, "We have less than Count_Type'Last pending plan requests in total"); Res := Add (Res, Element (routePlans, C2), Key (pendingRoute, C)); end loop; end; end loop; return Res; end Plan_To_Route; end Route_Aggregator;
data/expression/WithApp.agda
msuperdock/agda-unused
6
1313
<gh_stars>1-10 module WithApp where f : {A : Set} → A → A f x with x ... | y = y g : {A : Set} → A → A → A g x y with x ... | _ with y ... | _ = x
data/baseStats/caterpie.asm
AmateurPanda92/pokemon-rby-dx
9
80716
db DEX_CATERPIE ; pokedex id db 45 ; base hp db 30 ; base attack db 35 ; base defense db 45 ; base speed db 20 ; base special db BUG ; species type 1 db BUG ; species type 2 db 255 ; catch rate db 53 ; base exp yield INCBIN "pic/bmon/caterpie.pic",0,1 ; 55, sprite dimensions dw CaterpiePicFront dw CaterpiePicBack ; attacks known at lvl 0 db TACKLE db STRING_SHOT db 0 db 0 db 0 ; growth rate ; learnset tmlearn 0 tmlearn 0 tmlearn 0 tmlearn 0 tmlearn 0 tmlearn 0 tmlearn 0 db 0 ; padding
examples/tty_key.adb
ytomino/drake
33
17667
with Ada.Text_IO; procedure tty_key is use type Ada.Text_IO.Count; C, D : Character; Avail : Boolean; Line_Length : Ada.Text_IO.Count := Ada.Text_IO.Line_Length; Start_Col, Current_Col : Ada.Text_IO.Count; begin Ada.Text_IO.New_Page; -- clear screen Ada.Text_IO.Put ("push any key:"); Ada.Text_IO.Get_Immediate (C); Start_Col := Ada.Text_IO.Col; Current_Col := Start_Col; loop Ada.Text_IO.Get_Immediate (D, Avail); if Avail then exit when C = D; Current_Col := Ada.Text_IO.Col; else Ada.Text_IO.Put (C); Current_Col := Current_Col + 1; end if; if Current_Col = Line_Length then Ada.Text_IO.Set_Col (Start_Col); Current_Col := Start_Col; end if; end loop; Ada.Text_IO.New_Line; end tty_key;
theorems/groups/Cokernel.agda
mikeshulman/HoTT-Agda
0
10849
{-# OPTIONS --without-K --rewriting #-} open import HoTT -- an attempt to speed up [QuotGroup (im-nprop ...)] -- which removes most intermediate constructions module groups.Cokernel {i j} {G : Group i} {H : Group j} (φ : G →ᴳ H) (H-ab : is-abelian H) where -- G ---φ--→ᴳ H private module G = Group G module H = AbGroup (H , H-ab) module φ = GroupHom φ coker-rel : Rel H.El (lmax i j) coker-rel h₁ h₂ = Trunc -1 (hfiber φ.f (H.diff h₁ h₂)) private coker-El : Type (lmax i j) coker-El = SetQuot coker-rel coker-struct : GroupStructure coker-El coker-struct = record {M} where module M where ident : coker-El ident = q[ H.ident ] inv : coker-El → coker-El inv = SetQuot-rec SetQuot-level inv' inv-rel where inv' : H.El → coker-El inv' h = q[ H.inv h ] abstract inv-rel : ∀ {h₁ h₂} → coker-rel h₁ h₂ → inv' h₁ == inv' h₂ inv-rel {h₁} {h₂} = Trunc-rec (SetQuot-level _ _) λ{(g , φg=h₁h₂⁻¹) → quot-rel [ G.inv g , φ.pres-inv g ∙ ap H.inv φg=h₁h₂⁻¹ ∙ H.inv-diff h₁ h₂ ∙ H.comm h₂ (H.inv h₁) ∙ ap (H.comp (H.inv h₁)) (! (H.inv-inv h₂)) ]} comp : coker-El → coker-El → coker-El comp = SetQuot-rec level comp' comp-rel where abstract level : is-set (coker-El → coker-El) level = →-is-set SetQuot-level comp' : H.El → coker-El → coker-El comp' h₁ = SetQuot-rec SetQuot-level comp'' comp'-rel where comp'' : H.El → coker-El comp'' h₂ = q[ H.comp h₁ h₂ ] abstract comp'-rel : ∀ {h₂ h₂'} → coker-rel h₂ h₂' → comp'' h₂ == comp'' h₂' comp'-rel {h₂} {h₂'} = Trunc-rec (SetQuot-level _ _) λ{(g , φg=h₂h₂'⁻¹) → quot-rel [ g , ! ( ap (H.comp (H.comp h₁ h₂)) (H.inv-comp h₁ h₂') ∙ H.assoc h₁ h₂ (H.comp (H.inv h₂') (H.inv h₁)) ∙ ap (H.comp h₁) (! $ H.assoc h₂ (H.inv h₂') (H.inv h₁)) ∙ H.comm h₁ (H.comp (H.comp h₂ (H.inv h₂')) (H.inv h₁)) ∙ H.assoc (H.comp h₂ (H.inv h₂')) (H.inv h₁) h₁ ∙ ap2 H.comp (! φg=h₂h₂'⁻¹) (H.inv-l h₁) ∙ H.unit-r (φ.f g) )]} abstract comp-rel : ∀ {h₁ h₁'} → coker-rel h₁ h₁' → comp' h₁ == comp' h₁' comp-rel {h₁} {h₁'} = Trunc-rec (level _ _) λ{(g , φg=h₁h₁'⁻¹) → λ= $ SetQuot-elim (λ _ → =-preserves-set SetQuot-level) (λ h₂ → quot-rel [ g , ! ( ap (H.comp (H.comp h₁ h₂)) (H.inv-comp h₁' h₂) ∙ H.assoc h₁ h₂ (H.comp (H.inv h₂) (H.inv h₁')) ∙ ap (H.comp h₁) ( ! (H.assoc h₂ (H.inv h₂) (H.inv h₁')) ∙ ap (λ h → H.comp h (H.inv h₁')) (H.inv-r h₂) ∙ H.unit-l (H.inv h₁')) ∙ ! φg=h₁h₁'⁻¹ )]) (λ _ → prop-has-all-paths-↓ (SetQuot-level _ _))} abstract unit-l : ∀ cok → comp ident cok == cok unit-l = SetQuot-elim (λ _ → =-preserves-set SetQuot-level) (λ h → ap q[_] $ H.unit-l h) (λ _ → prop-has-all-paths-↓ (SetQuot-level _ _)) assoc : ∀ cok₁ cok₂ cok₃ → comp (comp cok₁ cok₂) cok₃ == comp cok₁ (comp cok₂ cok₃) assoc = SetQuot-elim (λ _ → Π-is-set λ _ → Π-is-set λ _ → =-preserves-set SetQuot-level) (λ h₁ → SetQuot-elim (λ _ → Π-is-set λ _ → =-preserves-set SetQuot-level) (λ h₂ → SetQuot-elim (λ _ → =-preserves-set SetQuot-level) (λ h₃ → ap q[_] $ H.assoc h₁ h₂ h₃) (λ _ → prop-has-all-paths-↓ (SetQuot-level _ _))) (λ _ → prop-has-all-paths-↓ (Π-is-prop λ _ → SetQuot-level _ _))) (λ _ → prop-has-all-paths-↓ (Π-is-prop λ _ → Π-is-prop λ _ → SetQuot-level _ _)) inv-l : ∀ cok → comp (inv cok) cok == ident inv-l = SetQuot-elim (λ _ → =-preserves-set SetQuot-level) (λ h → ap q[_] $ H.inv-l h) (λ _ → prop-has-all-paths-↓ (SetQuot-level _ _)) Coker : Group (lmax i j) Coker = group _ SetQuot-level coker-struct module Coker = Group Coker {- correctness -} Coker-β : Coker ≃ᴳ QuotGroup (im-npropᴳ φ H-ab) Coker-β = ≃-to-≃ᴳ (ide _) to-pres-comp where abstract to-pres-comp : preserves-comp Coker.comp (QuotGroup.comp (im-npropᴳ φ H-ab)) (idf _) to-pres-comp = SetQuot-elim (λ _ → Π-is-set λ _ → =-preserves-set SetQuot-level) (λ _ → SetQuot-elim (λ _ → =-preserves-set SetQuot-level) (λ _ → idp) (λ _ → prop-has-all-paths-↓ (SetQuot-level _ _))) (λ _ → prop-has-all-paths-↓ (Π-is-prop λ _ → SetQuot-level _ _))
RecursiveTypes/Subtyping/Example.agda
nad/codata
1
2063
------------------------------------------------------------------------ -- An example ------------------------------------------------------------------------ module RecursiveTypes.Subtyping.Example where open import Codata.Musical.Notation open import Data.Fin open import Data.Nat open import RecursiveTypes.Syntax open import RecursiveTypes.Subtyping.Semantic.Coinductive -- σ = μX. X ⟶ X. σ : Ty 0 σ = μ var zero ⟶ var zero -- τ = μX. (X ⟶ ⊥) ⟶ ⊤. τ : Ty 0 τ = μ (var zero ⟶ ⊥) ⟶ ⊤ -- σ is a subtype of τ. σ≤τ : σ ≤Coind τ σ≤τ = ♯ (♯ σ≤τ ⟶ ♯ ⊥) ⟶ ♯ ⊤
snippets/comparisons.i.asm
ped7g/ZXSpectrumNextMisc
15
2689
; examples of basic arithmetic comparisons for simple types int/uint 8/16 bit ; ; each example consist of two parts: ; - comparison itself (setting flag registers) ; - branching per condition ; ; In the branching part all possible variants are shown, but in your code you need to ; use only the particular condition which is important for your code (probably only ; single line, not all of them). ; ; The branching options are demonstrated by CALL instruction, but you can use any of ; the other conditional intructions JR/JP/RET, except the JR ones not having certain ; tests (pe/po/p/m), for those conditions one is forced to use JP instead of JR. ; ; Also the demonstration works correctly only because each sub-call modifying register ; E with "result value" does NOT modify any flags - if it would modify them, ; the subsequent calls would be branching on invalid state (fragile example). comparisons: ;; set result markers into E register (helper functions for examples) .equal: ld e,$00 ret .unequal: ld e,$80 ret .less: ld e,$FF ret .greaterEqual: ld e,$01 ret .negative: ld e,$2D ; '-' ret .positive: ld e,$2B ; '+' ret ;; example: uint8 A vs uint8 B .uint8: ; comparison code cp b ; equality call z,.equal ; A == B call nz,.unequal ; A != B ; less/greater+equal (below/above in x86 terminology) call c,.less ; A < B call nc,.greaterEqual ; A >= B ret ;; example: int8 A vs int8 B .int8: ; comparison code cp b ; equality call z,.equal ; A == B call nz,.unequal ; A != B ; less/greater+equal jp pe,.int8_overflow .int8_no_overflow: call m,.less ; A < B (m = minus) call p,.greaterEqual ; A >= B (p = plus) ret .int8_overflow: ; sign flag is inverted when overflow happened call p,.less ; A < B call m,.greaterEqual ; A >= B ret ;; example: uint16 HL vs uint16 BC .uint16: ; comparison code or a ; clear carry flag for SBC sbc hl,bc ; destructive to content of HL add hl,bc ; restore HL (flags: preserves Z, S, P/V, sets same C) ; equality call z,.equal ; HL == BC call nz,.unequal ; HL != BC ; less/greater+equal (below/above in x86 terminology) call c,.less ; HL < BC call nc,.greaterEqual ; HL >= BC ret ;; example: int16 HL vs int16 BC .int16: ; comparison code or a ; clear carry flag for SBC sbc hl,bc ; destructive to content of HL add hl,bc ; restore HL (flags: preserves Z, S, P/V, sets same C) ; equality call z,.equal ; HL == BC call nz,.unequal ; HL != BC ; less/greater+equal jp pe,.int16_overflow .int16_no_overflow: call m,.less ; HL < BC (m = minus) call p,.greaterEqual ; HL >= BC (p = plus) ret .int16_overflow: ; sign flag is inverted when overflow happened call p,.less ; HL < BC call m,.greaterEqual ; HL >= BC ret ;; example: int16 HL < int16 BC, modifies A, result flag is in zero+carry (like unsigned!) .int16_v2: call .int16_v2_impl ; comparison code (implementation) ; equality call z,.equal ; HL == BC call nz,.unequal ; HL != BC ; less/greater+equal call c,.less ; HL < BC call nc,.greaterEqual ; HL >= BC ret .int16_v2_impl: ld a,h xor b jp p,.int16_v2_same_sign .int16_v2_other_sign: ; sgn HL != sgn BC: one value is negative xor h ; A=B, CF=0, SF=BC<0 ret m ; HL >= 0 > BC, return CF=0, ZF=0 cp h ret ; HL < 0 <= BC, return CF=1, ZF=0 .int16_v2_same_sign: ; sgn HL == sgn BC: can compare as "unsigned" values ld a,h cp b ret nz ld a,l cp c ret ;; example: int16 HL vs uint16 BC (not simple flags-only-result, handling is in code) .int16_vs_uint16: ; conversion to int16 - if BC is above int16 limits, it's clearly "HL < BC" case bit 7,b call nz,.less ; HL < BC (BC is $8000+ value, over the int16 limit) ret nz ; abort early (flags PV/SF/CF are NOT set here) ; when BC is within int16 limits, then the example `.int16` above can be applied jr .int16 ;; example: int16 HL .is_negative_16: bit 7,h call nz,.negative call z,.positive ret ;; example: int8 A .is_negative_8: or a call m,.negative call p,.positive ret ;; example: int8 A .is_zero_8: or a call nz,.unequal call z,.equal ret ;; calling all examples (for trying them out in debugger single-stepping over them) .run: ld e,$EE ; no result ld a,12 ; first value "A" ld b,34 ; second value "B" call .uint8 ld e,$EE ; no result ld a,23 ; first value "A" ld b,45 ; second value "B" call .int8 ld e,$EE ; no result ld hl,1234 ; first value "HL" ld bc,5678 ; second value "BC" call .uint16 ld e,$EE ; no result ld hl,2345 ; first value "HL" ld bc,6789 ; second value "BC" call .int16 ld e,$EE ; no result ld hl,3456 ; first value "HL" ld bc,7890 ; second value "BC" call .int16_v2 ld e,$EE ; no result ld hl,-123 ; first value "HL" ld bc,40000 ; second value "BC" call .int16_vs_uint16 ld e,$EE ld hl,$7FFF call .is_negative_16 ld e,$EE ld a,-123 call .is_negative_8 ld e,$EE ld a,0 call .is_zero_8 ret
unittests/ASM/OpSize/66_6E.asm
woachk/FEX
1
8467
%ifdef CONFIG { "RegData": { "XMM0": ["0x45464748", "0x0"], "XMM1": ["0x5152535455565758", "0x0"] }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x4142434445464748 mov [rdx + 8 * 0], rax mov rax, 0x5152535455565758 mov [rdx + 8 * 1], rax mov rax, 0x6162636465666768 mov [rdx + 8 * 2], rax mov rax, 0x7172737475767778 mov [rdx + 8 * 3], rax mov rax, 0x0 mov [rdx + 8 * 4], rax mov [rdx + 8 * 5], rax movaps xmm2, [rdx + 8 * 2] movaps xmm3, [rdx + 8 * 3] movd xmm0, dword [rdx + 8 * 0] ; AMD's Architecture programmer's manual claims this mnemonic is still movd, but compilers only accept movq movq xmm1, qword [rdx + 8 * 1] hlt
math-and-functional-programming/1999-Type_Theory_and_Functional_Programming-Simon_Thompson/x.agda
haroldcarr/learn-haskell-coq-ml-etc
36
5296
module x where open import Level private variable a b c d e f ℓ p q r : Level A : Set a B : Set b C : Set c D : Set d E : Set e F : Set f ------------------------------------------------------------------------------ infixr 4 _,_ infixr 2 _^_ record _^_ (A : Set a) (B : Set b) : Set (a ⊔ b) where constructor _,_ field fst : A snd : B open _^_ swap : A ^ B → B ^ A swap (a , b) = b , a ------------------------------------------------------------------------------ infixr 1 _v_ data _v_ (A : Set a) (B : Set b) : Set (a ⊔ b) where inl : (x : A) → A v B inr : (y : B) → A v B cases : ∀ {A : Set a} {B : Set b} {C : Set c} → (A v B) → (A → C) → (B → C) → C cases (inl q) f g = f q cases (inr r) f g = g r ------------------------------------------------------------------------------ data ⊥ : Set where ⊥-elim : ∀ {A : Set a} → ⊥ → A ⊥-elim = λ () ------------------------------------------------------------------------------ ¬_ : Set → Set ¬ A = A → ⊥ ------------------------------------------------------------------------------ -- 4.1 assoc-^ : (A ^ B) ^ C → A ^ (B ^ C) assoc-^ ((a , b) , c) = a , (b , c) -- 4.2 e4-2 : (¬ A v B) → (A → B) e4-2 (inl ¬a) = λ a → ⊥-elim (¬a a) e4-2 (inr b) = λ _ → b {- not provable e4-2' : (A → B) → (¬ A v B) e4-2' a→b = {!!} -} -- 4.3 e4-3 : (A v ¬ A) → (¬ ¬ A → A) e4-3 (inl a) = λ _ → a e4-3 (inr ¬a) = λ ¬¬a → ⊥-elim (¬¬a ¬a) e4-3' : (A → ¬ ¬ A) e4-3' = λ a ¬¬a → ¬¬a a -- 4.4 -- this is similar to v elimination by cases e4-4 : ((A ^ B) → C) → A → (B → C) e4-4 a^b→c a = λ b → a^b→c (a , b) -- 4.5 e4-5 : (A → (B → C)) → ((A ^ B) → C) e4-5 a→b→c = λ (a , b) → a→b→c a b e4-5' : ((A ^ B) → C) → (A → (B → C)) e4-5' a^b→c = λ a → λ b → a^b→c (a , b) -- 4.6 e4-6 : A → (B v C) → ((A ^ B) v (A ^ C)) e4-6 a (inl b) = inl (a , b) e4-6 a (inr c) = inr (a , c) -- 4.7 e4-7 : (A → C) → (B → D) → ((A ^ B) → (C ^ D)) e4-7 a→c b→d = λ (a , b) → (a→c a , b→d b) -- section 4.5.2 -- function composition _∘_ : (B → C) → (A → B) → (A → C) _∘_ b→c a→b = λ a -> b→c (a→b a) srl : (A → B) → (¬ B → ¬ A) srl a→b = λ ¬b a → ¬b (a→b a) -- section 4.5.3 idA^A : (A ^ A) → (A ^ A) idA^A (a , a') = (a' , a) -- section 4.5.5 Conjunction and disjunction s455 : ((A v B) → C) → ((A → C) ^ (B → C)) s455 = λ avb→c → (avb→c ∘ inl , avb→c ∘ inr) s455' : ((A → C) ^ (B → C)) → ((A v B) → C) s455' (a→c , b→c) = λ { (inl a) → a→c a ; (inr b) → b→c b } dm : ¬ (A v B) → (¬ A ^ ¬ B) dm notAvB = (notAvB ∘ inl , notAvB ∘ inr) dm' : (¬ A v ¬ B) → ¬ (A ^ B) dm' (inl ¬a) = λ (a , _) → ¬a a dm' (inr ¬b) = λ (_ , b) → ¬b b -- 4.8 e4-8a : A → ¬ ¬ A e4-8a a = λ ¬a → ¬a a e4-8b : (B v C) → ¬ (¬ B ^ ¬ C) e4-8b (inl b) = λ (¬b , _) → ¬b b e4-8b (inr c) = λ ( _ , ¬c) → ¬c c e4-8c : (A → B) → ((A → C) → (A → (B ^ C))) e4-8c a→b = λ a→c → λ a → (a→b a , a→c a)
test/src/yaml-lexer-buffering_test.adb
robdaemon/AdaYaml
32
11301
-- part of AdaYaml, (c) 2017 <NAME> -- released under the terms of the MIT license, see the file "copying.txt" with AUnit.Assertions; use AUnit.Assertions; with Yaml.Source.File; with Utils; package body Yaml.Lexer.Buffering_Test is procedure Register_Tests (T : in out TC) is use AUnit.Test_Cases.Registration; begin Register_Routine (T, Test_File_Without_Refill'Access, "Read file of exact buffer size"); Register_Routine (T, Test_File_With_Single_Refill'Access, "Read file exceeding buffer size"); end Register_Tests; function Name (T : TC) return Message_String is pragma Unreferenced (T); begin return AUnit.Format ("Buffering tests for Lexer"); end Name; procedure Set_Up (T : in out TC) is begin T.Pool.Create (8092); end Set_Up; procedure Test_File_Without_Refill (T : in out Test_Cases.Test_Case'Class) is Data_Path : constant String := "test/data/64char.yaml"; Expected : constant String := Utils.File_Content (Data_Path) & End_Of_Input; S : constant Source.Pointer := Source.File.As_Source (Data_Path); L : Instance; begin Init (L, S, TC (T).Pool, 64); Assert (L.Buffer.all'Length = 64, "Buffer length does not match! Val:" & L.Buffer.all'Length'Img); for I in Expected'Range loop Assert (Expected (I) = L.Cur, "Buffer contents at" & I'Img & " does not match. Expected """ & Expected (I) & """, got """ & L.Cur & """."); exit when L.Cur = End_Of_Input; case L.Cur is when Line_Feed => Handle_LF (L); when Carriage_Return => Handle_CR (L); when others => null; end case; L.Cur := Next (L); end loop; end Test_File_Without_Refill; procedure Test_File_With_Single_Refill (T : in out Test_Cases.Test_Case'Class) is Data_Path : constant String := "test/data/98char.yaml"; Expected : constant String := Utils.File_Content (Data_Path); S : constant Source.Pointer := Source.File.As_Source (Data_Path); L : Instance; begin Init (L, S, TC (T).Pool, 64); Assert (L.Buffer.all'Length = 64, "Buffer length does not match! Val: " & L.Buffer.all'Length'Img); for I in Expected'Range loop Assert (Expected (I) = L.Cur, "Buffer contents at" & I'Img & " does not match. Expected """ & Expected (I) & """, got """ & L.Cur & """."); exit when L.Cur = End_Of_Input; case L.Cur is when Line_Feed => Handle_LF (L); when Carriage_Return => Handle_CR (L); when others => null; end case; L.Cur := Next (L); end loop; end Test_File_With_Single_Refill; end Yaml.Lexer.Buffering_Test;
cat.asm
dylsugar/cs461_hw5
0
87981
<reponame>dylsugar/cs461_hw5 _cat: file format elf64-x86-64 Disassembly of section .text: 0000000000001000 <cat>: char buf[512]; void cat(int fd) { 1000: f3 0f 1e fa endbr64 1004: 55 push %rbp 1005: 48 89 e5 mov %rsp,%rbp 1008: 48 83 ec 20 sub $0x20,%rsp 100c: 89 7d ec mov %edi,-0x14(%rbp) int n; while((n = read(fd, buf, sizeof(buf))) > 0) { 100f: eb 51 jmp 1062 <cat+0x62> if (write(1, buf, n) != n) { 1011: 8b 45 fc mov -0x4(%rbp),%eax 1014: 89 c2 mov %eax,%edx 1016: 48 be c0 22 00 00 00 movabs $0x22c0,%rsi 101d: 00 00 00 1020: bf 01 00 00 00 mov $0x1,%edi 1025: 48 b8 31 15 00 00 00 movabs $0x1531,%rax 102c: 00 00 00 102f: ff d0 callq *%rax 1031: 39 45 fc cmp %eax,-0x4(%rbp) 1034: 74 2c je 1062 <cat+0x62> printf(1, "cat: write error\n"); 1036: 48 be 18 1f 00 00 00 movabs $0x1f18,%rsi 103d: 00 00 00 1040: bf 01 00 00 00 mov $0x1,%edi 1045: b8 00 00 00 00 mov $0x0,%eax 104a: 48 ba 01 18 00 00 00 movabs $0x1801,%rdx 1051: 00 00 00 1054: ff d2 callq *%rdx exit(); 1056: 48 b8 fd 14 00 00 00 movabs $0x14fd,%rax 105d: 00 00 00 1060: ff d0 callq *%rax while((n = read(fd, buf, sizeof(buf))) > 0) { 1062: 8b 45 ec mov -0x14(%rbp),%eax 1065: ba 00 02 00 00 mov $0x200,%edx 106a: 48 be c0 22 00 00 00 movabs $0x22c0,%rsi 1071: 00 00 00 1074: 89 c7 mov %eax,%edi 1076: 48 b8 24 15 00 00 00 movabs $0x1524,%rax 107d: 00 00 00 1080: ff d0 callq *%rax 1082: 89 45 fc mov %eax,-0x4(%rbp) 1085: 83 7d fc 00 cmpl $0x0,-0x4(%rbp) 1089: 7f 86 jg 1011 <cat+0x11> } } if(n < 0){ 108b: 83 7d fc 00 cmpl $0x0,-0x4(%rbp) 108f: 79 2c jns 10bd <cat+0xbd> printf(1, "cat: read error\n"); 1091: 48 be 2a 1f 00 00 00 movabs $0x1f2a,%rsi 1098: 00 00 00 109b: bf 01 00 00 00 mov $0x1,%edi 10a0: b8 00 00 00 00 mov $0x0,%eax 10a5: 48 ba 01 18 00 00 00 movabs $0x1801,%rdx 10ac: 00 00 00 10af: ff d2 callq *%rdx exit(); 10b1: 48 b8 fd 14 00 00 00 movabs $0x14fd,%rax 10b8: 00 00 00 10bb: ff d0 callq *%rax } } 10bd: 90 nop 10be: c9 leaveq 10bf: c3 retq 00000000000010c0 <main>: int main(int argc, char *argv[]) { 10c0: f3 0f 1e fa endbr64 10c4: 55 push %rbp 10c5: 48 89 e5 mov %rsp,%rbp 10c8: 48 83 ec 20 sub $0x20,%rsp 10cc: 89 7d ec mov %edi,-0x14(%rbp) 10cf: 48 89 75 e0 mov %rsi,-0x20(%rbp) int fd, i; if(argc <= 1){ 10d3: 83 7d ec 01 cmpl $0x1,-0x14(%rbp) 10d7: 7f 1d jg 10f6 <main+0x36> cat(0); 10d9: bf 00 00 00 00 mov $0x0,%edi 10de: 48 b8 00 10 00 00 00 movabs $0x1000,%rax 10e5: 00 00 00 10e8: ff d0 callq *%rax exit(); 10ea: 48 b8 fd 14 00 00 00 movabs $0x14fd,%rax 10f1: 00 00 00 10f4: ff d0 callq *%rax } for(i = 1; i < argc; i++){ 10f6: c7 45 fc 01 00 00 00 movl $0x1,-0x4(%rbp) 10fd: e9 a0 00 00 00 jmpq 11a2 <main+0xe2> if((fd = open(argv[i], 0)) < 0){ 1102: 8b 45 fc mov -0x4(%rbp),%eax 1105: 48 98 cltq 1107: 48 8d 14 c5 00 00 00 lea 0x0(,%rax,8),%rdx 110e: 00 110f: 48 8b 45 e0 mov -0x20(%rbp),%rax 1113: 48 01 d0 add %rdx,%rax 1116: 48 8b 00 mov (%rax),%rax 1119: be 00 00 00 00 mov $0x0,%esi 111e: 48 89 c7 mov %rax,%rdi 1121: 48 b8 65 15 00 00 00 movabs $0x1565,%rax 1128: 00 00 00 112b: ff d0 callq *%rax 112d: 89 45 f8 mov %eax,-0x8(%rbp) 1130: 83 7d f8 00 cmpl $0x0,-0x8(%rbp) 1134: 79 46 jns 117c <main+0xbc> printf(1, "cat: cannot open %s\n", argv[i]); 1136: 8b 45 fc mov -0x4(%rbp),%eax 1139: 48 98 cltq 113b: 48 8d 14 c5 00 00 00 lea 0x0(,%rax,8),%rdx 1142: 00 1143: 48 8b 45 e0 mov -0x20(%rbp),%rax 1147: 48 01 d0 add %rdx,%rax 114a: 48 8b 00 mov (%rax),%rax 114d: 48 89 c2 mov %rax,%rdx 1150: 48 be 3b 1f 00 00 00 movabs $0x1f3b,%rsi 1157: 00 00 00 115a: bf 01 00 00 00 mov $0x1,%edi 115f: b8 00 00 00 00 mov $0x0,%eax 1164: 48 b9 01 18 00 00 00 movabs $0x1801,%rcx 116b: 00 00 00 116e: ff d1 callq *%rcx exit(); 1170: 48 b8 fd 14 00 00 00 movabs $0x14fd,%rax 1177: 00 00 00 117a: ff d0 callq *%rax } cat(fd); 117c: 8b 45 f8 mov -0x8(%rbp),%eax 117f: 89 c7 mov %eax,%edi 1181: 48 b8 00 10 00 00 00 movabs $0x1000,%rax 1188: 00 00 00 118b: ff d0 callq *%rax close(fd); 118d: 8b 45 f8 mov -0x8(%rbp),%eax 1190: 89 c7 mov %eax,%edi 1192: 48 b8 3e 15 00 00 00 movabs $0x153e,%rax 1199: 00 00 00 119c: ff d0 callq *%rax for(i = 1; i < argc; i++){ 119e: 83 45 fc 01 addl $0x1,-0x4(%rbp) 11a2: 8b 45 fc mov -0x4(%rbp),%eax 11a5: 3b 45 ec cmp -0x14(%rbp),%eax 11a8: 0f 8c 54 ff ff ff jl 1102 <main+0x42> } exit(); 11ae: 48 b8 fd 14 00 00 00 movabs $0x14fd,%rax 11b5: 00 00 00 11b8: ff d0 callq *%rax 00000000000011ba <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 11ba: f3 0f 1e fa endbr64 11be: 55 push %rbp 11bf: 48 89 e5 mov %rsp,%rbp 11c2: 48 83 ec 10 sub $0x10,%rsp 11c6: 48 89 7d f8 mov %rdi,-0x8(%rbp) 11ca: 89 75 f4 mov %esi,-0xc(%rbp) 11cd: 89 55 f0 mov %edx,-0x10(%rbp) asm volatile("cld; rep stosb" : 11d0: 48 8b 4d f8 mov -0x8(%rbp),%rcx 11d4: 8b 55 f0 mov -0x10(%rbp),%edx 11d7: 8b 45 f4 mov -0xc(%rbp),%eax 11da: 48 89 ce mov %rcx,%rsi 11dd: 48 89 f7 mov %rsi,%rdi 11e0: 89 d1 mov %edx,%ecx 11e2: fc cld 11e3: f3 aa rep stos %al,%es:(%rdi) 11e5: 89 ca mov %ecx,%edx 11e7: 48 89 fe mov %rdi,%rsi 11ea: 48 89 75 f8 mov %rsi,-0x8(%rbp) 11ee: 89 55 f0 mov %edx,-0x10(%rbp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 11f1: 90 nop 11f2: c9 leaveq 11f3: c3 retq 00000000000011f4 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 11f4: f3 0f 1e fa endbr64 11f8: 55 push %rbp 11f9: 48 89 e5 mov %rsp,%rbp 11fc: 48 83 ec 20 sub $0x20,%rsp 1200: 48 89 7d e8 mov %rdi,-0x18(%rbp) 1204: 48 89 75 e0 mov %rsi,-0x20(%rbp) char *os; os = s; 1208: 48 8b 45 e8 mov -0x18(%rbp),%rax 120c: 48 89 45 f8 mov %rax,-0x8(%rbp) while((*s++ = *t++) != 0) 1210: 90 nop 1211: 48 8b 55 e0 mov -0x20(%rbp),%rdx 1215: 48 8d 42 01 lea 0x1(%rdx),%rax 1219: 48 89 45 e0 mov %rax,-0x20(%rbp) 121d: 48 8b 45 e8 mov -0x18(%rbp),%rax 1221: 48 8d 48 01 lea 0x1(%rax),%rcx 1225: 48 89 4d e8 mov %rcx,-0x18(%rbp) 1229: 0f b6 12 movzbl (%rdx),%edx 122c: 88 10 mov %dl,(%rax) 122e: 0f b6 00 movzbl (%rax),%eax 1231: 84 c0 test %al,%al 1233: 75 dc jne 1211 <strcpy+0x1d> ; return os; 1235: 48 8b 45 f8 mov -0x8(%rbp),%rax } 1239: c9 leaveq 123a: c3 retq 000000000000123b <strcmp>: int strcmp(const char *p, const char *q) { 123b: f3 0f 1e fa endbr64 123f: 55 push %rbp 1240: 48 89 e5 mov %rsp,%rbp 1243: 48 83 ec 10 sub $0x10,%rsp 1247: 48 89 7d f8 mov %rdi,-0x8(%rbp) 124b: 48 89 75 f0 mov %rsi,-0x10(%rbp) while(*p && *p == *q) 124f: eb 0a jmp 125b <strcmp+0x20> p++, q++; 1251: 48 83 45 f8 01 addq $0x1,-0x8(%rbp) 1256: 48 83 45 f0 01 addq $0x1,-0x10(%rbp) while(*p && *p == *q) 125b: 48 8b 45 f8 mov -0x8(%rbp),%rax 125f: 0f b6 00 movzbl (%rax),%eax 1262: 84 c0 test %al,%al 1264: 74 12 je 1278 <strcmp+0x3d> 1266: 48 8b 45 f8 mov -0x8(%rbp),%rax 126a: 0f b6 10 movzbl (%rax),%edx 126d: 48 8b 45 f0 mov -0x10(%rbp),%rax 1271: 0f b6 00 movzbl (%rax),%eax 1274: 38 c2 cmp %al,%dl 1276: 74 d9 je 1251 <strcmp+0x16> return (uchar)*p - (uchar)*q; 1278: 48 8b 45 f8 mov -0x8(%rbp),%rax 127c: 0f b6 00 movzbl (%rax),%eax 127f: 0f b6 d0 movzbl %al,%edx 1282: 48 8b 45 f0 mov -0x10(%rbp),%rax 1286: 0f b6 00 movzbl (%rax),%eax 1289: 0f b6 c0 movzbl %al,%eax 128c: 29 c2 sub %eax,%edx 128e: 89 d0 mov %edx,%eax } 1290: c9 leaveq 1291: c3 retq 0000000000001292 <strlen>: uint strlen(char *s) { 1292: f3 0f 1e fa endbr64 1296: 55 push %rbp 1297: 48 89 e5 mov %rsp,%rbp 129a: 48 83 ec 18 sub $0x18,%rsp 129e: 48 89 7d e8 mov %rdi,-0x18(%rbp) int n; for(n = 0; s[n]; n++) 12a2: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) 12a9: eb 04 jmp 12af <strlen+0x1d> 12ab: 83 45 fc 01 addl $0x1,-0x4(%rbp) 12af: 8b 45 fc mov -0x4(%rbp),%eax 12b2: 48 63 d0 movslq %eax,%rdx 12b5: 48 8b 45 e8 mov -0x18(%rbp),%rax 12b9: 48 01 d0 add %rdx,%rax 12bc: 0f b6 00 movzbl (%rax),%eax 12bf: 84 c0 test %al,%al 12c1: 75 e8 jne 12ab <strlen+0x19> ; return n; 12c3: 8b 45 fc mov -0x4(%rbp),%eax } 12c6: c9 leaveq 12c7: c3 retq 00000000000012c8 <memset>: void* memset(void *dst, int c, uint n) { 12c8: f3 0f 1e fa endbr64 12cc: 55 push %rbp 12cd: 48 89 e5 mov %rsp,%rbp 12d0: 48 83 ec 10 sub $0x10,%rsp 12d4: 48 89 7d f8 mov %rdi,-0x8(%rbp) 12d8: 89 75 f4 mov %esi,-0xc(%rbp) 12db: 89 55 f0 mov %edx,-0x10(%rbp) stosb(dst, c, n); 12de: 8b 55 f0 mov -0x10(%rbp),%edx 12e1: 8b 4d f4 mov -0xc(%rbp),%ecx 12e4: 48 8b 45 f8 mov -0x8(%rbp),%rax 12e8: 89 ce mov %ecx,%esi 12ea: 48 89 c7 mov %rax,%rdi 12ed: 48 b8 ba 11 00 00 00 movabs $0x11ba,%rax 12f4: 00 00 00 12f7: ff d0 callq *%rax return dst; 12f9: 48 8b 45 f8 mov -0x8(%rbp),%rax } 12fd: c9 leaveq 12fe: c3 retq 00000000000012ff <strchr>: char* strchr(const char *s, char c) { 12ff: f3 0f 1e fa endbr64 1303: 55 push %rbp 1304: 48 89 e5 mov %rsp,%rbp 1307: 48 83 ec 10 sub $0x10,%rsp 130b: 48 89 7d f8 mov %rdi,-0x8(%rbp) 130f: 89 f0 mov %esi,%eax 1311: 88 45 f4 mov %al,-0xc(%rbp) for(; *s; s++) 1314: eb 17 jmp 132d <strchr+0x2e> if(*s == c) 1316: 48 8b 45 f8 mov -0x8(%rbp),%rax 131a: 0f b6 00 movzbl (%rax),%eax 131d: 38 45 f4 cmp %al,-0xc(%rbp) 1320: 75 06 jne 1328 <strchr+0x29> return (char*)s; 1322: 48 8b 45 f8 mov -0x8(%rbp),%rax 1326: eb 15 jmp 133d <strchr+0x3e> for(; *s; s++) 1328: 48 83 45 f8 01 addq $0x1,-0x8(%rbp) 132d: 48 8b 45 f8 mov -0x8(%rbp),%rax 1331: 0f b6 00 movzbl (%rax),%eax 1334: 84 c0 test %al,%al 1336: 75 de jne 1316 <strchr+0x17> return 0; 1338: b8 00 00 00 00 mov $0x0,%eax } 133d: c9 leaveq 133e: c3 retq 000000000000133f <gets>: char* gets(char *buf, int max) { 133f: f3 0f 1e fa endbr64 1343: 55 push %rbp 1344: 48 89 e5 mov %rsp,%rbp 1347: 48 83 ec 20 sub $0x20,%rsp 134b: 48 89 7d e8 mov %rdi,-0x18(%rbp) 134f: 89 75 e4 mov %esi,-0x1c(%rbp) int i, cc; char c; for(i=0; i+1 < max; ){ 1352: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) 1359: eb 4f jmp 13aa <gets+0x6b> cc = read(0, &c, 1); 135b: 48 8d 45 f7 lea -0x9(%rbp),%rax 135f: ba 01 00 00 00 mov $0x1,%edx 1364: 48 89 c6 mov %rax,%rsi 1367: bf 00 00 00 00 mov $0x0,%edi 136c: 48 b8 24 15 00 00 00 movabs $0x1524,%rax 1373: 00 00 00 1376: ff d0 callq *%rax 1378: 89 45 f8 mov %eax,-0x8(%rbp) if(cc < 1) 137b: 83 7d f8 00 cmpl $0x0,-0x8(%rbp) 137f: 7e 36 jle 13b7 <gets+0x78> break; buf[i++] = c; 1381: 8b 45 fc mov -0x4(%rbp),%eax 1384: 8d 50 01 lea 0x1(%rax),%edx 1387: 89 55 fc mov %edx,-0x4(%rbp) 138a: 48 63 d0 movslq %eax,%rdx 138d: 48 8b 45 e8 mov -0x18(%rbp),%rax 1391: 48 01 c2 add %rax,%rdx 1394: 0f b6 45 f7 movzbl -0x9(%rbp),%eax 1398: 88 02 mov %al,(%rdx) if(c == '\n' || c == '\r') 139a: 0f b6 45 f7 movzbl -0x9(%rbp),%eax 139e: 3c 0a cmp $0xa,%al 13a0: 74 16 je 13b8 <gets+0x79> 13a2: 0f b6 45 f7 movzbl -0x9(%rbp),%eax 13a6: 3c 0d cmp $0xd,%al 13a8: 74 0e je 13b8 <gets+0x79> for(i=0; i+1 < max; ){ 13aa: 8b 45 fc mov -0x4(%rbp),%eax 13ad: 83 c0 01 add $0x1,%eax 13b0: 39 45 e4 cmp %eax,-0x1c(%rbp) 13b3: 7f a6 jg 135b <gets+0x1c> 13b5: eb 01 jmp 13b8 <gets+0x79> break; 13b7: 90 nop break; } buf[i] = '\0'; 13b8: 8b 45 fc mov -0x4(%rbp),%eax 13bb: 48 63 d0 movslq %eax,%rdx 13be: 48 8b 45 e8 mov -0x18(%rbp),%rax 13c2: 48 01 d0 add %rdx,%rax 13c5: c6 00 00 movb $0x0,(%rax) return buf; 13c8: 48 8b 45 e8 mov -0x18(%rbp),%rax } 13cc: c9 leaveq 13cd: c3 retq 00000000000013ce <stat>: int stat(char *n, struct stat *st) { 13ce: f3 0f 1e fa endbr64 13d2: 55 push %rbp 13d3: 48 89 e5 mov %rsp,%rbp 13d6: 48 83 ec 20 sub $0x20,%rsp 13da: 48 89 7d e8 mov %rdi,-0x18(%rbp) 13de: 48 89 75 e0 mov %rsi,-0x20(%rbp) int fd; int r; fd = open(n, O_RDONLY); 13e2: 48 8b 45 e8 mov -0x18(%rbp),%rax 13e6: be 00 00 00 00 mov $0x0,%esi 13eb: 48 89 c7 mov %rax,%rdi 13ee: 48 b8 65 15 00 00 00 movabs $0x1565,%rax 13f5: 00 00 00 13f8: ff d0 callq *%rax 13fa: 89 45 fc mov %eax,-0x4(%rbp) if(fd < 0) 13fd: 83 7d fc 00 cmpl $0x0,-0x4(%rbp) 1401: 79 07 jns 140a <stat+0x3c> return -1; 1403: b8 ff ff ff ff mov $0xffffffff,%eax 1408: eb 2f jmp 1439 <stat+0x6b> r = fstat(fd, st); 140a: 48 8b 55 e0 mov -0x20(%rbp),%rdx 140e: 8b 45 fc mov -0x4(%rbp),%eax 1411: 48 89 d6 mov %rdx,%rsi 1414: 89 c7 mov %eax,%edi 1416: 48 b8 8c 15 00 00 00 movabs $0x158c,%rax 141d: 00 00 00 1420: ff d0 callq *%rax 1422: 89 45 f8 mov %eax,-0x8(%rbp) close(fd); 1425: 8b 45 fc mov -0x4(%rbp),%eax 1428: 89 c7 mov %eax,%edi 142a: 48 b8 3e 15 00 00 00 movabs $0x153e,%rax 1431: 00 00 00 1434: ff d0 callq *%rax return r; 1436: 8b 45 f8 mov -0x8(%rbp),%eax } 1439: c9 leaveq 143a: c3 retq 000000000000143b <atoi>: int atoi(const char *s) { 143b: f3 0f 1e fa endbr64 143f: 55 push %rbp 1440: 48 89 e5 mov %rsp,%rbp 1443: 48 83 ec 18 sub $0x18,%rsp 1447: 48 89 7d e8 mov %rdi,-0x18(%rbp) int n; n = 0; 144b: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) while('0' <= *s && *s <= '9') 1452: eb 28 jmp 147c <atoi+0x41> n = n*10 + *s++ - '0'; 1454: 8b 55 fc mov -0x4(%rbp),%edx 1457: 89 d0 mov %edx,%eax 1459: c1 e0 02 shl $0x2,%eax 145c: 01 d0 add %edx,%eax 145e: 01 c0 add %eax,%eax 1460: 89 c1 mov %eax,%ecx 1462: 48 8b 45 e8 mov -0x18(%rbp),%rax 1466: 48 8d 50 01 lea 0x1(%rax),%rdx 146a: 48 89 55 e8 mov %rdx,-0x18(%rbp) 146e: 0f b6 00 movzbl (%rax),%eax 1471: 0f be c0 movsbl %al,%eax 1474: 01 c8 add %ecx,%eax 1476: 83 e8 30 sub $0x30,%eax 1479: 89 45 fc mov %eax,-0x4(%rbp) while('0' <= *s && *s <= '9') 147c: 48 8b 45 e8 mov -0x18(%rbp),%rax 1480: 0f b6 00 movzbl (%rax),%eax 1483: 3c 2f cmp $0x2f,%al 1485: 7e 0b jle 1492 <atoi+0x57> 1487: 48 8b 45 e8 mov -0x18(%rbp),%rax 148b: 0f b6 00 movzbl (%rax),%eax 148e: 3c 39 cmp $0x39,%al 1490: 7e c2 jle 1454 <atoi+0x19> return n; 1492: 8b 45 fc mov -0x4(%rbp),%eax } 1495: c9 leaveq 1496: c3 retq 0000000000001497 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 1497: f3 0f 1e fa endbr64 149b: 55 push %rbp 149c: 48 89 e5 mov %rsp,%rbp 149f: 48 83 ec 28 sub $0x28,%rsp 14a3: 48 89 7d e8 mov %rdi,-0x18(%rbp) 14a7: 48 89 75 e0 mov %rsi,-0x20(%rbp) 14ab: 89 55 dc mov %edx,-0x24(%rbp) char *dst, *src; dst = vdst; 14ae: 48 8b 45 e8 mov -0x18(%rbp),%rax 14b2: 48 89 45 f8 mov %rax,-0x8(%rbp) src = vsrc; 14b6: 48 8b 45 e0 mov -0x20(%rbp),%rax 14ba: 48 89 45 f0 mov %rax,-0x10(%rbp) while(n-- > 0) 14be: eb 1d jmp 14dd <memmove+0x46> *dst++ = *src++; 14c0: 48 8b 55 f0 mov -0x10(%rbp),%rdx 14c4: 48 8d 42 01 lea 0x1(%rdx),%rax 14c8: 48 89 45 f0 mov %rax,-0x10(%rbp) 14cc: 48 8b 45 f8 mov -0x8(%rbp),%rax 14d0: 48 8d 48 01 lea 0x1(%rax),%rcx 14d4: 48 89 4d f8 mov %rcx,-0x8(%rbp) 14d8: 0f b6 12 movzbl (%rdx),%edx 14db: 88 10 mov %dl,(%rax) while(n-- > 0) 14dd: 8b 45 dc mov -0x24(%rbp),%eax 14e0: 8d 50 ff lea -0x1(%rax),%edx 14e3: 89 55 dc mov %edx,-0x24(%rbp) 14e6: 85 c0 test %eax,%eax 14e8: 7f d6 jg 14c0 <memmove+0x29> return vdst; 14ea: 48 8b 45 e8 mov -0x18(%rbp),%rax } 14ee: c9 leaveq 14ef: c3 retq 00000000000014f0 <fork>: mov $SYS_ ## name, %rax; \ mov %rcx, %r10 ;\ syscall ;\ ret SYSCALL(fork) 14f0: 48 c7 c0 01 00 00 00 mov $0x1,%rax 14f7: 49 89 ca mov %rcx,%r10 14fa: 0f 05 syscall 14fc: c3 retq 00000000000014fd <exit>: SYSCALL(exit) 14fd: 48 c7 c0 02 00 00 00 mov $0x2,%rax 1504: 49 89 ca mov %rcx,%r10 1507: 0f 05 syscall 1509: c3 retq 000000000000150a <wait>: SYSCALL(wait) 150a: 48 c7 c0 03 00 00 00 mov $0x3,%rax 1511: 49 89 ca mov %rcx,%r10 1514: 0f 05 syscall 1516: c3 retq 0000000000001517 <pipe>: SYSCALL(pipe) 1517: 48 c7 c0 04 00 00 00 mov $0x4,%rax 151e: 49 89 ca mov %rcx,%r10 1521: 0f 05 syscall 1523: c3 retq 0000000000001524 <read>: SYSCALL(read) 1524: 48 c7 c0 05 00 00 00 mov $0x5,%rax 152b: 49 89 ca mov %rcx,%r10 152e: 0f 05 syscall 1530: c3 retq 0000000000001531 <write>: SYSCALL(write) 1531: 48 c7 c0 10 00 00 00 mov $0x10,%rax 1538: 49 89 ca mov %rcx,%r10 153b: 0f 05 syscall 153d: c3 retq 000000000000153e <close>: SYSCALL(close) 153e: 48 c7 c0 15 00 00 00 mov $0x15,%rax 1545: 49 89 ca mov %rcx,%r10 1548: 0f 05 syscall 154a: c3 retq 000000000000154b <kill>: SYSCALL(kill) 154b: 48 c7 c0 06 00 00 00 mov $0x6,%rax 1552: 49 89 ca mov %rcx,%r10 1555: 0f 05 syscall 1557: c3 retq 0000000000001558 <exec>: SYSCALL(exec) 1558: 48 c7 c0 07 00 00 00 mov $0x7,%rax 155f: 49 89 ca mov %rcx,%r10 1562: 0f 05 syscall 1564: c3 retq 0000000000001565 <open>: SYSCALL(open) 1565: 48 c7 c0 0f 00 00 00 mov $0xf,%rax 156c: 49 89 ca mov %rcx,%r10 156f: 0f 05 syscall 1571: c3 retq 0000000000001572 <mknod>: SYSCALL(mknod) 1572: 48 c7 c0 11 00 00 00 mov $0x11,%rax 1579: 49 89 ca mov %rcx,%r10 157c: 0f 05 syscall 157e: c3 retq 000000000000157f <unlink>: SYSCALL(unlink) 157f: 48 c7 c0 12 00 00 00 mov $0x12,%rax 1586: 49 89 ca mov %rcx,%r10 1589: 0f 05 syscall 158b: c3 retq 000000000000158c <fstat>: SYSCALL(fstat) 158c: 48 c7 c0 08 00 00 00 mov $0x8,%rax 1593: 49 89 ca mov %rcx,%r10 1596: 0f 05 syscall 1598: c3 retq 0000000000001599 <link>: SYSCALL(link) 1599: 48 c7 c0 13 00 00 00 mov $0x13,%rax 15a0: 49 89 ca mov %rcx,%r10 15a3: 0f 05 syscall 15a5: c3 retq 00000000000015a6 <mkdir>: SYSCALL(mkdir) 15a6: 48 c7 c0 14 00 00 00 mov $0x14,%rax 15ad: 49 89 ca mov %rcx,%r10 15b0: 0f 05 syscall 15b2: c3 retq 00000000000015b3 <chdir>: SYSCALL(chdir) 15b3: 48 c7 c0 09 00 00 00 mov $0x9,%rax 15ba: 49 89 ca mov %rcx,%r10 15bd: 0f 05 syscall 15bf: c3 retq 00000000000015c0 <dup>: SYSCALL(dup) 15c0: 48 c7 c0 0a 00 00 00 mov $0xa,%rax 15c7: 49 89 ca mov %rcx,%r10 15ca: 0f 05 syscall 15cc: c3 retq 00000000000015cd <getpid>: SYSCALL(getpid) 15cd: 48 c7 c0 0b 00 00 00 mov $0xb,%rax 15d4: 49 89 ca mov %rcx,%r10 15d7: 0f 05 syscall 15d9: c3 retq 00000000000015da <sbrk>: SYSCALL(sbrk) 15da: 48 c7 c0 0c 00 00 00 mov $0xc,%rax 15e1: 49 89 ca mov %rcx,%r10 15e4: 0f 05 syscall 15e6: c3 retq 00000000000015e7 <sleep>: SYSCALL(sleep) 15e7: 48 c7 c0 0d 00 00 00 mov $0xd,%rax 15ee: 49 89 ca mov %rcx,%r10 15f1: 0f 05 syscall 15f3: c3 retq 00000000000015f4 <uptime>: SYSCALL(uptime) 15f4: 48 c7 c0 0e 00 00 00 mov $0xe,%rax 15fb: 49 89 ca mov %rcx,%r10 15fe: 0f 05 syscall 1600: c3 retq 0000000000001601 <dedup>: SYSCALL(dedup) 1601: 48 c7 c0 16 00 00 00 mov $0x16,%rax 1608: 49 89 ca mov %rcx,%r10 160b: 0f 05 syscall 160d: c3 retq 000000000000160e <freepages>: SYSCALL(freepages) 160e: 48 c7 c0 17 00 00 00 mov $0x17,%rax 1615: 49 89 ca mov %rcx,%r10 1618: 0f 05 syscall 161a: c3 retq 000000000000161b <putc>: #include <stdarg.h> static void putc(int fd, char c) { 161b: f3 0f 1e fa endbr64 161f: 55 push %rbp 1620: 48 89 e5 mov %rsp,%rbp 1623: 48 83 ec 10 sub $0x10,%rsp 1627: 89 7d fc mov %edi,-0x4(%rbp) 162a: 89 f0 mov %esi,%eax 162c: 88 45 f8 mov %al,-0x8(%rbp) write(fd, &c, 1); 162f: 48 8d 4d f8 lea -0x8(%rbp),%rcx 1633: 8b 45 fc mov -0x4(%rbp),%eax 1636: ba 01 00 00 00 mov $0x1,%edx 163b: 48 89 ce mov %rcx,%rsi 163e: 89 c7 mov %eax,%edi 1640: 48 b8 31 15 00 00 00 movabs $0x1531,%rax 1647: 00 00 00 164a: ff d0 callq *%rax } 164c: 90 nop 164d: c9 leaveq 164e: c3 retq 000000000000164f <print_x64>: static char digits[] = "0123456789abcdef"; static void print_x64(int fd, addr_t x) { 164f: f3 0f 1e fa endbr64 1653: 55 push %rbp 1654: 48 89 e5 mov %rsp,%rbp 1657: 48 83 ec 20 sub $0x20,%rsp 165b: 89 7d ec mov %edi,-0x14(%rbp) 165e: 48 89 75 e0 mov %rsi,-0x20(%rbp) int i; for (i = 0; i < (sizeof(addr_t) * 2); i++, x <<= 4) 1662: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) 1669: eb 35 jmp 16a0 <print_x64+0x51> putc(fd, digits[x >> (sizeof(addr_t) * 8 - 4)]); 166b: 48 8b 45 e0 mov -0x20(%rbp),%rax 166f: 48 c1 e8 3c shr $0x3c,%rax 1673: 48 ba a0 22 00 00 00 movabs $0x22a0,%rdx 167a: 00 00 00 167d: 0f b6 04 02 movzbl (%rdx,%rax,1),%eax 1681: 0f be d0 movsbl %al,%edx 1684: 8b 45 ec mov -0x14(%rbp),%eax 1687: 89 d6 mov %edx,%esi 1689: 89 c7 mov %eax,%edi 168b: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 1692: 00 00 00 1695: ff d0 callq *%rax for (i = 0; i < (sizeof(addr_t) * 2); i++, x <<= 4) 1697: 83 45 fc 01 addl $0x1,-0x4(%rbp) 169b: 48 c1 65 e0 04 shlq $0x4,-0x20(%rbp) 16a0: 8b 45 fc mov -0x4(%rbp),%eax 16a3: 83 f8 0f cmp $0xf,%eax 16a6: 76 c3 jbe 166b <print_x64+0x1c> } 16a8: 90 nop 16a9: 90 nop 16aa: c9 leaveq 16ab: c3 retq 00000000000016ac <print_x32>: static void print_x32(int fd, uint x) { 16ac: f3 0f 1e fa endbr64 16b0: 55 push %rbp 16b1: 48 89 e5 mov %rsp,%rbp 16b4: 48 83 ec 20 sub $0x20,%rsp 16b8: 89 7d ec mov %edi,-0x14(%rbp) 16bb: 89 75 e8 mov %esi,-0x18(%rbp) int i; for (i = 0; i < (sizeof(uint) * 2); i++, x <<= 4) 16be: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) 16c5: eb 36 jmp 16fd <print_x32+0x51> putc(fd, digits[x >> (sizeof(uint) * 8 - 4)]); 16c7: 8b 45 e8 mov -0x18(%rbp),%eax 16ca: c1 e8 1c shr $0x1c,%eax 16cd: 89 c2 mov %eax,%edx 16cf: 48 b8 a0 22 00 00 00 movabs $0x22a0,%rax 16d6: 00 00 00 16d9: 89 d2 mov %edx,%edx 16db: 0f b6 04 10 movzbl (%rax,%rdx,1),%eax 16df: 0f be d0 movsbl %al,%edx 16e2: 8b 45 ec mov -0x14(%rbp),%eax 16e5: 89 d6 mov %edx,%esi 16e7: 89 c7 mov %eax,%edi 16e9: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 16f0: 00 00 00 16f3: ff d0 callq *%rax for (i = 0; i < (sizeof(uint) * 2); i++, x <<= 4) 16f5: 83 45 fc 01 addl $0x1,-0x4(%rbp) 16f9: c1 65 e8 04 shll $0x4,-0x18(%rbp) 16fd: 8b 45 fc mov -0x4(%rbp),%eax 1700: 83 f8 07 cmp $0x7,%eax 1703: 76 c2 jbe 16c7 <print_x32+0x1b> } 1705: 90 nop 1706: 90 nop 1707: c9 leaveq 1708: c3 retq 0000000000001709 <print_d>: static void print_d(int fd, int v) { 1709: f3 0f 1e fa endbr64 170d: 55 push %rbp 170e: 48 89 e5 mov %rsp,%rbp 1711: 48 83 ec 30 sub $0x30,%rsp 1715: 89 7d dc mov %edi,-0x24(%rbp) 1718: 89 75 d8 mov %esi,-0x28(%rbp) char buf[16]; int64 x = v; 171b: 8b 45 d8 mov -0x28(%rbp),%eax 171e: 48 98 cltq 1720: 48 89 45 f8 mov %rax,-0x8(%rbp) if (v < 0) 1724: 83 7d d8 00 cmpl $0x0,-0x28(%rbp) 1728: 79 04 jns 172e <print_d+0x25> x = -x; 172a: 48 f7 5d f8 negq -0x8(%rbp) int i = 0; 172e: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%rbp) do { buf[i++] = digits[x % 10]; 1735: 48 8b 4d f8 mov -0x8(%rbp),%rcx 1739: 48 ba 67 66 66 66 66 movabs $0x6666666666666667,%rdx 1740: 66 66 66 1743: 48 89 c8 mov %rcx,%rax 1746: 48 f7 ea imul %rdx 1749: 48 c1 fa 02 sar $0x2,%rdx 174d: 48 89 c8 mov %rcx,%rax 1750: 48 c1 f8 3f sar $0x3f,%rax 1754: 48 29 c2 sub %rax,%rdx 1757: 48 89 d0 mov %rdx,%rax 175a: 48 c1 e0 02 shl $0x2,%rax 175e: 48 01 d0 add %rdx,%rax 1761: 48 01 c0 add %rax,%rax 1764: 48 29 c1 sub %rax,%rcx 1767: 48 89 ca mov %rcx,%rdx 176a: 8b 45 f4 mov -0xc(%rbp),%eax 176d: 8d 48 01 lea 0x1(%rax),%ecx 1770: 89 4d f4 mov %ecx,-0xc(%rbp) 1773: 48 b9 a0 22 00 00 00 movabs $0x22a0,%rcx 177a: 00 00 00 177d: 0f b6 14 11 movzbl (%rcx,%rdx,1),%edx 1781: 48 98 cltq 1783: 88 54 05 e0 mov %dl,-0x20(%rbp,%rax,1) x /= 10; 1787: 48 8b 4d f8 mov -0x8(%rbp),%rcx 178b: 48 ba 67 66 66 66 66 movabs $0x6666666666666667,%rdx 1792: 66 66 66 1795: 48 89 c8 mov %rcx,%rax 1798: 48 f7 ea imul %rdx 179b: 48 c1 fa 02 sar $0x2,%rdx 179f: 48 89 c8 mov %rcx,%rax 17a2: 48 c1 f8 3f sar $0x3f,%rax 17a6: 48 29 c2 sub %rax,%rdx 17a9: 48 89 d0 mov %rdx,%rax 17ac: 48 89 45 f8 mov %rax,-0x8(%rbp) } while(x != 0); 17b0: 48 83 7d f8 00 cmpq $0x0,-0x8(%rbp) 17b5: 0f 85 7a ff ff ff jne 1735 <print_d+0x2c> if (v < 0) 17bb: 83 7d d8 00 cmpl $0x0,-0x28(%rbp) 17bf: 79 32 jns 17f3 <print_d+0xea> buf[i++] = '-'; 17c1: 8b 45 f4 mov -0xc(%rbp),%eax 17c4: 8d 50 01 lea 0x1(%rax),%edx 17c7: 89 55 f4 mov %edx,-0xc(%rbp) 17ca: 48 98 cltq 17cc: c6 44 05 e0 2d movb $0x2d,-0x20(%rbp,%rax,1) while (--i >= 0) 17d1: eb 20 jmp 17f3 <print_d+0xea> putc(fd, buf[i]); 17d3: 8b 45 f4 mov -0xc(%rbp),%eax 17d6: 48 98 cltq 17d8: 0f b6 44 05 e0 movzbl -0x20(%rbp,%rax,1),%eax 17dd: 0f be d0 movsbl %al,%edx 17e0: 8b 45 dc mov -0x24(%rbp),%eax 17e3: 89 d6 mov %edx,%esi 17e5: 89 c7 mov %eax,%edi 17e7: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 17ee: 00 00 00 17f1: ff d0 callq *%rax while (--i >= 0) 17f3: 83 6d f4 01 subl $0x1,-0xc(%rbp) 17f7: 83 7d f4 00 cmpl $0x0,-0xc(%rbp) 17fb: 79 d6 jns 17d3 <print_d+0xca> } 17fd: 90 nop 17fe: 90 nop 17ff: c9 leaveq 1800: c3 retq 0000000000001801 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 1801: f3 0f 1e fa endbr64 1805: 55 push %rbp 1806: 48 89 e5 mov %rsp,%rbp 1809: 48 81 ec f0 00 00 00 sub $0xf0,%rsp 1810: 89 bd 1c ff ff ff mov %edi,-0xe4(%rbp) 1816: 48 89 b5 10 ff ff ff mov %rsi,-0xf0(%rbp) 181d: 48 89 95 60 ff ff ff mov %rdx,-0xa0(%rbp) 1824: 48 89 8d 68 ff ff ff mov %rcx,-0x98(%rbp) 182b: 4c 89 85 70 ff ff ff mov %r8,-0x90(%rbp) 1832: 4c 89 8d 78 ff ff ff mov %r9,-0x88(%rbp) 1839: 84 c0 test %al,%al 183b: 74 20 je 185d <printf+0x5c> 183d: 0f 29 45 80 movaps %xmm0,-0x80(%rbp) 1841: 0f 29 4d 90 movaps %xmm1,-0x70(%rbp) 1845: 0f 29 55 a0 movaps %xmm2,-0x60(%rbp) 1849: 0f 29 5d b0 movaps %xmm3,-0x50(%rbp) 184d: 0f 29 65 c0 movaps %xmm4,-0x40(%rbp) 1851: 0f 29 6d d0 movaps %xmm5,-0x30(%rbp) 1855: 0f 29 75 e0 movaps %xmm6,-0x20(%rbp) 1859: 0f 29 7d f0 movaps %xmm7,-0x10(%rbp) va_list ap; int i, c; char *s; va_start(ap, fmt); 185d: c7 85 20 ff ff ff 10 movl $0x10,-0xe0(%rbp) 1864: 00 00 00 1867: c7 85 24 ff ff ff 30 movl $0x30,-0xdc(%rbp) 186e: 00 00 00 1871: 48 8d 45 10 lea 0x10(%rbp),%rax 1875: 48 89 85 28 ff ff ff mov %rax,-0xd8(%rbp) 187c: 48 8d 85 50 ff ff ff lea -0xb0(%rbp),%rax 1883: 48 89 85 30 ff ff ff mov %rax,-0xd0(%rbp) for (i = 0; (c = fmt[i] & 0xff) != 0; i++) { 188a: c7 85 4c ff ff ff 00 movl $0x0,-0xb4(%rbp) 1891: 00 00 00 1894: e9 41 03 00 00 jmpq 1bda <printf+0x3d9> if (c != '%') { 1899: 83 bd 3c ff ff ff 25 cmpl $0x25,-0xc4(%rbp) 18a0: 74 24 je 18c6 <printf+0xc5> putc(fd, c); 18a2: 8b 85 3c ff ff ff mov -0xc4(%rbp),%eax 18a8: 0f be d0 movsbl %al,%edx 18ab: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 18b1: 89 d6 mov %edx,%esi 18b3: 89 c7 mov %eax,%edi 18b5: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 18bc: 00 00 00 18bf: ff d0 callq *%rax continue; 18c1: e9 0d 03 00 00 jmpq 1bd3 <printf+0x3d2> } c = fmt[++i] & 0xff; 18c6: 83 85 4c ff ff ff 01 addl $0x1,-0xb4(%rbp) 18cd: 8b 85 4c ff ff ff mov -0xb4(%rbp),%eax 18d3: 48 63 d0 movslq %eax,%rdx 18d6: 48 8b 85 10 ff ff ff mov -0xf0(%rbp),%rax 18dd: 48 01 d0 add %rdx,%rax 18e0: 0f b6 00 movzbl (%rax),%eax 18e3: 0f be c0 movsbl %al,%eax 18e6: 25 ff 00 00 00 and $0xff,%eax 18eb: 89 85 3c ff ff ff mov %eax,-0xc4(%rbp) if (c == 0) 18f1: 83 bd 3c ff ff ff 00 cmpl $0x0,-0xc4(%rbp) 18f8: 0f 84 0f 03 00 00 je 1c0d <printf+0x40c> break; switch(c) { 18fe: 83 bd 3c ff ff ff 25 cmpl $0x25,-0xc4(%rbp) 1905: 0f 84 74 02 00 00 je 1b7f <printf+0x37e> 190b: 83 bd 3c ff ff ff 25 cmpl $0x25,-0xc4(%rbp) 1912: 0f 8c 82 02 00 00 jl 1b9a <printf+0x399> 1918: 83 bd 3c ff ff ff 78 cmpl $0x78,-0xc4(%rbp) 191f: 0f 8f 75 02 00 00 jg 1b9a <printf+0x399> 1925: 83 bd 3c ff ff ff 63 cmpl $0x63,-0xc4(%rbp) 192c: 0f 8c 68 02 00 00 jl 1b9a <printf+0x399> 1932: 8b 85 3c ff ff ff mov -0xc4(%rbp),%eax 1938: 83 e8 63 sub $0x63,%eax 193b: 83 f8 15 cmp $0x15,%eax 193e: 0f 87 56 02 00 00 ja 1b9a <printf+0x399> 1944: 89 c0 mov %eax,%eax 1946: 48 8d 14 c5 00 00 00 lea 0x0(,%rax,8),%rdx 194d: 00 194e: 48 b8 58 1f 00 00 00 movabs $0x1f58,%rax 1955: 00 00 00 1958: 48 01 d0 add %rdx,%rax 195b: 48 8b 00 mov (%rax),%rax 195e: 3e ff e0 notrack jmpq *%rax case 'c': putc(fd, va_arg(ap, int)); 1961: 8b 85 20 ff ff ff mov -0xe0(%rbp),%eax 1967: 83 f8 2f cmp $0x2f,%eax 196a: 77 23 ja 198f <printf+0x18e> 196c: 48 8b 85 30 ff ff ff mov -0xd0(%rbp),%rax 1973: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1979: 89 d2 mov %edx,%edx 197b: 48 01 d0 add %rdx,%rax 197e: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1984: 83 c2 08 add $0x8,%edx 1987: 89 95 20 ff ff ff mov %edx,-0xe0(%rbp) 198d: eb 12 jmp 19a1 <printf+0x1a0> 198f: 48 8b 85 28 ff ff ff mov -0xd8(%rbp),%rax 1996: 48 8d 50 08 lea 0x8(%rax),%rdx 199a: 48 89 95 28 ff ff ff mov %rdx,-0xd8(%rbp) 19a1: 8b 00 mov (%rax),%eax 19a3: 0f be d0 movsbl %al,%edx 19a6: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 19ac: 89 d6 mov %edx,%esi 19ae: 89 c7 mov %eax,%edi 19b0: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 19b7: 00 00 00 19ba: ff d0 callq *%rax break; 19bc: e9 12 02 00 00 jmpq 1bd3 <printf+0x3d2> case 'd': print_d(fd, va_arg(ap, int)); 19c1: 8b 85 20 ff ff ff mov -0xe0(%rbp),%eax 19c7: 83 f8 2f cmp $0x2f,%eax 19ca: 77 23 ja 19ef <printf+0x1ee> 19cc: 48 8b 85 30 ff ff ff mov -0xd0(%rbp),%rax 19d3: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 19d9: 89 d2 mov %edx,%edx 19db: 48 01 d0 add %rdx,%rax 19de: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 19e4: 83 c2 08 add $0x8,%edx 19e7: 89 95 20 ff ff ff mov %edx,-0xe0(%rbp) 19ed: eb 12 jmp 1a01 <printf+0x200> 19ef: 48 8b 85 28 ff ff ff mov -0xd8(%rbp),%rax 19f6: 48 8d 50 08 lea 0x8(%rax),%rdx 19fa: 48 89 95 28 ff ff ff mov %rdx,-0xd8(%rbp) 1a01: 8b 10 mov (%rax),%edx 1a03: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1a09: 89 d6 mov %edx,%esi 1a0b: 89 c7 mov %eax,%edi 1a0d: 48 b8 09 17 00 00 00 movabs $0x1709,%rax 1a14: 00 00 00 1a17: ff d0 callq *%rax break; 1a19: e9 b5 01 00 00 jmpq 1bd3 <printf+0x3d2> case 'x': print_x32(fd, va_arg(ap, uint)); 1a1e: 8b 85 20 ff ff ff mov -0xe0(%rbp),%eax 1a24: 83 f8 2f cmp $0x2f,%eax 1a27: 77 23 ja 1a4c <printf+0x24b> 1a29: 48 8b 85 30 ff ff ff mov -0xd0(%rbp),%rax 1a30: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1a36: 89 d2 mov %edx,%edx 1a38: 48 01 d0 add %rdx,%rax 1a3b: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1a41: 83 c2 08 add $0x8,%edx 1a44: 89 95 20 ff ff ff mov %edx,-0xe0(%rbp) 1a4a: eb 12 jmp 1a5e <printf+0x25d> 1a4c: 48 8b 85 28 ff ff ff mov -0xd8(%rbp),%rax 1a53: 48 8d 50 08 lea 0x8(%rax),%rdx 1a57: 48 89 95 28 ff ff ff mov %rdx,-0xd8(%rbp) 1a5e: 8b 10 mov (%rax),%edx 1a60: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1a66: 89 d6 mov %edx,%esi 1a68: 89 c7 mov %eax,%edi 1a6a: 48 b8 ac 16 00 00 00 movabs $0x16ac,%rax 1a71: 00 00 00 1a74: ff d0 callq *%rax break; 1a76: e9 58 01 00 00 jmpq 1bd3 <printf+0x3d2> case 'p': print_x64(fd, va_arg(ap, addr_t)); 1a7b: 8b 85 20 ff ff ff mov -0xe0(%rbp),%eax 1a81: 83 f8 2f cmp $0x2f,%eax 1a84: 77 23 ja 1aa9 <printf+0x2a8> 1a86: 48 8b 85 30 ff ff ff mov -0xd0(%rbp),%rax 1a8d: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1a93: 89 d2 mov %edx,%edx 1a95: 48 01 d0 add %rdx,%rax 1a98: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1a9e: 83 c2 08 add $0x8,%edx 1aa1: 89 95 20 ff ff ff mov %edx,-0xe0(%rbp) 1aa7: eb 12 jmp 1abb <printf+0x2ba> 1aa9: 48 8b 85 28 ff ff ff mov -0xd8(%rbp),%rax 1ab0: 48 8d 50 08 lea 0x8(%rax),%rdx 1ab4: 48 89 95 28 ff ff ff mov %rdx,-0xd8(%rbp) 1abb: 48 8b 10 mov (%rax),%rdx 1abe: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1ac4: 48 89 d6 mov %rdx,%rsi 1ac7: 89 c7 mov %eax,%edi 1ac9: 48 b8 4f 16 00 00 00 movabs $0x164f,%rax 1ad0: 00 00 00 1ad3: ff d0 callq *%rax break; 1ad5: e9 f9 00 00 00 jmpq 1bd3 <printf+0x3d2> case 's': if ((s = va_arg(ap, char*)) == 0) 1ada: 8b 85 20 ff ff ff mov -0xe0(%rbp),%eax 1ae0: 83 f8 2f cmp $0x2f,%eax 1ae3: 77 23 ja 1b08 <printf+0x307> 1ae5: 48 8b 85 30 ff ff ff mov -0xd0(%rbp),%rax 1aec: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1af2: 89 d2 mov %edx,%edx 1af4: 48 01 d0 add %rdx,%rax 1af7: 8b 95 20 ff ff ff mov -0xe0(%rbp),%edx 1afd: 83 c2 08 add $0x8,%edx 1b00: 89 95 20 ff ff ff mov %edx,-0xe0(%rbp) 1b06: eb 12 jmp 1b1a <printf+0x319> 1b08: 48 8b 85 28 ff ff ff mov -0xd8(%rbp),%rax 1b0f: 48 8d 50 08 lea 0x8(%rax),%rdx 1b13: 48 89 95 28 ff ff ff mov %rdx,-0xd8(%rbp) 1b1a: 48 8b 00 mov (%rax),%rax 1b1d: 48 89 85 40 ff ff ff mov %rax,-0xc0(%rbp) 1b24: 48 83 bd 40 ff ff ff cmpq $0x0,-0xc0(%rbp) 1b2b: 00 1b2c: 75 41 jne 1b6f <printf+0x36e> s = "(null)"; 1b2e: 48 b8 50 1f 00 00 00 movabs $0x1f50,%rax 1b35: 00 00 00 1b38: 48 89 85 40 ff ff ff mov %rax,-0xc0(%rbp) while (*s) 1b3f: eb 2e jmp 1b6f <printf+0x36e> putc(fd, *(s++)); 1b41: 48 8b 85 40 ff ff ff mov -0xc0(%rbp),%rax 1b48: 48 8d 50 01 lea 0x1(%rax),%rdx 1b4c: 48 89 95 40 ff ff ff mov %rdx,-0xc0(%rbp) 1b53: 0f b6 00 movzbl (%rax),%eax 1b56: 0f be d0 movsbl %al,%edx 1b59: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1b5f: 89 d6 mov %edx,%esi 1b61: 89 c7 mov %eax,%edi 1b63: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 1b6a: 00 00 00 1b6d: ff d0 callq *%rax while (*s) 1b6f: 48 8b 85 40 ff ff ff mov -0xc0(%rbp),%rax 1b76: 0f b6 00 movzbl (%rax),%eax 1b79: 84 c0 test %al,%al 1b7b: 75 c4 jne 1b41 <printf+0x340> break; 1b7d: eb 54 jmp 1bd3 <printf+0x3d2> case '%': putc(fd, '%'); 1b7f: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1b85: be 25 00 00 00 mov $0x25,%esi 1b8a: 89 c7 mov %eax,%edi 1b8c: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 1b93: 00 00 00 1b96: ff d0 callq *%rax break; 1b98: eb 39 jmp 1bd3 <printf+0x3d2> default: // Print unknown % sequence to draw attention. putc(fd, '%'); 1b9a: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1ba0: be 25 00 00 00 mov $0x25,%esi 1ba5: 89 c7 mov %eax,%edi 1ba7: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 1bae: 00 00 00 1bb1: ff d0 callq *%rax putc(fd, c); 1bb3: 8b 85 3c ff ff ff mov -0xc4(%rbp),%eax 1bb9: 0f be d0 movsbl %al,%edx 1bbc: 8b 85 1c ff ff ff mov -0xe4(%rbp),%eax 1bc2: 89 d6 mov %edx,%esi 1bc4: 89 c7 mov %eax,%edi 1bc6: 48 b8 1b 16 00 00 00 movabs $0x161b,%rax 1bcd: 00 00 00 1bd0: ff d0 callq *%rax break; 1bd2: 90 nop for (i = 0; (c = fmt[i] & 0xff) != 0; i++) { 1bd3: 83 85 4c ff ff ff 01 addl $0x1,-0xb4(%rbp) 1bda: 8b 85 4c ff ff ff mov -0xb4(%rbp),%eax 1be0: 48 63 d0 movslq %eax,%rdx 1be3: 48 8b 85 10 ff ff ff mov -0xf0(%rbp),%rax 1bea: 48 01 d0 add %rdx,%rax 1bed: 0f b6 00 movzbl (%rax),%eax 1bf0: 0f be c0 movsbl %al,%eax 1bf3: 25 ff 00 00 00 and $0xff,%eax 1bf8: 89 85 3c ff ff ff mov %eax,-0xc4(%rbp) 1bfe: 83 bd 3c ff ff ff 00 cmpl $0x0,-0xc4(%rbp) 1c05: 0f 85 8e fc ff ff jne 1899 <printf+0x98> } } } 1c0b: eb 01 jmp 1c0e <printf+0x40d> break; 1c0d: 90 nop } 1c0e: 90 nop 1c0f: c9 leaveq 1c10: c3 retq 0000000000001c11 <free>: static Header base; static Header *freep; void free(void *ap) { 1c11: f3 0f 1e fa endbr64 1c15: 55 push %rbp 1c16: 48 89 e5 mov %rsp,%rbp 1c19: 48 83 ec 18 sub $0x18,%rsp 1c1d: 48 89 7d e8 mov %rdi,-0x18(%rbp) Header *bp, *p; bp = (Header*)ap - 1; 1c21: 48 8b 45 e8 mov -0x18(%rbp),%rax 1c25: 48 83 e8 10 sub $0x10,%rax 1c29: 48 89 45 f0 mov %rax,-0x10(%rbp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1c2d: 48 b8 d0 24 00 00 00 movabs $0x24d0,%rax 1c34: 00 00 00 1c37: 48 8b 00 mov (%rax),%rax 1c3a: 48 89 45 f8 mov %rax,-0x8(%rbp) 1c3e: eb 2f jmp 1c6f <free+0x5e> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1c40: 48 8b 45 f8 mov -0x8(%rbp),%rax 1c44: 48 8b 00 mov (%rax),%rax 1c47: 48 39 45 f8 cmp %rax,-0x8(%rbp) 1c4b: 72 17 jb 1c64 <free+0x53> 1c4d: 48 8b 45 f0 mov -0x10(%rbp),%rax 1c51: 48 3b 45 f8 cmp -0x8(%rbp),%rax 1c55: 77 2f ja 1c86 <free+0x75> 1c57: 48 8b 45 f8 mov -0x8(%rbp),%rax 1c5b: 48 8b 00 mov (%rax),%rax 1c5e: 48 39 45 f0 cmp %rax,-0x10(%rbp) 1c62: 72 22 jb 1c86 <free+0x75> for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1c64: 48 8b 45 f8 mov -0x8(%rbp),%rax 1c68: 48 8b 00 mov (%rax),%rax 1c6b: 48 89 45 f8 mov %rax,-0x8(%rbp) 1c6f: 48 8b 45 f0 mov -0x10(%rbp),%rax 1c73: 48 3b 45 f8 cmp -0x8(%rbp),%rax 1c77: 76 c7 jbe 1c40 <free+0x2f> 1c79: 48 8b 45 f8 mov -0x8(%rbp),%rax 1c7d: 48 8b 00 mov (%rax),%rax 1c80: 48 39 45 f0 cmp %rax,-0x10(%rbp) 1c84: 73 ba jae 1c40 <free+0x2f> break; if(bp + bp->s.size == p->s.ptr){ 1c86: 48 8b 45 f0 mov -0x10(%rbp),%rax 1c8a: 8b 40 08 mov 0x8(%rax),%eax 1c8d: 89 c0 mov %eax,%eax 1c8f: 48 c1 e0 04 shl $0x4,%rax 1c93: 48 89 c2 mov %rax,%rdx 1c96: 48 8b 45 f0 mov -0x10(%rbp),%rax 1c9a: 48 01 c2 add %rax,%rdx 1c9d: 48 8b 45 f8 mov -0x8(%rbp),%rax 1ca1: 48 8b 00 mov (%rax),%rax 1ca4: 48 39 c2 cmp %rax,%rdx 1ca7: 75 2d jne 1cd6 <free+0xc5> bp->s.size += p->s.ptr->s.size; 1ca9: 48 8b 45 f0 mov -0x10(%rbp),%rax 1cad: 8b 50 08 mov 0x8(%rax),%edx 1cb0: 48 8b 45 f8 mov -0x8(%rbp),%rax 1cb4: 48 8b 00 mov (%rax),%rax 1cb7: 8b 40 08 mov 0x8(%rax),%eax 1cba: 01 c2 add %eax,%edx 1cbc: 48 8b 45 f0 mov -0x10(%rbp),%rax 1cc0: 89 50 08 mov %edx,0x8(%rax) bp->s.ptr = p->s.ptr->s.ptr; 1cc3: 48 8b 45 f8 mov -0x8(%rbp),%rax 1cc7: 48 8b 00 mov (%rax),%rax 1cca: 48 8b 10 mov (%rax),%rdx 1ccd: 48 8b 45 f0 mov -0x10(%rbp),%rax 1cd1: 48 89 10 mov %rdx,(%rax) 1cd4: eb 0e jmp 1ce4 <free+0xd3> } else bp->s.ptr = p->s.ptr; 1cd6: 48 8b 45 f8 mov -0x8(%rbp),%rax 1cda: 48 8b 10 mov (%rax),%rdx 1cdd: 48 8b 45 f0 mov -0x10(%rbp),%rax 1ce1: 48 89 10 mov %rdx,(%rax) if(p + p->s.size == bp){ 1ce4: 48 8b 45 f8 mov -0x8(%rbp),%rax 1ce8: 8b 40 08 mov 0x8(%rax),%eax 1ceb: 89 c0 mov %eax,%eax 1ced: 48 c1 e0 04 shl $0x4,%rax 1cf1: 48 89 c2 mov %rax,%rdx 1cf4: 48 8b 45 f8 mov -0x8(%rbp),%rax 1cf8: 48 01 d0 add %rdx,%rax 1cfb: 48 39 45 f0 cmp %rax,-0x10(%rbp) 1cff: 75 27 jne 1d28 <free+0x117> p->s.size += bp->s.size; 1d01: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d05: 8b 50 08 mov 0x8(%rax),%edx 1d08: 48 8b 45 f0 mov -0x10(%rbp),%rax 1d0c: 8b 40 08 mov 0x8(%rax),%eax 1d0f: 01 c2 add %eax,%edx 1d11: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d15: 89 50 08 mov %edx,0x8(%rax) p->s.ptr = bp->s.ptr; 1d18: 48 8b 45 f0 mov -0x10(%rbp),%rax 1d1c: 48 8b 10 mov (%rax),%rdx 1d1f: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d23: 48 89 10 mov %rdx,(%rax) 1d26: eb 0b jmp 1d33 <free+0x122> } else p->s.ptr = bp; 1d28: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d2c: 48 8b 55 f0 mov -0x10(%rbp),%rdx 1d30: 48 89 10 mov %rdx,(%rax) freep = p; 1d33: 48 ba d0 24 00 00 00 movabs $0x24d0,%rdx 1d3a: 00 00 00 1d3d: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d41: 48 89 02 mov %rax,(%rdx) } 1d44: 90 nop 1d45: c9 leaveq 1d46: c3 retq 0000000000001d47 <morecore>: static Header* morecore(uint nu) { 1d47: f3 0f 1e fa endbr64 1d4b: 55 push %rbp 1d4c: 48 89 e5 mov %rsp,%rbp 1d4f: 48 83 ec 20 sub $0x20,%rsp 1d53: 89 7d ec mov %edi,-0x14(%rbp) char *p; Header *hp; if(nu < 4096) 1d56: 81 7d ec ff 0f 00 00 cmpl $0xfff,-0x14(%rbp) 1d5d: 77 07 ja 1d66 <morecore+0x1f> nu = 4096; 1d5f: c7 45 ec 00 10 00 00 movl $0x1000,-0x14(%rbp) p = sbrk(nu * sizeof(Header)); 1d66: 8b 45 ec mov -0x14(%rbp),%eax 1d69: 48 c1 e0 04 shl $0x4,%rax 1d6d: 48 89 c7 mov %rax,%rdi 1d70: 48 b8 da 15 00 00 00 movabs $0x15da,%rax 1d77: 00 00 00 1d7a: ff d0 callq *%rax 1d7c: 48 89 45 f8 mov %rax,-0x8(%rbp) if(p == (char*)-1) 1d80: 48 83 7d f8 ff cmpq $0xffffffffffffffff,-0x8(%rbp) 1d85: 75 07 jne 1d8e <morecore+0x47> return 0; 1d87: b8 00 00 00 00 mov $0x0,%eax 1d8c: eb 36 jmp 1dc4 <morecore+0x7d> hp = (Header*)p; 1d8e: 48 8b 45 f8 mov -0x8(%rbp),%rax 1d92: 48 89 45 f0 mov %rax,-0x10(%rbp) hp->s.size = nu; 1d96: 48 8b 45 f0 mov -0x10(%rbp),%rax 1d9a: 8b 55 ec mov -0x14(%rbp),%edx 1d9d: 89 50 08 mov %edx,0x8(%rax) free((void*)(hp + 1)); 1da0: 48 8b 45 f0 mov -0x10(%rbp),%rax 1da4: 48 83 c0 10 add $0x10,%rax 1da8: 48 89 c7 mov %rax,%rdi 1dab: 48 b8 11 1c 00 00 00 movabs $0x1c11,%rax 1db2: 00 00 00 1db5: ff d0 callq *%rax return freep; 1db7: 48 b8 d0 24 00 00 00 movabs $0x24d0,%rax 1dbe: 00 00 00 1dc1: 48 8b 00 mov (%rax),%rax } 1dc4: c9 leaveq 1dc5: c3 retq 0000000000001dc6 <malloc>: void* malloc(uint nbytes) { 1dc6: f3 0f 1e fa endbr64 1dca: 55 push %rbp 1dcb: 48 89 e5 mov %rsp,%rbp 1dce: 48 83 ec 30 sub $0x30,%rsp 1dd2: 89 7d dc mov %edi,-0x24(%rbp) Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 1dd5: 8b 45 dc mov -0x24(%rbp),%eax 1dd8: 48 83 c0 0f add $0xf,%rax 1ddc: 48 c1 e8 04 shr $0x4,%rax 1de0: 83 c0 01 add $0x1,%eax 1de3: 89 45 ec mov %eax,-0x14(%rbp) if((prevp = freep) == 0){ 1de6: 48 b8 d0 24 00 00 00 movabs $0x24d0,%rax 1ded: 00 00 00 1df0: 48 8b 00 mov (%rax),%rax 1df3: 48 89 45 f0 mov %rax,-0x10(%rbp) 1df7: 48 83 7d f0 00 cmpq $0x0,-0x10(%rbp) 1dfc: 75 4a jne 1e48 <malloc+0x82> base.s.ptr = freep = prevp = &base; 1dfe: 48 b8 c0 24 00 00 00 movabs $0x24c0,%rax 1e05: 00 00 00 1e08: 48 89 45 f0 mov %rax,-0x10(%rbp) 1e0c: 48 ba d0 24 00 00 00 movabs $0x24d0,%rdx 1e13: 00 00 00 1e16: 48 8b 45 f0 mov -0x10(%rbp),%rax 1e1a: 48 89 02 mov %rax,(%rdx) 1e1d: 48 b8 d0 24 00 00 00 movabs $0x24d0,%rax 1e24: 00 00 00 1e27: 48 8b 00 mov (%rax),%rax 1e2a: 48 ba c0 24 00 00 00 movabs $0x24c0,%rdx 1e31: 00 00 00 1e34: 48 89 02 mov %rax,(%rdx) base.s.size = 0; 1e37: 48 b8 c0 24 00 00 00 movabs $0x24c0,%rax 1e3e: 00 00 00 1e41: c7 40 08 00 00 00 00 movl $0x0,0x8(%rax) } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1e48: 48 8b 45 f0 mov -0x10(%rbp),%rax 1e4c: 48 8b 00 mov (%rax),%rax 1e4f: 48 89 45 f8 mov %rax,-0x8(%rbp) if(p->s.size >= nunits){ 1e53: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e57: 8b 40 08 mov 0x8(%rax),%eax 1e5a: 39 45 ec cmp %eax,-0x14(%rbp) 1e5d: 77 65 ja 1ec4 <malloc+0xfe> if(p->s.size == nunits) 1e5f: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e63: 8b 40 08 mov 0x8(%rax),%eax 1e66: 39 45 ec cmp %eax,-0x14(%rbp) 1e69: 75 10 jne 1e7b <malloc+0xb5> prevp->s.ptr = p->s.ptr; 1e6b: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e6f: 48 8b 10 mov (%rax),%rdx 1e72: 48 8b 45 f0 mov -0x10(%rbp),%rax 1e76: 48 89 10 mov %rdx,(%rax) 1e79: eb 2e jmp 1ea9 <malloc+0xe3> else { p->s.size -= nunits; 1e7b: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e7f: 8b 40 08 mov 0x8(%rax),%eax 1e82: 2b 45 ec sub -0x14(%rbp),%eax 1e85: 89 c2 mov %eax,%edx 1e87: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e8b: 89 50 08 mov %edx,0x8(%rax) p += p->s.size; 1e8e: 48 8b 45 f8 mov -0x8(%rbp),%rax 1e92: 8b 40 08 mov 0x8(%rax),%eax 1e95: 89 c0 mov %eax,%eax 1e97: 48 c1 e0 04 shl $0x4,%rax 1e9b: 48 01 45 f8 add %rax,-0x8(%rbp) p->s.size = nunits; 1e9f: 48 8b 45 f8 mov -0x8(%rbp),%rax 1ea3: 8b 55 ec mov -0x14(%rbp),%edx 1ea6: 89 50 08 mov %edx,0x8(%rax) } freep = prevp; 1ea9: 48 ba d0 24 00 00 00 movabs $0x24d0,%rdx 1eb0: 00 00 00 1eb3: 48 8b 45 f0 mov -0x10(%rbp),%rax 1eb7: 48 89 02 mov %rax,(%rdx) return (void*)(p + 1); 1eba: 48 8b 45 f8 mov -0x8(%rbp),%rax 1ebe: 48 83 c0 10 add $0x10,%rax 1ec2: eb 4e jmp 1f12 <malloc+0x14c> } if(p == freep) 1ec4: 48 b8 d0 24 00 00 00 movabs $0x24d0,%rax 1ecb: 00 00 00 1ece: 48 8b 00 mov (%rax),%rax 1ed1: 48 39 45 f8 cmp %rax,-0x8(%rbp) 1ed5: 75 23 jne 1efa <malloc+0x134> if((p = morecore(nunits)) == 0) 1ed7: 8b 45 ec mov -0x14(%rbp),%eax 1eda: 89 c7 mov %eax,%edi 1edc: 48 b8 47 1d 00 00 00 movabs $0x1d47,%rax 1ee3: 00 00 00 1ee6: ff d0 callq *%rax 1ee8: 48 89 45 f8 mov %rax,-0x8(%rbp) 1eec: 48 83 7d f8 00 cmpq $0x0,-0x8(%rbp) 1ef1: 75 07 jne 1efa <malloc+0x134> return 0; 1ef3: b8 00 00 00 00 mov $0x0,%eax 1ef8: eb 18 jmp 1f12 <malloc+0x14c> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1efa: 48 8b 45 f8 mov -0x8(%rbp),%rax 1efe: 48 89 45 f0 mov %rax,-0x10(%rbp) 1f02: 48 8b 45 f8 mov -0x8(%rbp),%rax 1f06: 48 8b 00 mov (%rax),%rax 1f09: 48 89 45 f8 mov %rax,-0x8(%rbp) if(p->s.size >= nunits){ 1f0d: e9 41 ff ff ff jmpq 1e53 <malloc+0x8d> } } 1f12: c9 leaveq 1f13: c3 retq
src/MLib/Matrix/Pow.agda
bch29/agda-matrices
0
12372
<reponame>bch29/agda-matrices open import MLib.Algebra.PropertyCode open import MLib.Algebra.PropertyCode.Structures module MLib.Matrix.Pow {c ℓ} (struct : Struct bimonoidCode c ℓ) where open import MLib.Prelude open import MLib.Matrix.Core open import MLib.Matrix.Equality struct open import MLib.Matrix.Mul struct open import MLib.Matrix.Plus struct open import MLib.Matrix.Bimonoid struct open FunctionProperties module _ {n} where open import MLib.Algebra.Operations (matrixStruct n) pow : Matrix S n n → ℕ → Matrix S n n pow M zero = 1● pow M (suc p) = M ⊗ pow M p pstar : Matrix S n n → ℕ → Matrix S n n pstar M zero = 0● pstar M (suc p) = 1● ⊕ M ⊗ pstar M p pstar′ : Matrix S n n → ℕ → Matrix S n n pstar′ M p = ∑[ q < p ] pow M (Fin.toℕ q) pstar′-unfold : ∀ {M : Matrix S n n} {p} → pstar′ M (suc p) ≈ 1● ⊕ M ⊗ pstar′ M p pstar′-unfold {M} {p} = begin pstar′ M (suc p) ≡⟨⟩ pow M (Fin.toℕ (zero {p})) ⊕ ∑[ q < p ] pow M (Fin.toℕ (suc q)) ≡⟨⟩ 1● ⊕ ∑[ q < p ] pow M (suc (Fin.toℕ q)) ≡⟨⟩ 1● ⊕ ∑[ q < p ] (M ⊗ pow M (Fin.toℕ q)) ≈⟨ ⊕-cong refl (sym (sumDistribˡ ⦃ {!!} ⦄ {p} M _)) ⟩ 1● ⊕ M ⊗ ∑[ q < p ] pow M (Fin.toℕ q) ≡⟨⟩ 1● ⊕ M ⊗ pstar′ M p ∎ where open EqReasoning setoid -- pstar-pstar′ : ∀ {M : Matrix S n n} {p} → pstar M p ≈ pstar′ M p -- pstar-pstar′ {p = zero} _ _ = S.refl -- pstar-pstar′ {M = M} {suc p} = -- begin -- ((1● ⊕ M) ⊗ pstar M p) ≈⟨ {!!} ⟩ -- pow M (Fin.toℕ (zero {p})) ⊕ (Table.foldr {n = p} _⊕_ 0● (tabulate (pow M ∘ Fin.toℕ ∘ suc))) ≡⟨⟩ -- pstar′ M (suc p) ∎ -- where open EqReasoning setoid
oeis/020/A020764.asm
neoneye/loda-programs
11
243435
<filename>oeis/020/A020764.asm ; A020764: Decimal expansion of 1/sqrt(7). ; Submitted by <NAME> ; 3,7,7,9,6,4,4,7,3,0,0,9,2,2,7,2,2,7,2,1,4,5,1,6,5,3,6,2,3,4,1,8,0,0,6,0,8,1,5,7,5,1,3,1,1,8,6,8,9,2,1,4,5,4,3,3,8,3,3,3,4,9,4,1,7,1,5,8,1,2,6,0,4,6,1,4,6,9,0,8,9,6,8,0,0,5,6,1,2,6,6,3,9,2,2,0,5,1,5,8 add $0,1 mov $3,$0 mul $3,4 lpb $3 add $1,$5 mov $2,$1 add $5,4 add $5,$1 add $1,$5 add $2,$1 mul $1,2 sub $3,1 lpe mov $4,10 pow $4,$0 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
ada-synchronous_task_control-edf.ads
mgrojo/adalib
15
11780
<reponame>mgrojo/adalib<filename>ada-synchronous_task_control-edf.ads -- Standard Ada library specification -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Ada.Synchronous_Task_Control.EDF is procedure Suspend_Until_True_And_Set_Deadline (S : in out Suspension_Object; TS : in Ada.Real_Time.Time_Span); end Ada.Synchronous_Task_Control.EDF;
archive/agda-3/src/Test/Thickandthin.agda
m0davis/oscar
0
9858
<reponame>m0davis/oscar open import Everything module Test.Thickandthin where module _ {x a b ℓb c ℓc} ⦃ _ : Thickandthin x a b ℓb c ℓc ⦄ where open Thickandthin ⦃ … ⦄ test-thin : 𝓽hin A B test-thin = thin test-check/thin=1 : 𝓬heck/thin=1 A B C _≈C_ test-check/thin=1 = check/thin=1 test-injectivity : ∀ {m : X} {x : A (⇑₀ m)} → 𝓶ap (_≈B_ on thin x) _≈B_ test-injectivity {x = x} = injectivity₂,₁ x
libsrc/_DEVELOPMENT/alloc/obstack/c/sdcc_iy/obstack_int_grow_callee.asm
meesokim/z88dk
0
247716
; void *obstack_int_grow_callee(struct obstack *ob, int data) SECTION code_alloc_obstack PUBLIC _obstack_int_grow_callee _obstack_int_grow_callee: pop af pop hl pop bc push af INCLUDE "alloc/obstack/z80/asm_obstack_int_grow.asm"
programs/oeis/168/A168300.asm
neoneye/loda
22
93231
<filename>programs/oeis/168/A168300.asm ; A168300: a(n) = 6*n - a(n-1) - 2 with a(1)=5. ; 5,5,11,11,17,17,23,23,29,29,35,35,41,41,47,47,53,53,59,59,65,65,71,71,77,77,83,83,89,89,95,95,101,101,107,107,113,113,119,119,125,125,131,131,137,137,143,143,149,149,155,155,161,161,167,167,173,173,179,179,185,185,191,191,197,197,203,203,209,209,215,215,221,221,227,227,233,233,239,239,245,245,251,251,257,257,263,263,269,269,275,275,281,281,287,287,293,293,299,299 div $0,2 mul $0,6 add $0,5
programs/oeis/035/A035340.asm
neoneye/loda
22
86419
<reponame>neoneye/loda ; A035340: 6th column of Wythoff array. ; 13,47,68,102,136,157,191,212,246,280,301,335,369,390,424,445,479,513,534,568,589,623,657,678,712,746,767,801,822,856,890,911,945,979,1000,1034,1055,1089,1123,1144,1178,1199,1233,1267,1288,1322,1356,1377,1411,1432,1466,1500,1521,1555,1576,1610,1644,1665,1699,1733,1754,1788,1809,1843,1877,1898,1932,1966,1987,2021,2042,2076,2110,2131,2165,2186,2220,2254,2275,2309,2343,2364,2398,2419,2453,2487,2508,2542,2576,2597,2631,2652,2686,2720,2741,2775,2796,2830,2864,2885 seq $0,134864 ; Wythoff BBB numbers. sub $0,3 seq $0,75317 ; Pair the odd numbers such that the k-th pair is (r, r+2k) where r is the smallest odd number not included earlier: (1,3),(5,9),(7,13),(11,19),(15,25),(17,29),(21,35),(23,39),(27,45),... This is the sequence of the first member of pairs. div $0,2 sub $0,3
tlsf/src/proof/model/tlsf-proof-model-context.adb
vasil-sd/ada-tlsf
3
28753
<filename>tlsf/src/proof/model/tlsf-proof-model-context.adb with System.Storage_Elements; with Ada.Containers.Formal_Hashed_Maps; package body TLSF.Proof.Model.Context With SPARK_Mode, Refined_State => (State => Block_Models) is package SSE renames System.Storage_Elements; package AC renames Ada.Containers; function Hash (Addr : System.Address) return AC.Hash_Type; package Map_Pkg is new Ada.Containers.Formal_Hashed_Maps (Key_Type => System.Address, Element_Type => MB.Formal_Model, Hash => Hash); Block_Models : Map_Pkg.Map (Capacity => 1000, Modulus => 777); function Hash (Addr : System.Address) return AC.Hash_Type is begin return AC.Hash_Type (SSE.To_Integer (Addr)); end Hash; --------------- -- Has_Model -- --------------- function Has_Model (Context : TC.Context) return Boolean with Refined_Post => Has_Model'Result = Map_Pkg.Contains (Block_Models, Context.Memory.Base) is begin return Map_Pkg.Contains (Block_Models, Context.Memory.Base); end Has_Model; --------------------- -- Get_Block_Model -- --------------------- function Get_Block_Model (Context : TC.Context) return MB.Formal_Model is Model : MB.Formal_Model renames Map_Pkg.Element (Block_Models, Context.Memory.Base); begin -- we cannot guarantee connection of Context and Formal model -- tha is why we Assume it :( -- TODO: think about this issue pragma Assume (Model.Mem_Region = Context.Memory.Region); return Model; end Get_Block_Model; --------------------- -- Set_Block_Model -- --------------------- procedure Set_Block_Model (Context : TC.Context; Blocks_Model : MB.Formal_Model) is begin Map_Pkg.Replace (Block_Models, Context.Memory.Base, Blocks_Model); pragma Assert (Get_Block_Model (Context) = Blocks_Model); end Set_Block_Model; ---------------- -- Init_Model -- ---------------- procedure Init_Model (Context : TC.Context) is Model : MB.Formal_Model := MB.Init_Model (Context.Memory.Region); use type Ada.Containers.Count_Type; begin pragma Assume (Map_Pkg.Length(Block_Models) < Block_Models.Capacity); Map_Pkg.Include (Block_Models, Context.Memory.Base, Model); pragma Assert (Get_Block_Model (Context) = Model); end Init_Model; end TLSF.Proof.Model.Context;