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
test/asset/agda-stdlib-1.0/Data/Container/Indexed/WithK.agda
omega12345/agda-mode
5
17063
<filename>test/asset/agda-stdlib-1.0/Data/Container/Indexed/WithK.agda ------------------------------------------------------------------------ -- The Agda standard library -- -- Some code related to indexed containers that uses heterogeneous -- equality ------------------------------------------------------------------------ -- The notation and presentation here is perhaps close to those used -- by Hancock and Hyvernat in "Programming interfaces and basic -- topology" (2006). {-# OPTIONS --with-K --safe --guardedness #-} module Data.Container.Indexed.WithK where open import Axiom.Extensionality.Heterogeneous using (Extensionality) open import Data.Container.Indexed hiding (module PlainMorphism) open import Data.Product as Prod hiding (map) open import Function renaming (id to ⟨id⟩; _∘_ to _⟨∘⟩_) open import Level open import Relation.Unary using (Pred; _⊆_) open import Relation.Binary.PropositionalEquality as P using (_≡_; refl) open import Relation.Binary.HeterogeneousEquality as H using (_≅_; refl) open import Relation.Binary.Indexed.Heterogeneous ------------------------------------------------------------------------ -- Equality, parametrised on an underlying relation. Eq : ∀ {i o c r ℓ} {I : Set i} {O : Set o} (C : Container I O c r) (X Y : Pred I ℓ) → IREL X Y ℓ → IREL (⟦ C ⟧ X) (⟦ C ⟧ Y) _ Eq C _ _ _≈_ {o₁} {o₂} (c , k) (c′ , k′) = o₁ ≡ o₂ × c ≅ c′ × (∀ r r′ → r ≅ r′ → k r ≈ k′ r′) private -- Note that, if propositional equality were extensional, then Eq _≅_ -- and _≅_ would coincide. Eq⇒≅ : ∀ {i o c r ℓ} {I : Set i} {O : Set o} {C : Container I O c r} {X : Pred I ℓ} {o₁ o₂ : O} {xs : ⟦ C ⟧ X o₁} {ys : ⟦ C ⟧ X o₂} → Extensionality r ℓ → Eq C X X (λ x₁ x₂ → x₁ ≅ x₂) xs ys → xs ≅ ys Eq⇒≅ {xs = c , k} {.c , k′} ext (refl , refl , k≈k′) = H.cong (_,_ c) (ext (λ _ → refl) (λ r → k≈k′ r r refl)) setoid : ∀ {i o c r s} {I : Set i} {O : Set o} → Container I O c r → IndexedSetoid I s _ → IndexedSetoid O _ _ setoid C X = record { Carrier = ⟦ C ⟧ X.Carrier ; _≈_ = _≈_ ; isEquivalence = record { refl = refl , refl , λ { r .r refl → X.refl } ; sym = sym ; trans = λ { {_} {i = xs} {ys} {zs} → trans {_} {i = xs} {ys} {zs} } } } where module X = IndexedSetoid X _≈_ : IRel (⟦ C ⟧ X.Carrier) _ _≈_ = Eq C X.Carrier X.Carrier X._≈_ sym : Symmetric (⟦ C ⟧ X.Carrier) _≈_ sym {_} {._} {_ , _} {._ , _} (refl , refl , k) = refl , refl , λ { r .r refl → X.sym (k r r refl) } trans : Transitive (⟦ C ⟧ X.Carrier) _≈_ trans {._} {_} {._} {_ , _} {._ , _} {._ , _} (refl , refl , k) (refl , refl , k′) = refl , refl , λ { r .r refl → X.trans (k r r refl) (k′ r r refl) } ------------------------------------------------------------------------ -- Functoriality module Map where identity : ∀ {i o c r s} {I : Set i} {O : Set o} (C : Container I O c r) (X : IndexedSetoid I s _) → let module X = IndexedSetoid X in ∀ {o} {xs : ⟦ C ⟧ X.Carrier o} → Eq C X.Carrier X.Carrier X._≈_ xs (map C {X.Carrier} ⟨id⟩ xs) identity C X = IndexedSetoid.refl (setoid C X) composition : ∀ {i o c r s ℓ₁ ℓ₂} {I : Set i} {O : Set o} (C : Container I O c r) {X : Pred I ℓ₁} {Y : Pred I ℓ₂} (Z : IndexedSetoid I s _) → let module Z = IndexedSetoid Z in {f : Y ⊆ Z.Carrier} {g : X ⊆ Y} {o : O} {xs : ⟦ C ⟧ X o} → Eq C Z.Carrier Z.Carrier Z._≈_ (map C {Y} f (map C {X} g xs)) (map C {X} (f ⟨∘⟩ g) xs) composition C Z = IndexedSetoid.refl (setoid C Z) ------------------------------------------------------------------------ -- Plain morphisms module PlainMorphism {i o c r} {I : Set i} {O : Set o} where open Data.Container.Indexed.PlainMorphism -- Naturality. Natural : ∀ {ℓ} {C₁ C₂ : Container I O c r} → ((X : Pred I ℓ) → ⟦ C₁ ⟧ X ⊆ ⟦ C₂ ⟧ X) → Set _ Natural {C₁ = C₁} {C₂} m = ∀ {X} Y → let module Y = IndexedSetoid Y in (f : X ⊆ Y.Carrier) → ∀ {o} (xs : ⟦ C₁ ⟧ X o) → Eq C₂ Y.Carrier Y.Carrier Y._≈_ (m Y.Carrier $ map C₁ {X} f xs) (map C₂ {X} f $ m X xs) -- Natural transformations. NT : ∀ {ℓ} (C₁ C₂ : Container I O c r) → Set _ NT {ℓ} C₁ C₂ = ∃ λ (m : (X : Pred I ℓ) → ⟦ C₁ ⟧ X ⊆ ⟦ C₂ ⟧ X) → Natural m -- Container morphisms are natural. natural : ∀ {ℓ} (C₁ C₂ : Container I O c r) (m : C₁ ⇒ C₂) → Natural {ℓ} ⟪ m ⟫ natural _ _ m {X} Y f _ = refl , refl , λ { r .r refl → lemma (coherent m) } where module Y = IndexedSetoid Y lemma : ∀ {i j} (eq : i ≡ j) {x} → P.subst Y.Carrier eq (f x) Y.≈ f (P.subst X eq x) lemma refl = Y.refl -- In fact, all natural functions of the right type are container -- morphisms. complete : ∀ {C₁ C₂ : Container I O c r} (nt : NT C₁ C₂) → ∃ λ m → (X : IndexedSetoid I _ _) → let module X = IndexedSetoid X in ∀ {o} (xs : ⟦ C₁ ⟧ X.Carrier o) → Eq C₂ X.Carrier X.Carrier X._≈_ (proj₁ nt X.Carrier xs) (⟪ m ⟫ X.Carrier {o} xs) complete {C₁} {C₂} (nt , nat) = m , (λ X xs → nat X (λ { (r , eq) → P.subst (IndexedSetoid.Carrier X) eq (proj₂ xs r) }) (proj₁ xs , (λ r → r , refl))) where m : C₁ ⇒ C₂ m = record { command = λ c₁ → proj₁ (lemma c₁) ; response = λ {_} {c₁} r₂ → proj₁ (proj₂ (lemma c₁) r₂) ; coherent = λ {_} {c₁} {r₂} → proj₂ (proj₂ (lemma c₁) r₂) } where lemma : ∀ {o} (c₁ : Command C₁ o) → Σ[ c₂ ∈ Command C₂ o ] ((r₂ : Response C₂ c₂) → Σ[ r₁ ∈ Response C₁ c₁ ] next C₁ c₁ r₁ ≡ next C₂ c₂ r₂) lemma c₁ = nt (λ i → Σ[ r₁ ∈ Response C₁ c₁ ] next C₁ c₁ r₁ ≡ i) (c₁ , λ r₁ → r₁ , refl) -- Composition commutes with ⟪_⟫. ∘-correct : {C₁ C₂ C₃ : Container I O c r} (f : C₂ ⇒ C₃) (g : C₁ ⇒ C₂) (X : IndexedSetoid I (c ⊔ r) _) → let module X = IndexedSetoid X in ∀ {o} {xs : ⟦ C₁ ⟧ X.Carrier o} → Eq C₃ X.Carrier X.Carrier X._≈_ (⟪ f ∘ g ⟫ X.Carrier xs) (⟪ f ⟫ X.Carrier (⟪ g ⟫ X.Carrier xs)) ∘-correct f g X = refl , refl , λ { r .r refl → lemma (coherent g) (coherent f) } where module X = IndexedSetoid X lemma : ∀ {i j k} (eq₁ : i ≡ j) (eq₂ : j ≡ k) {x} → P.subst X.Carrier (P.trans eq₁ eq₂) x X.≈ P.subst X.Carrier eq₂ (P.subst X.Carrier eq₁ x) lemma refl refl = X.refl ------------------------------------------------------------------------ -- All and any -- Membership. infix 4 _∈_ _∈_ : ∀ {i o c r ℓ} {I : Set i} {O : Set o} {C : Container I O c r} {X : Pred I (i ⊔ ℓ)} → IREL X (⟦ C ⟧ X) _ _∈_ {C = C} {X} x xs = ◇ C {X = X} ((x ≅_) ⟨∘⟩ proj₂) (-, xs)
spring semester 2 course/operatin_system_labs/lab_4/proc_output.asm
andrwnv/study-progs
4
245162
public output_proc data segment para public 'data' text db 'Input two number w/o space:$' new_line db 13, 10, '$' data ends code segment para public 'code' assume cs:code, ds:data input_start: output_proc proc near push bp mov bp, sp mov ax, [bp+4] m3: mov cx, 10h mov bx, ax mov ax, data mov ds, ax mov ah, 9h mov dx, offset new_line int 21h m4: xor dx, dx sal bx, 1 adc dl, 30h mov ah, 02h int 21h loop m4 mov sp, bp pop bp ret output_proc endp code ends end output_proc
programs/oeis/085/A085409.asm
karttu/loda
1
161285
; A085409: Sum of three solutions of the Diophantine equation x^2 - y^2 = z^3. ; 0,12,84,270,624,1200,2052,3234,4800,6804,9300,12342,15984,20280,25284,31050,37632,45084,53460,62814,73200,84672,97284,111090,126144,142500,160212,179334,199920,222024,245700,271002,297984,326700,357204,389550 mov $1,$0 mul $1,3 mul $0,$1 add $1,1 mul $0,$1 mov $1,$0
src/data_const.asm
maziac/dezogif
2
11326
<filename>src/data_const.asm ;=========================================================================== ; data.asm ; ; All volatile data is defined here. ; ; Note: The area does not need to be copied. i.e. is initialized on the fly. ;=========================================================================== ; The dezogif program version: MACRO PRG_VERSION defb "v2.0.0" ENDM ;=========================================================================== ; Magic number addresses to recognize the debugger ;=========================================================================== magic_number_a: equ 0x0000 ; Address 0x0000 (0xE000) magic_number_b: equ 0x0001 magic_number_c: equ 0x0066 ; Address 0x0066 (0xE066) magic_number_d: equ 0x0067 ;=========================================================================== ; Const data ;=========================================================================== ; 16 bit build time build_time_abs: defw BUILD_TIME16 build_time_rel = build_time_abs-MAIN_ADDR; ; UI INTRO_TEXT: defb AT, 0, 0 defb "ZX Next UART DeZog Interface" defb AT, 0, 1*8 PRG_VERSION defb " (DZRP v" defb DZRP_VERSION.MAJOR+'0', '.', DZRP_VERSION.MINOR+'0', '.', DZRP_VERSION.PATCH+'0' defb ")" defb AT, 0, 2*8 defb "ESP UART Baudrate: " STRINGIFY BAUDRATE defb AT, 0, 3*8 defb "Video timing:" defb AT, 0, 6*8 defb "Keys:" defb AT, 0, 7*8 defb "1 = Joy 1" defb AT, 0, 8*8 defb "2 = Joy 2" defb AT, 0, 9*8 defb "3 = No joystick port" defb AT, 0, 10*8 defb "R = Reset" defb AT, 0, 11*8 defb "B = Border" defb 0 JOY1_SELECTED_TEXT: defb AT, 0, 4*8, "Using Joy 1 (left)", 0 JOY2_SELECTED_TEXT: defb AT, 0, 4*8, "Using Joy 2 (right)", 0 NOJOY_SELECTED_TEXT: defb AT, 0, 4*8, "No joystick port used.", 0 SELECTED_TEXT_TABLE: defw NOJOY_SELECTED_TEXT defw JOY1_SELECTED_TEXT defw JOY2_SELECTED_TEXT BORDER_OFF_TEXT: defb AT, 11*8, 11*8, "off", 0 BORDER_ON_TEXT: defb AT, 11*8, 11*8, "on", 0 ; Error texts TEXT_LAST_ERROR: defb AT, 0, 13*8, "Last Error:", AT, 0, 14*8, 0 TEXT_ERROR_RX_TIMEOUT: defb "RX Timeout", 0 TEXT_ERROR_TX_TIMEOUT: defb "TX Timeout", 0 TEXT_ERROR_WRONG_FUNC_NUMBER: defb "Wrong function number", 0 TEXT_ERROR_WRITE_MAIN_BANK: defb "CMD_WRITE_BANK: Can't write to bank " STRINGIFY MAIN_BANK defb ". Bank is used by DeZog.", 0 ERROR_TEXT_TABLE: defw TEXT_ERROR_RX_TIMEOUT defw TEXT_ERROR_TX_TIMEOUT defw TEXT_ERROR_WRONG_FUNC_NUMBER defw TEXT_ERROR_WRITE_MAIN_BANK
oeis/087/A087076.asm
neoneye/loda-programs
11
16084
<reponame>neoneye/loda-programs ; A087076: Sums of the squares of the elements in the subsets of the integers 1 to n. ; Submitted by <NAME> ; 0,1,10,56,240,880,2912,8960,26112,72960,197120,518144,1331200,3354624,8314880,20316160,49020928,116981760,276430848,647495680,1504706560,3471835136,7958691840,18136170496,41104179200,92694118400,208071032832,465064427520,1035355553792,2296465326080,5076114472960,11184094838784,24567212933120,53811645251584,117553254891520,256151849533440,556833919991808,1207744803635200,2613951456083968,5645992208629760,12171593719480320,26191466485252096,56262009993297920,120656007985627136,258341252062248960 mov $1,$0 mov $2,$0 add $2,$0 mov $0,2 pow $0,$1 add $2,2 bin $2,3 mul $0,$2 div $0,8
Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_2508.asm
ljhsiun2/medusa
9
17939
<reponame>ljhsiun2/medusa<gh_stars>1-10 .global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %r9 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x1884b, %rsi nop xor $60732, %r9 and $0xffffffffffffffc0, %rsi vmovntdqa (%rsi), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %rbx nop nop nop inc %r9 lea addresses_D_ht+0x16d9f, %rbx xor $28670, %rsi movl $0x61626364, (%rbx) nop nop nop nop and $37733, %r9 lea addresses_WT_ht+0xf04b, %r12 xor %r8, %r8 mov (%r12), %rdx nop nop nop dec %rbx lea addresses_A_ht+0xa3e3, %rdx nop nop nop nop nop xor $3673, %r9 mov $0x6162636465666768, %rsi movq %rsi, %xmm6 vmovups %ymm6, (%rdx) nop nop sub %rsi, %rsi lea addresses_normal_ht+0x189fb, %rsi lea addresses_WC_ht+0x1ddbb, %rdi nop nop add $41632, %rdx mov $57, %rcx rep movsb nop nop nop nop inc %rbx lea addresses_WT_ht+0xb18b, %rcx clflush (%rcx) nop nop nop nop nop and $53607, %rbx mov $0x6162636465666768, %r8 movq %r8, (%rcx) nop nop nop nop nop inc %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %r8 push %r9 push %rbp push %rdi // Store lea addresses_PSE+0xc04b, %r11 nop nop nop cmp %r12, %r12 movb $0x51, (%r11) cmp %r11, %r11 // Faulty Load lea addresses_A+0x4b, %r14 nop nop nop sub %r8, %r8 mov (%r14), %rbp lea oracles, %r8 and $0xff, %rbp shlq $12, %rbp mov (%r8,%rbp,1), %rbp pop %rdi pop %rbp pop %r9 pop %r8 pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_A', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
oeis/288/A288516.asm
neoneye/loda-programs
11
170699
; A288516: Number of (undirected) paths in the ladder graph P_2 X P_n. ; 1,12,49,146,373,872,1929,4118,8589,17644,35889,72538,146021,293200,587801,1177278,2356541,4715412,9433537,18870210,37744021,75492152,150988969,301983206,603972333,1207951292,2415909969,4831828138,9663665349,19327340704,38654692409,77309396878,154618806941,309237628260,618475272161,1236950561298,2473901140981,4947802301832,9895604625097,19791209273270,39582418571341,79164837169292,158329674367089,316659348764666,633318697561893,1266637395158512,2533274790354009,5066549580747358,10133099161536509 mov $4,$0 add $4,1 mov $6,$0 lpb $4 mov $0,$6 sub $4,1 sub $0,$4 mov $7,$0 add $7,1 mov $8,0 mov $9,$0 lpb $7 mov $0,$9 sub $7,1 sub $0,$7 mov $2,$0 mov $3,1 mov $5,0 lpb $2 mov $0,2 sub $2,1 mul $3,2 add $3,6 add $3,$5 add $5,2 lpe add $0,$3 add $8,$0 lpe add $1,$8 lpe mov $0,$1
src/Prelude/List/Relations/Permutation.agda
t-more/agda-prelude
0
12375
module Prelude.List.Relations.Permutation where open import Prelude.List.Base open import Prelude.List.Relations.Any data Permutation {a} {A : Set a} : List A → List A → Set a where [] : Permutation [] [] _∷_ : ∀ {x xs ys} (i : x ∈ ys) → Permutation xs (deleteIx ys i) → Permutation (x ∷ xs) ys
programs/oeis/020/A020986.asm
neoneye/loda
22
10638
<reponame>neoneye/loda<filename>programs/oeis/020/A020986.asm ; A020986: a(n) = n-th partial sum of Golay-Rudin-Shapiro sequence A020985. ; 1,2,3,2,3,4,3,4,5,6,7,6,5,4,5,4,5,6,7,6,7,8,7,8,7,6,5,6,7,8,7,8,9,10,11,10,11,12,11,12,13,14,15,14,13,12,13,12,11,10,9,10,9,8,9,8,9,10,11,10,9,8,9,8,9,10,11,10,11,12,11,12,13,14,15,14,13,12,13,12,13,14,15,14,15,16,15,16,15,14,13,14,15,16,15,16,15,14,13,14 lpb $0 mov $2,$0 sub $0,1 seq $2,20985 ; The Rudin-Shapiro or Golay-Rudin-Shapiro sequence (coefficients of the Shapiro polynomials). add $1,$2 lpe add $1,1 mov $0,$1
src/results/adabase-results-sets.adb
jrmarino/AdaBase
30
12855
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with Ada.Characters.Handling; package body AdaBase.Results.Sets is package ACH renames Ada.Characters.Handling; -------------- -- column -- -------------- function column (row : Datarow; index : Positive) return ARF.Std_Field is begin if index > Natural (row.crate.Length) then raise COLUMN_DOES_NOT_EXIST with "Column" & index'Img & " requested, but only" & row.crate.Length'Img & " columns present."; end if; return row.crate.Element (Index => index); end column; -------------- -- column -- -------------- function column (row : Datarow; heading : String) return ARF.Std_Field is use type heading_map.Cursor; cursor : heading_map.Cursor; index : Positive; headup : String := ACH.To_Upper (heading); begin cursor := row.map.Find (Key => headup); if cursor = heading_map.No_Element then raise COLUMN_DOES_NOT_EXIST with "There is no column named '" & headup & "'."; end if; index := heading_map.Element (Position => cursor); return row.crate.Element (Index => index); end column; ------------- -- count -- ------------- function count (row : Datarow) return Natural is begin return Natural (row.crate.Length); end count; ---------------------- -- data_exhausted -- ---------------------- function data_exhausted (row : Datarow) return Boolean is begin return row.done; end data_exhausted; -------------------- -- Same_Strings -- -------------------- function Same_Strings (S, T : String) return Boolean is begin return S = T; end Same_Strings; ------------ -- push -- ------------ procedure push (row : out Datarow; heading : String; field : ARF.Std_Field; last_field : Boolean := False) is begin if row.locked then raise CONSTRUCTOR_DO_NOT_USE with "The push method is not for you."; end if; if last_field then row.locked := True; end if; row.crate.Append (New_Item => field); row.map.Insert (Key => ACH.To_Upper (heading), New_Item => row.crate.Last_Index); end push; end AdaBase.Results.Sets;
oeis/017/A017166.asm
neoneye/loda-programs
11
29907
<gh_stars>10-100 ; A017166: a(n) = (9*n)^6. ; 0,531441,34012224,387420489,2176782336,8303765625,24794911296,62523502209,139314069504,282429536481,531441000000,941480149401,1586874322944,2565164201769,4001504141376,6053445140625,8916100448256,12827693806929,18075490334784,25002110044521,34012224000000,45579633110361,60254729561664,78672340886049,101559956668416,129746337890625,164170508913216,205891132094649,256096265048064,316113500535561,387420489000000,471655843734321,570630428688384,686339028913329,820972403643456,976929722015625 pow $0,6 mul $0,531441
examples/asm-32/int_math.asm
patrickf2000/upl
0
84608
.intel_syntax noprefix .data .bss .text .extern puts .extern printf .extern exit .extern fflush .extern input_int .extern print_int .global main main: push ebp mov ebp, esp sub esp, 48 mov DWORD PTR [ebp-8], 10 mov DWORD PTR [ebp-12], 5 mov eax, [ebp-8] add eax, [ebp-12] mov DWORD PTR[ebp-16], eax push DWORD PTR [ebp-16] call print_int add esp, 4 mov eax, [ebp-8] add eax, [ebp-12] imul eax, 10 mov DWORD PTR[ebp-20], eax push DWORD PTR [ebp-20] call print_int add esp, 4 mov eax, 10 add eax, [ebp-8] add eax, [ebp-12] sub eax, 7 mov DWORD PTR[ebp-24], eax push DWORD PTR [ebp-24] call print_int add esp, 4 mov eax, [ebp-8] sub eax, [ebp-12] mov DWORD PTR[ebp-28], eax push DWORD PTR [ebp-28] call print_int add esp, 4 mov eax, [ebp-8] imul eax, [ebp-12] mov DWORD PTR[ebp-32], eax push DWORD PTR [ebp-32] call print_int add esp, 4 mov eax, [ebp-8] imul eax, [ebp-12] imul eax, 2 mov DWORD PTR[ebp-36], eax push DWORD PTR [ebp-36] call print_int add esp, 4 leave ret
test/emul/002-nop.asm
phillid/toy-cpu-assembler
0
94493
; POST $1 = 0x0 ; POST $2 = 0x0 ; POST $3 = 0x0 ; POST $4 = 0x0 ; POST $5 = 0x0 ; POST $6 = 0x0 nop
bb-runtimes/runtimes/ravenscar-full-stm32g474/gnat/s-chepoo.ads
JCGobbi/Nucleo-STM32G474RE
0
21383
<gh_stars>0 ------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . C H E C K E D _ P O O L S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2021, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System.Storage_Elements; with System.Storage_Pools; package System.Checked_Pools is type Checked_Pool is abstract new System.Storage_Pools.Root_Storage_Pool with private; -- Equivalent of storage pools with the addition that Dereference is -- called on each implicit or explicit dereference of a pointer which -- has such a storage pool. procedure Dereference (Pool : in out Checked_Pool; Storage_Address : Address; Size_In_Storage_Elements : System.Storage_Elements.Storage_Count; Alignment : System.Storage_Elements.Storage_Count) is abstract; -- Called implicitly each time a pointer to a checked pool is dereferenced -- All parameters in the profile are compatible with the profile of -- Allocate/Deallocate: the Storage_Address corresponds to the address of -- the dereferenced object, Size_in_Storage_Elements is its dynamic size -- (and thus may involve an implicit dispatching call to size) and -- Alignment is the alignment of the object. private type Checked_Pool is abstract new System.Storage_Pools.Root_Storage_Pool with null record; end System.Checked_Pools;
rails.adb
AfroMetal/concurrent-railroad-ada
0
12192
<gh_stars>0 -- -- <NAME> 221454 -- package body Rails is protected body Track is function Get_Id return Integer is begin return Id; end Get_Id; function Get_Type return Track_Type is begin return Typee; end Get_Type; entry Get_Lock(Suc : out Boolean) when TRUE is begin case Locked is when TRUE => Suc := FALSE; when FALSE => Locked := TRUE; Suc := TRUE; end case; end Get_Lock; entry Lock when not Locked is begin Locked := TRUE; end Lock; entry Unlock when Locked is begin Locked := FALSE; end Unlock; function As_String return String is begin case Typee is when Turntable => return "Turntable" & Integer'Image (Id); when Normal => return "NormalTrack" & Integer'Image (Id); when Station => return "StationTrack" & Integer'Image (Id) & " " & SU.To_String (Spec.Name); end case; end As_String; function As_Verbose_String return String is Id : String := Integer'Image (Get_Id); begin case Typee is when Turntable => return "rails.Turntable:" & Id (2 .. Id'Last) & "{time:" & Integer'Image (Spec.Rotation_Time) & "}"; when Normal => return "rails.NormalTrack:" & Id (2 .. Id'Last) & "{len:" & Integer'Image (Spec.Length) & ", limit:" & Integer'Image (Spec.Speed_Limit) & "}"; when Station => return "rails.StationTrack:" & Id (2 .. Id'Last) & ":" & SU.To_String (Spec.Name) & "{time:" & Integer'Image (Spec.Stop_Time) & "}"; end case; end As_Verbose_String; function Action_Time(Train_Speed : Integer) return Float is begin case Typee is when Turntable => return Float (Spec.Rotation_Time) / 60.0; when Normal => return Float (Spec.Length) / Float (Integer'Min(Spec.Speed_Limit, Train_Speed)); when Station => return Float (Spec.Stop_Time) / 60.0; end case; end Action_Time; procedure Init (I : in Integer; S : in Track_Record) is begin Id := I; Spec := S; end Init; end Track; function New_Turntable(I : Integer; T : Integer) return Track_Ptr is TP : Track_Ptr; S : Track_Record; begin TP := new Track(Turntable); S := (Typee => Turntable, Rotation_Time => T); TP.Init(I, S); return TP; end New_Turntable; function New_Normal_Track(I : Integer; L : Integer; SL : Integer) return Track_Ptr is TP : Track_Ptr; S : Track_Record; begin TP := new Track(Normal); S := (Typee => Normal, Length => L, Speed_Limit => SL); TP.Init(I, S); return TP; end New_Normal_Track; function New_Station_Track(I : Integer; T : Integer; N : SU.Unbounded_String) return Track_Ptr is TP : Track_Ptr; S : Track_Record; begin TP := new Track(Station); S := (Typee => Station, Stop_Time => T, Name => N); TP.Init(I, S); return TP; end New_Station_Track; function As_String(Self: Route_Array) return String is S : SU.Unbounded_String; begin S := SU.To_Unbounded_String ("["); for I in Self'range loop SU.Append(S, Integer'Image (I) (2 .. Integer'Image (I)'Last) & " "); end loop; SU.Append(S, "]"); return SU.To_String (S); end As_String; end Rails;
core/lib/types/Unit.agda
mikeshulman/HoTT-Agda
0
14063
{-# OPTIONS --without-K --rewriting #-} open import lib.Basics open import lib.types.Paths module lib.types.Unit where pattern tt = unit ⊙Unit : Ptd₀ ⊙Unit = ⊙[ Unit , unit ] abstract -- Unit is contractible Unit-is-contr : is-contr Unit Unit-is-contr = (unit , λ y → idp) Unit-is-prop : is-prop Unit Unit-is-prop = raise-level -2 Unit-is-contr Unit-is-set : is-set Unit Unit-is-set = raise-level -1 Unit-is-prop Unit-level = Unit-is-contr ⊤-is-contr = Unit-is-contr ⊤-level = Unit-is-contr ⊤-is-prop = Unit-is-prop ⊤-is-set = Unit-is-set
Driver/Socket/TCPIP/tcpipLink.asm
steakknife/pcgeos
504
164633
<gh_stars>100-1000 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved GEOWORKS CONFIDENTIAL PROJECT: Socket MODULE: TCP/IP Driver FILE: tcpipLink.asm AUTHOR: <NAME>, <NAME>, 1994 ROUTINES: Name Description ---- ----------- LinkCreateLinkTable Create the table for keeping track of link connections LinkCreateLoopbackEntry Create the loopback entry in the link table LinkCreateMainLinkEntry Create the main link entry in the link table LinkTableAddEntry Add a new entry into the link table and fill in the LinkControlBlock LinkTableDeleteEntry Delete a closed link from the link table. LinkTableGetEntry Get the entry in the link table corresponding to the given domain handle LinkTableDestroyTable Free all memory used by the link table. LinkGetLocalAddr Find the local address of the given link LinkResolveLinkAddr Resolve a link address LinkStopLinkResolve Stop resolving link address CloseAllLinks Close all link connections, unregistering the link drivers and unloading them LinkCheckOpen Check whether a link is opened LinkOpenConnection Open a link connection unless one is already open LinkCheckIfLoopback Returns loopback domainhandle if remote address for connection is a loopback address LinkSetupMainLink Load the main link driver and register it LinkStoreLinkAddress Store the link address in the LCB LinkOpenLink Tell link driver to establish link connection LinkLoadLinkDriver Load the link driver used by TCP for establishing connections LinkUnloadLinkDriver Unload the link driverused by TCP for establishing connections LinkGetMTU Get the mtu of the given link. LinkGetMediumAndUnit Get the medium and unit for a link. LinkGetMediumAndUnitConnection Look for a link over the specified medium and unit. LinkGetMediumAndUnitConnectionCB LinkCheckLocalAddr Verify the address belongs to the link. LinkSendData Send data over the given link. ECCheckLinkDomainHandle Verify that the domain handle is legal REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/ 8/94 Initial revision DESCRIPTION: $Id: tcpipLink.asm,v 1.38 98/06/25 15:31:30 jwu Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCreateLinkTable %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create the table for keeping track of link level drivers. Initialize it to contain the entry for the loopback link. CALLED BY: TcpipInit PASS: es = dgroup RETURN: carry set if insufficient memory else carry clear DESTROYED: nothing PSEUDO CODE/STRATEGY: Create the chunk array for the link table in an lmem block block and store its optr in dgroup. Create an entry for the loopback link. Create an entry for the main link. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCreateLinkTable proc far uses ax, bx, cx, si, ds .enter ; ; Allocate the LMem block for the link table and make sure ; we own it. ; mov ax, LMEM_TYPE_GENERAL clr cx ; default block header call MemAllocLMem ; bx <- block handle mov ax, handle 0 call HandleModifyOwner mov ax, mask HF_SHARABLE call MemModifyFlags ; ; Create the chunk array for the link table and save its ; optr in dgroup. ; push bx call MemLockExcl mov ds, ax clr bx, cx, si, ax ; var size, dflt hdr, alloc chunk call ChunkArrayCreate ; *ds:si = link table pop bx jc noMemory movdw es:[linkTable], bxsi ; ^lbx:si = link table ; ; Create loopback entry and entry for main link in the link table. ; call LinkCreateLoopbackEntry call LinkCreateMainLinkEntry call MemUnlockExcl clc exit: .leave ret noMemory: EC < WARNING TCPIP_CANNOT_CREATE_LINK_TABLE > call MemFree stc jmp exit LinkCreateLinkTable endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCreateLoopbackEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create the loopback entry in the link table. CALLED BY: LinkCreateLinkTable PASS: *ds:si = link table RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: ChunkArrayAppend returns new element all zeroed so no need to initialize zero fields. Connection handle for the link set to zero since we never attempt to open it. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 8/24/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCreateLoopbackEntry proc near uses ax, di .enter mov ax, size LinkControlBlock call ChunkArrayAppend ; ds:di = new LCB EC < call ChunkArrayPtrToElement > EC < tst ax > EC < ERROR_NE TCPIP_INTERNAL_ERROR ; loopback must be first! > mov ds:[di].LCB_state, LS_OPEN ; loopback is always open mov ds:[di].LCB_strategy.segment, segment TcpipDoNothing mov ds:[di].LCB_strategy.offset, offset TcpipDoNothing mov ds:[di].LCB_mtu, MAX_LINK_MTU ; no limit on loopback mov ds:[di].LCB_minHdr, TCPIP_SEQUENCED_PACKET_HDR_SIZE movdw ds:[di].LCB_localAddr, LOOPBACK_LOCAL_IP_ADDR .leave ret LinkCreateLoopbackEntry endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCreateMainLinkEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create the main link entry in the link table. CALLED BY: LinkCreateLinkTable PASS: *ds:si = link table RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: Allocate basic LinkControlBlock. When we have an actual address for the link, the entry can be resized later. ChunkArrayAppend returns the element all zeroed so no need to initialize zero fields. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 4/ 7/95 Initial version jwu 4/19/97 Added closeSem code %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCreateMainLinkEntry proc near uses ax, bx, di .enter ; ; Append a new LinkControlBlock to array. ; mov ax, size LinkControlBlock call ChunkArrayAppend ; ds:di = LCB EC < call ChunkArrayPtrToElement > EC < cmp ax, MAIN_LINK_DOMAIN_HANDLE > EC < ERROR_NE TCPIP_INTERNAL_ERROR ; main link must be 2nd!> ; ; Set state to closed and allocate sempahores. ; mov ds:[di].LCB_state, LS_CLOSED clr ds:[di].LCB_openCount ; no open attempts yet clr bx ; initially blocking call ThreadAllocSem mov ds:[di].LCB_sem, bx mov ax, handle 0 call HandleModifyOwner clr bx call ThreadAllocSem mov ds:[di].LCB_closeSem, bx mov ax, handle 0 call HandleModifyOwner .leave ret LinkCreateMainLinkEntry endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkTableAddEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Add a new entry into the link table and fill in the LCB. CALLED BY: TcpipAddDomain PASS: ax = client handle cl = min header size es:dx = driver entry point bp = driver handle ds = dgroup RETURN: bx = index of entry in table (used as domain handle) DESTROYED: nothing PSEUDO CODE/STRATEGY: Append the entry to the chunk array for the link table Fill in the information, initializing defaults Return index in table NOTE: currently uses default MTU. Need a way for link to specify its MTU. Don't need to allocate LCB_sem because only main link needs it. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkTableAddEntry proc far uses ax, cx, di, si, ds .enter ; ; Create a new entry at end of array. ; push ax ; save client handle movdw bxsi, ds:[linkTable] ; ^lbx:si = array call MemLockExcl mov ds, ax ; *ds:si = array mov ax, size LinkControlBlock call ChunkArrayAppend ; *ds:di = new entry pop ax ; ax = client handle ; ; Update all the info in the LinkControlBlock for the given ; protocol. ; movdw ds:[di].LCB_strategy, esdx mov ds:[di].LCB_minHdr, cl mov ds:[di].LCB_mtu, DEFAULT_LINK_MTU mov ds:[di].LCB_state, LS_CLOSED mov ds:[di].LCB_clientHan, ax mov ds:[di].LCB_drvr, bp clr ds:[di].LCB_linkSize call ChunkArrayPtrToElement ; ax = index # call MemUnlockExcl mov_tr bx, ax ; bx = index # ; aka domain handle .leave ret LinkTableAddEntry endp COMMENT @---------------------------------------------------------------- C FUNCTION: LinkTableDeleteEntry C DECLARATION: extern void _far _far _pascal LinkTableDeleteEntry(word link); CALLED BY: TcpipLinkClosed via message queue SYNOPSIS: Link closed and there is no registered client. STRATEGY: deref dgroup grab reg sem if not registered { lock link table and get entry if link closed { grab client handle and driver handle push fptr of link strategy on stack unlock link table call link driver to unregister free link driver relock link table if not main link, delete entry count number links left if 2 left { if main link driver not loaded destroy thread and timer } } unlock link table } release reg sem exit NOTE: This routine MUST be called from driver's thread so that the detach for destroying thread will not process until this task is completed. Code does not need to P taskSem because there are no clients and none will register as long as regSem is P-ed. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 1/23/95 Initial version jwu 9/22/95 2nd version -------------------------------------------------------------------------@ SetGeosConvention LINKTABLEDELETEENTRY proc far link:word uses di, si, ds .enter ; ; Make sure there is still no TCPIP client. ; mov bx, handle dgroup call MemDerefES mov bx, es:[regSem] call ThreadPSem tst es:[regStatus] LONG jne exit ; ; Make sure link is still closed. ; movdw bxsi, es:[linkTable] call MemLockExcl mov ds, ax ; *ds:si = link table mov ax, link call ChunkArrayElementToPtr ; ds:di = LCB EC < ERROR_C TCPIP_INTERNAL_ERROR ; link value out of bounds! > cmp ds:[di].LCB_state, LS_CLOSED jne done ; ; Unregister and free link driver, unlocking link table during ; call out of TCP. ; clr dx xchg dx, ds:[di].LCB_drvr mov cx, ds:[di].LCB_clientHan pushdw ds:[di].LCB_strategy call MemUnlockExcl mov bx, cx ; bx = client handle mov di, DR_SOCKET_UNREGISTER call PROCCALLFIXEDORMOVABLE_PASCAL EC < tst dx > EC < ERROR_E TCPIP_INTERNAL_ERROR ; missing drvr handle! > mov bx, dx ; bx = driver handle call GeodeFreeDriver ; ; Remove entry from link table and find out how many are left. ; Do NOT remove the main link entry! ; mov bx, es:[linkTable].handle call MemLockExcl mov ds, ax ; *ds:si = array mov ax, link cmp ax, MAIN_LINK_DOMAIN_HANDLE je getCount mov cx, 1 ; just delete one call ChunkArrayDeleteRange getCount: ; ; Okay to destroy thread and timer if only two links (loopback ; and main link) are left and the main link driver is not loaded. ; call ChunkArrayGetCount cmp cx, NUM_FIXED_LINK_ENTRIES ja done mov ax, MAIN_LINK_DOMAIN_HANDLE call ChunkArrayElementToPtr ; ds:di = LCB tst ds:[di].LCB_drvr jne done call TcpipDestroyThreadAndTimerFar done: call MemUnlockExcl exit: mov bx, es:[regSem] call ThreadVSem .leave ret LINKTABLEDELETEENTRY endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkTableGetEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the entry in the link table corresponding to the given domain handle. CALLED BY: TcpipGetLocalAddr TcpipLinkOpened TcpipLinkClosed TcpipCheckLinkIsMain TcpipGetDefaultIPAddr LinkGetLocalAddr LinkOpenConnection LinkGetMediumAndUnit LINKGETMTU LINKCHECKLOCALADDR LINKSENDDATA IPAddressControlAddChild PASS: bx = domain handle RETURN: ds:di = LinkControlBlock bx = handle of link table (so caller can unlock it) DESTROYED: nothing PSEUDO CODE/STRATEGY: NOTE: Caller MUST NOT have link table locked when calling this. Caller MUST unlock link table. (use MemUnlockExcl) REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkTableGetEntry proc far uses ax, cx, dx, si .enter mov_tr dx, bx ; dx = domain handle mov bx, handle dgroup call MemDerefDS movdw bxsi, ds:[linkTable] ; ^lbx:si = link table call MemLockExcl mov ds, ax ; *ds:si = link table mov_tr ax, dx ; ax = entry to find call ChunkArrayElementToPtr ; ds:di = LCB ; cx = element size EC < ERROR_C TCPIP_INTERNAL_ERROR ; invalid entry # for table > .leave ret LinkTableGetEntry endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkTableDestroyTable %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Free all memory used by the link table. CALLED BY: TcpipExit PASS: nothing RETURN: nothing DESTROYED: ax, bx, cx, di (allowed) PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/29/96 Initial version jwu 3/04/97 VSems if clients blocked %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkTableDestroyTable proc far uses ds .enter ; ; Make sure no clients are blocked before freeing semaphores. ; mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ^hbx = link table push bx ; ; Wake up any clients block on LCB_sem. ; tst ds:[di].LCB_semCount ; no waiters? EC < WARNING_NZ TCPIP_EXITING_WITH_CLIENTS_BLOCKED > jz checkCloseSem mov bx, ds:[di].LCB_sem mov cx, ds:[di].LCB_semCount wakeLoop: call ThreadVSem loop wakeLoop checkCloseSem: ; ; Wake up any clients blocked on LCB_closeSem. ; tst ds:[di].LCB_closeCount ; no waiters? EC < WARNING_NZ TCPIP_EXITING_WITH_CLIENTS_BLOCKED > jz freeSem mov bx, ds:[di].LCB_closeSem mov cx, ds:[di].LCB_closeCount wake2Loop: call ThreadVSem loop wake2Loop freeSem: ; ; The only things to free are the main link's semaphores ; and the link table. ; mov bx, ds:[di].LCB_sem call ThreadFreeSem mov bx, ds:[di].LCB_closeSem call ThreadFreeSem pop bx call MemUnlockExcl call MemFree .leave ret LinkTableDestroyTable endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetLocalAddr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% C FUNCTION: LinkGetLocalAddr C DECLARATION: extern dword _far _far _pascal LinkGetLocalAddr(word link); REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/18/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetGeosConvention LINKGETLOCALADDR proc far C_GetOneWordArg bx, ax, cx call LinkGetLocalAddr ; bxcx = addr movdw dxax, bxcx ret LINKGETLOCALADDR endp SetDefaultConvention COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetLocalAddr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Find the local address of the given link. CALLED BY: SocketStoreConnectionInfo LINKGETLOCALADDR PASS: bx = domain handle of link RETURN: bxcx = local address of the link (whether link open/closed) carry set if link closed else carry clear DESTROYED: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkGetLocalAddr proc far uses di, si, ds .enter ; ; Get local address of link and set carry according to ; link state. ; call LinkTableGetEntry ; ds:di = LCB ; bx = table's block movdw sicx, ds:[di].LCB_localAddr cmp ds:[di].LCB_state, LS_OPEN je okay ; carry clear stc okay: call MemUnlockExcl ; flags preserved mov bx, si ; bxcx = local addr .leave ret LinkGetLocalAddr endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkResolveLinkAddr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Have link driver resolve link address. CALLED BY: TcpipResolveAddr PASS: ds:si = link address string (non-null terminated) cx = link addr size dx:bp = buffer for resolved link addr ax = buffer size (after space for IP addr deducted) RETURN: carry set if error ax = SocketDrError else cx = resolved addr size dx = access point ID (0 if none) ax unchanged DESTROYED: nothing PSEUDO CODE/STRATEGY: Load link driver Get link driver's strategy routine and have it resolve the link address, returning the results. Free link driver REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/10/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkResolveLinkAddr proc far uses bx, di, es .enter EC < tst cx > EC < ERROR_E TCPIP_INTERNAL_ERROR ; should be non-zero > ; ; Load link driver and have it resolve the link address. ; call LinkLoadLinkDriver ; bx = driver handle jc error push ds, si call GeodeInfoDriver ; ds:si = driver info movdw esdi, dssi pop ds, si pushdw es:[di].DIS_strategy mov di, DR_SOCKET_RESOLVE_ADDR call PROCCALLFIXEDORMOVABLE_PASCAL pushf call LinkUnloadLinkDriver ; ; Get access point ID. ; clr dx ; assume no ID cmp {byte} ds:[si], LT_ID jne done mov dx, ds:[si+1] ; dx = ID done: popf exit: .leave ret error: mov ax, SDE_DRIVER_NOT_FOUND jmp exit LinkResolveLinkAddr endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkStopLinkResolve %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Have link driver interrupt resolving an address. CALLED BY: TcpipStopResolve PASS: ds:si = link address string (non-null terminated) cx = link addr size RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: If no link driver, just exit Else, Load link driver Get link driver's strategy routine and have it stop resolving the link address Free link driver NOTES: Load the link driver again to prevent it from exiting unexpectedly while we're stopping a resolve. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 8/ 7/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkStopLinkResolve proc far uses ax, bx, cx, dx, di, es .enter EC < tst cx > EC < ERROR_E TCPIP_INTERNAL_ERROR ; should be non-zero > ; ; If no link driver, just exit. ; mov bx, handle dgroup call MemDerefES tst_clc es:[di].LCB_drvr jz exit ; ; Load link driver, stop resolve, free driver. ; call LinkLoadLinkDriver ; bx = driver handle jc exit push ds, si call GeodeInfoDriver ; ds:si = driver info movdw esdi, dssi pop ds, si pushdw es:[di].DIS_strategy mov di, DR_SOCKET_STOP_RESOLVE call PROCCALLFIXEDORMOVABLE_PASCAL call LinkUnloadLinkDriver exit: .leave ret LinkStopLinkResolve endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CloseAllLinks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Close all link connections, unregistering the link drivers and unloading them. CALLED BY: TCPIPDETACHALLOWED PASS: es = dgroup RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: For each link, if the link is opened, close it first. Then unregister it and unload the driver. Delete entry for link if not a fixed entry. Caller MUST have regSem P-ed. There are no clients and none can register while caller has regSem P-ed so it's safe to unlock the link table without grabbing the task semaphore. Can't use ChunkArrayEnum because link table needs to be unlocked. Not using loop instruction because CX gets used during the loop. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/ 8/94 Initial version jwu 9/25/95 Unlock link table for drvr calls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CloseAllLinks proc far uses ax, bx, cx, dx, di, si, ds drvrEntry local fptr .enter EC < tst es:[regStatus] > EC < ERROR_NE TCPIP_STILL_REGISTERED > ; ; Process each link connection, backwards as entries may be ; deleted during enumeration. ; movdw bxsi, es:[linkTable] call MemLockExcl mov ds, ax ; *ds:si = link table call ChunkArrayGetCount ; cx = count mov dx, cx dec dx closeLoop: ; ; Only process entries where the driver is loaded because only ; the loopback and main link entries may have a null driver field ; and these entries never get deleted so code. ; mov ax, dx ; ax = index call ChunkArrayElementToPtr ; ds:di = LCB EC < ERROR_C TCPIP_INVALID_DOMAIN_HANDLE > clr cx xchg cx, ds:[di].LCB_drvr jcxz next ; ; If the link is open, close it. Unlock link table during ; calls outside of the TCP driver. ; push ax mov si, ds:[di].LCB_clientHan movdw drvrEntry, ds:[di].LCB_strategy, ax mov al, LS_CLOSED xchg al, ds:[di].LCB_state push ds:[di].LCB_connection call MemUnlockExcl pop bx ; bx = link connection cmp al, LS_CLOSED je closed mov ax, SCT_FULL mov di, DR_SOCKET_DISCONNECT_REQUEST pushdw drvrEntry call PROCCALLFIXEDORMOVABLE_PASCAL closed: ; ; Unregister and unload driver. ; mov bx, si ; bx = client handle mov di, DR_SOCKET_UNREGISTER pushdw drvrEntry call PROCCALLFIXEDORMOVABLE_PASCAL mov bx, cx ; bx = driver handle ; ; Must call LinkUnloadLinkDriver for the main link. ; pop ax push ax cmp ax, MAIN_LINK_DOMAIN_HANDLE jne notMain call LinkUnloadLinkDriver jmp delete notMain: call GeodeFreeDriver ; ; Delete entries for all links other than the loopback and main ; link. ; delete: movdw bxsi, es:[linkTable] call MemLockExcl mov ds, ax ; *ds:si = link array pop ax ; ax = link handle cmp ax, MAIN_LINK_DOMAIN_HANDLE jbe next mov cx, 1 call ChunkArrayDeleteRange next: dec dx LONG jns closeLoop call MemUnlockExcl .leave ret CloseAllLinks endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCheckOpen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Check if the main link is open and that it has the same link address. CALLED BY: TcpipSendDatagramCommon PASS: ds:si = remote address (non-null terminated string) (FXIP: address cannot be in a movable code resource) NOTE: SocketInfoBlock MUST NOT be locked and taskSem MUST NOT be P-ed when this is called! RETURN: carry clear if open ax = link handle else carry set ax = SocketDrError DESTROYED: nothing REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 1/24/96 Initial version ed 6/28/00 DHCP support %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCheckOpen proc far uses bx, cx, di, si, es .enter ; ; If we are using the loopback link, no need to open a link. ; call LinkCheckIfLoopback ; ax = loopback domain handle jnc exit ; ; First check if on the DHCP thread. If so, we don't need to check ; the link status, as it's marked closed but really open. ; mov bx, handle dgroup call MemDerefES mov bx, es:[dhcpThread] cmp bx, ss:[0].TPD_threadHandle jne notDhcp mov ax, MAIN_LINK_DOMAIN_HANDLE jmp exit ; ; Get entry of main link from table. ; notDhcp: call TcpipGainAccessFar segmov es, ds, bx ; es:si = address mov bx, MAIN_LINK_DOMAIN_HANDLE mov cx, bx ; cx = link handle, in case... call LinkTableGetEntry ; ds:di = LCB ; ^hbx = table segxchg es, ds ; es:di = LCB ; ds:si = address cmp es:[di].LCB_state, LS_CLOSED je noGood ; ; Link is open. Compare the link address w/ remote address. ; lodsw xchg cx, ax ; cx = link addr size ; ax = link handle cmp cx, es:[di].LCB_linkSize jne noGood jcxz unlock ; carry already clear add di, offset LCB_linkAddr repe cmpsb je unlock ; carry already clear noGood: mov ax, SDE_DESTINATION_UNREACHABLE stc unlock: call MemUnlockExcl call TcpipReleaseAccessFar exit: .leave ret LinkCheckOpen endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkOpenConnection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Open a link connection. If the connection is already open this does nothing. CALLED BY: TcpipDataConnectRequest TcpipSendDatagramCommon TcpipMediumConnectRequest PASS: ds:si = remote address (non-null terminated string) (FXIP: address cannot be in a movable code resource) cx = timeout value (in ticks) NOTE: SocketInfoBlock MUST NOT be locked and taskSem MUST NOT be P-ed when this is called! RETURN: carry clear if opened ax = domain handle of link connection else carry set if error ax = SocketDrError possibly (SDE_DRIVER_NOT_FOUND SDE_ALREADY_REGISTERED SDE_MEDIUM_BUSY SDE_INSUFFICIENT_MEMORY SDE_LINK_OPEN_FAILED SDE_CONNECTION_TIMEOUT SDE_CONNECTION_RESET SDE_CONNECTION_RESET_BY_PEER) DESTROYED: nothing PSEUDO CODE/STRATEGY: gain access check if loopback if closeCount != 0 or LS_CLOSING, wait until link closed load main link driver if not loaded if connection closed, open it Check link address with current address if connection being opened if address different return medium busy else wait for open to complete return link handle if opened, else error else link is open if address same return success else if no connections close current link open new link else return medium busy release access REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/11/94 Initial version jwu 9/22/95 Unlock link table when calling link driver jwu 7/29/96 Non blocking link connect requests jwu 4/19/97 queue link open requests ed 6/30/00 GCN notification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkOpenConnection proc far uses bx, cx, dx, di, ds, es .enter ; ; If we are using loopback link, no need to open a link. ; call LinkCheckIfLoopback ; ax = loopback domain handle LONG jnc exit segmov es, ds, bx ; es:si = address theStart: ; ; Get entry of main link from table. ; call TcpipGainAccessFar mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ds:di = LCB ; ^hbx = table ; ; If others are waiting for link to close, or link is closing, ; wait for link to close before opening a new connection. ; tst ds:[di].LCB_closeCount jnz waitForClose cmp ds:[di].LCB_state, LS_CLOSING jne setupLink waitForClose: inc ds:[di].LCB_closeCount push ds:[di].LCB_closeSem call MemUnlockExcl ; release table call TcpipReleaseAccessFar pop bx call ThreadPSem ; wait for close jmp theStart ; start over when awake setupLink: ; ; If link driver is not loaded, load and register it now. ; segxchg es, ds ; es:di = LCB ; ds:si = address call LinkSetupMainLink ; ax = SocketDrError LONG jc unlockTable ; ; If link is closed, open it now. ; mov dx, cx ; dx = timeout value cmp es:[di].LCB_state, LS_CLOSED LONG je openNow ; ; Check if link is being opened to same address as current. ; call LinkCompareLinkAddress lahf cmp es:[di].LCB_state, LS_OPEN je isOpen ; ; Link is being opened. If address is different, return medium ; busy. Else wait for open to complete. ; sahf jc mediumBusy ; addrs differ inc es:[di].LCB_semCount push es:[di].LCB_sem call MemUnlockExcl call TcpipReleaseAccessFar pop bx call ThreadPSem ; wait for open ; ; Check if link is opened, returning success or error. ; call TcpipGainAccessFar mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ds:di = LCB ; ^hbx = table cmp ds:[di].LCB_state, LS_OPEN je success ; carry clr from cmp mov ax, ds:[di].LCB_error jmp gotError mediumBusy: mov ax, SDE_MEDIUM_BUSY gotError: stc jmp unlockTable isOpen: ; ; Link is already open. If link address matches, return success. ; If not, close the current connection if it's not busy and open ; a new one. If link cannot be closed, return medium busy. ; sahf jc different success: mov ax, MAIN_LINK_DOMAIN_HANDLE jmp unlockTable ; carry is clr different: ; ; If no connections exist, close current link and reopen another ; one. Unlock link table before calling out of TCP driver. ; test es:[di].LCB_options, mask LO_ALWAYS_BUSY jnz mediumBusy mov ax, MAIN_LINK_DOMAIN_HANDLE call TSocketCheckLinkBusy jc mediumBusy mov ax, es:[di].LCB_connection pushdw es:[di].LCB_strategy call MemUnlockExcl mov_tr bx, ax ; bx = link connection mov ax, SCT_FULL mov di, DR_SOCKET_DISCONNECT_REQUEST call PROCCALLFIXEDORMOVABLE_PASCAL ; ; Relock link table for open attempt. ; segmov es, ds, bx ; es:si = address mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry segxchg es, ds ; es:di = LCB ; ds:si = address openNow: ; ; Store link address and open the link. ; call LinkStoreLinkAddress jc unlockTable mov es:[di].LCB_state, LS_OPENING call MemUnlockExcl ; unlock link table mov ax, TSNT_OPENING call LinkSendNotification ; Send GCN notify call LinkOpenLink ; ax = error or handle jmp releaseAccess unlockTable: call MemUnlockExcl releaseAccess: call TcpipReleaseAccessFar exit: .leave ret LinkOpenConnection endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCheckIfLoopback %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return the domain handle for the loopback link if the remote address is a loopback address. CALLED BY: LinkOpenConnection PASS: ds:si = remote address (not null terminated) RETURN: carry set if not loopback address else ax = loopback domain handle DESTROYED: ax if not loopback address PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 8/24/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCheckIfLoopback proc near uses si .enter lodsw ; ax = size of link part ; ds:si = link part add si, ax ; ds:si = ip addr mov al, ds:[si] cmp al, LOOPBACK_NET jne notLoopback mov ax, LOOPBACK_LINK_DOMAIN_HANDLE jmp exit ; carry clr from cmp notLoopback: stc exit: .leave ret LinkCheckIfLoopback endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkSetupMainLink %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If driver not already loaded, load the main link driver, get its strategy routine and register it. CALLED BY: LinkOpenConnection PASS: es:di = LCB of main link entry RETURN: carry clear if successful else carry set ax = SocketDrError (SDE_DRIVER_NOT_FOUND -- no link driver SDE_ALREADY_REGISTERED -- shouldn't happen SDE_MEDIUM_BUSY -- link driver in use SDE_INSUFFICIENT_MEMORY) DESTROYED: ax if not returned PSEUDO CODE/STRATEGY: Load the default link driver. Get its strategy routine Register it. If registration fails, unload link driver. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkSetupMainLink proc near uses bx, cx, dx, bp, di, si, ds .enter ; ; If link driver already loaded, do nothing. ; tst_clc es:[di].LCB_drvr jnz exit ; ; Load default link driver and get the strategy routine. ; call LinkLoadLinkDriver ; bx = driver handle mov ax, SDE_DRIVER_NOT_FOUND jc exit call GeodeInfoDriver movdw cxdx, ds:[si].DIS_strategy mov es:[di].LCB_drvr, bx movdw es:[di].LCB_strategy, cxdx ; ; Register the link driver. Registration fails if the link ; driver is already registered, either by us or someone else. ; mov bx, handle Strings call MemLock mov ds, ax mov si, offset categoryString mov si, ds:[si] ; ds:si = domain name push di, bx pushdw cxdx call GeodeGetProcessHandle mov_tr ax, bx ; our geode handle mov bx, MAIN_LINK_DOMAIN_HANDLE mov cl, SDT_LINK mov dx, segment TcpipClientStrategy mov bp, offset TcpipClientStrategy ; dx:bp = client entry mov di, DR_SOCKET_REGISTER call PROCCALLFIXEDORMOVABLE_PASCAL ; bx = client handle ; or ax = SocketDrError ; ch, cl = min hdr sizes mov_tr dx, bx pop di, bx call MemUnlock ; preserves flags jc failed mov es:[di].LCB_clientHan, dx ; ; Use larger of two minimum header sizes. ; cmp cl, ch jae haveSize mov cl, ch haveSize: mov es:[di].LCB_minHdr, cl clc exit: .leave ret failed: ; ; Unload link driver. ES:SI = LinkControlBlock. ; clr bx xchg bx, es:[di].LCB_drvr call LinkUnloadLinkDriver stc jmp exit LinkSetupMainLink endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCompareLinkAddress %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Compare the given address with the current link address. CALLED BY: LinkOpenConnection PASS: ds:si = link address es:di = LCB RETURN: carry set if address is the same else carry clear DESTROYED: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 4/19/97 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkCompareLinkAddress proc near uses cx .enter ; ; First compare the size for a quick elimination check. ; mov cx, ds:[si] ; cx = link addr size cmp cx, es:[di].LCB_linkSize jne different jcxz same ; both addrs are null ; ; Same size so compare actual address contents. ; push si, di inc si inc si add di, offset LCB_linkAddr repe cmpsb pop si, di jne different same: clc jmp exit different: stc exit: .leave ret LinkCompareLinkAddress endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkStoreLinkAddress %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Store the link address in the link control block. CALLED BY: LinkOpenConnection PASS: es:di = LinkControlBlock ds:si = remote address (non-null terminated) RETURN: carry set if error ax = SocketDrError else es:di - updated to point to new element DESTROYED: ax, di if not returned PSEUDO CODE/STRATEGY: Resize current element to fit link address store link addr size store link address REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 4/ 7/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkStoreLinkAddress proc near uses bx, cx, si .enter ; ; Resize link entry, if needed. ; lodsw ; ax = size of address mov_tr cx, ax cmp cx, es:[di].LCB_linkSize je storeAddr push si, ds, cx mov bx, handle dgroup call MemDerefDS mov si, ds:[linkTable].chunk segmov ds, es, bx ; *ds:si = chunk array mov ax, MAIN_LINK_DOMAIN_HANDLE add cx, size LinkControlBlock ; cx = new size call ChunkArrayElementResize ; ; Redereference LCB. ; pushf call ChunkArrayElementToPtr segmov es, ds, si ; es:di = LCB popf pop si, ds, cx ; ds:si = address jc error mov es:[di].LCB_linkSize, cx storeAddr: ; ; Copy address into LCB. ; push di add di, offset LCB_linkAddr rep movsb pop di clc exit: .leave ret error: mov ax, SDE_INSUFFICIENT_MEMORY jmp exit LinkStoreLinkAddress endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkOpenLink %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Tell the link driver to establish the link connection, updating the LinkControlBlock with local IP address of link connection, mtu, connection handle and link state. CALLED BY: LinkOpenConnection PASS: ds:si = remote address (non-null terminated) dx = timeout value (in ticks) RETURN: carry set if error ax = SocketDrError else ax = link domain handle DESTROYED: cx, dx, di, ds (allowed by caller) PSEUDO CODE/STRATEGY: NOTE: Caller has access. Return with access held! REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 4/ 7/95 Initial version ed 6/30/00 GCN notification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkOpenLink proc near uses bx, si .enter ; ; Allocate the connection to get a handle. ; segmov es, ds, bx ; es:si = address mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ds:di = LCB mov ax, SDE_NO_ERROR ; reset error xchg ds:[di].LCB_error, ax ; ax = last error mov ds:[di].LCB_lastError, ax ; save last error mov ax, ds:[di].LCB_clientHan pushdw ds:[di].LCB_strategy ; for alloc call MemUnlockExcl mov_tr bx, ax ; bx = client handle mov di, DR_SOCKET_ALLOC_CONNECTION call PROCCALLFIXEDORMOVABLE_PASCAL ; ax = error or handle jc checkError ; ; Store connection handle and open the connection. ; mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ds:di = LCB mov ds:[di].LCB_connection, ax inc ds:[di].LCB_openCount ; one more open attempt push ds:[di].LCB_openCount ; save open count pushdw ds:[di].LCB_strategy call MemUnlockExcl segmov ds, es, bx ; ds:si = link addres mov_tr bx, ax ; bx = conn handle mov cx, dx ; cx = timeout mov ax, ds:[si] ; ax = link addr size inc si inc si ; ds:si = link address mov di, DR_SOCKET_LINK_CONNECT_REQUEST call PROCCALLFIXEDORMOVABLE_PASCAL ; ax = error pop cx ; restore open count jc checkError ; ; Release access and wait for open to complete. ; mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry EC < tst ds:[di].LCB_semCount ; no waiters yet!! > EC < ERROR_NZ TCPIP_INTERNAL_ERROR > inc ds:[di].LCB_semCount push ds:[di].LCB_sem call MemUnlockExcl call TcpipReleaseAccessFar pop bx ; LCB_sem call ThreadPSem ; ; Regain access for caller. ; call TcpipGainAccessFar checkError: mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ; Compare the current open count against the last known open count. ; If different, someone else came along and started opening the ; link again before we woke up, so just retrieve the last error ; and exit. ; cmp cx, ds:[di].LCB_openCount je ourOpen mov ax, ds:[di].LCB_lastError jmp gotError ; ; If state is still OPENING, the alloc or link connect request ; failed immediately. Reset state to CLOSED and returnerror. ; ourOpen: CheckHack <LS_CLOSED lt LS_OPENING> CheckHack <LS_CLOSING lt LS_OPENING> CheckHack <LS_OPENING lt LS_OPEN> cmp ds:[di].LCB_state, LS_OPENING jne checkOpen mov ds:[di].LCB_connection, 0 mov ds:[di].LCB_state, LS_CLOSED push ax mov ax, TSNT_CLOSED call LinkSendNotification pop ax jmp gotError checkOpen: ; ; If link successfully opened, return link handle. ; Else get the error and return that. ; mov ax, MAIN_LINK_DOMAIN_HANDLE ; hope for the best... ja unlockTable ; it's open; carry clr mov ax, ds:[di].LCB_error ; ; If error is SDE_INTERRUPTED, wake up any clients waiting for ; link to close. Keep link table locked so clients can't ; proceed until we're done here. ; cmp ax, SDE_INTERRUPTED jne gotError tst ds:[di].LCB_closeCount jz gotError push bx, ax mov cx, ds:[di].LCB_closeCount mov bx, ds:[di].LCB_closeSem wakeLoop: call ThreadVSem ; destroys AX! loop wakeLoop mov ds:[di].LCB_closeCount, cx ; no more waiters pop bx, ax gotError: stc unlockTable: call MemUnlockExcl ; flags preserved .leave ret LinkOpenLink endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkLoadLinkDriver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Load the link driver used by TCP to establish connections. CALLED BY: LinkSetupMainLink LinkGetMediumAndUnit LinkResolveLinkAddr IPAddressControlAddChild via LinkLoadLinkDriverFar TcpipGetMinDgramHdr via LinkLoadLinkDriverFar PASS: nothing RETURN: carry set if failed else carry clear and bx = link driver's handle DESTROYED: nothing PSEUDO CODE/STRATEGY: Read permanent name of link driver from INI If name read, Try using GeodeUseDriverPermName If success, exit Read long name of link driver from INI Call GeodeUseDriver REVISION HISTORY: Name Date Description ---- ---- ----------- dhunter 8/10/00 Use GeodeUseDriverPermName instead dh 8/22/99 Optimized to use GeodeFind first jwu 7/13/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LocalDefNLString socketString, <"socket", 0> LinkLoadLinkDriverFar proc far call LinkLoadLinkDriver ret LinkLoadLinkDriverFar endp LinkLoadLinkDriver proc near uses ax, cx, dx, di, si, ds, es driverName local FileLongName driverPermName local GEODE_NAME_SIZE dup (char) .enter ; ; Set up category and key strings. ; mov bx, handle Strings call MemLock mov ds, ax mov cx, ax assume ds:Strings mov si, ds:[categoryString] ; ds:si = category str mov dx, ds:[linkDriverPermanentKeyString] ; cx:dx = key string assume ds:nothing ; ; Read the permanent driver name from the INI file. ; push bp ; local var ... segmov es, ss, di lea di, driverPermName mov bp, InitFileReadFlags \ <IFCC_INTACT, 0, 0, GEODE_NAME_SIZE> call InitFileReadString ; cx = # chars read pop bp ; local var ... mov bx, handle Strings call MemUnlock ; unlock strings jc loadDriver ; default to load driver if name unavailable ; ; Pad the name with spaces to the requisite length. ; push di add di, cx ; di <- ptr to last char read + 1 sub cx, 8 ; cx = -(# spaces needed) neg cx ; cx = # spaces needed jcxz padded mov al, C_SPACE rep stosb ; write the spaces padded: pop si ; es:si = permanent name ; ; Use GeodeUseDriverPermName to reuse the driver. This will ; fail if the driver is not loaded. ; push ds segmov ds, es, ax ; ds:si = driver name mov ax, SOCKET_PROTO_MAJOR mov bx, SOCKET_PROTO_MINOR call GeodeUseDriverPermName ; CF set if not found pop ds ; ; If the geode was found, we're done. ; jnc exit ; ; Set up category and key strings. ; loadDriver: mov bx, handle Strings call MemLock mov ds, ax mov cx, ax assume ds:Strings mov si, ds:[categoryString] ; ds:si = category str mov dx, ds:[linkDriverKeyString] ; cx:dx = key string assume ds:nothing ; ; Read the full driver name from the INI file. ; push bp ; local var ... segmov es, ss, di lea di, driverName mov bp, InitFileReadFlags \ <IFCC_INTACT, 0, 0, FILE_LONGNAME_BUFFER_SIZE> call InitFileReadString pop bp ; local var ... mov bx, handle Strings call MemUnlock ; unlock strings jc exit ; ; Switch to the socket directory. ; call FilePushDir mov bx, SP_SYSTEM segmov ds, cs, si mov dx, offset socketString call FileSetCurrentPath jc done ; ; Load the driver. ; segmov ds, es, ax mov_tr si, di ; ds:si = driver name mov ax, SOCKET_PROTO_MAJOR mov bx, SOCKET_PROTO_MINOR call GeodeUseDriver done: call FilePopDir exit: .leave ret LinkLoadLinkDriver endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkUnloadLinkDriver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Unload the link driver used by TCP to establish connections. CALLED BY: LinkSetupMainLink LinkGetMediumAndUnit LinkResolveLinkAddr IPAddressControlAddChild via LinkLoadLinkDriverFar TcpipGetMinDgramHdr via LinkLoadLinkDriverFar CloseAllLinks PASS: bx = link driver's handle RETURN: carry set if library was exited DESTROYED: bx PSEUDO CODE/STRATEGY: Call GeodeFreeDriver. REVISION HISTORY: Name Date Description ---- ---- ----------- dhunter 8/10/00 Removed semaphore nonsense dh 8/22/99 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkUnloadLinkDriverFar proc far call LinkUnloadLinkDriver ret LinkUnloadLinkDriverFar endp LinkUnloadLinkDriver proc near call GeodeFreeDriver ret LinkUnloadLinkDriver endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetMTU %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% C FUNCTION: LinkGetMTU C DECLARATION: extern word _far _far _pascal LinkGetMTU(word link); REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/18/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetGeosConvention LINKGETMTU proc far link:word uses di, ds .enter mov bx, link ; bx = link domain han call LinkTableGetEntry ; ds:di = LCB ; ^hbx = link table mov ax, ds:[di].LCB_mtu ; ax = mtu of link call MemUnlockExcl .leave ret LINKGETMTU endp SetDefaultConvention COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetMediumAndUnit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the medium and unit. CALLED BY: TcpipGetMediumAndUnit PASS: es = dgroup RETURN: carry set if error, else cxdx = MediumType bl = MediumUnitType bp = MediumUnit (port) DESTROYED: nothing PSEUDO CODE/STRATEGY: if main link is loaded get driver strategy else load it and get driver strategy query for the info unload link driver if loaded REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 1/ 5/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkGetMediumAndUnit proc far uses ax, di, si .enter ; ; Find out if link driver is loaded or not. If loaded, get ; its strategy routine, else load the driver and get the strategy ; routine from there. ; push ds mov bx, MAIN_LINK_DOMAIN_HANDLE call LinkTableGetEntry ; ds:si = LCB ; ^hbx = link table movdw cxdx, ds:[di].LCB_strategy mov ax, ds:[di].LCB_drvr call MemUnlockExcl pop ds tst ax je loadDriver clr bx jmp query loadDriver: call LinkLoadLinkDriver ; bx = driver handle jc exit push ds call GeodeInfoDriver movdw cxdx, ds:[si].DIS_strategy pop ds query: ; ; Query link driver for the medium and unit. ; push bx ; driver handle pushdw cxdx mov ax, SGIT_MEDIUM_AND_UNIT mov di, DR_SOCKET_GET_INFO call PROCCALLFIXEDORMOVABLE_PASCAL ; cxdx = MediumType ; bl = MediumUnitType ; bp = MediumUnit (port) ; ; Unload link driver if loaded here for the query. ; pop ax ; driver handle tst_clc ax je exit xchg bx, ax ; bx = driver handle call LinkUnloadLinkDriver xchg bx, ax ; bl = MediumUnitType clc exit: .leave ret LinkGetMediumAndUnit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetMediumAndUnitConnection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Look for a link over the specified MediumAndUnit. If found, return the link domain handle. CALLED BY: TcpipGetMediumConnection PASS: es = dgroup dx:bx = MediumAndUnit ds:si = buffer in which to place link address cx = size of buffer RETURN: carry set if no link is connected over unit of medium else cx = connection handle ax = size of link address, whether it fit in the buffer or not. DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: Enum over links, looking for one with matching MediumAndUnit. If found, return the connection handle. REVISION HISTORY: Name Date Description ---- ---- ----------- CL 2/ 3/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkGetMediumAndUnitConnection proc far uses bx, dx, di, si, ds mediumAndUnit local fptr.MediumAndUnit push dx, bx destBuf local fptr push ds, si destBufSize local word push cx ForceRef mediumAndUnit ; LinkGetMediumAndUnitConnectionCB ForceRef destBuf ; LinkGetMediumAndUnitConnectionCB ForceRef destBufSize ; LinkGetMediumAndUnitConnectionCB .enter movdw bxsi, es:[linkTable] call MemLockExcl mov ds, ax ; *ds:si = link table push bx ; save link table handle mov bx, cs mov di, offset LinkGetMediumAndUnitConnectionCB call ChunkArrayEnum ; ax = link domain handle ; cx = link addr size cmc ; return carry clear if found xchg cx, ax ; return cx = link domain handle ; and ax = address size pop bx call MemUnlockExcl ;flags preserved .leave ret LinkGetMediumAndUnitConnection endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkGetMediumAndUnitConnectionCB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Search for a link connected over MediumAndUnit, returning the link domain handle. CALLED BY: LinkGetMediumAndUnitConnection via ChunkArrayEnum PASS: *ds:si = LinkTable ds:di = LinkControlBlock ss:bp = inherited frame RETURN: carry set if link is found over MediumAndUnit: ax = link domain handle cx = size of link address else carry clear cx, dx preserved. DESTROYED: bx REVISION HISTORY: Name Date Description ---- ---- ----------- CL 2/ 3/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkGetMediumAndUnitConnectionCB proc far uses dx, es .enter inherit LinkGetMediumAndUnitConnection ; ; Don't bother querying for medium and unit if link driver is ; not loaded or if link is closed. ; tst_clc ds:[di].LCB_drvr je exit cmp ds:[di].LCB_state, LS_CLOSED je exit push bp, di pushdw ds:[di].LCB_strategy mov ax, SGIT_MEDIUM_AND_UNIT mov di, DR_SOCKET_GET_INFO call PROCCALLFIXEDORMOVABLE_PASCAL ; cxdx = MediumType ; bl = MediumUnitType ; bp = MediumUnit (port) mov_tr ax, bp ; ax = MediumUnit (port) pop bp, di ; ; Check if medium and unit of link matches. If found, ; return domain handle of the link. ; push bp les bp, mediumAndUnit ; es:bp = MediumAndUnit cmpdw es:[bp].MU_medium, cxdx jne mismatch cmp es:[bp].MU_unitType, bl jne mismatch cmp bl, MUT_NONE ; no unit to check? je copyIt cmp es:[bp].MU_unit, ax jne mismatch copyIt: ; ; Copy the link address into the buffer. ; pop bp push bp push si, di mov si, di ; ds:si <- LCB les di, ss:[destBuf] mov cx, ss:[destBufSize] mov ax, ds:[si].LCB_linkSize inc ax ; another two bytes for the inc ax ; address size word cmp ax, cx ; bigger than dest buf? jae doCopy ; yes -- copy what will fit mov cx, ax ; no -- copy only the address doCopy: add si, offset LCB_linkSize ; external rep of link addr ; includes size word, so start ; move from there rep movsb pop si, di mov_tr cx, ax ; cx <- link address size call ChunkArrayPtrToElement ; ax = link domain handle stc ; abort enum done: pop bp exit: .leave ret mismatch: clc jmp done LinkGetMediumAndUnitConnectionCB endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkCheckLocalAddr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% C FUNCTION: LinkCheckLocalAddr C DECLARATION: extern word _far _far _pascal LinkCheckLocalAddr(word link, dword addr); PSEUDOCODE: Returns non-zero value if address is not the local address of the link. REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 9/30/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetGeosConvention LINKCHECKLOCALADDR proc far link:word, addr:dword uses di, ds .enter mov bx, link call LinkTableGetEntry ; ds:di = LCB ; ^hbx = link table movdw dxax, addr cmpdw dxax, ds:[di].LCB_localAddr je match mov ax, -1 ; non-zero jmp done match: clr ax done: call MemUnlockExcl .leave ret LINKCHECKLOCALADDR endp SetDefaultConvention COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkSendData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% C FUNCTION: LinkSendData C DECLARATION: extern word _far _far _pascal LinkSendData(optr dataBuffer, word link); PSEUDOCODE: If link is closed, drop the packet. logBrkPt is used for swat to set a breakpoint for logging the contents of the packet REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/18/94 Initial version jwu 9/22/95 Unlock link table when calling link driver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetGeosConvention LINKSENDDATA proc far dataBuffer:optr, link:word uses si, di, ds .enter ; ; Make sure link is open before attempting to send data. ; mov bx, link ; bx = link domain han EC < tst bx > EC < ERROR_E LOOPBACK_SHOULD_NOT_REACH_LINK_LEVEL > call LinkTableGetEntry ; ds:di = LCB ; ^hbx = link table mov dx, ds:[di].LCB_clientHan cmp ds:[di].LCB_state, LS_OPEN je linkOpen push ds push bx mov bx, handle dgroup call MemDerefDS mov bx, ds:[dhcpThread] tst bx pop bx pop ds jz notOpen ; ; Unlock the link table before calling out of TCP driver. ; Get the size and data offset from the buffer. ; linkOpen: push bp pushdw ds:[di].LCB_strategy call MemUnlockExcl movdw bxbp, dataBuffer call HugeLMemLock mov es, ax mov di, es:[bp] ; es:di = SPH logBrkPt:: mov ax, es:[di].PH_dataOffset mov cx, es:[di].PH_dataSize call HugeLMemUnlock xchg dx, bx ; ^ldx:bp = buffer ; bx = client handle mov di, DR_SOCKET_SEND_DATAGRAM call PROCCALLFIXEDORMOVABLE_PASCAL pop bp clr ax ; no error jmp exit notOpen: ; ; Free data buffer as it cannot be sent. ; EC < WARNING TCPIP_DISCARDING_OUTPUT_BUFFER > call MemUnlockExcl movdw axcx, dataBuffer call HugeLMemFree mov ax, SDE_DESTINATION_UNREACHABLE exit: .leave ret LINKSENDDATA endp SetDefaultConvention if ERROR_CHECK COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ECCheckLinkDomainHandle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Verify that the domain handle is legal. CALLED BY: TcpipLinkOpened TcpipLinkClosed TcpipReceivePacket PASS: bx = domain handle RETURN: carry set if invalid DESTROYED: nothing PSEUDO CODE/STRATEGY: Ensure that the domain handle does not exceed the number of connections we know about. That's about all we can do... REVISION HISTORY: Name Date Description ---- ---- ----------- jwu 7/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ECCheckLinkDomainHandle proc far uses ax, bx, cx, dx, si, ds .enter mov dx, bx ; dx = link domain handle mov bx, handle dgroup call MemDerefDS movdw bxsi, ds:[linkTable] call MemLockShared mov ds, ax ; *ds:si = link table call ChunkArrayGetCount ; cx = # entries call MemUnlockShared cmp dx, cx ; carry set if < cmc .leave ret ECCheckLinkDomainHandle endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LinkSendNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends out a GCN update on the status of the link CALLED BY: LinkOpenConnection LinkOpenLink PASS: ax - TcpipStatusNotificationType RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- ed 6/30/00 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LinkSendNotification proc far uses ax,bx,cx,dx,si,di,bp .enter ; Record the message mov_tr bp, ax mov ax, MSG_META_NOTIFY mov cx, MANUFACTURER_ID_GEOWORKS mov dx, GWNT_TCPIP_LINK_STATUS clr bx, si mov di, mask MF_RECORD call ObjMessage ; Send it off to the GCN list mov bx, MANUFACTURER_ID_GEOWORKS mov ax, GCNSLT_TCPIP_STATUS_NOTIFICATIONS mov cx, di clr dx mov bp, mask GCNLSF_SET_STATUS call GCNListSend .leave ret LinkSendNotification endp LinkCode ends
libsrc/_DEVELOPMENT/math/float/math32/lm32/c/sccz80/round.asm
jpoikela/z88dk
0
85227
SECTION code_fp_math32 PUBLIC round EXTERN cm32_sccz80_round defc round = cm32_sccz80_round ; SDCC bridge for Classic IF __CLASSIC PUBLIC _round defc _round = round ENDIF
programs/oeis/063/A063732.asm
neoneye/loda
22
22897
<filename>programs/oeis/063/A063732.asm ; A063732: Numbers n such that Lucas representation of n excludes L_0 = 2. ; 0,1,3,4,5,7,8,10,11,12,14,15,16,18,19,21,22,23,25,26,28,29,30,32,33,34,36,37,39,40,41,43,44,45,47,48,50,51,52,54,55,57,58,59,61,62,63,65,66,68,69,70,72,73,75,76,77,79,80,81,83,84,86,87,88,90 mul $0,2 mov $1,$0 add $0,1 add $1,2 seq $1,90909 ; Terms a(k) of A073869 for which a(k-1), a(k) and a(k+1) are distinct. div $1,2 mov $2,$1 lpb $1 mov $1,1 lpe lpb $1 mul $0,2 sub $1,1 add $2,1 sub $0,$2 add $0,3 mul $0,2 lpe sub $0,4 div $0,2
T1.asm
matprado/Calculadora_Assembly
0
8963
#Trabalho 1 de Organização e Arquitetura de Computadores. #O objetivo desse trabalho é fazer um programa em Assembly MIPS que simule uma calculadora com #determinadas operações. #Convenção: argumentos para os procedimentos sempre ficam entre os registradores $a0, ..., $a3(ou $f.. para valores flutuantes) # e retorno sempre em $v0 e/ou $v1; #ATENÇÃO: APENAS DIVISÃO E IMC TRATAM NÚMEROS FLOAT #data: .data .align 0 ponteiro: .word str_menu: .asciiz "Escolha uma das seguintes opções:\n" str_op0: .asciiz "Opção 0 -> Soma;\n" str_op1: .asciiz "Opção 1 -> Subtração;\n" str_op2: .asciiz "Opção 2 -> Multiplicação;\n" str_op3: .asciiz "Opção 3 -> Divisão;\n" str_op4: .asciiz "Opção 4 -> Potência;\n" str_op5: .asciiz "Opção 5 -> Raiz quadrada;\n" str_op6: .asciiz "Opção 6 -> Tabuada de um número;\n" str_op7: .asciiz "Opção 7 -> Cálculo de IMC;\n" str_op8: .asciiz "Opção 8 -> Fatorial;\n" str_op9: .asciiz "Opção 9 -> Sequência de Fibonacci;\n" str_op10: .asciiz "Opção 10 -> Sair do programa;\n" str_dig1_32b: .asciiz "Digite um número(até 32 bits):" str_dig2_32b: .asciiz "Digite outro número(até 32 bits):" str_dig1_16b: .asciiz "Digite um número(até 16 bits):" str_dig2_16b: .asciiz "Digite outro número(até 16 bits):" str_peso: .asciiz "Digite o peso(em kg)(até 16 bits):" str_altura: .asciiz "Digite a altura:(em m)(até 16 bits):" str_res: .asciiz "O resultado é: " str_fim: .asciiz "Fim de execução.\n" str_erro: .asciiz "Erro -> Opção Inválida!\n" str_erro_16b: .asciiz "Erro -> Número digitado excede os 16 bits.\n" str_erro_div_zero: .asciiz "Erro -> Divisão por zero!\n" str_erro_raiz_neg: .asciiz "Erro -> Raiz negativa!\n" str_barra_n: .asciiz "\n" str_virgula: .asciiz ", " .align 2 float_16b: .float 65535.0 float_zero: .float 0.0 #text: .text .globl main main: #seta os valores de comparação: li $t0, 1 li $t1, 2 li $t2, 3 li $t3, 4 li $t4, 5 li $t5, 6 li $t6, 7 li $t7, 8 li $t8, 9 li $t9, 10 #variável auxiliar para o loop do switch: li $v1, 1 j switch erro: li $v0, 4 la $a0, str_erro syscall switch: #imprimir menu e opções: li $v0, 4 la $a0, str_menu syscall la $a0, str_op0 syscall la $a0, str_op1 syscall la $a0, str_op2 syscall la $a0, str_op3 syscall la $a0, str_op4 syscall la $a0, str_op5 syscall la $a0, str_op6 syscall la $a0, str_op7 syscall la $a0, str_op8 syscall la $a0, str_op9 syscall la $a0, str_op10 syscall #ler opção digitada: li $v0, 5 syscall #seleciona o label para onde realizará o brench blt $v0, $zero, erro beq $v0, $zero, op0 beq $v0, $t0, op1 beq $v0, $t1, op2 beq $v0, $t2, op3 beq $v0, $t3, op4 beq $v0, $t4, op5 beq $v0, $t5, op6 beq $v0, $t6, op7 beq $v0, $t7, op8 beq $v0, $t8, op9 beq $v0, $t9, op10 bgt $v0, $t9, erro #Soma op0: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o primeiro número li $v0, 5 syscall #argumento do procedimento soma move $a1, $v0 #imprime str_dig2_32b li $v0, 4 la $a0, str_dig2_32b syscall #lê o segundo número li $v0, 5 syscall move $a0, $a1 #primeiro argumento no a0 #argumento do procedimento soma move $a1, $v0 jal soma #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Subtração op1: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o primeiro número li $v0, 5 syscall #argumento do procedimento subtrair move $a1, $v0 #imprime str_dig2_32b li $v0, 4 la $a0, str_dig2_32b syscall #lê o segundo número li $v0, 5 syscall move $a0, $a1 #primeiro argumento no a0 #argumento do procedimento subtrair move $a1, $v0 jal subtracao #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Multiplicação op2: #imprime str_dig1_16b li $v0, 4 la $a0, str_dig1_16b syscall #lê o primeiro número li $v0, 5 syscall #argumento do procedimento multiplicar move $a1, $v0 #confere se o número digitado cabe em 16 bits li $v0, 65535 #v0 = (2^16 - 1) bgt $a1, $v0, erro_16b #imprime str_dig2_16b li $v0, 4 la $a0, str_dig2_16b syscall #lê o segundo número li $v0, 5 syscall move $a0, $a1 #primeiro argumento no a0 #argumento do procedimento multiplicar move $a1, $v0 #confere se o número digitado cabe em 16 bits li $v0, 65535 #v0 = (2^16 - 1) bgt $a1, $v0, erro_16b jal multiplicacao #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Divisão op3: #imprime str_dig1_16b li $v0, 4 la $a0, str_dig1_16b syscall #lê o primeiro número li $v0, 6 syscall #argumento do procedimento dividir mov.s $f1, $f0 #confere se o número digitado cabe em 16 bits l.s $f2, float_16b #f2 = (2^16 - 1) c.lt.s $f2, $f1 bc1t erro_16b #imprime str_dig2_16b li $v0, 4 la $a0, str_dig2_16b syscall #lê o segundo número li $v0, 6 syscall #primeiro argumento está no $f1, segundo no $f0 #confere se o número digitado cabe em 16 bits c.lt.s $f2, $f0 bc1t erro_16b #$v1 == 0 (inicializa sem erro) li $v1, 0 #swap entre $f0 e $f1 mov.s $f2, $f0 mov.s $f0, $f1 mov.s $f1, $f2 jal divisao #confere se o $v1 é 1(erro de divisão por 0) bne $v1, $zero, erro_div_zero #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno mov.s $f12, $f2 li $v0, 2 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch erro_div_zero: li $v0, 4 la $a0, str_erro_div_zero syscall j switch #Potenciação op4: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o primeiro número li $v0, 5 syscall #argumento do procedimento potencia move $a1, $v0 #imprime str_dig2_32b li $v0, 4 la $a0, str_dig2_32b syscall #lê o segundo número li $v0, 5 syscall move $a0, $a1 #primeiro argumento no a0 #argumento do procedimento potencia move $a1, $v0 jal potencia #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Raiz quadrada op5: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o número li $v0, 5 syscall #argumento do procedimento raiz move $a0, $v0 jal raiz_quadrada #confere se o $v1 é 1(erro de raiz de numero negativo) blt $v1, $zero, erro_raiz_neg #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch erro_raiz_neg: li $v0, 4 la $a0, str_erro_raiz_neg syscall j switch #Tabuada op6: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o número li $v0, 5 syscall #argumento do procedimento tabuada move $a0, $v0 jal tabuada j switch #Cálculo de IMC op7: #imprime str_altura li $v0, 4 la $a0, str_altura syscall #lê o primeiro número li $v0, 6 syscall #argumento do procedimento imc mov.s $f1, $f0 #confere se o número digitado cabe em 16 bits l.s $f2, float_16b #f2 = (2^16 - 1) c.lt.s $f2, $f1 bc1t erro_16b #imprime str_peso li $v0, 4 la $a0, str_peso syscall #lê o segundo número li $v0, 6 syscall #confere se o número digitado cabe em 16 bits c.lt.s $f2, $f0 bc1t erro_16b li $v1, 0 #seta erro para zero jal IMC bne $v1, $zero, erro_div_zero #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno mov.s $f12, $f2 li $v0, 2 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Fatorial op8: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o número li $v0, 5 syscall #argumento do procedimento fatorial move $a0, $v0 jal fatorial #argumento para imprimir posteriormente move $a1, $v0 #imprime str_res li $v0, 4 la $a0, str_res syscall #imprime o retorno move $a0, $a1 li $v0, 1 syscall #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall j switch #Fibonacci op9: #imprime str_dig1_32b li $v0, 4 la $a0, str_dig1_32b syscall #lê o primeiro número li $v0, 5 syscall #argumento do procedimento fibonacci move $a1, $v0 #imprime str_dig2_32b li $v0, 4 la $a0, str_dig2_32b syscall #lê o segundo número li $v0, 5 syscall move $a0, $a1 #primeiro argumento no a0 #argumento do procedimento fibonacci move $a1, $v0 jal fibonacci_em_intervalo j switch op10: #imprime mensagem de encerramento li $v0, 4 la $a0, str_fim syscall #sai do programa li $v0, 10 syscall erro_16b: #imprime mensagem de erro li $v0, 4 la $a0, str_erro_16b syscall j switch #Procedimentos: #procedimento soma: #parâmetros: $a0, $a1 #retorno: $v0 soma: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) add $v0, $a0, $a1 #soma os dois numeros dados e salva em v0 lw $a0, 0($sp) lw $a1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #procedimento subtracao: #parâmetros: $a0, $a1 #retorno: $v0 subtracao: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) sub $v0, $a0, $a1 #subtrai os dois numeros dados e salva em v0 lw $a0, 0($sp) lw $a1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #procedimento multiplicacao: #parâmetros: $a0, $a1 #retorno: $v0 multiplicacao: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) mul $v0, $a0, $a1 #multiplica os dois numeros dados e salva em v0 lw $a0, 0($sp) lw $a1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #procedimento divisao: #parâmetros: $f0, $f1 #retorno: $f2(resultado), $v1(erro) divisao: addi $sp, $sp, -12 s.s $f0, 0($sp) s.s $f1, 4($sp) sw $ra, 8($sp) #trata o caso de divisão por zero l.s $f2 , float_zero c.eq.s $f1, $f2 bc1t erro_divisao div.s $f2, $f0, $f1 #divide os dois numeros dados e salva o resultado em $f2 j retorna_divisao erro_divisao: li $v1, 1 retorna_divisao: l.s $f0, 0($sp) l.s $f1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #procedimento IMC: #parâmetros: $f0, $f1 (peso e altura, respectivamente) #retorno: $f2(IMC), $v1(erro) IMC: addi $sp, $sp, -12 s.s $f0, 0($sp) s.s $f1, 4($sp) sw $ra, 8($sp) #trata o caso de erro da altura == 0, para não dividir por 0 l.s $f2, float_zero c.eq.s $f1, $f2 bc1t erro_IMC mul.s $f2, $f1, $f1 #f2 = altura * altura div.s $f2, $f0, $f2 #f2 = peso / v0 j retorna_IMC erro_IMC: li $v1, 1 retorna_IMC: l.s $f0, 0($sp) l.s $f1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #procedimento fatorial recursivo: recebe como parametro o inteiro em $a0 e retorna o fatorial dele em $v0 fatorial: #armazena $a0 e $ra na pilha addi $sp, $sp, -8 sw $a0, 0($sp) sw $ra, 4($sp) ble $a0, $zero, retorna1 #a0 <= 0, retorna 1 subi $a0, $a0, 1 #a0-- jal fatorial #chamada recursiva addi $a0, $a0, 1 #evita que multiplique v0 por 0 mul $v0, $v0, $a0 j retorna_fat retorna1: li $v0, 1 retorna_fat: #recupera da pilha lw $a0, 0($sp) lw $ra, 4($sp) addi $sp, $sp, 8 #return jr $ra #Procedimento potencia recebe argumentos $a0 e $a1 e retorna em $v0 o resultado; #a0 base #a1 potencia desejada potencia: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) li $v0, 1 powLoop: beqz $a1, exit_powLoop mul $v0, $v0, $a0 addi $a1, $a1, -1 j powLoop exit_powLoop: lw $a0, 0($sp) lw $a1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #Procedimento raiz_quadrada recebe como argumento o $a0 e retorna sua raiz em $v0. #a0 base da raiz raiz_quadrada: #a0 base da raiz #EMPILHANDO $t0, $ra, $a0 addi $sp, $sp, -28 # $sp = $sp - 28 sw $t0, 0($sp) sw $t1, 4($sp) sw $t2, 8($sp) sw $t3, 12($sp) sw $t4, 16($sp) sw $ra, 20($sp) sw $a0, 24($sp) #COPIANDO O VALOR 2 PARA $t0 addi $t0, $zero, 2 # $t0 = zero + 2 addi $t1, $a0, 0 # $t1 = $a0 + 0 div $t1, $t0 # $t1 / $t0 mflo $t1 # send to $t1 quocient of div addi $t0, $zero, 0 # $t0 = $zero + 0 addi $t2, $a0, 0 # $t2 = $a0 + 0 addi $t4, $zero, 2 # $t4 = $zero + 2 rootLoop: bge $t0, $t1, exit_rootLoop # if $t0 >= $t1 then exit_rootLoop div $a0, $t2 # $a0 / $t2 mflo $t3 # send to $t3 quocient of div add $t2, $t3, $t2 # $t0 = $t3 + $t2 div $t2, $t4 # $t2 / $t4(2) mflo $t2 # send to $ quocient of div addi $t0, $t0, 1 # $t0 = $t0 + 1 j rootLoop # jump to rootLoop exit_rootLoop: add $v0, $t2, $zero # $v0 = $t2 + $zero lw $t0, 0($sp) lw $t1, 4($sp) lw $t2, 8($sp) lw $t3, 12($sp) lw $t4, 16($sp) lw $ra, 20($sp) lw $a0, 24($sp) addi $sp, $sp, 28 # $sp = $sp + 28 jr $ra # jump to $ra #Procedimento tabuada recebe como argumento o $a0. #a0 é o número que se deseja mostrar a tabuada. tabuada: #a0 como numero base para a tabuada addi $sp, $sp, -16 # $sp = $sp - 20 sw $ra, 0($sp) sw $t0, 4($sp) sw $t1, 8($sp) sw $t2, 12($sp) sw $a0, 16($sp) addi $t0, $zero, 1 # $t0 = $zero + 1 addi $t1, $zero, 10 # $t1 = $zero + 10 add $t2, $zero, $a0 # $t2 = $zero + $a0 tabuadaLoop: bgt $t0, $t1, tabuada_exitLoop # if $t0 > $t1 then tabuada_exitLoop add $a0, $zero, $t2 # $a0 = $zero + $t2 mult $a0, $t0 # $a0 * $t0 = Hi and Lo registers mflo $a0 # copy Lo to $a0 li $v0, 1 # $v0 = 1 syscall #printing integer #imprime str_barra_n li $v0, 4 la $a0, str_barra_n syscall addi $t0, $t0, 1 # $t0 = $zero + 1 j tabuadaLoop #jump to tabuadaLoop tabuada_exitLoop: lw $ra, 0($sp) lw $t0, 4($sp) lw $t1, 8($sp) lw $t2, 12($sp) lw $a0, 16($sp) addi $sp, $sp, 16 # $sp = $sp + 20 jr $ra # jump to $ra #Procedimento fibonacci_em_intervalo recebe como argumentos $a0 e $a1 com o intervalo de fibonacci desejado # e chama o procedimento fibonacci para cada valor do intervalo imprimindo seu resultado; fibonacci_em_intervalo: addi $sp, $sp, -12 sw $a0, 0($sp) sw $a1, 4($sp) sw $ra, 8($sp) subi $a0, $a0, 1 #loop para calcular o fibonacci de cada número do intervalo e imprimir este número loop_fibo: beq $a0, $a1, fim_loop_fibo jal fibonacci #retorno em $v0 #imprime retorno move $s0, $a0 move $s1, $v0 li $v0, 1 move $a0, $s1 syscall li $v0, 4 la $a0, str_virgula syscall move $a0, $s0 addi $a0, $a0, 1 j loop_fibo fim_loop_fibo: li $v0, 4 la $a0, str_barra_n syscall lw $a0, 0($sp) lw $a1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra #Procedimento fibonacci recebe como parâmetro $a0 para o número da sequência de fibonacci fibonacci: addi $sp, $sp, -16 sw $s0, 0($sp) sw $s1, 4($sp) sw $a0, 8($sp) sw $ra, 12($sp) li $s2, 0 slti $s2, $a0, 2 #se a0 menor que 2, s2 é 1 beq $s2, $zero, retorna_fib #se s2 for 0, vai pro retorna_fib addi $v0, $zero, 1 #últimas 2 chamadas da recursão j retorna retorna_fib: addi $s0, $a0, 0 addi $a0, $a0, -1 jal fibonacci addi $s1, $v0, 0 addi $a0, $s0, -2 jal fibonacci add $v0, $s1, $v0 #v0 tem o resultado retorna: lw $s0, 0($sp) lw $s1, 4($sp) lw $a0, 8($sp) lw $ra, 12($sp) addi $sp, $sp, 16 jr $ra
other.7z/NEWS.7z/NEWS/テープリストア/NEWS_05/NEWS_05.tar/home/kimura/kart/risc.lzh/risc/join/Object.asm
prismotizm/gigaleak
0
91447
<filename>other.7z/NEWS.7z/NEWS/テープリストア/NEWS_05/NEWS_05.tar/home/kimura/kart/risc.lzh/risc/join/Object.asm Name: Object.asm Type: file Size: 21179 Last-Modified: '1992-11-18T01:48:24Z' SHA-1: 090EDF701B6F46B8B7A37C9A8D850ABF035EFF69 Description: null
Ada/inc/Problem_36.ads
Tim-Tom/project-euler
0
16305
package Problem_36 is procedure Solve; end Problem_36;
oeis/138/A138401.asm
neoneye/loda-programs
11
10219
; A138401: a(n) = prime(n)^4 - prime(n). ; 14,78,620,2394,14630,28548,83504,130302,279818,707252,923490,1874124,2825720,3418758,4879634,7890428,12117302,13845780,20151054,25411610,28398168,38950002,47458238,62742152,88529184,104060300,112550778,131079494,141158052,163047248,260144514,294499790,352275224,373300902,492884252,519885450,607573044,705911598,777796154,895744868,1026625502,1073282940,1330863170,1387487808,1506138284,1568239002,1982119230,2472973218,2655237614,2750058252,2947295288,3262808402,3373402320,3969125750,4362470144 seq $0,40 ; The prime numbers. sub $1,$0 pow $0,4 add $1,$0 mov $0,$1
support/MinGW/lib/gcc/mingw32/9.2.0/adainclude/a-cforse.adb
orb-zhuchen/Orb
0
22609
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- A D A . C O N T A I N E R S . F O R M A L _ O R D E R E D _ S E T S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2010-2019, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- ------------------------------------------------------------------------------ with Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations); with Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys); with Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations; pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations); with System; use type System.Address; package body Ada.Containers.Formal_Ordered_Sets with SPARK_Mode => Off is ------------------------------ -- Access to Fields of Node -- ------------------------------ -- These subprograms provide functional notation for access to fields -- of a node, and procedural notation for modifiying these fields. function Color (Node : Node_Type) return Red_Black_Trees.Color_Type; pragma Inline (Color); function Left_Son (Node : Node_Type) return Count_Type; pragma Inline (Left_Son); function Parent (Node : Node_Type) return Count_Type; pragma Inline (Parent); function Right_Son (Node : Node_Type) return Count_Type; pragma Inline (Right_Son); procedure Set_Color (Node : in out Node_Type; Color : Red_Black_Trees.Color_Type); pragma Inline (Set_Color); procedure Set_Left (Node : in out Node_Type; Left : Count_Type); pragma Inline (Set_Left); procedure Set_Right (Node : in out Node_Type; Right : Count_Type); pragma Inline (Set_Right); procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type); pragma Inline (Set_Parent); ----------------------- -- Local Subprograms -- ----------------------- -- Comments needed??? generic with procedure Set_Element (Node : in out Node_Type); procedure Generic_Allocate (Tree : in out Tree_Types.Tree_Type'Class; Node : out Count_Type); procedure Free (Tree : in out Set; X : Count_Type); procedure Insert_Sans_Hint (Container : in out Set; New_Item : Element_Type; Node : out Count_Type; Inserted : out Boolean); procedure Insert_With_Hint (Dst_Set : in out Set; Dst_Hint : Count_Type; Src_Node : Node_Type; Dst_Node : out Count_Type); function Is_Greater_Element_Node (Left : Element_Type; Right : Node_Type) return Boolean; pragma Inline (Is_Greater_Element_Node); function Is_Less_Element_Node (Left : Element_Type; Right : Node_Type) return Boolean; pragma Inline (Is_Less_Element_Node); function Is_Less_Node_Node (L, R : Node_Type) return Boolean; pragma Inline (Is_Less_Node_Node); procedure Replace_Element (Tree : in out Set; Node : Count_Type; Item : Element_Type); -------------------------- -- Local Instantiations -- -------------------------- package Tree_Operations is new Red_Black_Trees.Generic_Bounded_Operations (Tree_Types, Left => Left_Son, Right => Right_Son); use Tree_Operations; package Element_Keys is new Red_Black_Trees.Generic_Bounded_Keys (Tree_Operations => Tree_Operations, Key_Type => Element_Type, Is_Less_Key_Node => Is_Less_Element_Node, Is_Greater_Key_Node => Is_Greater_Element_Node); package Set_Ops is new Red_Black_Trees.Generic_Bounded_Set_Operations (Tree_Operations => Tree_Operations, Set_Type => Set, Assign => Assign, Insert_With_Hint => Insert_With_Hint, Is_Less => Is_Less_Node_Node); --------- -- "=" -- --------- function "=" (Left, Right : Set) return Boolean is Lst : Count_Type; Node : Count_Type; ENode : Count_Type; begin if Length (Left) /= Length (Right) then return False; end if; if Is_Empty (Left) then return True; end if; Lst := Next (Left, Last (Left).Node); Node := First (Left).Node; while Node /= Lst loop ENode := Find (Right, Left.Nodes (Node).Element).Node; if ENode = 0 or else Left.Nodes (Node).Element /= Right.Nodes (ENode).Element then return False; end if; Node := Next (Left, Node); end loop; return True; end "="; ------------ -- Assign -- ------------ procedure Assign (Target : in out Set; Source : Set) is procedure Append_Element (Source_Node : Count_Type); procedure Append_Elements is new Tree_Operations.Generic_Iteration (Append_Element); -------------------- -- Append_Element -- -------------------- procedure Append_Element (Source_Node : Count_Type) is SN : Node_Type renames Source.Nodes (Source_Node); procedure Set_Element (Node : in out Node_Type); pragma Inline (Set_Element); function New_Node return Count_Type; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Unconditional_Insert_Sans_Hint is new Element_Keys.Generic_Unconditional_Insert (Insert_Post); procedure Unconditional_Insert_Avec_Hint is new Element_Keys.Generic_Unconditional_Insert_With_Hint (Insert_Post, Unconditional_Insert_Sans_Hint); procedure Allocate is new Generic_Allocate (Set_Element); -------------- -- New_Node -- -------------- function New_Node return Count_Type is Result : Count_Type; begin Allocate (Target, Result); return Result; end New_Node; ----------------- -- Set_Element -- ----------------- procedure Set_Element (Node : in out Node_Type) is begin Node.Element := SN.Element; end Set_Element; -- Local variables Target_Node : Count_Type; -- Start of processing for Append_Element begin Unconditional_Insert_Avec_Hint (Tree => Target, Hint => 0, Key => SN.Element, Node => Target_Node); end Append_Element; -- Start of processing for Assign begin if Target'Address = Source'Address then return; end if; if Target.Capacity < Source.Length then raise Constraint_Error with "Target capacity is less than Source length"; end if; Tree_Operations.Clear_Tree (Target); Append_Elements (Source); end Assign; ------------- -- Ceiling -- ------------- function Ceiling (Container : Set; Item : Element_Type) return Cursor is Node : constant Count_Type := Element_Keys.Ceiling (Container, Item); begin if Node = 0 then return No_Element; end if; return (Node => Node); end Ceiling; ----------- -- Clear -- ----------- procedure Clear (Container : in out Set) is begin Tree_Operations.Clear_Tree (Container); end Clear; ----------- -- Color -- ----------- function Color (Node : Node_Type) return Red_Black_Trees.Color_Type is begin return Node.Color; end Color; -------------- -- Contains -- -------------- function Contains (Container : Set; Item : Element_Type) return Boolean is begin return Find (Container, Item) /= No_Element; end Contains; ---------- -- Copy -- ---------- function Copy (Source : Set; Capacity : Count_Type := 0) return Set is Node : Count_Type; N : Count_Type; Target : Set (Count_Type'Max (Source.Capacity, Capacity)); begin if 0 < Capacity and then Capacity < Source.Capacity then raise Capacity_Error; end if; if Length (Source) > 0 then Target.Length := Source.Length; Target.Root := Source.Root; Target.First := Source.First; Target.Last := Source.Last; Target.Free := Source.Free; Node := 1; while Node <= Source.Capacity loop Target.Nodes (Node).Element := Source.Nodes (Node).Element; Target.Nodes (Node).Parent := Source.Nodes (Node).Parent; Target.Nodes (Node).Left := Source.Nodes (Node).Left; Target.Nodes (Node).Right := Source.Nodes (Node).Right; Target.Nodes (Node).Color := Source.Nodes (Node).Color; Target.Nodes (Node).Has_Element := Source.Nodes (Node).Has_Element; Node := Node + 1; end loop; while Node <= Target.Capacity loop N := Node; Formal_Ordered_Sets.Free (Tree => Target, X => N); Node := Node + 1; end loop; end if; return Target; end Copy; ------------ -- Delete -- ------------ procedure Delete (Container : in out Set; Position : in out Cursor) is begin if not Has_Element (Container, Position) then raise Constraint_Error with "Position cursor has no element"; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Delete"); Tree_Operations.Delete_Node_Sans_Free (Container, Position.Node); Formal_Ordered_Sets.Free (Container, Position.Node); Position := No_Element; end Delete; procedure Delete (Container : in out Set; Item : Element_Type) is X : constant Count_Type := Element_Keys.Find (Container, Item); begin if X = 0 then raise Constraint_Error with "attempt to delete element not in set"; end if; Tree_Operations.Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end Delete; ------------------ -- Delete_First -- ------------------ procedure Delete_First (Container : in out Set) is X : constant Count_Type := Container.First; begin if X /= 0 then Tree_Operations.Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end if; end Delete_First; ----------------- -- Delete_Last -- ----------------- procedure Delete_Last (Container : in out Set) is X : constant Count_Type := Container.Last; begin if X /= 0 then Tree_Operations.Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end if; end Delete_Last; ---------------- -- Difference -- ---------------- procedure Difference (Target : in out Set; Source : Set) is begin Set_Ops.Set_Difference (Target, Source); end Difference; function Difference (Left, Right : Set) return Set is begin if Left'Address = Right'Address then return Empty_Set; end if; if Length (Left) = 0 then return Empty_Set; end if; if Length (Right) = 0 then return Left.Copy; end if; return S : Set (Length (Left)) do Assign (S, Set_Ops.Set_Difference (Left, Right)); end return; end Difference; ------------- -- Element -- ------------- function Element (Container : Set; Position : Cursor) return Element_Type is begin if not Has_Element (Container, Position) then raise Constraint_Error with "Position cursor has no element"; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Element"); return Container.Nodes (Position.Node).Element; end Element; ------------------------- -- Equivalent_Elements -- ------------------------- function Equivalent_Elements (Left, Right : Element_Type) return Boolean is begin if Left < Right or else Right < Left then return False; else return True; end if; end Equivalent_Elements; --------------------- -- Equivalent_Sets -- --------------------- function Equivalent_Sets (Left, Right : Set) return Boolean is function Is_Equivalent_Node_Node (L, R : Node_Type) return Boolean; pragma Inline (Is_Equivalent_Node_Node); function Is_Equivalent is new Tree_Operations.Generic_Equal (Is_Equivalent_Node_Node); ----------------------------- -- Is_Equivalent_Node_Node -- ----------------------------- function Is_Equivalent_Node_Node (L, R : Node_Type) return Boolean is begin if L.Element < R.Element then return False; elsif R.Element < L.Element then return False; else return True; end if; end Is_Equivalent_Node_Node; -- Start of processing for Equivalent_Sets begin return Is_Equivalent (Left, Right); end Equivalent_Sets; ------------- -- Exclude -- ------------- procedure Exclude (Container : in out Set; Item : Element_Type) is X : constant Count_Type := Element_Keys.Find (Container, Item); begin if X /= 0 then Tree_Operations.Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end if; end Exclude; ---------- -- Find -- ---------- function Find (Container : Set; Item : Element_Type) return Cursor is Node : constant Count_Type := Element_Keys.Find (Container, Item); begin if Node = 0 then return No_Element; end if; return (Node => Node); end Find; ----------- -- First -- ----------- function First (Container : Set) return Cursor is begin if Length (Container) = 0 then return No_Element; end if; return (Node => Container.First); end First; ------------------- -- First_Element -- ------------------- function First_Element (Container : Set) return Element_Type is Fst : constant Count_Type := First (Container).Node; begin if Fst = 0 then raise Constraint_Error with "set is empty"; end if; declare N : Tree_Types.Nodes_Type renames Container.Nodes; begin return N (Fst).Element; end; end First_Element; ----------- -- Floor -- ----------- function Floor (Container : Set; Item : Element_Type) return Cursor is begin declare Node : constant Count_Type := Element_Keys.Floor (Container, Item); begin if Node = 0 then return No_Element; end if; return (Node => Node); end; end Floor; ------------------ -- Formal_Model -- ------------------ package body Formal_Model is ------------------------- -- E_Bigger_Than_Range -- ------------------------- function E_Bigger_Than_Range (Container : E.Sequence; Fst : Positive_Count_Type; Lst : Count_Type; Item : Element_Type) return Boolean is begin for I in Fst .. Lst loop if not (E.Get (Container, I) < Item) then return False; end if; end loop; return True; end E_Bigger_Than_Range; ------------------------- -- E_Elements_Included -- ------------------------- function E_Elements_Included (Left : E.Sequence; Right : E.Sequence) return Boolean is begin for I in 1 .. E.Length (Left) loop if not E.Contains (Right, 1, E.Length (Right), E.Get (Left, I)) then return False; end if; end loop; return True; end E_Elements_Included; function E_Elements_Included (Left : E.Sequence; Model : M.Set; Right : E.Sequence) return Boolean is begin for I in 1 .. E.Length (Left) loop declare Item : constant Element_Type := E.Get (Left, I); begin if M.Contains (Model, Item) then if not E.Contains (Right, 1, E.Length (Right), Item) then return False; end if; end if; end; end loop; return True; end E_Elements_Included; function E_Elements_Included (Container : E.Sequence; Model : M.Set; Left : E.Sequence; Right : E.Sequence) return Boolean is begin for I in 1 .. E.Length (Container) loop declare Item : constant Element_Type := E.Get (Container, I); begin if M.Contains (Model, Item) then if not E.Contains (Left, 1, E.Length (Left), Item) then return False; end if; else if not E.Contains (Right, 1, E.Length (Right), Item) then return False; end if; end if; end; end loop; return True; end E_Elements_Included; --------------- -- E_Is_Find -- --------------- function E_Is_Find (Container : E.Sequence; Item : Element_Type; Position : Count_Type) return Boolean is begin for I in 1 .. Position - 1 loop if Item < E.Get (Container, I) then return False; end if; end loop; if Position < E.Length (Container) then for I in Position + 1 .. E.Length (Container) loop if E.Get (Container, I) < Item then return False; end if; end loop; end if; return True; end E_Is_Find; -------------------------- -- E_Smaller_Than_Range -- -------------------------- function E_Smaller_Than_Range (Container : E.Sequence; Fst : Positive_Count_Type; Lst : Count_Type; Item : Element_Type) return Boolean is begin for I in Fst .. Lst loop if not (Item < E.Get (Container, I)) then return False; end if; end loop; return True; end E_Smaller_Than_Range; ---------- -- Find -- ---------- function Find (Container : E.Sequence; Item : Element_Type) return Count_Type is begin for I in 1 .. E.Length (Container) loop if Equivalent_Elements (Item, E.Get (Container, I)) then return I; end if; end loop; return 0; end Find; -------------- -- Elements -- -------------- function Elements (Container : Set) return E.Sequence is Position : Count_Type := Container.First; R : E.Sequence; begin -- Can't use First, Next or Element here, since they depend on models -- for their postconditions. while Position /= 0 loop R := E.Add (R, Container.Nodes (Position).Element); Position := Tree_Operations.Next (Container, Position); end loop; return R; end Elements; ---------------------------- -- Lift_Abstraction_Level -- ---------------------------- procedure Lift_Abstraction_Level (Container : Set) is null; ----------------------- -- Mapping_Preserved -- ----------------------- function Mapping_Preserved (E_Left : E.Sequence; E_Right : E.Sequence; P_Left : P.Map; P_Right : P.Map) return Boolean is begin for C of P_Left loop if not P.Has_Key (P_Right, C) or else P.Get (P_Left, C) > E.Length (E_Left) or else P.Get (P_Right, C) > E.Length (E_Right) or else E.Get (E_Left, P.Get (P_Left, C)) /= E.Get (E_Right, P.Get (P_Right, C)) then return False; end if; end loop; return True; end Mapping_Preserved; ------------------------------ -- Mapping_Preserved_Except -- ------------------------------ function Mapping_Preserved_Except (E_Left : E.Sequence; E_Right : E.Sequence; P_Left : P.Map; P_Right : P.Map; Position : Cursor) return Boolean is begin for C of P_Left loop if C /= Position and (not P.Has_Key (P_Right, C) or else P.Get (P_Left, C) > E.Length (E_Left) or else P.Get (P_Right, C) > E.Length (E_Right) or else E.Get (E_Left, P.Get (P_Left, C)) /= E.Get (E_Right, P.Get (P_Right, C))) then return False; end if; end loop; return True; end Mapping_Preserved_Except; ------------------------- -- P_Positions_Shifted -- ------------------------- function P_Positions_Shifted (Small : P.Map; Big : P.Map; Cut : Positive_Count_Type; Count : Count_Type := 1) return Boolean is begin for Cu of Small loop if not P.Has_Key (Big, Cu) then return False; end if; end loop; for Cu of Big loop declare Pos : constant Positive_Count_Type := P.Get (Big, Cu); begin if Pos < Cut then if not P.Has_Key (Small, Cu) or else Pos /= P.Get (Small, Cu) then return False; end if; elsif Pos >= Cut + Count then if not P.Has_Key (Small, Cu) or else Pos /= P.Get (Small, Cu) + Count then return False; end if; else if P.Has_Key (Small, Cu) then return False; end if; end if; end; end loop; return True; end P_Positions_Shifted; ----------- -- Model -- ----------- function Model (Container : Set) return M.Set is Position : Count_Type := Container.First; R : M.Set; begin -- Can't use First, Next or Element here, since they depend on models -- for their postconditions. while Position /= 0 loop R := M.Add (Container => R, Item => Container.Nodes (Position).Element); Position := Tree_Operations.Next (Container, Position); end loop; return R; end Model; --------------- -- Positions -- --------------- function Positions (Container : Set) return P.Map is I : Count_Type := 1; Position : Count_Type := Container.First; R : P.Map; begin -- Can't use First, Next or Element here, since they depend on models -- for their postconditions. while Position /= 0 loop R := P.Add (R, (Node => Position), I); pragma Assert (P.Length (R) = I); Position := Tree_Operations.Next (Container, Position); I := I + 1; end loop; return R; end Positions; end Formal_Model; ---------- -- Free -- ---------- procedure Free (Tree : in out Set; X : Count_Type) is begin Tree.Nodes (X).Has_Element := False; Tree_Operations.Free (Tree, X); end Free; ---------------------- -- Generic_Allocate -- ---------------------- procedure Generic_Allocate (Tree : in out Tree_Types.Tree_Type'Class; Node : out Count_Type) is procedure Allocate is new Tree_Operations.Generic_Allocate (Set_Element); begin Allocate (Tree, Node); Tree.Nodes (Node).Has_Element := True; end Generic_Allocate; ------------------ -- Generic_Keys -- ------------------ package body Generic_Keys with SPARK_Mode => Off is ----------------------- -- Local Subprograms -- ----------------------- function Is_Greater_Key_Node (Left : Key_Type; Right : Node_Type) return Boolean; pragma Inline (Is_Greater_Key_Node); function Is_Less_Key_Node (Left : Key_Type; Right : Node_Type) return Boolean; pragma Inline (Is_Less_Key_Node); -------------------------- -- Local Instantiations -- -------------------------- package Key_Keys is new Red_Black_Trees.Generic_Bounded_Keys (Tree_Operations => Tree_Operations, Key_Type => Key_Type, Is_Less_Key_Node => Is_Less_Key_Node, Is_Greater_Key_Node => Is_Greater_Key_Node); ------------- -- Ceiling -- ------------- function Ceiling (Container : Set; Key : Key_Type) return Cursor is Node : constant Count_Type := Key_Keys.Ceiling (Container, Key); begin if Node = 0 then return No_Element; end if; return (Node => Node); end Ceiling; -------------- -- Contains -- -------------- function Contains (Container : Set; Key : Key_Type) return Boolean is begin return Find (Container, Key) /= No_Element; end Contains; ------------ -- Delete -- ------------ procedure Delete (Container : in out Set; Key : Key_Type) is X : constant Count_Type := Key_Keys.Find (Container, Key); begin if X = 0 then raise Constraint_Error with "attempt to delete key not in set"; end if; Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end Delete; ------------- -- Element -- ------------- function Element (Container : Set; Key : Key_Type) return Element_Type is Node : constant Count_Type := Key_Keys.Find (Container, Key); begin if Node = 0 then raise Constraint_Error with "key not in set"; end if; declare N : Tree_Types.Nodes_Type renames Container.Nodes; begin return N (Node).Element; end; end Element; --------------------- -- Equivalent_Keys -- --------------------- function Equivalent_Keys (Left, Right : Key_Type) return Boolean is begin if Left < Right or else Right < Left then return False; else return True; end if; end Equivalent_Keys; ------------- -- Exclude -- ------------- procedure Exclude (Container : in out Set; Key : Key_Type) is X : constant Count_Type := Key_Keys.Find (Container, Key); begin if X /= 0 then Delete_Node_Sans_Free (Container, X); Formal_Ordered_Sets.Free (Container, X); end if; end Exclude; ---------- -- Find -- ---------- function Find (Container : Set; Key : Key_Type) return Cursor is Node : constant Count_Type := Key_Keys.Find (Container, Key); begin return (if Node = 0 then No_Element else (Node => Node)); end Find; ----------- -- Floor -- ----------- function Floor (Container : Set; Key : Key_Type) return Cursor is Node : constant Count_Type := Key_Keys.Floor (Container, Key); begin return (if Node = 0 then No_Element else (Node => Node)); end Floor; ------------------ -- Formal_Model -- ------------------ package body Formal_Model is ------------------------- -- E_Bigger_Than_Range -- ------------------------- function E_Bigger_Than_Range (Container : E.Sequence; Fst : Positive_Count_Type; Lst : Count_Type; Key : Key_Type) return Boolean is begin for I in Fst .. Lst loop if not (Generic_Keys.Key (E.Get (Container, I)) < Key) then return False; end if; end loop; return True; end E_Bigger_Than_Range; --------------- -- E_Is_Find -- --------------- function E_Is_Find (Container : E.Sequence; Key : Key_Type; Position : Count_Type) return Boolean is begin for I in 1 .. Position - 1 loop if Key < Generic_Keys.Key (E.Get (Container, I)) then return False; end if; end loop; if Position < E.Length (Container) then for I in Position + 1 .. E.Length (Container) loop if Generic_Keys.Key (E.Get (Container, I)) < Key then return False; end if; end loop; end if; return True; end E_Is_Find; -------------------------- -- E_Smaller_Than_Range -- -------------------------- function E_Smaller_Than_Range (Container : E.Sequence; Fst : Positive_Count_Type; Lst : Count_Type; Key : Key_Type) return Boolean is begin for I in Fst .. Lst loop if not (Key < Generic_Keys.Key (E.Get (Container, I))) then return False; end if; end loop; return True; end E_Smaller_Than_Range; ---------- -- Find -- ---------- function Find (Container : E.Sequence; Key : Key_Type) return Count_Type is begin for I in 1 .. E.Length (Container) loop if Equivalent_Keys (Key, Generic_Keys.Key (E.Get (Container, I))) then return I; end if; end loop; return 0; end Find; ----------------------- -- M_Included_Except -- ----------------------- function M_Included_Except (Left : M.Set; Right : M.Set; Key : Key_Type) return Boolean is begin for E of Left loop if not Contains (Right, E) and not Equivalent_Keys (Generic_Keys.Key (E), Key) then return False; end if; end loop; return True; end M_Included_Except; end Formal_Model; ------------------------- -- Is_Greater_Key_Node -- ------------------------- function Is_Greater_Key_Node (Left : Key_Type; Right : Node_Type) return Boolean is begin return Key (Right.Element) < Left; end Is_Greater_Key_Node; ---------------------- -- Is_Less_Key_Node -- ---------------------- function Is_Less_Key_Node (Left : Key_Type; Right : Node_Type) return Boolean is begin return Left < Key (Right.Element); end Is_Less_Key_Node; --------- -- Key -- --------- function Key (Container : Set; Position : Cursor) return Key_Type is begin if not Has_Element (Container, Position) then raise Constraint_Error with "Position cursor has no element"; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Key"); declare N : Tree_Types.Nodes_Type renames Container.Nodes; begin return Key (N (Position.Node).Element); end; end Key; ------------- -- Replace -- ------------- procedure Replace (Container : in out Set; Key : Key_Type; New_Item : Element_Type) is Node : constant Count_Type := Key_Keys.Find (Container, Key); begin if not Has_Element (Container, (Node => Node)) then raise Constraint_Error with "attempt to replace key not in set"; else Replace_Element (Container, Node, New_Item); end if; end Replace; end Generic_Keys; ----------------- -- Has_Element -- ----------------- function Has_Element (Container : Set; Position : Cursor) return Boolean is begin if Position.Node = 0 then return False; else return Container.Nodes (Position.Node).Has_Element; end if; end Has_Element; ------------- -- Include -- ------------- procedure Include (Container : in out Set; New_Item : Element_Type) is Position : Cursor; Inserted : Boolean; begin Insert (Container, New_Item, Position, Inserted); if not Inserted then declare N : Tree_Types.Nodes_Type renames Container.Nodes; begin N (Position.Node).Element := New_Item; end; end if; end Include; ------------ -- Insert -- ------------ procedure Insert (Container : in out Set; New_Item : Element_Type; Position : out Cursor; Inserted : out Boolean) is begin Insert_Sans_Hint (Container, New_Item, Position.Node, Inserted); end Insert; procedure Insert (Container : in out Set; New_Item : Element_Type) is Position : Cursor; Inserted : Boolean; begin Insert (Container, New_Item, Position, Inserted); if not Inserted then raise Constraint_Error with "attempt to insert element already in set"; end if; end Insert; ---------------------- -- Insert_Sans_Hint -- ---------------------- procedure Insert_Sans_Hint (Container : in out Set; New_Item : Element_Type; Node : out Count_Type; Inserted : out Boolean) is procedure Set_Element (Node : in out Node_Type); function New_Node return Count_Type; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Conditional_Insert_Sans_Hint is new Element_Keys.Generic_Conditional_Insert (Insert_Post); procedure Allocate is new Generic_Allocate (Set_Element); -------------- -- New_Node -- -------------- function New_Node return Count_Type is Result : Count_Type; begin Allocate (Container, Result); return Result; end New_Node; ----------------- -- Set_Element -- ----------------- procedure Set_Element (Node : in out Node_Type) is begin Node.Element := New_Item; end Set_Element; -- Start of processing for Insert_Sans_Hint begin Conditional_Insert_Sans_Hint (Container, New_Item, Node, Inserted); end Insert_Sans_Hint; ---------------------- -- Insert_With_Hint -- ---------------------- procedure Insert_With_Hint (Dst_Set : in out Set; Dst_Hint : Count_Type; Src_Node : Node_Type; Dst_Node : out Count_Type) is Success : Boolean; pragma Unreferenced (Success); procedure Set_Element (Node : in out Node_Type); function New_Node return Count_Type; pragma Inline (New_Node); procedure Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Insert_Sans_Hint is new Element_Keys.Generic_Conditional_Insert (Insert_Post); procedure Local_Insert_With_Hint is new Element_Keys.Generic_Conditional_Insert_With_Hint (Insert_Post, Insert_Sans_Hint); procedure Allocate is new Generic_Allocate (Set_Element); -------------- -- New_Node -- -------------- function New_Node return Count_Type is Result : Count_Type; begin Allocate (Dst_Set, Result); return Result; end New_Node; ----------------- -- Set_Element -- ----------------- procedure Set_Element (Node : in out Node_Type) is begin Node.Element := Src_Node.Element; end Set_Element; -- Start of processing for Insert_With_Hint begin Local_Insert_With_Hint (Dst_Set, Dst_Hint, Src_Node.Element, Dst_Node, Success); end Insert_With_Hint; ------------------ -- Intersection -- ------------------ procedure Intersection (Target : in out Set; Source : Set) is begin Set_Ops.Set_Intersection (Target, Source); end Intersection; function Intersection (Left, Right : Set) return Set is begin if Left'Address = Right'Address then return Left.Copy; end if; return S : Set (Count_Type'Min (Length (Left), Length (Right))) do Assign (S, Set_Ops.Set_Intersection (Left, Right)); end return; end Intersection; -------------- -- Is_Empty -- -------------- function Is_Empty (Container : Set) return Boolean is begin return Length (Container) = 0; end Is_Empty; ----------------------------- -- Is_Greater_Element_Node -- ----------------------------- function Is_Greater_Element_Node (Left : Element_Type; Right : Node_Type) return Boolean is begin -- Compute e > node same as node < e return Right.Element < Left; end Is_Greater_Element_Node; -------------------------- -- Is_Less_Element_Node -- -------------------------- function Is_Less_Element_Node (Left : Element_Type; Right : Node_Type) return Boolean is begin return Left < Right.Element; end Is_Less_Element_Node; ----------------------- -- Is_Less_Node_Node -- ----------------------- function Is_Less_Node_Node (L, R : Node_Type) return Boolean is begin return L.Element < R.Element; end Is_Less_Node_Node; --------------- -- Is_Subset -- --------------- function Is_Subset (Subset : Set; Of_Set : Set) return Boolean is begin return Set_Ops.Set_Subset (Subset, Of_Set => Of_Set); end Is_Subset; ---------- -- Last -- ---------- function Last (Container : Set) return Cursor is begin return (if Length (Container) = 0 then No_Element else (Node => Container.Last)); end Last; ------------------ -- Last_Element -- ------------------ function Last_Element (Container : Set) return Element_Type is begin if Last (Container).Node = 0 then raise Constraint_Error with "set is empty"; end if; declare N : Tree_Types.Nodes_Type renames Container.Nodes; begin return N (Last (Container).Node).Element; end; end Last_Element; -------------- -- Left_Son -- -------------- function Left_Son (Node : Node_Type) return Count_Type is begin return Node.Left; end Left_Son; ------------ -- Length -- ------------ function Length (Container : Set) return Count_Type is begin return Container.Length; end Length; ---------- -- Move -- ---------- procedure Move (Target : in out Set; Source : in out Set) is N : Tree_Types.Nodes_Type renames Source.Nodes; X : Count_Type; begin if Target'Address = Source'Address then return; end if; if Target.Capacity < Length (Source) then raise Constraint_Error with -- ??? "Source length exceeds Target capacity"; end if; Clear (Target); loop X := Source.First; exit when X = 0; Insert (Target, N (X).Element); -- optimize??? Tree_Operations.Delete_Node_Sans_Free (Source, X); Formal_Ordered_Sets.Free (Source, X); end loop; end Move; ---------- -- Next -- ---------- function Next (Container : Set; Position : Cursor) return Cursor is begin if Position = No_Element then return No_Element; end if; if not Has_Element (Container, Position) then raise Constraint_Error; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Next"); return (Node => Tree_Operations.Next (Container, Position.Node)); end Next; procedure Next (Container : Set; Position : in out Cursor) is begin Position := Next (Container, Position); end Next; ------------- -- Overlap -- ------------- function Overlap (Left, Right : Set) return Boolean is begin return Set_Ops.Set_Overlap (Left, Right); end Overlap; ------------ -- Parent -- ------------ function Parent (Node : Node_Type) return Count_Type is begin return Node.Parent; end Parent; -------------- -- Previous -- -------------- function Previous (Container : Set; Position : Cursor) return Cursor is begin if Position = No_Element then return No_Element; end if; if not Has_Element (Container, Position) then raise Constraint_Error; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Previous"); declare Node : constant Count_Type := Tree_Operations.Previous (Container, Position.Node); begin return (if Node = 0 then No_Element else (Node => Node)); end; end Previous; procedure Previous (Container : Set; Position : in out Cursor) is begin Position := Previous (Container, Position); end Previous; ------------- -- Replace -- ------------- procedure Replace (Container : in out Set; New_Item : Element_Type) is Node : constant Count_Type := Element_Keys.Find (Container, New_Item); begin if Node = 0 then raise Constraint_Error with "attempt to replace element not in set"; end if; Container.Nodes (Node).Element := New_Item; end Replace; --------------------- -- Replace_Element -- --------------------- procedure Replace_Element (Tree : in out Set; Node : Count_Type; Item : Element_Type) is pragma Assert (Node /= 0); function New_Node return Count_Type; pragma Inline (New_Node); procedure Local_Insert_Post is new Element_Keys.Generic_Insert_Post (New_Node); procedure Local_Insert_Sans_Hint is new Element_Keys.Generic_Conditional_Insert (Local_Insert_Post); procedure Local_Insert_With_Hint is new Element_Keys.Generic_Conditional_Insert_With_Hint (Local_Insert_Post, Local_Insert_Sans_Hint); NN : Tree_Types.Nodes_Type renames Tree.Nodes; -------------- -- New_Node -- -------------- function New_Node return Count_Type is N : Node_Type renames NN (Node); begin N.Element := Item; N.Color := Red; N.Parent := 0; N.Right := 0; N.Left := 0; return Node; end New_Node; Hint : Count_Type; Result : Count_Type; Inserted : Boolean; -- Start of processing for Insert begin if Item < NN (Node).Element or else NN (Node).Element < Item then null; else NN (Node).Element := Item; return; end if; Hint := Element_Keys.Ceiling (Tree, Item); if Hint = 0 then null; elsif Item < NN (Hint).Element then if Hint = Node then NN (Node).Element := Item; return; end if; else pragma Assert (not (NN (Hint).Element < Item)); raise Program_Error with "attempt to replace existing element"; end if; Tree_Operations.Delete_Node_Sans_Free (Tree, Node); Local_Insert_With_Hint (Tree => Tree, Position => Hint, Key => Item, Node => Result, Inserted => Inserted); pragma Assert (Inserted); pragma Assert (Result = Node); end Replace_Element; procedure Replace_Element (Container : in out Set; Position : Cursor; New_Item : Element_Type) is begin if not Has_Element (Container, Position) then raise Constraint_Error with "Position cursor has no element"; end if; pragma Assert (Vet (Container, Position.Node), "bad cursor in Replace_Element"); Replace_Element (Container, Position.Node, New_Item); end Replace_Element; --------------- -- Right_Son -- --------------- function Right_Son (Node : Node_Type) return Count_Type is begin return Node.Right; end Right_Son; --------------- -- Set_Color -- --------------- procedure Set_Color (Node : in out Node_Type; Color : Red_Black_Trees.Color_Type) is begin Node.Color := Color; end Set_Color; -------------- -- Set_Left -- -------------- procedure Set_Left (Node : in out Node_Type; Left : Count_Type) is begin Node.Left := Left; end Set_Left; ---------------- -- Set_Parent -- ---------------- procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type) is begin Node.Parent := Parent; end Set_Parent; --------------- -- Set_Right -- --------------- procedure Set_Right (Node : in out Node_Type; Right : Count_Type) is begin Node.Right := Right; end Set_Right; -------------------------- -- Symmetric_Difference -- -------------------------- procedure Symmetric_Difference (Target : in out Set; Source : Set) is begin Set_Ops.Set_Symmetric_Difference (Target, Source); end Symmetric_Difference; function Symmetric_Difference (Left, Right : Set) return Set is begin if Left'Address = Right'Address then return Empty_Set; end if; if Length (Right) = 0 then return Left.Copy; end if; if Length (Left) = 0 then return Right.Copy; end if; return S : Set (Length (Left) + Length (Right)) do Assign (S, Set_Ops.Set_Symmetric_Difference (Left, Right)); end return; end Symmetric_Difference; ------------ -- To_Set -- ------------ function To_Set (New_Item : Element_Type) return Set is Node : Count_Type; Inserted : Boolean; begin return S : Set (Capacity => 1) do Insert_Sans_Hint (S, New_Item, Node, Inserted); pragma Assert (Inserted); end return; end To_Set; ----------- -- Union -- ----------- procedure Union (Target : in out Set; Source : Set) is begin Set_Ops.Set_Union (Target, Source); end Union; function Union (Left, Right : Set) return Set is begin if Left'Address = Right'Address then return Left.Copy; end if; if Length (Left) = 0 then return Right.Copy; end if; if Length (Right) = 0 then return Left.Copy; end if; return S : Set (Length (Left) + Length (Right)) do Assign (S, Source => Left); Union (S, Right); end return; end Union; end Ada.Containers.Formal_Ordered_Sets;
programs/oeis/037/A037281.asm
neoneye/loda
22
80464
; A037281: Number of iterations of transformation in A037280 needed to reach 1 or a prime, or -1 if no such number exists. ; 0,0,0,1,0,1,0,1,1,2,0 mov $1,$0 dif $0,2 div $1,2 dif $1,2 add $1,2 div $0,$1
plurals/plural.g4
fighterlyt/t
8
656
<reponame>fighterlyt/t grammar plural; // 关于复数表达式的官方描述: // https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html#index-specifying-plural-form-in-a-PO-file // plural 表达式是 C 语法的表达式,但不允许负数出现,而且只能出现整数,变量只允许 n。可以有空白,但不能反斜杠换行。 // 生成 Go 代码的命令 (在本目录下执行): antlr4 -Dlanguage=Go plural.g4 -o parser start: exp; exp: primary | exp postfix = ('++' | '--') | prefix = ('+' | '-' | '++' | '--') exp | prefix = ('~' | '!') exp | exp bop = ('*' | '/' | '%') exp | exp bop = ('+' | '-') exp | exp bop = ('>>' | '<<') exp | exp bop = ('>' | '<') exp | exp bop = ('>=' | '<=') exp | exp bop = ('==' | '!=') exp | exp bop = '&' exp | exp bop = '^' exp | exp bop = '|' exp | exp bop = '&&' exp | exp bop = '||' exp | <assoc = right> exp bop = '?' exp ':' exp; primary: '(' exp ')' | 'n' | INT; INT: [0-9]+; WS: [ \t]+ -> skip;
Definition/LogicalRelation/Substitution/MaybeEmbed.agda
CoqHott/logrel-mltt
2
9391
{-# OPTIONS --safe #-} open import Definition.Typed.EqualityRelation module Definition.LogicalRelation.Substitution.MaybeEmbed {{eqrel : EqRelSet}} where open EqRelSet {{...}} open import Definition.Untyped open import Definition.LogicalRelation open import Definition.LogicalRelation.Irrelevance open import Definition.LogicalRelation.Properties open import Definition.LogicalRelation.Substitution open import Tools.Product -- Any level can be embedded into the highest level (validity variant). maybeEmbᵛ : ∀ {l A r Γ} ([Γ] : ⊩ᵛ Γ) → Γ ⊩ᵛ⟨ l ⟩ A ^ r / [Γ] → Γ ⊩ᵛ⟨ ∞ ⟩ A ^ r / [Γ] maybeEmbᵛ {ι ⁰} [Γ] [A] ⊢Δ [σ] = let [σA] = proj₁ ([A] ⊢Δ [σ]) [σA]′ = maybeEmb (proj₁ ([A] ⊢Δ [σ])) in [σA]′ , (λ [σ′] [σ≡σ′] → irrelevanceEq [σA] [σA]′ (proj₂ ([A] ⊢Δ [σ]) [σ′] [σ≡σ′])) maybeEmbᵛ {ι ¹} [Γ] [A] ⊢Δ [σ] = let [σA] = proj₁ ([A] ⊢Δ [σ]) [σA]′ = maybeEmb (proj₁ ([A] ⊢Δ [σ])) in [σA]′ , (λ [σ′] [σ≡σ′] → irrelevanceEq [σA] [σA]′ (proj₂ ([A] ⊢Δ [σ]) [σ′] [σ≡σ′])) maybeEmbᵛ {∞} [Γ] [A] ⊢Δ [σ] = [A] ⊢Δ [σ] maybeEmbTermᵛ : ∀ {l A t r Γ} → ([Γ] : ⊩ᵛ Γ) → ([A] : Γ ⊩ᵛ⟨ l ⟩ A ^ r / [Γ]) → Γ ⊩ᵛ⟨ l ⟩ t ∷ A ^ r / [Γ] / [A] → Γ ⊩ᵛ⟨ ∞ ⟩ t ∷ A ^ r / [Γ] / maybeEmbᵛ {A = A} [Γ] [A] maybeEmbTermᵛ {ι ⁰} [Γ] [A] [t] = [t] maybeEmbTermᵛ {ι ¹} [Γ] [A] [t] = [t] maybeEmbTermᵛ {∞} [Γ] [A] [t] = [t] -- The lowest level can be embedded in any level (validity variant). maybeEmbₛ′ : ∀ {l A r Γ} ([Γ] : ⊩ᵛ Γ) → Γ ⊩ᵛ⟨ ι ⁰ ⟩ A ^ r / [Γ] → Γ ⊩ᵛ⟨ l ⟩ A ^ r / [Γ] maybeEmbₛ′ {ι ⁰} [Γ] [A] = [A] maybeEmbₛ′ {ι ¹} [Γ] [A] ⊢Δ [σ] = let [σA] = proj₁ ([A] ⊢Δ [σ]) [σA]′ = maybeEmb′ (<is≤ 0<1) (proj₁ ([A] ⊢Δ [σ])) in [σA]′ , (λ [σ′] [σ≡σ′] → irrelevanceEq [σA] [σA]′ (proj₂ ([A] ⊢Δ [σ]) [σ′] [σ≡σ′])) maybeEmbₛ′ {∞} [Γ] [A] ⊢Δ [σ] = let [σA] = proj₁ ([A] ⊢Δ [σ]) [σA]′ = maybeEmb (proj₁ ([A] ⊢Δ [σ])) in [σA]′ , (λ [σ′] [σ≡σ′] → irrelevanceEq [σA] [σA]′ (proj₂ ([A] ⊢Δ [σ]) [σ′] [σ≡σ′])) maybeEmbEqTermᵛ : ∀ {l A t u r Γ} → ([Γ] : ⊩ᵛ Γ) → ([A] : Γ ⊩ᵛ⟨ l ⟩ A ^ r / [Γ] ) → Γ ⊩ᵛ⟨ l ⟩ t ≡ u ∷ A ^ r / [Γ] / [A] → Γ ⊩ᵛ⟨ ∞ ⟩ t ≡ u ∷ A ^ r / [Γ] / maybeEmbᵛ {A = A} [Γ] [A] maybeEmbEqTermᵛ {ι ⁰} [Γ] [A] [t≡u] = [t≡u] maybeEmbEqTermᵛ {ι ¹} [Γ] [A] [t≡u] = [t≡u] maybeEmbEqTermᵛ {∞} [Γ] [A] [t≡u] = [t≡u]
s-ficobl.adb
ytomino/gnat4drake
0
28178
<gh_stars>0 package body System.File_Control_Block is function Stream (File : AFCB_Ptr) return Interfaces.C_Streams.FILEs is begin raise Program_Error; -- FILE * is not used in drake return Stream (File); end Stream; end System.File_Control_Block;
src/skill-types.ads
skill-lang/adaCommon
0
29378
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ API types for skill types -- -- |___/_|\_\_|_|____| by: <NAME>, <NAME> -- -- -- pragma Ada_2012; with Ada.Containers.Doubly_Linked_Lists; with Ada.Containers.Hashed_Sets; with Ada.Containers.Hashed_Maps; with Ada.Tags; with Interfaces; with System; limited with Skill.Field_Declarations; with Skill.Containers; package Skill.Types is -- this is a boxed object; it is required, because one can not mix generic -- and object oriented polymorphism in ada. -- we use size of pointer and store all regular object in it by just abusing -- the space :-] type Box is access String; function Hash (This : Box) return Ada.Containers.Hash_Type; subtype i8 is Interfaces.Integer_8 range Interfaces.Integer_8'Range; subtype i16 is Interfaces.Integer_16 range Interfaces.Integer_16'Range; subtype i32 is Interfaces.Integer_32 range Interfaces.Integer_32'Range; subtype i64 is Interfaces.Integer_64 range Interfaces.Integer_64'Range; subtype v64 is Interfaces.Integer_64 range Interfaces.Integer_64'Range; -- used in places, where v64 values are used as lengths or counts subtype Uv64 is Interfaces.Unsigned_64 range Interfaces.Unsigned_64'Range; -- TF: we can not restrict range, because that would destroy NaNs, right? subtype F32 is Interfaces.IEEE_Float_32; subtype F64 is Interfaces.IEEE_Float_64; type String_Access is access String; type String_Access_Array is array (Integer range <>) of not null String_Access; type String_Access_Array_Access is access all String_Access_Array; subtype Boxed_Array is Skill.Containers.Boxed_Array; subtype Boxed_List is Skill.Containers.Boxed_Array; subtype Boxed_Map is Skill.Containers.Boxed_Map; -- declare skill ids type for later configuration subtype Skill_ID_T is Integer; -- we use integer IDs, because they are smaller and we would -- internal use only! type Skill_Object is tagged record Skill_ID : Skill_ID_T; end record; type Annotation is access all Skill_Object; type Annotation_Dyn is access all Skill_Object'Class; type Annotation_Array_T is array (Positive range <>) of Annotation; type Annotation_Array is access Annotation_Array_T; -- default type conversion for root type function To_Annotation (This : access Skill_Object'Class) return Skill.Types.Annotation; pragma Inline (To_Annotation); pragma Pure_Function (To_Annotation); function Skill_Name (This : access Skill_Object) return String_Access; function Dynamic (This : access Skill_Object) return Annotation_Dyn; pragma Inline (Dynamic); pragma Pure_Function (Dynamic); -- return true, iff the argument object will be deleted on the next flush -- operation -- @note: references to the object carried by other managed skill objects -- will be deleted automatically function Is_Deleted(This : access Skill_Object'Class) return Boolean is (0 = This.Skill_ID); function Tag (This : access Skill_Object'Class) return Ada.Tags.Tag is (This'Tag); pragma Inline (Tag); pragma Pure_Function (Tag); -- reflective getter function Reflective_Get (This : access Skill_Object; F : Skill.Field_Declarations.Field_Declaration) return Box; -- reflective setter procedure Reflective_Set (This : access Skill_Object; F : Field_Declarations.Field_Declaration; V : Box); end Skill.Types;
programs/oeis/057/A057070.asm
karttu/loda
1
175461
; A057070: floor[8^8/n]. ; 16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277 add $0,1 mov $1,16777216 div $1,$0
BasicIS4/Metatheory/DyadicGentzenSpinalNormalForm-HereditarySubstitution.agda
mietek/hilbert-gentzen
29
13400
<reponame>mietek/hilbert-gentzen module BasicIS4.Metatheory.DyadicGentzenSpinalNormalForm-HereditarySubstitution where open import BasicIS4.Syntax.DyadicGentzenSpinalNormalForm public -- Hereditary substitution and reduction. mutual [_≔_]ⁿᶠ_ : ∀ {A B Γ Δ} → (i : A ∈ Γ) → Γ ∖ i ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ⁿᶠ B → Γ ∖ i ⁏ Δ ⊢ⁿᶠ B [ i ≔ s ]ⁿᶠ neⁿᶠ (spⁿᵉ j xs y) with i ≟∈ j [ i ≔ s ]ⁿᶠ neⁿᶠ (spⁿᵉ .i xs y) | same = reduce s ([ i ≔ s ]ˢᵖ xs) ([ i ≔ s ]ᵗᵖ y) [ i ≔ s ]ⁿᶠ neⁿᶠ (spⁿᵉ ._ xs y) | diff j = neⁿᶠ (spⁿᵉ j ([ i ≔ s ]ˢᵖ xs) ([ i ≔ s ]ᵗᵖ y)) [ i ≔ s ]ⁿᶠ neⁿᶠ (mspⁿᵉ j xs y) = neⁿᶠ (mspⁿᵉ j ([ i ≔ s ]ˢᵖ xs) ([ i ≔ s ]ᵗᵖ y)) [ i ≔ s ]ⁿᶠ lamⁿᶠ t = lamⁿᶠ ([ pop i ≔ mono⊢ⁿᶠ weak⊆ s ]ⁿᶠ t) [ i ≔ s ]ⁿᶠ boxⁿᶠ t = boxⁿᶠ t [ i ≔ s ]ⁿᶠ pairⁿᶠ t u = pairⁿᶠ ([ i ≔ s ]ⁿᶠ t) ([ i ≔ s ]ⁿᶠ u) [ i ≔ s ]ⁿᶠ unitⁿᶠ = unitⁿᶠ [_≔_]ˢᵖ_ : ∀ {A B C Γ Δ} → (i : A ∈ Γ) → Γ ∖ i ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ˢᵖ B ⦙ C → Γ ∖ i ⁏ Δ ⊢ˢᵖ B ⦙ C [ i ≔ s ]ˢᵖ nilˢᵖ = nilˢᵖ [ i ≔ s ]ˢᵖ appˢᵖ xs u = appˢᵖ ([ i ≔ s ]ˢᵖ xs) ([ i ≔ s ]ⁿᶠ u) [ i ≔ s ]ˢᵖ fstˢᵖ xs = fstˢᵖ ([ i ≔ s ]ˢᵖ xs) [ i ≔ s ]ˢᵖ sndˢᵖ xs = sndˢᵖ ([ i ≔ s ]ˢᵖ xs) [_≔_]ᵗᵖ_ : ∀ {A B C Γ Δ} → (i : A ∈ Γ) → Γ ∖ i ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ᵗᵖ B ⦙ C → Γ ∖ i ⁏ Δ ⊢ᵗᵖ B ⦙ C [ i ≔ s ]ᵗᵖ nilᵗᵖ = nilᵗᵖ [ i ≔ s ]ᵗᵖ unboxᵗᵖ u = unboxᵗᵖ u′ where u′ = [ i ≔ mmono⊢ⁿᶠ weak⊆ s ]ⁿᶠ u m[_≔_]ⁿᶠ_ : ∀ {A B Γ Δ} → (i : A ∈ Δ) → ∅ ⁏ Δ ∖ i ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ⁿᶠ B → Γ ⁏ Δ ∖ i ⊢ⁿᶠ B m[ i ≔ s ]ⁿᶠ neⁿᶠ (spⁿᵉ j xs y) = neⁿᶠ (spⁿᵉ j (m[ i ≔ s ]ˢᵖ xs) (m[ i ≔ s ]ᵗᵖ y)) m[ i ≔ s ]ⁿᶠ neⁿᶠ (mspⁿᵉ j xs y) with i ≟∈ j m[ i ≔ s ]ⁿᶠ neⁿᶠ (mspⁿᵉ .i xs y) | same = reduce (mono⊢ⁿᶠ bot⊆ s) (m[ i ≔ s ]ˢᵖ xs) (m[ i ≔ s ]ᵗᵖ y) m[ i ≔ s ]ⁿᶠ neⁿᶠ (mspⁿᵉ ._ xs y) | diff j = neⁿᶠ (mspⁿᵉ j (m[ i ≔ s ]ˢᵖ xs) (m[ i ≔ s ]ᵗᵖ y)) m[ i ≔ s ]ⁿᶠ lamⁿᶠ t = lamⁿᶠ (m[ i ≔ s ]ⁿᶠ t) m[ i ≔ s ]ⁿᶠ boxⁿᶠ t = boxⁿᶠ (m[ i ≔ s ]ⁿᶠ t) m[ i ≔ s ]ⁿᶠ pairⁿᶠ t u = pairⁿᶠ (m[ i ≔ s ]ⁿᶠ t) (m[ i ≔ s ]ⁿᶠ u) m[ i ≔ s ]ⁿᶠ unitⁿᶠ = unitⁿᶠ m[_≔_]ˢᵖ_ : ∀ {A B C Γ Δ} → (i : A ∈ Δ) → ∅ ⁏ Δ ∖ i ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ˢᵖ B ⦙ C → Γ ⁏ Δ ∖ i ⊢ˢᵖ B ⦙ C m[ i ≔ s ]ˢᵖ nilˢᵖ = nilˢᵖ m[ i ≔ s ]ˢᵖ appˢᵖ xs u = appˢᵖ (m[ i ≔ s ]ˢᵖ xs) (m[ i ≔ s ]ⁿᶠ u) m[ i ≔ s ]ˢᵖ fstˢᵖ xs = fstˢᵖ (m[ i ≔ s ]ˢᵖ xs) m[ i ≔ s ]ˢᵖ sndˢᵖ xs = sndˢᵖ (m[ i ≔ s ]ˢᵖ xs) m[_≔_]ᵗᵖ_ : ∀ {A B C Γ Δ} → (i : A ∈ Δ) → ∅ ⁏ Δ ∖ i ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ᵗᵖ B ⦙ C → Γ ⁏ Δ ∖ i ⊢ᵗᵖ B ⦙ C m[ i ≔ s ]ᵗᵖ nilᵗᵖ = nilᵗᵖ m[ i ≔ s ]ᵗᵖ unboxᵗᵖ u = unboxᵗᵖ u′ where u′ = m[ pop i ≔ mmono⊢ⁿᶠ weak⊆ s ]ⁿᶠ u reduce : ∀ {A B C Γ Δ} → Γ ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ˢᵖ A ⦙ B → Γ ⁏ Δ ⊢ᵗᵖ B ⦙ C → {{_ : Tyⁿᵉ C}} → Γ ⁏ Δ ⊢ⁿᶠ C reduce t nilˢᵖ nilᵗᵖ = t reduce (neⁿᶠ (spⁿᵉ i xs nilᵗᵖ)) nilˢᵖ y = neⁿᶠ (spⁿᵉ i xs y) reduce (neⁿᶠ (spⁿᵉ i xs (unboxᵗᵖ u))) nilˢᵖ y = neⁿᶠ (spⁿᵉ i xs (unboxᵗᵖ u′)) where u′ = reduce u nilˢᵖ (mmono⊢ᵗᵖ weak⊆ y) reduce (neⁿᶠ (mspⁿᵉ i xs nilᵗᵖ)) nilˢᵖ y = neⁿᶠ (mspⁿᵉ i xs y) reduce (neⁿᶠ (mspⁿᵉ i xs (unboxᵗᵖ u))) nilˢᵖ y = neⁿᶠ (mspⁿᵉ i xs (unboxᵗᵖ u′)) where u′ = reduce u nilˢᵖ (mmono⊢ᵗᵖ weak⊆ y) reduce (neⁿᶠ t {{()}}) (appˢᵖ xs u) y reduce (neⁿᶠ t {{()}}) (fstˢᵖ xs) y reduce (neⁿᶠ t {{()}}) (sndˢᵖ xs) y reduce (lamⁿᶠ t) (appˢᵖ xs u) y = reduce ([ top ≔ u ]ⁿᶠ t) xs y reduce (boxⁿᶠ t) nilˢᵖ (unboxᵗᵖ u) = m[ top ≔ t ]ⁿᶠ u reduce (pairⁿᶠ t u) (fstˢᵖ xs) y = reduce t xs y reduce (pairⁿᶠ t u) (sndˢᵖ xs) y = reduce u xs y -- Reduction-based normal forms. appⁿᶠ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᶠ A ▻ B → Γ ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ⁿᶠ B appⁿᶠ (neⁿᶠ t {{()}}) appⁿᶠ (lamⁿᶠ t) u = [ top ≔ u ]ⁿᶠ t fstⁿᶠ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᶠ A ∧ B → Γ ⁏ Δ ⊢ⁿᶠ A fstⁿᶠ (neⁿᶠ t {{()}}) fstⁿᶠ (pairⁿᶠ t u) = t sndⁿᶠ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᶠ A ∧ B → Γ ⁏ Δ ⊢ⁿᶠ B sndⁿᶠ (neⁿᶠ t {{()}}) sndⁿᶠ (pairⁿᶠ t u) = u -- Useful equipment for deriving neutrals. ≪appˢᵖ : ∀ {A B C Γ Δ} → Γ ⁏ Δ ⊢ˢᵖ C ⦙ A ▻ B → Γ ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ˢᵖ C ⦙ B ≪appˢᵖ nilˢᵖ t = appˢᵖ nilˢᵖ t ≪appˢᵖ (appˢᵖ xs u) t = appˢᵖ (≪appˢᵖ xs t) u ≪appˢᵖ (fstˢᵖ xs) t = fstˢᵖ (≪appˢᵖ xs t) ≪appˢᵖ (sndˢᵖ xs) t = sndˢᵖ (≪appˢᵖ xs t) ≪fstˢᵖ : ∀ {A B C Γ Δ} → Γ ⁏ Δ ⊢ˢᵖ C ⦙ A ∧ B → Γ ⁏ Δ ⊢ˢᵖ C ⦙ A ≪fstˢᵖ nilˢᵖ = fstˢᵖ nilˢᵖ ≪fstˢᵖ (appˢᵖ xs u) = appˢᵖ (≪fstˢᵖ xs) u ≪fstˢᵖ (fstˢᵖ xs) = fstˢᵖ (≪fstˢᵖ xs) ≪fstˢᵖ (sndˢᵖ xs) = sndˢᵖ (≪fstˢᵖ xs) ≪sndˢᵖ : ∀ {A B C Γ Δ} → Γ ⁏ Δ ⊢ˢᵖ C ⦙ A ∧ B → Γ ⁏ Δ ⊢ˢᵖ C ⦙ B ≪sndˢᵖ nilˢᵖ = sndˢᵖ nilˢᵖ ≪sndˢᵖ (appˢᵖ xs u) = appˢᵖ (≪sndˢᵖ xs) u ≪sndˢᵖ (fstˢᵖ xs) = fstˢᵖ (≪sndˢᵖ xs) ≪sndˢᵖ (sndˢᵖ xs) = sndˢᵖ (≪sndˢᵖ xs) -- Derived neutrals. varⁿᵉ : ∀ {A Γ Δ} → A ∈ Γ → Γ ⁏ Δ ⊢ⁿᵉ A varⁿᵉ i = spⁿᵉ i nilˢᵖ nilᵗᵖ appⁿᵉ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᵉ A ▻ B → Γ ⁏ Δ ⊢ⁿᶠ A → Γ ⁏ Δ ⊢ⁿᵉ B appⁿᵉ (spⁿᵉ i xs nilᵗᵖ) t = spⁿᵉ i (≪appˢᵖ xs t) nilᵗᵖ appⁿᵉ (spⁿᵉ i xs (unboxᵗᵖ u)) t = spⁿᵉ i xs (unboxᵗᵖ u′) where u′ = appⁿᶠ u (mmono⊢ⁿᶠ weak⊆ t) appⁿᵉ (mspⁿᵉ i xs nilᵗᵖ) t = mspⁿᵉ i (≪appˢᵖ xs t) nilᵗᵖ appⁿᵉ (mspⁿᵉ i xs (unboxᵗᵖ u)) t = mspⁿᵉ i xs (unboxᵗᵖ u′) where u′ = appⁿᶠ u (mmono⊢ⁿᶠ weak⊆ t) mvarⁿᵉ : ∀ {A Γ Δ} → A ∈ Δ → Γ ⁏ Δ ⊢ⁿᵉ A mvarⁿᵉ i = mspⁿᵉ i nilˢᵖ nilᵗᵖ fstⁿᵉ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᵉ A ∧ B → Γ ⁏ Δ ⊢ⁿᵉ A fstⁿᵉ (spⁿᵉ i xs nilᵗᵖ) = spⁿᵉ i (≪fstˢᵖ xs) nilᵗᵖ fstⁿᵉ (spⁿᵉ i xs (unboxᵗᵖ u)) = spⁿᵉ i xs (unboxᵗᵖ (fstⁿᶠ u)) fstⁿᵉ (mspⁿᵉ i xs nilᵗᵖ) = mspⁿᵉ i (≪fstˢᵖ xs) nilᵗᵖ fstⁿᵉ (mspⁿᵉ i xs (unboxᵗᵖ u)) = mspⁿᵉ i xs (unboxᵗᵖ (fstⁿᶠ u)) sndⁿᵉ : ∀ {A B Γ Δ} → Γ ⁏ Δ ⊢ⁿᵉ A ∧ B → Γ ⁏ Δ ⊢ⁿᵉ B sndⁿᵉ (spⁿᵉ i xs nilᵗᵖ) = spⁿᵉ i (≪sndˢᵖ xs) nilᵗᵖ sndⁿᵉ (spⁿᵉ i xs (unboxᵗᵖ u)) = spⁿᵉ i xs (unboxᵗᵖ (sndⁿᶠ u)) sndⁿᵉ (mspⁿᵉ i xs nilᵗᵖ) = mspⁿᵉ i (≪sndˢᵖ xs) nilᵗᵖ sndⁿᵉ (mspⁿᵉ i xs (unboxᵗᵖ u)) = mspⁿᵉ i xs (unboxᵗᵖ (sndⁿᶠ u)) -- Iterated expansion. expand : ∀ {A Γ Δ} → Γ ⁏ Δ ⊢ⁿᵉ A → Γ ⁏ Δ ⊢ⁿᶠ A expand {α P} t = neⁿᶠ t {{α P}} expand {A ▻ B} t = lamⁿᶠ (expand (appⁿᵉ (mono⊢ⁿᵉ weak⊆ t) (expand (varⁿᵉ top)))) expand {□ A} t = neⁿᶠ t {{□ A}} expand {A ∧ B} t = pairⁿᶠ (expand (fstⁿᵉ t)) (expand (sndⁿᵉ t)) expand {⊤} t = unitⁿᶠ -- Expansion-based normal forms. varⁿᶠ : ∀ {A Γ Δ} → A ∈ Γ → Γ ⁏ Δ ⊢ⁿᶠ A varⁿᶠ i = expand (varⁿᵉ i) mvarⁿᶠ : ∀ {A Γ Δ} → A ∈ Δ → Γ ⁏ Δ ⊢ⁿᶠ A mvarⁿᶠ i = expand (mvarⁿᵉ i) mutual unboxⁿᶠ : ∀ {A C Γ Δ} → Γ ⁏ Δ ⊢ⁿᶠ □ A → Γ ⁏ Δ , A ⊢ⁿᶠ C → Γ ⁏ Δ ⊢ⁿᶠ C unboxⁿᶠ (neⁿᶠ t) u = expand (unboxⁿᵉ t u) unboxⁿᶠ (boxⁿᶠ t) u = m[ top ≔ t ]ⁿᶠ u unboxⁿᵉ : ∀ {A C Γ Δ} → Γ ⁏ Δ ⊢ⁿᵉ □ A → Γ ⁏ Δ , A ⊢ⁿᶠ C → Γ ⁏ Δ ⊢ⁿᵉ C unboxⁿᵉ (spⁿᵉ i xs nilᵗᵖ) u = spⁿᵉ i xs (unboxᵗᵖ u) unboxⁿᵉ (spⁿᵉ i xs (unboxᵗᵖ t)) u = spⁿᵉ i xs (unboxᵗᵖ u′) where u′ = unboxⁿᶠ t (mmono⊢ⁿᶠ (keep (weak⊆)) u) unboxⁿᵉ (mspⁿᵉ i xs nilᵗᵖ) u = mspⁿᵉ i xs (unboxᵗᵖ u) unboxⁿᵉ (mspⁿᵉ i xs (unboxᵗᵖ t)) u = mspⁿᵉ i xs (unboxᵗᵖ u′) where u′ = unboxⁿᶠ t (mmono⊢ⁿᶠ (keep (weak⊆)) u) -- Translation from terms to normal forms. tm→nf : ∀ {A Γ Δ} → Γ ⁏ Δ ⊢ A → Γ ⁏ Δ ⊢ⁿᶠ A tm→nf (var i) = varⁿᶠ i tm→nf (lam t) = lamⁿᶠ (tm→nf t) tm→nf (app t u) = appⁿᶠ (tm→nf t) (tm→nf u) tm→nf (mvar i) = mvarⁿᶠ i tm→nf (box t) = boxⁿᶠ (tm→nf t) tm→nf (unbox t u) = unboxⁿᶠ (tm→nf t) (tm→nf u) tm→nf (pair t u) = pairⁿᶠ (tm→nf t) (tm→nf u) tm→nf (fst t) = fstⁿᶠ (tm→nf t) tm→nf (snd t) = sndⁿᶠ (tm→nf t) tm→nf unit = unitⁿᶠ -- Normalisation by hereditary substitution. norm : ∀ {A Γ Δ} → Γ ⁏ Δ ⊢ A → Γ ⁏ Δ ⊢ A norm = nf→tm ∘ tm→nf
Cubical/Foundations/Equiv/Properties.agda
howsiyu/cubical
0
17034
<filename>Cubical/Foundations/Equiv/Properties.agda {- A couple of general facts about equivalences: - if f is an equivalence then (cong f) is an equivalence ([equivCong]) - if f is an equivalence then pre- and postcomposition with f are equivalences ([preCompEquiv], [postCompEquiv]) - if f is an equivalence then (Σ[ g ] section f g) and (Σ[ g ] retract f g) are contractible ([isContr-section], [isContr-retract]) - isHAEquiv is a proposition [isPropIsHAEquiv] (these are not in 'Equiv.agda' because they need Univalence.agda (which imports Equiv.agda)) -} {-# OPTIONS --safe #-} module Cubical.Foundations.Equiv.Properties where open import Cubical.Core.Everything open import Cubical.Data.Sigma open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Equiv open import Cubical.Foundations.Equiv.HalfAdjoint open import Cubical.Foundations.Univalence open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Path open import Cubical.Foundations.HLevels open import Cubical.Functions.FunExtEquiv private variable ℓ ℓ′ ℓ′′ : Level A B C : Type ℓ isEquivInvEquiv : isEquiv (λ (e : A ≃ B) → invEquiv e) isEquivInvEquiv = isoToIsEquiv goal where open Iso goal : Iso (A ≃ B) (B ≃ A) goal .fun = invEquiv goal .inv = invEquiv goal .rightInv g = equivEq refl goal .leftInv f = equivEq refl invEquivEquiv : (A ≃ B) ≃ (B ≃ A) invEquivEquiv = _ , isEquivInvEquiv isEquivCong : {x y : A} (e : A ≃ B) → isEquiv (λ (p : x ≡ y) → cong (equivFun e) p) isEquivCong e = isoToIsEquiv (congIso (equivToIso e)) congEquiv : {x y : A} (e : A ≃ B) → (x ≡ y) ≃ (equivFun e x ≡ equivFun e y) congEquiv e = isoToEquiv (congIso (equivToIso e)) equivAdjointEquiv : (e : A ≃ B) → ∀ {a b} → (a ≡ invEq e b) ≃ (equivFun e a ≡ b) equivAdjointEquiv e = compEquiv (congEquiv e) (compPathrEquiv (secEq e _)) invEq≡→equivFun≡ : (e : A ≃ B) → ∀ {a b} → invEq e b ≡ a → equivFun e a ≡ b invEq≡→equivFun≡ e = equivFun (equivAdjointEquiv e) ∘ sym isEquivPreComp : (e : A ≃ B) → isEquiv (λ (φ : B → C) → φ ∘ equivFun e) isEquivPreComp e = snd (equiv→ (invEquiv e) (idEquiv _)) preCompEquiv : (e : A ≃ B) → (B → C) ≃ (A → C) preCompEquiv e = (λ φ → φ ∘ fst e) , isEquivPreComp e isEquivPostComp : (e : A ≃ B) → isEquiv (λ (φ : C → A) → e .fst ∘ φ) isEquivPostComp e = snd (equivΠCod (λ _ → e)) postCompEquiv : (e : A ≃ B) → (C → A) ≃ (C → B) postCompEquiv e = _ , isEquivPostComp e -- see also: equivΠCod for a dependent version of postCompEquiv hasSection : (A → B) → Type _ hasSection {A = A} {B = B} f = Σ[ g ∈ (B → A) ] section f g hasRetract : (A → B) → Type _ hasRetract {A = A} {B = B} f = Σ[ g ∈ (B → A) ] retract f g isEquiv→isContrHasSection : {f : A → B} → isEquiv f → isContr (hasSection f) fst (isEquiv→isContrHasSection isEq) = invIsEq isEq , secIsEq isEq snd (isEquiv→isContrHasSection isEq) (f , ε) i = (λ b → fst (p b i)) , (λ b → snd (p b i)) where p : ∀ b → (invIsEq isEq b , secIsEq isEq b) ≡ (f b , ε b) p b = isEq .equiv-proof b .snd (f b , ε b) isEquiv→hasSection : {f : A → B} → isEquiv f → hasSection f isEquiv→hasSection = fst ∘ isEquiv→isContrHasSection isContr-hasSection : (e : A ≃ B) → isContr (hasSection (fst e)) isContr-hasSection e = isEquiv→isContrHasSection (snd e) isEquiv→isContrHasRetract : {f : A → B} → isEquiv f → isContr (hasRetract f) fst (isEquiv→isContrHasRetract isEq) = invIsEq isEq , retIsEq isEq snd (isEquiv→isContrHasRetract {f = f} isEq) (g , η) = λ i → (λ b → p b i) , (λ a → q a i) where p : ∀ b → invIsEq isEq b ≡ g b p b = sym (η (invIsEq isEq b)) ∙' cong g (secIsEq isEq b) -- one square from the definition of invIsEq ieSq : ∀ a → Square (cong g (secIsEq isEq (f a))) refl (cong (g ∘ f) (retIsEq isEq a)) refl ieSq a k j = g (commSqIsEq isEq a k j) -- one square from η ηSq : ∀ a → Square (η (invIsEq isEq (f a))) (η a) (cong (g ∘ f) (retIsEq isEq a)) (retIsEq isEq a) ηSq a i j = η (retIsEq isEq a i) j -- and one last square from the definition of p pSq : ∀ b → Square (η (invIsEq isEq b)) refl (cong g (secIsEq isEq b)) (p b) pSq b i j = compPath'-filler (sym (η (invIsEq isEq b))) (cong g (secIsEq isEq b)) j i q : ∀ a → Square (retIsEq isEq a) (η a) (p (f a)) refl q a i j = hcomp (λ k → λ { (i = i0) → ηSq a j k ; (i = i1) → η a (j ∧ k) ; (j = i0) → pSq (f a) i k ; (j = i1) → η a k }) (ieSq a j i) isEquiv→hasRetract : {f : A → B} → isEquiv f → hasRetract f isEquiv→hasRetract = fst ∘ isEquiv→isContrHasRetract isContr-hasRetract : (e : A ≃ B) → isContr (hasRetract (fst e)) isContr-hasRetract e = isEquiv→isContrHasRetract (snd e) cong≃ : (F : Type ℓ → Type ℓ′) → (A ≃ B) → F A ≃ F B cong≃ F e = pathToEquiv (cong F (ua e)) cong≃-char : (F : Type ℓ → Type ℓ′) {A B : Type ℓ} (e : A ≃ B) → ua (cong≃ F e) ≡ cong F (ua e) cong≃-char F e = ua-pathToEquiv (cong F (ua e)) cong≃-idEquiv : (F : Type ℓ → Type ℓ′) (A : Type ℓ) → cong≃ F (idEquiv A) ≡ idEquiv (F A) cong≃-idEquiv F A = cong≃ F (idEquiv A) ≡⟨ cong (λ p → pathToEquiv (cong F p)) uaIdEquiv ⟩ pathToEquiv refl ≡⟨ pathToEquivRefl ⟩ idEquiv (F A) ∎ isPropIsHAEquiv : {f : A → B} → isProp (isHAEquiv f) isPropIsHAEquiv {f = f} ishaef = goal ishaef where equivF : isEquiv f equivF = isHAEquiv→isEquiv ishaef rCoh1 : (sec : hasSection f) → Type _ rCoh1 (g , ε) = Σ[ η ∈ retract f g ] ∀ x → cong f (η x) ≡ ε (f x) rCoh2 : (sec : hasSection f) → Type _ rCoh2 (g , ε) = Σ[ η ∈ retract f g ] ∀ x → Square (ε (f x)) refl (cong f (η x)) refl rCoh3 : (sec : hasSection f) → Type _ rCoh3 (g , ε) = ∀ x → Σ[ ηx ∈ g (f x) ≡ x ] Square (ε (f x)) refl (cong f ηx) refl rCoh4 : (sec : hasSection f) → Type _ rCoh4 (g , ε) = ∀ x → Path (fiber f (f x)) (g (f x) , ε (f x)) (x , refl) characterization : isHAEquiv f ≃ Σ _ rCoh4 characterization = isHAEquiv f -- first convert between Σ and record ≃⟨ isoToEquiv (iso (λ e → (e .g , e .rinv) , (e .linv , e .com)) (λ e → record { g = e .fst .fst ; rinv = e .fst .snd ; linv = e .snd .fst ; com = e .snd .snd }) (λ _ → refl) λ _ → refl) ⟩ Σ _ rCoh1 -- secondly, convert the path into a dependent path for later convenience ≃⟨ Σ-cong-equiv-snd (λ s → Σ-cong-equiv-snd λ η → equivΠCod λ x → compEquiv (flipSquareEquiv {a₀₀ = f x}) (invEquiv slideSquareEquiv)) ⟩ Σ _ rCoh2 ≃⟨ Σ-cong-equiv-snd (λ s → invEquiv Σ-Π-≃) ⟩ Σ _ rCoh3 ≃⟨ Σ-cong-equiv-snd (λ s → equivΠCod λ x → ΣPath≃PathΣ) ⟩ Σ _ rCoh4 ■ where open isHAEquiv goal : isProp (isHAEquiv f) goal = subst isProp (sym (ua characterization)) (isPropΣ (isContr→isProp (isEquiv→isContrHasSection equivF)) λ s → isPropΠ λ x → isProp→isSet (isContr→isProp (equivF .equiv-proof (f x))) _ _) -- loop spaces connected by a path are equivalent conjugatePathEquiv : {A : Type ℓ} {a b : A} (p : a ≡ b) → (a ≡ a) ≃ (b ≡ b) conjugatePathEquiv p = compEquiv (compPathrEquiv p) (compPathlEquiv (sym p)) -- composition on the right induces an equivalence of path types compr≡Equiv : {A : Type ℓ} {a b c : A} (p q : a ≡ b) (r : b ≡ c) → (p ≡ q) ≃ (p ∙ r ≡ q ∙ r) compr≡Equiv p q r = congEquiv ((λ s → s ∙ r) , compPathr-isEquiv r) -- composition on the left induces an equivalence of path types compl≡Equiv : {A : Type ℓ} {a b c : A} (p : a ≡ b) (q r : b ≡ c) → (q ≡ r) ≃ (p ∙ q ≡ p ∙ r) compl≡Equiv p q r = congEquiv ((λ s → p ∙ s) , (compPathl-isEquiv p)) isEquivFromIsContr : {A : Type ℓ} {B : Type ℓ′} → (f : A → B) → isContr A → isContr B → isEquiv f isEquivFromIsContr f isContrA isContrB = subst isEquiv (λ i x → isContr→isProp isContrB (fst B≃A x) (f x) i) (snd B≃A) where B≃A = isContr→Equiv isContrA isContrB isEquiv[f∘equivFunA≃B]→isEquiv[f] : {A : Type ℓ} {B : Type ℓ′} {C : Type ℓ′′} → (f : B → C) (A≃B : A ≃ B) → isEquiv (f ∘ equivFun A≃B) → isEquiv f isEquiv[f∘equivFunA≃B]→isEquiv[f] f (g , gIsEquiv) f∘gIsEquiv = precomposesToId→Equiv f _ w w' where w : f ∘ g ∘ equivFun (invEquiv (_ , f∘gIsEquiv)) ≡ idfun _ w = (cong fst (invEquiv-is-linv (_ , f∘gIsEquiv))) w' : isEquiv (g ∘ equivFun (invEquiv (_ , f∘gIsEquiv))) w' = (snd (compEquiv (invEquiv (_ , f∘gIsEquiv) ) (_ , gIsEquiv)))
extern/gnat_sdl/gnat_sdl2/src/sdl_messagebox_h.ads
AdaCore/training_material
15
16638
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with SDL_stdinc_h; with Interfaces.C.Strings; limited with SDL_video_h; package SDL_messagebox_h is -- Simple DirectMedia Layer -- Copyright (C) 1997-2018 <NAME> <<EMAIL>> -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- 3. This notice may not be removed or altered from any source distribution. -- -- For SDL_Window -- Set up for C function definitions, even when using C++ --* -- * \brief SDL_MessageBox flags. If supported will display warning icon, etc. -- --*< error dialog --*< warning dialog --*< informational dialog subtype SDL_MessageBoxFlags is unsigned; SDL_MESSAGEBOX_ERROR : constant unsigned := 16; SDL_MESSAGEBOX_WARNING : constant unsigned := 32; SDL_MESSAGEBOX_INFORMATION : constant unsigned := 64; -- ..\SDL2_tmp\SDL_messagebox.h:42 --* -- * \brief Flags for SDL_MessageBoxButtonData. -- --*< Marks the default button when return is hit --*< Marks the default button when escape is hit subtype SDL_MessageBoxButtonFlags is unsigned; SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT : constant unsigned := 1; SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT : constant unsigned := 2; -- ..\SDL2_tmp\SDL_messagebox.h:51 --* -- * \brief Individual button data. -- --*< ::SDL_MessageBoxButtonFlags type SDL_MessageBoxButtonData is record flags : aliased SDL_stdinc_h.Uint32; -- ..\SDL2_tmp\SDL_messagebox.h:58 buttonid : aliased int; -- ..\SDL2_tmp\SDL_messagebox.h:59 text : Interfaces.C.Strings.chars_ptr; -- ..\SDL2_tmp\SDL_messagebox.h:60 end record; pragma Convention (C_Pass_By_Copy, SDL_MessageBoxButtonData); -- ..\SDL2_tmp\SDL_messagebox.h:61 -- skipped anonymous struct anon_68 --*< User defined button id (value returned via SDL_ShowMessageBox) --*< The UTF-8 button text --* -- * \brief RGB value used in a message box color scheme -- type SDL_MessageBoxColor is record r : aliased SDL_stdinc_h.Uint8; -- ..\SDL2_tmp\SDL_messagebox.h:68 g : aliased SDL_stdinc_h.Uint8; -- ..\SDL2_tmp\SDL_messagebox.h:68 b : aliased SDL_stdinc_h.Uint8; -- ..\SDL2_tmp\SDL_messagebox.h:68 end record; pragma Convention (C_Pass_By_Copy, SDL_MessageBoxColor); -- ..\SDL2_tmp\SDL_messagebox.h:69 -- skipped anonymous struct anon_69 type SDL_MessageBoxColorType is (SDL_MESSAGEBOX_COLOR_BACKGROUND, SDL_MESSAGEBOX_COLOR_TEXT, SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, SDL_MESSAGEBOX_COLOR_MAX); pragma Convention (C, SDL_MessageBoxColorType); -- ..\SDL2_tmp\SDL_messagebox.h:79 --* -- * \brief A set of colors to use for message box dialogs -- type SDL_MessageBoxColorScheme_colors_array is array (0 .. 4) of aliased SDL_MessageBoxColor; type SDL_MessageBoxColorScheme is record colors : aliased SDL_MessageBoxColorScheme_colors_array; -- ..\SDL2_tmp\SDL_messagebox.h:86 end record; pragma Convention (C_Pass_By_Copy, SDL_MessageBoxColorScheme); -- ..\SDL2_tmp\SDL_messagebox.h:87 -- skipped anonymous struct anon_71 --* -- * \brief MessageBox structure containing title, text, window, etc. -- --*< ::SDL_MessageBoxFlags type SDL_MessageBoxData is record flags : aliased SDL_stdinc_h.Uint32; -- ..\SDL2_tmp\SDL_messagebox.h:94 window : access SDL_video_h.Class_SDL_Window.SDL_Window; -- ..\SDL2_tmp\SDL_messagebox.h:95 title : Interfaces.C.Strings.chars_ptr; -- ..\SDL2_tmp\SDL_messagebox.h:96 message : Interfaces.C.Strings.chars_ptr; -- ..\SDL2_tmp\SDL_messagebox.h:97 numbuttons : aliased int; -- ..\SDL2_tmp\SDL_messagebox.h:99 buttons : access constant SDL_MessageBoxButtonData; -- ..\SDL2_tmp\SDL_messagebox.h:100 colorScheme : access constant SDL_MessageBoxColorScheme; -- ..\SDL2_tmp\SDL_messagebox.h:102 end record; pragma Convention (C_Pass_By_Copy, SDL_MessageBoxData); -- ..\SDL2_tmp\SDL_messagebox.h:103 -- skipped anonymous struct anon_72 --*< Parent window, can be NULL --*< UTF-8 title --*< UTF-8 message text --*< ::SDL_MessageBoxColorScheme, can be NULL to use system settings --* -- * \brief Create a modal message box. -- * -- * \param messageboxdata The SDL_MessageBoxData structure with title, text, etc. -- * \param buttonid The pointer to which user id of hit button should be copied. -- * -- * \return -1 on error, otherwise 0 and buttonid contains user id of button -- * hit or -1 if dialog was closed. -- * -- * \note This function should be called on the thread that created the parent -- * window, or on the main thread if the messagebox has no parent. It will -- * block execution of that thread until the user clicks a button or -- * closes the messagebox. -- function SDL_ShowMessageBox (messageboxdata : access constant SDL_MessageBoxData; buttonid : access int) return int; -- ..\SDL2_tmp\SDL_messagebox.h:119 pragma Import (C, SDL_ShowMessageBox, "SDL_ShowMessageBox"); --* -- * \brief Create a simple modal message box -- * -- * \param flags ::SDL_MessageBoxFlags -- * \param title UTF-8 title text -- * \param message UTF-8 message text -- * \param window The parent window, or NULL for no parent -- * -- * \return 0 on success, -1 on error -- * -- * \sa SDL_ShowMessageBox -- function SDL_ShowSimpleMessageBox (flags : SDL_stdinc_h.Uint32; title : Interfaces.C.Strings.chars_ptr; message : Interfaces.C.Strings.chars_ptr; window : access SDL_video_h.Class_SDL_Window.SDL_Window) return int; -- ..\SDL2_tmp\SDL_messagebox.h:133 pragma Import (C, SDL_ShowSimpleMessageBox, "SDL_ShowSimpleMessageBox"); -- Ends C function definitions when using C++ -- vi: set ts=4 sw=4 expandtab: end SDL_messagebox_h;
45/qb/ir/context.asm
minblock/msdos
0
161386
<reponame>minblock/msdos<gh_stars>0 TITLE context.asm - context manager ;*** ;context.asm - context manager for the Quick Basic Interpreter ; ; Copyright <C> 1986, 1987 Microsoft Corporation ; ;Purpose: ; - Creation and Deletion of entries in the Module and Procedure Register Set ; tables. ; - Swapping module and procedure register sets between the global table ; of Rs's and the static current working register sets 'mrsCur' and ; 'prsCur'. ; ; Note: static handling of Procedure Register Sets is performed by this ; module; frame (per invocation) handling is performed by ; the Procedure Manager. ; ; ;****************************************************************************** .xlist include version.inc CONTEXT_ASM = ON includeOnce architec includeOnce context includeOnce conint includeOnce heap includeOnce names includeOnce pcode includeOnce qbimsgs includeOnce rtinterp includeOnce parser includeOnce sb includeOnce scanner includeOnce txtmgr includeOnce ui includeOnce util includeOnce variable includeOnce edit .list assumes CS,CP assumes DS,DATA assumes SS,DATA assumes ES,NOTHING sBegin DATA globalB conFlags,F_CON_StaticStructs ;static bit flags staticB fCouldBeBogusPrs,FALSE ;TRUE if there's a possiblity of staticW oRsTest,UNDEFINED ;For use in ValidORs globalW oRsDupErr,0 ;MrsMake and PrsMake tell ; caller duplicate oRs globalW oPrsFirst,UNDEFINED ; head of prs chain in tRs staticW oFreePrsFirst,UNDEFINED ; head of free prs chain staticW oFreeMrsFirst,UNDEFINED ; head of free mrs chain sEnd DATA extrn B$ClearRange:FAR ;clears all owners in given rg sBegin CP ;============================================================================== ;Notes On mrs and prs structures: ; There is a single global table which contains both mrs and prs ; structures. The first entry in this table MUST be the global mrs ; (code exists which assumes the oMrs for the global mrs is OMRS_GLOBAL). ; We also assume that, if there is an empty unnamed mrs, it is the ; very next struct in the table after the global mrs. ; ; All mrs valid mrs entries are chained from this entry via the ; oMrsNext entry; UNDEFINED marks the end of the chain. ; Prs's are similarly chained together, with the global 'oPrsFirst' ; pointing to the first prs. It is NOT safe to assume that these ; chains relate to table position; the only safe way to walk the ; Rs table in any way is via the appropriate chain. ; ; Table entries are fixed in place; oRs/oMrs/oPrs's are known and ; saved outside of this component, so an mrs or prs can never move ; within this structure. If an entry is discarded, it is added to ; a free chain, for later re-use. Since mrs and prs structs are of ; different size, there are two free chains; oFreePrsFirst and ; oFreeMrsFirst are the head pointers for these chains. ; ; Note that when an mrs or prs is 'active' (i.e., copied to mrsCur/ ; prsCur) the copy in the table should not be referenced or modified ; but that entry remains linked in place. Care should be taken when ; updating an Rs chain to consider the active prs and/or mrs, i.e., ; mrsCur and prsCur are not and cannot be linked in an rs chain. ; ; The actual first entries in the mrs & prs structs are the count of ; frame temps and frame vars allocated for each instance of that ; module or procedure. There are definite dependancies on the fact ; that these are in the same spot in the mrs & prs structs. ; ; For all prs's, there is guaranteed to be a name table entry for the ; prs name. This eliminates some OM_ERR checking when obtaining the oNam ; of a prs (generally via FieldsOfPrs). ; ; At execution time, the heap-update & block copy time required by the ; normal context switching code is too slow for CALL speed. For this ; reason, whenever program execution is started, DisStaticStructs is ; called to set a static flag and deactivate mrsCur, prsCur, and txdCur. ; At execution time (only), a couple of grs fields are used to allow ; for quickly fetching the segment address of the current text table. ; Note that whenever this flag (F_CON_StaticStructs) is reset (FALSE), ; the mrsCur and prsCur structures contain garbage; only the oMrsCur, ; oPrsCur, and oRsCur fields in grs can be used to access current ; context information. ; .errnz SIZE MRS AND 1 .errnz SIZE PRS AND 1 ; The two assertions above are based on the procedure manager depending ; on an oRs always being an even number (so the low bit can be used ; as a boolean in a special case). For oRs's to always be even, mrs ; and prs structs must in turn both be even. ; ;============================================================================== ;############################################################################## ;# # ;# Initialization Functions # ;# # ;############################################################################## sEnd CP ;initialization code goes in RARE seg sBegin RARE assumes CS,RARE ;*** ;InitContext() ; ;Purpose: ; This function is called once during BASIC initialization to initialize: ; - the global register set (grs) ; - the Rs table (grs.bd[l]Rs), mrsCur, and the global mrs via MrsMake ;Entry: ; none. ;Exit: ; grs, mrsCur initialized. ; ax = 0 if no error, else [18] ; ax = standard error code. [18] ; PSW flags set up based on an OR AX,AX [18] ;******************************************************************************* cProc InitContext,<NEAR,PUBLIC,NODATA> cBegin InitContext mov ax,dataOFFSET grs ;ax == pointer to global 'grs' struct mov bx,SIZE GRSTYPE ;bx == size of 'grs' struct mov cx,GRS_CB_ZERO_INIT ;cx == cb @ start of grs to 0-fill push ax ; parm to ZeroFill push cx ; parm to ZeroFill shr bx,1 ; convert cbStruct to cwStruct cCall FillUndef,<ax,bx> ; fill whole struct with UNDEFINED cCall ZeroFill ; fill first 'cbZeroes' with zeroes PUSHI ax,<dataOFFSET grs.GRS_bdlDirect> PUSHI ax,CB_PCODE_MIN ;it must never be < CB_PCODE_MIN bytes PUSHBDL_TYPE pgtypEBPcode,ax ; pass sb type for EB version call BdlAlloc ;allocate direct mode buffer (far heap) or ax,ax DJMP jz OM_Err_In_Init PUSHI ax,<dataOFFSET grs.GRS_bdRs> PUSHI ax,0 PUSHI ax,IT_MRS call BdAlloc ;allocate table of register sets or ax,ax jz OM_Err_In_Init PUSHI ax,OGNAM_GMRS ; make global module PUSHI ax,<100h * FM2_File> call far ptr MrsMake ; make initial (untitled) mrs or ax,ax jnz InitContext_Exit ; return error code to caller call far ptr MakeInitMrs ;make initial mrs, ax=errCode ; just pass retval to caller for non FV_QB4LANG case or ax,ax jnz InitContext_Exit PUSHI ax,<dataOFFSET grs.GRS_bdtComBlk> PUSHI ax,0 PUSHI ax,IT_COMMON_BLOCK call BdAlloc ;allocate table of common blocks or ax,ax jz OM_Err_In_Init PUSHI ax,UNDEFINED call MakeCommon ;allocate table(s) for blank common inc ax ;UNDEFINED returned if OM error .errnz UNDEFINED - 0FFFFH jz OM_Err_In_Init DbAssertRel ax,z,1,RARE,<InitContext: Unnamed block not at offset 0> mov [grs.GRS_fDirect],al ;so UserInterface() thinks opEot was ;from direct mode buffer sub ax,ax ; retval; 0 == 'no errors' InitContext_Exit: or ax,ax cEnd InitContext OM_Err_In_Init: mov ax,ER_OM jmp short InitContext_Exit sEnd RARE sBegin CP assumes CS,CP ;############################################################################## ;# # ;# Context Manager Functions Common to mrs's and prs's # ;# # ;############################################################################## ;*** ;InitStruct ; ;Purpose: ; This function is designed to initialize a structure by filling ; it partly with UNDEFINED words, and partly with zeroes. The input ; pointer is to the start of the structure, and the input count ; is for the number of zeroes to fill in at the beginning of the ; structure, after first filling the entire structure with UNDEFINED. ; The result is a structure with the first cbZeroes bytes initialized ; to zero, the remainder filled with UNDEFINED. ; ; Made NEAR in CP (moved from RARE) as part of revision [17]. ;Entry: ; ax = pStruct - pointer to the start of the structure. ; bx = cbStruct - count of bytes in the structure ; cx = cbZeroes - count of bytes to fill (@ start of struct) w/0 ;Exit: ; none. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* InitStruct PROC NEAR push ax ;parm to ZeroFill push cx ;parm to ZeroFill shr bx,1 ;convert cbStruct to cwStruct cCall FillUndef,<ax,bx> ;fill whole struct with UNDEFINED cCall ZeroFill ;fill first 'cbZeroes' with zeroes ret InitStruct ENDP ;*** ;MrsTableEmpty - see if there are any mrs entries ; ;Purpose: ; This function is called to check to see if there are any active ; mrs entries in tRs. ; We ignore any text mrs's, i.e., if the only mrs's in the table are for ; text objects (rather than for modules), say that the table is empty. ; Also ignore the global mrs. ; ; NOTE: it is assumed that this routine will only be called when there ; is no current entry, i.e., grs.oMrsCur is UNDEFINED. ; ;Entry: ; es set to rs table segment ;Exit: ; PSW.Z set if table empty, clear if it has one or more active entries. ; if table not empty, bx = oMrs for active entry. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc MrsTableEmpty,<NEAR>,<ES> cBegin MrsTableEmpty GETRS_SEG es,bx,<SIZE,LOAD> mov bx,OMRS_GLOBAL ; es:bx points to the global mrs ; (ignore the global mrs) RS_BASE add,bx ;add base of tRs to bx Walk_Loop: mov bx,PTRRS[bx.MRS_oMrsNext] ;advance to next mrs inc bx ;end of chain? .errnz UNDEFINED - 0FFFFH jz Exit_Table_Walk ; brif so - - - no module mrs's found dec bx RS_BASE add,bx ;add base of tRs to bx test BPTRRS[bx.MRS_flags2],FM2_Include jnz Walk_Loop ;brif found an include file - ignore test BPTRRS[bx.MRS_flags2],FM2_NoPcode jnz Walk_Loop ;brif active mrs found for a non-file ; mrs (ignore it) RS_BASE sub,bx ;subtract base of tRs from bx or sp,sp ;clear PSW.Z Exit_Table_Walk: cEnd MrsTableEmpty ;*** ;RsTableSearch - search the Rs table ; ;Purpose: ; This function is shared by mrs-specific and prs-specific code to ; search for a matching structure entry. 'procType' (ax input value) ; indicates whether we're to search the mrs or prs chain; in addition, ; it cues us in on additional search logic needed in the case we're to ; search for a DEF FN (must then also match oMrs and oTyp). ; ; [10] This shared routine is only possible so long as the ogNam fields ; [10] are in the same place relative to the start of prs & mrs structs, ; [10] and the ogNam field of an valid prs or mrs entry can never be ; [10] UNDEFINED (which is the signal that an entry is active, ; [10] and is thus a 'hole' in the table). ; [10] Also, note that a special case (mrs chain only) exists where ; [10] an "untitled" entry can exist, whose ogNam field will be ; [13] OGNAM_UNNAMED. ; ; [10] Note that the global mrs has an ogNam that can't possibly be a ; [10] valid ogNam, yet is not UNDEFINED, so no tMrs search should ever ; [10] 'find' the global mrs unless it's specifically being looked for ; [10] but it shouldn't be, since it ALWAYS exists, and is always at ; [10] offset 0. ; ; NOTE: This routine assumes that names are unique - - - a simple ; NOTE: comparison is done to see if they match, so any differences ; NOTE: w.r.t. file paths will cause no match to occur. Case Sensitivity ; NOTE: is, however, ignored in the comparison (i.e., 'a' == 'A' for ; NOTE: the search). ; ;Entry: ; al == procType - If this is PT_NOT_PROC, then the mrs chain is searched ; otherwise, it must be PT_SUB, PT_FUNCTION, or PT_DEFFN. ; PT_SUB and PT_FUNCTION use the same search logic as ; PT_NOT_PROC, but for PT_DEFFN, additional matching logic ; is used. ; dl == oTyp, IF ax == PT_DEFFN; only used in the case we're searching ; the prs table for a DEF FN. If ax is not PT_DEFFN, ; then dl is undefined, and not used in search. ; Only used for FV_QB4LANG versions. ; es set to rs table segment (if FV_FAR_RSTBL) ; ogNam - Name of entry to search for (ogNam field). ; If ogNam == OGNAM_UNNAMED, then we know we're searching ; for an entry (in the mrs chain) whose ogNam entry is ; also OGNAM_UNNAMED. ; NOTE: it is assumed on entry that there is no 'current' entry for ; the table being searched, i.e., if the prs chain is to be ; searched, it is assumed that grs.oPrsCur == UNDEFINED - - - ; therefore, callers of this routine should call ; Mrs/PrsDeActivate first. ; NOTE: it is assumed by at least one caller of this routine that it ; cannot trigger any heap movement. ;Exit: ; AX == offset into the appropriate table if the search is successful, ; or UNDEFINED if it is not. ; BX == if AX is UNDEFINED, then this is an offset into the ; appropriate table to the last 'hole', or UNDEFINED if there ; are no holes in the table. ; If, however, AX is a table offset, BX is a pointer to the ; found entry. ; ES will be set to the tRs seg (if FV_FAR_RSTBL) ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc RsTableSearch,<NEAR,NODATA>,<SI,DI> parmW ogNam LocalB oTyp LocalB procType LocalW oRsFree cBegin RsTableSearch mov [oTyp],0 mov [procType],al mov di,[ogNam] mov bx,[oFreePrsFirst] ;assume we're searching prs chain cmp al,PT_NOT_PROC ;Should we search the prs chain? jnz Search_tPRS ; brif so DbAssertRel grs.GRS_oMrsCur,e,UNDEFINED,CP,<grs.oMrsCur not UNDEFINED in RsTableSearch in context.asm> mov si,OMRS_GLOBAL ; offset to the global mrs mov bx,[oFreeMrsFirst] jmp short Search_Table Search_tPRS: DbAssertRel grs.GRS_oPrsCur,e,UNDEFINED,CP,<grs.oPrsCur not UNDEFINED in RsTableSearch context.asm> mov si,[oPrsFirst] cmp al,PT_DEFFN ;are we searching for a DEF FN? jnz Search_Table ;brif not mov [oTyp],dl ;save type of DEF FN (else oTyp stays 0) DbAssertRelB ET_MAX,ae,dl,CP,<RsTableSearch input oTyp not predefined> Search_Table: mov [oRsFree],bx ;offset to first free struct GETRS_SEG es,bx,<SIZE,LOAD> ;At this point, [oTyp]=0 for MRS, SUB, FUNCTION, non-zero for DEF FN ; si is the oRs for the first struct to examine ; [procType] = PT_xxx of entry being searched for ; di = input ogNam Search_Loop: inc si .errnz UNDEFINED - 0FFFFH jz Quit_Search ;brif end of chain found dec si RS_BASE add,si ;add base of table DbAssertRel PTRRS[si.MRS_ogNam],nz,UNDEFINED,CP,<RsTableSearch: err 1> mov ax,PTRRS[si.MRS_ogNam] .errnz OGNAM_UNNAMED - 0 or di,di ; special case where ogNam = 0? jz Untitled_Mrs ;brif so cmp di,ax jnz Not_A_Match ;brif names don't match mov al,[oTyp] or al,al ;searching for a DEF FN? jz Match_Found ; brif not mov dx,[grs.GRS_oMrsCur] ;oMrs of the DEF must be oMrsCur ... cmp dx,PTRRS[si.PRS_oMrs] jnz Not_A_Match ; brif they're not the same mov ah,BPTRRS[si.PRS_oType] and ah,M_PT_OTYPE ; mask out any flags in this byte cmp al,ah ; oTyp's must match if it's a DEF jz Match_Found Not_A_Match: cmp [procType],PT_NOT_PROC jz MrsSearch ;brif we're walking the mrs chain mov si,PTRRS[si.PRS_oPrsNext] ;move to next entry jmp Search_Loop ;loop to consider next entry MrsSearch: mov si,PTRRS[si.MRS_oMrsNext] ;move to next entry jmp Search_Loop ;loop to consider next entry Untitled_Mrs: or ax,ax ;is this the special 'untitled' entry? .errnz OGNAM_UNNAMED - 0 jnz Not_A_Match ;brif not Match_Found: xchg ax,si ;pointer to found entry RS_BASE sub,ax ;pRs --> oRs jmp short Exit_Table_Search ;found entry - exit routine Quit_Search: mov ax,UNDEFINED ;entry not found mov bx,[oRsFree] ;first free struct of appropriate ; size Exit_Table_Search: cEnd RsTableSearch ;*** ;PrsFind - find a prs in the tRs ;Purpose: ; Given the name of a prs, return the oPrs for it, or UNDEFINED if it's ; not found. ; Preserve the Mrs & Prs state of the caller. ; ; NOTE: This should never be called to search for a DEF FN's, only ; NOTE: a SUB or a FUNCTION. ; ; For complete details of the matching algorithm, see RsTableSearch. ;Entry: ; ogNam - name of the prs to search for ;Exit: ; AX = UNDEFINED if no match found, otherwise it's the oPrs for the ; desired prs. ;Exceptions: ; none. ;**** ;*** ;MrsFind - find an mrs in tRs ;Purpose: ; Given the name of an mrs, return the oMrs for it, or UNDEFINED if it's ; not found. ; Preserve the Mrs & Prs state of the caller. ; ; For complete details of the matching algorithm, see RsTableSearch. ;Entry: ; ogNam - name of the mrs to search for ;Exit: ; AX = UNDEFINED if no match found, otherwise it's the oMrs for the ; desired mrs. ;Exceptions: ; none. ;**** cProc PrsFind,<PUBLIC,FAR,NODATA> cBegin <nogen> mov al,PT_SUB ;search for prs's SKIP2_PSW ;skip MrsFind, fall into RsFind cEnd <nogen> cProc MrsFind,<PUBLIC,FAR,NODATA> cBegin <nogen> mov al,PT_NOT_PROC ;search for mrs's cEnd <nogen> ?DFP = DFP_NONE ; don't smash regs on entry cProc RsFind,<FAR,NODATA>,<si> parmW ogNam cBegin ?DFP = DFP_CP ; restore switch DbChk ogNam,ogNam push ax mov si,[grs.GRS_oRsCur] ;save, so we can restore at exit cCall MrsDeActivate pop ax cCall RsTableSearch,<ogNam> push ax ;save retval cCall RsActivateCP,<si> ;reactivate original RsCur pop ax ;restore retval cEnd ;*** ;MoveTheMrs ; ;Purpose: ; This code is intended to be used by the Mrs[De]Activate routines, ; to copy a structure from static data into the table or vice versa. ; ; Changed significantly and renamed (was CopyNchg2Bds) as part of ; revision [10]. ;Entry: ; si == pointer to the start of the source mrs ; bx == pointer to the start of the dest. mrs ; if FV_FAR_RSTBL, ds is source seg, es is dest. seg ; NOTE: if FV_FAR_RSTBL, one CANNOT assume ds == ss! ;Exit: ; none. ;Uses: ; si ;Exceptions: ; None. ;**** MoveTheMrs PROC NEAR push di mov di,bx ;so pDst is saved across calls mov cx,SIZE MRS ; cx == cbMrs mov dx,MRS_txd.TXD_bdlText call CopyNchgMrs ;Common code for mrs's and prs's mov ax,[si.MRS_bdlnam.FHD_pNext] ;special case: in case call to mov [di.MRS_bdlnam.FHD_pNext],ax ; BdlChgOwner in CopyNchgMrs ; changed the pNext field ; in source bdl mov ax,MRS_bdlnam mov bx,di add bx,ax ;bx = destination pBdlNam add ax,si ;ax = source pBdlNam cCall BdlChgOwner,<ax,bx> ;NOTE: We MUST call this AFTER ; the block copy mov ax,MRS_bdVar add si,ax add di,ax cCall BdChgOwner_NoCopy,<si,di> ;change owner of 2nd bd ; copies the mrs pop di ret MoveTheMrs ENDP ;*** ;CopyNchgMrs, CopyNchgPrs ; ;Purpose: ; This code is intended to be used by the Mrs/Prs[De]Activate routines, ; for copying a structure from static data into a table or vice versa. ; In addition, the owner to the bdlText is also updated (via bdmgr) ; for CopyNchgMrs. ;Entry: ; si == pointer to the start of the source struct ; bx == pointer to the start of the dest. struct ; For Mrs callers: ; cx == count of bytes in the structure to copy ; dx == offset into structure to prs/mrs text bdl ; For Prs callers: ; if FV_FAR_RSTBL, ds is source seg, es is dest. seg, ; and NOTE that in this case, one CANNOT assume ss == ds ;Exit: ; none. ;Exceptions: ; None. ;**** CopyNchgPrs PROC NEAR mov ax,sp mov cx,SIZE PRS - SIZE TXD .errnz (SIZE PRS - SIZE TXD) - PRS_txd ;we're counting on the txd ; being the last element in ; the prs structure SKIP2_PSW CopyNChgMrs: sub ax,ax push di push ss pop es xchg di,ax ;save flag in di mov ax,dx add ax,bx ;points to dest. bdlText add dx,si ;points to source bdlText push dx ;pass to BdlChgOwner push ax ;pass to BdlChgOwner push si ;pass pbSrc to CopyBlk push bx ;pass bpDst to CopyBlk push cx ;pass cbStruct to CopyBlk call CopyBlk or di,di jnz CopyNchg_Cont ;brif don't want to move bdl ; owner from the table cCall BdlChgOwner ;must do this AFTER block copy SKIP2_AX CopyNchg_Cont: pop ax ;disgard parms to BdlChgOwner pop ax mov [si.MRS_ogNam],UNDEFINED ; indicate struct not active pop di ret CopyNchgPrs ENDP ;*** ;SetMrsUndef, SetMrsAx ;Purpose: ; Set grs.oMrsCur and grs.oRsCur to [ax] or UNDEFINED ;Entry: ; SetMrsAx: ax = new grs.oMrsCur ;Preserves: ; Caller's assume that no registers other than ax are modified ; ;*************************************************************************** SetMrsUndef PROC NEAR mov ax,UNDEFINED SetMrsUndef ENDP ;fall into SetMrsAx SetMrsAx PROC NEAR mov [grs.GRS_oMrsCur],ax mov [grs.GRS_oRsCur],ax ret SetMrsAx ENDP ;*** ;SetPrsUndef, SetPrsAx ;Purpose: ; Set grs.oPrsCur to [ax] or UNDEFINED, keeping grs.oRsCur consistent. ;Entry: ; SetPrsAx: ax = new grs.oPrsCur ;Preserves: ; Caller's assume that no registers other than ax are modified ; ;*************************************************************************** SetPrsUndef PROC NEAR mov ax,UNDEFINED SetPrsUndef ENDP ;fall into SetPrsAx SetPrsAx PROC NEAR mov [grs.GRS_oPrsCur],ax inc ax ;test for UNDEFINED jz NoPrs ;brif no prs is active dec ax or ah,80h ;high bit indicates prs active mov [grs.GRS_oRsCur],ax ret NoPrs: mov ax,[grs.GRS_oMrsCur] mov [grs.GRS_oRsCur],ax ;oRsCur = oMrsCur (no prs active) ret SetPrsAx ENDP ;############################################################################## ;# # ;# Module related Context Manager Functions # ;# # ;############################################################################## ;*** ;MrsDiscard() ; ;Purpose: ; Release all resources associated with current module. This includes the ; module's type table, static value table, and text table. ; This routine calls DiscardPrs for every procedure in this module. ; ; TxtDiscard is also called (prior to setting grs.oMrsCur to UNDEFINED). ; ;Entry: ; static bit flag F_CON_LeaveTMrsEmpty in conFlags - - - if we're ; discarding the last mrs and this bit flag is set (TRUE), just ; leave no mrs in tRs, otherwise, call MrsMake to create a ; new unnamed module. ;Exit: ; AX = non-zero ; Special case: AX = UNDEFINED if MakeInitMrs is called. [47] ; grs.oMrsCur = grs.oPrsCur = UNDEFINED ;Uses: ; none. ;Exceptions: ; if the module has been modified and user cancels, triggers a runtime ; error. ;******************************************************************************* cProc MrsDiscard,<PUBLIC,FAR,NODATA> cBegin MrsDiscard DbAssertRel mrsCur.MRS_ogNam,nz,OGNAM_GMRS,CP,<MrsDiscard: global mrs!> DbAssertRel mrsCur.MRS_ogNam,nz,OGNAM_CLIPBOARD,CP,<MrsDiscard: err 1> DbAssertRel mrsCur.MRS_ogNam,nz,OGNAM_IMMEDIATE,CP,<MrsDiscard: err 2> cCall PrsDeActivate call AlphaORsFree ;release table of sorted oRs's call VarDealloc ;deallocate any owners in ; the module variable table cCall DiscardHistoryORs,<grs.GRS_oMrsCur> ; throw away help ; history for mrs. ;Note that the below scheme depends on the fact that NextPrsInMrs ;finds the first prs in the table if grs.GRS_oPrsCur is UNDEFINED, and ;then subsequent prs's based on grs.GRS_oPrsCur. It is not safe to ;call ForEachCP to do this, because that scheme depends on walking ;the prs chain, and PrsDiscard1 might discard the current entry. ;In essense we are starting from the top of the prs chain each time ;through the loop below. ; To further complicate things, PrsDiscard1 might or might not ; free the prs; if it does not, the below still works, but we ; walk from prs to prs, not freeing them, but marking them as ; undefined proc.s and freeing associated resources. PrsDiscard_Loop: call far ptr NextPrsInMrs ;activate next prs in this mrs inc ax ;no more prs's in this module? jz MrsDiscard_Cont ; brif so call PrsDiscard1 ;discard active prs it jmp short PrsDiscard_Loop MrsDiscard_Cont: cCall PrsDeActivate ; ensure TxtDeleteAll ; deletes txt in MODULE ; text table, so any ; declares to proc.s in ; this module are removed ; prior to calling ; ChkAllUndefPrsSaveRs call TxtDeleteAll ;delete all text in txt table, ; but don't free bdl yet call ChkAllUndefPrsSaveRs ;search for new defining ;references for Prs entries ;which had their "defining" ;reference deleted. cCall TxtDiscard ;discard current text table PUSHI ax,<dataOFFSET mrsCur.MRS_bdVar> cCall BdFree PUSHI ax,<dataOFFSET mrsCur.MRS_bdlNam> call BdlFree ;free module name table test [mrsCur.mrs_flags2],FM2_NoPcode ; is a document mrs? jz NoDocBuffer ; brif not push [mrsCur.MRS_pDocumentBuf] ; document table to delete call FreeBuf ; Free the buffer NoDocBuffer: ;don't need to modify entry in table - - - without an active mrs, ; it will automatically look like a 'hole'. mov ax,[grs.GRS_oMrsCur] cmp ax,[grs.GRS_oMrsMain] ;discarding Main module? jnz Not_Main_Module ;brif not mov [grs.GRS_oMrsMain],UNDEFINED ;now there is no current Main jmp SHORT UndefCur Not_Main_Module: call MainModified ;mark main module as modified ; if current mrs is pcode ; mrs (so we will be sure ; to save updated xxx.MAK) ; (preserves ax) UndefCur: push ax call SetMrsUndef ;grs.oMrsCur=oRsCur=UNDEFINED pop ax ;restore ax = oMrsCur ;now unlink this entry from the mrs chain and link it into the free ; mrs chain GETRS_SEG es,bx,<SIZE,LOAD> mov bx,ax ;ax = bx = oMrs we're unlinking RS_BASE add,bx ;PTRRS:bx = pMrs we're unlinking mov cx,ax xchg cx,[oFreeMrsFirst] ;cx = offset to first free mrs, ; this mrs is new first free xchg PTRRS[bx.MRS_oMrsNext],cx ;mrs now linked into free list ;now, cx is the offset to the next mrs in the active chain; use ; that to unlink this mrs from the active chain mov bx,OMRS_GLOBAL ; start from global mrs UnLink_Loop: RS_BASE add,bx mov dx,PTRRS[bx.MRS_oMrsNext] ;offset to next mrs in chain cmp dx,ax ;found previous chain entry? jz UnLinkIt ; brif so mov bx,dx ;advance to next entry jmp UnLink_Loop UnLinkIt: mov PTRRS[bx.MRS_oMrsNext],cx ;unlink the discarded mrs push sp ; Default return value ; Assumes: ; sp != 0 ; sp != UNDEFINED test [conFlags],F_CON_LeaveTMrsEmpty ;should we just leave tMrs ; empty if this was only mrs? jnz MrsDiscard_Exit ;brif so Mrs_No_Trim: push ax ;pass oMrsCur to WnReAssign call MrsTableEmpty ;PSW.Z clear if no mrs's ; bx = remaining oMrs (if any) push bx ;pass oMrsNew to WnReAssign jnz MrsDiscard_Exit1 ;brif mrs table not empty call far ptr MakeInitMrs ;make initial mrs ; (certain it won't run out ; of memory here ...) DbAssertRel ax,z,0,CP,<MrsDiscard: MakeInitMrs returned an error code> pop bx ;discard invalid oMrsNew pop dx ; Get oMrsOld pop ax ; discard default ret val pushi ax, UNDEFINED ; return UNDEFINED to ; indicate MakeInitMrs called push dx ; Put oMrsOld back push [grs.GRS_oMrsCur] ;pass oMrsNew to WnReAssign cCall MrsDeActivate ;don't want it active MrsDiscard_Exit1: PUSHI ax,0 ;not just renaming an oRs call WnReAssign ;parms already pushed MrsDiscard_Exit: pop ax ; Get return value MrsDiscard_Exit2: cEnd MrsDiscard ;*** ;UnlinkFreeMrs ;Purpose: ; Given an oMrs, search the free mrs chain for the oMrs and unlink it ; from the chain if found. ;Input: ; ax = oMrs to be unlinked from the free list ;Exit: ; none ;****************************************************************************** UnlinkFreeMrs PROC NEAR GETRS_SEG es,bx,<SIZE,LOAD> ; prepare for link work mov dx,[oFreeMrsFirst] inc dx jz UnlinkEmpty_Done ;free chain is empty dec dx cmp ax,dx jnz Unlink_Unnamed_Entry ;brif unnamed hole not first free mov bx,dx RS_BASE add,bx mov dx,PTRRS[bx.MRS_oMrsNext] mov [oFreeMrsFirst],dx ;unlink complete jmp short UnlinkEmpty_Done Unlink_Unnamed_Entry: mov bx,dx RS_BASE add,bx mov dx,PTRRS[bx.MRS_oMrsNext] inc dx jz UnlinkEmpty_Done ;unnamed mrs hole not in free list dec dx cmp ax,dx jnz Unlink_Unnamed_Entry xchg dx,bx RS_BASE add,bx mov cx,PTRRS[bx.MRS_oMrsNext] xchg dx,bx mov PTRRS[bx.MRS_oMrsNext],cx ;unlink complete UnlinkEmpty_Done: ret UnlinkFreeMrs ENDP ;*** ;MrsMake(ogNam, flags) ; ;Purpose: ; The user-interface is the only QBI component which deals in any way with ; module names. A module's name is the same as the path name from which it ; was loaded. This function searches for a module by the name 'ogNam'. If ; found, an error code is returned (ER_DD). If not found, it creates ; a new Mrs entry and names it 'ogNam'. Calls the TextMgr routine ; TxtCurInit() to initialize the text table. Calls the Variable Manager's ; MakeMrsTVar() if this mrs is not for a text object. ; ; Note that if we're making a named mrs and there exists an empty unnamed ; mrs (which can only be at a specific offset from the start of the ; table), we'll just discard the empty unnamed one, and use that as a ; hole to put the new mrs in. ; ; Note also that, if there is no MAIN module on successful conclusion of ; this routine, the new current module will be made the MAIN one. ; ;Entry: ; ogNam: ; If module's name is to be 'Untitled', ; ogNam = OGNAM_UNNAMED ; else if module is the global module (created only once) ; ogNam = OGNAM_GMRS ; else if module is for some other special purpose ; ogNam <= OGNAM_PSEUDO_MAX ; else ; ogNam is an offset into the global name table for this module name ; flags: ; low byte = initial value of MRS_flags ; high byte = initial value of MRS_flags2 ; Command Window: FM2_NoPcode ; ClipBoard: FM2_NoPcode ; Module: FM2_File ; Include File: FM2_File + FM2_Include ; Document File: FM2_File + FM2_NoPcode ; If either FM2_Include or FM2_NoPcode are set: ; - we must NOT replace the existing first module even if it's empty ; - this mrs can never be made the MAIN module ; - it can never have oMrs of 0 ; - this mrs can never have a variable table (or be scanned to ; SS_PARSE or SS_EXECUTE) ;Exit: ; if no error ; AX = 0 ; grs.oMrsCur = new module's oMrs ; grs.oPrsCur = UNDEFINED ; all fields in mrsCur are setup ; all fields in txdCur are setup ; rsNew = module's oMrs (tell's user interface to show list window) ; else ; caller can count on the input mrsCur being still active ; if out of memory error, AX = ER_OM ; if a matching module is found, AX = ER_DD and [oRsDupErr] = ; oRs of existing module with same name. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc MrsMake,<PUBLIC,FAR,NODATA>,<SI,DI> parmW ogNam parmW flags localB fUsingUnNamed_Mrs localB fGrewRsTable cBegin MrsMake mov word ptr [fGrewRsTable],FALSE ; initialize both ; fUsingUnNamed_Mrs and ; fGrewRsTable with one mov mov di,[grs.GRS_oMrsCur] ; save grs.oMrsCur cmp [ogNam],OGNAM_GMRS ; making global mrs? DJMP jz Make_gMrs ; brif so - special case call AlphaORsFree ;release table of sorted oRs's cCall MrsDeActivate ;save existing mrs, empty mrsCur mov al,PT_NOT_PROC ;signal to search tMrs, not tPrs cCall RsTableSearch,<ogNam> ; returns oMrs if entry ; found, or mov dx,UNDEFINED cmp ax,dx ; UNDEFINED if not found ; also puts oHole in bx jnz Make_Mrs_DD_ER ;brif entry was found inc dx ;now dx == 0 .errnz OGNAM_UNNAMED - 0 mov cx,[ogNam] cmp cx,dx ; making an unnamed mrs? jz Make_Unnamed_Mrs ; brif so cmp cx,OGNAM_PSEUDO_MAX ; some other special ogNam? jbe Make_Mrs ; brif so DbChk ogNam,ogNam test byte ptr ([flags+1]),FM2_NoPcode OR FM2_Include ;is this mrs for a text object? jnz Make_Mrs ; brif so; keep unnamed mrs call EmptyMrs ;see if there's an empty ; unnamed mrs jcxz Make_Mrs ; brif there isn't one jmp short Use_Empty_Mrs Make_Mrs_DD_ER: mov [oRsDupErr],ax ;tell caller oRs of conflict mov ax,ER_DD jmp MrsMake_Err_Exit1 ;reactivate input mrsCur & exit Use_Empty_Mrs: mov si,SIZE MRS + OMRS_GLOBAL ; oMrs for unnamed entry push si ;parm to MrsActivateCP call MrsActivateCP or [conFlags],F_CON_LeaveTMrsEmpty ;so MrsDiscard won't create a ; new module after discarding! cCall MrsDiscard ;discard empty unnamed mrs and [conFlags],NOT F_CON_LeaveTMrsEmpty ;reset to default mov [fUsingUnNamed_Mrs],TRUE ;in case of later OM error mov ax,si ;oMrs to unlink from free list call UnlinkFreeMrs ;unlink the entry from the ; free list, (MrsDiscard ; linked it in) jmp SHORT Init_New_Mrs1 Make_Text_Mrs: or bx,bx jnz Make_Mrs dec bx ;if making a text mrs, CANNOT ; allow it to go in @ offset 0 jmp short Make_Mrs Make_Unnamed_Mrs: mov ax,SIZE MRS + OMRS_GLOBAL ;offset that empty unnamed mrs ; MUST go at (parm to UnlinkFree Mrs) mov si,ax call UnlinkFreeMrs ;unlink the entry from the mov bx,si ; offset that empty unnamed ; mrs MUST go at cmp bx,[grs.GRS_bdRs.BD_cbLogical] ;is the table empty? jz Make_Mrs_Grow Init_New_Mrs1: jmp short Init_New_Mrs Make_gMrs: mov si,OMRS_GLOBAL ; new oMrs PUSHI ax,<dataOFFSET grs.GRS_bdRs> PUSHI ax,<SIZE MRS + OMRS_GLOBAL> call BdGrow jmp short Make_Mrs_Grow_1 Make_Mrs: mov si,bx ;save hole location cmp si,UNDEFINED ;is there a hole in table? jz Make_Mrs_Grow ; brif not DbAssertRel bx,z,oFreeMrsFirst,CP,<MrsMake: given hole not first free> RS_BASE add,bx mov bx,PTRRS[bx.MRS_oMrsNext] mov [oFreeMrsFirst],bx ;free entry now unlinked from ; free mrs chain GETRS_SEG es,bx,<SIZE,LOAD> jmp short Init_New_Mrs Make_Mrs_Grow: mov si,[grs.GRS_bdRs.BD_cbLogical] ;new oMrs or si,si ; Rs table > 32k? js J_MrsMake_OM_Err ; brif so ... give OM error PUSHI ax,<dataOFFSET grs.GRS_bdRs> PUSHI ax,<SIZE MRS> call BdGrow Make_Mrs_Grow_1: or ax,ax jnz @F ; brif successful J_MrsMake_OM_Err: jmp MrsMake_OM_Err @@: mov [fGrewRsTable],TRUE ; remember we grew in case ; later error Init_New_Mrs: mov ax,dataOFFSET mrsCur mov bx,SIZE MRS mov cx,MRS_CB_ZERO_INIT call InitStruct mov [mrsCur.MRS_cbFrameVars],-FR_FirstVar ; ; reset to init. value. This ; value is 2 to account for ; the fact that b$curframe ; is always pushed on the ; stack after bp, so we ; treat this word as a frame ; var for ref'ing the real ; frame vars off of bp mov ax,[flags] mov [mrsCur.MRS_flags],al mov [mrsCur.MRS_flags2],ah mov ax,si call SetMrsAx ;grs.oMrsCur = oRsCur = ax GETRS_SEG es,bx,<SIZE,LOAD> mov bx,si ;oMrsNew RS_BASE add,bx ;add base of tRs to bx mov PTRRS[bx.MRS_ogNam],UNDEFINED ;mark entry as inactive, since ; mrsCur has actual mrs mov PTRRS[bx.MRS_oMrsNext],UNDEFINED ;in case someone tries to walk ; the mrs chain before this ; mrs gets deactivated cCall TxtCurInit ;init txdCur jnz no_error jmp MrsMake_TxtInit_Err no_error: test byte ptr ([flags+1]),FM2_NoPcode; is a document mrs? jz MakeVarTables ; brif not, create tables call NewBuf ; allocate document buffer mov WORD PTR [mrsCur.MRS_pDocumentBuf],ax ; set ptr to buffer or ax,ax ; was it successful? mov al,ER_OM ; assume not, set error jz MrsMake_OM_2_Err ; brif out of memory jmp SHORT MrsMake_Name ; finish creating txt tbl MakeVarTables: cCall MakeMrsTVar ; set up module var table or ax,ax jz MrsMake_OM_2_Err mov ax,SbGNam ; assume global mrs cmp [ogNam],OGNAM_GMRS ; making global mrs? jz MrsMake_TNam ; brif so sub ax,ax ; don't use special sb MrsMake_TNam: cCall TNamInit,<ax> ; set up module name table or ax,ax jz MrsMake_OM_3_Err MrsMake_Name: mov ax,[ogNam] mov [mrsCur.MRS_ogNam],ax ; set module name mov [mrsCur.MRS_oMrsNext],UNDEFINED .errnz 1 - OGNAM_GMRS dec ax ; is this the global module? jz MrsMake_Exit ; brif so - exit (this ; mrs doesn't have to be ; linked, as it's known ; to be at offset 0) ;After this point, no errors can occur, so its ok to tell ;user interface the oRs of the new module xchg ax,dx mov ax,[grs.GRS_oMrsCur] mov [rsNew],ax ;tell user interface to ; show new mrs in list window Link_Mrs: ;Now, link this module into mrs chain GETRS_SEG es,bx,<SIZE,LOAD> mov bx,OMRS_GLOBAL ;start with global mrs MrsLink_Loop: RS_BASE add,bx mov dx,PTRRS[bx.MRS_oMrsNext] inc dx .errnz UNDEFINED - 0FFFFH jz GotChainEnd ;brif bx points to last current ; entry in the mrs chain dec dx mov bx,dx jmp MrsLink_Loop GotChainEnd: mov PTRRS[bx.MRS_oMrsNext],ax ;link new entry at end of chain ;Note that the oMrsNext field in the new entry will automatically be ;UNDEFINED in the new entry, and we set it to UNDEFINED earlier in ;this routine xor ax,ax test byte ptr ([flags+1]),FM2_NoPcode OR FM2_Include ;is this mrs for a text or ; INCLUDE object? jnz Main_Set2 ; brif so - IT can't be MAIN dec ax .errnz UNDEFINED - 0FFFFh cmp [grs.GRS_oMrsMain],ax ;is there already a MAIN module? jz Main_Set0 ; brif not call MainModified ;mark main module as modified ; if current mrs is pcode ; mrs (so we will be sure ; to save updated xxx.MAK) jmp SHORT Main_Set1 Main_Set0: mov dx,[grs.GRS_oMrsCur] mov [grs.GRS_oMrsMain],dx ;this mrs gets set as MAIN Main_Set1: inc ax ;inc ax back to 0 Main_Set2: .errnz FALSE MrsMake_Exit: cEnd MrsMake MrsMake_OM_3_Err: mov bx,dataOFFSET mrsCur.MRS_bdVar cCall BdFree,<bx> mov bx,dataOFFSET mrsCur.MRS_bdlNam cCall BdlFree,<bx> MrsMake_OM_2_Err: call TxtDiscard MrsMake_TxtInit_Err: cmp [fGrewRsTable],FALSE ; did we grow Rs table? jz @F ; brif not sub [grs.GRS_bdRs.BD_cbLogical],SIZE MRS @@: MrsMake_OM_Err: ;Tried to grow the Rs table but failed call SetMrsUndef ;grs.oMrsCur=oRsCur=UNDEFINED cmp [fUsingUnNamed_Mrs],FALSE ;special case where we tried ; to reuse unnamed mrs? jz Not_Unnamed ; brif not cmp di,SIZE MRS + OMRS_GLOBAL ; was the unnamed one the ; active one on entry? jnz Not_Unnamed ; brif not ;can't reactivate the one that was active on input, as we've ; tried to reuse that one but failed. For this special case, we ; must recurse to restore the unnamed empty mrs call far ptr MakeInitMrs ;remake empty unnamed mrs ; (certain it won't run out ; of memory here ...) DbAssertRel ax,z,0,CP,<MrsMake: MakeInitMrs returned an error code> DbAssertRel di,z,grs.GRS_oMrsCur,CP,<MrsMake: di not equal to oMrsCur> Not_Unnamed: mov ax,ER_OM MrsMake_Err_Exit1: push ax ;save error code push di ;input oMrsCur call MrsActivateCP ;re-activate original mrs pop ax ;restore error code for retval jmp MrsMake_Exit ;*** ; MakeInitMrs ; Purpose: ; Make an unnamed module mrs. ; Entry: ; none ; Exit: ; ax = error code ; ;******************************************************************************* cProc MakeInitMrs,<FAR,NODATA> cBegin MakeInitMrs xor ax,ax ; set to OGNAM_UNNAMED .errnz OGNAM_UNNAMED - 0 push ax ;make untitled module PUSHI ax,<100h * FM2_File> ;initial flags for module mrs call MrsMake ;make initial (untitled) mrs cEnd MakeInitMrs ;*** ; MainModified ; Purpose: ; Mark main module as modified if current mrs is pcode mrs. ; This is done so we will be sure to save updated xxx.MAK) ; Preserves: ; ax (caller's assume this) ; es is either preserved, or explicitly set to seg of tRs ; ;******************************************************************************* PUBLIC MainModified ;for debugging only MainModified PROC NEAR DbAssertRel [grs.GRS_oMrsMain],ne,[grs.GRS_oMrsCur],CP,<MainModified: err1> mov bx,[grs.GRS_oMrsMain] inc bx ;test for UNDEFINED jz MmExit ;brif no main module ; (can happen when we're terminating ; and main module discarded before ; command window's mrs) test [mrsCur.MRS_flags2],FM2_NoPcode OR FM2_Include jnz MmExit ;brif current mrs is not a pcode mrs dec bx RS_BASE add,bx ;bx now points to main mrs ; (we know mrs oMrsMain is in table, ; i.e. not in mrsCur struct) or BPTRRS[bx.MRS_flags2],FM2_Modified GETRS_SEG es,bx,<SIZE,LOAD> MmExit: ret MainModified ENDP ;*** ;MrsDeActivate() ; ;Purpose: ; Save the current module's register set (mrsCur) back into the tRs ; entry. This includes a call to TxtDeActivate prior to actually ; deactivating the mrs, as well as deactivating the current procedure ; (via PrsDeActivate). ; ; NOTE: This routine is guaranteed to cause no heap movement. ; ;Entry: ; grs.oMrsCur = current module to be deactivated ; UNDEFINED if there is no current module ;Exit: ; grs.oMrsCur = UNDEFINED ; grs.oPrsCur = UNDEFINED ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc MrsDeActivate,<PUBLIC,NEAR,NODATA>,<SI> cBegin MrsDeActivate cmp [grs.GRS_oMrsCur],UNDEFINED ;is there an active mrs? jz MrsDeAct_Exit ;just return if not DbHeapMoveOff ;assert no heap movement here DbChk ConStatStructs cCall PrsDeActivate ;deactivate current prs, if any cCall TxtDeActivate ;deactivate current txd, if any mov bx,[grs.GRS_oMrsCur] RS_BASE add,bx GETRS_SEG es,si,<SIZE,LOAD> ; es set to mrs dst. seg mov si,dataOFFSET mrsCur ;now ds:si == mrs src. address call MoveTheMrs ; move mrsCur into tRs call SetMrsUndef ;grs.oMrsCur=oRsCur=UNDEFINED DbHeapMoveOn MrsDeAct_Exit: cEnd MrsDeActivate ;*** ;MrsActivate(oMrsNew) ; ;Purpose: ; Make the module indicated by oMrsNew the current active module. The ; current module's register set (if any) will be saved via MrsDeActivate, ; and TxtActivate will be called at the end. ; ; NOTE: This routine is guaranteed to cause no heap movement. ; ;Entry: ; 'oMrsNew' is an offset into the tRs for module to be made current. ; Note that if oMrsNew is UNDEFINED or if the entry at offset oMrsNew is ; a discarded entry, the current mrs (if any) will be ; deactivated, and no new mrs will be activated. ;Exit: ; grs.oMrsCur = oMrsNew ; grs.oPrsCur = UNDEFINED ; if oMrsNew != UNDEFINED, ; all fields in mrsCur are setup ; all fields in txdCur are setup ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc MrsActivate,<PUBLIC,FAR,NODATA> parmW oMrsNew cBegin MrsActivate cCall MrsActivateCP,<oMrsNew> cEnd MrsActivate cProc MrsActivateCP,<PUBLIC,NEAR,NODATA>,<SI> parmW oMrsNew cBegin MrsActivateCP DbHeapMoveOff ;assert no heap movement here call PrsDeActivate mov ax,[oMrsNew] cmp ax,[grs.GRS_oMrsCur] jz MrsActivate_Exit push ax ;save oMrsNew cCall MrsDeActivate ;deactivate current mrs, if any pop ax ;ax = oMrsNew inc ax ;test for UNDEFINED jz MrsActivate_Exit ;brif no mrs is to be activated dec ax ;restore ax = oMrsNew DbChk oMrs,ax ;ife RELEASE - ensure validity xchg ax,si ;si = oMrs to activate RS_BASE add,si ;si = pMrs to activate GETRS_SEG ds,bx,<SIZE,LOAD> ; ds set to mrs src. seg assumes DS,NOTHING mov bx,dataOFFSET mrsCur ;bx == mrs dest. address SETSEG_EQ_SS es ;es:bx = mrs dest. address call MoveTheMrs ; move mrsCur into tRs SETSEG_EQ_SS ds ;restore ds = ss assumes DS,DATA mov ax,[oMrsNew] ;note new oMrsCur call SetMrsAx ;grs.oMrsCur = oRsCur = ax cCall TxtActivate ;activate txdCur from this mrs MrsActivate_Exit: DbHeapMoveOn cEnd MrsActivate ;*** ;EmptyMrs ;Purpose: ; This boolean function is used to determine whether there is an ; empty unnamed module. ; [52] NOTE: more than one caller of this routine assumes that if ; [52] there IS an empty unnamed mrs, then there is no other ; [52] (pcode) mrs loaded. ;Entry: ; none. ;Exit: ; CX = 0 if there is not an empty unnamed module ; else CX is the offset in the Rs table to the empty unnamed module ;Uses: ; none. ;Preserves: ; BX ;Exceptions: ; none. ;******************************************************************************* PUBLIC EmptyMrs EmptyMrs PROC NEAR push bx ;--------------------------------------------------------------------- ;NOTE: an inherent assumption is that, if there exists an unnamed mrs, ; it will be at offset SIZE MRS + OMRS_GLOBAL in the table (the ; global mrs is at offset OMRSGLOBAL in the table). The user ; cannot create an unnamed mrs, so this seems a safe assumption. ;--------------------------------------------------------------------- mov cx,SIZE MRS + OMRS_GLOBAL ;[60] mov bx,OFFSET DGROUP:mrsCur ;assume this is the current module mov ax,[txdCur.TXD_bdlText_cbLogical] SETSEG_EQ_SS es ;seg of mrsCur is always same as ss cmp [grs.GRS_oMrsCur],cx ;is this the current module? jz EmptyMrs_Cont ; brif so GETRS_SEG es,bx,<SIZE,LOAD> mov bx,cx ;bx = oMrs RS_BASE add,bx ;bx = pMrs mov ax,PTRRS[bx.MRS_txd.TXD_bdlText_cbLogical] EmptyMrs_Cont: cmp PTRRS[bx.MRS_ogNam],OGNAM_UNNAMED ;[10] is MAIN mrs unnamed? jnz EmptyMrs_FalseExit ; brif not cmp ax,CB_EMPTY_TEXT ;is it's text table empty? ja EmptyMrs_FalseExit ; brif not ;This block checks to see if module has any procedures mov ax,UNDEFINED mov bx,cx ;bx == oMrs of interest for call below DbAssertRel grs.GRS_oPrsCur,z,UNDEFINED,CP,<EmptyMrs: prsCur active> call GetNextPrsInMrs ;ax = oPrs of 1st prs in module js EmptyMrs_Exit ; brif module contains no prs's EmptyMrs_FalseExit: xor cx,cx ; indicate no empty unnamed mrs EmptyMrs_Exit: pop bx ret EmptyMrs ENDP ;############################################################################## ;# # ;# Procedure related Context Manager Functions # ;# # ;############################################################################## ;------------------------------------------------------------------------------ ; ; Prs Transition States ; ; Due to the user interface, prs handling is more complicated than mrs ; handling. For a Module Register Set, there are just 2 states: no mrs, or ; an mrs, with two arcs connecting the states: MrsMake, and MrsDiscard. ; ; Procedure Register Sets have the following states and transitions: ; ; S0 - No prs entry ; S1 - SUB has been referenced, but not declared or defined ; This only applies to SUBs, not FUNCTIONS or DEFFNs. ; (i.e. FUNCTIONS and DEF FNs never enter this state) ; If a prs entry is still in this state at runtime, ; We bind to a compiled SUB on first execution. ; S2 - procedure has no text tbl, has been DECLAREd but not defined. ; If a prs entry is still in this state at runtime, ; We bind to a compiled SUB/FUNCTION on first execution. ; The procedure may or may not have declarations. ; (DEF FNs never enter this state) ; S3 - procedure text tbl & window allocated, but no definition. ; The procedure may or may not have declarations. ; (DEF FNs never enter this state) ; S4 - procedure has a definition (i.e. SUB/FUNCTION/DEF FN stmt) ; ; These states can be uniquely determined by these fields in the prs structure: ; (But note: txd.bdlText.status should only be tested while the ; prs is not active, i.e., in the tPrs. To see if prsCur has ; a text table, test txdCur.TXD_flags - - if FTX_mrs is set, ; prsCur has no text table) ; S0: bdName.pb == NULL ; S1: bdName.pb != NULL, txd.bdlText.status == NOT_OWNER, ; FP_DECLARED and FP_DEFINED are NOT set, ; (mrs,prs,otx refer to the CALL reference) ; S2: bdName.pb != NULL, txd.bdlText.status == NOT_OWNER ; FP_DECLARED IS set, FP_DEFINED is NOT set, ; (mrs,prs,otx refer to DECLARE stmt's pcode), ; S3: bdName.pb != NULL, txd.bdlText.status != NOT_OWNER, ; FP_DEFINED is NOT set, ; S4: bdName.pb != NULL, txd.bdlText.status != NOT_OWNER for SUB/FUNC ; but is UNDEFINED for DEF FNs, FP_DEFINED is set, The setting of ; FP_DECLARED is not important in this state. ; (mrs,prs,otx refer to SUB/FUNCTION/ DEF FN statement's pcode) ; ; With these states defined, and arcs connecting them being functions ; defined below, the following table shows how the arcs connect the states: ; In this table, PrsDefine refers to when PrsDefine is called with fNotDefine=0, ; i.e. for a SUB/FUNCTION/DEF FN statement. ; PrsDeclare refers to when PrsDefine is called with fNotDefine != 0, ; i.e. for a DECLARE SUB/FUNCTION/DEF FN statement. ; ; Initial State Arc Final State ; ------------- --- ----------- ; S0 PrsRef(FUNC/DEF)S0 ; S0 PrsRef(SUB) S1 ; S0 PrsDeclare S2 ; S0 PrsMake S3 ; S0 PrsDefine S4 ; ; S1 <txt mgr sees defining reference deleted and: ; finds another SUB reference -> S1 ; finds no other references -> PrsFree -> S0 ; S1 PrsRef(SUB) S1 ; S1 PrsDeclare S2 ; S1 PrsMake S3 ; S1 PrsDefine S4 ; ; S2 <txt mgr sees defining DECLARE stmt deleted and: ; finds another DECLARE -> S2 ; finds another SUB reference -> S1 ; finds no other declares or references -> PrsFree -> S0 ; S2 PrsRef S2 ; S2 PrsDeclare S2 ; S2 PrsMake S3 ; S2 PrsDefine S4 ; ; S3 PrsRef S3 ; S3 PrsMake S3 ; S3 PrsDeclare S3 ; S3 PrsDefine S4 ; S3 <txt mgr sees text table and window removed and: ; finds a SUB reference -> S1 ; finds no SUB reference -> PrsFree -> S0 ; ; S4 PrsRef S4 ; S4 PrsMake S4 ; S4 PrsDeclare S4 ; S4 <txt mgr sees defining SUB/FUNC/DEF stmt deleted and: ; finds text table and window still active -> S3 ; finds a DECLARE -> S2 ; finds a SUB reference -> S1 ; finds no declares or references -> PrsFree -> S0 ; ; ; Note that PrsDiscard cannot directly eliminate the Prs Entry if there ; are references to the prs in other text tables. It can only ; eliminate the text table associated with the entry by calling TxdDiscard, ; which will cause the text manager to see the definition be deleted. ; If the text manager is unable to find a DECLARE to replace as the new ; definition of the prs, the text manager calls PrsFree to completely ; eliminate the Prs entry. ; ; The above table describes a state-transition diagram, which was not ; attempted in this source file due to the number of transitions. ;------------------------------------------------------------------------------ ;*** ;PrsRef(oNam,procType,oTyp) ; ;Purpose: ; This function searches for a procedure in the tRs by the name oNam. ; If a match is found to a prs entry, the oPrs is returned, otherwise, ; UNDEFINED. ; This function will not normally affect prsCur; if, however, procType ; is PT_SUB and the entry does not already exist, instead of returning ; UNDEFINED, it will create the entry and return the oPrs. ; ; The procType field is primarily used to indicate whether the procedure ; is a DEF FN or not; if not, then the oTyp input is not used. If it ; is a DEF FN, however, the search logic is different - - - rather than ; just matching on the name, the search algorithm must match on the oTyp ; and oMrs as well. ; ; This routine is called by the parser when a procedure reference is seen, ; and probably by the scanner when it sees a function entry in a variable ; table. ; ;Entry: ; oNam is an offset into current module's name table for proc name ; procType is either PT_SUB, PT_FUNCTION, or PT_DEFFN. ; oTyp is only valid if procType == PT_DEFFN, in which case it is ; the oTyp of the DEF; otherwise, this input is undefined. ;Exit: ; AX == oPrs if found, UNDEFINED otherwise. ; In the event that the input procType is PT_SUB and no matching prs ; is found, the prs will be created; if an error occurs in ; creating the prs, the same standard error code will be returned, ; (as is returned by PrsDefine) OR'd with 0x8000. If no error ; occurs, the oPrs of the new prs will be returned. ; In all cases, prsCur will be the same on exit as on entry. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc PrsRef,<PUBLIC,NEAR,NODATA>,<SI> parmW oNam parmB procType parmB oTyp cBegin PrsRef DbChk oNam,oNam ;sanity check on input oNam mov si,[grs.GRS_oPrsCur] ;save for later restoring cCall PrsDeActivate ;must deactivate for search cCall OgNamOfONam,<oNam> ; given oNam, fetch ogNam xchg ax,cx ; cx = ogNam or 0 mov ax,08000H OR ER_OM ;[10] in case of OM err ret jcxz PrsRef_Exit ;[10] brif OM error mov al,[procType] ;tell RsTableSearch to use tPrs mov dl,[oTyp] cCall RsTableSearch,<cx> ; search tRs for entry cmp ax,UNDEFINED jnz PrsRef_Exit ;brif found PrsRef_No_Match: cmp [procType],PT_SUB ;looking for a SUB? jnz PrsRef_Exit ; brif not - exit ;special case; reference to a SUB which was not found. Create the ; entry, return the oPrs or error code push [oNam] push Word Ptr [procType] push ax ;push garbage for oTyp parm mov al,1 push ax ;push a non-zero word (true) call far ptr PrsDefine ; create the entry PrsRef_Err_Check: or ah,080h ;set high bit in case of error cmp ax,08000h ;FALSE return if no error jnz PrsRef_Exit ; brif error; pass code back mov ax,[grs.GRS_oPrsCur] ;retval PrsRef_Exit: push ax ;save retval push si ;parm to PrsActivateCP call PrsActivateCP ;reactivate original prs pop ax ;retval cEnd PrsRef ;*** ;PrsMake(ogNam, procType) ; ;Purpose: ; This function searches for a procedure by the name ogNam. ; If found, it gives an ER_DD if the found procedure has ; a text table; otherwise, it just activates the found procedure and gives ; it a text table. If a new entry is created, it calls the TextMgr ; routine TxtCurInit() to initialize the text table, ; and calls the Variable Manager's MakePrsTVar(). ;Entry: ; ogNam for the proc name ; procType - PT_SUB or PT_FUNCTION (should never get PT_DEFFN here) ;Exit: ; AX == FALSE if no error, ER_OM if out of memory, MSG_IdTooLong ; if the input name is too long, and ER_DD if a matching ; entry is found that already has a text table, or if a ; match is found to a compiled module name. ; if ER_DD, [oRsDupErr] = oRs of existing proc with same name. ; Note that is an error code is returned, there will be no active prs ; grs.oMrsCur = procedure's oMrs (unchanged if new proc) ; grs.oPrsCur = procedure's oPrs ; all fields in prsCur are setup if we're making an existing prs active ; if we're creating a new prs, then prsCur will have the correct ; ogNam, oVarHash, oMrs, and oPrs fields; other fields must be ; set up by caller as appropriate. ; all fields in txdCur are setup ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc PrsMake,<PUBLIC,FAR,NODATA>,<SI> parmW ogNam parmB procType LocalW oPrsSave LocalW oMrsSave LocalW searchResult cBegin PrsMake mov ax,[grs.GRS_oPrsCur] mov [oPrsSave],ax ;save original oPrs mov ax,[grs.GRS_oMrsCur] mov [oMrsSave],ax ;save original oMrs cCall PrsDeActivate mov si,[ogNam] cCall ONamOfOgNam,<si> ; given ogNam, fetch oNam jnz PrsMake_Cont ; Catch possible OM error ; now, so later callers of FieldsOfPrs ; don't have to consider it. jmp PrsMake_ER_OM1 ;brif ONamOfOgNam returned Out of Memory PrsMake_Cont: ;--------------------------------------------------------------------- cmp [procType],PT_SUB jnz PrsMake_Namespace_OK ;brif not a SUB - leave name space alone push ax ;save oNam across call mov dl,NMSP_Sub cCall SetONamSpace,<ax,dx> ;set namespace bit to remember that this ; is a procedure name pop ax jnz PrsMake_ER_DD_1 ;brif namespace conflict PrsMake_Namespace_OK: cCall GetVarNamChar,<ax> ;ah non-zero if name starts with FN or ah,ah jz No_FN_Name_Error cmp [procType],PT_DEFFN jz No_FN_Name_Error mov ax,MSG_FNstart ;"Can't start with 'FN'" jmp PrsMake_ER_Exit No_FN_Name_Error: DbAssertRelB procType,nz,PT_DEFFN,CP,<PrsMake got called with PT_DEFFN> mov al,[procType] cCall RsTableSearch,<ogNam> ; if err code in CX on retn, ignore mov [searchResult],ax ;save in case of OM error inc ax ;matching entry found? .errnz UNDEFINED - 0FFFFh jz No_Match_Found ; brif not dec ax ;restore search result push ax ;parm to PrsActivate call PrsActivateCP ;activate this oPrs test [txdCur.TXD_flags],FTX_mrs jnz PrsMake_EnsureTxd ;no error ;txdCur is for found prs - - error PrsMake_ER_DD_1: jmp short PrsMake_ER_DD No_Match_Found: call MakeNewPrs ;make a new entry in prsCur jz PrsMake_ER_OM ; brif so mov [prsCur.PRS_ogNam],si ; set ogNam in new entry to input PrsMake_EnsureTxd: mov al,[procType] ;if we found a match on a FUNCTION or a mov [prsCur.PRS_procType],al; DEF FN, FORCE it's proctype to the cCall EnsurePrsTVar ;ax = prs's oVarHash jz PrsMake_ER_OM call AlphaORsFree ;release table of sorted oRs's cCall TxtDeActivate ;save the txd for mrsCur ; table. leave txdCur as mrs ;This assignment is necessary for case where prs ref preceded prs ;definition. When prs was created for reference, prs's oMrs field ;was set to mrs with reference. Now that definition is here, the ;oMrs field must be set to the mrs which 'owns' the prs. mov ax,[oMrsSave] ;ax = caller's oMrs mov [prsCur.PRS_oMrs],ax ; ; At this point mrsCur may not be the same as prsCur.PRS_oMrs, so let's ; ensure that it is. ; cmp [grs.GRS_oMrsCur], ax je @F ;[477 push [grs.GRS_oPrsCur] ; For PrsActivate call PrsDeactivate call far ptr PrsActivate @@: cCall TxtCurInit ;init txdCur for this new prs jz PrsMake_ER_OM_Txd .errnz FALSE xor ax,ax ;return FALSE PrsMake_Exit: cEnd PrsMake PrsMake_ER_DD: mov ax,[grs.GRS_oRsCur] mov [oRsDupErr],ax ;tell caller oRs of conflict mov ax,ER_DD jmp short PrsMake_ER_Exit PrsMake_ER_OM_Txd: call TxtActivate ;reactivate txd for mrsCur call PrsDeActivate ; Set oPrsCur to UNDEFINED, ;so TxtActivate will activate txd for ;mrsCur, not this aborted prs ; Also, in case prsCur on entry was ; the given prs, must deactivate it ; here so shared code below will ; succeed in activating oPrsSave PrsMake_ER_OM: mov ax,[searchResult] inc ax .errnz UNDEFINED - 0FFFFh jnz PrsMake_ER_OM1 ;brif we did not create this prs ;O.K. - we created it, so we must remove it from the prs table mov ax,dataOFFSET prsCur push ax add ax,SIZE PRS dec ax ;pointer to last byte in range to free push ax call B$ClearRange ;free any owners in prsCur call SetPrsUndef ;grs.oPrsCur=UNDEFINED, oRsCur=oMrsCur PrsMake_ER_OM1: mov ax,ER_OM PrsMake_ER_Exit: push ax push oPrsSave ;parm to PrsActivate call PrsActivateCP ;reactivate prsCur pop ax jmp short PrsMake_Exit ;*** ;MakeNewPrs ; ;Purpose: ; Common code to PrsDefine and PrsMake. Sets up prsCur as a new prs. ;Entry: ; bx = offset to hole in prs table, or UNDEFINED if there is no hole ; This function assumes that no prs is active (i.e. txdCur reflects ; the module's text table) ;Exit: ; PSW.Z set if out-of-memory ; grs.oPrsCur is set, meaning prsCur now contains valid info ;Uses: ; none. ;Exceptions: ; none. ;**** MakeNewPrs PROC NEAR push di inc bx ;was there a hole in the table? .errnz UNDEFINED - 0FFFFh jz Prs_GrowTbl ;brif not ;Unlink the hole from the free list GETRS_SEG es,di,<SIZE,LOAD> dec bx mov di,bx ;put oHole in di DbAssertRel bx,z,oFreePrsFirst,CP,<MakeNewPrs: hole not 1st in free list> RS_BASE add,bx mov ax,PTRRS[bx.PRS_oPrsNext] mov [oFreePrsFirst],ax ;free entry now unlinked jmp short PRS_Hole_Found Prs_GrowTbl: sub ax,ax mov di,[grs.GRS_bdRs.BD_cbLogical] ;offset to new prs in table or di,di ; Rs table > 32k? js @F ; brif so - OM error PUSHI ax,<dataOFFSET grs.GRS_bdRs> PUSHI ax,<SIZE PRS> call BdGrow @@: or ax,ax jz MakeNewPrs_Ret PRS_Hole_Found: mov ax,di ;new entry put in hole location call SetPrsAx ;grs.oPrsCur = ax ;grs.oRsCur = 8000h + ax GETRS_SEG es,bx,<SIZE,LOAD> mov bx,di ;bx = offset to prs in table RS_BASE add,bx ;bx = pointer to prs in table mov PTRRS[bx.PRS_ogNam],UNDEFINED ; mark tbl entry as inactve, ; since prs is in prsCur ;Now, link this new prs entry into the prs chain mov PTRRS[bx.PRS_oPrsNext],UNDEFINED ; terminate chain mov dx,bx ; save pPrsNew mov ax,[oPrsFirst] inc ax ; is this the first prs? jnz LastPrs_Loop ; brif not mov [oPrsFirst],di ; point to new entry jmp short After_Link ; link complete - continue LastPrs_Loop: dec ax ; bx == oPrs xchg ax,bx ; advance to next prs RS_BASE add,bx ; bx = ptr to prs in table mov ax,PTRRS[bx.PRS_oPrsNext] ; fetch pointer to next prs inc ax ; no more prs's? jz @F ; brif so jmp short LastPrs_Loop ; loop until end of chain @@: mov PTRRS[bx.PRS_oPrsNext],di ; link new prs in @ end After_Link: mov ax,dataOFFSET prsCur ;initialize prsCur, filling it mov bx,SIZE PRS ; with UNDEFINED, and zeroes mov cx,PRS_CB_ZERO_INIT ; as appropriate call InitStruct ; note that this sets ; the PRS_oPrsNext field to ; UNDEFINED mov [prsCur.PRS_cbFrameVars],-FR_FirstVar ; ; reset to init. value. This ; value is 2 to account for ; the fact that b$curframe ; is always pushed on the ; stack after bp, so we ; treat this word as a frame ; var for ref'ing the real ; frame vars off of bp mov ax,[grs.GRS_oMrsCur] ;set oMrs field mov [prsCur.PRS_oMrs],ax mov [fCouldBeBogusPrs],TRUE ;note that there's now a chance ; of an unref'd prs or sp,sp ;normal return - reset PSW.Z MakeNewPrs_Ret: pop di ;restore caller's di ret MakeNewPrs ENDP ;*** ;EnsurePrsTVar ;Purpose: ; Create a local variable table (i.e. allocate oVarHash in ; module's variable table for local variables) iff: ; (1) prs doesn't already have one AND ; (2) prs's scan state != SS_RUDE ;Entry: ; none ;Exit: ; If didn't need to make local variable table, because prs already ; had one, or procedure's scan state == SS_RUDE, ax = UNDEFINED ; Else if out-of-memory, ; ax = 0 ; Else ; ax = prs's newly created oVarHash ; PSW is set based on value in ax ;Exceptions: ; none ; ;******************************************************************************* EnsurePrsTVar PROC NEAR mov ax,UNDEFINED cmp [txdCur.TXD_scanState],SS_RUDE ;test table's scan state jae NoTVar ; don't make hash table if there ; is no variable table cmp [prsCur.PRS_oVarHash],ax jnz NoTVar ;brif prs already has oVarHash cCall MakePrsTVar ;ax = prs's oVarHash, (0 if no memory) NoTVar: or ax,ax ;set PSW for caller ret EnsurePrsTVar ENDP ;*** ;PrsDefine(oNam, procType, oTyp, fNotDefine) ; ;Purpose: ; Declare or Define a procedure. grs.oPrsCur will be UNDEFINED if we ; must first create a new prs entry, or prsCur will be set up to the ; appropriate prs entry otherwise; in this latter case, caller ; wants to rename an existing prs so, we'll create ; a new prs for the input name if different from the name of prsCur, ; leaving the existing prs (without a text table) in case there are ; references (oPrs's) to it. ; ; This routine is only called when an actual procedure definition ; is found or when a declaration of a procedure is found. ; ;Entry: ; oNam - offset into the name table for mrsCur to the proc name. ; procType - PT_SUB, PT_FUNCTION, or PT_DEFFN. ; oTyp - only defined if procType == PT_DEFFN; used in searching ; the Rs table for a matching DEF. Note that this is ; accepted as a Byte - - we know it must be a predefined ; type, and the oTyp in the PRS is just stored as a byte. ; fNotDefine - non zero if called for DECLARE SUB/FUNCTION ; If a prs by this name already exists, it is activated, ; otherwise, a new one is created with no text table ; allocated to it. ; ;Exit: ; AX == FALSE if no error, ER_OM if out of memory, ER_DD if a matching ; entry belongs in another module, and ER_CN if grs.otxCONT is ; not UNDEFINED (i.e. CONT is possible) and the module variable ; table would have to grow for this to succeed. ; Note that if an error code is returned, there may or may not be a ; current prs. ; if a matching module is found, AX = ER_DD and [oRsDupErr] = ; oRs of existing module with same name. ; grs.oMrsCur will be unchanged. ; grs.oPrsCur = procedure's oPrs ; prsCur will have the correct bdName, procType, fDefined, oTyp, ; oVarHash, oMrs, and oPrs fields; other ; fields must be set up by caller as appropriate. ; all fields in txdCur are setup (will be for mrsCur if PT_DEFFN or ; input fNotDefine is TRUE) ; NOTE: In the special case where we're changing the name of an ; existing prs entry (prsCur on input), we'll create a new ; entry, copy the old one to the new one, but with the new ; name, and mark the old one as having no text table or ; definition. This is because references (oPrs's) may still ; exist to the old prs name. The new entry will be prsCur, set ; up as described above. ; PSW set based on value in ax ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc PrsDefine,<PUBLIC,FAR,NODATA>,<SI,DI> parmW oNam parmB procType parmB oTyp parmB fNotDefine LocalV bdName,%(SIZE BD) LocalW oPrsSave LocalW oMrsSave LocalW SearchResult cBegin PrsDefine DbChk oNam,oNam ;sanity check on input oNam mov ax,[grs.GRS_oPrsCur] mov [oPrsSave],ax ;save original oPrs xchg ax,di ;in case of error exit mov ax,[grs.GRS_oMrsCur] mov [oMrsSave],ax ;save original oMrs cCall PrsDeActivate ;for table search, below cCall OgNamOfONam,<oNam> ; given oNam, fetch ogNam xchg ax,si ; si = ogNam or 0 mov ax,ER_OM jz PrsDefine_Exit1 ;brif OM error return mov bx,[oNam] mov al,NMSP_SUB ;-------------------------------------------------------------------- cmp [procType],PT_SUB jnz PrsDefine_Reset_Namespace ;brif not a SUB - reset SUB ; bit in name entry in case ; we're converting a SUB to ; a FUNCTION cCall SetONamSpace,<bx,ax> jnz JNZ_PrsDefine_DD_1 ;[69]brif namespace already ; set to something else jmp short PrsDefine_Namespace_OK PrsDefine_Reset_Namespace: call ResetONamMask ;reset the NMSP_SUB bit PrsDefine_Namespace_OK: mov ax,ER_CN cmp [grs.GRS_otxCONT],UNDEFINED ;is user able to CONTinue? jnz PrsDefine_Exit1 ; brif so - - - don't want ; to risk moving var tab mov dl,[oTyp] mov al,[procType] ;tell RsTableSearch to use tPrs cmp al,PT_SUB jnz PrsDefine_NotSub ;brif not a sub mov [oTyp],0 ; scanner depends on 0 in ; oTyp field of SUB prs's PrsDefine_NotSub: cCall RsTableSearch,<si> ;search Rs table for entry ;bx=offset to hole if not found mov dx,[oPrsSave] ;for later reference mov [SearchResult],ax ;save in case of OM error inc ax ;was a matching entry found? jz PrsDefine_No_Match ; brif not dec ax jmp SHORT PrsDefine_Match_OK ;brif no match error in search PrsDefine_Exit1: jmp PrsDefine_ER_Exit ;exit with error code PrsDefine_Match_OK: inc dx ;was prsCur active on input? jz Change_Entry ; brif not dec dx cmp ax,dx ;was match made w/ input prsCur? jz Change_Entry ; brif so - change that entry xchg di,ax ;di = oPrsFound. cCall FieldsOfPrs,<di> ;dh = prs flags, GETRS_SEG es,ax,<SIZE,LOAD> ; es:bx = pPrsFound test dh,FP_DEFINED JNZ_PrsDefine_DD_1: jnz PrsDefine_DD_1 ;Error - caller trying to change ; name to prsCur to the name ; of an already existing ; defined prs cmp PTRRS[bx.PRS_txd.TXD_bdlText_status],NOT_OWNER jnz PrsDefine_DD_1 ;Error - found prs has text ; table. mov ax,PTRRS[bx.PRS_oPrsNext] ; save link field so we mov [prsCur.PRS_oPrsNext],ax ; can restore after blk cpy DJMP jmp SHORT PrsDefine_Cont1 ;jmp to copy input prsCur to ; this one - - found prs ; not defined, so we'll just ; copy prsCur to it, and make ; it defined, leaving the ; input current prs around, ; but w/out a text table ; (in case of ref.s to it) PrsDefine_No_Match: cmp dx,UNDEFINED ;was a prs active? jnz Change_Entry_1 ; brif so - change the entry call MakeNewPrs ;make a new entry in prsCur jz PrsDefine_OM_1 ; brif OM error return jmp PrsDefine_Cont Change_Entry_1: xchg ax,dx ;ax = oPrsSave, dx = garbage mov [searchResult],ax ;in case of OM error when ; changing the name Change_Entry: xchg di,ax ;di = oPrsFound push di ;parm to PrsActivate: oPrsFound call PrsActivateCP ;activate entry to change cmp [fNotDefine],FALSE jnz PrsDefine_No_Err ;brif called for DECLARE test [prsCur.PRS_flags],FP_DEFINED jz PrsDefine_No_Err1 ;error - prs [di] was already defined PrsDefine_DD_1: xchg ax,di ;ax = existing duplicate oPrs or ah,80h ;ax = existing duplicate oRs mov [oRsDupErr],ax ;tell caller oRs of conflict mov ax,ER_DD jmp PrsDefine_ER_Exit PrsDefine_No_Err1: test [txdCur.TXD_flags],FTX_Mrs ;does this prs have a text table jnz PrsDefine_No_Err ; brif not cmp [oPrsSave],UNDEFINED ;was a prs active at entry? je PrsDefine_DD_1 ;brif not - must be entering ; a SUB at module level, when ; the SUB line has been deleted, ; or commented out. If we don't ; do this, a Prs could change ; from one Mrs to another ; unexpectedly. PrsDefine_No_Err: cmp [prsCur.PRS_ogNam],si ; change name of current prs ; if it was different jz Names_Match ; brif no change ;changing name of an existing prs. Must create a new prs for the new ; name, and leave the old one around (minus its text table) in ; case there are references to it hanging around (oPrs's) in ; text or variable tables DbAssertRelB [fNotDefine],z,FALSE,CP,<PrsDefine got Change_Entry error> cCall PrsDeActivate mov di,[grs.GRS_bdRs.BD_cbLogical] ;offset to new prs in table mov bx,UNDEFINED ; just grow the table call MakeNewPrs jnz PrsDefine_Cont1 PrsDefine_OM_1: jmp PrsDefine_ER_OM ;di = oPrsNew PrsDefine_Cont1: mov bx,[grs.GRS_bdRs.BD_pb] ;base pointer to prs table mov cx,bx add cx,di ;cx = pPrsNew add bx,[oPrsSave] ;bx = pPrsOld push bx ;save pPrsOld push cx ;save pPrsNew push bx ;pass pPrsOld to CopyBlk push cx ;pass pPrsNew to CopyBlk PUSHI ax,<SIZE PRS> cCall CopyBlk ;copy prs ;After duplicating the entry, we need to initialize a few fields ;in both the old and new prs entries. Note that prs.oVarHash ;is now meaningless in both entries since the only way we could ;be here is after the user has edited the name of a procedure, ;which the text manager guarentees is a Rude Edit (causing ;the module's variable table to be discarded). call SetPrsUndef ; in case MakeNewPrs set mov ax,[oPrsSave] push [prsCur.PRS_oPrsNext] ; preserve across call call UndefPrs ;old prs is no longer defined ;It is up to text mgr ;ChkAllUndefPrs ;function to redefine it if ;any other refs exist GETRS_SEG es,bx,<SIZE,LOAD> ; in case modified by call pop ax ; link field for new entry pop bx ;es:bx = pPrsNew mov PTRRS[bx.PRS_oPrsNext],ax ; so link field is correct mov PTRRS[bx.PRS_ogNam],NULL ; new prs entry has no name xchg ax,bx ; yet hang onto pPrsNew for ; a moment pop bx ;bx = pPrsOld add bx,PRS_txd.TXD_bdlText ;make this a pBdl for old prs add ax,PRS_txd.TXD_bdlText ;make this a pBdl for new prs cCall BdlChgOwner,<bx,ax> call AlphaORsFree ;release table of sorted oRs's push di ;oPrsNew call PrsActivateCP ;reactivate prsCur Names_Match: PrsDefine_Cont: ;If this PRS has the defined bit set, then we have a more powerful ;reference, don't arbitrarily change the proc type. If we did this, ;changing a DECLARE from SUB to FUNCTION for a defined SUB would ;cause us to list the SUB with an END FUNCTION. If we are editting, ;the SUB/FUNCTION definition line, then the txtmgr will have already ;turned off the FP_DEFINED bit for this prs. test [prsCur.PRS_flags],FP_DEFINED ;Is this prs already defined? jnz PrsAlreadyDefined ;brif so mov al,[procType] mov [prsCur.PRS_procType],al PrsAlreadyDefined: cmp [fNotDefine],FALSE jnz PrsDefine_Declare ;brif called for DECLARE/REF mov ax,[oMrsSave] ;ax = caller's oMrs mov [prsCur.PRS_oMrs],ax call EnsurePrsTVar ;make local var table if ; none already jz PrsDefine_TVar_Err PrsDefine_Declare: mov al,[oTyp] and [prsCur.PRS_oType],NOT M_PT_OTYPE or [prsCur.PRS_oType],al mov [prsCur.PRS_ogNam],si ; set name of prs xor ax,ax ; retval PrsDefine_Exit: or ax,ax ;set PSW for caller cEnd PrsDefine ;NOTE: The error handling code is fairly large due to the constraint that, ;NOTE: on any error, the error code is returned, and the context is left just ;NOTE: as it was prior to the call. PrsDefine_TVar_Err: cmp [SearchResult],UNDEFINED ;did prs already exist? jnz PrsDefine_ER_OM_2 ; brif so - leave prs entry PrsDefine_ER_OM: mov ax,dataOFFSET prsCur push ax add ax,SIZE PRS dec ax ;pointer to last byte in range push ax call B$ClearRange ;free any owners in prsCur call SetPrsUndef ;grs.oPrsCur=UNDEFINED, ;oRsCur=oMrsCur PrsDefine_ER_OM_2: mov ax,ER_OM PrsDefine_ER_Exit: push ax push oMrsSave ;parm to MrsActivateCP call MrsActivateCP ;reactivate prsCur push oPrsSave ;parm to PrsActivate call PrsActivateCP ;reactivate prsCur pop ax jmp short PrsDefine_Exit ;*** ;OTypeOfTypeChar ;Purpose: ; Returns the oType associated with the specified type character. ; ; Split from oRsOfHstProc and rewritten in revision [90] ; ;Entry: ; AL - The character. ;Exit: ; AX - otype of the specified type character ; ET_IMP if not a valid type character. ; Z flag is set if ax == ET_IMP. ; ;******************************************************************************* tcEt LABEL BYTE cEt_SD: db '$' cEt_R8: db '#' cEt_R4: db '!' cEt_I4: db '&' cEt_I2: db '%' tcEtEnd LABEL BYTE .erre ET_R4 EQ (tcEtEnd - cEt_R4) .erre ET_SD EQ (tcEtEnd - cEt_SD) .erre ET_R8 EQ (tcEtEnd - cEt_R8) .erre ET_I4 EQ (tcEtEnd - cEt_I4) .erre ET_I2 EQ (tcEtEnd - cEt_I2) DbPub OTypeOfTypeChar cProc OTypeOfTypeChar,<NEAR>,<DI> cBegin push cs pop es mov di,CPoffset tcEt mov cx,tcEtEnd - tcEt repnz scasb ;NZ and cx == 0 if not found ; Z and cx == oType-1 if found jnz @F inc cx ;cx == oType @@: .errnz ET_IMP mov ax, cx ;ax == ET_IMP if not found ; == ET_ type if found or ax,ax cEnd cProc OTypeOfTypeCharFar,<FAR,PUBLIC> parmB TypeChar cBegin mov al,[TypeChar] call OTypeOfTypeChar cEnd ;*** ;PrsDeActivate, PrsDeAct_NoTxd ; ;Purpose: ; Save the current procedure's register set (prsCur) back into the tRs. ; TxtDeActivate is called to handle the procedure text table. ; ; PrsDeAct_NoTxd is the same as PrsDeActivate, except that it doesn't ; activate mrsCur's txd - - - i.e., there is no txd active on exit, unless ; the routine is called without an active prs - - - in this latter case, ; no action is taken. ; ; NOTE: This routine is guaranteed to cause no heap movement. ; ;Entry: ; grs.oPrsCur = current procedure to be DeActivated ; UNDEFINED if there is no current procedure ;Exit: ; grs.oPrsCur = UNDEFINED ; For PrsDeActivate, txdCur is setup for mrsCur ; (unless grs.oMrsCur == UNDEFINED on input) ;Uses: ; none. ;Preserves: ; ES ;Exceptions: ; none. ; ;******************************************************************************* PUBLIC PrsDeActivate PrsDeActivate: mov ax,sp SKIP2_PSW PrsDeAct_NoTxd: xor ax,ax cProc PrsDeAct,<PUBLIC,NEAR,NODATA> cBegin PrsDeAct DbHeapMoveOff ;assert no heap movement here cmp [grs.GRS_oPrsCur],UNDEFINED jz PrsDeAct_Exit push si push di push es xchg ax,di ;save flag in di DbChk ConStatStructs mov si,[grs.GRS_oPrsCur] ;si = pointer to prs entry RS_BASE add,si GETRS_SEG es,bx,<SIZE,LOAD> mov PTRRS[si.PRS_txd.TXD_bdlText_status],NOT_OWNER mov BPTRRS[si.PRS_txd.TXD_flags],FTX_mrs ;ensure txd looks invalid in ; table, in case this prs has ; no text table cCall TxtDeActivate ;copies txd into prs table or ; mrs table, as appropriate GETRS_SEG es,bx,<SIZE,LOAD> mov bx,si ;bx = pointer to prs entry mov si,dataOFFSET prsCur ;si = pointer to prsCur call CopyNchgPrs ;copy prs & move bdName owner call SetPrsUndef ;grs.oPrsCur=UNDEFINED, ;oRsCur=oMrsCur or di,di jz PrsDeAct_NoTxd_Exit ;brif want no txd active on exit cCall TxtActivate ;activate txdCur for mrsCur PrsDeAct_NoTxd_Exit: pop es pop di pop si PrsDeAct_Exit: DbHeapMoveOn cEnd PrsDeAct ;*** ;PrsDeActivateFar() ; ;Purpose: ; Same as PrsDeActivate, but accessible from other code segments. ; ;Entry: ; grs.oPrsCur = current procedure to be DeActivated ; UNDEFINED if there is no current procedure ;Exit: ; grs.oPrsCur = UNDEFINED ; txdCur is setup for mrsCur (unless grs.oMrsCur == UNDEFINED on input) ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc PrsDeActivateFar,<PUBLIC,FAR,NODATA> cBegin PrsDeActivateFar cCall PrsDeActivate cEnd PrsDeActivateFar ;*** ;PrsActivate(oPrsNew) ; ;Purpose: ; Make the procedure indicated by oPrsNew the current active procedure. The ; current procedure's register set is saved via PrsDeActivate. If oPrsNew's ; module is different from grs.oMrsCur and the procedure has an associated ; text table, MrsActivate() is called to make the procedure's module ; current. TxtActivate is called at the end. ; ; NOTE: This routine is guaranteed to cause no heap movement. ; ;Entry: ; 'oPrsNew' is an offset into the Rs table ; for procedure to be made current. ; Note that, if oPrsNew == UNDEFINED or if the entry at offset oPrsNew ; is a discarded entry, the current procedure (if any) ; will be deactivated, and no new prs will be activated. ;Exit: ; grs.oPrsCur = oPrsNew ; if oPrsNew != UNDEFINED ; all fields in prsCur are setup ; all fields in txdCur are setup ; If prs @ offset oPrsNew has a text table, then mrsCur is activated ; for prsNew.oMrs. ;Uses: ; none. ;Preserves: ; ES ;Exceptions: ; none. ; ;******************************************************************************* cProc PrsActivate,<PUBLIC,FAR,NODATA> parmW oPrsNew cBegin PrsActivate cCall PrsActivateCP,<oPrsNew> cEnd PrsActivate cProc PrsActivateCP,<PUBLIC,NEAR,NODATA>,<SI,ES> parmW oPrsNew cBegin PrsActivateCP DbHeapMoveOff ;assert no heap movement here mov ax,[oPrsNew] mov bx,[grs.GRS_oPrsCur] cmp ax,bx DJMP jz PrsActivate_Exit ;brif desired prs is already ; active mov si,ax ;si = ax = oPrsNew inc ax jz PrsActivate_Cont ;brif oPrsNew == UNDEFINED DbChk oPrs,si ;ife RELEASE - ensure validity ;we're actually activating a prs. If we currently have a prs active, ;then we can avoid activating and then just deactivating the txd for ;mrsCur if both prs's are in the same module - - - that's a ;considerable speed savings. RS_BASE add,si ;si = pPrs GETRS_SEG es,cx,<SIZE,LOAD> mov cx,PTRRS[si.PRS_oMrs] ;is oMrs for this prs the same cmp [grs.GRS_oMrsCur],cx ; as oMrsCur? jnz PrsActivate_Cont1 ; brif not - inc bx jz NoPrs_Active ;brif no prs active call PrsDeAct_NoTxd ;deactivate existing prs, ; don't activate txd for mrsCur jmp short MrsCur_Is_Correct NoPrs_Active: ;no prs currently active, and we're activating a prs in mrsCur cCall TxtDeActivate ;deactivate txd for mrsCur jmp short MrsCur_Is_Correct PrsActivate_Cont1: dec ax xchg ax,si ;si = oPrsNew PrsActivate_Cont: cCall PrsDeActivate ;deactivate current prs, if any inc si ;test for UNDEFINED jz PrsActivate_Exit ;brif not dec si ;restore si = oPrsNew RS_BASE add,si ;si = pPrs GETRS_SEG es,bx,<SIZE,LOAD> mov ax,PTRRS[si.PRS_oMrs] ;is oMrs for this prs the same mov dx,[grs.GRS_oMrsCur] cmp dx,ax ; as oMrsCur? jz MrsCur_Is_Correct1 ; brif so ;When activating a PRS, we must activate the PRS's MRS iff: ; - the procedure has a Text Table or ; - the procedure has a Definition (i.e. SUB/FUNCTION stmt) ;A PRS could have a text table and no Definition after PrsMake ; (i.e. after user does a File/New/Sub) ;A DEF FN PRS could have a Definition and no text table ;A SUB/FUNCTION PRS could have a Definition and no text table ; after a SUB/FUNCTION statement is seen by Parser during ; ASCII Load, but before the TxtMgr calls PrsMake to give the ; prs a text table. cmp PTRRS[si.PRS_txd.TXD_bdlText_status],NOT_OWNER jnz PrsHasText ;brif prs has a text tbl ; (if so, its mrs must also ; be activated) inc dx ; is there an active mrs? jz PrsHasText ; brif not - make sure that ; an mrs is active test BPTRRS[si.PRS_flags],FP_DEFINED jz MrsCur_Is_Correct1 ;brif prs is DECLAREd but not ;defined PrsHasText: cCall MrsActivateCP,<ax> ;activate the mrs for this prs MrsCur_Is_Correct1: cCall TxtDeActivate ;deactivate txdCur for mrsCur MrsCur_Is_Correct: DbChk MrsCur ;in case mrsCur not active on ; input, and FP_DEFINED not set GETRS_SEG ds,bx,<SIZE,LOAD> assumes ds,nothing mov bx,dataOFFSET prsCur ;now bx == prsCur dest address SETSEG_EQ_SS es ;es:bx == dest address call CopyNchgPrs ;copy prs & move bdName owner SETSEG_EQ_SS ds assumes ds,DATA mov ax,[oPrsNew] ;note new oPrsCur call SetPrsAx ;grs.oPrsCur = ax ;grs.oRsCur = 8000h + ax cCall TxtActivate ;activate txdCur for this prsCur ; from the Rs table PrsActivate_Exit: DbHeapMoveOn cEnd PrsActivateCP ;*** ;PrsFree() ; ;Purpose: ; This is called to remove prsCur from the Rs table. It releases all ; resources associated with current procedure including its dynamic value ; table and text table (the latter via TxtDiscard). Note that it also ; causes ALL variables to be cleared! Note that it also resets the ; flags byte in the name table entry. ; Note also that this function should only be called after PrsDiscard ; has been called for the procedure. ; ; NOTE: some callers of this routine expect no heap movement to occur. ; ;Entry: ; grs.oPrsCur assumed != UNDEFINED, and prsCur is a valid, active prs. ; It is assumed that the txd for prsCur (i.e., txdCur) has already been ; discarded via a call to PrsDiscard. ;Exit: ; AX != FALSE (for use with ForEach...) ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc PrsFree,<PUBLIC,FAR,NODATA> cBegin PrsFree DbHeapMoveOff ;assert no heap movement here DbChk ogNam,prsCur.PRS_ogNam mov ax,[prsCur.PRS_oMrs] cmp ax,[grs.GRS_oMrsCur] ; 'defining' mrs active? jz @F ; brif so push [grs.GRS_oPrsCur] ; parm to PrsActivateCP cCall MrsActivateCP,<ax> ; activate mrs for this prs call PrsActivateCP ; reactivate prsCur @@: cCall ONamOfOgNam,<prsCur.PRS_ogNam> ; get oNam for this prs DbAssertRel ax,nz,0,CP,<PrsFree: Out of memory return from ONamOfOgNam> xchg ax,bx ;bx=oNam, parm to ResetONamMask mov al,NMSP_SUB OR NM_fShared ;reset these bit flags, i.e., call ResetONamMask ; free the module namespace ; for this name cCall DiscardHistoryORs,<grs.GRS_oRsCur> ; throw away help ; history for prs. ;Now, unlink from the prs chain, and link into the prs free chain GETRS_SEG es,bx,<SIZE,LOAD> mov ax,[grs.GRS_oPrsCur] mov cx,ax xchg [oFreePrsFirst],ax ;link at head of prs free chain mov bx,[oPrsFirst] cmp bx,cx ;was this prs at head of chain? jnz UnlinkPrs_Loop ; brif not RS_BASE add,bx xchg ax,PTRRS[bx.PRS_oPrsNext] ;finish free chain link, ; set ax for unlink mov [oPrsFirst],ax jmp short PrsFree_LinksOk UnlinkPrs_Loop: RS_BASE add,bx mov dx,PTRRS[bx.PRS_oPrsNext] cmp dx,cx ;is this the previous entry? jz GotPrevEntry ; brif so mov bx,dx jmp UnlinkPrs_Loop GotPrevEntry: xchg bx,dx RS_BASE add,bx xchg ax,PTRRS[bx.PRS_oPrsNext] ;finish free chain link, ; set ax for unlink xchg bx,dx mov PTRRS[bx.PRS_oPrsNext],ax ;link now complete PrsFree_LinksOk: call SetPrsUndef ;grs.oPrsCur=UNDEFINED, ;oRsCur=oMrsCur mov ax,sp ;non-zero retval DbHeapMoveOn cEnd PrsFree ;*** ;PrsDiscard() ; ;Purpose: ; This is called by the user-interface in response to the Discard Procedure ; menu selection. It releases all resources associated with current ; procedure including its dynamic value table and text table (the latter ; via TxtDiscard). Note that it also causes ALL variables to be cleared! ; This is also called by MrsDiscard for all prs's that have a text table. ; ; PrsDiscard1 is identical to PrsDiscard, except that it doesn't try ; to find new "defining" references for prs entries which lost their ; defining references. This is a speed opt for cases which need to ; call PrsDiscard multiple times. After all calls to PrsDiscard1 have ; been made, the caller should call ChkAllUndefPrs, to update the ; prs entries. ; ;Entry: ; grs.oPrsCur assumed != UNDEFINED, and prsCur is a valid, active prs. ; mrsCur assumed set up correctly as well. ; grs.oMrsCur assumed == prsCur.oMrs ; txdCur assumed to be set up correctly for prsCur if the prs has a ; text table. ;Exit: ; AX == TRUE (non-zero) ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc PrsDiscard,<PUBLIC,FAR,NODATA> cBegin PrsDiscard call PrsDiscard1 call ChkAllUndefPrs ;search for new defining ;references for Prs entries ;which had their "defining" ;reference deleted. PrsDiscardX: mov ax,sp ;reval = true cEnd PrsDiscard cProc PrsDiscard1,<PUBLIC,NEAR,NODATA> cBegin PrsDiscard1 DbChk ConStatStructs or [mrsCur.MRS_flags],FM_VARNEW ;tell CLEAR code we want to ; deallocate $static arrays, ; not just zero-fill them (in ; this module only) call ClearTheWorld and [mrsCur.MRS_flags],NOT FM_VARNEW ;reset bit in mrs flags test [txdCur.TXD_flags],FTX_mrs jnz PrsHasNoTxtTbl ;brif DECLARE or DEF FN prs call AlphaORsFree ;release table of sorted oRs's push [grs.GRS_oRsCur] ;force module level code to push [grs.GRS_oMrsCur] ; be visible in any windows ; that show this prs (if any) PUSHI ax,0 ;not just renaming an oRs call WnReAssign cCall DiscardHistoryORs,<grs.GRS_oRsCur> ; throw away help ; history for prs. cCall TxtDiscard ;discard prs's text table cCall TxtActivate ;activate txdCur for mrsCur PrsHasNoTxtTbl: test [grs.GRS_flagsDir],FDIR_new jz PrsMayHaveRefs ;brif NewStmt isn't active call PrsFree ;delete entry from table PrsMayHaveRefs: mov ax,sp ;retval = true cEnd PrsDiscard1 ;*************************************************************************** ; GetNextPrsInMrs, GetNextPrs ; Purpose: ; For GetNextPrs, find next prs. ; For GetNextPrsInMrs, find next prs in given module. ; ; GetNextPrs added as part of revision [40]. ; Note: ; [13] This function now handles the case where the next prs in ; [13] the Rs table (or the first prs, if ax = UNDEFINED on entry) ; [13] is a hole for prsCur. Note, therefore, that the oPrs returned ; [13] could be for prsCur, i.e., do not assume that this can be ; [13] used to access the prs in the Rs table. Suggestion: Use ; [13] PPrsOPrs or FieldsOfPrs to access prs information. ; Entry: ; ax = oPrs of current prs (UNDEFINED if caller wants oPrs of ; 1st prs [in module]. ; bx = module of interest (only used for GetNextPrsInMrs) ; Exit: ; ax = UNDEFINED if there are no more prs's that meet the requirement ; else it is the offset into the prs table for the current prs. ; Since no oPrs can exceed 7FFFH (for global reasons), it ; is safe for the caller to do: ; js NoPrs ; es = seg of Rs table in far Rs table versions. ;Uses: ; none. ;Preserves: ; cx ;Exceptions: ; none. ; ;*************************************************************************** cProc GetNextPrs,<PUBLIC,NEAR,NODATA> cBegin <nogen> sub dx,dx jmp short GetNext_Prs cEnd <nogen> cProc GetNextPrsInMrs,<PUBLIC,NEAR,NODATA> cBegin <nogen> mov dx,sp cEnd <nogen> ?DFP = DFP_NONE ; don't smash regs on entry cProc GetNext_Prs,<NEAR,NODATA>,<DI,CX> cBegin ?DFP = DFP_CP ; restore switch mov cx,dx ; cx == 0 ==> ignore oMrs mov dx,bx ;dx = oMrs GETRS_SEG es,bx,<SIZE,LOAD> mov bx,ax ;bx = UNDEFINED/oPrs inc ax jnz NextPrs_Loop_Start ;brif a prs is active mov bx,[oPrsFirst] ;bx == oPrsCur jmp short NextPrs_Start NextPrs_Loop_Start: RS_BASE add,bx NextPrs_Loop: mov bx,PTRRS[bx.PRS_oPrsNext] NextPrs_Start: mov ax,UNDEFINED inc bx .errnz UNDEFINED - 0FFFFH jz NextPrs_Exit ;brif no more prs's in table dec bx mov ax,bx ;potential return value RS_BASE add,bx cmp PTRRS[bx.PRS_ogNam],UNDEFINED ; is current entry valid? jnz Got_Valid_Entry ; brif so DbAssertRel ax,z,grs.GRS_oPrsCur,CP,<NextPrs err> ;UNDEFINED ogNam, must be active mov bx,dataOFFSET prsCur SETSEG_EQ_SS es Got_Valid_Entry: jcxz NextPrs_Exit ; brif we want all prs's, ; not just those for a ; given module cmp dx,PTRRS[bx.PRS_oMrs] ;is this prs in current module? jnz NextPrs_Loop ; brif not, loop to next entry NextPrs_Exit: or ax,ax ;set condition codes for caller cEnd ;*************************************************************************** ; NextMrsFile ; Purpose: ; Find and activate the next mrs for which has FM2_File set. ; Entry: ; grs.oMrsCur = oMrs of current mrs (UNDEFINED if caller wants first ; module in the Rs table. ; Note that this does NOT find or activate the global module. ; Exit: ; next mrs is loaded into mrsCur, ; ax = grs.oMrsCur = UNDEFINED if there are no more mrs's in the ; Rs table to be activated, ; else it is actually oMrsCur. ; Note that if ax = UNDEFINED on exit, no mrs will be active. ;Uses: ; none. ;Exceptions: ; none. ; ;*************************************************************************** cProc NextMrsFile_All,<PUBLIC,FAR,NODATA> cBegin <nogen> sub ax,ax ; do find empty unnamed jmp short NextMrsFile_Common cEnd <nogen> cProc NextMrsFile,<PUBLIC,FAR,NODATA> cBegin <nogen> mov ax,sp ; don't find empty unnamed cEnd <nogen> ?DFP = DFP_NONE ; don't smash regs on entry cProc NextMrsFile_Common,<PUBLIC,FAR,NODATA> cBegin ?DFP = DFP_CP ; restore switch ; NOTE: shares exit with PrevMrsFile push ax ; preserve flag push [grs.GRS_oMrsCur] cCall MrsDeActivate GETRS_SEG es,bx,<SIZE,LOAD> pop bx .errnz UNDEFINED - 0FFFFh inc bx ;want first module? jnz Got_oMrs ;brif not mov bx,OMRS_GLOBAL + 1 ; start looking w/1st entry ; after the global mrs Got_oMrs: dec bx ;bx = oMrs for global mrs RS_BASE add,bx NextMrs_Loop: mov bx,PTRRS[bx.MRS_oMrsNext] mov ax,bx ;retval in case of no more mrs's inc bx .errnz UNDEFINED - 0FFFFH jz NextMrs_Exit ;brif no more mrs's in table dec bx RS_BASE add,bx test BPTRRS[bx.MRS_flags2],FM2_File jz NextMrs_Loop ;brif not a File mrs cmp PTRRS[bx.MRS_ogNam],OGNAM_UNNAMED ; UNNAMED mrs? jnz @F ; brif not pop cx ; fetch flag push cx ; restore to stack for ; next time thru loop jcxz @F ; brif want ALL file mrs's call EmptyMrs ; cx = 0 if no empty unnamed GETRS_SEG es,ax,<SIZE,LOAD> ; refresh ES jcxz @F ; brif unnamed mrs not empty jmp short NextMrs_Loop ; skip empty unnamed mrs @@: RS_BASE sub,bx ;pMrs --> oMrs push bx ; parm to MrsActivateCP Skip_Empty_Unnamed: ; shared exit point cCall MrsActivateCP NextMrs_Exit: pop cx ; clean flag off stack mov ax,[grs.GRS_oMrsCur] cEnd ;*************************************************************************** ; NextTextPrsInMrs ; Purpose: ; Find and activate the next prs in current module for which there ; is a text table. ; Entry: ; grs.oPrsCur = oPrs of current prs (UNDEFINED if caller wants oPrs of ; 1st prs in module. ; grs.oMrsCur identifies current module ; Exit: ; next prs is loaded into prsCur, ; ax = grs.oPrsCur = UNDEFINED if there are no more prs's in this mrs ; with text tables ; else it is the offset into the Rs table for the current prs. ;Uses: ; none. ;Exceptions: ; none. ; ;*************************************************************************** cProc NextTextPrsInMrs,<PUBLIC,FAR,NODATA> cBegin mov cx,sp ;want only prs's w/text tables jmp short NextPrs_Shared cEnd <nogen> ;*************************************************************************** ; NextPrsInMrs ; Purpose: ; Find and activate the next prs in current module ; Entry: ; grs.oPrsCur = oPrs of current prs (UNDEFINED if caller wants oPrs of ; 1st prs in module. ; grs.oMrsCur identifies current module ; Exit: ; next prs is loaded into prsCur, ; ax = grs.oPrsCur = UNDEFINED if there are no more prs's in this mrs. ; else it is the offset into the Rs table for the current prs. ;Uses: ; none. ;Exceptions: ; none. ; ;*************************************************************************** cProc NextPrsInMrs,<PUBLIC,FAR,NODATA> cBegin xor cx,cx ;want all valid prs's NextPrs_Shared: mov ax,[grs.GRS_oPrsCur] mov bx,[grs.GRS_oMrsCur] push cx ;save fText call GetNextPrsInMrs ;ax = next prs ;or UNDEFINED if no more cCall PrsActivateCP,<ax> ;activate current entry ;or deactivate prs if ax=UNDEFINED pop cx jcxz NextPrs_IgnoreText ;brif don't care about text tbl cmp [grs.GRS_oPrsCur],UNDEFINED jz NextPrs_IgnoreText ;brif beyond last prs in mrs test [txdCur.TXD_flags],FTX_mrs jnz NextPrs_Shared ;brif prs has no text table NextPrs_IgnoreText: mov ax,[grs.GRS_oPrsCur] cEnd ;*** ;FreeAllUnrefdPrs ; ;Purpose: ; This frees all prs entries which have no more references to them. ; Calls PrsFree for each prs that doesn't have PRS_otxDef = UNDEFINED. ; This is done in case the user does something which causes a prs ; entry to be made for which there is no reference in a text table ; (such as simply typing 'foo' in direct mode - - - don't want a ; prs for SUB foo hanging around ...). ;Entry: ; none. ;Exit: ; Since it is called from Executors, we preserve grs.fDirect ; and grs.oRsCur. ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc FreeAllUnrefdPrs,<PUBLIC,FAR,NODATA> cBegin xor cx,cx xchg cl,[fCouldBeBogusPrs] ;reset, and get existing setting to test jcxz FreeAllUnrefdPrs_Exit ;brif no chance of bogus prs's around ; (this is a speed optimization) push WORD PTR [grs.GRS_fDirect] push [grs.GRS_oRsCur] call FreeAllUndefinedPrs ;call common code to do the work call RsActivateCP PopfDirect ax ;set fDirect to pushed value FreeAllUnrefdPrs_Exit: cEnd ;*** ;PPrsOPrs ;Purpose: ; Given an oPrs, return a pointer to the actual prs entry. ;Entry: ; ax = oPrs ;Exit: ; bx = pPrs ; if FV_FAR_RSTBL ; es is set to the seg of the prs (i.e., retval is es:bx) ; ax = oPrs (same as input) ;Exceptions: ; none. ;Preserves: ; All but bx ; ;*************************************************************************** PPrsOPrs PROC NEAR public PPrsOPrs assumes ds,NOTHING DbChk oPrs,ax ;ife RELEASE - ensure oPrs is valid test conFlags,F_CON_StaticStructs jz PrsInTable ;brif static structs are disabled mov bx,dataOFFSET prsCur ;assume oPrs is for prsCur SETSEG_EQ_SS es ;es:bx points to desired prs cmp ax,[grs.GRS_oPrsCur] jz Got_pPrs ;brif oPrs is for prsCur PrsInTable: GETRS_SEG es,bx,<SIZE,LOAD> mov bx,ax RS_BASE add,bx Got_pPrs: ret assumes ds,DATA PPrsOPrs ENDP sEnd CP sBegin SCAN assumes CS,SCAN ;*** ;PPrsOPrsSCAN ;Purpose: ; Given an oPrs, return a pointer to the actual prs entry. ; Added as revision [46]. ; [69] For FV_SBSWAP versions, sets sbRsScan to the sb of the ; [69] segment containing the prs, to facilitate refreshing this ; [69] this segment value. ;Entry: ; ax = oPrs ;Exit: ; bx = pPrs ; if FV_FAR_RSTBL ; es is set to the seg of the prs (i.e., retval is es:bx) ; ax = oPrs (same as input) ;Exceptions: ; none. ;Preserves: ; All but bx ; ;*************************************************************************** PPrsOPrsSCAN PROC NEAR public PPrsOPrsSCAN assumes ds,NOTHING DbChk oPrs,ax ;ife RELEASE - ensure oPrs is valid DbChk ConStatStructs mov bx,dataOFFSET prsCur ;assume oPrs is for prsCur SETSEG_EQ_SS es ;es:bx points to desired prs cmp ax,[grs.GRS_oPrsCur] jz @F ;brif oPrs is for prsCur GETRS_SEG es,bx,<SIZE,LOAD> mov bx,ax RS_BASE add,bx @@: ret assumes ds,DATA PPrsOPrsSCAN ENDP sEnd SCAN sBegin CP assumes CS,CP ;*** ;FFreePrs ;Purpose: ; Given an oPrs, return zero in AX if it is a free prs ; This is useful when a routine wants to activate a caller's prs ; if it has not been freed during the course of the routine. ;Entry: ; ax = oPrs ;Exit: ; bx = pPrs ; ax = zero if invalid prs, non-zero if valid prs ; condition codes set based on value in AX ;Exceptions: ; none. ;Preserves: ; All but bx ;*************************************************************************** FFreePrs PROC NEAR DbChk ConStatStructs mov bx,dataOFFSET prsCur ;assume oPrs is for prsCur SETSEG_EQ_SS es cmp ax,[grs.GRS_oPrsCur] jz Got_pPrs1 ;brif oPrs is for prsCur GETRS_SEG es,bx,<SIZE,LOAD> xchg ax,bx RS_BASE add,bx ;bx points to prs in the Rs table Got_pPrs1: mov ax,PTRRS[bx.PRS_ogNam] ; ax = UNDEFINED if free prs inc ax ;ax (and condition codes) = zero if free ret FFreePrs ENDP ;*** ;RsActivateIfNotFree ;Purpose: ; Activate a register set if it is not a free prs ; This is useful when a routine wants to activate a caller's prs ; if it has not been freed during the course of the routine. ; If oRs is a free prs, the current oRs is left active. ;Entry: ; ax = oRs ;Exit: ; none. ;Exceptions: ; none. ; ;*************************************************************************** PUBLIC RsActivateIfNotFree RsActivateIfNotFree PROC NEAR or ax,ax jns NotAPrs ;brif activating an MRS push ax and ah,7Fh ;ax = oPrs (instead of an oRs) call FFreePrs ;see if it is a free prs pop ax ;restore ax = oRs jz ItsFree ;brif prs is not active NotAPrs: cCall RsActivateCP,<ax> ItsFree: ret RsActivateIfNotFree ENDP ;*** ;FieldsOfPrs ;Purpose: ; Given an oPrs, get its oNam, Fields, and flags without changing ; the current prs. ; ; Note: it costs nothing for this routine to return a pointer to the ; prs in bx, BUT: caller beware! This represents a pointer either to ; prsCur, OR into the global table of prs's. If the latter, then ; the knowledge of what information is valid when in the table and ; how to use it is best left internal to the contextmgr. ;Entry: ; oPrs ;Exit: ; ax = oNam (offset into the MODULE name table) ; bx = pointer to the prs ; cx = oPrs (same as input parm) ; dl = procType ; dh = proc's flags (only useful to masm callers) ; es = seg of the prs (far Rs table versions only) ; ; NOTE: The code that creates a new prs explicitly calls the namemgr ; to create a name entry, even though it doesn't need the oNam. ; This ensures that FieldsOfPrs doesn't need an out-of-memory ; error return. ;Exceptions: ; none. ;Preserves: ; es ;*************************************************************************** cProc FieldsOfPrs,<PUBLIC,NEAR,NODATA> parmW oPrs cBegin FieldsOfPrs mov ax,[oPrs] push ax ;save for retval push es ; preserve call PPrsOPrs ;bx = pPrs DbHeapMoveOff ;assert no heap movement here push bx ;save pPrs across call push es ;save seg of Rs table across call push PTRRS[bx.PRS_ogNam] call ONamOfOgNam ; get oNam for this prs DbHeapMoveOn DbAssertRel ax,nz,0,CP,<Out of memory error in FieldsOfPrs> pop es pop bx mov dl,BPTRRS[bx.PRS_procType] mov dh,BPTRRS[bx.PRS_flags] pop es pop cx ;return input oPrs cEnd FieldsOfPrs cProc FieldsOfPrsFar,<PUBLIC,FAR,NODATA> parmW oPrs cBegin FieldsOfPrsFar cCall FieldsOfPrs,<[oPrs]> cEnd FieldsOfPrsFar ;*** ;SetPrsField ;Purpose: ; Given an oPrs, an offset into the prs and a 16-bit value, set ; the field at the given offset in the prs to that value. ; This function is provided to eliminate the requirement to ; activate and then deactivate a prs to set one field. ; ; NOTE: This routine should not be used to set fields in the txd, ; unless the caller first ensures that the prs (and thus, the txd) ; is not active. ; ;Entry: ; oPrs, oField, wValue ;Exit: ; ax = oPrs (same as input) ;Exceptions: ; none. ;Preserves: ; es ;*************************************************************************** cProc SetPrsField,<PUBLIC,NEAR,NODATA>,<es> parmW oPrs parmW oField parmW wValue cBegin SetPrsField mov ax,[oPrs] call PPrsOPrs ;bx = pPrs, ax = oPrs add bx,[oField] ;bx now points to desired field mov cx,[wValue] ;fetch given value mov PTRRS[bx],cx ;set the field with given value cEnd SetPrsField ;*** ;OMrsORs ;Purpose: ; Given an oRs, return the oMrs for the associated module. ;Entry: ; ax = oRs ;Exit: ; ax = oMrs for the module of the given oRs ;Exceptions: ; none. ;Preserves: ; all but bx and es ;*************************************************************************** PUBLIC OMrsORs OMrsORs PROC NEAR test ah,080H ;is this already an oMrs? jz OMrsORs_Exit ; brif so and ah,07FH ;ax = an oPrs DbChk oPrs,ax call PPrsOPrs ;bx = pPrs mov ax,PTRRS[bx.PRS_oMrs] OMrsORs_Exit: DbChk oMrs,ax ret OMrsORs ENDP ;*** ;EnStaticStructs ;Purpose: ; Called to ensure that mrsCur, prsCur (if a prs is active), and ; txdCur are set up correctly for the current context. Used in ; conjunction with DisStaticStructs. ;Entry: ; grs.GRS_oRsCur set correctly for current context. ; if conFlags bit flag F_CON_StaticStructs is reset (FALSE) on ; entry, it is assumed that mrsCur, prsCur, and txdCur ; contain no heap owners. ;Exit: ; conFlags bit flag F_CON_StaticStructs is set (TRUE). ; mrsCur and txdCur are activated. ; if high bit of oRsCur is set, oPrsCur is activated. ; ax = 0 if no action taken, non-zero otherwise. This allows the ; caller an easy determination as to whether he should call ; DisStaticStructs at some later point or not. ;*************************************************************************** cProc EnStaticStructs,<PUBLIC,FAR,NODATA> cBegin EnStaticStructs xor ax,ax ; assume no work to do test [conFlags],F_CON_StaticStructs jnz EnStatic_Exit ;brif things are already set correctly or [conFlags],F_CON_StaticStructs mov ax,UNDEFINED mov [grs.GRS_oMrsCur],ax ;so MrsDeActivate doesn't get confused mov [grs.GRS_oPrsCur],ax ;so PrsDeActivate doesn't get confused xchg [grs.GRS_oRsCur],ax push ax ;ax = oRsCur call RsActivateCP ;reactivate mrsCur, prsCur, and txdCur mov ax,sp ; non-zero indicates we changed the ; state of things EnStatic_Exit: cEnd EnStaticStructs ;*** ;DisStaticStructs ;Purpose: ; Called to deactivate mrsCur, prsCur, and txdCur, and set a flag ; such that RsActivateCP will do just the minimal amount of work, ; realizing that the actual register sets are in the tables, rather ; than in their static structures. ; This is the state of things whenever execution is begun, so procedure ; call/return speed will be reasonable. GetEsDi fetches ES from the ; appropriate table based on GRS fields set in this routine. ;Entry: ; if conFlags bit flag F_CON_StaticStructs is set (TRUE) on ; entry, it is assumed that mrsCur, prsCur, and txdCur ; are set up. ;Exit: ; conFlags bit flag F_CON_StaticStructs is reset (set to FALSE). ; prsCur, mrsCur, and txdCur are deactivated, but the oRsCur and ; oMrsCur & oPrsCur fields in grs are left correctly set. ; ; In non-RELEASE code, mrsCur, prsCur, and txdCur get filled with ; 0FFFFH to help catch cases where code is depending on values in ; these static structures when deactivated. ;*************************************************************************** cProc DisStaticStructs,<PUBLIC,FAR,NODATA> cBegin DisStaticStructs test [conFlags],F_CON_StaticStructs jz DisStatic_Exit ;brif things are already set correctly push [grs.GRS_oRsCur] ;preserve across MrsDeActivate call call MrsDeActivate ;deactivate mrsCur, prsCur, and txdCur and [conFlags],NOT F_CON_StaticStructs call RsActivateCP ;oRsCur is still on the stack DisStatic_Exit: cEnd DisStaticStructs ;*** ; RsActivate, RsActivateCP ; Purpose: ; Activate a given Module's or Procedure's register set. ; ; NOTE: This function does one of two very different things based ; on the current setting of the F_CON_StaticStructs bit flag ; in 'conFlags'. If static structures are currently being used ; to maintain mrsCur, prsCur & txdCur, then this just calls ; MrsActivate or PrsActivate; if not, then the only action ; is to update some grs fields. ; Entry: ; parm1: ushort oRsNew - If high bit is set, low 15 bits = oPrs ; else low 15 bits = oMrs to activate ; Exit: Preserves input AX value, and sets PSW based on an OR AX,AX on exit ; ; Preserves: ; AX ; ;*************************************************************************** cProc RsActivateCP,<PUBLIC,NEAR,NODATA> parmW oRsNew cBegin RsActivateCP push ax ;preserve input value mov ax,[oRsNew] test [conFlags],F_CON_StaticStructs jz No_StaticStr ;brif no static structures inc ax js GotAPrs ;brif not mrs or UNDEFINED dec ax ;ax = oMrs or UNDEFINED push ax call MrsActivateCP jmp SHORT RsActCPExit GotAPrs: dec ax ;ax = 8000h + oPrs and ah,7Fh ;mask off high bit, ax = oPrs push ax call PrsActivateCP jmp short RsActCPExit No_StaticStr: ;no static structures; mrsCur and ; prsCur are to be found in the Rs tbl push ax call far ptr RsActivateCODEFar RsActCPExit: pop ax ; restore input value or ax,ax ; set PSW based on input ax, as a ; service to some callers cEnd RsActivateCP cProc RsActivate,<PUBLIC,FAR,NODATA> parmW oRsNew cBegin RsActivate push oRsNew call RsActivateCP cEnd RsActivate ;NOTE: For EB, the ForEach... varients which take a far pointer cannot be ;NOTE: supported, because code segments could move. The only callers which ;NOTE: use FE_FarCall (below) are the QB User Interface, and a couple of ;NOTE: non-Release routines; these latter are okay for EB, as we'll make the ;NOTE: ;*** ;ForEachMrs(pFunction) ; ;Purpose: ; Invoke *pFunction for each module, after first making that module the ; current module. ; If pFunction ever returns FALSE, ; ForEachMrs() returns FALSE without examining ; any further modules ; Else ; returns TRUE (non-zero) ; ; NOTE: This routine is guaranteed to cause no heap movement in and of ; itself; the function if CALLS may cause heap movement however. ; ;Usage: ; boolean ClearModule() ; if (ForEachMrs(ClearModule)) {... ;Entry: ; pFunction is the FAR address of a the function to be ; invoked for each module. ; the static fMrsTextMask is a flags mask; if we're to search for ALL ; mrs's (i.e., those for user text objects as well as for modules) ; then this will be 0, otherwise, it will be set so we can filter ; out mrs's for which the fText flag is set, and call the given ; function only for each module. The default is to call it for ; modules only. ; NOTE: Even though the flags byte in the mrs structure is a byte, ; this static mask is a word, so we can keep it in SI - - ; all the high bits are zero in the mask all the time, so ; we can safely TEST it against the flags byte as if it ; were a word. ;Exit: ; returns TRUE (non-zero) iff pFunction returned TRUE for each module. ; ALWAYS restores initial module on exit. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc ForEachMrs,<PUBLIC,FAR,NODATA> parmD pFunction cBegin ForEachMrs mov al,FE_PcodeMrs+FE_CallMrs+FE_FarCall+FE_SaveRs les bx,[pFunction] call ForEachCP cEnd ForEachMrs ;*** ;ForEachPrsInMrs(pFunction) ; ;Purpose: ; Invoke *pFunction for each procedure in the current module after first ; making that procedure current. ; If pFunction ever returns FALSE, ; ForEachPrsInMrs() returns FALSE without examining ; any further procedures ; Else ; returns TRUE (non-zero) ; ; NOTE: This routine is guaranteed to cause no heap movement in and of ; itself; the function if CALLS may cause heap movement however. ; ; NOTE: This routine assumes that, if a prs is active on entry, it can ; safely be reactivated on exit. ;Usage: ; boolean ClearPrs() ; if (ForEachPrsInMrs(ClearPrs) {... ;Entry: ; pFunction is the FAR address of the function to be ; invoked for each procedure in the module. ;Exit: ; returns TRUE (non-zero) iff pFunction returned TRUE for each prs. ; Always restores initial Mrs and Prs on exit. ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc ForEachPrsInMrs,<PUBLIC,FAR,NODATA>,<SI,DI> parmD pFunction cBegin ForEachPrsInMrs mov al,FE_PcodePrs+FE_NoPcodePrs+FE_FarCall+FE_SaveRs les bx,[pFunction] call ForEachCP cEnd ForEachPrsInMrs ;******************************************************************************* ;ForEach(flags, pFunction) ;Purpose: ; Same as ForEachCP ;Entry: ; flags identifies what is to be done (FE_xxx) ; pFunction = adr of FAR function to call ;Exit: ; Same as ForEach ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc ForEach,<PUBLIC,FAR> parmB flags parmD pFunction cBegin mov al,[flags] les bx,[pFunction] call ForEachCP cEnd ;******************************************************************************* ;ForEachTxtTblInMrs ;Purpose: ; Same as ForEachCP, except pFunction is called for the ; mrs's text table, and for every SUB and FUNCTION's text table ;Entry: ; bx = offset into CP segment to function to be called ; ;******************************************************************************* cProc ForEachTxtTblInMrs,<PUBLIC,NEAR> cBegin <nogen> mov al,FE_CallMrs+FE_PcodePrs+FE_SaveRs jmp SHORT ForEachCP cEnd <nogen> ;******************************************************************************* ;ForEachTxtTbl ;Purpose: ; Same as ForEachCP, except pFunction is called for each ; mrs's text table, and for every SUB and FUNCTION's text table ;Entry: ; bx = offset into CP segment to function to be called ; ;******************************************************************************* ;******************************************************************************* ;ForEachCP ;Purpose: ; If pFunction ever returns FALSE, ; ForEachCP() returns FALSE without examining any further register sets ; Else ; returns TRUE (non-zero) ; This function can be called recursively ;NOTE: ; This routine is guaranteed to cause no heap movement in and of ; itself; the function it CALLS may cause heap movement however. ;NOTE: ; None of the ForEach routines invoke the given function with the ; global mrs active EVER, regardless of the passed flag combinations. ;Entry: ; if near (CP) callee, bx = adr of function to call ; else es:bx = adr of function to call ; flags identifies what is to be done (FE_xxx) ; These flags indicate for what contexts pFunction is to be called: ; FE_PcodeMrs TRUE if mrs's containing pcode are to be visited ; (NOTE: This does not include INCLUDE mrs's, even ; though they have the FM2_NoPcode bit set to 0) ; FE_TextMrs TRUE if FM2_NoPcode mrs's are to be visited (i.e. ; INCLUDE files, command window's mrs, document files) ; FE_CallMrs TRUE if pFunc is to be called for mrs's text table ; FE_PcodePrs TRUE if prs's with text tables (SUBs/FUNCTIONs) ; are to be visited ; FE_NoPcodePrs TRUE if DEF FN and DECLARE prs's are to be visited ; These flags indicate how pFunction is to be called: ; FE_FarCall TRUE if function to be called is FAR ; (NOTE: only available in non-Release and non-windows ; code) ; FE_SaveRs TRUE if ForEach is to restore caller's oRsCur on exit ; ;For Example, (ignoring FE_FarCall and FE_SaveRs): ; if pFunction is to be called for File (pcode or document): ; al=FE_PcodeMrs+FE_TextMrs+FE_CallMrs ; if pFunction is to be called for every pcode text table in the system ; and it is to be called for the MRS BEFORE all prs's in that module: ; al=FE_PcodeMrs+FE_CallMrs+FE_PcodePrs ; if pFunction is to be called for every pcode text table in the system ; and it is to be called for the MRS AFTER all prs's in that module: ; al=FE_PcodeMrs+FE_CallMrsAfter+FE_PcodePrs ; if pFunction is to be called for every pcode text table in the system ; and it is to be called for the MRS BEFORE AND AFTER all prs's in ; that module: ; al=FE_PcodeMrs+FE_CallMrs+FE_CallMrsAfter+FE_PcodePrs ; if pFunction is to be called for every prs in the system: ; al=FE_PcodeMrs+FE_PcodePrs+FE_NoPcodePrs ; if pFunction is to be called for every prs in current module: ; al=FE_PcodePrs+FE_NoPcodePrs ; if pFunction is to be called for every prs in the system which ; has no text table (DEF FNs and DECLAREs): ; al=FE_PcodeMrs+FE_NoPcodePrs ;Exit: ; Returns TRUE (non-zero) iff pFunction returned TRUE for each module. ; If FALSE is returned and caller didn't have FE_SaveRs set in the ; input flags byte, the active prs and/or mrs is/are for ; the context from which pFunction returned FALSE. ;Uses: ; none. ;Exceptions: ; none. ; ;******************************************************************************* cProc ForEachTxtTbl,<PUBLIC,NEAR> cBegin <nogen> mov al,FE_PcodeMrs+FE_CallMrs+FE_PcodePrs+FE_SaveRs cEnd <nogen> ;fall into ForEachCP ;Register usage: ; si = current oMrs ; di = current oPrs ; cProc ForEachCP,<PUBLIC,NEAR>,<si,di> localD pFunction localW oMrsSave localW oPrsSave localB flags localB fDoneWithPrss cBegin DbChk ConStatStructs mov [flags],al mov [OFF_pFunction],bx mov [SEG_pFunction],es mov ax,[grs.GRS_oMrsCur] ;save caller's register set mov [oMrsSave],ax mov ax,[grs.GRS_oPrsCur] ;save caller's register set mov [oPrsSave],ax mov di,UNDEFINED ;start with 1st prs in mrs test [flags],FE_PcodeMrs OR FE_TextMrs jz ThisMrsOnly ;brif not visiting all mrs's mov si,OMRS_GLOBAL ; start with 1st mrs, skip gMrs MrsLoop: GETRS_SEG es,bx,<SIZE,LOAD> RS_BASE add,si mov si,PTRRS[si.MRS_oMrsNext] inc si ;Any more mrs's left? jnz NotDone ; brif not jmp FeExitTrue ;exit if beyond end of table NotDone: dec si mov bx,si RS_BASE add,bx ; swapped these ... cmp [grs.GRS_oMrsCur],si ; ... two instructions jnz MrsNotActive ;brif desired mrs is not mrsCur mov bx,dataOFFSET mrsCur SETSEG_EQ_SS es ;mrsCur is in DGROUP, not rs table seg MrsNotActive: mov al,FE_PcodeMrs test BPTRRS[bx.MRS_flags2],FM2_NoPcode OR FM2_Include jz GotPcodeMrs ;brif got a REAL pcode mrs (not ascii ; text or INCLUDE file) shl al,1 ;al = FE_TextMrs .errnz FE_TextMrs - (FE_PcodeMrs + FE_PcodeMrs) GotPcodeMrs: test [flags],al jz MrsLoop ;brif this mrs is not to be visited cCall MrsActivateCP,<si> ;activate next entry ;We're interested in this mrs. Call pFunction with one or more of: ; - the mrs's active, ; - each prs which has a text table active, ; - each prs which has no text table active. ; ThisMrsOnly: mov [fDoneWithPrss],0 call PrsDeactivate ;make module's text table active test [flags],FE_CallMrs jnz CallFunc ;brif pFunction is to be called for mrs PrsLoop: xchg ax,di ;ax = current oPrs mov bx,[grs.GRS_oMrsCur] ;cx = module of interest call GetNextPrsInMrs ;ax = next prs xchg di,ax ;save oPrs in di or di,di js PrsDone ;brif no more prs's mov al,FE_PcodePrs GETRS_SEG es,bx,<SIZE,LOAD> mov bx,di ;bx = oPrs RS_BASE add,bx ;bx = pPrs of prs we propose activating ;NOTE: [13] we can safely add the table base here because we explicitly ;NOTE: [13] called PrsDeactivate, above DbAssertRel di,nz,grs.GRS_oPrsCur,CP,<ForEachCP: active prs in PrsLoop> cmp PTRRS[bx.PRS_txd.TXD_bdlText_status],NOT_OWNER jnz GotPcodePrs ;brif got a prs with pcode-text-table ; i.e. a SUB or FUNCTION shl al,1 ;al = FE_NoPcodePrs .errnz FE_NoPcodePrs - (FE_PcodePrs + FE_PcodePrs) GotPcodePrs: test [flags],al jz PrsLoop ;brif this prs is not to be visited CallFunc: cCall PrsActivateCP,<di> ;activate next prs (or activate module ; if di==UNDEFINED test [flags],FE_FarCall jnz CallFarFunc mov bx,[OFF_pFunction] call bx ;call given NEAR function jmp SHORT CallRet CallFarFunc: cCall pFunction ;call given FAR function CallRet: or ax,ax ;is retval FALSE? jz FeExit ; brif so cmp [fDoneWithPrss],0 jne DoneWithThisMrs ;brif just called for MRS after PRSs test [flags],FE_PcodePrs OR FE_NoPcodePrs jnz PrsLoop ;brif visiting prs's PrsDone: call PrsDeactivate ;make module's text table active mov [fDoneWithPrss],1 ;remember that we're done with this ;module's prss test [flags],FE_CallMrsAfter jnz CallFunc ;brif pFunction is to be called for mrs DoneWithThisMrs: test [flags],FE_PcodeMrs OR FE_TextMrs jz FeExitTrue jmp MrsLoop ;brif visiting mrs's ;ax is still = pFunction's return value FeExitTrue: mov ax,sp ;return TRUE (non-zero) FeExit: xchg ax,si ;save ret value in si test [flags],FE_SaveRs jz FeNoRestore ;brif caller wants to restore oRs push [oMrsSave] cCall MrsActivateCP ;activate caller's mrs push [oPrsSave] cCall PrsActivateCP ;activate caller's prs ;Note that saving grs.oRsCur on entry and calling RsActivate ;on exit is not sufficient, because if the caller's prs was ;not defined, RsActivate would not activate the caller's mrs. FeNoRestore: xchg ax,si ;ax = return value or ax,ax ;set condition codes for caller cEnd ;*** ;ForEachPrsInPlaceCP, ForEachPrsInPlaceCPSav ; ;Purpose: ; This function walks through each prs, and passes a POINTER to the ; current PRS to the specified function. This function is guaranteed ; not to cause ANY heap movement of and by itself. The called function ; is responsible for any adjustment to the entry pPrs to account for ; heap movement that it may cause. ; [63] If the called function returns AX == 0 then ; the ForEach is aborted. Note: called function ; must return with CC reflecting contents of AX. ; ; This routine exists primarily to speed up text editting. It can ; be used when an innocuous action needs to be taken for each PRS ; in the system (eg - checking PRS flags for particular conditions). ; This routine is SIGNIFICANTLY faster than the generalized ForEach ; construct since it just walks the table of Prs's instead of activating ; each PRS individually. ; ; ForEachPrsInPlaceCPSav - restores callers oRs on Exit ; ;Entry: ; bx = CP adr of function to call ;Exit: ; ax = last value return by the called function ; Condition Codes reflect contents of ax ;Uses: ; none. ;Exceptions: ; none. ;******************************************************************************* cProc ForEachPrsInPlaceCPSav,<NEAR,PUBLIC,NODATA> cBegin ForEachPrsInPlaceCPSav push [grs.GRS_oRsCur] ;remember current oRs for RsActivate call ForEachPrsInPlaceCP pop bx push ax push bx call RsActivateCP ;oRsCur already on stack pop ax or ax, ax cEnd cProc ForEachPrsInPlaceCP,<NEAR,PUBLIC,NODATA>,<SI,DI> cBegin ForEachPrsInPlaceCP xchg bx,di ;di = function address call PrsDeactivate ;deactivate prs mov si,[oPrsFirst] ;first prs in Rs table GETRS_SEG es,bx,<SIZE,LOAD> DbHeapMoveOff ;assert no heap movement in this section ;------------------------------------------------------ ;Now, si == offset to current entry ; di == CP addr of ForEach function ;------------------------------------------------------ push sp ; TRUE return value (when no prs's) PrsInPlaceLoop: inc si ;any entries remaining in table? .errnz UNDEFINED - 0FFFFH jz PrsInPlaceExit ;end of table dec si RS_BASE add,si pop ax ; toss last return value call di ;call function push ax ; save return value jz PrsInPlaceExit ; Exit and return Z GETRS_SEG es,bx,<SIZE,LOAD> mov si,PTRRS[si.PRS_oPrsNext] jmp PrsInPlaceLoop ;loop to consider next entry PrsInPlaceExit: DbHeapMoveOn ;heap movement allowed again pop ax ; Return value or ax,ax cEnd ForEachPrsInPlaceCP ;*** ; ValidORs_Check ; Purpose: ; Given what might be an oRs, return FALSE if it matches oMrsCur or ; oPrsCur. ; Used in conjunction with ValidORs. ; Entry: ; grs.GRS_oRsCur ; ; Exit: ; AX = FALSE if oRs looks valid, otherwise TRUE. ; ;*************************************************************************** cProc ValidORs_Check,<NEAR,NODATA> cBegin ValidORs_Check mov ax,sp ;non-zero mov bx,[oRsTest] cmp bx,[grs.GRS_oRsCur] jnz ValidORs_Check_Exit ;brif oRs's don't match or bx,bx jns ValidORs_Check_Done ;brif oRs not an oPrs - - - success cmp [prsCur.PRS_procType],PT_DEFFN jz ValidORs_Check_Done ;brif oRs for an active DEF FN - okay test [txdCur.TXD_flags],FTX_mrs jnz ValidORs_Check_Exit ;brif oRsCur is for prsCur, but the ; active text table for mrsCur. ValidORs_Check_Done: xor ax,ax ;success ValidORs_Check_Exit: cEnd ValidORs_Check ;*** ; ValidORs ; Purpose: ; Given what might be an oRs and an oTx, tell caller if they look ; valid or not. ; If they look valid, activate the oRs. ; [10] NOTE: given the oRs for the global mrs (i.e., OMRS_GLOBAL), ; [10] ValidOrs will say that it looks Invalid. ; Entry: ; [di+4] = possible oRs ; [di+2] = possible oTx ; Exit: ; AX != 0 if oRs and oTx don't look valid; otherwise, ; AX = 0, and the given oRs is activated. ; ;*************************************************************************** cProc ValidORs,<PUBLIC,NEAR,NODATA> cBegin ValidORs mov ax,[di+4] mov [oRsTest],ax mov al,FE_PcodeMrs+FE_CallMrs+FE_PcodePrs+FE_NoPcodePrs push cs pop es mov bx,OFFSET CP:ValidORs_Check call ForEachCP ;returns AX = 0 if oRs valid cEnd ValidORs sEnd CP sBegin CODE assumes CS,CODE ;*** ; RsActivateCODE ; Purpose: ; Activate a given Module's or Procedure's register set. ; ; NOTE: This function is only callable when static structures are ; disabled. ; Entry: ; ax = oRsNew - If high bit is set, low 15 bits = oPrs ; else low 15 bits = oMrs to activate ; Exit: ; Updates the oRsCur, oMrsCur, oPrsCur and offsetTxdSeg fields in the ; grs structure as appropriate, based on the input oRs. ; if FV_FAR_RSTBL, es is set to the seg of the Rs table on exit. ; if SizeD, ds is set to the seg of the variable table for mrsCur. ;*************************************************************************** PUBLIC RsActivateCODE RsActivateCODE PROC NEAR DbChk oRs,ax mov [grs.GRS_oRsCur],ax GETRS_SEG es,bx,<SIZE,LOAD> or ax,ax js Activate_oPrs ;brif oRsNew is an oPrs mov [grs.GRS_oMrsCur],ax mov bx,ax RS_BASE add,bx ;bx = pMrsCur mov [grs.GRS_pMrsCur],bx ;set up to save code when accessing mov [grs.GRS_pRsCur],bx ;set up to save code when accessing add ax,MRS_txd.TXD_bdlText_seg ;ax = offset in tRs to the segment ; address of the current text table mov [grs.GRS_oPrsCur],UNDEFINED mov [grs.GRS_offsetTxdSeg],ax DbChk ConNoStatStructs ;start of [20] ;end of [20] ret Activate_oPrs: and ah,7Fh ;mask off high bit, ax = oPrs mov [grs.GRS_oPrsCur],ax mov bx,ax ;bx = oPrsNew RS_BASE add,bx ;bx = pPrsNew mov cx,PTRRS[bx.PRS_oMrs] mov [grs.GRS_oMrsCur],cx mov [grs.GRS_pRsCur],bx add cx,[grs.GRS_bdRs.BD_pb] mov [grs.GRS_pMrsCur],cx DbChk ConNoStatStructs cmp PTRRS[bx.PRS_txd.TXD_bdlText_status],NOT_OWNER jz Activate_oPrs_Def ;brif oPrsNew is for a DEF FN/DECLARE add ax,PRS_txd.TXD_bdlText_seg ;ax = offset in Rs table to the segment ; address of the current text table mov [grs.GRS_offsetTxdSeg],ax ;start of [20] ;end of [20] ret Activate_oPrs_Def: sub cx,[grs.GRS_bdRs.BD_pb] add cx,MRS_txd.TXD_bdlText_seg mov [grs.GRS_offsetTxdSeg],cx ret RsActivateCODE ENDP ;*** ; RsActivateCODEFar ; Purpose: ; Activate a given Module's or Procedure's register set. ; Far interface to RsActivateCODE ; ; NOTE: This function is only callable when static structures are ; disabled. ; Entry: ; ax = oRsNew - If high bit is set, low 15 bits = oPrs ; else low 15 bits = oMrs to activate ; ;*************************************************************************** cProc RsActivateCODEFar,<PUBLIC,FAR,NODATA> parmW oRsNew cBegin RsActivateCODEFar assumes ds,NOTHING mov ax,[oRsNew] call RsActivateCODE assumes ds,DATA cEnd RsActivateCODEFar sEnd CODE end
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c5/c54a42b.ada
best08618/asylo
7
12746
<reponame>best08618/asylo<filename>gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c5/c54a42b.ada -- C54A42B.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT A CASE_STATEMENT CORRECTLY HANDLES A SMALL RANGE OF -- POTENTIAL VALUES GROUPED INTO A SMALL NUMBER OF ALTERNATIVES. -- (OPTIMIZATION TEST -- JUMP TABLE.) -- RM 03/26/81 -- PWN 11/30/94 SUBTYPE QUALIFIED LITERALS FOR ADA 9X. WITH REPORT; PROCEDURE C54A42B IS USE REPORT ; BEGIN TEST( "C54A42B" , "TEST THAT A CASE_STATEMENT HANDLES CORRECTLY" & " A SMALL NUMBER OF POTENTIAL VALUES GROUPED" & " INTO A SMALL NUMBER OF ALTERNATIVES" ); DECLARE STATCON : CONSTANT CHARACTER RANGE 'A'..'K' := 'J' ; STATVAR : CHARACTER RANGE 'A'..'K' := 'A' ; DYNCON : CONSTANT CHARACTER RANGE 'A'..'K' :=IDENT_CHAR('K'); DYNVAR : CHARACTER RANGE 'A'..'K' :=IDENT_CHAR('G'); BEGIN CASE STATVAR IS WHEN 'B' | 'E' => FAILED( "WRONG ALTERNATIVE A1" ); WHEN 'J' | 'C' => FAILED( "WRONG ALTERNATIVE A2" ); WHEN 'F' => FAILED( "WRONG ALTERNATIVE A3" ); WHEN 'D' | 'H'..'I' => FAILED( "WRONG ALTERNATIVE A4" ); WHEN 'G' => FAILED( "WRONG ALTERNATIVE A5" ); WHEN OTHERS => NULL ; END CASE; CASE CHARACTER'('B') IS WHEN 'B' | 'E' => NULL ; WHEN 'J' | 'C' => FAILED( "WRONG ALTERNATIVE B2" ); WHEN 'F' => FAILED( "WRONG ALTERNATIVE B3" ); WHEN 'D' | 'H'..'I' => FAILED( "WRONG ALTERNATIVE B4" ); WHEN 'G' => FAILED( "WRONG ALTERNATIVE B5" ); WHEN OTHERS => FAILED( "WRONG ALTERNATIVE B6" ); END CASE; CASE DYNVAR IS WHEN 'B' | 'E' => FAILED( "WRONG ALTERNATIVE C1" ); WHEN 'J' | 'C' => FAILED( "WRONG ALTERNATIVE C2" ); WHEN 'F' => FAILED( "WRONG ALTERNATIVE C3" ); WHEN 'D' | 'H'..'I' => FAILED( "WRONG ALTERNATIVE C4" ); WHEN 'G' => NULL ; WHEN OTHERS => FAILED( "WRONG ALTERNATIVE C6" ); END CASE; CASE IDENT_CHAR(STATCON) IS WHEN 'B' | 'E' => FAILED( "WRONG ALTERNATIVE D1" ); WHEN 'J' | 'C' => NULL ; WHEN 'F' => FAILED( "WRONG ALTERNATIVE D3" ); WHEN 'D' | 'H'..'I' => FAILED( "WRONG ALTERNATIVE D4" ); WHEN 'G' => FAILED( "WRONG ALTERNATIVE D5" ); WHEN OTHERS => FAILED( "WRONG ALTERNATIVE D6" ); END CASE; CASE DYNCON IS WHEN 'B' | 'E' => FAILED( "WRONG ALTERNATIVE E1" ); WHEN 'J' | 'C' => FAILED( "WRONG ALTERNATIVE E2" ); WHEN 'F' => FAILED( "WRONG ALTERNATIVE E3" ); WHEN 'D' | 'H'..'I' => FAILED( "WRONG ALTERNATIVE E4" ); WHEN 'G' => FAILED( "WRONG ALTERNATIVE E5" ); WHEN OTHERS => NULL ; END CASE; END ; DECLARE NUMBER : CONSTANT := 1 ; LITEXPR : CONSTANT := NUMBER + 5 ; STATCON : CONSTANT INTEGER RANGE 0..10 := 9 ; DYNVAR : INTEGER RANGE 0..10 := IDENT_INT( 10 ); DYNCON : CONSTANT INTEGER RANGE 0..10 := IDENT_INT( 2 ); BEGIN CASE INTEGER'(0) IS WHEN 1 | 4 => FAILED("WRONG ALTERNATIVE F1"); WHEN 9 | 2 => FAILED("WRONG ALTERNATIVE F2"); WHEN 5 => FAILED("WRONG ALTERNATIVE F3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE F4"); WHEN 6 => FAILED("WRONG ALTERNATIVE F5"); WHEN OTHERS => NULL ; END CASE; CASE INTEGER'(NUMBER) IS WHEN 1 | 4 => NULL ; WHEN 9 | 2 => FAILED("WRONG ALTERNATIVE G2"); WHEN 5 => FAILED("WRONG ALTERNATIVE G3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE G4"); WHEN 6 => FAILED("WRONG ALTERNATIVE G5"); WHEN OTHERS => FAILED("WRONG ALTERNATIVE G6"); END CASE; CASE IDENT_INT(LITEXPR) IS WHEN 1 | 4 => FAILED("WRONG ALTERNATIVE H1"); WHEN 9 | 2 => FAILED("WRONG ALTERNATIVE H2"); WHEN 5 => FAILED("WRONG ALTERNATIVE H3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE H4"); WHEN 6 => NULL ; WHEN OTHERS => FAILED("WRONG ALTERNATIVE H6"); END CASE; CASE STATCON IS WHEN 1 | 4 => FAILED("WRONG ALTERNATIVE I1"); WHEN 9 | 2 => NULL ; WHEN 5 => FAILED("WRONG ALTERNATIVE I3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE I4"); WHEN 6 => FAILED("WRONG ALTERNATIVE I5"); WHEN OTHERS => FAILED("WRONG ALTERNATIVE I6"); END CASE; CASE DYNVAR IS WHEN 1 | 4 => FAILED("WRONG ALTERNATIVE J1"); WHEN 9 | 2 => FAILED("WRONG ALTERNATIVE J2"); WHEN 5 => FAILED("WRONG ALTERNATIVE J3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE J4"); WHEN 6 => FAILED("WRONG ALTERNATIVE J5"); WHEN OTHERS => NULL ; END CASE; CASE DYNCON IS WHEN 1 | 4 => FAILED("WRONG ALTERNATIVE K1"); WHEN 9 | 2 => NULL ; WHEN 5 => FAILED("WRONG ALTERNATIVE K3"); WHEN 3 | 7..8 => FAILED("WRONG ALTERNATIVE K4"); WHEN 6 => FAILED("WRONG ALTERNATIVE K5"); WHEN OTHERS => FAILED("WRONG ALTERNATIVE K6"); END CASE; END ; RESULT ; END C54A42B ;
lab7/src/5/src/boot/mbr.asm
YatSenOS/YatSenOS-Tutorial-Volume-1
400
21399
%include "boot.inc" org 0x7c00 [bits 16] xor ax, ax ; eax = 0 ; 初始化段寄存器, 段地址全部设为0 mov ds, ax mov ss, ax mov es, ax mov fs, ax mov gs, ax ; 初始化栈指针 mov sp, 0x7c00 mov ax, LOADER_START_SECTOR mov cx, LOADER_SECTOR_COUNT mov bx, LOADER_START_ADDRESS load_bootloader: push ax push bx call asm_read_hard_disk ; 读取硬盘 add sp, 4 inc ax add bx, 512 loop load_bootloader ; 获取内存大小 mov ax, 0xe801 int 15h mov [0x7c00], ax mov [0x7c00+2], bx jmp 0x0000:0x7e00 ; 跳转到bootloader jmp $ ; 死循环 ; asm_read_hard_disk(memory,block) ; 加载逻辑扇区号为block的扇区到内存地址memory asm_read_hard_disk: push bp mov bp, sp push ax push bx push cx push dx mov ax, [bp + 2 * 3] ; 逻辑扇区低16位 mov dx, 0x1f3 out dx, al ; LBA地址7~0 inc dx ; 0x1f4 mov al, ah out dx, al ; LBA地址15~8 xor ax, ax inc dx ; 0x1f5 out dx, al ; LBA地址23~16 = 0 inc dx ; 0x1f6 mov al, ah and al, 0x0f or al, 0xe0 ; LBA地址27~24 = 0 out dx, al mov dx, 0x1f2 mov al, 1 out dx, al ; 读取1个扇区 mov dx, 0x1f7 ; 0x1f7 mov al, 0x20 ;读命令 out dx,al ; 等待处理其他操作 .waits: in al, dx ; dx = 0x1f7 and al,0x88 cmp al,0x08 jnz .waits ; 读取512字节到地址ds:bx mov bx, [bp + 2 * 2] mov cx, 256 ; 每次读取一个字,2个字节,因此读取256次即可 mov dx, 0x1f0 .readw: in ax, dx mov [bx], ax add bx, 2 loop .readw pop dx pop cx pop bx pop ax pop bp ret times 510 - ($ - $$) db 0 db 0x55, 0xaa
arch/ARM/STM32/svd/stm32f103/stm32_svd-wwdg.ads
morbos/Ada_Drivers_Library
2
29999
<reponame>morbos/Ada_Drivers_Library -- This spec has been automatically generated from STM32F103.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.WWDG is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_T_Field is HAL.UInt7; -- Control register (WWDG_CR) type CR_Register is record -- 7-bit counter (MSB to LSB) T : CR_T_Field := 16#7F#; -- Activation bit WDGA : Boolean := False; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record T at 0 range 0 .. 6; WDGA at 0 range 7 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype CFR_W_Field is HAL.UInt7; subtype CFR_WDGTB_Field is HAL.UInt2; -- Configuration register (WWDG_CFR) type CFR_Register is record -- 7-bit window value W : CFR_W_Field := 16#7F#; -- Timer Base WDGTB : CFR_WDGTB_Field := 16#0#; -- Early Wakeup Interrupt EWI : Boolean := False; -- unspecified Reserved_10_31 : HAL.UInt22 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CFR_Register use record W at 0 range 0 .. 6; WDGTB at 0 range 7 .. 8; EWI at 0 range 9 .. 9; Reserved_10_31 at 0 range 10 .. 31; end record; -- Status register (WWDG_SR) type SR_Register is record -- Early Wakeup Interrupt EWI : Boolean := False; -- unspecified Reserved_1_31 : HAL.UInt31 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for SR_Register use record EWI at 0 range 0 .. 0; Reserved_1_31 at 0 range 1 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Window watchdog type WWDG_Peripheral is record -- Control register (WWDG_CR) CR : aliased CR_Register; -- Configuration register (WWDG_CFR) CFR : aliased CFR_Register; -- Status register (WWDG_SR) SR : aliased SR_Register; end record with Volatile; for WWDG_Peripheral use record CR at 16#0# range 0 .. 31; CFR at 16#4# range 0 .. 31; SR at 16#8# range 0 .. 31; end record; -- Window watchdog WWDG_Periph : aliased WWDG_Peripheral with Import, Address => System'To_Address (16#40002C00#); end STM32_SVD.WWDG;
access_types.adb
charlesincharge/Intro_to_Ada
0
25786
-- Example adapted from "Ada Crash Course" with Ada.Unchecked_Deallocation; -- Declaring access types (similar application to pointers) -- Often times, an "out" variable will suffice procedure Access_Types is type Integer_Access is access all Integer; Int_P : Integer_Access; -- initializes to null -- P1 = P2 if they point to the same object type Date is record Day, Month, Year : Integer; end record; type Date_Access is access all Date; D1, D2 : Date_Access; D3 : Date; -- `Unchecked_Deallocation` is a generic procedure, so we must procedure Delete_Integer is new Ada.Unchecked_Deallocation(Integer, Integer_Access); procedure Delete_Date is new Ada.Unchecked_Deallocation(Date, Date_Access); begin -- What is returned if new fails? Int_P := new Integer'(0); -- Ada 83 to create Integer access type, initialized to 0 Int_P.all := 1; -- .all "dereferences" the pointer Delete_Integer(Int_P); -- Ada has OPTIONAL garbage collection, bc GC is problematic in embedded systems -- For maximum portability, programmers must assume GC is not done. D1 := new Date; D1.Day := 1; D2 := D1; -- D2 points to the same object as D1 D3 := D2.all; -- copy Date objects (redundant) Delete_Date(D1); end Access_Types;
Transynther/x86/_processed/AVXALIGN/_zr_/i3-7100_9_0xca_notsx.log_21829_1422.asm
ljhsiun2/medusa
9
99089
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %r8 push %rcx push %rdi push %rsi lea addresses_A_ht+0xb2ea, %r8 nop nop nop nop dec %r15 vmovups (%r8), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $0, %xmm5, %rdi nop nop xor $38794, %r15 lea addresses_UC_ht+0x18412, %r13 nop nop nop nop add %r11, %r11 vmovups (%r13), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $1, %xmm3, %rsi nop cmp %r15, %r15 lea addresses_WC_ht+0xe6ea, %rsi lea addresses_WT_ht+0x1abea, %rdi nop nop nop nop nop and $59588, %r8 mov $30, %rcx rep movsl nop add $61870, %r11 lea addresses_WT_ht+0xe37c, %r8 nop nop nop cmp $46155, %r11 movl $0x61626364, (%r8) nop nop inc %r13 lea addresses_D_ht+0xd1ea, %rdi dec %r11 mov $0x6162636465666768, %rcx movq %rcx, %xmm5 movups %xmm5, (%rdi) add $44469, %r11 lea addresses_normal_ht+0xe46a, %r13 nop nop nop add %rcx, %rcx mov (%r13), %di sub $7607, %r11 lea addresses_A_ht+0x189fa, %rdi nop nop nop nop sub $34966, %r11 mov (%rdi), %r15w nop nop nop nop nop sub %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %r8 pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %rax push %rbx push %rdi push %rdx // Store mov $0xcea, %r13 nop nop nop nop add %rbx, %rbx movw $0x5152, (%r13) and %rbx, %rbx // Store lea addresses_UC+0x1b96a, %rdx nop nop nop nop nop add $6426, %r8 movl $0x51525354, (%rdx) nop nop nop nop xor $38960, %rbx // Store lea addresses_US+0x8bcf, %r8 nop xor $40045, %rdx movl $0x51525354, (%r8) nop nop sub $25515, %rdi // Store mov $0x388, %rax inc %r12 movb $0x51, (%rax) nop nop nop and $13805, %r13 // Store lea addresses_normal+0x1c2ea, %r12 nop and %rbx, %rbx mov $0x5152535455565758, %r8 movq %r8, %xmm0 movups %xmm0, (%r12) nop nop inc %rbx // Store mov $0xe6a, %r12 nop nop nop nop nop add %rax, %rax mov $0x5152535455565758, %r8 movq %r8, %xmm7 vmovups %ymm7, (%r12) nop nop nop xor %rdi, %rdi // Store lea addresses_PSE+0xe86a, %rbx nop nop add %r8, %r8 mov $0x5152535455565758, %rdx movq %rdx, %xmm3 vmovups %ymm3, (%rbx) nop and $6863, %r8 // Store lea addresses_A+0x10aea, %rbx nop nop nop nop nop inc %rax mov $0x5152535455565758, %r13 movq %r13, %xmm5 vmovups %ymm5, (%rbx) nop nop nop add $39657, %rbx // Store lea addresses_RW+0x12492, %rax add $13724, %r12 mov $0x5152535455565758, %r13 movq %r13, %xmm4 vmovups %ymm4, (%rax) nop nop nop nop nop cmp %rdi, %rdi // Faulty Load lea addresses_normal+0x86ea, %rdi nop nop nop nop sub %rdx, %rdx movntdqa (%rdi), %xmm4 vpextrq $0, %xmm4, %r13 lea oracles, %rax and $0xff, %r13 shlq $12, %r13 mov (%rax,%r13,1), %r13 pop %rdx pop %rdi pop %rbx pop %rax pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_P', 'size': 2, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_P', 'size': 1, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_normal', 'size': 16, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_P', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_PSE', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_A', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_RW', 'size': 32, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': True, 'type': 'addresses_normal', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False}} {'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'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 */
oeis/024/A024647.asm
neoneye/loda-programs
11
242946
; A024647: n written in fractional base 8/5. ; Submitted by <NAME> ; 0,1,2,3,4,5,6,7,50,51,52,53,54,55,56,57,520,521,522,523,524,525,526,527,570,571,572,573,574,575,576,577,5240,5241,5242,5243,5244,5245,5246,5247,5710,5711,5712,5713,5714,5715,5716,5717,5760,5761,5762,5763,5764,5765 mov $3,1 lpb $0 mov $2,$0 div $0,8 mul $0,5 mod $2,8 mul $2,$3 add $1,$2 mul $3,10 lpe mov $0,$1
Library/SpecUI/CommonUI/CButton/copenButtonCommon.asm
steakknife/pcgeos
504
17196
COMMENT @---------------------------------------------------------------------- Copyright (c) GeoWorks 1994 -- All Rights Reserved PROJECT: PC GEOS MODULE: CommonUI/COpen (gadgets code common to all specific UIs) FILE: copenButtonCommon.asm ROUTINES: Name Description ---- ------------ INT OLButtonDetermineIfNewState Draw this button if its state has changed since the last draw. INT OLButtonDrawLATERIfNewStateFar Redraw the button, delaying the update via the UI queue, or until the next EXPOSE, whichever is appropriate. INT OLButtonDrawLATERIfNewState Redraw the button, delaying the update via the UI queue, or until the next EXPOSE, whichever is appropriate. INT OLButtonActivate This routine sends the ActionDescriptor for this trigger. INT OLButtonSendCascadeModeToMenuFar Calls OLButtonSendCascadeModeToMenu INT OLButtonSendCascadeModeToMenu Packages up a MSG_MO_MW_CASCADE_MODE message and sends it to the menu window object. INT OLButtonSaveStateSetBorderedAndOrDepressed This procedure makes sure that this GenTrigger is drawn as depressed, which depending upon the specific UI might mean DEPRESSED (blackened) and/or BORDERED. INT OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW This routine resets the DEPRESSED and BORDERED flags as necessary, and then immediately redraws the button if necessary INT OLButtonSaveBorderedAndDepressedStatus Save the current BORDERED status of this button so that it can be restored. Basically, it is nearly impossible to tell wether a button at rest should be bordered or not, because buttons in pinned menus change. INT OLButtonRestoreBorderedAndDepressedStatus Save the current BORDERED status of this button so that it can be restored. Basically, it is nearly impossible to tell wether a button at rest should be bordered or not, because buttons in pinned menus change. INT OLButtonEnsureMouseGrab This procedure makes sure that this button has the mouse grab (exclusive). INT OLButtonGrabExclusives This procedure grabs some exclusives for the button object. Regardless of the carry flag, the gadget and default exclusives are grabbed. MTD MSG_META_GAINED_SYS_FOCUS_EXCL This procedure is called when the window in which this button is located decides that this button has the focus exclusive. INT OLButtonSaveStateSetCursored This routine tests if the button is pressed already, and if not, saves the button's current bordered and depressed state, and sets the new state, so that the button shows the cursored emphasis. MTD MSG_META_LOST_SYS_FOCUS_EXCL This procedure is called when the window in which this button is located decides that this button does not have the focus exclusive. MTD MSG_VIS_LOST_GADGET_EXCL HandleMem losing of gadget exclusive. We MUST release any gadget exclusive if we get this method, for it is used both for the case of the grab being given to another gadget & when a window on which this gadget sits is being closed. MTD MSG_META_GAINED_DEFAULT_EXCL This method is sent by the parent window (see OpenWinGupQuery) when it decides that this GenTrigger should have the default exclusive. INT CallMethodIfApplyOrReset Calls passed method on itself if apply or reset button. MTD MSG_SPEC_NOTIFY_ENABLED We intercept these methods here to make sure that the button redraws and that we grab or release the master default exclusive for the window. MTD MSG_SPEC_NOTIFY_NOT_ENABLED We intercept these methods here to make sure that the button redraws and that we grab or release the master default exclusive for the window. INT FinishChangeEnabled We intercept these methods here to make sure that the button redraws and that we grab or release the master default exclusive for the window. INT OLButtonResetMasterDefault Releases "Master Default" exclusive, if this button has it. MTD MSG_VIS_DRAW Draw the button INT UpdateButtonState Note which specific state flags have been set in order to use this information for later drawing optimizations. Also, notes the enabled/disabled state. INT OLButtonDrawMoniker Draw the moniker for this button. MTD MSG_VIS_OPEN Called when the button is to be made visible on the screen. Subclassed to check if this is a button in the title bar that required rounded edges. INT OLButtonReleaseMouseGrab This procedure makes sure that this button has released the mouse grab (exclusive). INT OLButtonReleaseDefaultExclusive This procedure releases the default exclusive for this button. The window will send a method to itself on the queue, so that if no other button grabs the default exclusive IMMEDIATELY, the master default for the window will grab it. INT OLButtonReleaseAllGrabs Intercept this method here to ensure that this button has released any grabs it may have. MTD MSG_SPEC_SET_LEGOS_LOOK Set the hints on a button according to the legos look requested, after removing the hints for its previous look. These hints are stored in tables that each different SpecUI will change according to the legos looks they support. MTD MSG_SPEC_GET_LEGOS_LOOK Get the legos look of an object MTD MSG_OL_BUTTON_SET_DRAW_STATE_UNKNOWN This procedure marks the button as invalid so that next time it is drawn, no optimizations are attempted. MTD MSG_OL_BUTTON_SET_BORDERED Makes the button bordered/unbordered. This makes it possible for popup menus to broadcast a notification to all its button children to draw their borders when the window is pinned. MTD MSG_SPEC_CHANGE Does a "change" for this button. REVISION HISTORY: Name Date Description ---- ---- ----------- dlitwin 10/10/94 Broken out of copenButton.asm DESCRIPTION: $Id: copenButtonCommon.asm,v 1.2 98/03/11 05:44:50 joon Exp $ ------------------------------------------------------------------------------@ CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonDrawNOWIfNewState CALLED BY: OLButtonGenActivate OLButtonMouse OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW DESCRIPTION: Draw this button if its state has changed since the last draw. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ ;IMPORTANT: THIS IS NOT A DYNAMIC METHOD HANDLER, SO DO NOT EXPECT DS:DI. OLButtonDrawNOWIfNewState method OLButtonClass, MSG_OL_BUTTON_REDRAW call OLButtonDetermineIfNewState jz done ;skip if no state change... call OpenDrawObject ;draw object and save new state done: ret OLButtonDrawNOWIfNewState endp OLButtonDetermineIfNewState proc near mov di, ds:[si] add di, ds:[di].Vis_offset mov al, {byte}ds:[di].OLBI_specState ;get new state xor al, ds:[di].OLBI_optFlags ;compare to old state call OpenCheckIfKeyboard ;no keyboard, ignore cursored jnc dontCheckCursored ; state. -cbh if _OL_STYLE ;-------------------------------------------------------------- test al, mask OLBSS_BORDERED or \ mask OLBSS_DEPRESSED or \ mask OLBSS_DEFAULT or \ mask OLBSS_SELECTED endif ;-------------------------------------------------------------- if _CUA_STYLE ;-------------------------------------------------------------- ;CUA/Motif: if inside a menu, or if is a menu button, ignore the ;cursored flag, because we set the BORDERED/DEPRESSED flag to show ;something as cursored. (Don't ignore if a popup list, with a ;OLBSS_MENU_DOWN_MARK.) test ds:[di].OLBI_specState, mask OLBSS_IN_MENU or \ mask OLBSS_MENU_RIGHT_MARK jz 10$ ;skip if standard button... dontCheckCursored: ;menu button, or button in menu: test al, mask OLBSS_BORDERED or \ mask OLBSS_DEPRESSED or \ mask OLBSS_DEFAULT or \ mask OLBSS_SELECTED jmp short 20$ 10$: ;standard button test al, mask OLBSS_BORDERED or \ mask OLBSS_DEPRESSED or \ mask OLBSS_CURSORED or \ mask OLBSS_DEFAULT or \ mask OLBSS_SELECTED 20$: endif ;-------------------------------------------------------------- ret OLButtonDetermineIfNewState endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonDrawLATERIfNewState DESCRIPTION: Redraw the button, delaying the update via the UI queue, or until the next EXPOSE, whichever is appropriate. CALLED BY: OLButtonGainedFocusExcl OLButtonLostFocusExcl OLButtonGainedDefaultExclusive OLButtonLostDefaultExclusive PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 6/90 initial version ------------------------------------------------------------------------------@ OLButtonDrawLATERIfNewStateFar proc far call OLButtonDrawLATERIfNewState ret OLButtonDrawLATERIfNewStateFar endp OLButtonDrawLATERIfNewState proc near call OLButtonDetermineIfNewState jz exit ;if there is a MSG_META_EXPOSED event pending for this window, ;just add this button to the invalid region. Sending a method ;to the queue will not help, because when it arrives, its drawing ;may be clipped. push cx, dx, bp push si call VisQueryWindow ;find Window for this OLWinClass or di, di ;is it realized yet? jz useManual ;skip if not... mov si, WIT_FLAGS ;pass which info we need back call WinGetInfo ;get info on Window structure test al, mask WRF_EXPOSE_PENDING ;will a MSG_META_EXPOSED arrive? jz useManual ;skip if not... pop si call OpenGetLineBounds push si clr bp ;region is rectangular clr si call WinInvalReg afterInval:: pop si jmp short done useManual: pop si mov ax, MSG_OL_BUTTON_REDRAW mov bx, ds:[LMBH_handle] mov di, mask MF_FORCE_QUEUE or mask MF_INSERT_AT_FRONT call ObjMessage done: pop cx, dx, bp exit: ret OLButtonDrawLATERIfNewState endp CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonPtr DESCRIPTION: HandleMem pointer movement across button CALLED BY: MSG_META_PTR PASS: ds:*si - instance data cx, dx - location bp - [ UIFunctionsActive | buttonInfo ] ax - message # RETURN: ax = MouseReturnFlags MRF_PROCESSED - event was process by the button MRF_REPLAY - event was released by the button DESTROYED: bx, cx, dx, di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 4/89 Initial version ------------------------------------------------------------------------------@ OLButtonPtr method OLButtonClass, MSG_META_PTR ;if not in a menu and we do not yet have the mouse grab, it means that ;the mouse is simply dragging across this control. IGNORE this event. mov di, ds:[si] add di, ds:[di].Vis_offset ; ds:di = SpecificInstance test ds:[di].OLBI_specState, mask OLBSS_IN_MENU \ or mask OLBSS_IN_MENU_BAR jz stdButton ;skip if in not in menu... ;CUA/Motif: a menu button can be selected even if the mouse button ;is not pressed. Allow mouse to slide over control without un-selecting ;button. CUAS < test bp, (mask UIFA_SELECT) shl 8 ;are we dragging? > CUAS < jz returnProcessed ;skip if not... > jmp short handlePtrEvent stdButton: ;want to avoid grabbing the mouse if we don't own it. test ds:[di].OLBI_specState, mask OLBSS_HAS_MOUSE_GRAB jz returnProcessed ;if do not have grab, ignore event... handlePtrEvent: if BUBBLE_HELP mov ax, MSG_META_PTR endif GOTO OLButtonMouse ;process normally returnProcessed: ;we are not dragging: we are just sliding across the button. ;no need to upset the button state. mov ax, mask MRF_PROCESSED or mask MRF_CLEAR_POINTER_IMAGE ret OLButtonPtr endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonRelease DESCRIPTION: HandleMem SELECT or FEATURES release on button. The Trigger OD is then sent off. CALLED BY: MSG_META_END_SELECT PASS: *ds:si - instance data cx, dx - mouse location bp - [ UIFunctionsActive | buttonInfo ] ax - message # RETURN: ax = MouseReturnFlags MRF_PROCESSED - event was process by the button MRF_REPLAY - event was released by the button DESTROYED: bx, cx, dx, di REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 4/89 Initial version ------------------------------------------------------------------------------@ OLButtonRelease method OLButtonClass, MSG_META_END_SELECT if BUBBLE_HELP ; ; clear bubble help, if any ; push cx, dx, bp mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call OpenCheckBubbleMinTime jc leaveHelp call OLButtonDestroyBubbleHelp leaveHelp: mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_HAS_MOUSE_GRAB jnz leaveGrab call VisReleaseMouse leaveGrab: ; ; if disabled, return processed -- we only got here because ; of bubble help (normal case doesn't grab mouse for disabled ; button) ; call OpenButtonCheckIfFullyEnabled pop cx, dx, bp jc continueProcessing mov ax, mask MRF_PROCESSED or mask MRF_CLEAR_POINTER_IMAGE ret continueProcessing: endif test bp, (mask UIFA_IN) shl 8 ; see if in bounds jz 50$ ;skip if not... ;SELECT or MENU ended within button: trigger! push cx, dx, bp clr cx ;assume not double press mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_moreAttrs, mask OLBMA_WAS_DOUBLE_CLICKED jz 10$ and ds:[di].OLBI_moreAttrs, not mask OLBMA_WAS_DOUBLE_CLICKED dec cx ;else mark as a double press 10$: call OpenDoClickSound ; doing sound, make a noise ; ; New, exciting code to sleep a little if we're in pen mode, so ; we can see an inverting button. ; call SysGetPenMode ; ax = TRUE if penBased tst ax jz 20$ push ds mov ax, segment olButtonInvertDelay mov ds, ax mov ax, ds:[olButtonInvertDelay] pop ds call TimerSleep 20$: ; only called once from jz above call OLButtonActivate if SHORT_LONG_TOUCH call EndShortLongTouch ; send out short/long message if needed endif pop cx, dx, bp 50$: if BUBBLE_HELP mov ax, MSG_META_END_SELECT endif GOTO OLButtonMouse OLButtonRelease endp CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonActivate DESCRIPTION: This routine sends the ActionDescriptor for this trigger. CALLED BY: PASS: *ds:si = instance data for object cl -- non-zero if from user double-click RETURN: nothing DESTROYED: ax, bx, cx, dx, di, bp PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 6/90 initial version ------------------------------------------------------------------------------@ OLButtonActivate proc far uses si, es .enter mov ax, MSG_GEN_TRIGGER_SEND_ACTION ;assume is GenTrigger mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_fixedAttrs, mask OLBFA_IMMEDIATE_ACTION pushf ;save results ;if this OLButtonClass object was fabricated to open a command window ;or summons, then send MSG_OL_POPUP_OPEN directly to the window. mov di, ds:[si] ;point to instance data les di, ds:[di].MB_class ;set es:di = class table for object cmp es:[di].Class_masterOffset, offset Vis_offset ;is the specific part the highest- ;level master class for this object? jne sendMethod ;skip if not (has generic part)... mov di, ds:[si] add di, ds:[di].Vis_offset ;make sure that OLSetting is handling activation itself. EC < test ds:[di].OLBI_specState, mask OLBSS_SETTING > EC < ERROR_NZ OL_ERROR > mov si, ds:[di].OLBI_genChunk ;si = chunk handle of window ;(is in same ObjectBlock) mov ax, MSG_OL_POPUP_ACTIVATE ;bring up command window sendMethod: popf ;get IS_IMMEDIATE test results mov di, mask MF_FORCE_QUEUE or mask MF_INSERT_AT_FRONT or \ mask MF_FIXUP_DS jz afterCheck ;skip if not immediate... ;this is an IMMEDIATE ACTION trigger: use MF_CALL. mov di, mask MF_CALL or mask MF_FIXUP_DS afterCheck: mov bx, ds:[LMBH_handle] call ObjMessage .leave ret OLButtonActivate endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonMouse DESCRIPTION: Process current ptr & function state to determine whether a button should be up or down CALLED BY: MSG_META_START_SELECT OLButtonPtr OLButtonRelease PASS: ds:*si - OLButton object cx, dx - ptr position bp - [ UIFunctionsActive | buttonInfo ] RETURN: ax = MouseReturnFlags MRF_PROCESSED - event was process by the button MRF_REPLAY - event was released by the button clear - event was ignored by the button DESTROYED: bx, cx, dx, di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 4/89 Initial version ------------------------------------------------------------------------------@ OLButtonStartSelect method OLButtonClass, MSG_META_START_SELECT if SHORT_LONG_TOUCH call StartShortLongTouch ;start short/long touch endif OLButtonMouse label far test bp, (mask UIFA_IN) shl 8 ; see if in bounds jz notInBounds ;if not in bounds, then should be up. ; is SELECT function still on? test bp, (mask UIFA_SELECT) shl 8 jz short inBoundsNotPressed inBoundsAndPressed: ;Button has been pressed on. Before depressing it, see if enabled call OpenButtonCheckIfFullyEnabled if BUBBLE_HELP jc continueProcessing cmp ax, MSG_META_START_SELECT jne notStartSelect mov ax, TEMP_OL_BUTTON_BUBBLE_HELP_JUST_CLOSED call ObjVarDeleteData jnc notStartSelect ; found and deleted call VisGrabMouse call OLButtonCreateBubbleHelp notStartSelect: jmp returnProcessed continueProcessing: else jnc returnProcessed ;skip if not enabled... endif ; Set double-click flag if appropriate test bp, mask BI_DOUBLE_PRESS jz 1$ mov di, ds:[si] add di, ds:[di].Vis_offset or ds:[di].OLBI_moreAttrs, mask OLBMA_WAS_DOUBLE_CLICKED 1$: if _CASCADING_MENUS ; if this button is in a menu and is in the process of being selected ; (i.e., it is not yet depressed and/or bordered, but it is going to ; be since it is calling OLButtonSaveStateSetBorderedAndOrDepressed ; next) then send a message to the menu window indicating that this ; button (since it is just a trigger) will not cause the menu to ; cascade. mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_IN_MENU jz dontSendMessage test ds:[di].OLBI_specState, mask OLBSS_BORDERED or \ mask OLBSS_DEPRESSED jnz dontSendMessage push cx ; Flags passed in cl: Not cascading, don't start grab. clr cx call OLButtonSendCascadeModeToMenu pop cx dontSendMessage: endif ;_CASCADING_MENUS ;if this button is not yet CURSORED or HAS_MOUSE_GRAB-ed, then save ;the current bordered and depressed state, and set DEPRESSED and/or ;BORDERED as required by specific UI. call OLButtonSaveStateSetBorderedAndOrDepressed ;grab gadget, focus, keyboard, mouse, and default exclusives ;(As we gain the focus exclusive, will set the OLBSS_CURSORED flag, ;and redraw the button.) stc ;set flag: grab everything call OLButtonGrabExclusives ;in case we already had the focus, check draw state flags again ;(DO NOT DRAW USING THE QUEUE! Must draw button for quick mouse ;press-release sequences) call OLButtonDrawNOWIfNewState ;redraw button if have new state jmp short returnProcessed inBoundsNotPressed: ;now reset the BORDERED and or DEPRESSED status to normal and REDRAW ;(DO NOT DRAW USING THE QUEUE! Must draw button for quick mouse ;press-release sequences) call OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW call OLButtonReleaseMouseGrab jmp short returnProcessed ;---------------------------------------------------------------------- notInBounds: ;is SELECT function still on? test bp, (mask UIFA_SELECT) shl 8 jz short notInBoundsNotPressed notInBoundsIsPressed: ;the user has dragged the mouse out of the button: draw as ;un-depressed, but KEEP THE MOUSE GRAB to prevent interacting with ;other controls (if is not in a menu or menu bar) mov di, ds:[si] add di, ds:[di].Vis_offset ; ds:di = SpecificInstance test ds:[di].OLBI_specState, mask OLBSS_IN_MENU or \ mask OLBSS_IN_MENU_BAR jnz isMenuNotInBoundsNotPressed ;skip if in menu or menu bar... ;now reset the BORDERED and or DEPRESSED status to normal and REDRAW ;(DO NOT DRAW USING THE QUEUE! Must draw button for quick mouse ;press-release sequences) call OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW returnProcessed: mov ax, mask MRF_PROCESSED or mask MRF_CLEAR_POINTER_IMAGE ; Say processed if ptr in bounds ret isMenuNotInBoundsNotPressed: ;moving off of a menu item: turn off cursored also, so that when ;we get a LOST_FOCUS, we don't redraw again. mov di, ds:[si] add di, ds:[di].Vis_offset ANDNF ds:[di].OLBI_specState, not (mask OLBSS_CURSORED) notInBoundsNotPressed: ;now reset the BORDERED and or DEPRESSED status to normal and REDRAW ;(DO NOT DRAW USING THE QUEUE! Must draw button for quick mouse ;press-release sequences) call OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW call OLButtonReleaseMouseGrab ;returns carry set if released grab jnc returnProcessed ;skip if did not have grab... ;(i.e. already un-depressed) ;we just released the grab: replay this event mov ax, mask MRF_REPLAY ; Replay this one, since we didn't ret OLButtonStartSelect endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonStartMoveCopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Start bubble help on MOVE_COPY CALLED BY: MSG_META_START_MOVE_COPY PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # cx = X position of mouse dx = X position of mouse bp low = ButtonInfo bp high = UIFunctionsActive RETURN: ax = MouseReturnFlags DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- joon 11/1/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonStartMoveCopy method dynamic OLButtonClass, MSG_META_START_MOVE_COPY mov ax, TEMP_OL_BUTTON_BUBBLE_HELP_JUST_CLOSED call ObjVarDeleteData jnc callsuper ; found and deleted call VisGrabMouse call OLButtonCreateBubbleHelp callsuper: mov di, offset OLButtonClass GOTO ObjCallSuperNoLock OLButtonStartMoveCopy endm endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonEndMoveCopy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: End bubble help on MOVE_COPY CALLED BY: MSG_META_END_MOVE_COPY PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # cx = X position of mouse dx = X position of mouse bp low = ButtonInfo bp high = UIFunctionsActive RETURN: ax = MouseReturnFlags DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- joon 11/1/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonEndMoveCopy method dynamic OLButtonClass, MSG_META_END_MOVE_COPY push ax mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call OpenCheckBubbleMinTime pop ax jc leaveHelp call OLButtonDestroyBubbleHelp leaveHelp: call VisReleaseMouse mov di, offset OLButtonClass GOTO ObjCallSuperNoLock OLButtonEndMoveCopy endm endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonSendCascadeModeToMenuFar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calls OLButtonSendCascadeModeToMenu CALLED BY: OLItemMouse PASS: cl = OLMenuWinCascadeModeOptions OMWCMO_CASCADE True=Enable/False=Disable cascade mode. OMWCMO_START_GRAB If TRUE, will take the grabs and take the gadget exclusive after setting the cascade mode. if OMWCMO_CASCADE = TRUE ^ldx:bp = optr to submenu else dx, bp are ignored *ds:si = button object RETURN: Nothing DESTROYED: cx, di SIDE EFFECTS: WARNING: This routine MAY resize LMem and/or object blocks, moving them on the heap and invalidating stored segment pointers and current register or stored offsets to them. PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- JimG 5/ 3/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if _CASCADING_MENUS OLButtonSendCascadeModeToMenuFar proc far call OLButtonSendCascadeModeToMenu ret OLButtonSendCascadeModeToMenuFar endp endif ;_CASCADING_MENUS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonSendCascadeModeToMenu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Packages up a MSG_MO_MW_CASCADE_MODE message and sends it to the menu window object. CALLED BY: OLButtonMouse, OLMenuButtonHandleEvent, OLMenuButtonHandleMenuFunction, OLButtonSendCascadeModeToMenuFar PASS: cl = OLMenuWinCascadeModeOptions OMWCMO_CASCADE True=Enable/False=Disable cascade mode. OMWCMO_START_GRAB If TRUE, will take the grabs and take the gadget exclusive after setting the cascade mode. if OMWCMO_CASCADE = TRUE ^ldx:bp = optr to submenu else dx, bp are ignored *ds:si = button object RETURN: Nothing DESTROYED: cx, di SIDE EFFECTS: WARNING: This routine MAY resize LMem and/or object blocks, moving them on the heap and invalidating stored segment pointers and current register or stored offsets to them. PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- JimG 4/22/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if _CASCADING_MENUS OLButtonSendCascadeModeToMenu proc near uses ax,bx .enter if ERROR_CHECK ;If ^ldx:bp should be valid, then ensure that it is valid and that ;it points to an OLMenuWinClass object. ; * * * DESTROYS: ax, bx, di. DS may be fixed up. * * * test cl, mask OMWCMO_CASCADE jz skipTest ; not cascading, skip this push cx, dx, bp, si movdw bxsi, dxbp ; ensure object has been built out ; ^lbx:si points to object passed in as ^ldx:bp mov di, mask MF_CALL or mask MF_FIXUP_DS mov ax, MSG_META_DUMMY call ObjMessage ; Destroys: ax, cx, dx, bp ; check to be sure it is an OLMenuWinClass object mov cx, segment OLMenuWinClass mov dx, offset OLMenuWinClass mov di, mask MF_CALL or mask MF_FIXUP_DS mov ax, MSG_META_IS_OBJECT_IN_CLASS call ObjMessage ; Destroys: ax, cx, dx, bp ERROR_NC OL_ERROR ; NOT OLMenuWinClass.. bad. pop cx, dx, bp, si skipTest: endif ;ERROR_CHECK push si mov bx, segment OLMenuWinClass mov si, offset OLMenuWinClass mov ax, MSG_MO_MW_CASCADE_MODE ; cl, and possibly dx & bp, are arguments to this message mov di, mask MF_RECORD call ObjMessage pop si ; restore si for object ptr mov cx, di ; cx <= ClassedEvent mov ax, MSG_VIS_VUP_CALL_OBJECT_OF_CLASS call VisCallParentEnsureStack ; MSG_MO_MW_CASCADE_MODE destroys ax, cx .leave ret OLButtonSendCascadeModeToMenu endp endif ;_CASCADING_MENUS COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonSaveStateSetBorderedAndOrDepressed DESCRIPTION: This procedure makes sure that this GenTrigger is drawn as depressed, which depending upon the specific UI might mean DEPRESSED (blackened) and/or BORDERED. CALLED BY: OLButtonMouse OLButtonActivate PASS: *ds:si = instance data for object RETURN: ds, si, cx, dx, bp = same DESTROYED: bx, di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 6/90 initial version ------------------------------------------------------------------------------@ OLButtonSaveStateSetBorderedAndOrDepressed proc far ;see if already interacting with this button mov di, ds:[si] add di, ds:[di].Vis_offset if FOCUSED_GADGETS_ARE_INVERTED test ds:[di].OLBI_specState, mask OLBSS_DEPRESSED or \ mask OLBSS_HAS_MOUSE_GRAB else test ds:[di].OLBI_specState, mask OLBSS_CURSORED or \ mask OLBSS_HAS_MOUSE_GRAB endif jnz 10$ ;skip if so... ;Before we enforce a new state for the button, save the bordered ;status into OLBI_optFlags so that we can restore when button is ;released (since we don't know if we are in a pinned menu). ;This saves us from all of this conditional logic crap at the end. call OLButtonSaveBorderedAndDepressedStatus ;does not trash bx, ds, si, di 10$: ;first let's decide which of the DEPRESSED and BORDERED flags ;we are dealing with. Start by assuming this trigger is inside ;a normal window: ; OPEN_LOOK: assume B, set D ; MOTIF: assume B, set D ; PM: assume B, set D ; CUA: assume B, set D ; RUDY: assume B if FOCUSED_GADGETS_ARE_INVERTED clr bx else mov bx, mask OLBSS_DEPRESSED ;bx = flags to set endif test ds:[di].OLBI_specState, mask OLBSS_IN_MENU jz haveFlags ;this trigger is inside a menu: ; OPEN_LOOK: set B, set D ; (OL: if in pinned menu, B will already be set) ; PM: set B, set D ; MOTIF: set B ; CUA: set D ; MAC: set D ; If _BW_MENU_ITEM_SELECTION_IS_DEPRESSED is TRUE, the buttons ; are depressed if we are in B&W. If _ASSUME_BW_ONLY is true, then ; we do not check confirm that we are in B&W mode, but just assume ; that is the case. --JimG 5/5/94 if _BW_MENU_ITEM_SELECTION_IS_DEPRESSED mov bx, mask OLBSS_DEPRESSED endif ;_BW_MENU_ITEM_SELECTION_IS_DEPRESSED if _BW_MENU_ITEM_SELECTION_IS_DEPRESSED and not _ASSUME_BW_ONLY call OpenCheckIfBW jc haveFlags ; if BW, we are done.. endif ;_BW_MENU_ITEM_SELECTION_IS_DEPRESSED and (not _ASSUME_BW_ONLY) if not _BW_MENU_ITEM_SELECTION_IS_DEPRESSED or (not _ASSUME_BW_ONLY) MO < mov bx, mask OLBSS_BORDERED > ISU < mov bx, mask OLBSS_DEPRESSED > endif ;(not _BW_MENU_ITEM_SELECTION_IS_DEPRESSED) or (not _ASSUME_BW_ONLY) haveFlags: ORNF ds:[di].OLBI_specState, bx done: ret OLButtonSaveStateSetBorderedAndOrDepressed endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW DESCRIPTION: This routine resets the DEPRESSED and BORDERED flags as necessary, and then immediately redraws the button if necessary CALLED BY: OLButtonMouse OLMenuButtonHandleMenuFunction OLMenuButtonHandleDefaultFunction OLMenuButtonGenActivate OLMenuButtonCloseMenu OLMenuButtonLeaveStayUpMode PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ax, bx, cx, dx, di, bp PSEUDO CODE/STRATEGY: DO NOT DRAW USING THE QUEUE! Must draw button for quick mouse press-release sequences. REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 6/90 initial version ------------------------------------------------------------------------------@ OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW proc far ;restore BORDERED state from bit in OLBI_optFlags. mov di, ds:[si] add di, ds:[di].Vis_offset call OLButtonRestoreBorderedAndDepressedStatus call OLButtonDrawNOWIfNewState ;redraw if state changed ret OLButtonRestoreBorderedAndDepressedStatusAndDrawNOW endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonSaveBorderedAndDepressedStatus FUNCTION: OLButtonRestoreBorderedAndDepressedStatus DESCRIPTION: Save the current BORDERED status of this button so that it can be restored. Basically, it is nearly impossible to tell wether a button at rest should be bordered or not, because buttons in pinned menus change. PASS: *ds:si = instance data for object ds:di = Spec instance data for object RETURN: ds, si, di = same DESTROYED: ax PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonSaveBorderedAndDepressedStatus proc near ;copy status flags from lower byte of OLBI_specState to higher byte. ANDNF ds:[di].OLBI_specState, not \ (mask OLBSS_WAS_BORDERED or mask OLBSS_WAS_DEPRESSED) mov al, {byte} ds:[di].OLBI_specState ;get LOW BYTE ANDNF al, mask OLBSS_BORDERED or mask OLBSS_DEPRESSED ORNF {byte} ds:[di].OLBI_specState+1, al ;OR into HIGH BYTE ret OLButtonSaveBorderedAndDepressedStatus endp OLButtonRestoreBorderedAndDepressedStatus proc far ;restore status flags from higher byte of OLBI_specState to lower byte. ANDNF ds:[di].OLBI_specState, not \ (mask OLBSS_BORDERED or mask OLBSS_DEPRESSED) mov al, {byte} ds:[di].OLBI_specState+1 ;get HIGH BYTE ANDNF al, mask OLBSS_BORDERED or mask OLBSS_DEPRESSED ORNF {byte} ds:[di].OLBI_specState, al ;OR into LOW BYTE done: ret OLButtonRestoreBorderedAndDepressedStatus endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonEnsureMouseGrab DESCRIPTION: This procedure makes sure that this button has the mouse grab (exclusive). CALLED BY: OLMenuButtonHandleDefaultFunction OLButtonMouse PASS: *ds:si = instance data for object RETURN: ds, si, cx, dx, bp = same DESTROYED: di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonEnsureMouseGrab proc near mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_HAS_MOUSE_GRAB jnz done ;skip if already have it... ORNF ds:[di].OLBI_specState, mask OLBSS_HAS_MOUSE_GRAB ;set bit so we release later call VisGrabMouse ;Grab the mouse for this button done: ret OLButtonEnsureMouseGrab endp CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonGrabExclusives DESCRIPTION: This procedure grabs some exclusives for the button object. Regardless of the carry flag, the gadget and default exclusives are grabbed. CALLED BY: OLButtonMouse PASS: *ds:si = instance data for object carry set to grab focus, mouse, and keyboard grab also RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonGrabExclusives proc near pushf if _CUA_STYLE ;------------------------------------------------------- ;CUA: if this GenTrigger is not marked as the DEFAULT trigger, ;and is not destructive, request the parent window that this ;trigger be given a temporary default exclusive. (When parent window ;sends this button a MSG_META_GAINED_DEFAULT_EXCL, it will pass a flag ;so that this button does not redraw, because we are also taking the ;FOCUS exclusive.) mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_fixedAttrs, mask OLBFA_CAN_BE_TEMP_DEFAULT_TRIGGER jz 10$ ;skip if is destructive... test ds:[di].OLBI_specState, mask OLBSS_IN_MENU or \ mask OLBSS_IN_MENU_BAR or \ mask OLBSS_SYS_ICON jnz 10$ ;skip if default or nasty... mov ax, MSG_VIS_VUP_QUERY mov cx, SVQT_TAKE_DEFAULT_EXCLUSIVE mov bp, ds:[LMBH_handle] ;pass ^lbp:dx = this object mov dx, si call CallOLWin ; call OLWinClass object above us 10$: endif ;-------------------------------------------------------------- ;take gadget exclusive for UI window mov cx, ds:[LMBH_handle] mov dx, si mov ax, MSG_VIS_TAKE_GADGET_EXCL call VisCallParent ;see if we have been called by OLButtonMouse popf jnc done ;skip if only need some exclusives... ;now grab the mouse, BEFORE we grab the focus, because we want the ;OLBSS_HAS_MOUSE_GRAB flag to be set before we gain the focus, ;because we have already saved the BORDERED and DEPRESSED states, ;and don't want to again! call OLButtonEnsureMouseGrab ;grab mouse, if don't have already if _CUA_STYLE ;------------------------------------------------------ ;MOTIF/PM/CUA: ;If this is not a SYS_ICON or menu bar object, take FOCUS exclusive, ;so other UI object will lose cursored emphasis. (Cannot navigate ;to system icons, so don't allow them to take focus) mov di, ds:[si] add di, ds:[di].Vis_offset if _GCM test ds:[di].OLBI_fixedAttrs, mask OLBFA_GCM_SYS_ICON jnz 15$ ;skip if GCM icon (can navigate to it). endif if MENU_BAR_IS_A_MENU ; ; if menu bar is a menu, allow menu bar items to grab focus ; test ds:[di].OLBI_specState, mask OLBSS_SYS_ICON else test ds:[di].OLBI_specState, mask OLBSS_SYS_ICON or \ mask OLBSS_IN_MENU_BAR endif jnz 20$ ;skip if is icon or in menu bar... 15$:: ;see if the FOCUS is currently on a VisText object or GenView object. ;If on either, then DO NOT take the focus. call OpenTestIfFocusOnTextEditObject jnc 20$ ;skip if should not take focus... mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_moreAttrs, mask OLBMA_IN_TOOLBOX jnz 20$ ;in toolbox, do not take focus... ;take the FOCUS exclusive. Also take keyboard exclusive, so will ;receive non-system keyboard shortcuts directly from the Flow Object. call MetaGrabFocusExclLow ;see OLButtonGainedFocusExcl 20$: endif ;-------------------------------------------------------------- done: ret OLButtonGrabExclusives endp CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonGainedSystemFocusExcl DESCRIPTION: This procedure is called when the window in which this button is located decides that this button has the focus exclusive. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonGainedSystemFocusExcl method dynamic OLButtonClass, MSG_META_GAINED_SYS_FOCUS_EXCL if PARENT_CTRLS_INVERTED_ON_CHILD_FOCUS push ax endif if FOCUSED_GADGETS_ARE_INVERTED test ds:[di].OLBI_specState, mask OLBSS_DEPRESSED else test ds:[di].OLBI_specState, mask OLBSS_CURSORED endif jnz done ;skip if already drawn as cursored... if _GCM ;not necessary. EDS 7/12/90 ; test ds:[di].OLBI_fixedAttrs, mask OLBFA_GCM_SYS_ICON ; jnz 10$ ;skip if GCM icon (not menu related).. endif ;if this button is not yet CURSORED, then save the current bordered ;and depressed state, and set DEPRESSED and/or BORDERED as required ;by the specific UI. call OLButtonSaveStateSetCursored ;sets OLBSS_CURSORED 10$: ;grab the gadget and default exclusives clc ;pass flag: nothing else required. call OLButtonGrabExclusives ;NOTE: TRY MOVING THIS LABEL LOWER TO MINIMIZE METHODS SENT done: call OLButtonDrawLATERIfNewState ;send method to self on queue so ;will redraw button if necessary exit: if PARENT_CTRLS_INVERTED_ON_CHILD_FOCUS pop cx mov dx, 1 or (1 shl 8) ;top, bottom margins for invert mov ax, MSG_SPEC_NOTIFY_CHILD_CHANGING_FOCUS call VisCallParent endif ret OLButtonGainedSystemFocusExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonCreateBubbleHelp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create bubble help CALLED BY: OLButtonGainedSystemFocusExcl PASS: *ds:si = OLButtonClass object RETURN: ds:di = OLButtonClass instance data DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Joon 8/ 5/96 Initial version Cassie 3/10/97 Added bubble help delay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonCreateBubbleHelp proc far uses ax,bx,cx,dx,es,bp .enter push ds mov di, segment olBubbleOptions mov ds, di mov cx, ds:[olBubbleHelpDelayTime] ; cx = bubble help delay mov bp, ds:[olBubbleHelpTime] ; bp = bubble help time test ds:[olBubbleOptions], mask BO_HELP pop ds jz done ; CF = 0 call FindBubbleHelp jnc done ; ; At this point, ; ds:bx = ptr to help text ; cx = bubble help delay ; bp = bubble help time ; jcxz noDelay ; open bubble now! push cx mov ax, TEMP_OL_BUTTON_BUBBLE_HELP mov cx, size BubbleHelpData call ObjVarAddData pop cx clr ax mov ds:[bx].BHD_window, ax mov ds:[bx].BHD_borderRegion, ax ; ; start timer ; mov ds:[bx].BHD_timer, 0 ; in case no time out push bx ; save vardata mov al, TIMER_EVENT_ONE_SHOT mov dx, MSG_OL_BUTTON_BUBBLE_DELAY_TIME_OUT mov bx, ds:[LMBH_handle] ; ^lbx:si = object call TimerStart pop di ; ds:di = vardata mov ds:[di].BHD_timer, bx ; save timer handle mov ds:[di].BHD_timerID, ax ; save timer ID done: mov di, ds:[si] ; redeference for lmem moves add di, ds:[di].Vis_offset .leave ret noDelay: mov di, ds:[bx].offset mov bx, ds:[bx].handle call ObjLockObjBlock push bx mov es, ax mov cx, ax mov dx, es:[di] ; cx:dx = bubble help text mov ax, TEMP_OL_BUTTON_BUBBLE_HELP mov bx, MSG_OL_BUTTON_BUBBLE_TIME_OUT call OpenCreateBubbleHelp call VisAddButtonPrePassive pop bx call MemUnlock jmp done OLButtonCreateBubbleHelp endp FindBubbleHelp proc far push si, di mov di, ds:[si] add di, ds:[di].Vis_offset call OpenButtonCheckIfFullyEnabled mov si, ds:[di].OLBI_genChunk mov ax, ATTR_GEN_FOCUS_HELP jc haveFocusHelpType mov ax, ATTR_GEN_FOCUS_DISABLED_HELP call ObjVarFindData jc gotFocusHelp ; found disabled help mov ax, ATTR_GEN_FOCUS_HELP ; no disabled help, try help haveFocusHelpType: call ObjVarFindData ; carry set if found gotFocusHelp: pop si, di ret FindBubbleHelp endp endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonCreateBubbleHelpLow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Really Create bubble help CALLED BY: OLButtonCreateBubbleHelp, OLButtonBubbleDelayTimeOut PASS: *ds:si = OLButtonClass object RETURN: ds:di = OLButtonClass instance data DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Cassie 3/10/97 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonCreateBubbleHelpLow proc near uses ax,bx,cx,dx,es,bp .enter push ds mov di, segment olBubbleOptions mov ds, di mov bp, ds:[olBubbleHelpTime] ; bp = bubble help time pop ds call FindBubbleHelp EC < ERROR_NC -1 > mov di, ds:[bx].offset mov bx, ds:[bx].handle call ObjLockObjBlock push bx mov es, ax mov cx, ax mov dx, es:[di] ; cx:dx = bubble help text mov ax, TEMP_OL_BUTTON_BUBBLE_HELP mov bx, MSG_OL_BUTTON_BUBBLE_TIME_OUT call OpenCreateBubbleHelp call VisAddButtonPrePassive pop bx call MemUnlock mov di, ds:[si] ; redeference for lmem moves add di, ds:[di].Vis_offset .leave ret OLButtonCreateBubbleHelpLow endp endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonDestroyBubbleHelp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Destroy bubble help CALLED BY: OLButtonLostSystemFocusExcl, OLMenuButtonLostFocusExcl PASS: *ds:si = OLButtonClass object RETURN: ds:di = OLButtonClass instance data DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Joon 8/ 5/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonDestroyBubbleHelp proc far uses ax,bx .enter call VisRemoveButtonPrePassive mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call OpenDestroyBubbleHelp mov di, ds:[si] ; rederefence, just in case add di, ds:[di].Vis_offset done: .leave ret OLButtonDestroyBubbleHelp endp endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonBubbleTimeOut %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: bubble time out, close bubble CALLED BY: MSG_OL_BUTTON_BUBBLE_TIME_OUT PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # RETURN: nothing DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 9/27/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonBubbleTimeOut method dynamic OLButtonClass, MSG_OL_BUTTON_BUBBLE_TIME_OUT mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call ObjVarFindData jnc done mov ds:[bx].BHD_timer, 0 call OLButtonDestroyBubbleHelp done: ret OLButtonBubbleTimeOut endm endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonVisClose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: object closing, close bubble CALLED BY: MSG_VIS_CLOSE PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # RETURN: nothing DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 3/19/99 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonVisClose method dynamic OLButtonClass, MSG_VIS_CLOSE push ax mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call ObjVarFindData pop ax jnc done call OLButtonDestroyBubbleHelp done: ; Ensure that we don't still have the mouse grabbed from either ; START_SELECT or START_MOVE_COPY. -dhunter 2/23/2000 call VisReleaseMouse mov di, offset OLButtonClass GOTO ObjCallSuperNoLock OLButtonVisClose endm endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonPrePassiveButton %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: if another click, close bubble help CALLED BY: MSG_META_PRE_PASSIVE_BUTTON PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # bp low = ButtonInfo RETURN: nothing DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 1/12/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonPrePassiveButton method dynamic OLButtonClass, MSG_META_PRE_PASSIVE_BUTTON test bp, mask BI_PRESS jz done call OLButtonDestroyBubbleHelp ; ; prevent re-opening of bubble help ; mov ax, TEMP_OL_BUTTON_BUBBLE_HELP_JUST_CLOSED clr cx call ObjVarAddData mov ax, MSG_META_DELETE_VAR_DATA mov cx, TEMP_OL_BUTTON_BUBBLE_HELP_JUST_CLOSED mov bx, ds:[LMBH_handle] mov di, mask MF_FORCE_QUEUE call ObjMessage done: clr ax ; continue with mouse event ret OLButtonPrePassiveButton endm endif ; BUBBLE_HELP COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonBubbleDelayTimeOut %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: bubble delay time out, open bubble CALLED BY: MSG_OL_BUTTON_BUBBLE_DELAY_TIME_OUT PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # RETURN: nothing DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 9/27/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonBubbleDelayTimeOut method dynamic OLButtonClass, MSG_OL_BUTTON_BUBBLE_DELAY_TIME_OUT mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call ObjVarFindData jnc done mov ds:[bx].BHD_timer, 0 call OLButtonCreateBubbleHelpLow done: ret OLButtonBubbleDelayTimeOut endm endif ; BUBBLE_HELP COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonSaveStateSetCursored DESCRIPTION: This routine tests if the button is pressed already, and if not, saves the button's current bordered and depressed state, and sets the new state, so that the button shows the cursored emphasis. SEE ALSO: OLButtonSaveStateSetBorderedAndOrDepressed CALLED BY: OLButtonGainedFocusExcl PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ax, bx, di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 6/90 initial version ------------------------------------------------------------------------------@ OLButtonSaveStateSetCursored proc near ;see if already interacting with this button mov di, ds:[si] add di, ds:[di].Vis_offset if FOCUSED_GADGETS_ARE_INVERTED test ds:[di].OLBI_specState, mask OLBSS_DEPRESSED or \ mask OLBSS_HAS_MOUSE_GRAB else test ds:[di].OLBI_specState, mask OLBSS_CURSORED or \ mask OLBSS_HAS_MOUSE_GRAB endif jnz 10$ ;skip if so... ;Before we enforce a new state for the button, save the bordered ;status into OLBI_optFlags so that we can restore when button is ;released (since we don't know if we are in a pinned menu). ;This saves us from all of this conditional logic crap at the end. call OLButtonSaveBorderedAndDepressedStatus ;does not trash bx, ds, si, di 10$: ;now set the CURSORED flag if not FOCUSED_GADGETS_ARE_INVERTED ORNF ds:[di].OLBI_specState, mask OLBSS_CURSORED endif ;first let's decide which of the DEPRESSED and BORDERED flags ;first let's decide which of the DEPRESSED and BORDERED flags ;we are dealing with. Start by assuming this trigger is inside ;a normal window: ; OPEN_LOOK: set nothing (CURSORED flag shown independently) ; MOTIF: set nothing (CURSORED flag shown independently) ; PM: set nothing (CURSORED flag shown independently) ; CUA: set nothing (CURSORED flag shown independently) ; RUDY: set DEPRESSED, don't set CURSORED! if FOCUSED_GADGETS_ARE_INVERTED mov bx, mask OLBSS_DEPRESSED else clr bx ;bx = flags to set endif test ds:[di].OLBI_specState, mask OLBSS_IN_MENU jz haveFlags ;this trigger is inside a menu: ; OPEN_LOOK: set B, set D ; (OL: if in pinned menu, B will already be set) ; PM: set B, set D ; MOTIF: set B ; CUA: set D ; If _BW_MENU_ITEM_SELECTION_IS_DEPRESSED is TRUE, the buttons ; are depressed if we are in B&W. If _ASSUME_BW_ONLY is true, then ; we do not check confirm that we are in B&W mode, but just assume ; that is the case. --JimG 5/5/94 if _BW_MENU_ITEM_SELECTION_IS_DEPRESSED mov bx, mask OLBSS_DEPRESSED endif ;_BW_MENU_ITEM_SELECTION_IS_DEPRESSED if _BW_MENU_ITEM_SELECTION_IS_DEPRESSED and not _ASSUME_BW_ONLY call OpenCheckIfBW jc haveFlags ; if BW, we are done.. endif ;_BW_MENU_ITEM_SELECTION_IS_DEPRESSED and (not _ASSUME_BW_ONLY) if not _BW_MENU_ITEM_SELECTION_IS_DEPRESSED or (not _ASSUME_BW_ONLY) MO < mov bx, mask OLBSS_BORDERED > ISU < mov bx, mask OLBSS_DEPRESSED > NOT_MO< mov bx, mask OLBSS_DEPRESSED > endif ;(not _BW_MENU_ITEM_SELECTION_IS_DEPRESSED) or (not _ASSUME_BW_ONLY) haveFlags: ORNF ds:[di].OLBI_specState, bx done: ret OLButtonSaveStateSetCursored endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonLostSystemFocusExcl DESCRIPTION: This procedure is called when the window in which this button is located decides that this button does not have the focus exclusive. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonLostSystemFocusExcl method dynamic OLButtonClass, MSG_META_LOST_SYS_FOCUS_EXCL if PARENT_CTRLS_INVERTED_ON_CHILD_FOCUS push ax endif if FOCUSED_GADGETS_ARE_INVERTED test ds:[di].OLBI_specState, mask OLBSS_DEPRESSED jz done ;skip if already drawn as not cursored ANDNF ds:[di].OLBI_specState, not (mask OLBSS_DEPRESSED) else test ds:[di].OLBI_specState, mask OLBSS_CURSORED jz done ;skip if already drawn as not cursored ANDNF ds:[di].OLBI_specState, not (mask OLBSS_CURSORED) endif ;if not the master default trigger, release the default exclusive ;so that the master default can gain it. call OLButtonReleaseDefaultExclusive ;now reset the BORDERED and or DEPRESSED status to normal and REDRAW mov di, ds:[si] add di, ds:[di].Vis_offset call OLButtonRestoreBorderedAndDepressedStatus ; ; Remove the known drawn state. In keyboard-only systems, the ; cursor interferes with the mnemonic underline, so the entire thing ; should be redrawn. (Changed to happen for all keyboard-only systems.) ; call OpenCheckIfKeyboardOnly jnc 10$ mov di, ds:[si] add di, ds:[di].Vis_offset and ds:[di].OLBI_optFlags, not mask OLBOF_DRAW_STATE_KNOWN 10$: call OLButtonDrawLATERIfNewState ;send method to self on queue so ;will redraw button if necessary done: if PARENT_CTRLS_INVERTED_ON_CHILD_FOCUS pop cx mov dx, 1 or (1 shl 8) ;top, bottom margins for invert mov ax, MSG_SPEC_NOTIFY_CHILD_CHANGING_FOCUS call VisCallParent endif ret OLButtonLostSystemFocusExcl endm COMMENT @---------------------------------------------------------------------- METHOD: OLButtonLostGadgetExcl -- MSG_VIS_LOST_GADGET_EXCL DESCRIPTION: HandleMem losing of gadget exclusive. We MUST release any gadget exclusive if we get this method, for it is used both for the case of the grab being given to another gadget & when a window on which this gadget sits is being closed. PASS: *ds:si - instance data es - segment of MetaClass ax - MSG_VIS_LOST_GADGET_EXCL RETURN: nothing DESTROYED: REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 7/89 Initial version ------------------------------------------------------------------------------@ OLButtonLostGadgetExcl method dynamic OLButtonClass, MSG_VIS_LOST_GADGET_EXCL ;release the mouse grab call OLButtonReleaseMouseGrab ;if this button has the FOCUS, let's assume that it will shortly ;lose the focus, and so OLButtonLostFocusExcl will force it to ;redraw. Otherwise, lets reset the button visually now! if FOCUSED_GADGETS_ARE_INVERTED test ds:[di].OLBI_specState, mask OLBSS_DEPRESSED else test ds:[di].OLBI_specState, mask OLBSS_CURSORED endif jnz done ;skip if not cursored... ;now reset the BORDERED and or DEPRESSED status to normal and REDRAW ;pass ds:di call OLButtonRestoreBorderedAndDepressedStatus call OLButtonDrawLATERIfNewState ;send method to self on queue so ;will redraw button if necessary done: ret OLButtonLostGadgetExcl endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonGainedDefaultExclusive -- MSG_META_GAINED_DEFAULT_EXCL DESCRIPTION: This method is sent by the parent window (see OpenWinGupQuery) when it decides that this GenTrigger should have the default exclusive. PASS: *ds:si = instance data for object ds:di = ptr to intance data es = class segment bp = TRUE if this button should redraw itself, because it did not initiate this GAINED sequence, and is not gaining any other exclusives that would cause it to redraw. RETURN: nothing ALLOWED TO DESTROY: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonGainedDefaultExclusive method static OLButtonClass, MSG_META_GAINED_DEFAULT_EXCL uses bx, di, es ; To comply w/static call requirements .enter ; that bx, si, di, & es are preserved. ; NOTE that es is NOT segment of class call OpenCheckDefaultRings jnc done mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_DEFAULT jnz done ;skip if already have default... ORNF ds:[di].OLBI_specState, mask OLBSS_DEFAULT tst bp ;check flag passed by OpenWinGupQuery jz done ;skip if no need to redraw... call OLButtonDrawLATERIfNewState ;send method to self on queue so ;will redraw button if necessary done: .leave ret OLButtonGainedDefaultExclusive endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonLostDefaultExclusive -- MSG_META_LOST_DEFAULT_EXCL DESCRIPTION: This method is sent by the parent window (see OpenWinGupQuery) when it decides that this GenTrigger should NOT have the default exclusive. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonLostDefaultExclusive method OLButtonClass, MSG_META_LOST_DEFAULT_EXCL call OpenCheckDefaultRings jnc done mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_DEFAULT jz done ;skip if do not have default... ANDNF ds:[di].OLBI_specState, not mask OLBSS_DEFAULT call OLButtonDrawLATERIfNewState ;send method to self on queue so ;will redraw button if necessary done: ret OLButtonLostDefaultExclusive endp CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonNavigate - MSG_SPEC_NAVIGATION_QUERY handler for OLButtonClass DESCRIPTION: This method is used to implement the keyboard navigation within-a-window mechanism. See method declaration for full details. CALLED BY: utility PASS: *ds:si = instance data for object cx:dx = OD of object which originated the navigation method bp = NavigationFlags RETURN: ds, si = same cx:dx = OD of replying object bp = NavigationFlags (in reply) carry set if found the next/previous object we were seeking DESTROYED: ax, bx, es, di PSEUDO CODE/STRATEGY: OLButtonClass handler: 1) If this OLButtonClass object is subclassed GenItem, we should not even get this query. The OLItemGroup should have first received the query, and handled as a leaf node (should not have sent to children). 2) similarly, if this OLButtonClass object is subclassed by OLMenuButtonClass, we should not get this query. 3) Otherwise, this must be a GenTrigger object. As a leaf-node in the subset of the visible tree which is traversed by this query, this object must handle this method by calling a utility routine, passing flags indicating whether or not this object is focusable. (May be trigger in menu bar!) REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonNavigate method OLButtonClass, MSG_SPEC_NAVIGATION_QUERY ;ERROR CHECKING is in OLButtonNavigateCommon ;see if this button is enabled (generic state may come from window ;which is opened by this button) push cx, dx call OLButtonGetGenAndSpecState ;returns dh = VI_attrs ;bx = OLBI_specState if not _KBD_NAVIGATION ;_CR_NAVIGATION might be true, so preserve navigation sequencing. clr dh ;indicate this node is disabled. endif mov cx, bx clr bl ;default: not root-level node, is not ;composite node, is not focusable call OpenCheckIfKeyboard jnc haveFlags ;no keyboard, can't take focus. 4/20/93 test ds:[di].OLBI_moreAttrs, mask OLBMA_IN_TOOLBOX jnz haveFlags ;in toolbox, do not take focus... ; ; If this button is a SYS_ICON (in the header area), then ; indicate that it is not FOCUSABLE. Users can activate it ; using the system menu. ; test cx, mask OLBSS_SYS_ICON jz notSysIcon ;skip if is not a system icon... if not _GCM jmp haveFlags ; it's a system icon else ; _GCM ; ; It's a sys icon. Do something special if it's GCM. ; test ds:[di].OLBI_fixedAttrs, mask OLBFA_GCM_SYS_ICON jz haveFlags ;skip if is not a GCM icon... jnz focusableIfEnabledAndDrawable endif ; _GCM notSysIcon: if not MENU_BAR_IS_A_MENU ; ; if this button has been placed in a menu bar, indicate ; that it is menu related ; test cx, mask OLBSS_IN_MENU_BAR jz focusableIfEnabledAndDrawable ORNF bl, mask NCF_IS_MENU_RELATED endif ;(not MENU_BAR_IS_A_MENU) focusableIfEnabledAndDrawable:: ; ; Set this button as focusable if it is enabled and drawable ; mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].VI_attrs, mask VA_DRAWABLE jz haveFlags ;not drawable, branch call OpenButtonCheckIfFullyEnabled jnc haveFlags ORNF bl, mask NCF_IS_FOCUSABLE haveFlags: ; ; call utility routine, passing flags to indicate that this is ; a leaf node in visible tree, and whether or not this object can ; get the focus. This routine will check the passed NavigationFlags ; and decide what to respond. ; pop cx, dx mov di, ds:[si] ;pass *ds:di = generic object add di, ds:[di].Vis_offset ;which may contain relevant hints mov di, ds:[di].OLBI_genChunk call VisNavigateCommon ret OLButtonNavigate endm COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonBroadcastForDefaultFocus -- MSG_SPEC_BROADCAST_FOR_DEFAULT_FOCUS handler. DESCRIPTION: This broadcast method is used to find the object within a windw which has HINT_DEFAULT_FOCUS{_WIN}. PASS: *ds:si = instance data for object RETURN: ^lcx:dx = OD of object with hint carry set if broadcast handled DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 3/90 initial version ------------------------------------------------------------------------------@ OLButtonBroadcastForDefaultFocus method OLButtonClass, \ MSG_SPEC_BROADCAST_FOR_DEFAULT_FOCUS mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_fixedAttrs, mask OLBFA_DEFAULT_FOCUS jz done ;skip if not... mov cx, ds:[LMBH_handle] mov dx, si clr bp done: ret OLButtonBroadcastForDefaultFocus endm CommonFunctional ends CommonFunctional segment resource COMMENT @---------------------------------------------------------------------- METHOD: OLButtonMakeNotApplyable -- MSG_OL_MAKE_NOT_APPLYALE for OLButtonClass DESCRIPTION: We get this when an apply or reset happens. If this is an APPLY/RESET type trigger, we'll disable it. PASS: *ds:si - instance data es - segment of MetaClass ax - MSG_OL_MAKE_NOT_APPLYABLE RETURN: nothing DESTROYED: bx, si, di, ds, es REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Chris 6/11/90 Initial version ------------------------------------------------------------------------------@ OLButtonMakeApplyable method OLButtonClass, MSG_OL_MAKE_APPLYABLE mov ax, MSG_GEN_SET_ENABLED ;we'll enable if our button GOTO CallMethodIfApplyOrReset OLButtonMakeApplyable endm OLButtonMakeNotApplyable method OLButtonClass, MSG_OL_MAKE_NOT_APPLYABLE mov ax, MSG_GEN_SET_NOT_ENABLED ;else disable it FALL_THRU CallMethodIfApplyOrReset OLButtonMakeNotApplyable endm COMMENT @---------------------------------------------------------------------- ROUTINE: CallMethodIfApplyOrReset SYNOPSIS: Calls passed method on itself if apply or reset button. CALLED BY: OLButtonMakeApplyable, OLButtonMakeNotApplyable PASS: *ds:si -- handle of a button ax -- method to call RETURN: nothing DESTROYED: ax, cx, dx, bp, di, es PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Chris 6/12/90 Initial version ------------------------------------------------------------------------------@ CallMethodIfApplyOrReset proc far push ax mov ax, ATTR_GEN_TRIGGER_INTERACTION_COMMAND call ObjVarFindData pop ax jnc exit ;not found, done VarDataFlagsPtr ds, bx, cx test cx, mask VDF_EXTRA_DATA jz exit cmp {word} ds:[bx], IC_APPLY je callIt cmp {word} ds:[bx], IC_RESET jne exit ;no match, branch callIt: EC < mov di, ds:[si] ;gen should match spec > EC < add di, ds:[di].Vis_offset > EC < cmp si, ds:[di].OLBI_genChunk > EC < ERROR_NE OL_ERROR > mov dl, VUM_NOW ;else call a method on it GOTO ObjCallInstanceNoLock exit: ret CallMethodIfApplyOrReset endp CommonFunctional ends ButtonCommon segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonChangeEnabled -- MSG_SPEC_NOTIFY_ENABLED and MSG_SPEC_NOTIFY_NOT_ENABLED hander. DESCRIPTION: We intercept these methods here to make sure that the button redraws and that we grab or release the master default exclusive for the window. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 3/90 initial version ------------------------------------------------------------------------------@ OLButtonNotifyEnabled method static OLButtonClass, MSG_SPEC_NOTIFY_ENABLED uses bx, di .enter if ALLOW_ACTIVATION_OF_DISABLED_MENUS call OpenButtonCheckIfAlwaysEnabled jc exit endif mov di, offset OLButtonClass CallSuper MSG_SPEC_NOTIFY_ENABLED call FinishChangeEnabled exit:: .leave ret OLButtonNotifyEnabled endm OLButtonNotifyNotEnabled method static OLButtonClass, MSG_SPEC_NOTIFY_NOT_ENABLED uses bx, di .enter if ALLOW_ACTIVATION_OF_DISABLED_MENUS call OpenButtonCheckIfAlwaysEnabled jc exit endif mov di, offset OLButtonClass CallSuper MSG_SPEC_NOTIFY_NOT_ENABLED call FinishChangeEnabled exit:: .leave ret OLButtonNotifyNotEnabled endm FinishChangeEnabled proc near push ax, cx, dx, bp call OLButtonGetGenAndSpecState test dh, mask VA_FULLY_ENABLED jnz isEnabled ;skip if enabled... ;we are setting this button NOT enabled. First: if it is CURSORED, ;force navigation to move onto the next object in this window. mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_CURSORED jz 10$ ;skip if not cursored... mov ax, MSG_GEN_NAVIGATE_TO_NEXT_FIELD call VisCallParent 10$: ;in case this button has HINT_DEFAULT_DEFAULT_ACTION, release the master default ;exclusive for this window. (If this button is not the master default, ;this does nada). Do this BEFORE you release the DEFAULT exclusive. call OLButtonResetMasterDefault ;now, force the release of any other grabs that we might have. ;(If this is the only object in the window, it will still have the ;FOCUS and KBD grabs, so this is really important.) call OLButtonReleaseAllGrabs jmp short done isEnabled: ;this button is now enabled. If it has HINT_DEFAULT_DEFAULT_ACTION, request ;the master default for this window. mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_fixedAttrs, mask OLBFA_MASTER_DEFAULT_TRIGGER ;HINT_DEFAULT_DEFAULT_ACTION present? jz done ;skip if not... mov cx, SVQT_SET_MASTER_DEFAULT mov ax, MSG_VIS_VUP_QUERY mov bp, ds:[LMBH_handle] ; pass ^lbp:dx = this object mov dx, si call CallOLWin ; call OLWinClass object above us done: ;draw object and save new state pop ax, cx, dx, bp clc ;return flag: allows Gen handler exit: ;to continue ret FinishChangeEnabled endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonResetMasterDefault DESCRIPTION: Releases "Master Default" exclusive, if this button has it. CALLED BY: INTERNAL OLButtonChangeEnabled OLButtonVisUnbuildBranch PASS: *ds:si - OLButton RETURN: nothing DESTROYED: ax, cx, dx, bp, di REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 4/92 Initial version ------------------------------------------------------------------------------@ OLButtonResetMasterDefault proc far uses bx, si .enter ; In case this button has HINT_DEFAULT_DEFAULT_ACTION, release the master default ; exclusive for this window. (If this button is not the master default, ; this does nada). ; mov bp, ds:[LMBH_handle] ;pass ^lbp:dx = this OLButton mov dx, si call SwapLockOLWin ; If no OLWin class above us, done. jnc done mov di, ds:[si] add di, ds:[di].Vis_offset cmp ds:[di].OLWI_masterDefault.handle, bp ;set new master OD jne afterResetMasterDefault cmp ds:[di].OLWI_masterDefault.chunk, dx jne afterResetMasterDefault mov cx, SVQT_RESET_MASTER_DEFAULT mov ax, MSG_VIS_VUP_QUERY call ObjCallInstanceNoLock afterResetMasterDefault: call ObjSwapUnlock done: .leave ret OLButtonResetMasterDefault endp COMMENT @---------------------------------------------------------------------- METHOD: OLButtonQueryIsTrigger -- MSG_OL_BUTTON_QUERY_IS_TRIGGER for OLButtonClass DESCRIPTION: Respond to a query from an OLMenuItemGroup object in this visible composite (menu). The query is asking a specific child - are you a trigger (or sub-menu button)? If the sibling is not a trigger, it will not respond to the query, so the carry flag will return cleared. PASS: *ds:si - instance data es - segment of OLButtonClass ax - MSG_OL_BUTTON_QUERY_IS_TRIGGER cx, dx, bp - RETURN: carry - set if child can answer query cx = TRUE / FALSE DESTROYED: cx REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: respond TRUE or FALSE KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 8/89 Initial version ------------------------------------------------------------------------------@ OLButtonQueryIsTrigger method OLButtonClass, MSG_OL_BUTTON_QUERY_IS_TRIGGER mov cx, TRUE ;return = TRUE (is trigger) stc ;return query acknowledged ret OLButtonQueryIsTrigger endm ButtonCommon ends ButtonCommon segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonMetaExposed %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle META_EXPOSED for bubble help window CALLED BY: MSG_META_EXPOSED PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # RETURN: DESTROYED: SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Joon 8/ 2/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if BUBBLE_HELP OLButtonMetaExposed method dynamic OLButtonClass, MSG_META_EXPOSED mov di, cx call GrCreateState call GrBeginUpdate mov ax, TEMP_OL_BUTTON_BUBBLE_HELP call ObjVarFindData jnc endUpdate push si mov si, ds:[bx].BHD_borderRegion mov si, ds:[si] clr ax, bx call GrDrawRegion pop si call FindBubbleHelp jnc endUpdate mov si, ds:[bx].offset mov bx, ds:[bx].handle call ObjLockObjBlock push bx mov ds, ax mov si, ds:[si] ; ds:si = help text mov ax, BUBBLE_HELP_TEXT_X_MARGIN mov bx, BUBBLE_HELP_TEXT_Y_MARGIN clr cx call GrDrawText pop bx call MemUnlock endUpdate: call GrEndUpdate GOTO GrDestroyState OLButtonMetaExposed endm endif ; BUBBLE_HELP COMMENT @---------------------------------------------------------------------- METHOD: OLButtonDraw -- MSG_VIS_DRAW for OLButtonClass DESCRIPTION: Draw the button PASS: *ds:si - instance data es - segment of MetaClass ax - MSG_VIS_DRAW cl - DrawFlags: DF_EXPOSED set if updating bp - GState to use RETURN: nothing DESTROYED: REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: Call the correct draw routine based on the display type: if (black & white) { DrawBWButton(); } else { DrawColorButton(); } KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 2/89 Initial version ------------------------------------------------------------------------------@ OLButtonDraw method dynamic OLButtonClass, MSG_VIS_DRAW ;since this procedure can be called directly when the mouse button ;is released, we want to make sure that the button is realized, ;drawable, and not invalid. ; make sure object is drawable test ds:[di].VI_attrs, mask VA_DRAWABLE jz common ; if not, skip drawing it ; make sure object is realized if _HAS_LEGOS_LOOKS mov bl, ds:[di].OLBI_legosLook push bx endif ; legos looks ;get display scheme data mov di, bp ;put GState in di push cx, dx mov ax, GIT_PRIVATE_DATA call GrGetInfo ;returns ax, bx, cx, dx pop cx, dx if _HAS_LEGOS_LOOKS pop bx endif ;al = color scheme, ah = display type, cl = update flag ANDNF ah, mask DF_DISPLAY_TYPE ;keep display type bits cmp ah, DC_GRAY_1 ;is this a B&W display? mov ch, cl ;Pass DrawFlags in ch mov cl, al ;Pass color scheme in cl ;(ax & bx get trashed) ;CUA & MAC use one handler for Color and B&W draws. push di ;save gstate ; ; pcv is in color, but uses some bw regions :) if not _ASSUME_BW_ONLY MO < jnz color ;skip to draw color button... > ISU < jnz color ;skip to draw color button... > endif bw: ;draw black & white button CallMod DrawBWButton if ( _OL_STYLE or _MOTIF or _ISUI ) and ( not _ASSUME_BW_ONLY ) ;------------- jmp short afterDraw color: ;draw color button if _HAS_LEGOS_LOOKS tst bl jne bw ; if not standard look draw in BW endif CallMod DrawColorButton endif ;-------------------------------------------------------------- ; mov bp, di ; afterDraw: pop bp ;restore gstate common: ;both B&W and Color draws finish here: ;copy generic state data from ;GenTrigger object,set DRAW_STATE_KNOWN call UpdateButtonState mov di, bp ;pass gstate mov al, SDM_100 ;make sure these are correct call GrSetAreaMask ; call GrSetTextMask ; call GrSetLineMask ret OLButtonDraw endp COMMENT @---------------------------------------------------------------------- FUNCTION: UpdateButtonState DESCRIPTION: Note which specific state flags have been set in order to use this information for later drawing optimizations. Also, notes the enabled/disabled state. CALLED BY: OLButtonDraw, OLButtonSpecBuild, OLMenuButtonSetup PASS: ds:*si - object RETURN: ds:di = VisInstance carry set DESTROYED: ax, dx REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 3/89 Initial version ------------------------------------------------------------------------------@ ;see FALL_THROUGH above... UpdateButtonState proc far class OLButtonClass call OLButtonGetGenAndSpecState ;sets bx = OLBI_specState ;dh = VI_attrs ANDNF bl, OLBOF_STATE_FLAGS_MASK ;remove non-state flags, ;including OLBOF_ENABLED call OpenButtonCheckIfFullyEnabled ;use our special routine jnc 10$ ORNF bl, mask VA_FULLY_ENABLED ;or into OLButtonFlags 10$: ORNF bl, mask OLBOF_DRAW_STATE_KNOWN ;set draw state known mov di, ds:[si] add di, ds:[di].Vis_offset ;ds:di = SpecificInstance ANDNF ds:[di].OLBI_optFlags, not (OLBOF_STATE_FLAGS_MASK \ or mask OLBOF_ENABLED) ;clear old state flags ORNF ds:[di].OLBI_optFlags, bl ;and or new flags in stc ret UpdateButtonState endp COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonDrawMoniker DESCRIPTION: Draw the moniker for this button. CALLED BY: DrawColorButton, DrawBWButton PASS: *ds:si = instance data for object di = GState al = DrawMonikerFlags (justification, clipping) cx = OLMonikerAttributes (window mark, cursored) dl = X inset amount dh = Y inset amount RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonDrawMoniker proc far class OLButtonClass ;Draw moniker offset in X and centered in Y sub sp, size OpenMonikerArgs ;make room for args mov bp, sp ;pass pointer in bp EC < call ECInitOpenMonikerArgs ;save IDs on stack for testing > mov ss:[bp].OMA_gState, di ;pass gstate clr ah ;high byte not used mov ss:[bp].OMA_drawMonikerFlags, ax ;pass DrawMonikerFlags mov ss:[bp].OMA_monikerAttrs, cx ;pass OLMonikerAttrs mov bl, dh ;keep y inset here clr dh ;x inset in dx clr bh ;y inset in bx mov ss:[bp].OMA_leftInset, dx ;pass left inset mov ss:[bp].OMA_topInset, bx ;pass top inset if DRAW_SHADOWS_ON_BW_GADGETS or DRAW_SHADOWS_ON_BW_TRIGGERS_ONLY push di mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_SYS_ICON or \ mask OLBSS_IN_MENU_BAR jnz 17$ test ds:[di].OLBI_moreAttrs, mask OLBMA_IN_TOOLBOX jnz 17$ call OpenCheckIfBW jnc 17$ inc dx inc bx 17$: pop di endif mov ss:[bp].OMA_rightInset, dx ;pass right inset mov ss:[bp].OMA_bottomInset, bx ;pass bottom inset mov bx, ds:[si] ;pass gen chunk in es:bx add bx, ds:[bx].Vis_offset ; ; Hack in CGA to make mnemonics appear a little better in menus. ; -cbh 2/15/92 CHECK BW FOR CUA LOOK ; push ds:[bx].VI_bounds.R_top ;is this the worst I've done? push ds:[bx].VI_bounds.R_bottom call OpenCheckIfCGA jnc 8$ ;not CGA, branch call OpenCheckIfKeyboardNavigation ;Check if using kbd mnemonics jnc 8$ ; if not, don't bother test ds:[bx].OLBI_specState, mask OLBSS_IN_MENU_BAR jz 8$ dec ds:[bx].VI_bounds.R_top ;is this the worst I've done? dec ds:[bx].VI_bounds.R_bottom 8$: ; ; Center the moniker if desired. (Not an option in Rudy.) ; test ds:[bx].OLBI_moreAttrs, mask OLBMA_CENTER_MONIKER jz 10$ or ss:[bp].OMA_drawMonikerFlags, J_CENTER shl offset DMF_X_JUST 10$: ; ; Clip monikers if desired. (Always clip if menu down or right marks ; are displayed. -cbh 12/16/92 ; test ds:[bx].OLBI_specState, (mask OLBSS_MENU_DOWN_MARK or \ mask OLBSS_MENU_RIGHT_MARK) jnz 15$ test ds:[bx].OLBI_moreAttrs, (mask OLBMA_CAN_CLIP_MONIKER_WIDTH or \ mask OLBMA_CAN_CLIP_MONIKER_HEIGHT) jz 20$ 15$: or ss:[bp].OMA_drawMonikerFlags, mask DMF_CLIP_TO_MAX_WIDTH 20$: mov bx, ds:[bx].OLBI_genChunk segmov es, ds ;pass *es:bx = generic object ;which holds moniker. call OpenDrawMoniker EC < call ECVerifyOpenMonikerArgs ;make structure still ok > mov bx, ds:[si] ;pass gen chunk in es:bx add bx, ds:[bx].Vis_offset pop ds:[bx].VI_bounds.R_bottom pop ds:[bx].VI_bounds.R_top ;is this the worst I've done? add sp, size OpenMonikerArgs ;dump args ret OLButtonDrawMoniker endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonVisOpen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Called when the button is to be made visible on the screen. Subclassed to check if this is a button in the title bar that required rounded edges. CALLED BY: MSG_VIS_OPEN PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data ds:bx = OLButtonClass object (same as *ds:si) es = segment of OLButtonClass ax = message # bp = 0 if top window, else window for object to open on RETURN: None DESTROYED: ax, cx, dx, bp SIDE EFFECTS: None PSEUDO CODE/STRATEGY: Sadly enough, this seems to be the best place to do this check even though it will be done every time the window is opened. But this will not send a message to the window if the button is not in the title bar, or if it is and the special bit is already set. Also, if the button is in the title bar, but does not have a rounded top corner, then an attribute is set so that we do not have to keep sending messages to the parent window. REVISION HISTORY: Name Date Description ---- ---- ----------- JimG 4/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if _ROUND_THICK_DIALOGS OLButtonVisOpen method dynamic OLButtonClass, MSG_VIS_OPEN push bp ; save bp for call superclass ; See if we have already set this special bit. test ds:[di].OLBI_optFlags, mask OLBOF_HAS_ROUNDED_TOP_CORNER jnz done ; already set, skip this ; See if we have already checked this object, and there is no ; need to continue because it is not special. mov ax, ATTR_OL_BUTTON_NO_ROUNDED_TOP_CORNER call ObjVarFindData jc done ; no rounded corner needed, ; alredy checked ; If this button is a sys icon or has asked to seek the title bar, ; then check if it needs a rounded top corner test ds:[di].OLBI_specState, mask OLBSS_SYS_ICON jnz checkWindow mov ax, ATTR_OL_BUTTON_IN_TITLE_BAR call ObjVarFindData jnc done checkWindow: ; Check with parent to see if this button indeed needs to have ; a rounded top corner. Look up the vis tree till we find on ; object of class OLWinClass ; visual tree until we find an object of class OLWinClass. mov cx, es mov dx, offset OLWinClass ; *ds:si points to self mov ax, MSG_VIS_VUP_FIND_OBJECT_OF_CLASS call ObjCallInstanceNoLock ; Destroys: ax, bp jnc setNoRoundedTopCorner ; no object of such class ; ^lcx:dx = object ptr for parent of correct class mov di, ds:[si] add di, ds:[di].Vis_offset push si ; preserve handle to self mov bx, cx mov si, dx mov cx, ds:[di].VI_bounds.R_left mov dx, ds:[di].VI_bounds.R_right cmp cx, dx je setNoRoundedTopCornerPopSi ; no width, no rounded corner ; bx:si points to parent of class OLWinClass mov di, mask MF_CALL or mask MF_FIXUP_DS mov ax, MSG_OL_WIN_SHOULD_TITLE_BUTTON_HAVE_ROUNDED_CORNER call ObjMessage ; Destroys: ax?, cx, dx, bp pop si ; handle to self jnc setNoRoundedTopCorner ; Doesn't need rounded corner ; Should have a rounded corner! mov di, ds:[si] add di, ds:[di].Vis_offset ornf ds:[di].OLBI_optFlags, mask OLBOF_HAS_ROUNDED_TOP_CORNER tst ax jz done ; right corner, done. mov ax, ATTR_OL_BUTTON_ROUNDED_TOP_LEFT_CORNER clr cx ; no data call ObjVarAddData done: ; Call superclass pop bp ; restore arg for superclass mov ax, MSG_VIS_OPEN mov di, offset OLButtonClass GOTO ObjCallSuperNoLock ; <= RETURN setNoRoundedTopCornerPopSi: pop si ; jumped before we could pop ; Set the no rounded top corner attribute, and then exit. setNoRoundedTopCorner: mov ax, ATTR_OL_BUTTON_NO_ROUNDED_TOP_CORNER clr cx ; no data call ObjVarAddData jmp done OLButtonVisOpen endm endif ;_ROUND_THICK_DIALOGS ButtonCommon ends ButtonCommon segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonReleaseMouseGrab DESCRIPTION: This procedure makes sure that this button has released the mouse grab (exclusive). CALLED BY: OLMenuButtonHandleDefaultFunction OLButtonMouse PASS: *ds:si = instance data for object RETURN: ds, si, di, cx, dx, bp = same carry set if did release mouse grab DESTROYED: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonReleaseMouseGrab proc far mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_specState, mask OLBSS_HAS_MOUSE_GRAB jz done ;skip if not (cy=0)... ANDNF ds:[di].OLBI_specState, not mask OLBSS_HAS_MOUSE_GRAB push di call VisReleaseMouse ;Release the mouse grab pop di stc ;return flag: did release mouse done: ret OLButtonReleaseMouseGrab endp ButtonCommon ends ButtonCommon segment resource COMMENT @---------------------------------------------------------------------- METHOD: OLButtonReleaseDefaultExclusive DESCRIPTION: This procedure releases the default exclusive for this button. The window will send a method to itself on the queue, so that if no other button grabs the default exclusive IMMEDIATELY, the master default for the window will grab it. PASS: *ds:si - instance data es - segment of MetaClass RETURN: nothing DESTROYED: REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 Initial version ------------------------------------------------------------------------------@ OLButtonReleaseDefaultExclusive proc far ;if this GenTrigger is not marked as the DEFAULT trigger, ;and is not destructive, release the teporary default exclusive ;we have been granted. Master Default MUST NOT do this. mov di, ds:[si] add di, ds:[di].Vis_offset test ds:[di].OLBI_fixedAttrs, mask OLBFA_CAN_BE_TEMP_DEFAULT_TRIGGER jz 90$ ;skip if destructive... test ds:[di].OLBI_specState, mask OLBSS_IN_MENU or \ mask OLBSS_IN_MENU_BAR jnz 90$ ;skip if default or nasty... mov ax, MSG_VIS_VUP_QUERY mov cx, SVQT_RELEASE_DEFAULT_EXCLUSIVE mov bp, ds:[LMBH_handle] ;pass ^lbp:dx = this object mov dx, si call CallOLWin ; call OLWinClass object above us 90$: ret OLButtonReleaseDefaultExclusive endp ButtonCommon ends ButtonCommon segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonReleaseAllGrabs DESCRIPTION: Intercept this method here to ensure that this button has released any grabs it may have. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonReleaseAllGrabs proc far ; Release Mouse, Default, & Focus exlcusives, if we have them. ; call OLButtonReleaseMouseGrab call OLButtonReleaseDefaultExclusive call MetaReleaseFocusExclLow ret OLButtonReleaseAllGrabs endp if _HAS_LEGOS_LOOKS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLBSpecSetLegosLook %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the hints on a button according to the legos look requested, after removing the hints for its previous look. These hints are stored in tables that each different SpecUI will change according to the legos looks they support. CALLED BY: MSG_SPEC_SET_LEGOS_LOOK PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data cl = legos look RETURN: carry = set if the look was invalid (new look not set) = clear if the look was valid (new look set) DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- dlitwin 10/10/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ OLBSpecSetLegosLook method dynamic OLButtonClass, MSG_SPEC_SET_LEGOS_LOOK uses ax, cx .enter ; ; Legos users pass in 0 as the base, we really want ; this to map to the a hint, so we up it to 1. ; We will dec it when in SPEC_GET_LEGOS_LOOK inc cl clr bx mov bl, ds:[di].OLBI_legosLook cmp bx, LAST_LEGOS_BUTTON_LOOK jbe validExistingLook clr bx ; make the look valid if it wasn't EC< WARNING WARNING_INVALID_LEGOS_LOOK > validExistingLook: clr ch cmp cx, LAST_LEGOS_BUTTON_LOOK ja invalidNewLook mov ds:[di].OLBI_legosLook, cl ; ; remove hint from old look ; shl bx ; byte value to word table offset mov ax, cs:[legosButtonLookHintTable][bx] tst ax jz noHintToRemove call ObjVarDeleteData ; ; add hints for new look ; noHintToRemove: mov bx, cx shl bx ; byte value to word table offset mov ax, cs:[legosButtonLookHintTable][bx] tst ax jz noHintToAdd clr cx call ObjVarAddData noHintToAdd: clc done: .leave ret invalidNewLook: stc jmp done OLBSpecSetLegosLook endm ; ; Make sure this table matches that in copenButtonCommon.asm. The ; only reason the table is in two places it is that I don't want ; to be bringing in the ButtonCommon resource at build time, and it ; is really a small table. ; Make sure any changes in either table are reflected in the other ; legosButtonLookHintTable label word word 0 ; standard button has no special hint. LAST_LEGOS_BUTTON_LOOK equ ((($ - legosButtonLookHintTable)/(size word)) - 1) CheckHack<LAST_LEGOS_BUTTON_LOOK eq LAST_BUILD_LEGOS_BUTTON_LOOK> COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLBSpecGetLegosLook %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the legos look of an object CALLED BY: MSG_SPEC_GET_LEGOS_LOOK PASS: *ds:si = OLButtonClass object ds:di = OLButtonClass instance data RETURN: cl = legos look DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- dlitwin 10/11/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ OLBSpecGetLegosLook method dynamic OLButtonClass, MSG_SPEC_GET_LEGOS_LOOK .enter mov cl, ds:[di].OLBI_legosLook ; ; We inc'd it in set. dec cl .leave ret OLBSpecGetLegosLook endm endif ; endif of _HAS_LEGOS_LOOKS ButtonCommon ends GadgetCommon segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonSetDrawStateUnknown -- MSG_OL_BUTTON_SET_DRAW_STATE_UNKNOWN DESCRIPTION: This procedure marks the button as invalid so that next time it is drawn, no optimizations are attempted. PASS: *ds:si = instance data for object RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 2/90 initial version ------------------------------------------------------------------------------@ OLButtonSetDrawStateUnknown method dynamic OLButtonClass, \ MSG_OL_BUTTON_SET_DRAW_STATE_UNKNOWN ANDNF ds:[di].OLBI_optFlags, not (mask OLBOF_DRAW_STATE_KNOWN) ret OLButtonSetDrawStateUnknown endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonSetBordered %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Makes the button bordered/unbordered. This makes it possible for popup menus to broadcast a notification to all its button children to draw their borders when the window is pinned. CALLED BY: MSG_OL_BUTTON_SET_BORDERED PASS: *ds:si = instance data for object cx = TRUE to make the button bordered, FALSE to not RETURN: *ds:si = same DESTROYED: ax, bx, cx, dx, bp, es, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Clayton 8/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if _OL_STYLE ;--------------------------------------------------------------- OLButtonSetBordered method dynamic OLButtonClass, \ MSG_OL_BUTTON_SET_BORDERED ANDNF ds:[di].OLBI_specState, not (mask OLBSS_BORDERED) cmp cx, FALSE je 10$ ORNF ds:[di].OLBI_specState, mask OLBSS_BORDERED 10$: mov cl, mask VOF_GEOMETRY_INVALID mov dl, VUM_MANUAL call VisMarkInvalid clc ;keeps VisIfFlagSetCallVisChildren quick ret OLButtonSetBordered endp endif ;--------------------------------------------------------------- COMMENT @---------------------------------------------------------------------- FUNCTION: OLButtonGetGenPart -- MSG_OL_BUTTON_GET_GEN_PART for OLButtonClass DESCRIPTION: This procedure returns the OD of the generic object which is associated with this button. For simple GenTriggers, the generic object is the button itself. For others, the generic object might be a GenInteraction or GenDisplay which has the moniker for the button. PASS: ds:*si - instance data RETURN: ^lcx:dx - OD of generic object DESTROYED: di PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Eric 12/89 initial version ------------------------------------------------------------------------------@ OLButtonGetGenPart method OLButtonClass, MSG_OL_BUTTON_GET_GEN_PART mov di, ds:[si] add di, ds:[di].Vis_offset mov cx, ds:[LMBH_handle] mov dx, ds:[di].OLBI_genChunk ; get chunk holding gen data ret OLButtonGetGenPart endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OLButtonChange -- MSG_SPEC_CHANGE for OLButtonClass %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: Does a "change" for this button. PASS: *ds:si - instance data es - segment of OLButtonClass ax - MSG_SPEC_CHANGE RETURN: nothing ax, cx, dx, bp - destroyed ALLOWED TO DESTROY: bx, si, di, ds, es REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chris 12/ 1/94 Initial Version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GadgetCommon ends
bitwise-trie.asm
andrestorino/computer-organization
0
166009
# SSC-0112 - Organização de Computadores Digitais # # Implementação de uma Bitwise Trie em Assembly MIPS # # Alunos: # <NAME> - 9442688 # <NAME> - 9292970 # <NAME> - ... # <NAME> - ... # # Montado e executado utilizando MARS # # USO DE REGISTRADORES # ╔═════════════╦══════════════════════════╗ # ║ Registrador ║ Usado para ║ # ╠═════════════╬══════════════════════════╣ # ║ $s0-$s4 ║ Opções do Menu ║ # ║ $t0 ║ Input do Menu ║ # ║ $s5 ║ Endereço inicial da Trie ║ # ║ $s6 ║ Contador (Trie) ║ # ║ $s7 ║ Contador (Pilha) ║ # ╚═════════════╩══════════════════════════╝ # # ESTRUTURA DE DADOS # ╔══════════════════════╦══════════════╦═════════╗ # ║ Atributo ║ Tipo de Dado ║ Tamanho ║ # ╠══════════════════════╬══════════════╬═════════╣ # ║ Conteúdo ║ Inteiro ║ 4 bytes ║ # ║ Endereço nó esquerda ║ Ponteiro ║ 4 bytes ║ # ║ Endereço nó direita ║ Ponteiro ║ 4 bytes ║ # ╚══════════════════════╩══════════════╩═════════╝ .data # Strings de menu str_menu: .asciiz "\n\nBITWISE TRIE\n\n 1. Inserção\n 2. Remoção\n 3. Busca\n 4. Visualização\n 5. Sair\n Escolha uma opção (1 a 5): " # Strings das opções do menu str_insert: .asciiz "Digite o binário para inserção: " str_remove: .asciiz "Digite o binário para remoção: " str_search: .asciiz "Digite o binário parra busca: " str_duplicated: .asciiz "Chave repetida. Inserção não permitida.\n" str_invalid: .asciiz "Chave inválida. Insira somente números binários (ou -1 retorna ao menu)\n" str_return: .asciiz "Retornando ao menu.\n" # Strings da visualização str_vis_n: .asciiz "N" str_vis_p1: .asciiz "(" str_vis_p2: .asciiz ")" srt_vis_info_t: .asciiz "T" str_vis_info_nt: .asciiz "NT" str_vis_null: .asciiz "null" # Input chave: .space 64 # 16 dígitos = 64 bytes .text main: # Opções do Menu ficam armazenadas # nos registradores $sX li $s0, 1 # 1 - Inserção li $s1, 2 # 2 - Remoção li $s2, 3 # 3 - Busca li $s3, 4 # 4 - Visualizar li $s4, 5 # 5 - Sair # Alocar vetor que representa a Trie li $v0, 9 # alocar memória la $a0, 12 # 1 nó = 12 bytes syscall # Armazenar endereço inicial da Trie move $s5, $v0 # Funcionalidade de Menu menu: li $v0, 4 # imprimir string la $a0, str_menu syscall li $v0, 5 # ler inteiro syscall move $t0, $v0 # guardar input em $t0 beq $t0, $s0, insert_node # 1 beq $t0, $s1, delete_node # 2 beq $t0, $s2, search_node # 3 beq $t0, $s3, print_trie # 4 beq $t0, $s4, exit # 5 j menu # loop # Funcionalidades da Trie insert_node: li $v0, 4 # imprimir string la $a0, str_insert li $v0, 8 # ler string la $a0, chave # armazenar 'chave' li $a1, 64 # preparar para ler 64 bytes syscall jal check_input j menu delete_node: li $v0, 4 # imprimir string la $a0, str_remove li $v0, 8 # ler string la $a0, chave li $a1, 64 syscall jal check_input j menu search_node: li $v0, 4 # imprimir string la $a0, str_search syscall li $v0, 8 # ler string la $a0, chave li $a1, 64 syscall jal check_input j menu print_trie: li $v0, 4 # imprimir string la $a0, str_vis syscall j menu # Funções auxiliares check_input: # Percorrer string de entrada ($a0 = chave) check_input_loop: # Verificar se bit atual é 0, 1 ou -1 # Imprimir mensagem de erro caso não seja # Voltar para menu caso seja -1 # beq "source", -1, menu check_input_error: li $v0, -1 check_input_pass: jr $ra # retornar exit: li $v0, 4 # imprimir string la $a0, str_exit syscall li $v0, 10 # finalizar execução syscall
resources/scripts/scrape/searchcode.ads
wisdark/amass
2
5626
-- Copyright 2021 <NAME>. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "Searchcode" type = "scrape" function start() set_rate_limit(2) end function vertical(ctx, domain) for i=0,20 do local page, err = request(ctx, {url=build_url(domain, i)}) if (err ~= nil and err ~= "") then log(ctx, "vertical request to service failed: " .. err) break end page = page:gsub("<strong>", "") local ok = find_names(ctx, page, domain) if not ok then break end check_rate_limit() end end function build_url(domain, pagenum) return "https://searchcode.com/?q=." .. domain .. "&p=" .. pagenum end function find_names(ctx, content, domain) local names = find(content, subdomain_regex) if (names == nil or #names == 0) then return false end local found = false for _, name in pairs(names) do if in_scope(ctx, name) then found = true new_name(ctx, name) end end if not found then return false end return true end
examples/stm32f1/bootloader/bootloader.adb
ekoeppen/STM32_Generic_Ada_Drivers
1
12167
<reponame>ekoeppen/STM32_Generic_Ada_Drivers<filename>examples/stm32f1/bootloader/bootloader.adb<gh_stars>1-10 with System.Machine_Code; use System.Machine_Code; with System; use System; with Interfaces; use Interfaces; with STM32_SVD; use STM32_SVD; with Flash; with STM32GD.Board; package body Bootloader is Line : array (Unsigned_32 range 0 .. 47) of Unsigned_8; Write_Addr : Unsigned_32; Count : Unsigned_8; Flash_End : constant Unsigned_32 with Import, Convention => Asm, External_Name => "__flash_end"; Reset_Vector_Address : constant Unsigned_32 := 16#0000_0004#; Bootloader_Address : constant Unsigned_32 := Flash_End - 1536; User_Vector_Address : constant Unsigned_32 := Bootloader_Address - 4; Flash_Segment_Size : constant Unsigned_32 with Import, Convention => Asm, External_Name => "__page_size"; package Board renames STM32GD.Board; package USART renames Board.USART; procedure Erase is Addr : Unsigned_32 := 16#0#; Saved_Vector_Low : Unsigned_16; Saved_Vector_High : Unsigned_16; begin Saved_Vector_Low := Flash.Read (Reset_Vector_Address); Saved_Vector_High := Flash.Read (Reset_Vector_Address + 2); Flash.Unlock; while Addr < Bootloader_Address loop Flash.Erase (Addr); Addr := Addr + Flash_Segment_Size; end loop; Flash.Enable_Write; Flash.Write (Reset_Vector_Address, Saved_Vector_Low); Flash.Write (Reset_Vector_Address + 2, Saved_Vector_High); Flash.Lock; end Erase; function Nibble (N : Unsigned_8) return Unsigned_8 is begin return (if N >= 65 then N - 65 + 10 else N - 48); end Nibble; function From_Hex (I : Unsigned_32) return Unsigned_8 is begin return 16 * Nibble (Line (I)) + Nibble (Line (I + 1)); end From_Hex; procedure Write is Value : Unsigned_16; J : Unsigned_32; begin Flash.Unlock; Flash.Enable_Write; J := 9; for I in Unsigned_32 range 1 .. Unsigned_32 (Count) / 2 loop Value := Unsigned_16 (From_Hex (J)) + 256 * Unsigned_16 (From_Hex (J + 2)); if Write_Addr = Reset_Vector_Address then Flash.Write (User_Vector_Address, Value); elsif Write_Addr = Reset_Vector_Address + 2 then Flash.Write (User_Vector_Address + 2, Value); else Flash.Write (Write_Addr, Value); end if; J := J + 4; Write_Addr := Write_Addr + Unsigned_32 (2); end loop; Flash.Lock; end Write; procedure Read_Lines is Record_Type : Unsigned_8; XON : constant Byte := 17; XOFF : constant Byte := 19; begin loop USART.Transmit (XON); for I in Line'Range loop Line (I) := Unsigned_8 (USART.Receive); exit when Line (I) = 10; end loop; USART.Transmit (XOFF); Count := From_Hex (1); Write_Addr := Unsigned_32 (From_Hex (3)) * 256 + Unsigned_32 (From_Hex (5)); Record_Type := From_Hex (7); case Record_Type is when 16#00# => Write; when 16#80# => Flash.Erase (Write_Addr); when others => null; end case; end loop; end Read_Lines; procedure Start is begin Board.Init; USART.Transmit (Character'Pos ('?')); for J in 1 .. 12 loop for I in 0 .. Unsigned_32'Last loop if USART.Data_Available then while USART.Data_Available loop USART.Transmit (USART.Receive); end loop; Flash.Init; Erase; Read_Lines; end if; end loop; end loop; if Flash.Read (User_Vector_Address) /= 16#FFFF# then -- Asm ("mov #0xffbe, r8", Volatile => True); -- Asm ("mov.b #0x60, &0x56", Volatile => True); -- Asm ("mov.b #0x87, &0x57", Volatile => True); -- Asm ("mov #0x5a00, &0x120", Volatile => True); -- Asm ("br 0(r8)", Volatile => True); null; end if; end Start; end Bootloader;
Transynther/x86/_processed/AVXALIGN/_zr_/i7-8650U_0xd2.log_21829_239.asm
ljhsiun2/medusa
9
92389
<gh_stars>1-10 .global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x15e22, %rsi lea addresses_D_ht+0x14b22, %rdi clflush (%rdi) inc %rbp mov $113, %rcx rep movsb nop nop nop nop nop sub %r13, %r13 lea addresses_normal_ht+0x10822, %rsi nop nop nop sub $13247, %r12 mov $0x6162636465666768, %rcx movq %rcx, %xmm0 movups %xmm0, (%rsi) nop nop nop nop nop sub $19392, %rdi lea addresses_normal_ht+0x19b22, %rcx nop nop and %r11, %r11 movb $0x61, (%rcx) nop nop nop add $60041, %r13 lea addresses_normal_ht+0x2522, %rsi lea addresses_D_ht+0x9822, %rdi xor $47446, %r8 mov $12, %rcx rep movsl inc %rbp lea addresses_D_ht+0xb402, %rdi nop nop and $24153, %r12 movl $0x61626364, (%rdi) nop nop nop xor %rbp, %rbp lea addresses_WT_ht+0x882, %rsi lea addresses_WT_ht+0xb22, %rdi clflush (%rsi) nop nop nop nop nop sub %r13, %r13 mov $42, %rcx rep movsl nop nop nop nop nop cmp $56631, %r12 lea addresses_D_ht+0x1441e, %r12 clflush (%r12) nop cmp %r8, %r8 mov $0x6162636465666768, %rcx movq %rcx, %xmm3 vmovups %ymm3, (%r12) nop inc %r12 lea addresses_D_ht+0xf422, %rsi nop nop nop nop cmp $21610, %r12 movb $0x61, (%rsi) inc %rbp lea addresses_WC_ht+0x1a9a2, %rsi lea addresses_normal_ht+0xe0e2, %rdi nop nop nop inc %r12 mov $11, %rcx rep movsq add $7612, %rcx lea addresses_D_ht+0x126a2, %rsi lea addresses_A_ht+0x19fa2, %rdi nop nop nop dec %r8 mov $70, %rcx rep movsb nop nop nop xor %rcx, %rcx lea addresses_WC_ht+0x1cf6c, %rsi lea addresses_normal_ht+0x1ce22, %rdi nop lfence mov $9, %rcx rep movsb nop nop xor %r8, %r8 lea addresses_A_ht+0xc2de, %rsi lea addresses_UC_ht+0x5222, %rdi clflush (%rdi) nop sub $44553, %r8 mov $20, %rcx rep movsl nop nop nop nop nop sub $37710, %r12 lea addresses_WT_ht+0xa8e2, %rsi nop nop nop xor $32454, %r13 mov $0x6162636465666768, %r8 movq %r8, %xmm2 vmovups %ymm2, (%rsi) nop nop nop nop cmp %r12, %r12 pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %rax push %rcx push %rdx // Faulty Load lea addresses_A+0x16e22, %r12 nop nop nop nop nop sub %rcx, %rcx vmovaps (%r12), %ymm5 vextracti128 $0, %ymm5, %xmm5 vpextrq $0, %xmm5, %rax lea oracles, %r12 and $0xff, %rax shlq $12, %rax mov (%r12,%rax,1), %rax pop %rdx pop %rcx pop %rax pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 1, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 32, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': 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 */
programs/oeis/021/A021136.asm
karttu/loda
0
3968
<reponame>karttu/loda ; A021136: Decimal expansion of 1/132. ; 0,0,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7,5,7 lpb $0,1 mod $0,2 add $1,1 mul $1,7 sub $1,$0 sub $1,$0 lpe
programs/oeis/204/A204269.asm
neoneye/loda
22
103440
<gh_stars>10-100 ; A204269: Symmetric matrix: f(i,j)=floor[(i+j+2)/4]-floor[(i+j)/4], by (constant) antidiagonals. ; 1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 seq $0,204164 ; Symmetric matrix based on f(i,j)=floor[(i+j)/2], by antidiagonals. mod $0,2
Cubical/Data/Sigma/Properties.agda
Edlyr/cubical
0
3951
<reponame>Edlyr/cubical {- Basic properties about Σ-types - Action of Σ on functions ([map-fst], [map-snd]) - Characterization of equality in Σ-types using dependent paths ([ΣPath{Iso,≃,≡}PathΣ], [Σ≡Prop]) - Proof that discrete types are closed under Σ ([discreteΣ]) - Commutativity and associativity ([Σ-swap-*, Σ-assoc-*]) - Distributivity of Π over Σ ([Σ-Π-*]) - Action of Σ on isomorphisms, equivalences, and paths ([Σ-cong-fst], [Σ-cong-snd], ...) - Characterization of equality in Σ-types using transport ([ΣPathTransport{≃,≡}PathΣ]) - Σ with a contractible base is its fiber ([Σ-contractFst, ΣUnit]) -} {-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Data.Sigma.Properties where open import Cubical.Data.Sigma.Base open import Cubical.Core.Everything open import Cubical.Foundations.Prelude open import Cubical.Foundations.Function open import Cubical.Foundations.Isomorphism open import Cubical.Foundations.Equiv open import Cubical.Foundations.Equiv.HalfAdjoint open import Cubical.Foundations.GroupoidLaws open import Cubical.Foundations.Path open import Cubical.Foundations.Transport open import Cubical.Foundations.Univalence open import Cubical.Relation.Nullary open import Cubical.Data.Unit.Base open import Cubical.Reflection.StrictEquiv open Iso private variable ℓ ℓ' ℓ'' : Level A A' : Type ℓ B B' : (a : A) → Type ℓ C : (a : A) (b : B a) → Type ℓ map-fst : {B : Type ℓ} → (f : A → A') → A × B → A' × B map-fst f (a , b) = (f a , b) map-snd : (∀ {a} → B a → B' a) → Σ A B → Σ A B' map-snd f (a , b) = (a , f b) map-× : {B : Type ℓ} {B' : Type ℓ'} → (A → A') → (B → B') → A × B → A' × B' map-× f g (a , b) = (f a , g b) ≡-× : {A : Type ℓ} {B : Type ℓ'} {x y : A × B} → fst x ≡ fst y → snd x ≡ snd y → x ≡ y ≡-× p q i = (p i) , (q i) -- Characterization of paths in Σ using dependent paths module _ {A : I → Type ℓ} {B : (i : I) → A i → Type ℓ'} {x : Σ (A i0) (B i0)} {y : Σ (A i1) (B i1)} where ΣPathP : Σ[ p ∈ PathP A (fst x) (fst y) ] PathP (λ i → B i (p i)) (snd x) (snd y) → PathP (λ i → Σ (A i) (B i)) x y ΣPathP eq i = fst eq i , snd eq i PathPΣ : PathP (λ i → Σ (A i) (B i)) x y → Σ[ p ∈ PathP A (fst x) (fst y) ] PathP (λ i → B i (p i)) (snd x) (snd y) PathPΣ eq = (λ i → fst (eq i)) , (λ i → snd (eq i)) -- allows one to write -- open PathPΣ somePathInΣAB renaming (fst ... ) module PathPΣ (p : PathP (λ i → Σ (A i) (B i)) x y) where open Σ (PathPΣ p) public ΣPathIsoPathΣ : Iso (Σ[ p ∈ PathP A (fst x) (fst y) ] (PathP (λ i → B i (p i)) (snd x) (snd y))) (PathP (λ i → Σ (A i) (B i)) x y) fun ΣPathIsoPathΣ = ΣPathP inv ΣPathIsoPathΣ = PathPΣ rightInv ΣPathIsoPathΣ _ = refl leftInv ΣPathIsoPathΣ _ = refl unquoteDecl ΣPath≃PathΣ = declStrictIsoToEquiv ΣPath≃PathΣ ΣPathIsoPathΣ ΣPath≡PathΣ : (Σ[ p ∈ PathP A (fst x) (fst y) ] (PathP (λ i → B i (p i)) (snd x) (snd y))) ≡ (PathP (λ i → Σ (A i) (B i)) x y) ΣPath≡PathΣ = ua ΣPath≃PathΣ ×≡Prop : isProp A' → {u v : A × A'} → u .fst ≡ v .fst → u ≡ v ×≡Prop pB {u} {v} p i = (p i) , (pB (u .snd) (v .snd) i) -- Characterization of dependent paths in Σ module _ {A : I → Type ℓ} {B : (i : I) → (a : A i) → Type ℓ'} {x : Σ (A i0) (B i0)} {y : Σ (A i1) (B i1)} where ΣPathPIsoPathPΣ : Iso (Σ[ p ∈ PathP A (x .fst) (y .fst) ] PathP (λ i → B i (p i)) (x .snd) (y .snd)) (PathP (λ i → Σ (A i) (B i)) x y) ΣPathPIsoPathPΣ .fun (p , q) i = p i , q i ΣPathPIsoPathPΣ .inv pq .fst i = pq i .fst ΣPathPIsoPathPΣ .inv pq .snd i = pq i .snd ΣPathPIsoPathPΣ .rightInv _ = refl ΣPathPIsoPathPΣ .leftInv _ = refl unquoteDecl ΣPathP≃PathPΣ = declStrictIsoToEquiv ΣPathP≃PathPΣ ΣPathPIsoPathPΣ ΣPathP≡PathPΣ = ua ΣPathP≃PathPΣ -- Σ of discrete types discreteΣ : Discrete A → ((a : A) → Discrete (B a)) → Discrete (Σ A B) discreteΣ {B = B} Adis Bdis (a0 , b0) (a1 , b1) = discreteΣ' (Adis a0 a1) where discreteΣ' : Dec (a0 ≡ a1) → Dec ((a0 , b0) ≡ (a1 , b1)) discreteΣ' (yes p) = J (λ a1 p → ∀ b1 → Dec ((a0 , b0) ≡ (a1 , b1))) (discreteΣ'') p b1 where discreteΣ'' : (b1 : B a0) → Dec ((a0 , b0) ≡ (a0 , b1)) discreteΣ'' b1 with Bdis a0 b0 b1 ... | (yes q) = yes (transport ΣPath≡PathΣ (refl , q)) ... | (no ¬q) = no (λ r → ¬q (subst (λ X → PathP (λ i → B (X i)) b0 b1) (Discrete→isSet Adis a0 a0 (cong fst r) refl) (cong snd r))) discreteΣ' (no ¬p) = no (λ r → ¬p (cong fst r)) module _ {A : Type ℓ} {A' : Type ℓ'} where Σ-swap-Iso : Iso (A × A') (A' × A) fun Σ-swap-Iso (x , y) = (y , x) inv Σ-swap-Iso (x , y) = (y , x) rightInv Σ-swap-Iso _ = refl leftInv Σ-swap-Iso _ = refl unquoteDecl Σ-swap-≃ = declStrictIsoToEquiv Σ-swap-≃ Σ-swap-Iso module _ {A : Type ℓ} {B : A → Type ℓ'} {C : ∀ a → B a → Type ℓ''} where Σ-assoc-Iso : Iso (Σ[ (a , b) ∈ Σ A B ] C a b) (Σ[ a ∈ A ] Σ[ b ∈ B a ] C a b) fun Σ-assoc-Iso ((x , y) , z) = (x , (y , z)) inv Σ-assoc-Iso (x , (y , z)) = ((x , y) , z) rightInv Σ-assoc-Iso _ = refl leftInv Σ-assoc-Iso _ = refl unquoteDecl Σ-assoc-≃ = declStrictIsoToEquiv Σ-assoc-≃ Σ-assoc-Iso Σ-Π-Iso : Iso ((a : A) → Σ[ b ∈ B a ] C a b) (Σ[ f ∈ ((a : A) → B a) ] ∀ a → C a (f a)) fun Σ-Π-Iso f = (fst ∘ f , snd ∘ f) inv Σ-Π-Iso (f , g) x = (f x , g x) rightInv Σ-Π-Iso _ = refl leftInv Σ-Π-Iso _ = refl unquoteDecl Σ-Π-≃ = declStrictIsoToEquiv Σ-Π-≃ Σ-Π-Iso Σ-cong-iso-fst : (isom : Iso A A') → Iso (Σ A (B ∘ fun isom)) (Σ A' B) fun (Σ-cong-iso-fst isom) x = fun isom (x .fst) , x .snd inv (Σ-cong-iso-fst {B = B} isom) x = inv isom (x .fst) , subst B (sym (ε (x .fst))) (x .snd) where ε = isHAEquiv.rinv (snd (iso→HAEquiv isom)) rightInv (Σ-cong-iso-fst {B = B} isom) (x , y) = ΣPathP (ε x , toPathP goal) where ε = isHAEquiv.rinv (snd (iso→HAEquiv isom)) goal : subst B (ε x) (subst B (sym (ε x)) y) ≡ y goal = sym (substComposite B (sym (ε x)) (ε x) y) ∙∙ cong (λ x → subst B x y) (lCancel (ε x)) ∙∙ substRefl {B = B} y leftInv (Σ-cong-iso-fst {A = A} {B = B} isom) (x , y) = ΣPathP (leftInv isom x , toPathP goal) where ε = isHAEquiv.rinv (snd (iso→HAEquiv isom)) γ = isHAEquiv.com (snd (iso→HAEquiv isom)) lem : (x : A) → sym (ε (fun isom x)) ∙ cong (fun isom) (leftInv isom x) ≡ refl lem x = cong (λ a → sym (ε (fun isom x)) ∙ a) (γ x) ∙ lCancel (ε (fun isom x)) goal : subst B (cong (fun isom) (leftInv isom x)) (subst B (sym (ε (fun isom x))) y) ≡ y goal = sym (substComposite B (sym (ε (fun isom x))) (cong (fun isom) (leftInv isom x)) y) ∙∙ cong (λ a → subst B a y) (lem x) ∙∙ substRefl {B = B} y Σ-cong-equiv-fst : (e : A ≃ A') → Σ A (B ∘ equivFun e) ≃ Σ A' B -- we could just do this: -- Σ-cong-equiv-fst e = isoToEquiv (Σ-cong-iso-fst (equivToIso e)) -- but the following reduces slightly better Σ-cong-equiv-fst {A = A} {A' = A'} {B = B} e = intro , isEqIntro where intro : Σ A (B ∘ equivFun e) → Σ A' B intro (a , b) = equivFun e a , b isEqIntro : isEquiv intro isEqIntro .equiv-proof x = ctr , isCtr where PB : ∀ {x y} → x ≡ y → B x → B y → Type _ PB p = PathP (λ i → B (p i)) open Σ x renaming (fst to a'; snd to b) open Σ (equivCtr e a') renaming (fst to ctrA; snd to α) ctrB : B (equivFun e ctrA) ctrB = subst B (sym α) b ctrP : PB α ctrB b ctrP = symP (transport-filler (λ i → B (sym α i)) b) ctr : fiber intro x ctr = (ctrA , ctrB) , ΣPathP (α , ctrP) isCtr : ∀ y → ctr ≡ y isCtr ((r , s) , p) = λ i → (a≡r i , b!≡s i) , ΣPathP (α≡ρ i , coh i) where open PathPΣ p renaming (fst to ρ; snd to σ) open PathPΣ (equivCtrPath e a' (r , ρ)) renaming (fst to a≡r; snd to α≡ρ) b!≡s : PB (cong (equivFun e) a≡r) ctrB s b!≡s i = comp (λ k → B (α≡ρ i (~ k))) (λ k → (λ { (i = i0) → ctrP (~ k) ; (i = i1) → σ (~ k) })) b coh : PathP (λ i → PB (α≡ρ i) (b!≡s i) b) ctrP σ coh i j = fill (λ k → B (α≡ρ i (~ k))) (λ k → (λ { (i = i0) → ctrP (~ k) ; (i = i1) → σ (~ k) })) (inS b) (~ j) Σ-cong-fst : (p : A ≡ A') → Σ A (B ∘ transport p) ≡ Σ A' B Σ-cong-fst {B = B} p i = Σ (p i) (B ∘ transp (λ j → p (i ∨ j)) i) Σ-cong-iso-snd : ((x : A) → Iso (B x) (B' x)) → Iso (Σ A B) (Σ A B') fun (Σ-cong-iso-snd isom) (x , y) = x , fun (isom x) y inv (Σ-cong-iso-snd isom) (x , y') = x , inv (isom x) y' rightInv (Σ-cong-iso-snd isom) (x , y) = ΣPathP (refl , rightInv (isom x) y) leftInv (Σ-cong-iso-snd isom) (x , y') = ΣPathP (refl , leftInv (isom x) y') Σ-cong-equiv-snd : (∀ a → B a ≃ B' a) → Σ A B ≃ Σ A B' Σ-cong-equiv-snd h = isoToEquiv (Σ-cong-iso-snd (equivToIso ∘ h)) Σ-cong-snd : ((x : A) → B x ≡ B' x) → Σ A B ≡ Σ A B' Σ-cong-snd {A = A} p i = Σ[ x ∈ A ] (p x i) Σ-cong-iso : (isom : Iso A A') → ((x : A) → Iso (B x) (B' (fun isom x))) → Iso (Σ A B) (Σ A' B') Σ-cong-iso isom isom' = compIso (Σ-cong-iso-snd isom') (Σ-cong-iso-fst isom) Σ-cong-equiv : (e : A ≃ A') → ((x : A) → B x ≃ B' (equivFun e x)) → Σ A B ≃ Σ A' B' Σ-cong-equiv e e' = isoToEquiv (Σ-cong-iso (equivToIso e) (equivToIso ∘ e')) Σ-cong' : (p : A ≡ A') → PathP (λ i → p i → Type ℓ') B B' → Σ A B ≡ Σ A' B' Σ-cong' p p' = cong₂ (λ (A : Type _) (B : A → Type _) → Σ A B) p p' -- Alternative version for path in Σ-types, as in the HoTT book ΣPathTransport : (a b : Σ A B) → Type _ ΣPathTransport {B = B} a b = Σ[ p ∈ (fst a ≡ fst b) ] transport (λ i → B (p i)) (snd a) ≡ snd b IsoΣPathTransportPathΣ : (a b : Σ A B) → Iso (ΣPathTransport a b) (a ≡ b) IsoΣPathTransportPathΣ {B = B} a b = compIso (Σ-cong-iso-snd (λ p → invIso (equivToIso (PathP≃Path (λ i → B (p i)) _ _)))) ΣPathIsoPathΣ ΣPathTransport≃PathΣ : (a b : Σ A B) → ΣPathTransport a b ≃ (a ≡ b) ΣPathTransport≃PathΣ {B = B} a b = isoToEquiv (IsoΣPathTransportPathΣ a b) ΣPathTransport→PathΣ : (a b : Σ A B) → ΣPathTransport a b → (a ≡ b) ΣPathTransport→PathΣ a b = Iso.fun (IsoΣPathTransportPathΣ a b) PathΣ→ΣPathTransport : (a b : Σ A B) → (a ≡ b) → ΣPathTransport a b PathΣ→ΣPathTransport a b = Iso.inv (IsoΣPathTransportPathΣ a b) ΣPathTransport≡PathΣ : (a b : Σ A B) → ΣPathTransport a b ≡ (a ≡ b) ΣPathTransport≡PathΣ a b = ua (ΣPathTransport≃PathΣ a b) Σ-contractFst : (c : isContr A) → Σ A B ≃ B (c .fst) Σ-contractFst {B = B} c = isoToEquiv isom where isom : Iso _ _ isom .fun (a , b) = subst B (sym (c .snd a)) b isom .inv b = (c .fst , b) isom .rightInv b = cong (λ p → subst B p b) (isProp→isSet (isContr→isProp c) _ _ _ _) ∙ transportRefl _ isom .leftInv (a , b) = ΣPathTransport≃PathΣ _ _ .fst (c .snd a , transportTransport⁻ (cong B (c .snd a)) _) -- a special case of the above module _ (A : Unit → Type ℓ) where ΣUnit : Σ Unit A ≃ A tt unquoteDef ΣUnit = defStrictEquiv ΣUnit snd (λ { x → (tt , x) }) Σ-contractSnd : ((a : A) → isContr (B a)) → Σ A B ≃ A Σ-contractSnd c = isoToEquiv isom where isom : Iso _ _ isom .fun = fst isom .inv a = a , c a .fst isom .rightInv _ = refl isom .leftInv (a , b) = cong (a ,_) (c a .snd b) isEmbeddingFstΣProp : ((x : A) → isProp (B x)) → {u v : Σ A B} → isEquiv (λ (p : u ≡ v) → cong fst p) isEmbeddingFstΣProp {B = B} pB {u = u} {v = v} .equiv-proof x = ctr , isCtr where ctrP : u ≡ v ctrP = ΣPathP (x , isProp→PathP (λ _ → pB _) _ _) ctr : fiber (λ (p : u ≡ v) → cong fst p) x ctr = ctrP , refl isCtr : ∀ z → ctr ≡ z isCtr (z , p) = ΣPathP (ctrP≡ , cong (sym ∘ snd) fzsingl) where fzsingl : Path (singl x) (x , refl) (cong fst z , sym p) fzsingl = isContrSingl x .snd (cong fst z , sym p) ctrSnd : SquareP (λ i j → B (fzsingl i .fst j)) (cong snd ctrP) (cong snd z) _ _ ctrSnd = isProp→SquareP (λ _ _ → pB _) _ _ _ _ ctrP≡ : ctrP ≡ z ctrP≡ i = ΣPathP (fzsingl i .fst , ctrSnd i) Σ≡PropEquiv : ((x : A) → isProp (B x)) → {u v : Σ A B} → (u .fst ≡ v .fst) ≃ (u ≡ v) Σ≡PropEquiv pB = invEquiv (_ , isEmbeddingFstΣProp pB) Σ≡Prop : ((x : A) → isProp (B x)) → {u v : Σ A B} → (p : u .fst ≡ v .fst) → u ≡ v Σ≡Prop pB p = equivFun (Σ≡PropEquiv pB) p ≃-× : ∀ {ℓ'' ℓ'''} {A : Type ℓ} {B : Type ℓ'} {C : Type ℓ''} {D : Type ℓ'''} → A ≃ C → B ≃ D → A × B ≃ C × D ≃-× eq1 eq2 = map-× (fst eq1) (fst eq2) , record { equiv-proof = λ {(c , d) → ((eq1⁻ c .fst .fst , eq2⁻ d .fst .fst) , ≡-× (eq1⁻ c .fst .snd) (eq2⁻ d .fst .snd)) , λ {((a , b) , p) → ΣPathP (≡-× (cong fst (eq1⁻ c .snd (a , cong fst p))) (cong fst (eq2⁻ d .snd (b , cong snd p))) , λ i → ≡-× (snd ((eq1⁻ c .snd (a , cong fst p)) i)) (snd ((eq2⁻ d .snd (b , cong snd p)) i)))}}} where eq1⁻ = equiv-proof (eq1 .snd) eq2⁻ = equiv-proof (eq2 .snd) {- Some simple ismorphisms -} prodIso : ∀ {ℓ ℓ' ℓ'' ℓ'''} {A : Type ℓ} {B : Type ℓ'} {C : Type ℓ''} {D : Type ℓ'''} → Iso A C → Iso B D → Iso (A × B) (C × D) Iso.fun (prodIso iAC iBD) (a , b) = (Iso.fun iAC a) , Iso.fun iBD b Iso.inv (prodIso iAC iBD) (c , d) = (Iso.inv iAC c) , Iso.inv iBD d Iso.rightInv (prodIso iAC iBD) (c , d) = ΣPathP ((Iso.rightInv iAC c) , (Iso.rightInv iBD d)) Iso.leftInv (prodIso iAC iBD) (a , b) = ΣPathP ((Iso.leftInv iAC a) , (Iso.leftInv iBD b)) toProdIso : {B C : A → Type ℓ} → Iso ((a : A) → B a × C a) (((a : A) → B a) × ((a : A) → C a)) Iso.fun toProdIso = λ f → (λ a → fst (f a)) , (λ a → snd (f a)) Iso.inv toProdIso (f , g) = λ a → (f a) , (g a) Iso.rightInv toProdIso (f , g) = refl Iso.leftInv toProdIso b = refl module _ {A : Type ℓ} {B : A → Type ℓ'} {C : ∀ a → B a → Type ℓ''} where curryIso : Iso (((a , b) : Σ A B) → C a b) ((a : A) → (b : B a) → C a b) Iso.fun curryIso f a b = f (a , b) Iso.inv curryIso f a = f (fst a) (snd a) Iso.rightInv curryIso a = refl Iso.leftInv curryIso f = refl unquoteDecl curryEquiv = declStrictIsoToEquiv curryEquiv curryIso
Validation/pyFrame3DD-master/gcc-master/gcc/ada/gnatlink.adb
djamal2727/Main-Bearing-Analytical-Model
0
3146
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T L I N K -- -- -- -- B o d y -- -- -- -- Copyright (C) 1996-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Gnatlink usage: please consult the gnat documentation with ALI; use ALI; with Csets; with Gnatvsn; use Gnatvsn; with Indepsw; use Indepsw; with Namet; use Namet; with Opt; with Osint; use Osint; with Output; use Output; with Snames; with Switch; use Switch; with System; use System; with Table; with Targparm; with Types; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with System.OS_Lib; use System.OS_Lib; with System.CRTL; with Interfaces.C_Streams; use Interfaces.C_Streams; with Interfaces.C.Strings; use Interfaces.C.Strings; procedure Gnatlink is pragma Ident (Gnatvsn.Gnat_Static_Version_String); Shared_Libgcc_String : constant String := "-shared-libgcc"; Shared_Libgcc : constant String_Access := new String'(Shared_Libgcc_String); -- Used to invoke gcc when the binder is invoked with -shared Static_Libgcc_String : constant String := "-static-libgcc"; Static_Libgcc : constant String_Access := new String'(Static_Libgcc_String); -- Used to invoke gcc when shared libs are not used package Gcc_Linker_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Gcc_Linker_Options"); -- Comments needed ??? package Libpath is new Table.Table ( Table_Component_Type => Character, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 4096, Table_Increment => 100, Table_Name => "Gnatlink.Libpath"); -- Comments needed ??? package Linker_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Linker_Options"); -- Comments needed ??? package Linker_Objects is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Linker_Objects"); -- This table collects the objects file to be passed to the linker. In the -- case where the linker command line is too long then programs objects -- are put on the Response_File_Objects table. Note that the binder object -- file and the user's objects remain in this table. This is very -- important because on the GNU linker command line the -L switch is not -- used to look for objects files but -L switch is used to look for -- objects listed in the response file. This is not a problem with the -- applications objects as they are specified with a full name. package Response_File_Objects is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Response_File_Objects"); -- This table collects the objects file that are to be put in the response -- file. Only application objects are collected there (see details in -- Linker_Objects table comments) package Binder_Options_From_ALI is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, -- equals low bound of Argument_List for Spawn Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Binder_Options_From_ALI"); -- This table collects the switches from the ALI file of the main -- subprogram. package Binder_Options is new Table.Table ( Table_Component_Type => String_Access, Table_Index_Type => Integer, Table_Low_Bound => 1, -- equals low bound of Argument_List for Spawn Table_Initial => 20, Table_Increment => 100, Table_Name => "Gnatlink.Binder_Options"); -- This table collects the arguments to be passed to compile the binder -- generated file. Gcc : String_Access := Program_Name ("gcc", "gnatlink"); Read_Mode : constant String := "r" & ASCII.NUL; Begin_Info : constant String := "-- BEGIN Object file/option list"; End_Info : constant String := "-- END Object file/option list "; Gcc_Path : String_Access; Linker_Path : String_Access; Output_File_Name : String_Access; Ali_File_Name : String_Access; Binder_Spec_Src_File : String_Access; Binder_Body_Src_File : String_Access; Binder_Ali_File : String_Access; Binder_Obj_File : String_Access; Base_Command_Name : String_Access; Target_Debuggable_Suffix : String_Access; Tname : Temp_File_Name; Tname_FD : File_Descriptor := Invalid_FD; -- Temporary file used by linker to pass list of object files on -- certain systems with limitations on size of arguments. Debug_Flag_Present : Boolean := False; Verbose_Mode : Boolean := False; Very_Verbose_Mode : Boolean := False; Standard_Gcc : Boolean := True; Compile_Bind_File : Boolean := True; -- Set to False if bind file is not to be compiled Create_Map_File : Boolean := False; -- Set to True by switch -M. The map file name is derived from -- the ALI file name (mainprog.ali => mainprog.map). Object_List_File_Supported : Boolean; for Object_List_File_Supported'Size use Character'Size; pragma Import (C, Object_List_File_Supported, "__gnat_objlist_file_supported"); -- Predicate indicating whether the linker has an option whereby the -- names of object files can be passed to the linker in a file. Object_File_Option_Ptr : Interfaces.C.Strings.chars_ptr; pragma Import (C, Object_File_Option_Ptr, "__gnat_object_file_option"); -- Pointer to a string representing the linker option which specifies -- the response file. Object_File_Option : constant String := Value (Object_File_Option_Ptr); -- The linker option which specifies the response file as a string Using_GNU_response_file : constant Boolean := Object_File_Option'Length > 0 and then Object_File_Option (Object_File_Option'Last) = '@'; -- Whether a GNU response file is used Object_List_File_Required : Boolean := False; -- Set to True to force generation of a response file Shared_Libgcc_Default : Character; for Shared_Libgcc_Default'Size use Character'Size; pragma Import (C, Shared_Libgcc_Default, "__gnat_shared_libgcc_default"); -- Indicates wether libgcc should be statically linked (use 'T') or -- dynamically linked (use 'H') by default. function Base_Name (File_Name : String) return String; -- Return just the file name part without the extension (if present) procedure Check_Existing_Executable (File_Name : String); -- Delete any existing executable to avoid accidentally updating the target -- of a symbolic link, but produce a Fatail_Error if File_Name matches any -- of the source file names. This avoids overwriting of extensionless -- source files by accident on systems where executables do not have -- extensions. procedure Delete (Name : String); -- Wrapper to unlink as status is ignored by this application procedure Error_Msg (Message : String); -- Output the error or warning Message procedure Exit_With_Error (Error : String); -- Output Error and exit program with a fatal condition procedure Process_Args; -- Go through all the arguments and build option tables procedure Process_Binder_File (Name : String); -- Reads the binder file and extracts linker arguments procedure Usage; -- Display usage procedure Write_Header; -- Show user the program name, version and copyright procedure Write_Usage; -- Show user the program options --------------- -- Base_Name -- --------------- function Base_Name (File_Name : String) return String is Findex1 : Natural; Findex2 : Natural; begin Findex1 := File_Name'First; -- The file might be specified by a full path name. However, -- we want the path to be stripped away. for J in reverse File_Name'Range loop if Is_Directory_Separator (File_Name (J)) then Findex1 := J + 1; exit; end if; end loop; Findex2 := File_Name'Last; while Findex2 > Findex1 and then File_Name (Findex2) /= '.' loop Findex2 := Findex2 - 1; end loop; if Findex2 = Findex1 then Findex2 := File_Name'Last + 1; end if; return File_Name (Findex1 .. Findex2 - 1); end Base_Name; ------------------------------- -- Check_Existing_Executable -- ------------------------------- procedure Check_Existing_Executable (File_Name : String) is Ename : String := File_Name; Efile : File_Name_Type; Sfile : File_Name_Type; begin Canonical_Case_File_Name (Ename); Name_Len := 0; Add_Str_To_Name_Buffer (Ename); Efile := Name_Find; for J in Units.Table'First .. Units.Last loop Sfile := Units.Table (J).Sfile; if Sfile = Efile then Exit_With_Error ("executable name """ & File_Name & """ matches " & "source file name """ & Get_Name_String (Sfile) & """"); end if; end loop; Delete (File_Name); end Check_Existing_Executable; ------------ -- Delete -- ------------ procedure Delete (Name : String) is Status : int; pragma Unreferenced (Status); begin Status := unlink (Name'Address); -- Is it really right to ignore an error here ??? end Delete; --------------- -- Error_Msg -- --------------- procedure Error_Msg (Message : String) is begin Write_Str (Base_Command_Name.all); Write_Str (": "); Write_Str (Message); Write_Eol; end Error_Msg; --------------------- -- Exit_With_Error -- --------------------- procedure Exit_With_Error (Error : String) is begin Error_Msg (Error); Exit_Program (E_Fatal); end Exit_With_Error; ------------------ -- Process_Args -- ------------------ procedure Process_Args is Next_Arg : Integer; Skip_Next : Boolean := False; -- Set to true if the next argument is to be added into the list of -- linker's argument without parsing it. procedure Check_Version_And_Help is new Check_Version_And_Help_G (Usage); -- Start of processing for Process_Args begin -- First, check for --version and --help Check_Version_And_Help ("GNATLINK", "1996"); -- Loop through arguments of gnatlink command Next_Arg := 1; loop exit when Next_Arg > Argument_Count; Process_One_Arg : declare Arg : constant String := Argument (Next_Arg); begin -- Case of argument which is a switch -- We definitely need section by section comments here ??? if Skip_Next then -- This argument must not be parsed, just add it to the -- list of linker's options. Skip_Next := False; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); elsif Arg'Length /= 0 and then Arg (1) = '-' then if Arg'Length > 4 and then Arg (2 .. 5) = "gnat" then Exit_With_Error ("invalid switch: """ & Arg & """ (gnat not needed here)"); end if; if Arg = "-Xlinker" then -- Next argument should be sent directly to the linker. -- We do not want to parse it here. Skip_Next := True; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); elsif Arg (2) = 'g' and then (Arg'Length < 5 or else Arg (2 .. 5) /= "gnat") then Debug_Flag_Present := True; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); elsif Arg'Length >= 3 and then Arg (2) = 'M' then declare Switches : String_List_Access; begin Convert (Map_File, Arg (3 .. Arg'Last), Switches); if Switches /= null then for J in Switches'Range loop Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Switches (J); end loop; end if; end; elsif Arg'Length = 2 then case Arg (2) is when 'f' => if Object_List_File_Supported then Object_List_File_Required := True; else Exit_With_Error ("Object list file not supported on this target"); end if; when 'M' => Create_Map_File := True; when 'n' => Compile_Bind_File := False; when 'o' => Next_Arg := Next_Arg + 1; if Next_Arg > Argument_Count then Exit_With_Error ("Missing argument for -o"); end if; Output_File_Name := new String'(Executable_Name (Argument (Next_Arg), Only_If_No_Suffix => True)); when 'P' => Opt.CodePeer_Mode := True; when 'R' => Opt.Run_Path_Option := False; when 'v' => -- Support "double" verbose mode. Second -v -- gets sent to the linker and binder phases. if Verbose_Mode then Very_Verbose_Mode := True; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); else Verbose_Mode := True; end if; when others => Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end case; elsif Arg (2) = 'B' then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Linker_Options.Table (Linker_Options.Last); elsif Arg'Length >= 7 and then Arg (1 .. 7) = "--LINK=" then if Arg'Length = 7 then Exit_With_Error ("Missing argument for --LINK="); end if; declare L_Args : constant Argument_List_Access := Argument_String_To_List (Arg (8 .. Arg'Last)); begin -- The linker program is the first argument Linker_Path := System.OS_Lib.Locate_Exec_On_Path (L_Args.all (1).all); if Linker_Path = null then Exit_With_Error ("Could not locate linker: " & L_Args.all (1).all); end if; -- The other arguments are passed as-is to the linker and -- override those coming from --GCC= if any. if L_Args.all'Last >= 2 then Gcc_Linker_Options.Set_Last (0); end if; for J in 2 .. L_Args.all'Last loop Gcc_Linker_Options.Increment_Last; Gcc_Linker_Options.Table (Gcc_Linker_Options.Last) := new String'(L_Args.all (J).all); end loop; end; elsif Arg'Length >= 6 and then Arg (1 .. 6) = "--GCC=" then if Arg'Length = 6 then Exit_With_Error ("Missing argument for --GCC="); end if; declare Program_Args : constant Argument_List_Access := Argument_String_To_List (Arg (7 .. Arg'Last)); begin if Program_Args.all (1).all /= Gcc.all then Gcc := new String'(Program_Args.all (1).all); Standard_Gcc := False; end if; -- Set appropriate flags for switches passed for J in 2 .. Program_Args.all'Last loop declare Arg : constant String := Program_Args.all (J).all; AF : constant Integer := Arg'First; begin if Arg'Length /= 0 and then Arg (AF) = '-' then if Arg (AF + 1) = 'g' and then (Arg'Length = 2 or else Arg (AF + 2) in '0' .. '3' or else Arg (AF + 2 .. Arg'Last) = "coff") then Debug_Flag_Present := True; end if; end if; -- Add directory to source search dirs so that -- Get_Target_Parameters can find system.ads if Arg (AF .. AF + 1) = "-I" and then Arg'Length > 2 then Add_Src_Search_Dir (Arg (AF + 2 .. Arg'Last)); end if; -- Pass to gcc for compiling binder generated file -- No use passing libraries, it will just generate -- a warning if not (Arg (AF .. AF + 1) = "-l" or else Arg (AF .. AF + 1) = "-L") then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'(Arg); end if; -- Pass to gcc for linking program Gcc_Linker_Options.Increment_Last; Gcc_Linker_Options.Table (Gcc_Linker_Options.Last) := new String'(Arg); end; end loop; end; -- Send all multi-character switches not recognized as -- a special case by gnatlink to the linker/loader stage. else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end if; -- Here if argument is a file name rather than a switch else -- If explicit ali file, capture it if Arg'Length > 4 and then Arg (Arg'Last - 3 .. Arg'Last) = ".ali" then if Ali_File_Name = null then Ali_File_Name := new String'(Arg); else Exit_With_Error ("cannot handle more than one ALI file"); end if; -- If target object file, record object file elsif Arg'Length > Get_Target_Object_Suffix.all'Length and then Arg (Arg'Last - Get_Target_Object_Suffix.all'Length + 1 .. Arg'Last) = Get_Target_Object_Suffix.all then Linker_Objects.Increment_Last; Linker_Objects.Table (Linker_Objects.Last) := new String'(Arg); -- If host object file, record object file elsif Arg'Length > Get_Object_Suffix.all'Length and then Arg (Arg'Last - Get_Object_Suffix.all'Length + 1 .. Arg'Last) = Get_Object_Suffix.all then Linker_Objects.Increment_Last; Linker_Objects.Table (Linker_Objects.Last) := new String'(Arg); -- If corresponding ali file exists, capture it elsif Ali_File_Name = null and then Is_Regular_File (Arg & ".ali") then Ali_File_Name := new String'(Arg & ".ali"); -- Otherwise assume this is a linker options entry, but -- see below for interesting adjustment to this assumption. else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Arg); end if; end if; end Process_One_Arg; Next_Arg := Next_Arg + 1; end loop; -- Compile the bind file with warnings suppressed, because -- otherwise the with of the main program may cause junk warnings. Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-gnatws"); -- If we did not get an ali file at all, and we had at least one -- linker option, then assume that was the intended ali file after -- all, so that we get a nicer message later on. if Ali_File_Name = null and then Linker_Options.Last >= Linker_Options.First then Ali_File_Name := new String'(Linker_Options.Table (Linker_Options.First).all & ".ali"); end if; end Process_Args; ------------------------- -- Process_Binder_File -- ------------------------- procedure Process_Binder_File (Name : String) is Fd : FILEs; -- Binder file's descriptor Link_Bytes : Integer := 0; -- Projected number of bytes for the linker command line Link_Max : Integer; pragma Import (C, Link_Max, "__gnat_link_max"); -- Maximum number of bytes on the command line supported by the OS -- linker. Passed this limit the response file mechanism must be used -- if supported. Next_Line : String (1 .. 1000); -- Current line value Nlast : Integer; Nfirst : Integer; -- Current line slice (the slice does not contain line terminator) Last : Integer; -- Current line last character for shared libraries (without version) Objs_Begin : Integer := 0; -- First object file index in Linker_Objects table Objs_End : Integer := 0; -- Last object file index in Linker_Objects table Status : int; pragma Warnings (Off, Status); -- Used for various Interfaces.C_Streams calls Closing_Status : Boolean; pragma Warnings (Off, Closing_Status); -- For call to Close GNAT_Static : Boolean := False; -- Save state of -static option GNAT_Shared : Boolean := False; -- Save state of -shared option Xlinker_Was_Previous : Boolean := False; -- Indicate that "-Xlinker" was the option preceding the current option. -- If True, then the current option is never suppressed. -- Rollback data -- These data items are used to store current binder file context. The -- context is composed of the file descriptor position and the current -- line together with the slice indexes (first and last position) for -- this line. The rollback data are used by the Store_File_Context and -- Rollback_File_Context routines below. The file context mechanism -- interact only with the Get_Next_Line call. For example: -- Store_File_Context; -- Get_Next_Line; -- Rollback_File_Context; -- Get_Next_Line; -- Both Get_Next_Line calls above will read the exact same data from -- the file. In other words, Next_Line, Nfirst and Nlast variables -- will be set with the exact same values. RB_File_Pos : long; -- File position RB_Next_Line : String (1 .. 1000); -- Current line content RB_Nlast : Integer; -- Slice last index RB_Nfirst : Integer; -- Slice first index Run_Path_Option_Ptr : Interfaces.C.Strings.chars_ptr; pragma Import (C, Run_Path_Option_Ptr, "__gnat_run_path_option"); -- Pointer to string representing the native linker option which -- specifies the path where the dynamic loader should find shared -- libraries. Equal to null string if this system doesn't support it. Libgcc_Subdir_Ptr : Interfaces.C.Strings.chars_ptr; pragma Import (C, Libgcc_Subdir_Ptr, "__gnat_default_libgcc_subdir"); -- Pointer to string indicating the installation subdirectory where -- a default shared libgcc might be found. Object_Library_Ext_Ptr : Interfaces.C.Strings.chars_ptr; pragma Import (C, Object_Library_Ext_Ptr, "__gnat_object_library_extension"); -- Pointer to string specifying the default extension for -- object libraries, e.g. Unix uses ".a". Separate_Run_Path_Options : Boolean; for Separate_Run_Path_Options'Size use Character'Size; pragma Import (C, Separate_Run_Path_Options, "__gnat_separate_run_path_options"); -- Whether separate rpath options should be emitted for each directory procedure Get_Next_Line; -- Read the next line from the binder file without the line -- terminator. function Index (S, Pattern : String) return Natural; -- Return the last occurrence of Pattern in S, or 0 if none procedure Store_File_Context; -- Store current file context, Fd position and current line data. -- The file context is stored into the rollback data above (RB_*). -- Store_File_Context can be called at any time, only the last call -- will be used (i.e. this routine overwrites the file context). procedure Rollback_File_Context; -- Restore file context from rollback data. This routine must be called -- after Store_File_Context. The binder file context will be restored -- with the data stored by the last Store_File_Context call. procedure Write_RF (S : String); -- Write a string to the response file and check if it was successful. -- Fail the program if it was not successful (disk full). ------------------- -- Get_Next_Line -- ------------------- procedure Get_Next_Line is Fchars : chars; begin Fchars := fgets (Next_Line'Address, Next_Line'Length, Fd); if Fchars = System.Null_Address then Exit_With_Error ("Error reading binder output"); end if; Nfirst := Next_Line'First; Nlast := Nfirst; while Nlast <= Next_Line'Last and then Next_Line (Nlast) /= ASCII.LF and then Next_Line (Nlast) /= ASCII.CR loop Nlast := Nlast + 1; end loop; Nlast := Nlast - 1; end Get_Next_Line; ----------- -- Index -- ----------- function Index (S, Pattern : String) return Natural is Len : constant Natural := Pattern'Length; begin for J in reverse S'First .. S'Last - Len + 1 loop if Pattern = S (J .. J + Len - 1) then return J; end if; end loop; return 0; end Index; --------------------------- -- Rollback_File_Context -- --------------------------- procedure Rollback_File_Context is begin Next_Line := RB_Next_Line; Nfirst := RB_Nfirst; Nlast := RB_Nlast; Status := fseek (Fd, RB_File_Pos, Interfaces.C_Streams.SEEK_SET); if Status = -1 then Exit_With_Error ("Error setting file position"); end if; end Rollback_File_Context; ------------------------ -- Store_File_Context -- ------------------------ procedure Store_File_Context is use type System.CRTL.long; begin RB_Next_Line := Next_Line; RB_Nfirst := Nfirst; RB_Nlast := Nlast; RB_File_Pos := ftell (Fd); if RB_File_Pos = -1 then Exit_With_Error ("Error getting file position"); end if; end Store_File_Context; -------------- -- Write_RF -- -------------- procedure Write_RF (S : String) is Success : Boolean := True; Back_Slash : constant Character := '\'; begin -- If a GNU response file is used, space and backslash need to be -- escaped because they are interpreted as a string separator and -- an escape character respectively by the underlying mechanism. -- On the other hand, quote and double-quote are not escaped since -- they are interpreted as string delimiters on both sides. if Using_GNU_response_file then for J in S'Range loop if S (J) = ' ' or else S (J) = '\' then if Write (Tname_FD, Back_Slash'Address, 1) /= 1 then Success := False; end if; end if; if Write (Tname_FD, S (J)'Address, 1) /= 1 then Success := False; end if; end loop; else if Write (Tname_FD, S'Address, S'Length) /= S'Length then Success := False; end if; end if; if Write (Tname_FD, ASCII.LF'Address, 1) /= 1 then Success := False; end if; if not Success then Exit_With_Error ("Error generating response file: disk full"); end if; end Write_RF; -- Start of processing for Process_Binder_File begin Fd := fopen (Name'Address, Read_Mode'Address); if Fd = NULL_Stream then Exit_With_Error ("Failed to open binder output"); end if; -- Skip up to the Begin Info line loop Get_Next_Line; exit when Next_Line (Nfirst .. Nlast) = Begin_Info; end loop; loop Get_Next_Line; -- Go to end when end line is reached (this will happen in -- High_Integrity_Mode where no -L switches are generated) exit when Next_Line (Nfirst .. Nlast) = End_Info; Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast); Nlast := Nlast - 8; -- Go to next section when switches are reached exit when Next_Line (1) = '-'; -- Otherwise we have another object file to collect Linker_Objects.Increment_Last; -- Mark the positions of first and last object files in case they -- need to be placed with a named file on systems having linker -- line limitations. if Objs_Begin = 0 then Objs_Begin := Linker_Objects.Last; end if; Linker_Objects.Table (Linker_Objects.Last) := new String'(Next_Line (Nfirst .. Nlast)); -- Nlast - Nfirst + 1, for the size, plus one for the space between -- each arguments. Link_Bytes := Link_Bytes + Nlast - Nfirst + 2; end loop; Objs_End := Linker_Objects.Last; -- Continue to compute the Link_Bytes, the linker options are part of -- command line length. Store_File_Context; while Next_Line (Nfirst .. Nlast) /= End_Info loop Link_Bytes := Link_Bytes + Nlast - Nfirst + 2; Get_Next_Line; end loop; Rollback_File_Context; -- On systems that have limitations on handling very long linker lines -- we make use of the system linker option which takes a list of object -- file names from a file instead of the command line itself. What we do -- is to replace the list of object files by the special linker option -- which then reads the object file list from a file instead. The option -- to read from a file instead of the command line is only triggered if -- a conservative threshold is passed. if Object_List_File_Required or else (Object_List_File_Supported and then Link_Bytes > Link_Max) then -- Create a temporary file containing the Ada user object files -- needed by the link. This list is taken from the bind file and is -- output one object per line for maximal compatibility with linkers -- supporting this option. Create_Temp_File (Tname_FD, Tname); -- ??? File descriptor should be checked to not be Invalid_FD. -- ??? Status of Write and Close operations should be checked, and -- failure should occur if a status is wrong. for J in Objs_Begin .. Objs_End loop Write_RF (Linker_Objects.Table (J).all); Response_File_Objects.Increment_Last; Response_File_Objects.Table (Response_File_Objects.Last) := Linker_Objects.Table (J); end loop; Close (Tname_FD, Closing_Status); -- Add the special objects list file option together with the name -- of the temporary file (removing the null character) to the objects -- file table. Linker_Objects.Table (Objs_Begin) := new String'(Object_File_Option & Tname (Tname'First .. Tname'Last - 1)); -- The slots containing these object file names are then removed -- from the objects table so they do not appear in the link. They are -- removed by moving up the linker options and non-Ada object files -- appearing after the Ada object list in the table. declare N : Integer; begin N := Objs_End - Objs_Begin + 1; for J in Objs_End + 1 .. Linker_Objects.Last loop Linker_Objects.Table (J - N + 1) := Linker_Objects.Table (J); end loop; Linker_Objects.Set_Last (Linker_Objects.Last - N + 1); end; end if; -- Process switches and options if Next_Line (Nfirst .. Nlast) /= End_Info then Xlinker_Was_Previous := False; loop if Xlinker_Was_Previous or else Next_Line (Nfirst .. Nlast) = "-Xlinker" then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); elsif Next_Line (Nfirst .. Nlast) = "-static" then GNAT_Static := True; elsif Next_Line (Nfirst .. Nlast) = "-shared" then GNAT_Shared := True; -- Add binder options only if not already set on the command line. -- This rule is a way to control the linker options order. else if Nlast > Nfirst + 2 and then Next_Line (Nfirst .. Nfirst + 1) = "-L" then -- Construct a library search path for use later to locate -- static gnatlib libraries. if Libpath.Last > 1 then Libpath.Increment_Last; Libpath.Table (Libpath.Last) := Path_Separator; end if; for I in Nfirst + 2 .. Nlast loop Libpath.Increment_Last; Libpath.Table (Libpath.Last) := Next_Line (I); end loop; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); elsif Next_Line (Nfirst .. Nlast) = "-lgnarl" or else Next_Line (Nfirst .. Nlast) = "-lgnat" or else Next_Line (1 .. Natural'Min (Nlast, 8 + Library_Version'Length)) = Shared_Lib ("gnarl") or else Next_Line (1 .. Natural'Min (Nlast, 7 + Library_Version'Length)) = Shared_Lib ("gnat") then -- If it is a shared library, remove the library version. -- We will be looking for the static version of the library -- as it is in the same directory as the shared version. if Nlast >= Library_Version'Length and then Next_Line (Nlast - Library_Version'Length + 1 .. Nlast) = Library_Version then -- Set Last to point to last character before the -- library version. Last := Nlast - Library_Version'Length - 1; else Last := Nlast; end if; -- Given a Gnat standard library, search the library path to -- find the library location. -- Shouldn't we abstract a proc here, we are getting awfully -- heavily nested ??? declare File_Path : String_Access; Object_Lib_Extension : constant String := Value (Object_Library_Ext_Ptr); File_Name : constant String := "lib" & Next_Line (Nfirst + 2 .. Last) & Object_Lib_Extension; Run_Path_Opt : constant String := Value (Run_Path_Option_Ptr); GCC_Index : Natural; Run_Path_Opt_Index : Natural := 0; begin File_Path := Locate_Regular_File (File_Name, String (Libpath.Table (1 .. Libpath.Last))); if File_Path /= null then if GNAT_Static then -- If static gnatlib found, explicitly specify to -- overcome possible linker default usage of shared -- version. Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(File_Path.all); elsif GNAT_Shared then if Opt.Run_Path_Option then -- If shared gnatlib desired, add appropriate -- system specific switch so that it can be -- located at runtime. if Run_Path_Opt'Length /= 0 then -- Output the system specific linker command -- that allows the image activator to find -- the shared library at runtime. Also add -- path to find libgcc_s.so, if relevant. declare Path : String (1 .. File_Path'Length + 15); Path_Last : constant Natural := File_Path'Length; begin Path (1 .. File_Path'Length) := File_Path.all; -- To find the location of the shared version -- of libgcc, we look for "gcc-lib" in the -- path of the library. However, this -- subdirectory is no longer present in -- recent versions of GCC. So, we look for -- the last subdirectory "lib" in the path. GCC_Index := Index (Path (1 .. Path_Last), "gcc-lib"); if GCC_Index /= 0 then -- The shared version of libgcc is -- located in the parent directory. GCC_Index := GCC_Index - 1; else GCC_Index := Index (Path (1 .. Path_Last), "/lib/"); if GCC_Index = 0 then GCC_Index := Index (Path (1 .. Path_Last), Directory_Separator & "lib" & Directory_Separator); end if; -- If we have found a "lib" subdir in -- the path to libgnat, the possible -- shared libgcc of interest by default -- is in libgcc_subdir at the same -- level. if GCC_Index /= 0 then declare Subdir : constant String := Value (Libgcc_Subdir_Ptr); begin Path (GCC_Index + 1 .. GCC_Index + Subdir'Length) := Subdir; GCC_Index := GCC_Index + Subdir'Length; end; end if; end if; -- Look for an eventual run_path_option in -- the linker switches. if Separate_Run_Path_Options then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String' (Run_Path_Opt & File_Path (1 .. File_Path'Length - File_Name'Length)); if GCC_Index /= 0 then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String' (Run_Path_Opt & Path (1 .. GCC_Index)); end if; else for J in reverse 1 .. Linker_Options.Last loop if Linker_Options.Table (J) /= null and then Linker_Options.Table (J)'Length > Run_Path_Opt'Length and then Linker_Options.Table (J) (1 .. Run_Path_Opt'Length) = Run_Path_Opt then -- We have found an already -- specified run_path_option: -- we will add to this -- switch, because only one -- run_path_option should be -- specified. Run_Path_Opt_Index := J; exit; end if; end loop; -- If there is no run_path_option, we -- need to add one. if Run_Path_Opt_Index = 0 then Linker_Options.Increment_Last; end if; if GCC_Index = 0 then if Run_Path_Opt_Index = 0 then Linker_Options.Table (Linker_Options.Last) := new String' (Run_Path_Opt & File_Path (1 .. File_Path'Length - File_Name'Length)); else Linker_Options.Table (Run_Path_Opt_Index) := new String' (Linker_Options.Table (Run_Path_Opt_Index).all & Path_Separator & File_Path (1 .. File_Path'Length - File_Name'Length)); end if; else if Run_Path_Opt_Index = 0 then Linker_Options.Table (Linker_Options.Last) := new String' (Run_Path_Opt & File_Path (1 .. File_Path'Length - File_Name'Length) & Path_Separator & Path (1 .. GCC_Index)); else Linker_Options.Table (Run_Path_Opt_Index) := new String' (Linker_Options.Table (Run_Path_Opt_Index).all & Path_Separator & File_Path (1 .. File_Path'Length - File_Name'Length) & Path_Separator & Path (1 .. GCC_Index)); end if; end if; end if; end; end if; end if; -- Then we add the appropriate -l switch Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end if; else -- If gnatlib library not found, then add it anyway in -- case some other mechanism may find it. Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end if; end; else Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Next_Line (Nfirst .. Nlast)); end if; end if; Xlinker_Was_Previous := Next_Line (Nfirst .. Nlast) = "-Xlinker"; Get_Next_Line; exit when Next_Line (Nfirst .. Nlast) = End_Info; Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast); Nlast := Nlast - 8; end loop; end if; -- If -shared was specified, invoke gcc with -shared-libgcc if GNAT_Shared then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Shared_Libgcc; end if; Status := fclose (Fd); end Process_Binder_File; ----------- -- Usage -- ----------- procedure Usage is begin Write_Str ("Usage: "); Write_Str (Base_Command_Name.all); Write_Str (" switches mainprog.ali [non-Ada-objects] [linker-options]"); Write_Eol; Write_Eol; Write_Line (" mainprog.ali the ALI file of the main program"); Write_Eol; Write_Eol; Display_Usage_Version_And_Help; Write_Line (" -f Force object file list to be generated"); Write_Line (" -g Compile binder source file with debug information"); Write_Line (" -n Do not compile the binder source file"); Write_Line (" -P Process files for use by CodePeer"); Write_Line (" -R Do not use a run_path_option"); Write_Line (" -v Verbose mode"); Write_Line (" -v -v Very verbose mode"); Write_Eol; Write_Line (" -o nam Use 'nam' as the name of the executable"); Write_Line (" -Bdir Load compiler executables from dir"); if Is_Supported (Map_File) then Write_Line (" -Mmap Create map file map"); Write_Line (" -M Create map file mainprog.map"); end if; Write_Line (" --GCC=comp Use 'comp' as the compiler rather than 'gcc'"); Write_Line (" --LINK=lnk Use 'lnk' as the linker rather than 'gcc'"); Write_Eol; Write_Line (" [non-Ada-objects] list of non Ada object files"); Write_Line (" [linker-options] other options for the linker"); end Usage; ------------------ -- Write_Header -- ------------------ procedure Write_Header is begin if Verbose_Mode then Write_Eol; Display_Version ("GNATLINK", "1995"); end if; end Write_Header; ----------------- -- Write_Usage -- ----------------- procedure Write_Usage is begin Write_Header; Usage; end Write_Usage; -- Start of processing for Gnatlink begin -- Add the directory where gnatlink is invoked in front of the path, if -- gnatlink is invoked with directory information. declare Command : constant String := Command_Name; begin for Index in reverse Command'Range loop if Command (Index) = Directory_Separator then declare Absolute_Dir : constant String := Normalize_Pathname (Command (Command'First .. Index)); PATH : constant String := Absolute_Dir & Path_Separator & Getenv ("PATH").all; begin Setenv ("PATH", PATH); end; exit; end if; end loop; end; Base_Command_Name := new String'(Base_Name (Command_Name)); Process_Args; if Argument_Count = 0 or else (Verbose_Mode and then Argument_Count = 1) then Write_Usage; Exit_Program (E_Fatal); end if; -- Initialize packages to be used Csets.Initialize; Snames.Initialize; -- We always compile with -c Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-c"); if Ali_File_Name = null then Exit_With_Error ("no ali file given for link"); end if; if not Is_Regular_File (Ali_File_Name.all) then Exit_With_Error (Ali_File_Name.all & " not found"); end if; -- Read the ALI file of the main subprogram if the binder generated file -- needs to be compiled and no --GCC= switch has been specified. Fetch the -- back end switches from this ALI file and use these switches to compile -- the binder generated file if Compile_Bind_File and then Standard_Gcc then Initialize_ALI; Name_Len := Ali_File_Name'Length; Name_Buffer (1 .. Name_Len) := Ali_File_Name.all; declare use Types; F : constant File_Name_Type := Name_Find; T : Text_Buffer_Ptr; A : ALI_Id; begin -- Load the ALI file T := Read_Library_Info (F, True); -- Read it. Note that we ignore errors, since we only want very -- limited information from the ali file, and likely a slightly -- wrong version will be just fine, though in normal operation -- we don't expect this to happen. A := Scan_ALI (F, T, Ignore_ED => False, Err => False, Ignore_Errors => True); if A /= No_ALI_Id then for Index in Units.Table (ALIs.Table (A).First_Unit).First_Arg .. Units.Table (ALIs.Table (A).First_Unit).Last_Arg loop -- Do not compile with the front end switches. However, --RTS -- is to be dealt with specially because it needs to be passed -- to compile the file generated by the binder. declare Arg : String_Ptr renames Args.Table (Index); begin if not Is_Front_End_Switch (Arg.all) then Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := String_Access (Arg); -- GNAT doesn't support GCC's multilib mechanism when it -- is configured with --disable-libada. This means that, -- when a multilib switch is used to request a particular -- compilation mode, the corresponding --RTS switch must -- also be specified. It is convenient to eliminate the -- redundancy by keying the compilation mode on a single -- switch, namely --RTS, and have the compiler reinstate -- the multilib switch (see gcc-interface/lang-specs.h). -- This switch must be passed to the driver at link time. if Arg'Length = 5 and then Arg (Arg'First + 1 .. Arg'First + 4) = "mrtp" then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := String_Access (Arg); end if; elsif Arg'Length > 5 and then Arg (Arg'First + 2 .. Arg'First + 5) = "RTS=" then Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := String_Access (Arg); -- Set the RTS_*_Path_Name variables, so that -- the correct directories will be set when -- Osint.Add_Default_Search_Dirs will be called later. Opt.RTS_Src_Path_Name := Get_RTS_Search_Dir (Arg (Arg'First + 6 .. Arg'Last), Include); Opt.RTS_Lib_Path_Name := Get_RTS_Search_Dir (Arg (Arg'First + 6 .. Arg'Last), Objects); end if; end; end loop; end if; end; end if; -- Get target parameters Osint.Add_Default_Search_Dirs; Targparm.Get_Target_Parameters; -- Compile the bind file with the following switches: -- -gnatA stops reading gnat.adc, since we don't know what -- pragmas would work, and we do not need it anyway. -- -gnatWb allows brackets coding for wide characters -- -gnatiw allows wide characters in identifiers. This is needed -- because bindgen uses brackets encoding for all upper -- half and wide characters in identifier names. -- In addition, in CodePeer mode compile with -x adascil -gnatcC Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-gnatA"); Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-gnatWb"); Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-gnatiw"); if Opt.CodePeer_Mode then Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-x"); Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("adascil"); Binder_Options_From_ALI.Increment_Last; Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) := new String'("-gnatcC"); end if; -- Locate all the necessary programs and verify required files are present Gcc_Path := System.OS_Lib.Locate_Exec_On_Path (Gcc.all); if Gcc_Path = null then Exit_With_Error ("Couldn't locate " & Gcc.all); end if; if Linker_Path = null then Linker_Path := Gcc_Path; end if; Write_Header; Target_Debuggable_Suffix := Get_Target_Debuggable_Suffix; -- If no output name specified, then use the base name of .ali file name if Output_File_Name = null then Output_File_Name := new String'(Base_Name (Ali_File_Name.all) & Target_Debuggable_Suffix.all); end if; Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'("-o"); Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := new String'(Output_File_Name.all); Check_Existing_Executable (Output_File_Name.all); -- Warn if main program is called "test", as that may be a built-in command -- on Unix. On non-Unix systems executables have a suffix, so the warning -- will not appear. However, do not warn in the case of a cross compiler. -- Assume this is a cross tool if the executable name is not gnatlink. -- Note that the executable name is also gnatlink on windows, but in that -- case the output file name will be test.exe rather than test. if Base_Command_Name.all = "gnatlink" and then Output_File_Name.all = "test" then Error_Msg ("warning: executable name """ & Output_File_Name.all & """ may conflict with shell command"); end if; -- Special warnings for worrisome file names on windows -- Recent versions of Windows by default cause privilege escalation if an -- executable file name contains substrings "install", "setup", "update" -- or "patch". A console application will typically fail to load as a -- result, so we should warn the user. Bad_File_Names_On_Windows : declare FN : String := Output_File_Name.all; procedure Check_File_Name (S : String); -- Warn if file name has the substring S procedure Check_File_Name (S : String) is begin for J in 1 .. FN'Length - (S'Length - 1) loop if FN (J .. J + (S'Length - 1)) = S then Error_Msg ("warning: executable file name """ & Output_File_Name.all & """ contains substring """ & S & '"'); Error_Msg ("admin privileges may be required to run this file"); end if; end loop; end Check_File_Name; -- Start of processing for Bad_File_Names_On_Windows begin for J in FN'Range loop FN (J) := Csets.Fold_Lower (FN (J)); end loop; -- For now we detect Windows by its executable suffix of .exe if Target_Debuggable_Suffix.all = ".exe" then Check_File_Name ("install"); Check_File_Name ("setup"); Check_File_Name ("update"); Check_File_Name ("patch"); end if; end Bad_File_Names_On_Windows; -- If -M switch was specified, add the switches to create the map file if Create_Map_File then declare Map_Name : constant String := Base_Name (Ali_File_Name.all) & ".map"; Switches : String_List_Access; begin Convert (Map_File, Map_Name, Switches); if Switches /= null then for J in Switches'Range loop Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Switches (J); end loop; end if; end; end if; -- Perform consistency checks -- Transform the .ali file name into the binder output file name Make_Binder_File_Names : declare Fname : constant String := Base_Name (Ali_File_Name.all); Fname_Len : Integer := Fname'Length; function Get_Maximum_File_Name_Length return Integer; pragma Import (C, Get_Maximum_File_Name_Length, "__gnat_get_maximum_file_name_length"); Maximum_File_Name_Length : constant Integer := Get_Maximum_File_Name_Length; Bind_File_Prefix : Types.String_Ptr; -- Contains prefix used for bind files begin -- Set prefix Bind_File_Prefix := new String'("b~"); -- If the length of the binder file becomes too long due to -- the addition of the "b?" prefix, then truncate it. if Maximum_File_Name_Length > 0 then while Fname_Len > Maximum_File_Name_Length - Bind_File_Prefix.all'Length loop Fname_Len := Fname_Len - 1; end loop; end if; declare Fnam : constant String := Bind_File_Prefix.all & Fname (Fname'First .. Fname'First + Fname_Len - 1); begin Binder_Spec_Src_File := new String'(Fnam & ".ads"); Binder_Body_Src_File := new String'(Fnam & ".adb"); Binder_Ali_File := new String'(Fnam & ".ali"); Binder_Obj_File := new String'(Fnam & Get_Target_Object_Suffix.all); end; if Fname_Len /= Fname'Length then Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := new String'("-o"); Binder_Options.Increment_Last; Binder_Options.Table (Binder_Options.Last) := Binder_Obj_File; end if; end Make_Binder_File_Names; Process_Binder_File (Binder_Body_Src_File.all & ASCII.NUL); -- Compile the binder file. This is fast, so we always do it, unless -- specifically told not to by the -n switch if Compile_Bind_File then Bind_Step : declare Success : Boolean; Args : Argument_List (1 .. Binder_Options_From_ALI.Last + Binder_Options.Last + 1); begin for J in 1 .. Binder_Options_From_ALI.Last loop Args (J) := Binder_Options_From_ALI.Table (J); end loop; for J in 1 .. Binder_Options.Last loop Args (Binder_Options_From_ALI.Last + J) := Binder_Options.Table (J); end loop; -- Use the full path of the binder generated source, so that it is -- guaranteed that the debugger will find this source, even with -- STABS. Args (Args'Last) := new String'(Normalize_Pathname (Binder_Body_Src_File.all)); if Verbose_Mode then Write_Str (Base_Name (Gcc_Path.all)); for J in Args'Range loop Write_Str (" "); Write_Str (Args (J).all); end loop; Write_Eol; end if; System.OS_Lib.Spawn (Gcc_Path.all, Args, Success); if not Success then Exit_Program (E_Fatal); end if; end Bind_Step; end if; -- In CodePeer mode, there's nothing left to do after the binder file has -- been compiled. if Opt.CodePeer_Mode then if Tname_FD /= Invalid_FD then Delete (Tname); end if; return; end if; -- Now, actually link the program Link_Step : declare Num_Args : Natural := (Linker_Options.Last - Linker_Options.First + 1) + (Gcc_Linker_Options.Last - Gcc_Linker_Options.First + 1) + (Linker_Objects.Last - Linker_Objects.First + 1); Stack_Op : Boolean := False; begin -- Remove duplicate stack size setting from the Linker_Options table. -- The stack setting option "-Xlinker --stack=R,C" can be found -- in one line when set by a pragma Linker_Options or in two lines -- ("-Xlinker" then "--stack=R,C") when set on the command line. We -- also check for the "-Wl,--stack=R" style option. -- We must remove the second stack setting option instance because -- the one on the command line will always be the first one. And any -- subsequent stack setting option will overwrite the previous one. -- This is done especially for GNAT/NT where we set the stack size -- for tasking programs by a pragma in the NT specific tasking -- package System.Task_Primitives.Operations. -- Note: This is not a FOR loop that runs from Linker_Options.First -- to Linker_Options.Last, since operations within the loop can -- modify the length of the table. Clean_Link_Option_Set : declare J : Natural; Shared_Libgcc_Seen : Boolean := False; Static_Libgcc_Seen : Boolean := False; begin J := Linker_Options.First; while J <= Linker_Options.Last loop if Linker_Options.Table (J).all = "-Xlinker" and then J < Linker_Options.Last and then Linker_Options.Table (J + 1)'Length > 8 and then Linker_Options.Table (J + 1) (1 .. 8) = "--stack=" then if Stack_Op then Linker_Options.Table (J .. Linker_Options.Last - 2) := Linker_Options.Table (J + 2 .. Linker_Options.Last); Linker_Options.Decrement_Last; Linker_Options.Decrement_Last; Num_Args := Num_Args - 2; else Stack_Op := True; end if; end if; -- Remove duplicate -shared-libgcc switches if Linker_Options.Table (J).all = Shared_Libgcc_String then if Shared_Libgcc_Seen then Linker_Options.Table (J .. Linker_Options.Last - 1) := Linker_Options.Table (J + 1 .. Linker_Options.Last); Linker_Options.Decrement_Last; Num_Args := Num_Args - 1; else Shared_Libgcc_Seen := True; end if; end if; -- Remove duplicate -static-libgcc switches if Linker_Options.Table (J).all = Static_Libgcc_String then if Static_Libgcc_Seen then Linker_Options.Table (J .. Linker_Options.Last - 1) := Linker_Options.Table (J + 1 .. Linker_Options.Last); Linker_Options.Decrement_Last; Num_Args := Num_Args - 1; else Static_Libgcc_Seen := True; end if; end if; -- Here we just check for a canonical form that matches the -- pragma Linker_Options set in the NT runtime. if (Linker_Options.Table (J)'Length > 17 and then Linker_Options.Table (J) (1 .. 17) = "-Xlinker --stack=") or else (Linker_Options.Table (J)'Length > 12 and then Linker_Options.Table (J) (1 .. 12) = "-Wl,--stack=") then if Stack_Op then Linker_Options.Table (J .. Linker_Options.Last - 1) := Linker_Options.Table (J + 1 .. Linker_Options.Last); Linker_Options.Decrement_Last; Num_Args := Num_Args - 1; else Stack_Op := True; end if; end if; J := J + 1; end loop; if Linker_Path = Gcc_Path then -- For systems where the default is to link statically with -- libgcc, if gcc is not called with -shared-libgcc, call it -- with -static-libgcc, as there are some platforms where one -- of these two switches is compulsory to link. -- Don't push extra switches if we already saw one. if Shared_Libgcc_Default = 'T' and then not Shared_Libgcc_Seen and then not Static_Libgcc_Seen then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Static_Libgcc; Num_Args := Num_Args + 1; end if; -- Likewise, the reverse. if Shared_Libgcc_Default = 'H' and then not Static_Libgcc_Seen and then not Shared_Libgcc_Seen then Linker_Options.Increment_Last; Linker_Options.Table (Linker_Options.Last) := Shared_Libgcc; Num_Args := Num_Args + 1; end if; end if; end Clean_Link_Option_Set; -- Prepare arguments for call to linker Call_Linker : declare Success : Boolean; Args : Argument_List (1 .. Num_Args + 1); Index : Integer := Args'First; begin Args (Index) := Binder_Obj_File; -- Add the object files and any -largs libraries for J in Linker_Objects.First .. Linker_Objects.Last loop Index := Index + 1; Args (Index) := Linker_Objects.Table (J); end loop; -- Add the linker options from the binder file for J in Linker_Options.First .. Linker_Options.Last loop Index := Index + 1; Args (Index) := Linker_Options.Table (J); end loop; -- Finally add the libraries from the --GCC= switch for J in Gcc_Linker_Options.First .. Gcc_Linker_Options.Last loop Index := Index + 1; Args (Index) := Gcc_Linker_Options.Table (J); end loop; if Verbose_Mode then Write_Str (Linker_Path.all); for J in Args'Range loop Write_Str (" "); Write_Str (Args (J).all); end loop; Write_Eol; -- If we are on very verbose mode (-v -v) and a response file -- is used we display its content. if Very_Verbose_Mode and then Tname_FD /= Invalid_FD then Write_Eol; Write_Str ("Response file (" & Tname (Tname'First .. Tname'Last - 1) & ") content : "); Write_Eol; for J in Response_File_Objects.First .. Response_File_Objects.Last loop Write_Str (Response_File_Objects.Table (J).all); Write_Eol; end loop; Write_Eol; end if; end if; System.OS_Lib.Spawn (Linker_Path.all, Args, Success); -- Delete the temporary file used in conjunction with linking if one -- was created. See Process_Bind_File for details. if Tname_FD /= Invalid_FD then Delete (Tname); end if; if not Success then Error_Msg ("error when calling " & Linker_Path.all); Exit_Program (E_Fatal); end if; end Call_Linker; end Link_Step; -- Only keep the binder output file and it's associated object -- file if compiling with the -g option. These files are only -- useful if debugging. if not Debug_Flag_Present then Delete (Binder_Ali_File.all & ASCII.NUL); Delete (Binder_Spec_Src_File.all & ASCII.NUL); Delete (Binder_Body_Src_File.all & ASCII.NUL); Delete (Binder_Obj_File.all & ASCII.NUL); end if; Exit_Program (E_Success); exception when X : others => Write_Line (Exception_Information (X)); Exit_With_Error ("INTERNAL ERROR. Please report"); end Gnatlink;
programs/oeis/108/A108598.asm
neoneye/loda
22
166461
; A108598: Floor(n*((5+sqrt(5))/4)). ; 1,3,5,7,9,10,12,14,16,18,19,21,23,25,27,28,30,32,34,36,37,39,41,43,45,47,48,50,52,54,56,57,59,61,63,65,66,68,70,72,74,75,77,79,81,83,85,86,88,90,92,94,95,97,99,101,103,104,106,108,110,112,113,115,117,119,121 mov $1,$0 add $1,1 seq $1,276881 ; Sums-complement of the Beatty sequence for 1 + sqrt(5). add $0,$1 sub $0,1 div $0,2 add $0,1
projects/project2_lc3_symbol_table_python/p1.asm
pegurnee/2015-01-341
0
172547
<reponame>pegurnee/2015-01-341 .ORIG x1000 LD R2, A LD R3, B ADD R4, R2, R3 ST R4, ANS HALT ANS .FILL X0000 A .FILL X0001 B .FILL X0002 C .STRINGZ "answer" D .BLKW 5 E .FILL X0003 .END
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/discr26.ads
best08618/asylo
7
2770
<gh_stars>1-10 with Discr26_Pkg; package Discr26 is type T1 (D : Integer) is record case D is when 1 => I : Integer; when others => null; end case; end record; type My_T1 is new T1 (Discr26_Pkg.N); procedure Proc; end Discr26;
programs/oeis/336/A336649.asm
neoneye/loda
22
16564
<reponame>neoneye/loda ; A336649: Sum of divisors of A336651(n) (odd part of n divided by its largest squarefree divisor). ; 1,1,1,1,1,1,1,1,4,1,1,1,1,1,1,1,1,4,1,1,1,1,1,1,6,1,13,1,1,1,1,1,1,1,1,4,1,1,1,1,1,1,1,1,4,1,1,1,8,6,1,1,1,13,1,1,1,1,1,1,1,1,4,1,1,1,1,1,1,1,1,4,1,1,6,1,1,1,1,1,40,1,1,1,1,1,1,1,1,4,1,1,1,1,1,1,1,8,4,6 seq $0,336551 ; a(n) = A003557(n) - 1. seq $0,593 ; Sum of odd divisors of n.
src/ether-forms.ads
Lucretia/ether
4
22095
<reponame>Lucretia/ether -- -*- Mode: Ada -*- -- Filename : ether-forms.ads -- Description : Abstraction around the form data returned from the SCGI client (HTTP server). -- Author : <NAME> -- Created On : Tue May 1 13:10:29 2012 with GNAT.Sockets; with Unicode.CES; package Ether.Forms is -- Form data is transmitted to the SCGI server in 1 of 2 ways, GET and PUT. GET provides -- the form data in the URI -- Each item in a form will have some data associated with it. This data will either be -- Unicode.CES.Byte_Sequence if it is normal data or it will be data, i.e. a file that -- has been encoded, Base64? -- -- We will handle the translation of text from whatever it comes in as, i.e. UTF-8 to -- the abstract type, Unicode.CES.Byte_Sequence, the application must then translate it to -- it's preferred encoding. -- -- Some forms can send multiple items per field, this will be handled internally as a list. -- The data stored will look something like this: -- -- +------------------------+ -- | Field | Data | -- +------------------------+ -- | forename | Barry | -- | surname | Watkins | -- | filename | hello.txt | - First in the filename list -- | filename | hello2.txt | - Second in the filename list -- +------------------------+ -- -- Obviously, any file that is transmitted to the SCGI server will also include the file -- data. -- -- Both urlencoded and multipart type forms will be supported by this package and will -- present the data in the same way. -- -- The form data is essentially mapping of: -- field name :-> list of data. -- type Data_Type is -- (Octet, -- This represents a file. -- String -- This is a unicode string encoded to Byte_Sequence. -- ); -- type Form is private; Form_Error : exception; procedure Decode_Query (Data : in String); procedure Decode_Content (Data : access String); -- private -- type Form is -- null record -- end record; end Ether.Forms;
arch/ARM/STM32/svd/stm32l0x3/stm32_svd-stk.ads
morbos/Ada_Drivers_Library
2
15738
<reponame>morbos/Ada_Drivers_Library<gh_stars>1-10 -- This spec has been automatically generated from STM32L0x3.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.STK is pragma Preelaborate; --------------- -- Registers -- --------------- -- SysTick control and status register type CSR_Register is record -- Counter enable ENABLE : Boolean := False; -- SysTick exception request enable TICKINT : Boolean := False; -- Clock source selection CLKSOURCE : Boolean := False; -- unspecified Reserved_3_15 : HAL.UInt13 := 16#0#; -- COUNTFLAG COUNTFLAG : Boolean := False; -- unspecified Reserved_17_31 : HAL.UInt15 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CSR_Register use record ENABLE at 0 range 0 .. 0; TICKINT at 0 range 1 .. 1; CLKSOURCE at 0 range 2 .. 2; Reserved_3_15 at 0 range 3 .. 15; COUNTFLAG at 0 range 16 .. 16; Reserved_17_31 at 0 range 17 .. 31; end record; subtype RVR_RELOAD_Field is HAL.UInt24; -- SysTick reload value register type RVR_Register is record -- RELOAD value RELOAD : RVR_RELOAD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for RVR_Register use record RELOAD at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype CVR_CURRENT_Field is HAL.UInt24; -- SysTick current value register type CVR_Register is record -- Current counter value CURRENT : CVR_CURRENT_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CVR_Register use record CURRENT at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype CALIB_TENMS_Field is HAL.UInt24; -- SysTick calibration value register type CALIB_Register is record -- Calibration value TENMS : CALIB_TENMS_Field := 16#0#; -- unspecified Reserved_24_29 : HAL.UInt6 := 16#0#; -- SKEW flag: Indicates whether the TENMS value is exact SKEW : Boolean := False; -- NOREF flag. Reads as zero NOREF : Boolean := False; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CALIB_Register use record TENMS at 0 range 0 .. 23; Reserved_24_29 at 0 range 24 .. 29; SKEW at 0 range 30 .. 30; NOREF at 0 range 31 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- SysTick timer type STK_Peripheral is record -- SysTick control and status register CSR : aliased CSR_Register; -- SysTick reload value register RVR : aliased RVR_Register; -- SysTick current value register CVR : aliased CVR_Register; -- SysTick calibration value register CALIB : aliased CALIB_Register; end record with Volatile; for STK_Peripheral use record CSR at 16#0# range 0 .. 31; RVR at 16#4# range 0 .. 31; CVR at 16#8# range 0 .. 31; CALIB at 16#C# range 0 .. 31; end record; -- SysTick timer STK_Periph : aliased STK_Peripheral with Import, Address => System'To_Address (16#E000E010#); end STM32_SVD.STK;
Transynther/x86/_processed/NONE/_zr_/i9-9900K_12_0xca.log_21829_479.asm
ljhsiun2/medusa
9
12529
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r15 push %rax push %rdi lea addresses_UC_ht+0x1beec, %r14 nop nop nop nop nop mfence mov $0x6162636465666768, %rdi movq %rdi, (%r14) nop nop add $36246, %r15 pop %rdi pop %rax pop %r15 pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %r9 push %rax push %rbx push %rdi push %rsi // Store lea addresses_US+0x10540, %rbx cmp $9951, %r15 mov $0x5152535455565758, %r9 movq %r9, %xmm3 movups %xmm3, (%rbx) nop nop nop add $13792, %rax // Store mov $0x246f650000000550, %rax nop and $17869, %r10 mov $0x5152535455565758, %r9 movq %r9, %xmm0 movntdq %xmm0, (%rax) // Exception!!! nop nop nop nop mov (0), %rbx nop nop nop add $13326, %rax // Store lea addresses_RW+0x16dc0, %r9 nop nop dec %rsi movl $0x51525354, (%r9) nop nop nop sub $47792, %r9 // Faulty Load lea addresses_UC+0x173c0, %r15 nop nop cmp %r10, %r10 movups (%r15), %xmm6 vpextrq $0, %xmm6, %rsi lea oracles, %r9 and $0xff, %rsi shlq $12, %rsi mov (%r9,%rsi,1), %rsi pop %rsi pop %rdi pop %rbx pop %rax pop %r9 pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 9}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_UC', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 2}} {'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 */
Source/Levels/L1011.asm
AbePralle/FGB
0
15538
<gh_stars>0 ; L1011.asm ; Generated 04.26.2001 by mlevel ; Modified 04.26.2001 by <NAME> INCLUDE "Source/Defs.inc" INCLUDE "Source/Levels.inc" STATE_DEFUSED EQU 2 ;--------------------------------------------------------------------- SECTION "Level1011Section",ROMX ;--------------------------------------------------------------------- L1011_Contents:: DW L1011_Load DW L1011_Init DW L1011_Check DW L1011_Map ;--------------------------------------------------------------------- ; Load ;--------------------------------------------------------------------- L1011_Load: DW ((L1011_LoadFinished - L1011_Load2)) ;size L1011_Load2: call ParseMap ret L1011_LoadFinished: ;--------------------------------------------------------------------- ; Map ;--------------------------------------------------------------------- L1011_Map: INCBIN "Data/Levels/L1011_ssa_sw.lvl" ;--------------------------------------------------------------------- ; Init ;--------------------------------------------------------------------- L1011_Init: DW ((L1011_InitFinished - L1011_Init2)) ;size L1011_Init2: ld a,BANK(L0012_defused_gtx) ld [dialogBank],a call SetPressBDialog ldio a,[mapState] cp STATE_DEFUSED jr nz,.afterRemoveBomb ;remove bomb ld a,MAPBANK ldio [$ff70],a xor a ld hl,$d062 ld [hl+],a ld [hl],a ld hl,$d082 ld [hl+],a ld [hl],a .afterRemoveBomb ret L1011_InitFinished: ;--------------------------------------------------------------------- ; Check ;--------------------------------------------------------------------- L1011_Check: DW ((L1011_CheckFinished - L1011_Check2)) ;size L1011_Check2: call ((.checkAtBomb-L1011_Check2)+levelCheckRAM) ret .checkAtBomb ldio a,[mapState] cp STATE_DEFUSED ret z ld hl,((.checkHeroAtBomb-L1011_Check2)+levelCheckRAM) xor a call CheckEachHero ret .checkHeroAtBomb ld c,a call GetFirst call GetCurZone cp 2 jr z,.atBomb xor a ret .atBomb ld a,STATE_DEFUSED ldio [mapState],a call UpdateState ;remove bomb ld a,MAPBANK ldio [$ff70],a xor a ld hl,$d062 ld [hl+],a ld [hl],a ld hl,$d082 ld [hl+],a ld [hl],a ;check all defused ld d,0 ld a,LEVELSTATEBANK ldio [$ff70],a ld a,[levelState+$b8] cp 2 jr nz,.check2 inc d .check2 ld a,[levelState+$b9] cp 2 jr nz,.check3 inc d .check3 ld a,[levelState+$ba] cp 2 jr nz,.check4 inc d .check4 ld a,[levelState+$bb] cp 2 jr nz,.checkTotal inc d .checkTotal ;if 3 bombs were defused before this one then that's all ld a,d cp 3 jr nz,.bombsRemain ld hl,L0012_alldefused_gtx jr .dialog .bombsRemain ld hl,L0012_defused_gtx .dialog call MakeIdle ld de,((.afterDialog-L1011_Check2)+levelCheckRAM) call SetDialogSkip ld d,h ld e,l call SetSpeakerFromHeroIndex call ShowDialogAtBottom .afterDialog call ClearDialogSkipForward call MakeNonIdle ld a,1 ret L1011_CheckFinished: PRINT "1011 Script Sizes (Load/Init/Check) (of $500): " PRINT (L1011_LoadFinished - L1011_Load2) PRINT " / " PRINT (L1011_InitFinished - L1011_Init2) PRINT " / " PRINT (L1011_CheckFinished - L1011_Check2) PRINT "\n"
src/main/antlr/org/softlang/megal/grammar/Megal.g4
lukashaertel/megal-vm
0
5270
<filename>src/main/antlr/org/softlang/megal/grammar/Megal.g4 grammar Megal; import JSON; // Tokens that describe increase and decrease of indentation tokens { INDENT, DEDENT } // Setup the imports for the Denter Helper @lexer::header { import com.yuvalshavit.antlr4.DenterHelper; import static org.softlang.megal.grammar.LiteralsHelperKt.acceptLiteral; } // Configure denter helper on new line @lexer::members { private final DenterHelper denter = DenterHelper.builder() .nl(NL) .indent(MegalParser.INDENT) .dedent(MegalParser.DEDENT) .pullToken(MegalLexer.super::nextToken); @Override public Token nextToken() { return denter.nextToken(); } } module: 'module' ID NL declaration* group*; submodule: 'submodule' ID (NL | INDENT declaration* group* DEDENT); group: DOC NL declaration+; declaration: submodule | statement | imports; statement: (ID '\'')? node node node cart* bind? (NL | INDENT (cont NL)* DEDENT); bind: '=' node; cart: '*' node; cont: node node; node: (primary | tuple | json | literal | op); primary: abstr? ID (obj | array | tuple)?; abstr: '?'; tuple: '(' (node (',' node)*)? ')'; literal: LITERAL; op: '->' | ':->' | '<-' | '<-:' | '<->' | '<' | '>' | '=' | ':' | '<<' | '>>' | '|>>' | '|<<' | '>>|' | '<<|'; imports: 'import' ID (NL | 'where' INDENT substitution* DEDENT); substitution: ID 'sub' ID NL; // Nested URLs LITERAL: '<' (~'>')* '>' {acceptLiteral(getText())}?; // Qualified identifier ID: FRAG ('.' FRAG)*; // Identifier text fragment FRAG: [A-Za-z_] [A-Za-z0-9_\-]*; // Documentation DOC: '/*' .*? '*/'; // Newline with capturing whitespaces NL: ('\r'? '\n' [ \t]*); // Comments COMMENT: ('//' (~[\n\r])*) -> skip; // Non-significant newline NSNL: '\\' '\r'? '\n' -> skip; // Whitespaces WS: [ \t] -> skip;
libsrc/target/bondwell/ioctl/generic_console_scrollup.asm
ahjelm/z88dk
640
99146
SECTION code_graphics PUBLIC generic_console_scrollup EXTERN swapgfxbk EXTERN swapgfxbk1 EXTERN clsgraph EXTERN CONSOLE_ROWS EXTERN CONSOLE_COLUMNS defc DISPLAY = 0xF800 defc pagein = swapgfxbk defc pageout = swapgfxbk1 generic_console_scrollup: push de push bc call pagein ld hl, DISPLAY + 80 ld de, DISPLAY ld bc,+ ((80) * (CONSOLE_ROWS-1)) ldir ex de,hl ld b,CONSOLE_COLUMNS generic_console_scrollup_3: ld (hl),32 inc hl djnz generic_console_scrollup_3 call pageout pop bc pop de ret
audio/sfx/cry02_3.asm
adhi-thirumala/EvoYellow
16
243193
<filename>audio/sfx/cry02_3.asm SFX_Cry02_3_Ch1: duty 0 unknownsfx0x20 8, 245, 128, 4 unknownsfx0x20 2, 225, 224, 5 unknownsfx0x20 8, 209, 220, 5 endchannel SFX_Cry02_3_Ch2: dutycycle 165 unknownsfx0x20 7, 149, 65, 4 unknownsfx0x20 2, 129, 33, 5 unknownsfx0x20 8, 97, 26, 5 SFX_Cry02_3_Ch3: endchannel
1-base/lace/applet/demo/event/distributed/source/chat-client-local.adb
charlie5/lace
20
29887
<filename>1-base/lace/applet/demo/event/distributed/source/chat-client-local.adb with chat.Registrar, lace.Response, lace.Observer, lace.Event.utility, system.RPC, ada.Exceptions, ada.Text_IO; package body chat.Client.local is -- Utility -- function "+" (From : in unbounded_String) return String renames to_String; -- Responses -- type Show is new lace.Response.item with null record; -- Response is to display the chat message on the users console. -- overriding procedure respond (Self : in out Show; to_Event : in lace.Event.item'Class) is pragma Unreferenced (Self); use ada.Text_IO; the_Message : constant Message := Message (to_Event); begin put_Line (the_Message.Text (1 .. the_Message.Length)); end respond; the_Response : aliased chat.Client.local.show; -- Forge -- function to_Client (Name : in String) return Item is begin return Self : Item do Self.Name := to_unbounded_String (Name); end return; end to_Client; -- Attributes -- overriding function Name (Self : in Item) return String is begin return to_String (Self.Name); end Name; overriding function as_Observer (Self : access Item) return lace.Observer.view is begin return Self; end as_Observer; overriding function as_Subject (Self : access Item) return lace.Subject.view is begin return Self; end as_Subject; -- Operations -- overriding procedure register_Client (Self : in out Item; other_Client : in Client.view) is use lace.Event.utility, ada.Text_IO; begin lace.Event.utility.connect (the_Observer => Self'unchecked_Access, to_Subject => other_Client.as_Subject, with_Response => the_Response'Access, to_Event_Kind => to_Kind (chat.Client.Message'Tag)); put_Line (other_Client.Name & " is here."); end register_Client; overriding procedure deregister_Client (Self : in out Item; other_Client_as_Observer : in lace.Observer.view; other_Client_Name : in String) is use lace.Event.utility, ada.Text_IO; begin begin Self.as_Subject.deregister (other_Client_as_Observer, to_Kind (chat.Client.Message'Tag)); exception when constraint_Error => raise unknown_Client with "Other client not known. Deregister is not required."; end; Self.as_Observer.rid (the_Response'unchecked_Access, to_Kind (chat.Client.Message'Tag), other_Client_Name); put_Line (other_Client_Name & " leaves."); end deregister_Client; overriding procedure Registrar_has_shutdown (Self : in out Item) is use ada.Text_IO; begin put_Line ("The Registrar has shutdown. Press <Enter> to exit."); Self.Registrar_has_shutdown := True; end Registrar_has_shutdown; task check_Registrar_lives is entry start (Self : in chat.Client.local.view); entry halt; end check_Registrar_lives; task body check_Registrar_lives is use ada.Text_IO; Done : Boolean := False; Self : chat.Client.local.view; begin loop select accept start (Self : in chat.Client.local.view) do check_Registrar_lives.Self := Self; end start; or accept halt do Done := True; end halt; or delay 15.0; end select; exit when Done; begin chat.Registrar.ping; exception when system.RPC.communication_Error => put_Line ("The Registrar has died. Press <Enter> to exit."); Self.Registrar_is_dead := True; end; end loop; exception when E : others => new_Line; put_Line ("Error in check_Registrar_lives task."); new_Line; put_Line (ada.exceptions.exception_Information (E)); end check_Registrar_lives; procedure start (Self : in out chat.Client.local.item) is use ada.Text_IO; begin -- Setup -- begin chat.Registrar.register (Self'unchecked_Access); -- Register our client with the registrar. exception when chat.Registrar.Name_already_used => put_Line (+Self.Name & " is already in use."); check_Registrar_lives.halt; return; end; lace.Event.utility.use_text_Logger ("events"); check_Registrar_lives.start (Self'unchecked_Access); declare Peers : constant chat.Client.views := chat.Registrar.all_Clients; begin for i in Peers'Range loop if Self'unchecked_Access /= Peers (i) then begin Peers (i).register_Client (Self'unchecked_Access); -- Register our client with all other clients. Self .register_Client (Peers (i)); -- Register all other clients with our client. exception when system.RPC.communication_Error | storage_Error => null; -- Peer (i) has died, so ignore it and do nothing. end; end if; end loop; end; -- Main loop -- loop declare procedure broadcast (the_Text : in String) is the_Message : constant chat.Client.Message := (Length (Self.Name) + 2 + the_Text'Length, +Self.Name & ": " & the_Text); begin Self.emit (the_Message); end broadcast; chat_Message : constant String := get_Line; begin exit when chat_Message = "q" or Self.Registrar_has_shutdown or Self.Registrar_is_dead; broadcast (chat_Message); end; end loop; -- Shutdown -- if not Self.Registrar_has_shutdown and not Self.Registrar_is_dead then begin chat.Registrar.deregister (Self'unchecked_Access); exception when system.RPC.communication_Error => Self.Registrar_is_dead := True; end; if not Self.Registrar_is_dead then declare Peers : constant chat.Client.views := chat.Registrar.all_Clients; begin for i in Peers'Range loop if Self'unchecked_Access /= Peers (i) then begin Peers (i).deregister_Client ( Self'unchecked_Access, -- Deregister our client with every other client. +Self.Name); exception when system.RPC.communication_Error | storage_Error => null; -- Peer is dead, so do nothing. end; end if; end loop; end; end if; end if; check_Registrar_lives.halt; lace.Event.utility.close; end start; -- 'last_chance_Handler' is commented out to avoid multiple definitions -- of link symbols in 'build_All' test procedure (Tier 5). -- -- procedure last_chance_Handler (Msg : in system.Address; -- Line : in Integer); -- -- pragma Export (C, last_chance_Handler, -- "__gnat_last_chance_handler"); -- -- procedure last_chance_Handler (Msg : in System.Address; -- Line : in Integer) -- is -- pragma Unreferenced (Msg, Line); -- use ada.Text_IO; -- begin -- put_Line ("The Registrar is not running."); -- put_Line ("Press Ctrl-C to quit."); -- check_Registrar_lives.halt; -- delay Duration'Last; -- end last_chance_Handler; end chat.Client.local;
other.7z/SFC.7z/SFC/ソースデータ/ヨッシーアイランド/日本_Ver1/sfc/ys_w28.asm
prismotizm/gigaleak
0
177701
Name: ys_w28.asm Type: file Size: 22387 Last-Modified: '2016-05-13T04:51:15Z' SHA-1: 3BD7EAA78A150060440791826313F6333462AB4F Description: null
audio/sfx/cry25_3.asm
opiter09/ASM-Machina
1
243530
<reponame>opiter09/ASM-Machina<gh_stars>1-10 SFX_Cry25_3_Ch5: duty_cycle_pattern 2, 2, 1, 1 square_note 6, 15, 4, 1856 square_note 15, 14, 3, 1840 square_note 4, 15, 4, 1856 square_note 5, 11, 3, 1864 square_note 8, 13, 1, 1872 sound_ret SFX_Cry25_3_Ch6: duty_cycle_pattern 1, 3, 1, 3 square_note 6, 12, 3, 1810 square_note 15, 11, 3, 1796 square_note 3, 12, 3, 1810 square_note 4, 12, 3, 1825 square_note 8, 11, 1, 1842 sound_ret SFX_Cry25_3_Ch8: noise_note 8, 13, 6, 44 noise_note 12, 12, 6, 60 noise_note 10, 11, 6, 44 noise_note 8, 9, 1, 28 sound_ret
elena_lang/src30/asm/x32/core_vm.asm
bencz/cpu-simulator
2
6142
<reponame>bencz/cpu-simulator<gh_stars>1-10 // --- System Core API -- define NEWFRAME 10014h define INIT_ET 10015h define ENDFRAME 10016h define RESTORE_ET 10017h define OPENFRAME 10019h define CLOSEFRAME 1001Ah rstructure core_vm'dll_name db 101 // e db 108 // l db 101 // e db 110 // n db 097 // a db 118 // v db 109 // m db 046 // . db 100 // d db 108 // l db 108 // l db 0 end rstructure core_vm'SetDebugMode // SetDebugMode db 083 // S db 101 // e db 116 // t db 068 // D db 101 // e db 098 // b db 117 // u db 103 // g db 077 // M db 111 // o db 100 // d db 101 // e db 0 end rstructure core_vm'Interpret // Interpret db 073 // I db 110 // n db 116 // t db 101 // e db 114 // r db 112 // p db 114 // r db 101 // e db 116 // t db 0 end rstructure core_vm'ErrorProc // GetLVMStatus db 071 // G db 101 // e db 116 // t db 076 // L db 086 // V db 077 // M db 083 // S db 116 // t db 097 // a db 116 // t db 117 // u db 115 // s db 0 end rstructure core_vm'DllError // Cannot load dd 12 db 067 // C db 097 // a db 110 // n db 110 // n db 111 // o db 116 // t db 032 // db 108 // l db 111 // o db 097 // a db 100 // d db 032 // db 0 end rstructure core_vm'InvalidDllError // Incorrect elenavm.dll\n dd 21 db 073 // I db 110 // n db 099 // c db 111 // o db 114 // r db 101 // e db 099 // c db 116 // t db 032 // db 101 // e db 108 // l db 101 // e db 110 // n db 097 // a db 118 // v db 109 // m db 046 // . db 100 // d db 108 // l db 108 // l db 010 // \n db 0 end procedure core_vm'console_vm_start // load dll mov eax, rdata : "$native'core_vm'dll_name" push eax call extern 'dlls'KERNEL32.LoadLibraryA test eax, eax jz lbCannotLoadVM push eax // save hModule // ; set debug mode if debug hook is set mov ebx, [data:"'vm_hook"] mov ebx, [ebx] test ebx, ebx jz short labHookEnd mov esi, rdata : "$native'core_vm'SetDebugMode" // load SetDebugMode push esi push eax call extern 'dlls'KERNEL32.GetProcAddress test eax, eax jz lbCannotFindEntry push eax mov eax, esp call [eax] // call SetDebugMode lea esp, [esp+4] // ; set debug section info mov esi, [data:"'vm_hook"] mov [esi+4], eax mov eax, [esp] labHookEnd: // start the program mov esi, rdata : "$native'core_vm'Interpret" // load entry procedure name push esi push eax call extern 'dlls'KERNEL32.GetProcAddress test eax, eax jz lbCannotFindEntry push eax mov eax, esp mov ebx, data:"'vm_tape" push ebx call [eax] // call Interpret lea esp, [esp + 8] test eax, eax jz short lbFailed call extern 'dlls'KERNEL32.FreeLibrary xor eax, eax push eax call extern 'dlls'KERNEL32.ExitProcess ret lbCannotLoadVM: mov ebx, rdata : "$native'core_vm'DllError" // Cannot load elenavm.dll mov ecx, [ebx] lea ebx, [ebx+4] jmp short lbError lbFailed: mov eax, [esp] mov esi, rdata : "$native'core_vm'ErrorProc" // load error procedure name push esi push eax call extern 'dlls'KERNEL32.GetProcAddress push eax mov eax, esp call [eax] lea esp, [esp + 4] mov ebx, eax xor ecx, ecx lbNextLEn: cmp byte ptr [eax], 0 jz lbError add ecx, 1 lea eax, [eax+1] jmp short lbNextLEn lbCannotFindEntry: mov ebx, rdata : "$native'core_vm'InvalidDllError" // Incorrect elenavm.dll mov ecx, [ebx] lea ebx, [ebx+4] lbError: push 0FFFFFFF5h call extern 'dlls'KERNEL32.GetStdHandle push 00 mov edx, esp push 00 // place lpReserved push edx push ecx // place length push ebx push eax call extern 'dlls'KERNEL32.WriteConsoleA lea esp, [esp+4] call extern 'dlls'KERNEL32.FreeLibrary call extern 'dlls'KERNEL32.ExitProcess ret end procedure core_vm'start_n_eval mov eax, [esp+4] push ebx push ecx push edi push esi push ebp call code : % NEWFRAME // set default exception handler mov ebx, code : "$native'core_vm'default_handler" call code : % INIT_ET // invoke symbol mov ebp, esp mov edx, [ebp+20h] mov esi, [edx] call eax call code : % ENDFRAME pop ebp pop esi pop edi pop ecx pop ebx ret end procedure core_vm'eval mov eax, [esp+4] push ebx push ecx push edi push esi call code : % OPENFRAME // invoke symbol call eax call code : % CLOSEFRAME pop esi pop edi pop ecx pop ebx ret end procedure core_vm'default_handler call code : % RESTORE_ET call code : % ENDFRAME xor eax, eax pop ebp pop esi pop edi pop ecx pop ebx ret end
test/Fail/Imports/Issue958.agda
cruhland/agda
1,989
14917
module Imports.Issue958 where postulate FunctorOps : Set module FunctorOps (ops : FunctorOps) where postulate map : Set postulate IsFunctor : Set module IsFunctor (fun : IsFunctor) where postulate ops : FunctorOps open FunctorOps ops public
test/include/gmp-6.1.2/mpn/cnd_sub_n.asm
kcpikkt/apa
43
19455
dnl AMD64 mpn_cnd_add_n, mpn_cnd_sub_n dnl Copyright 2011-2013 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C AMD K8,K9 2 C AMD K10 2 C AMD bd1 2.32 C AMD bobcat 3 C Intel P4 13 C Intel core2 2.9 C Intel NHM 2.8 C Intel SBR 2.4 C Intel atom 5.33 C VIA nano 3 C NOTES C * It might seem natural to use the cmov insn here, but since this function C is supposed to have the exact same execution pattern for cnd true and C false, and since cmov's documentation is not clear about whether it C actually reads both source operands and writes the register for a false C condition, we cannot use it. C * Two cases could be optimised: (1) cnd_add_n could use ADCSBB-from-memory C to save one insn/limb, and (2) when up=rp cnd_add_n and cnd_sub_n could use C ADCSBB-to-memory, again saving 1 insn/limb. C * This runs optimally at decoder bandwidth on K10. It has not been tuned C for any other processor. C INPUT PARAMETERS define(`cnd', `%rdi') dnl rcx define(`rp', `%rsi') dnl rdx define(`up', `%rdx') dnl r8 define(`vp', `%rcx') dnl r9 define(`n', `%r8') dnl rsp+40 ifdef(`OPERATION_cnd_add_n', ` define(ADDSUB, add) define(ADCSBB, adc) define(func, mpn_cnd_add_n)') ifdef(`OPERATION_cnd_sub_n', ` define(ADDSUB, sub) define(ADCSBB, sbb) define(func, mpn_cnd_sub_n)') MULFUNC_PROLOGUE(mpn_cnd_add_n mpn_cnd_sub_n) ABI_SUPPORT(DOS64) ABI_SUPPORT(STD64) ASM_START() TEXT ALIGN(16) PROLOGUE(func) FUNC_ENTRY(4) IFDOS(` mov 56(%rsp), R32(%r8)') push %rbx push %rbp push %r12 push %r13 push %r14 neg cnd sbb cnd, cnd C make cnd mask lea (vp,n,8), vp lea (up,n,8), up lea (rp,n,8), rp mov R32(n), R32(%rax) neg n and $3, R32(%rax) jz L(top) C carry-save reg rax = 0 in this arc cmp $2, R32(%rax) jc L(b1) jz L(b2) L(b3): mov (vp,n,8), %r12 mov 8(vp,n,8), %r13 mov 16(vp,n,8), %r14 and cnd, %r12 mov (up,n,8), %r10 and cnd, %r13 mov 8(up,n,8), %rbx and cnd, %r14 mov 16(up,n,8), %rbp ADDSUB %r12, %r10 mov %r10, (rp,n,8) ADCSBB %r13, %rbx mov %rbx, 8(rp,n,8) ADCSBB %r14, %rbp mov %rbp, 16(rp,n,8) sbb R32(%rax), R32(%rax) C save carry add $3, n js L(top) jmp L(end) L(b2): mov (vp,n,8), %r12 mov 8(vp,n,8), %r13 mov (up,n,8), %r10 and cnd, %r12 mov 8(up,n,8), %rbx and cnd, %r13 ADDSUB %r12, %r10 mov %r10, (rp,n,8) ADCSBB %r13, %rbx mov %rbx, 8(rp,n,8) sbb R32(%rax), R32(%rax) C save carry add $2, n js L(top) jmp L(end) L(b1): mov (vp,n,8), %r12 mov (up,n,8), %r10 and cnd, %r12 ADDSUB %r12, %r10 mov %r10, (rp,n,8) sbb R32(%rax), R32(%rax) C save carry add $1, n jns L(end) ALIGN(16) L(top): mov (vp,n,8), %r12 mov 8(vp,n,8), %r13 mov 16(vp,n,8), %r14 mov 24(vp,n,8), %r11 and cnd, %r12 mov (up,n,8), %r10 and cnd, %r13 mov 8(up,n,8), %rbx and cnd, %r14 mov 16(up,n,8), %rbp and cnd, %r11 mov 24(up,n,8), %r9 add R32(%rax), R32(%rax) C restore carry ADCSBB %r12, %r10 mov %r10, (rp,n,8) ADCSBB %r13, %rbx mov %rbx, 8(rp,n,8) ADCSBB %r14, %rbp mov %rbp, 16(rp,n,8) ADCSBB %r11, %r9 mov %r9, 24(rp,n,8) sbb R32(%rax), R32(%rax) C save carry add $4, n js L(top) L(end): neg R32(%rax) pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx FUNC_EXIT() ret EPILOGUE()
src/main/resources/g.g4
Dastamn/antlr-compiler
0
4017
grammar g; /*parser*/ axiom: importLib* MODIFIER? 'class_SJ' CLASS_NAME L_BR declaration* mainBlock? R_BR EOF; importLib: 'import' lib SEMI_COLON+; lib: LIBRARY | ID; declaration: VAR_TYPE idList SEMI_COLON+; idList: ID (COMA ID)*; mainBlock: 'main_SJ' instBlock; instBlock: L_BR instruction* R_BR; instruction: (affectation | input | output) SEMI_COLON+ | condition; affectation: ID ASSIGN expression; expression : L_PAREN expression R_PAREN # ExpParen | MINUS expression #UnaryMinus | expression TIMES expression # Times | expression DIV expression # Div | expression PLUS expression # Plus | expression MINUS expression # Minus | NUMBER # Number | STR # Str | ID # Id; condition: ifStatement thenBlock elseBlock?; thenBlock: (instBlock | instruction); ifStatement: 'Si' L_PAREN evaluation R_PAREN 'Alors'; evaluation: L_PAREN evaluation R_PAREN # EvalParen | expression evalOperand expression # Comp | NOT evaluation # Not | evaluation AND evaluation # And | evaluation OR evaluation # Or; evalOperand: GT | GTE | LT | LTE | EQ | NOT_EQ; elseBlock: 'Sinon' (instBlock | instruction) | 'Sinon' ifStatement (instBlock | instruction); input: 'In_SJ' L_PAREN FORMAT COMA idList R_PAREN; output: 'Out_SJ' L_PAREN outputArgs R_PAREN; outputArgs: strFormat outputIdList?; strFormat: (FORMAT | STR); outputIdList: COMA idList; /*lexer*/ fragment DIGIT: [0-9]; fragment LOWERCASE: [a-z]; fragment UPPERCASE: [A-Z]; fragment ANYCASE: LOWERCASE | UPPERCASE; fragment INT: 'int_SJ'; fragment FLOAT: 'float_SJ'; fragment STRING: 'string_SJ'; fragment INT_FORMAT: '%d'; fragment FLOAT_FORMAT: '%f'; fragment STRING_FORMAT: '%s'; fragment LINE_COMMENT: '//' (LINE_COMMENT | ~[\n\r])*; fragment MULTI_LINE_COMMENT: '/*' (LINE_COMMENT | .)*? '*/'; fragment POINT: '.'; fragment UNDERSCORE: '_'; QUOT: '"'; SEMI_COLON: ';'; COMA: ','; L_PAREN: '('; R_PAREN: ')'; TIMES: '*'; DIV: '/'; PLUS: '+'; MINUS: '-'; ASSIGN: ':='; GT: '>'; GTE: '>='; LT: '<'; LTE: '<='; EQ: '='; NOT_EQ: '!='; AND: '&'; OR: '|'; NOT: '!'; L_BR: '{'; R_BR: '}'; CLASS_NAME: UPPERCASE (DIGIT | ANYCASE)*; MODIFIER: 'public' | 'protected'; VAR_TYPE: INT | FLOAT | STRING; ID: ANYCASE (DIGIT | ANYCASE)*; LIBRARY: ANYCASE (ANYCASE | DIGIT | UNDERSCORE | POINT)*; NUMBER: DIGIT+ | DIGIT* [.,] DIGIT+; FORMAT: QUOT (INT_FORMAT | FLOAT_FORMAT | STRING_FORMAT | ' ')+ QUOT; STR: QUOT (~[\n\r"]|'\\"')* QUOT; COMMENT: (LINE_COMMENT | MULTI_LINE_COMMENT) -> skip; WHITESPACE: [ \t\r\n]+ -> skip;
test/asset/agda-stdlib-1.0/Data/AVL/Value.agda
omega12345/agda-mode
5
10429
------------------------------------------------------------------------ -- The Agda standard library -- -- Values for AVL trees -- Values must respect the underlying equivalence on keys ----------------------------------------------------------------------- {-# OPTIONS --without-K --safe #-} open import Relation.Binary using (Setoid; _Respects_) module Data.AVL.Value {a ℓ} (S : Setoid a ℓ) where open import Level using (suc; _⊔_) import Function as F open Setoid S renaming (Carrier to Key) record Value v : Set (a ⊔ ℓ ⊔ suc v) where constructor MkValue field family : Key → Set v respects : family Respects _≈_ -- The function `const` is defined using copatterns to prevent eager -- unfolding of the function in goal types. const : ∀ {v} → Set v → Value v Value.family (const V) = F.const V Value.respects (const V) = F.const F.id
tools-src/gnu/gcc/gcc/ada/a-comlin.ads
enfoTek/tomato.linksys.e2000.nvram-mod
80
16711
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . C O M M A N D _ L I N E -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 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. -- -- -- ------------------------------------------------------------------------------ package Ada.Command_Line is pragma Preelaborate (Command_Line); function Argument_Count return Natural; -- If the external execution environment supports passing arguments to a -- program, then Argument_Count returns the number of arguments passed to -- the program invoking the function. Otherwise it return 0. -- -- In GNAT: Corresponds to (argc - 1) in C. function Argument (Number : Positive) return String; -- If the external execution environment supports passing arguments to -- a program, then Argument returns an implementation-defined value -- corresponding to the argument at relative position Number. If Number -- is outside the range 1 .. Argument_Count, then Constraint_Error is -- propagated. -- -- in GNAT: Corresponds to argv [n] (for n > 0) in C. function Command_Name return String; -- If the external execution environment supports passing arguments to -- a program, then Command_Name returns an implementation-defined value -- corresponding to the name of the command invoking the program. -- Otherwise Command_Name returns the null string. -- -- in GNAT: Corresponds to argv [0] in C. type Exit_Status is new Integer; Success : constant Exit_Status; Failure : constant Exit_Status; procedure Set_Exit_Status (Code : Exit_Status); private Success : constant Exit_Status := 0; Failure : constant Exit_Status := 1; -- The following locations support the operation of the package -- Ada.Command_Line_Remove, whih provides facilities for logically -- removing arguments from the command line. If one of the remove -- procedures is called in this unit, then Remove_Args/Remove_Count -- are set to indicate which arguments are removed. If no such calls -- have been made, then Remove_Args is null. Remove_Count : Natural; -- Number of arguments reflecting removals. Not defined unless -- Remove_Args is non-null. type Arg_Nums is array (Positive range <>) of Positive; type Arg_Nums_Ptr is access Arg_Nums; -- An array that maps logical argument numbers (reflecting removal) -- to physical argument numbers (e.g. if the first argument has been -- removed, but not the second, then Arg_Nums (1) will be set to 2. Remove_Args : Arg_Nums_Ptr := null; -- Left set to null if no remove calls have been made, otherwise set -- to point to an appropriate mapping array. Only the first Remove_Count -- elements are relevant. pragma Import (C, Set_Exit_Status, "__gnat_set_exit_status"); end Ada.Command_Line;
apps/breakfast/pde_fw/toast/examples/Assembly (CCE)/msp430x24x_tb_07.asm
tp-freeforall/breakfast
1
163995
<filename>apps/breakfast/pde_fw/toast/examples/Assembly (CCE)/msp430x24x_tb_07.asm ;****************************************************************************** ; MSP430F249 Demo - Timer_B, PWM TB1-6, Up Mode, DCO SMCLK ; ; Description: This program generates six PWM outputs on P4.1-6 using ; Timer_B configured for up mode. The value in CCR0, 512-1, defines the PWM ; period and the values in CCR1-6 the PWM duty cycles. Using ~1.1MHz SMCLK ; as TBCLK, the timer period is ~ (512/1.045M) ~ 500us. ; ACLK = na, SMCLK = MCLK = TBCLK = default DCO ~1.1MHz. ; ; MSP430F249 ; ----------------- ; /|\| XIN|- ; | | | ; --|RST XOUT|- ; | | ; | P4.1/TB1|--> CCR1 - 75% PWM ; | P4.2/TB2|--> CCR2 - 25% PWM ; | P4.3/TB3|--> CCR3 - 12.5% PWM ; | P4.4/TB4|--> CCR4 - 6.25% PWM ; | P4.5/TB5|--> CCR5 - 3.125% PWM ; | P4.6/TB6|--> CCR6 - 1.5625% PWM ; ; <NAME> ; Texas Instruments Inc. ; May 2008 ; Built Code Composer Essentials: v3 FET ;******************************************************************************* .cdecls C,LIST, "msp430x24x.h" ;------------------------------------------------------------------------------- .text ;Program Start ;------------------------------------------------------------------------------- RESET mov.w #0500h,SP ; Initialize stackpointer StopWDT mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop WDT SetupP4 mov.b #07Eh, &P4DIR ; P4.1 - P4.6 output mov.b #07Eh, &P4SEL ; P4.1 - P4.6 TBx options SetupTA mov.w #512-1,&TBCCR0 ;PWM period mov.w #OUTMOD_7, &TBCCTL1 ; CCR1 reset/set mov.w #0384h, &TBCCR1 ; CCR1 PWM duty cycle mov.w #OUTMOD_7, &TBCCTL2 mov.w #0128h, &TBCCR2 mov.w #OUTMOD_7, &TBCCTL3 mov.w #064, &TBCCR3 mov.w #OUTMOD_7, &TBCCTL4 mov.w #032, &TBCCR4 mov.w #OUTMOD_7, &TBCCTL5 mov.w #016, &TBCCR5 mov.w #OUTMOD_7, &TBCCTL6 mov.w #8, &TBCCR6 mov.w #TBSSEL_2 + MC_1, &TBCTL ;SMCLK, up mode Mainloop bis.w #LPM0,SR ; LPM0, nop ; Required for debugger ;------------------------------------------------------------------------------- ; Interrupt Vectors ;------------------------------------------------------------------------------- .sect ".reset" ; MSP430 RESET Vector .short RESET ; .end
Transynther/x86/_processed/AVXALIGN/_zr_/i3-7100_9_0x84_notsx.log_573_1194.asm
ljhsiun2/medusa
9
179552
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r8 push %rdi lea addresses_A_ht+0xb1d0, %r12 clflush (%r12) inc %r13 vmovups (%r12), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %r8 nop sub %rdi, %rdi pop %rdi pop %r8 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r15 push %r8 push %r9 push %rax push %rsi // Faulty Load mov $0x5d0, %rsi nop nop nop add %rax, %rax mov (%rsi), %r9d lea oracles, %r15 and $0xff, %r9 shlq $12, %r9 mov (%r15,%r9,1), %r9 pop %rsi pop %rax pop %r9 pop %r8 pop %r15 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_P', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_P', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'00': 573} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
oeis/277/A277369.asm
neoneye/loda-programs
11
94861
; A277369: a(0) = 5, a(1) = 8; for n>1, a(n) = 2*a(n-1) + a(n-2). ; Submitted by <NAME> ; 5,8,21,50,121,292,705,1702,4109,9920,23949,57818,139585,336988,813561,1964110,4741781,11447672,27637125,66721922,161080969,388883860,938848689,2266581238,5472011165,13210603568,31893218301,76997040170,185887298641,448771637452,1083430573545,2615632784542,6314696142629,15245025069800,36804746282229,88854517634258,214513781550745,517882080735748,1250277943022241,3018437966780230,7287153876582701,17592745719945632,42472645316473965,102538036352893562,247548718022261089,597635472397415740 mov $1,6 mov $3,2 lpb $0 sub $0,1 mov $2,$3 add $3,$1 mov $1,$2 sub $3,1 add $1,$3 lpe mov $0,$1 sub $0,1
msp430-gcc-tics/msp430-gcc-7.3.1.24-source-full/gcc/gcc/testsuite/gnat.dg/null_pointer_deref2.adb
TUDSSL/TICS
7
16838
<reponame>TUDSSL/TICS -- { dg-do run } -- { dg-options "-gnatp" } -- This test requires architecture- and OS-specific support code for unwinding -- through signal frames (typically located in *-unwind.h) to pass. Feel free -- to disable it if this code hasn't been implemented yet. procedure Null_Pointer_Deref2 is task T; task body T is type Int_Ptr is access all Integer; function Ident return Int_Ptr is begin return null; end; Data : Int_Ptr := Ident; begin Data.all := 1; exception when others => null; end T; begin null; end;
Transynther/x86/_processed/NONE/_zr_xt_/i9-9900K_12_0xa0_notsx.log_21829_61.asm
ljhsiun2/medusa
9
84929
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r14 push %r15 push %rcx push %rdi push %rsi lea addresses_WT_ht+0x147dd, %r14 cmp %r15, %r15 and $0xffffffffffffffc0, %r14 vmovntdqa (%r14), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %r13 nop nop nop nop xor %rdi, %rdi lea addresses_A_ht+0x27d, %rsi lea addresses_normal_ht+0xfcc5, %rdi nop nop nop nop nop xor $35703, %r11 mov $49, %rcx rep movsw nop xor %r11, %r11 lea addresses_A_ht+0xac3b, %rdi nop nop nop nop sub $35916, %r13 movb (%rdi), %cl nop nop nop and $39511, %rdi lea addresses_WT_ht+0x8e25, %r15 nop nop nop dec %r11 movw $0x6162, (%r15) nop add %r14, %r14 lea addresses_normal_ht+0x19b9d, %rsi lea addresses_WC_ht+0x10565, %rdi clflush (%rsi) nop and $36093, %r12 mov $123, %rcx rep movsb nop cmp %r12, %r12 lea addresses_normal_ht+0xc9d, %r11 nop nop nop nop nop and %r12, %r12 movb $0x61, (%r11) nop nop nop nop nop cmp %rcx, %rcx lea addresses_D_ht+0x155d, %rsi lea addresses_WT_ht+0x1419d, %rdi nop add %r13, %r13 mov $70, %rcx rep movsq nop nop nop nop nop cmp $9592, %r11 lea addresses_normal_ht+0x409d, %rdi nop xor %r14, %r14 movl $0x61626364, (%rdi) nop nop xor %r13, %r13 lea addresses_A_ht+0x12dcd, %rsi lea addresses_D_ht+0x1023c, %rdi nop nop sub $14771, %r14 mov $40, %rcx rep movsl nop nop sub $63844, %r11 lea addresses_UC_ht+0x1275d, %r14 dec %rsi movups (%r14), %xmm6 vpextrq $1, %xmm6, %rdi nop nop nop nop nop and $23135, %r12 pop %rsi pop %rdi pop %rcx pop %r15 pop %r14 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %rbp push %rcx push %rdi push %rsi // REPMOV lea addresses_UC+0xb75d, %rsi lea addresses_UC+0x249d, %rdi nop nop xor $47275, %r14 mov $115, %rcx rep movsw nop xor $14577, %rsi // Store lea addresses_UC+0x158f1, %r15 nop nop nop nop dec %r10 mov $0x5152535455565758, %rsi movq %rsi, (%r15) nop nop nop xor %rdi, %rdi // Faulty Load lea addresses_A+0x1dc9d, %r14 nop nop nop nop nop dec %r15 mov (%r14), %r10w lea oracles, %rsi and $0xff, %r10 shlq $12, %r10 mov (%rsi,%r10,1), %r10 pop %rsi pop %rdi pop %rcx pop %rbp pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC', 'congruent': 6, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 2}} [Faulty Load] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 2}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1, 'NT': True, 'same': False, 'congruent': 1}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': True, 'size': 2, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 11}} {'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 10}} {'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'} {'35': 21828, '00': 1} 00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
test/interaction/CompilationWarnings.agda
shlevy/agda
1,989
12784
-- See also test/Succeed/InlineCompiled.agda module _ where id : {A : Set} → A → A id x = x {-# INLINE id #-} -- this is pointless and should generate a warning in the info buffer {-# COMPILE GHC id = \ _ x -> x #-}
src/src/c/borlandc/dpmi32/peek.asm
amindlost/wdosx
7
170460
.386 .model flat,C PUBLIC peek PUBLIC peekb .code peek proc near push ds mov ds,[esp+4] mov edx,[esp+8] mov eax,[edx] pop ds ret peek endp peekb proc near push ds mov ds,[esp+4] mov edx,[esp+8] sub eax,eax mov al,[edx] pop ds ret peekb endp end
data/pokemon/base_stats/magikarp.asm
Dev727/ancientplatinum
2
11456
db 0 ; species ID placeholder db 20, 10, 55, 80, 15, 20 ; hp atk def spd sat sdf db WATER, WATER ; type db 255 ; catch rate db 20 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 5 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/magikarp/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_SLOW ; growth rate dn EGG_WATER_2, EGG_DRAGON ; egg groups ; tm/hm learnset tmhm ; end
as4.adb
twinbee/djikstrasStabilizing
0
12133
<filename>as4.adb ----------------------------csc410/prog4/as4.adb---------------------------- -- Author: <NAME> -- Class: CSC410 Burgess -- Date: 10-05-04 Modified: 10-17-04 -- Due: 10-12-04 -- Desc: Assignment 4: DJIKSTRA'S STABILIZING ALGORITHM -- -- a nonproduction implementation of -- DJIKSTRA's algorithm which describes -- mutual exclusion, fairness, and deadlock avoidance -- n processes (TASKS), and is self-correcting -- -- BRIEF: (please read all of this) -- n processes form a [directed] virtual ring topology, and -- use an internal integer counter called flag to determine -- which may go next. In general, a process may not proceed -- unless its flag is not equal to its previous neighbor, except for process0 -- -- The algorithm is ASYMMETRIC. Process0 behaves differently than -- processes [1..n] in several respects. Also, since the -- asymmetrical behavior is neccessary for the algorithm to -- continue, some other process MUST assume the behavior of -- Process0 in case that process is killed or quits. -- -- The algorithm is self-stabilizing, so it should operate on a -- "dummy resource" for several iterations (up to 10) eahc time -- the tasks are reordered. I will try to add this feature to -- code soon. -- !! MUTUAL EXCLUSION IS NOT GUARANTEED UNTIL THE TASKS STABILIZE !! -- -- DJIKSTRA implemented as described in -- "Algorithms for Mutual Exclusion", M. Raynal -- MIT PRESS Cambridge, 1986 ISBN: 0-262-18119-3 -- with minor revisions ---------------------------------------------------------------- -- Refactorings 10-05-04: (denoted @FIX@) -- (1) enumerated types {_PREV_, _SELF_, _NEXT_} instead of {-1, 0 1} -- (2) message passing / reindezvouz instead of function calls -- (3) slect instead of case -- (4) linked list of processes instread of array -- (5) randomly kill of processes including process #1, check for stabiliz. -- (6) remove "magic" constants ---------------------------------------------------------------- -- dependencies -- style note: the reasons to "with in" but not "use" packages are -- (1) to avoid crowding of the namespace -- (2) to be explicit where abstract data types and methods come from. -- for instance, line randomPool : Ada.Numerics.Float_Random.Generator; -- is more explicit than randomPool : Generator; WITH ADA.TEXT_IO; USE ADA.TEXT_IO; WITH ADA.INTEGER_TEXT_IO; USE ADA.INTEGER_TEXT_IO; WITH ADA.NUMERICS.FLOAT_RANDOM; USE ADA.NUMERICS.FLOAT_RANDOM; --by request only WITH ADA.CALENDAR; -- (provides cast: natural -> time for input into delay) WITH ADA.STRINGS; USE ADA.STRINGS; ---------------------------------------------------------------- ---------------------------------------------------------------- PROCEDURE AS4 IS --globals are: RandomPool, constants scale_factor, max_tasks, SPACES randomPool : Ada.Numerics.Float_Random.Generator; -- yields a random Natural after seed MAX_TASKS : CONSTANT := 100; --global constant for mem allocation restriction SCALE_FACTOR : CONSTANT := 1.0; --used to increase "spread" of random delays SPACES : STRING(1..80) := (Others => ' '); --for convenience in string manipulations TYPE RX; --outer, receiving task --this task contains djikstra's algorithm (djikstraTask), -- and also the rendezvouz entries for interprocess communication -- which is message passing, using entry calls. -- its primary job is to listen in case a DjistraTask of some other task -- tried to communicate with it, using the ENTRIES specified for the SELECT -- statement. TYPE RX_PTR IS ACCESS RX; --for our array, so we do not lose track ---- Begin RX_Task declaration and definition ---- TASK TYPE RX IS --outer task spawns algorithm and then waits for a msg ENTRY init ( --rendezvouz for initializing each task i : Integer; --process ID number. may NOT change if processes die self : RX_Ptr; --pointer so the process can refer to itself prev : RX_Ptr; --pointer to ring neighbor prev next : RX_Ptr; --pointer to ring neighbor next selfFlag : Integer; --flag of self prevFlag : Integer; --flag of prev, for comparisons nextFlag : Integer; --flag of next, for comparisons n : Integer; --total number of tasks lowID : boolean -- am I the chosen one? ); ENTRY Receive( mesgType : Character; -- @FIX@ should be seprate rendezvous-es id : Integer; -- process id flag : Integer; -- new flag value prev : RX_Ptr; -- prev pointer next : RX_Ptr; -- next pointer lowId : boolean -- am I the new low? ); END RX; --end specification TASK BODY RX IS -- "local globals" (specific to each task) procArray : array (0..2) of RX_Ptr; flagArray : array (0..2) of Integer := (Others => 0); --flagarray(0) is flag of prev process --flagarray(1) is flag of curr process --flagarray(2) is flag of next process --same holds for procArray myId : Integer; recId : Integer; num_count : Integer; suicide : Boolean := false; -- used to determine if the process' death has been requested lowestId : Boolean; -- used to determine if special protocol is in order ---- Begin AL_Task declaration and definition ---- TASK TYPE djikstraTask IS --gee, that was short END djikstraTask; --interior task, does the algorithm TASK BODY djikstraTask IS BEGIN LOOP IF (lowestId) THEN -- Process 0, special protocol -- LOOP EXIT WHEN flagArray(1) = flagArray(0); END LOOP; --equivalent to wait loop --!! IN CRITICAL SECTION PROCESS[0] !!-- Put (myId, (80/myId -8)); Put_line (" in CS"); delay (Standard.Duration( random(randomPool) * SCALE_FACTOR) ); -- note: callbacks, function calls, or code may be placed here -- in order to use this code in some production environment -- (in place of the delay) Put (myId, (80/myId-8)); Put_line(" out CS"); --!! OUT CRITICAL SECTION PROCESS[0] !!-- flagArray(1) := (flagArray(1) + 1) MOD num_count; procArray(2).Receive('U', myId, flagArray(1), null, null, FALSE); -- done Process0 protocol -- --=====================================================-- ELSE --IF (NOT lowestID) THEN -- process[k NOT EQUAL 0] -- LOOP EXIT WHEN (flagArray(1) /= flagArray(0)); END LOOP; --!! IN CRITICAL SECTION PROCESS[K] !!-- Put (myId, (80/myId-8)); Put_line (" in CS"); delay (Standard.Duration( random(randomPool) * SCALE_FACTOR) ); -- note: callbacks, function calls, or code may be placed here -- in order to use this code in some production environment -- (in place of the delay) Put (myId, (80/myId-8)); Put_line (" out CS"); --!! OUT CRITICAL SECTION PROCESS[K] !!-- flagArray(1) := flagArray(0); procArray(2).Receive('U', myId, flagArray(1), null, null, FALSE); END IF; END LOOP; END djikstraTask; ---- End AL_Task declaration and definition ---- TYPE Djik IS ACCESS djikstraTask; ptr : Djik; --pointer to interior task for algorithm from RX_TASK BEGIN -- Entry Point to initalize our id's from the main procedure ACCEPT init ( i : IN Integer; --process number of self self : IN RX_Ptr; --pointer to self prev : IN RX_Ptr; --pointer to prev in ring next : IN RX_Ptr; --pointer to next in ring selfFlag : IN Integer; --self's flag initializer prevFlag : IN Integer; --flag of prev intial condition nextFlag : IN Integer; --flag of next initial condition n : IN Integer; --num tasks lowID : IN Boolean --am i the chosen one? ) DO procArray(1) := self; -- "save my pointer to self" procArray(0) := prev; -- "save my pointer to prev" procArray(2) := next; -- "save my pointer to next, I'm in the list!" flagArray(1) := selfFlag; --initialize my flag flagArray(0) := prevFlag; --save my copy of prev's flag flagArray(2) := nextFlag; --save my copy of next's flag num_count := n; --save number of processes myId := i; --save self's process number lowestId := lowId; END init; ptr := new djikstraTask; --throw of an djikstra_TASK for each R(eceving X_TASK -- RX twiddles its thumbs and waits for messages. -- there should be a delay here, but I cant get the timing to work well -- without giving me significant lag problems LOOP ACCEPT Receive ( mesgType : Character; --@FIX@ it! id : Integer; flag : Integer; prev : RX_Ptr; next : RX_Ptr; lowId: boolean ) DO CASE mesgType IS WHEN 'U' => -- update message BEGIN Put (myId, (1+4*myId)); Put (","); Put (id,0); Put_line(" Update"); -- As we always receive update messages from the prev neighbour -- we simply change our local copy of prev's new flag flagArray(0) := flag; END; WHEN 'N' => -- newnode message BEGIN Put (myId, (1+4*myId)); Put (","); Put (id,0); Put_line (" Neighbour"); IF (prev = null) THEN -- Someone is updating our next neighbour procArray( 2) := next; flagArray( 2) := flag; ELSE -- Someone is updating our prev neighbour procArray(0) := prev; flagArray(0) := flag; lowestID := lowID; END IF; END; WHEN 'R' => -- remove msg -- this TASK is doomed!! BEGIN Put (myId, (1+4*myId)); Put (","); Put (id,0); Put_line (" RIP"); procArray(0).Receive('N', myId, flagArray(2),null,procArray(2),FALSE); -- Tell my prev who my next was -- Also, if dying, we pass true as the lowest id to the next, -- as it is our next lowest, if we were the lowest already IF (lowestID) THEN procArray(2).Receive('N',myId,flagArray(0), procArray(0), null,TRUE); -- Tell my next who my prev was, and crown it the new low ELSE procArray(2).Receive('N',myId,flagArray(0), procArray(0),null,FALSE); -- Tell my next who my prev was END IF; suicide := true; -- kill thyself, as requested by a higher power! END; WHEN Others => null; --needed for {case/select} default path (do nothing) END CASE; END Receive; EXIT WHEN suicide; END LOOP; END RX; ---- End RX_Task declaration and definition ---- PROCEDURE Driver IS --seperate out variables to avoid excess globals numtasks_user, seed_user : Integer; --user defined at runtime by std. in ptrArray : array (0..MAX_TASKS) of RX_Ptr; --to keep up with each task spun specialProtocol : boolean; --temp var used for which djistra protocol to use BEGIN put("# random seed: "); get(seed_user); --to ensure a significantly random series, a seed is needed -- to generate pseudo-random numbers Ada.Numerics.Float_Random.Reset(randomPool,seed_user); --seed the random number pool --sanity checked on the input LOOP put("# tasks[1-50]: "); get(numTasks_user); --sanity checked input EXIT WHEN (numTasks_user > 0 AND numTasks_user <= MAX_TASKS); END LOOP; FOR task_counter IN 0 .. (numTasks_user - 1) LOOP ptrArray(task_counter) := new RX; END LOOP; --spin out all our processes --seperate, bc we'll want pointers to next process at initialization FOR task_counter IN 0 .. (numTasks_user - 1) LOOP IF TASK_COUNTER = 0 THEN specialProtocol := TRUE; ELSE specialProtocol := FALSE; END IF; ptrArray(task_counter).init( task_counter, --this will be the process' id number ptrArray(task_counter), --this is the process' pointer to itself ptrArray((task_counter - 1) MOD numTasks_user), --process' pointer to prev ptrArray((task_counter + 1) MOD numTasks_user), --process' pointer to next task_counter, -- process' initial flag ( so flag(n)=n ) -- in order to demonstrate stabilization ((task_counter - 1) MOD numTasks_user), --process' initial prev flag ( so flag(_PREV)=n-1 ) ((task_counter + 1) MOD numTasks_user), --process' initial next flag ( so flag(_NEXT)=n+1 ) numTasks_user, --number of processes, which is constant specialProtocol --flag for asymmetry in the algorithm ); END LOOP; --initialize out all our processes FOR kill_index IN REVERSE 0 .. (numTasks_user - 1) LOOP delay (600.0); Put_Line ("Going to kill random process ... "); ptrArray(kill_index).Receive('R', 0, 0, null, null, FALSE); END LOOP; --kill out all our processes END Driver; -- main exec for AS4.adb: BEGIN Driver; END AS4;
chap15/ex36/no_unroll_reduce.asm
JamesType/optimization-manual
374
173606
<reponame>JamesType/optimization-manual ; ; Copyright (C) 2021 by Intel Corporation ; ; Permission to use, copy, modify, and/or distribute this software for any ; purpose with or without fee is hereby granted. ; ; 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. ; ; .globl no_unroll_reduce ; float no_unroll_reduce(float *a, uint32_t len) ; On entry: ; rcx = a ; edx = len ; xmm0 = retval .code no_unroll_reduce PROC public push rbx mov eax, edx mov rbx, rcx vmovups ymm0, ymmword ptr [rbx] sub eax, 8 loop_start: add rbx, 32 vaddps ymm0, ymm0, ymmword ptr [rbx] sub eax, 8 jnz loop_start vextractf128 xmm1, ymm0, 1 vaddps xmm0, xmm0, xmm1 vpermilps xmm1, xmm0, 0eh vaddps xmm0, xmm0, xmm1 vpermilps xmm1, xmm0, 1 vaddss xmm0, xmm0, xmm1 ; The following instruction is not needed as xmm0 already ; holds the return value. ; movss result, xmm0 pop rbx vzeroupper ret no_unroll_reduce ENDP end
components/src/touch_panel/ft5336/ft5336.ads
rocher/Ada_Drivers_Library
192
17594
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- Generic driver for the FT5336 touch panel with HAL; use HAL; with HAL.I2C; use HAL.I2C; with HAL.Touch_Panel; use HAL.Touch_Panel; package FT5336 is type FT5336_Device (Port : not null Any_I2C_Port; I2C_Addr : I2C_Address) is limited new Touch_Panel_Device with private; function Check_Id (This : in out FT5336_Device) return Boolean; -- Checks the ID of the touch panel controller, returns false if not found -- or invalid. procedure TP_Set_Use_Interrupts (This : in out FT5336_Device; Enabled : Boolean); -- Whether the data is retrieved upon interrupt or by polling by the -- software. overriding procedure Set_Bounds (This : in out FT5336_Device; Width : Natural; Height : Natural; Swap : HAL.Touch_Panel.Swap_State); -- Set screen bounds. Touch_State must should stay within screen bounds overriding function Active_Touch_Points (This : in out FT5336_Device) return HAL.Touch_Panel.Touch_Identifier; -- Retrieve the number of active touch points overriding function Get_Touch_Point (This : in out FT5336_Device; Touch_Id : HAL.Touch_Panel.Touch_Identifier) return HAL.Touch_Panel.TP_Touch_State; -- Retrieves the position and pressure information of the specified -- touch overriding function Get_All_Touch_Points (This : in out FT5336_Device) return HAL.Touch_Panel.TP_State; -- Retrieves the position and pressure information of every active touch -- points private type FT5336_Device (Port : not null Any_I2C_Port; I2C_Addr : I2C_Address) is limited new HAL.Touch_Panel.Touch_Panel_Device with record LCD_Natural_Width : Natural := 0; LCD_Natural_Height : Natural := 0; Swap : Swap_State := 0; end record; function I2C_Read (This : in out FT5336_Device; Reg : UInt8; Status : out Boolean) return UInt8; procedure I2C_Write (This : in out FT5336_Device; Reg : UInt8; Data : UInt8; Status : out Boolean); end FT5336;
Transynther/x86/_processed/NONE/_zr_/i7-7700_9_0xca.log_21829_1528.asm
ljhsiun2/medusa
9
242026
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x14fee, %rax nop nop nop nop add $6520, %r9 movb $0x61, (%rax) nop nop nop nop xor $20153, %rbp lea addresses_normal_ht+0xfc6e, %rsi lea addresses_WT_ht+0x63c, %rdi nop nop and %r8, %r8 mov $116, %rcx rep movsl nop nop and %rax, %rax lea addresses_A_ht+0x18c6e, %rsi lea addresses_WC_ht+0x118b8, %rdi dec %r12 mov $88, %rcx rep movsl nop sub %r8, %r8 lea addresses_UC_ht+0x14072, %r12 nop nop nop nop add $14235, %r8 mov (%r12), %rsi dec %rdi lea addresses_WC_ht+0x137f7, %r12 nop nop nop nop nop inc %rbp movb (%r12), %r8b sub %rax, %rax lea addresses_D_ht+0xfcae, %rdi nop nop nop sub %rax, %rax movb $0x61, (%rdi) nop nop nop nop sub $30164, %rcx lea addresses_WC_ht+0x906e, %rsi sub %rax, %rax mov (%rsi), %r8w nop nop nop add $53807, %r8 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r15 push %rax push %rcx push %rdi // Faulty Load lea addresses_A+0x206e, %rax nop nop cmp %rcx, %rcx mov (%rax), %r15w lea oracles, %rdi and $0xff, %r15 shlq $12, %r15 mov (%rdi,%r15,1), %r15 pop %rdi pop %rcx pop %rax pop %r15 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'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 */
alloy4fun_models/trashltl/models/10/Zc8oDSDxwtvZsMd7Y.als
Kaixi26/org.alloytools.alloy
0
1336
open main pred idZc8oDSDxwtvZsMd7Y_prop11 { (File - Protected) in Protected' } pred __repair { idZc8oDSDxwtvZsMd7Y_prop11 } check __repair { idZc8oDSDxwtvZsMd7Y_prop11 <=> prop11o }
grammars/JsonPath2Lexer.g4
Open-MBEE/text2text
0
2818
<filename>grammars/JsonPath2Lexer.g4<gh_stars>0 lexer grammar JsonPath2Lexer; STRING : '"' (~'\\' | '\\' ~'\n')*? '"'; // STRING adapted from <NAME>, https://stackoverflow.com/questions/23799285/parsing-quoted-string-with-escape-chars QUESTION : '?' ; OPENROUND : '(' ; CLOSEROUND : ')' ; WILDCARD : '*' ; DOLLAR : '$' ; DOT : '.' ; CARET : '^' ; TILDE : '~' ; BANG : '!' ; EQUALS : '=' ; COMMA : ',' ; COLON : ':' ; OPENSQUARE : '[' ; CLOSESQUARE : ']' ; DOC : 'DOC' ; REF : 'REF' ; HERE : 'HERE'; LIB : 'LIB' ; IDENTIFIER : [a-zA-Z_][a-zA-Z0-9_]* ; NATURALNUM : '0' | [1-9][0-9]* ; WS : [ \t\n\r]+ -> skip ;
Ficheiros assembly (TP's e Testes)/ex15a-folha4.asm
pemesteves/mpcp-1718
0
23132
include mpcp.inc ;; declaracoes de dados (variaveis globais) .data ;; seccao de codigo principal .code recinv PROC USES edi esi SEQ: PTR SDWORD, N: DWORD mov edi, SEQ mov esi, edi dec N mov eax, N sal eax, 2 add esi, eax .WHILE edi < esi mov eax, [edi] mov edi, [esi] mov esi, eax add edi, 4 sub esi, 4 .ENDW ret recinv ENDP main PROC C invoke _getch invoke ExitProcess, 0 main ENDP ;; ----------------------------- ;; codigo de outras rotinas end
programs/oeis/263/A263941.asm
jmorken/loda
1
173040
; A263941: Minimal most likely sum for a roll of n 8-sided dice. ; 1,9,13,18,22,27,31,36,40,45,49,54,58,63,67,72,76,81,85,90,94,99,103,108,112,117,121,126,130,135,139,144,148,153,157,162,166,171,175,180,184,189,193,198,202,207,211,216,220,225 mov $2,$0 mul $0,8 sub $0,1 mov $1,1 add $2,$0 div $2,2 lpb $0 mov $0,2 add $1,$2 add $1,4 lpe
oeis/022/A022000.asm
neoneye/loda-programs
11
91682
; A022000: Expansion of 1/((1-x)(1-4x)(1-11x)(1-12x)). ; Submitted by <NAME> ; 1,28,533,8648,128889,1824276,24950461,333078016,4367420897,56484732044,722650676709,9164986526904,115404823162825,1444532800672132,17990818115880077,223110488408176112,2756753247818503473,33954740252852825340,417067597195198493365,5110529022479496278440,62489244688728228783641,762662796879319815284468,9292664029335685800161373,113059783486744382778398688,1373743368323185578250816129,16672206051184510972895934316,202126614558589260847001920901,2448180936091221570256793493656 add $0,2 lpb $0 sub $0,1 add $2,2 mul $2,11 mul $3,12 add $3,$1 mul $1,4 add $1,$2 lpe mov $0,$3 div $0,22
add.ads
gonma95/RealTimeSystem_CarDistrations
0
14551
<filename>add.ads package add is procedure Background; end add;
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/loop_optimization3_pkg.adb
best08618/asylo
7
16998
package body Loop_Optimization3_Pkg is function F (n : Integer) return Integer is begin return n; end; end Loop_Optimization3_Pkg;
libsrc/_DEVELOPMENT/arch/zxn/esxdos/c/sccz80/p3dos_edrv_from_pdrv.asm
jpoikela/z88dk
640
24237
; unsigned char p3dos_edrv_from_pdrv(unsigned char pdrv) SECTION code_esxdos PUBLIC p3dos_edrv_from_pdrv EXTERN asm_p3dos_edrv_from_pdrv defc p3dos_edrv_from_pdrv = asm_p3dos_edrv_from_pdrv
awa/plugins/awa-workspaces/src/model/awa-workspaces-models.ads
My-Colaborations/ada-awa
81
6818
<filename>awa/plugins/awa-workspaces/src/model/awa-workspaces-models.ads ----------------------------------------------------------------------- -- AWA.Workspaces.Models -- AWA.Workspaces.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2020 <NAME> -- Written by <NAME> (<EMAIL>) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Basic.Lists; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On); package AWA.Workspaces.Models is pragma Style_Checks ("-mr"); type Workspace_Ref is new ADO.Objects.Object_Ref with null record; type Workspace_Member_Ref is new ADO.Objects.Object_Ref with null record; type Invitation_Ref is new ADO.Objects.Object_Ref with null record; type Workspace_Feature_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The workspace controls the features available in the application -- for a set of users: the workspace members. A user could create -- several workspaces and be part of several workspaces that other -- users have created. -- -------------------- -- Create an object key for Workspace. function Workspace_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Workspace from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Workspace_Key (Id : in String) return ADO.Objects.Object_Key; Null_Workspace : constant Workspace_Ref; function "=" (Left, Right : Workspace_Ref'Class) return Boolean; -- Set the workspace identifier procedure Set_Id (Object : in out Workspace_Ref; Value : in ADO.Identifier); -- Get the workspace identifier function Get_Id (Object : in Workspace_Ref) return ADO.Identifier; -- function Get_Version (Object : in Workspace_Ref) return Integer; -- procedure Set_Create_Date (Object : in out Workspace_Ref; Value : in Ada.Calendar.Time); -- function Get_Create_Date (Object : in Workspace_Ref) return Ada.Calendar.Time; -- procedure Set_Owner (Object : in out Workspace_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Owner (Object : in Workspace_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Workspace_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Workspace_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Workspace_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Workspace_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Workspace_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Workspace_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WORKSPACE_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Workspace_Ref); -- Copy of the object. procedure Copy (Object : in Workspace_Ref; Into : in out Workspace_Ref); -- -------------------- -- The workspace member indicates the users who -- are part of the workspace. The join_date is NULL when -- a user was invited but has not accepted the invitation. -- -------------------- -- Create an object key for Workspace_Member. function Workspace_Member_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Workspace_Member from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Workspace_Member_Key (Id : in String) return ADO.Objects.Object_Key; Null_Workspace_Member : constant Workspace_Member_Ref; function "=" (Left, Right : Workspace_Member_Ref'Class) return Boolean; -- procedure Set_Id (Object : in out Workspace_Member_Ref; Value : in ADO.Identifier); -- function Get_Id (Object : in Workspace_Member_Ref) return ADO.Identifier; -- Set the date when the user has joined the workspace. procedure Set_Join_Date (Object : in out Workspace_Member_Ref; Value : in ADO.Nullable_Time); -- Get the date when the user has joined the workspace. function Get_Join_Date (Object : in Workspace_Member_Ref) return ADO.Nullable_Time; -- Set the member role. procedure Set_Role (Object : in out Workspace_Member_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Role (Object : in out Workspace_Member_Ref; Value : in String); -- Get the member role. function Get_Role (Object : in Workspace_Member_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Role (Object : in Workspace_Member_Ref) return String; -- procedure Set_Member (Object : in out Workspace_Member_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Member (Object : in Workspace_Member_Ref) return AWA.Users.Models.User_Ref'Class; -- procedure Set_Workspace (Object : in out Workspace_Member_Ref; Value : in AWA.Workspaces.Models.Workspace_Ref'Class); -- function Get_Workspace (Object : in Workspace_Member_Ref) return AWA.Workspaces.Models.Workspace_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Workspace_Member_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Workspace_Member_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Workspace_Member_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Workspace_Member_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Workspace_Member_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Workspace_Member_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WORKSPACE_MEMBER_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Workspace_Member_Ref); -- Copy of the object. procedure Copy (Object : in Workspace_Member_Ref; Into : in out Workspace_Member_Ref); -- Create an object key for Invitation. function Invitation_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Invitation from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Invitation_Key (Id : in String) return ADO.Objects.Object_Key; Null_Invitation : constant Invitation_Ref; function "=" (Left, Right : Invitation_Ref'Class) return Boolean; -- Set the invitation identifier. procedure Set_Id (Object : in out Invitation_Ref; Value : in ADO.Identifier); -- Get the invitation identifier. function Get_Id (Object : in Invitation_Ref) return ADO.Identifier; -- Get version optimistic lock. function Get_Version (Object : in Invitation_Ref) return Integer; -- Set date when the invitation was created and sent. procedure Set_Create_Date (Object : in out Invitation_Ref; Value : in Ada.Calendar.Time); -- Get date when the invitation was created and sent. function Get_Create_Date (Object : in Invitation_Ref) return Ada.Calendar.Time; -- Set the email address to which the invitation was sent. procedure Set_Email (Object : in out Invitation_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Email (Object : in out Invitation_Ref; Value : in String); -- Get the email address to which the invitation was sent. function Get_Email (Object : in Invitation_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Email (Object : in Invitation_Ref) return String; -- Set the invitation message. procedure Set_Message (Object : in out Invitation_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Invitation_Ref; Value : in String); -- Get the invitation message. function Get_Message (Object : in Invitation_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Invitation_Ref) return String; -- Set the date when the invitation was accepted. procedure Set_Acceptance_Date (Object : in out Invitation_Ref; Value : in ADO.Nullable_Time); -- Get the date when the invitation was accepted. function Get_Acceptance_Date (Object : in Invitation_Ref) return ADO.Nullable_Time; -- Set the workspace where the user is invited. procedure Set_Workspace (Object : in out Invitation_Ref; Value : in AWA.Workspaces.Models.Workspace_Ref'Class); -- Get the workspace where the user is invited. function Get_Workspace (Object : in Invitation_Ref) return AWA.Workspaces.Models.Workspace_Ref'Class; -- procedure Set_Access_Key (Object : in out Invitation_Ref; Value : in AWA.Users.Models.Access_Key_Ref'Class); -- function Get_Access_Key (Object : in Invitation_Ref) return AWA.Users.Models.Access_Key_Ref'Class; -- Set the user being invited. procedure Set_Invitee (Object : in out Invitation_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- Get the user being invited. function Get_Invitee (Object : in Invitation_Ref) return AWA.Users.Models.User_Ref'Class; -- procedure Set_Inviter (Object : in out Invitation_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Inviter (Object : in Invitation_Ref) return AWA.Users.Models.User_Ref'Class; -- procedure Set_Member (Object : in out Invitation_Ref; Value : in AWA.Workspaces.Models.Workspace_Member_Ref'Class); -- function Get_Member (Object : in Invitation_Ref) return AWA.Workspaces.Models.Workspace_Member_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Invitation_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Invitation_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Invitation_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Invitation_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Invitation_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Invitation_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition INVITATION_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Invitation_Ref); -- Copy of the object. procedure Copy (Object : in Invitation_Ref; Into : in out Invitation_Ref); -- Create an object key for Workspace_Feature. function Workspace_Feature_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Workspace_Feature from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Workspace_Feature_Key (Id : in String) return ADO.Objects.Object_Key; Null_Workspace_Feature : constant Workspace_Feature_Ref; function "=" (Left, Right : Workspace_Feature_Ref'Class) return Boolean; -- procedure Set_Id (Object : in out Workspace_Feature_Ref; Value : in ADO.Identifier); -- function Get_Id (Object : in Workspace_Feature_Ref) return ADO.Identifier; -- procedure Set_Limit (Object : in out Workspace_Feature_Ref; Value : in Integer); -- function Get_Limit (Object : in Workspace_Feature_Ref) return Integer; -- procedure Set_Workspace (Object : in out Workspace_Feature_Ref; Value : in AWA.Workspaces.Models.Workspace_Ref'Class); -- function Get_Workspace (Object : in Workspace_Feature_Ref) return AWA.Workspaces.Models.Workspace_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Workspace_Feature_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Workspace_Feature_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Workspace_Feature_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Workspace_Feature_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Workspace_Feature_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Workspace_Feature_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition WORKSPACE_FEATURE_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Workspace_Feature_Ref); -- Copy of the object. procedure Copy (Object : in Workspace_Feature_Ref; Into : in out Workspace_Feature_Ref); Query_Member_In_Role : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- The Member_Info describes a member of the workspace. -- -------------------- type Member_Info is new Util.Beans.Basic.Bean with record -- the member identifier. Id : ADO.Identifier; -- the user identifier. User_Id : ADO.Identifier; -- the user name. Name : Ada.Strings.Unbounded.Unbounded_String; -- the user email address. Email : Ada.Strings.Unbounded.Unbounded_String; -- the user's role. Role : Ada.Strings.Unbounded.Unbounded_String; -- the date when the user joined the workspace. Join_Date : ADO.Nullable_Time; -- the date when the invitation was sent to the user. Invite_Date : ADO.Nullable_Time; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Member_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Member_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Member_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Member_Info); package Member_Info_Vectors renames Member_Info_Beans.Vectors; subtype Member_Info_List_Bean is Member_Info_Beans.List_Bean; type Member_Info_List_Bean_Access is access all Member_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Member_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Member_Info_Vector is Member_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Member_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Workspace_Member_List : constant ADO.Queries.Query_Definition_Access; -- -------------------- -- Operation to load the invitation. -- -------------------- type Invitation_Bean is abstract new AWA.Workspaces.Models.Invitation_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Key : Ada.Strings.Unbounded.Unbounded_String; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Invitation_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Invitation_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Invitation_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- -------------------- -- load the list of members. -- -------------------- type Member_List_Bean is abstract limited new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record -- the number of members per page. Page_Size : Integer; -- the number of pages. Count : Integer; -- the current page number. Page : Integer; end record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Member_List_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Member_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Member_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; -- -------------------- -- load the member information. -- -------------------- type Member_Bean is abstract new AWA.Workspaces.Models.Workspace_Member_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Member_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Member_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Load (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Member_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private WORKSPACE_NAME : aliased constant String := "awa_workspace"; COL_0_1_NAME : aliased constant String := "id"; COL_1_1_NAME : aliased constant String := "version"; COL_2_1_NAME : aliased constant String := "create_date"; COL_3_1_NAME : aliased constant String := "owner_id"; WORKSPACE_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 4, Table => WORKSPACE_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access) ); WORKSPACE_TABLE : constant ADO.Schemas.Class_Mapping_Access := WORKSPACE_DEF'Access; Null_Workspace : constant Workspace_Ref := Workspace_Ref'(ADO.Objects.Object_Ref with null record); type Workspace_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WORKSPACE_DEF'Access) with record Version : Integer; Create_Date : Ada.Calendar.Time; Owner : AWA.Users.Models.User_Ref; end record; type Workspace_Access is access all Workspace_Impl; overriding procedure Destroy (Object : access Workspace_Impl); overriding procedure Find (Object : in out Workspace_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Workspace_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Workspace_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Workspace_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Workspace_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Workspace_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Workspace_Ref'Class; Impl : out Workspace_Access); WORKSPACE_MEMBER_NAME : aliased constant String := "awa_workspace_member"; COL_0_2_NAME : aliased constant String := "id"; COL_1_2_NAME : aliased constant String := "join_date"; COL_2_2_NAME : aliased constant String := "role"; COL_3_2_NAME : aliased constant String := "member_id"; COL_4_2_NAME : aliased constant String := "workspace_id"; WORKSPACE_MEMBER_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 5, Table => WORKSPACE_MEMBER_NAME'Access, Members => ( 1 => COL_0_2_NAME'Access, 2 => COL_1_2_NAME'Access, 3 => COL_2_2_NAME'Access, 4 => COL_3_2_NAME'Access, 5 => COL_4_2_NAME'Access) ); WORKSPACE_MEMBER_TABLE : constant ADO.Schemas.Class_Mapping_Access := WORKSPACE_MEMBER_DEF'Access; Null_Workspace_Member : constant Workspace_Member_Ref := Workspace_Member_Ref'(ADO.Objects.Object_Ref with null record); type Workspace_Member_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WORKSPACE_MEMBER_DEF'Access) with record Join_Date : ADO.Nullable_Time; Role : Ada.Strings.Unbounded.Unbounded_String; Member : AWA.Users.Models.User_Ref; Workspace : AWA.Workspaces.Models.Workspace_Ref; end record; type Workspace_Member_Access is access all Workspace_Member_Impl; overriding procedure Destroy (Object : access Workspace_Member_Impl); overriding procedure Find (Object : in out Workspace_Member_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Workspace_Member_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Workspace_Member_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Workspace_Member_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Workspace_Member_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Workspace_Member_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Workspace_Member_Ref'Class; Impl : out Workspace_Member_Access); INVITATION_NAME : aliased constant String := "awa_invitation"; COL_0_3_NAME : aliased constant String := "id"; COL_1_3_NAME : aliased constant String := "version"; COL_2_3_NAME : aliased constant String := "create_date"; COL_3_3_NAME : aliased constant String := "email"; COL_4_3_NAME : aliased constant String := "message"; COL_5_3_NAME : aliased constant String := "acceptance_date"; COL_6_3_NAME : aliased constant String := "workspace_id"; COL_7_3_NAME : aliased constant String := "access_key_id"; COL_8_3_NAME : aliased constant String := "invitee_id"; COL_9_3_NAME : aliased constant String := "inviter_id"; COL_10_3_NAME : aliased constant String := "member_id"; INVITATION_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 11, Table => INVITATION_NAME'Access, Members => ( 1 => COL_0_3_NAME'Access, 2 => COL_1_3_NAME'Access, 3 => COL_2_3_NAME'Access, 4 => COL_3_3_NAME'Access, 5 => COL_4_3_NAME'Access, 6 => COL_5_3_NAME'Access, 7 => COL_6_3_NAME'Access, 8 => COL_7_3_NAME'Access, 9 => COL_8_3_NAME'Access, 10 => COL_9_3_NAME'Access, 11 => COL_10_3_NAME'Access) ); INVITATION_TABLE : constant ADO.Schemas.Class_Mapping_Access := INVITATION_DEF'Access; Null_Invitation : constant Invitation_Ref := Invitation_Ref'(ADO.Objects.Object_Ref with null record); type Invitation_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => INVITATION_DEF'Access) with record Version : Integer; Create_Date : Ada.Calendar.Time; Email : Ada.Strings.Unbounded.Unbounded_String; Message : Ada.Strings.Unbounded.Unbounded_String; Acceptance_Date : ADO.Nullable_Time; Workspace : AWA.Workspaces.Models.Workspace_Ref; Access_Key : AWA.Users.Models.Access_Key_Ref; Invitee : AWA.Users.Models.User_Ref; Inviter : AWA.Users.Models.User_Ref; Member : AWA.Workspaces.Models.Workspace_Member_Ref; end record; type Invitation_Access is access all Invitation_Impl; overriding procedure Destroy (Object : access Invitation_Impl); overriding procedure Find (Object : in out Invitation_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Invitation_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Invitation_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Invitation_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Invitation_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Invitation_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Invitation_Ref'Class; Impl : out Invitation_Access); WORKSPACE_FEATURE_NAME : aliased constant String := "awa_workspace_feature"; COL_0_4_NAME : aliased constant String := "id"; COL_1_4_NAME : aliased constant String := "limit"; COL_2_4_NAME : aliased constant String := "workspace_id"; WORKSPACE_FEATURE_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 3, Table => WORKSPACE_FEATURE_NAME'Access, Members => ( 1 => COL_0_4_NAME'Access, 2 => COL_1_4_NAME'Access, 3 => COL_2_4_NAME'Access) ); WORKSPACE_FEATURE_TABLE : constant ADO.Schemas.Class_Mapping_Access := WORKSPACE_FEATURE_DEF'Access; Null_Workspace_Feature : constant Workspace_Feature_Ref := Workspace_Feature_Ref'(ADO.Objects.Object_Ref with null record); type Workspace_Feature_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => WORKSPACE_FEATURE_DEF'Access) with record Limit : Integer; Workspace : AWA.Workspaces.Models.Workspace_Ref; end record; type Workspace_Feature_Access is access all Workspace_Feature_Impl; overriding procedure Destroy (Object : access Workspace_Feature_Impl); overriding procedure Find (Object : in out Workspace_Feature_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Workspace_Feature_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Workspace_Feature_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Workspace_Feature_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Workspace_Feature_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Workspace_Feature_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Workspace_Feature_Ref'Class; Impl : out Workspace_Feature_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "workspace-permissions.xml", Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543"); package Def_Member_In_Role is new ADO.Queries.Loaders.Query (Name => "member-in-role", File => File_1.File'Access); Query_Member_In_Role : constant ADO.Queries.Query_Definition_Access := Def_Member_In_Role.Query'Access; package File_2 is new ADO.Queries.Loaders.File (Path => "member-list.xml", Sha1 => "D92F1CB6DBE47F7A72E83CD4AE8E39F2048D0728"); package Def_Memberinfo_Workspace_Member_List is new ADO.Queries.Loaders.Query (Name => "workspace-member-list", File => File_2.File'Access); Query_Workspace_Member_List : constant ADO.Queries.Query_Definition_Access := Def_Memberinfo_Workspace_Member_List.Query'Access; end AWA.Workspaces.Models;
ANTLR_Project/src/MiniC.g4
SeokBA/Compiler_Term
0
425
grammar MiniC; @header { package generated; } program : decl+ ; decl : var_decl | fun_decl ; var_decl : type_spec IDENT ';' | type_spec IDENT '=' LITERAL ';' | type_spec IDENT '[' LITERAL ']' ';' ; type_spec : VOID | INT ; fun_decl : type_spec IDENT '(' params ')' compound_stmt ; params : param (',' param)* | VOID | ; param : type_spec IDENT | type_spec IDENT '[' ']' ; stmt : expr_stmt | compound_stmt | if_stmt | while_stmt | return_stmt ; expr_stmt : expr ';' ; while_stmt : WHILE '(' expr ')' stmt ; compound_stmt: '{' local_decl* stmt* '}' ; local_decl : type_spec IDENT ';' | type_spec IDENT '=' LITERAL ';' | type_spec IDENT '[' LITERAL ']' ';' ; if_stmt : IF '(' expr ')' stmt | IF '(' expr ')' stmt ELSE stmt ; return_stmt : RETURN ';' | RETURN expr ';' ; expr : LITERAL | '(' expr ')' | IDENT | IDENT '[' expr ']' | IDENT '(' args ')' | '-' expr | '+' expr | '--' expr | '++' expr | expr '*' expr | expr '/' expr | expr '%' expr | expr '+' expr | expr '-' expr | expr EQ expr | expr NE expr | expr LE expr | expr '<' expr | expr GE expr | expr '>' expr | '!' expr | expr AND expr | expr OR expr | IDENT '=' expr | IDENT '[' expr ']' '=' expr ; args : expr (',' expr)* | ; VOID: 'void'; INT: 'int'; WHILE: 'while'; IF: 'if'; ELSE: 'else'; RETURN: 'return'; OR: 'or'; AND: 'and'; LE: '<='; GE: '>='; EQ: '=='; NE: '!='; IDENT : [a-zA-Z_] ( [a-zA-Z_] | [0-9] )*; LITERAL: DecimalConstant | OctalConstant | HexadecimalConstant ; DecimalConstant : '0' | [1-9] [0-9]* ; OctalConstant : '0'[0-7]* ; HexadecimalConstant : '0' [xX] [0-9a-fA-F] + ; WS : ( ' ' | '\t' | '\r' | '\n' )+ -> channel(HIDDEN) ;
Task/Multisplit/Ada/multisplit.ada
LaudateCorpus1/RosettaCodeData
1
25302
<filename>Task/Multisplit/Ada/multisplit.ada with Ada.Containers.Indefinite_Doubly_Linked_Lists; with Ada.Text_IO; procedure Multisplit is package String_Lists is new Ada.Containers.Indefinite_Doubly_Linked_Lists (Element_Type => String); use type String_Lists.Cursor; function Split (Source : String; Separators : String_Lists.List) return String_Lists.List is Result : String_Lists.List; Next_Position : Natural := Source'First; Prev_Position : Natural := Source'First; Separator_Position : String_Lists.Cursor; Separator_Length : Natural; Changed : Boolean; begin loop Changed := False; Separator_Position := Separators.First; while Separator_Position /= String_Lists.No_Element loop Separator_Length := String_Lists.Element (Separator_Position)'Length; if Next_Position + Separator_Length - 1 <= Source'Last and then Source (Next_Position .. Next_Position + Separator_Length - 1) = String_Lists.Element (Separator_Position) then if Next_Position > Prev_Position then Result.Append (Source (Prev_Position .. Next_Position - 1)); end if; Result.Append (String_Lists.Element (Separator_Position)); Next_Position := Next_Position + Separator_Length; Prev_Position := Next_Position; Changed := True; exit; end if; Separator_Position := String_Lists.Next (Separator_Position); end loop; if not Changed then Next_Position := Next_Position + 1; end if; if Next_Position > Source'Last then Result.Append (Source (Prev_Position .. Source'Last)); exit; end if; end loop; return Result; end Split; Test_Input : constant String := "a!===b=!=c"; Test_Separators : String_Lists.List; Test_Result : String_Lists.List; Pos : String_Lists.Cursor; begin Test_Separators.Append ("=="); Test_Separators.Append ("!="); Test_Separators.Append ("="); Test_Result := Split (Test_Input, Test_Separators); Pos := Test_Result.First; while Pos /= String_Lists.No_Element loop Ada.Text_IO.Put (" " & String_Lists.Element (Pos)); Pos := String_Lists.Next (Pos); end loop; Ada.Text_IO.New_Line; -- other order of separators Test_Separators.Clear; Test_Separators.Append ("="); Test_Separators.Append ("!="); Test_Separators.Append ("=="); Test_Result := Split (Test_Input, Test_Separators); Pos := Test_Result.First; while Pos /= String_Lists.No_Element loop Ada.Text_IO.Put (" " & String_Lists.Element (Pos)); Pos := String_Lists.Next (Pos); end loop; end Multisplit;
edk2/ArmPkg/Library/CompilerIntrinsicsLib/Arm/memmove.asm
awwiniot/Aw1689UEFI
21
6890
<reponame>awwiniot/Aw1689UEFI //------------------------------------------------------------------------------ // // Copyright (c) 2011, ARM Limited. All rights reserved. // // This program and the accompanying materials // are licensed and made available under the terms and conditions of the BSD License // which accompanies this distribution. The full text of the license may be found at // http://opensource.org/licenses/bsd-license.php // // THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, // WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. // //------------------------------------------------------------------------------ EXPORT __aeabi_memmove AREA Memmove, CODE, READONLY ; ;VOID ;EFIAPI ;__aeabi_memmove ( ; IN VOID *Destination, ; IN CONST VOID *Source, ; IN UINT32 Size ; ); ; __aeabi_memmove CMP r2, #0 BXEQ r14 CMP r0, r1 BXEQ r14 BHI memmove_backward BLS memmove_forward memmove_forward LDRB r3, [r1], #1 STRB r3, [r0], #1 SUBS r2, r2, #1 BXEQ r14 B memmove_forward memmove_backward add r0, r2 add r1, r2 memmove_backward_loop LDRB r3, [r1], #-1 STRB r3, [r0], #-1 SUBS r2, r2, #-1 BXEQ r14 B memmove_backward_loop END
Task/Address-of-a-variable/Ada/address-of-a-variable-1.ada
LaudateCorpus1/RosettaCodeData
1
11955
<reponame>LaudateCorpus1/RosettaCodeData The_Address : System.Address; I : Integer; The_Address := I'Address;
agda-stdlib/src/Algebra/Structures.agda
DreamLinuxer/popl21-artifact
5
16074
<reponame>DreamLinuxer/popl21-artifact ------------------------------------------------------------------------ -- The Agda standard library -- -- Some algebraic structures (not packed up with sets, operations, -- etc.) ------------------------------------------------------------------------ -- The contents of this module should be accessed via `Algebra`, unless -- you want to parameterise it via the equality relation. {-# OPTIONS --without-K --safe #-} open import Relation.Binary using (Rel; Setoid; IsEquivalence) module Algebra.Structures {a ℓ} {A : Set a} -- The underlying set (_≈_ : Rel A ℓ) -- The underlying equality relation where -- The file is divided into sections depending on the arities of the -- components of the algebraic structure. open import Algebra.Core open import Algebra.Definitions _≈_ import Algebra.Consequences.Setoid as Consequences open import Data.Product using (_,_; proj₁; proj₂) open import Level using (_⊔_) ------------------------------------------------------------------------ -- Structures with 1 binary operation ------------------------------------------------------------------------ record IsMagma (∙ : Op₂ A) : Set (a ⊔ ℓ) where field isEquivalence : IsEquivalence _≈_ ∙-cong : Congruent₂ ∙ open IsEquivalence isEquivalence public setoid : Setoid a ℓ setoid = record { isEquivalence = isEquivalence } ∙-congˡ : LeftCongruent ∙ ∙-congˡ y≈z = ∙-cong refl y≈z ∙-congʳ : RightCongruent ∙ ∙-congʳ y≈z = ∙-cong y≈z refl record IsSemigroup (∙ : Op₂ A) : Set (a ⊔ ℓ) where field isMagma : IsMagma ∙ assoc : Associative ∙ open IsMagma isMagma public record IsBand (∙ : Op₂ A) : Set (a ⊔ ℓ) where field isSemigroup : IsSemigroup ∙ idem : Idempotent ∙ open IsSemigroup isSemigroup public record IsCommutativeSemigroup (∙ : Op₂ A) : Set (a ⊔ ℓ) where field isSemigroup : IsSemigroup ∙ comm : Commutative ∙ open IsSemigroup isSemigroup public record IsSemilattice (∧ : Op₂ A) : Set (a ⊔ ℓ) where field isBand : IsBand ∧ comm : Commutative ∧ open IsBand isBand public renaming (∙-cong to ∧-cong; ∙-congˡ to ∧-congˡ; ∙-congʳ to ∧-congʳ) record IsSelectiveMagma (∙ : Op₂ A) : Set (a ⊔ ℓ) where field isMagma : IsMagma ∙ sel : Selective ∙ open IsMagma isMagma public ------------------------------------------------------------------------ -- Structures with 1 binary operation & 1 element ------------------------------------------------------------------------ record IsMonoid (∙ : Op₂ A) (ε : A) : Set (a ⊔ ℓ) where field isSemigroup : IsSemigroup ∙ identity : Identity ε ∙ open IsSemigroup isSemigroup public identityˡ : LeftIdentity ε ∙ identityˡ = proj₁ identity identityʳ : RightIdentity ε ∙ identityʳ = proj₂ identity record IsCommutativeMonoid (∙ : Op₂ A) (ε : A) : Set (a ⊔ ℓ) where field isMonoid : IsMonoid ∙ ε comm : Commutative ∙ open IsMonoid isMonoid public isCommutativeSemigroup : IsCommutativeSemigroup ∙ isCommutativeSemigroup = record { isSemigroup = isSemigroup ; comm = comm } record IsIdempotentCommutativeMonoid (∙ : Op₂ A) (ε : A) : Set (a ⊔ ℓ) where field isCommutativeMonoid : IsCommutativeMonoid ∙ ε idem : Idempotent ∙ open IsCommutativeMonoid isCommutativeMonoid public -- Idempotent commutative monoids are also known as bounded lattices. -- Note that the BoundedLattice necessarily uses the notation inherited -- from monoids rather than lattices. IsBoundedLattice = IsIdempotentCommutativeMonoid module IsBoundedLattice {∙ : Op₂ A} {ε : A} (isIdemCommMonoid : IsIdempotentCommutativeMonoid ∙ ε) = IsIdempotentCommutativeMonoid isIdemCommMonoid ------------------------------------------------------------------------ -- Structures with 1 binary operation, 1 unary operation & 1 element ------------------------------------------------------------------------ record IsGroup (_∙_ : Op₂ A) (ε : A) (_⁻¹ : Op₁ A) : Set (a ⊔ ℓ) where field isMonoid : IsMonoid _∙_ ε inverse : Inverse ε _⁻¹ _∙_ ⁻¹-cong : Congruent₁ _⁻¹ open IsMonoid isMonoid public infixl 6 _-_ _-_ : Op₂ A x - y = x ∙ (y ⁻¹) inverseˡ : LeftInverse ε _⁻¹ _∙_ inverseˡ = proj₁ inverse inverseʳ : RightInverse ε _⁻¹ _∙_ inverseʳ = proj₂ inverse uniqueˡ-⁻¹ : ∀ x y → (x ∙ y) ≈ ε → x ≈ (y ⁻¹) uniqueˡ-⁻¹ = Consequences.assoc+id+invʳ⇒invˡ-unique setoid ∙-cong assoc identity inverseʳ uniqueʳ-⁻¹ : ∀ x y → (x ∙ y) ≈ ε → y ≈ (x ⁻¹) uniqueʳ-⁻¹ = Consequences.assoc+id+invˡ⇒invʳ-unique setoid ∙-cong assoc identity inverseˡ record IsAbelianGroup (∙ : Op₂ A) (ε : A) (⁻¹ : Op₁ A) : Set (a ⊔ ℓ) where field isGroup : IsGroup ∙ ε ⁻¹ comm : Commutative ∙ open IsGroup isGroup public isCommutativeMonoid : IsCommutativeMonoid ∙ ε isCommutativeMonoid = record { isMonoid = isMonoid ; comm = comm } open IsCommutativeMonoid isCommutativeMonoid public using (isCommutativeSemigroup) ------------------------------------------------------------------------ -- Structures with 2 binary operations ------------------------------------------------------------------------ -- Note that `IsLattice` is not defined in terms of `IsSemilattice` -- because the idempotence laws of ∨ and ∧ can be derived from the -- absorption laws, which makes the corresponding "idem" fields -- redundant. The derived idempotence laws are stated and proved in -- `Algebra.Properties.Lattice` along with the fact that every lattice -- consists of two semilattices. record IsLattice (∨ ∧ : Op₂ A) : Set (a ⊔ ℓ) where field isEquivalence : IsEquivalence _≈_ ∨-comm : Commutative ∨ ∨-assoc : Associative ∨ ∨-cong : Congruent₂ ∨ ∧-comm : Commutative ∧ ∧-assoc : Associative ∧ ∧-cong : Congruent₂ ∧ absorptive : Absorptive ∨ ∧ open IsEquivalence isEquivalence public ∨-absorbs-∧ : ∨ Absorbs ∧ ∨-absorbs-∧ = proj₁ absorptive ∧-absorbs-∨ : ∧ Absorbs ∨ ∧-absorbs-∨ = proj₂ absorptive ∧-congˡ : LeftCongruent ∧ ∧-congˡ y≈z = ∧-cong refl y≈z ∧-congʳ : RightCongruent ∧ ∧-congʳ y≈z = ∧-cong y≈z refl ∨-congˡ : LeftCongruent ∨ ∨-congˡ y≈z = ∨-cong refl y≈z ∨-congʳ : RightCongruent ∨ ∨-congʳ y≈z = ∨-cong y≈z refl record IsDistributiveLattice (∨ ∧ : Op₂ A) : Set (a ⊔ ℓ) where field isLattice : IsLattice ∨ ∧ ∨-distribʳ-∧ : ∨ DistributesOverʳ ∧ open IsLattice isLattice public ∨-∧-distribʳ = ∨-distribʳ-∧ {-# WARNING_ON_USAGE ∨-∧-distribʳ "Warning: ∨-∧-distribʳ was deprecated in v1.1. Please use ∨-distribʳ-∧ instead." #-} ------------------------------------------------------------------------ -- Structures with 2 binary operations & 1 element ------------------------------------------------------------------------ record IsNearSemiring (+ * : Op₂ A) (0# : A) : Set (a ⊔ ℓ) where field +-isMonoid : IsMonoid + 0# *-isSemigroup : IsSemigroup * distribʳ : * DistributesOverʳ + zeroˡ : LeftZero 0# * open IsMonoid +-isMonoid public renaming ( assoc to +-assoc ; ∙-cong to +-cong ; ∙-congˡ to +-congˡ ; ∙-congʳ to +-congʳ ; identity to +-identity ; identityˡ to +-identityˡ ; identityʳ to +-identityʳ ; isMagma to +-isMagma ; isSemigroup to +-isSemigroup ) open IsSemigroup *-isSemigroup public using () renaming ( assoc to *-assoc ; ∙-cong to *-cong ; ∙-congˡ to *-congˡ ; ∙-congʳ to *-congʳ ; isMagma to *-isMagma ) record IsSemiringWithoutOne (+ * : Op₂ A) (0# : A) : Set (a ⊔ ℓ) where field +-isCommutativeMonoid : IsCommutativeMonoid + 0# *-isSemigroup : IsSemigroup * distrib : * DistributesOver + zero : Zero 0# * open IsCommutativeMonoid +-isCommutativeMonoid public using () renaming ( comm to +-comm ; isMonoid to +-isMonoid ; isCommutativeSemigroup to +-isCommutativeSemigroup ) zeroˡ : LeftZero 0# * zeroˡ = proj₁ zero zeroʳ : RightZero 0# * zeroʳ = proj₂ zero isNearSemiring : IsNearSemiring + * 0# isNearSemiring = record { +-isMonoid = +-isMonoid ; *-isSemigroup = *-isSemigroup ; distribʳ = proj₂ distrib ; zeroˡ = zeroˡ } open IsNearSemiring isNearSemiring public hiding (+-isMonoid; zeroˡ) record IsCommutativeSemiringWithoutOne (+ * : Op₂ A) (0# : A) : Set (a ⊔ ℓ) where field isSemiringWithoutOne : IsSemiringWithoutOne + * 0# *-comm : Commutative * open IsSemiringWithoutOne isSemiringWithoutOne public ------------------------------------------------------------------------ -- Structures with 2 binary operations & 2 elements ------------------------------------------------------------------------ record IsSemiringWithoutAnnihilatingZero (+ * : Op₂ A) (0# 1# : A) : Set (a ⊔ ℓ) where field -- Note that these structures do have an additive unit, but this -- unit does not necessarily annihilate multiplication. +-isCommutativeMonoid : IsCommutativeMonoid + 0# *-isMonoid : IsMonoid * 1# distrib : * DistributesOver + distribˡ : * DistributesOverˡ + distribˡ = proj₁ distrib distribʳ : * DistributesOverʳ + distribʳ = proj₂ distrib open IsCommutativeMonoid +-isCommutativeMonoid public renaming ( assoc to +-assoc ; ∙-cong to +-cong ; ∙-congˡ to +-congˡ ; ∙-congʳ to +-congʳ ; identity to +-identity ; identityˡ to +-identityˡ ; identityʳ to +-identityʳ ; comm to +-comm ; isMagma to +-isMagma ; isSemigroup to +-isSemigroup ; isMonoid to +-isMonoid ; isCommutativeSemigroup to +-isCommutativeSemigroup ) open IsMonoid *-isMonoid public using () renaming ( assoc to *-assoc ; ∙-cong to *-cong ; ∙-congˡ to *-congˡ ; ∙-congʳ to *-congʳ ; identity to *-identity ; identityˡ to *-identityˡ ; identityʳ to *-identityʳ ; isMagma to *-isMagma ; isSemigroup to *-isSemigroup ) record IsSemiring (+ * : Op₂ A) (0# 1# : A) : Set (a ⊔ ℓ) where field isSemiringWithoutAnnihilatingZero : IsSemiringWithoutAnnihilatingZero + * 0# 1# zero : Zero 0# * open IsSemiringWithoutAnnihilatingZero isSemiringWithoutAnnihilatingZero public isSemiringWithoutOne : IsSemiringWithoutOne + * 0# isSemiringWithoutOne = record { +-isCommutativeMonoid = +-isCommutativeMonoid ; *-isSemigroup = *-isSemigroup ; distrib = distrib ; zero = zero } open IsSemiringWithoutOne isSemiringWithoutOne public using ( isNearSemiring ; zeroˡ ; zeroʳ ) record IsCommutativeSemiring (+ * : Op₂ A) (0# 1# : A) : Set (a ⊔ ℓ) where field isSemiring : IsSemiring + * 0# 1# *-comm : Commutative * open IsSemiring isSemiring public isCommutativeSemiringWithoutOne : IsCommutativeSemiringWithoutOne + * 0# isCommutativeSemiringWithoutOne = record { isSemiringWithoutOne = isSemiringWithoutOne ; *-comm = *-comm } *-isCommutativeSemigroup : IsCommutativeSemigroup * *-isCommutativeSemigroup = record { isSemigroup = *-isSemigroup ; comm = *-comm } *-isCommutativeMonoid : IsCommutativeMonoid * 1# *-isCommutativeMonoid = record { isMonoid = *-isMonoid ; comm = *-comm } ------------------------------------------------------------------------ -- Structures with 2 binary operations, 1 unary operation & 2 elements ------------------------------------------------------------------------ record IsRing (+ * : Op₂ A) (-_ : Op₁ A) (0# 1# : A) : Set (a ⊔ ℓ) where field +-isAbelianGroup : IsAbelianGroup + 0# -_ *-isMonoid : IsMonoid * 1# distrib : * DistributesOver + zero : Zero 0# * open IsAbelianGroup +-isAbelianGroup public renaming ( assoc to +-assoc ; ∙-cong to +-cong ; ∙-congˡ to +-congˡ ; ∙-congʳ to +-congʳ ; identity to +-identity ; identityˡ to +-identityˡ ; identityʳ to +-identityʳ ; inverse to -‿inverse ; inverseˡ to -‿inverseˡ ; inverseʳ to -‿inverseʳ ; ⁻¹-cong to -‿cong ; comm to +-comm ; isMagma to +-isMagma ; isSemigroup to +-isSemigroup ; isMonoid to +-isMonoid ; isCommutativeMonoid to +-isCommutativeMonoid ; isCommutativeSemigroup to +-isCommutativeSemigroup ; isGroup to +-isGroup ) open IsMonoid *-isMonoid public using () renaming ( assoc to *-assoc ; ∙-cong to *-cong ; ∙-congˡ to *-congˡ ; ∙-congʳ to *-congʳ ; identity to *-identity ; identityˡ to *-identityˡ ; identityʳ to *-identityʳ ; isMagma to *-isMagma ; isSemigroup to *-isSemigroup ) zeroˡ : LeftZero 0# * zeroˡ = proj₁ zero zeroʳ : RightZero 0# * zeroʳ = proj₂ zero isSemiringWithoutAnnihilatingZero : IsSemiringWithoutAnnihilatingZero + * 0# 1# isSemiringWithoutAnnihilatingZero = record { +-isCommutativeMonoid = +-isCommutativeMonoid ; *-isMonoid = *-isMonoid ; distrib = distrib } isSemiring : IsSemiring + * 0# 1# isSemiring = record { isSemiringWithoutAnnihilatingZero = isSemiringWithoutAnnihilatingZero ; zero = zero } open IsSemiring isSemiring public using (distribˡ; distribʳ; isNearSemiring; isSemiringWithoutOne) record IsCommutativeRing (+ * : Op₂ A) (- : Op₁ A) (0# 1# : A) : Set (a ⊔ ℓ) where field isRing : IsRing + * - 0# 1# *-comm : Commutative * open IsRing isRing public *-isCommutativeMonoid : IsCommutativeMonoid * 1# *-isCommutativeMonoid = record { isMonoid = *-isMonoid ; comm = *-comm } isCommutativeSemiring : IsCommutativeSemiring + * 0# 1# isCommutativeSemiring = record { isSemiring = isSemiring ; *-comm = *-comm } open IsCommutativeSemiring isCommutativeSemiring public using ( isCommutativeSemiringWithoutOne ) record IsBooleanAlgebra (∨ ∧ : Op₂ A) (¬ : Op₁ A) (⊤ ⊥ : A) : Set (a ⊔ ℓ) where field isDistributiveLattice : IsDistributiveLattice ∨ ∧ ∨-complementʳ : RightInverse ⊤ ¬ ∨ ∧-complementʳ : RightInverse ⊥ ¬ ∧ ¬-cong : Congruent₁ ¬ open IsDistributiveLattice isDistributiveLattice public
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c3/c35502m.ada
best08618/asylo
7
11753
<gh_stars>1-10 -- C35502M.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 'POS' AND 'VAL' YIELD THE CORRECT RESULTS WHEN -- THE PREFIX IS AN ENUMERATION TYPE, OTHER THAN A BOOLEAN OR A -- CHARACTER TYPE, WITH AN ENUMERATION REPRESENTATION CLAUSE. -- HISTORY: -- RJW 05/27/86 CREATED ORIGINAL TEST. -- BCB 01/04/88 MODIFIED HEADER. -- PWB 05/11/89 CHANGED EXTENSION FROM '.DEP' TO '.ADA'. WITH REPORT; USE REPORT; PROCEDURE C35502M IS TYPE ENUM IS (A, BC, ABC, A_B_C, ABCD); FOR ENUM USE (A => 2, BC => 4, ABC => 6, A_B_C => 8, ABCD => 10); SUBTYPE SUBENUM IS ENUM RANGE A .. BC; TYPE NEWENUM IS NEW ENUM; SUBTYPE SUBNEW IS NEWENUM RANGE A .. BC; BEGIN TEST ("C35502M", "CHECK THAT 'POS' AND 'VAL' YIELD THE " & "CORRECT RESULTS WHEN THE PREFIX IS AN " & "ENUMERATION TYPE, OTHER THAN A CHARACTER " & "OR A BOOLEAN TYPE, WITH AN ENUMERATION " & "REPRESENTATION CLAUSE" ); DECLARE POSITION : INTEGER; BEGIN POSITION := 0; FOR E IN ENUM LOOP IF SUBENUM'POS (E) /= POSITION THEN FAILED ( "INCORRECT SUBENUM'POS (" & ENUM'IMAGE (E) & ")" ); END IF; IF SUBENUM'VAL (POSITION) /= E THEN FAILED ( "INCORRECT SUBENUM'VAL (" & INTEGER'IMAGE (POSITION) & ")" ); END IF; POSITION := POSITION + 1; END LOOP; POSITION := 0; FOR E IN NEWENUM LOOP IF SUBNEW'POS (E) /= POSITION THEN FAILED ( "INCORRECT SUBNEW'POS (" & NEWENUM'IMAGE (E) & ")" ); END IF; IF SUBNEW'VAL (POSITION) /= E THEN FAILED ( "INCORRECT SUBNEW'VAL (" & INTEGER'IMAGE (POSITION) & ")" ); END IF; POSITION := POSITION + 1; END LOOP; END; DECLARE FUNCTION A_B_C RETURN ENUM IS BEGIN RETURN A; END A_B_C; BEGIN IF ENUM'VAL (0) /= A_B_C THEN FAILED ( "WRONG ENUM'VAL (0) WHEN HIDDEN " & "BY FUNCTION - 1" ); END IF; IF ENUM'VAL (0) = C35502M.A_B_C THEN FAILED ( "WRONG ENUM'VAL (0) WHEN HIDDEN " & "BY FUNCTION - 2" ); END IF; END; BEGIN IF ENUM'VAL (IDENT_INT (-1)) = ENUM'FIRST THEN FAILED ( "NO EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (-1)) - 1" ); ELSE FAILED ( "NO EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (-1)) - 2" ); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (-1))" ); END; BEGIN IF NEWENUM'VAL (IDENT_INT (-1)) = NEWENUM'LAST THEN FAILED ( "NO EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (-1)) - 1" ); ELSE FAILED ( "NO EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (-1)) - 2" ); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (-1))" ); END; BEGIN IF ENUM'VAL (IDENT_INT (5)) = ENUM'LAST THEN FAILED ( "NO EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (5)) - 1" ); ELSE FAILED ( "NO EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (5)) - 2" ); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR " & "ENUM'VAL (IDENT_INT (5))" ); END; BEGIN IF NEWENUM'VAL (IDENT_INT (5)) = NEWENUM'LAST THEN FAILED ( "NO EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (5)) - 1" ); ELSE FAILED ( "NO EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (5)) - 2" ); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED FOR " & "NEWENUM'VAL (IDENT_INT (5))" ); END; RESULT; END C35502M;
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/overriding_ops_p.ads
best08618/asylo
7
24260
package overriding_ops_p is subtype Name_Type is String (1 .. 30); type Device is synchronized interface; -- Base type of devices procedure Set_Name (Object : in out Device; Name : Name_Type) is abstract; -- Set the name of the Device end overriding_ops_p;
test/succeed/CopatternTrailingImplicit.agda
larrytheliquid/agda
0
13456
<filename>test/succeed/CopatternTrailingImplicit.agda {-# OPTIONS --copatterns --sized-types #-} -- {-# OPTIONS -v tc.size.solve:30 #-} -- {-# OPTIONS -v term:40 -v term.proj:60 --show-implicit #-} -- Andreas, 2013-10-01 Make sure trailing implicit insertion -- works with copatterns module CopatternTrailingImplicit where import Common.Level open import Common.Size open import Common.Prelude -- Sized streams record Stream (A : Set) {i : Size} : Set where coinductive field head : A tail : {j : Size< i} → Stream A {j} open Stream -- Mapping over streams map : {A B : Set} (f : A → B) {i : Size} → Stream A {i} → Stream B {i} tail (map f {i} s) {j} = map f (tail s) head (map f s) = f (head s) -- Nats defined using map nats : {i : Size} → Stream Nat {i} head nats = 0 tail nats = map suc nats -- Before this patch, Agda would insert a {_} also in the `head' clause -- leading to a type error. -- 2013-10-12 works now also without manual {_} insertion -- (See TermCheck.introHiddenLambdas.) nats' : {i : Size} → Stream Nat {i} head nats' = 0 tail nats' = map suc nats' -- Before this latest patch, the termination checker would complain -- since it would not see the type of the hidden {j : Size< i} -- which is the argument to the recursive call. -- All this would not be an issue if Agda still eagerly introduced -- trailing hidden arguments on the LHS, but this has other -- drawbacks (Q: even with varying arity?): cannot have -- hidden lambdas on rhs (used to name trailing hiddens in with-clauses).
programs/oeis/189/A189887.asm
neoneye/loda
22
167004
; A189887: Dimension of homogeneous component of degree n in x in the Malcev-Poisson superalgebra S^tilde(M). ; 1,1,2,3,4,6,9,11,12,14,17,19,20,22,25,27,28,30,33,35,36,38,41,43,44,46,49,51,52,54,57,59,60,62,65,67,68,70,73,75,76,78,81,83,84,86,89,91,92,94,97,99,100,102,105,107,108,110,113,115,116,118,121,123,124,126,129,131,132,134,137,139,140,142,145,147,148,150,153,155 mov $1,$0 div $0,2 lpb $1 sub $1,2 mov $0,$1 add $0,$1 bin $1,2 gcd $1,2 add $0,$1 sub $0,2 lpe add $0,1
complete-progress.agda
hazelgrove/hazelnut-dynamics-agda
16
5808
<reponame>hazelgrove/hazelnut-dynamics-agda open import Nat open import Prelude open import core open import contexts open import progress open import htype-decidable open import lemmas-complete module complete-progress where -- as in progress, we define a datatype for the possible outcomes of -- progress for readability. data okc : (d : ihexp) (Δ : hctx) → Set where V : ∀{d Δ} → d val → okc d Δ S : ∀{d Δ} → Σ[ d' ∈ ihexp ] (d ↦ d') → okc d Δ complete-progress : {Δ : hctx} {d : ihexp} {τ : htyp} → Δ , ∅ ⊢ d :: τ → d dcomplete → okc d Δ complete-progress wt comp with progress wt complete-progress wt comp | I x = abort (lem-ind-comp comp x) complete-progress wt comp | S x = S x complete-progress wt comp | BV (BVVal x) = V x complete-progress wt (DCCast comp x₂ ()) | BV (BVHoleCast x x₁) complete-progress (TACast wt x) (DCCast comp x₃ x₄) | BV (BVArrCast x₁ x₂) = abort (x₁ (complete-consistency x x₃ x₄))