commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
ddc36dae24c43d057f2b8f67f617631d371130bf
lib/Control/Process/Type.agda
lib/Control/Process/Type.agda
{- On the one hand this module has nothing to do with JS, on the other hand our JS binding relies on this particular type definition. -} module Control.Process.Type where open import Data.String.Base using (String) data Proc (C {-channels-} : Set₀) (M {-messages-} : Set₀) : Set₀ where end : Proc C M send : (d : C) (m : M) (p : Proc C M) → Proc C M recv : (d : C) (p : M → Proc C M) → Proc C M spawn : (p : C → Proc C M) (q : C → Proc C M) → Proc C M error : (err : String) → Proc C M
Add Control.Process.Type
Add Control.Process.Type
Agda
bsd-3-clause
audreyt/agda-libjs,crypto-agda/agda-libjs
e0c6a8e5b17986de3b0562105b17b44fb570453b
FiniteField/FinImplem.agda
FiniteField/FinImplem.agda
-- Implements ℤq with Data.Fin open import Type open import Data.Nat open import Data.Fin.NP as Fin open import Relation.Binary.PropositionalEquality open import Explore.Type open import Explore.Explorable open Fin.Modulo renaming (sucmod to [suc]; sucmod-inj to [suc]-inj) module FiniteField.FinImplem (q-1 : ℕ) ([0]' [1]' : Fin (suc q-1)) where -- open Sum q : ℕ q = suc q-1 ℤq : ★ ℤq = Fin q μℤq : Explorable ℤq μℤq = {!μFinSuc q-1!} sumℤq : Sum ℤq sumℤq = sum μℤq [0] : ℤq [0] = [0]' [1] : ℤq [1] = [1]' [suc]-stable : SumStableUnder (sum μℤq) [suc] [suc]-stable = {!μFinSUI [suc] [suc]-inj!} _ℕ⊞_ : ℕ → ℤq → ℤq zero ℕ⊞ n = n suc m ℕ⊞ n = m ℕ⊞ ([suc] n) ℕ⊞-inj : ∀ n {x y} → n ℕ⊞ x ≡ n ℕ⊞ y → x ≡ y ℕ⊞-inj zero eq = eq ℕ⊞-inj (suc n) eq = [suc]-inj (ℕ⊞-inj n eq) ℕ⊞-stable : ∀ m → SumStableUnder (sum μℤq) (_ℕ⊞_ m) ℕ⊞-stable m = {!μFinSUI (_ℕ⊞_ m) (ℕ⊞-inj m)!} _⊞_ : ℤq → ℤq → ℤq m ⊞ n = Fin▹ℕ m ℕ⊞ n ⊞-inj : ∀ m {x y} → m ⊞ x ≡ m ⊞ y → x ≡ y ⊞-inj m = ℕ⊞-inj (Fin▹ℕ m) ⊞-stable : ∀ m → SumStableUnder (sum μℤq) (_⊞_ m) ⊞-stable m = {!μFinSUI (_⊞_ m) (⊞-inj m)!} _ℕ⊠_ : ℕ → ℤq → ℤq zero ℕ⊠ n = [0] suc m ℕ⊠ n = n ⊞ (m ℕ⊠ n) _⊠_ : ℤq → ℤq → ℤq m ⊠ n = Fin▹ℕ m ℕ⊠ n _[^]ℕ_ : ℤq → ℕ → ℤq m [^]ℕ zero = [1] m [^]ℕ suc n = m ⊠ (m [^]ℕ n) _[^]_ : ℤq → ℤq → ℤq m [^] n = m [^]ℕ (Fin▹ℕ n)
Add FiniteField/FinImplem.agda (unfinished)
Add FiniteField/FinImplem.agda (unfinished)
Agda
bsd-3-clause
crypto-agda/crypto-agda
80516389760b8a704422d85e8bf6d5b682422d9d
Parametric/Change/Equivalence.agda
Parametric/Change/Equivalence.agda
------------------------------------------------------------------------ -- INCREMENTAL λ-CALCULUS -- -- Delta-observational equivalence ------------------------------------------------------------------------ import Parametric.Syntax.Type as Type import Parametric.Denotation.Value as Value module Parametric.Change.Equivalence {Base : Type.Structure} (⟦_⟧Base : Value.Structure Base) where open Type.Structure Base open Value.Structure Base ⟦_⟧Base open import Base.Denotation.Notation public open import Relation.Binary.PropositionalEquality open import Base.Change.Algebra open import Level open import Data.Unit -- Extension Point: None (currently). Do we need to allow plugins to customize -- this concept? Structure : Set Structure = Unit module Structure (unused : Structure) where module _ {ℓ} {A} {{ca : ChangeAlgebra ℓ A}} {x : A} where -- Delta-observational equivalence: these asserts that two changes -- give the same result when applied to a base value. _≙_ : ∀ dx dy → Set dx ≙ dy = x ⊞ dx ≡ x ⊞ dy -- _≙_ is indeed an equivalence relation: ≙-refl : ∀ {dx} → dx ≙ dx ≙-refl = refl ≙-symm : ∀ {dx dy} → dx ≙ dy → dy ≙ dx ≙-symm ≙ = sym ≙ ≙-trans : ∀ {dx dy dz} → dx ≙ dy → dy ≙ dz → dx ≙ dz ≙-trans ≙₁ ≙₂ = trans ≙₁ ≙₂ -- TODO: we want to show that all functions of interest respect -- delta-observational equivalence, so that two d.o.e. changes can be -- substituted for each other freely. That should be true for functions -- using changes parametrically, for derivatives and function changes, and -- for functions using only the interface to changes (including the fact -- that function changes are functions). Stating the general result, though, -- seems hard, we should rather have lemmas proving that certain classes of -- functions respect this equivalence.
Implement delta-observational equivalence (#244, #299)
Implement delta-observational equivalence (#244, #299) This proof shows that delta-observational equivalence is an equivalence relation. Known limitations of this commit: * it does not show that any function respects this relation; * it does not rephrase existing results; * this might better belong in Base.Change.Equivalence. Old-commit-hash: 46789e08b7a8bbd95738f9bf14b3ff8644151772
Agda
mit
inc-lc/ilc-agda
f58fb12a605924ada6a2cc1645dc725167a301ea
meaning.agda
meaning.agda
module meaning where open import Level record Meaning (Syntax : Set) {ℓ : Level} : Set (suc ℓ) where constructor meaning field Semantics : Set ℓ ⟦_⟧ : Syntax → Semantics open Meaning {{...}} public
Add missing file.
Add missing file. Forgot to add this file in commit ba1d8a8be0778b4d917c4d98c7db8f78f8f3cbbc. Old-commit-hash: 02fcec1035aa2e0190d1ba3fc335cecbade97c9b
Agda
mit
inc-lc/ilc-agda
14b8f096b525d8a615d01965c700b05596b5d603
New/Equivalence.agda
New/Equivalence.agda
module New.Equivalence where open import Relation.Binary.PropositionalEquality open import Function open import Data.Product open import Postulate.Extensionality open import New.Changes module _ {a} {A : Set a} {{CA : ChAlg A}} {x : A} where -- Delta-observational equivalence: these asserts that two changes -- give the same result when applied to a base value. -- To avoid unification problems, use a one-field record (a Haskell "newtype") -- instead of a "type synonym". record _≙_ (dx dy : Ch A) : Set a where -- doe = Delta-Observational Equivalence. constructor doe field proof : x ⊕ dx ≡ x ⊕ dy open _≙_ public -- Same priority as ≡ infix 4 _≙_ open import Relation.Binary -- _≙_ is indeed an equivalence relation: ≙-refl : ∀ {dx} → dx ≙ dx ≙-refl = doe refl ≙-sym : ∀ {dx dy} → dx ≙ dy → dy ≙ dx ≙-sym ≙ = doe $ sym $ proof ≙ ≙-trans : ∀ {dx dy dz} → dx ≙ dy → dy ≙ dz → dx ≙ dz ≙-trans ≙₁ ≙₂ = doe $ trans (proof ≙₁) (proof ≙₂) -- That's standard congruence applied to ≙ ≙-cong : ∀ {b} {B : Set b} (f : A → B) {dx dy} → dx ≙ dy → f (x ⊕ dx) ≡ f (x ⊕ dy) ≙-cong f da≙db = cong f $ proof da≙db ≙-isEquivalence : IsEquivalence (_≙_) ≙-isEquivalence = record { refl = ≙-refl ; sym = ≙-sym ; trans = ≙-trans } ≙-setoid : Setoid a a ≙-setoid = record { Carrier = Ch A ; _≈_ = _≙_ ; isEquivalence = ≙-isEquivalence } ≙-syntax : ∀ {a} {A : Set a} {{CA : ChAlg A}} (x : A) (dx₁ dx₂ : Ch A) → Set a ≙-syntax x dx₁ dx₂ = _≙_ {x = x} dx₁ dx₂ syntax ≙-syntax x dx₁ dx₂ = dx₁ ≙[ x ] dx₂ module BinaryValid {A : Set} {{CA : ChAlg A}} {B : Set} {{CB : ChAlg B}} {C : Set} {{CC : ChAlg C}} (f : A → B → C) (df : A → Ch A → B → Ch B → Ch C) where open import Data.Product binary-valid-preserve-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) → valid (f a b) (df a da b db) binary-valid-eq-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) → (f ⊕ df) (a ⊕ da) (b ⊕ db) ≡ f a b ⊕ df a da b db binary-valid : binary-valid-preserve-hp → binary-valid-eq-hp → valid f df binary-valid ext-valid proof a da ada = (λ b db bdb → ext-valid a da ada b db bdb , lem2 b db bdb) , ext lem1 where lem1 : ∀ b → f (a ⊕ da) b ⊕ df (a ⊕ da) (nil (a ⊕ da)) b (nil b) ≡ f a b ⊕ df a da b (nil b) lem1 b rewrite sym (update-nil b) | proof a da ada b (nil b) (nil-valid b) | update-nil b = refl lem2 : ∀ b (db : Ch B) (bdb : valid b db) → f a (b ⊕ db) ⊕ df a da (b ⊕ db) (nil (b ⊕ db)) ≡ f a b ⊕ df a da b db lem2 b db bdb rewrite sym (proof a da ada (b ⊕ db) (nil (b ⊕ db)) (nil-valid (b ⊕ db))) | update-nil (b ⊕ db) = proof a da ada b db bdb module TernaryValid {A : Set} {{CA : ChAlg A}} {B : Set} {{CB : ChAlg B}} {C : Set} {{CC : ChAlg C}} {D : Set} {{CD : ChAlg D}} (f : A → B → C → D) (df : A → Ch A → B → Ch B → C → Ch C → Ch D) where ternary-valid-preserve-hp = ∀ a da (ada : valid a da) b db (bdb : valid b db) c dc (cdc : valid c dc) → valid (f a b c) (df a da b db c dc) -- These are explicit definitions only to speed up typechecking. CA→B→C→D : ChAlg (A → B → C → D) CA→B→C→D = funCA f⊕df = (_⊕_ {{CA→B→C→D}} f df) -- Already this definition takes a while to typecheck. ternary-valid-eq-hp = ∀ a (da : Ch A {{CA}}) (ada : valid {{CA}} a da) b (db : Ch B {{CB}}) (bdb : valid {{CB}} b db) c (dc : Ch C {{CC}}) (cdc : valid {{CC}} c dc) → f⊕df (a ⊕ da) (b ⊕ db) (c ⊕ dc) ≡ f a b c ⊕ df a da b db c dc ternary-valid : ternary-valid-preserve-hp → ternary-valid-eq-hp → valid f df ternary-valid ext-valid proof a da ada = binary-valid (λ b db bdb c dc cdc → ext-valid a da ada b db bdb c dc cdc) lem2 , ext (λ b → ext (lem1 b)) where open BinaryValid (f a) (df a da) lem1 : ∀ b c → f⊕df (a ⊕ da) b c ≡ (f a ⊕ df a da) b c lem1 b c rewrite sym (update-nil b) | sym (update-nil c) | proof a da ada b (nil b) (nil-valid b) c (nil c) (nil-valid c) | update-nil b | update-nil c = refl -- rewrite -- sym -- (proof -- (a ⊕ da) (nil (a ⊕ da)) (nil-valid (a ⊕ da)) -- b (nil b) (nil-valid b) -- c (nil c) (nil-valid c)) -- | update-nil (a ⊕ da) -- | update-nil b -- | update-nil c = {! !} lem2 : ∀ b db (bdb : valid b db) c dc (cdc : valid c dc) → (f a ⊕ df a da) (b ⊕ db) (c ⊕ dc) ≡ f a b c ⊕ df a da b db c dc lem2 b db bdb c dc cdc rewrite sym (proof a da ada (b ⊕ db) (nil (b ⊕ db)) (nil-valid (b ⊕ db)) (c ⊕ dc) (nil (c ⊕ dc)) (nil-valid (c ⊕ dc)) ) | update-nil (b ⊕ db) | update-nil (c ⊕ dc) = proof a da ada b db bdb c dc cdc
Add lemmas to prove function changes valid
Add lemmas to prove function changes valid
Agda
mit
inc-lc/ilc-agda
02b7dc1fcde2d5ea5944dc426ae4920689962b5d
experiments/NonregularTraversable.agda
experiments/NonregularTraversable.agda
-- A traversable functor that is not regular. open import Data.Nat open import Data.Vec open import Data.Product record Applicative : Set₁ where constructor appl field Map : Set → Set pure : ∀ {A} → A → Map A call : ∀ {A B} → Map (A → B) → Map A → Map B Traversable : (Set → Set) → Set₁ Traversable F = (G : Applicative) → ∀ {A B} → (A → Map G B) → F A → Map G (F B) where open Applicative infixr 10 _^_ -- exponents for naturals _^_ : ℕ → ℕ → ℕ m ^ zero = 1 m ^ suc n = m * (m ^ n) -- a regular container RegCon : Set → Set RegCon A = Σ ℕ (Vec A) -- a regular traversal regTrav : Traversable RegCon regTrav G f (0 , []) = pure G ((0 , [])) where open Applicative regTrav G f (suc n , x ∷ xs) = call G (call G (pure G (λ y nys → (suc (proj₁ nys) , y ∷ proj₂ nys))) (f x)) (regTrav G f (n , xs)) where open Applicative -- a nonregular language: 0, 10, 1100, 111000, .... nonreg : ℕ → ℕ nonreg n = let 2n = 2 ^ n in 2n * pred 2n -- a nonregular finitary container NonregCon : Set → Set NonregCon A = Σ ℕ (λ n → Vec A (nonreg n)) fmap : ∀ {A B} (G : Applicative) → (A → B) → let open Applicative in Map G A → Map G B fmap G f gx = call G (pure G f) gx where open Applicative -- a nonregular traversable functor nonregTrav : Traversable NonregCon nonregTrav G f (n , xs) = let gnnys = regTrav G f ((nonreg n , xs)) in fmap G (λ{(nn , ys) → (n , {!ys!})}) gnnys -- should be well-typed but is not
add example of non-regular traversable functor
add example of non-regular traversable functor
Agda
mit
yfcai/CREG
ccc91a1d485cba9d42a78ea4ff80597f0f7e7849
bytecode.agda
bytecode.agda
-- This module is an example of the use of the circuit building library. -- The point is to start with a tiny bytecode evaluator for bit operations. module bytecode where open import Function open import Data.Nat open import Data.Vec open import Data.Product.NP open import Data.Bits open import Data.Bool open import Algebra.FunctionProperties data I : ℕ → Set where `[] : I 1 `op₀ : ∀ {i} (b : Bit) (is : I (1 + i)) → I i `op₁ : ∀ {i} (op₁ : Op₁ Bit) (is : I (1 + i)) → I (1 + i) `op₂ : ∀ {i} (op₂ : Op₂ Bit) (is : I (1 + i)) → I (2 + i) eval : ∀ {i} → I i → Bits i → Bit eval `[] (x ∷ []) = x eval (`op₀ b is) st = eval is (b ∷ st) eval (`op₁ op₁ is) (b ∷ st) = eval is (op₁ b ∷ st) eval (`op₂ op₂ is) (b₀ ∷ b₁ ∷ st) = eval is (op₂ b₀ b₁ ∷ st) eval₀ : I 0 → Bit eval₀ i₀ = eval i₀ [] open import circuit module Ck {C} (cb : CircuitBuilder C) where open CircuitBuilder cb data IC : ℕ → Set where `[] : IC 1 `op : ∀ {i ki ko} (op : C ki ko) (is : IC (ko + i)) → IC (ki + i) module Eval (runC : RunCircuit C) where module CF = CircuitBuilder bitsFunCircuitBuilder ckIC : ∀ {i} → IC i → C i 1 ckIC `[] = idC ckIC (`op op is) = op *** idC >>> ckIC is evalIC : ∀ {i} → IC i → Bits i → Bit evalIC is bs = head (runC (ckIC is) bs) ck : ∀ {i} → I i → C i 1 ck `[] = idC ck (`op₀ b is) = bit b *** idC >>> ck is ck (`op₁ op₁ is) = unOp op₁ *** idC >>> ck is ck (`op₂ op₂ is) = binOp op₂ *** idC >>> ck is I2IC : ∀ {i} → I i → IC i I2IC `[] = `[] I2IC (`op₀ b is) = `op (bit b) (I2IC is) I2IC (`op₁ op₁ is) = `op (unOp op₁) (I2IC is) I2IC (`op₂ op₂ is) = `op (binOp op₂) (I2IC is) ck₀ : I 0 → C 0 1 ck₀ = ck module CheckCk where open Ck bitsFunCircuitBuilder open CircuitBuilder bitsFunCircuitBuilder open import Relation.Binary.PropositionalEquality ck-eval : ∀ {i} (is : I i) bs → ck is bs ≡ eval is bs ∷ [] ck-eval `[] (x ∷ []) = refl ck-eval (`op₀ b is) bs = ck-eval is (b ∷ bs) ck-eval (`op₁ op₁ is) (b ∷ bs) = ck-eval is (op₁ b ∷ bs) ck-eval (`op₂ op₂ is) (b₀ ∷ b₁ ∷ bs) = ck-eval is (op₂ b₀ b₁ ∷ bs)
Add bytecode.agda to experiment with circuits
Add bytecode.agda to experiment with circuits
Agda
bsd-3-clause
crypto-agda/crypto-agda
095f53c09c64b3abe9688067512e48f0db0bf52b
ZK/SigmaProtocol/KnownStatement.agda
ZK/SigmaProtocol/KnownStatement.agda
open import Type using (Type) open import Data.Bool.Base using (Bool; true) open import Relation.Binary.Core using (_≡_; _≢_) -- This module assumes the exact statement of the Zero-Knowledge proof to be -- known by all parties. module ZK.SigmaProtocol.KnownStatement (Commitment : Type) -- Prover commitments (Challenge : Type) -- Verifier challenges, picked at random (Response : Type) -- Prover responses/proofs to challenges (Randomness : Type) -- Prover's randomness (Witness : Type) -- Prover's witness (ValidWitness : Witness → Type) -- Valid witness for the statement where -- The prover is made of two steps. -- * First, send the commitment. -- * Second, receive a challenge and send back the response. -- -- Therefor one represents a prover as a pair (a record) made -- of a commitment (get-A) and a function (get-f) from challenges -- to responses. -- -- Note that one might wish the function get-f to be partial. -- -- This covers any kind of prover, either honest or dishonest -- Notice as well that such should depend on some randomness. -- So such a prover as type: SomeRandomness → Prover record Prover-Interaction : Type where constructor _,_ field get-A : Commitment get-f : Challenge → Response Prover : Type Prover = (r : Randomness)(w : Witness) → Prover-Interaction -- A transcript of the interaction between the prover and the -- verifier. -- -- Note that in the case of an interactive zero-knowledge -- proof the transcript alone does not prove anything. It can usually -- be simulated if one knows the challenge before the commitment. -- -- The only way to be convinced by an interactive prover is to be/trust the verifier, -- namely to receive the commitment first and send a randomly picked challenge -- thereafter. So the proof is not transferable. -- -- The other way is by making the zero-knowledge proof non-interactive, which forces the -- challenge to be a cryptographic hash of the commitment and the statement. -- See the StrongFiatShamir module and the corresponding paper for more details. record Transcript : Type where constructor mk field get-A : Commitment get-c : Challenge get-f : Response -- The actual behavior of an interactive verifier is as follows: -- * Given a statement -- * Receive a commitment from the prover -- * Send a randomly chosen challenge to the prover -- * Receive a response to that challenge -- Since the first two points are common to all Σ-protocols we describe -- the verifier behavior as a computable test on the transcript. Verifier : Type Verifier = (t : Transcript) → Bool -- To run the interaction, one only needs the prover and a randomly -- chosen challenge. The returned transcript is then checked by the -- verifier afterwards. run : Prover-Interaction → Challenge → Transcript run (A , f) c = mk A c (f c) -- A Σ-protocol is made of the code for honest prover -- and honest verifier. record Σ-Protocol : Type where constructor _,_ field prover : Prover verifier : Verifier Verified : (t : Transcript) → Type Verified t = verifier t ≡ true -- Correctness (also called completeness in some papers): a Σ-protocol is said -- to be correct if for any challenge, the (honest) verifier accepts what -- the (honest) prover returns. Correct : Σ-Protocol → Type Correct (prover , verifier) = ∀ r {w} c → ValidWitness w → verifier (run (prover r w) c) ≡ true -- A simulator takes a challenge and a response and returns a commitment. -- -- As defined next, a correct simulator picks the commitment such that -- the transcript is accepted by the verifier. -- -- Notice that generally, to make a valid looking transcript one should -- randomly pick the challenge and the response. Simulator : Type Simulator = (c : Challenge) (s : Response) → Commitment -- A correct simulator always convinces the honest verifier. Correct-simulator : Verifier → Simulator → Type Correct-simulator verifier simulator = ∀ c s → let A = simulator c s in verifier (mk A c s) ≡ true {- A Σ-protocol, more specifically a verifier which is equipped with a correct simulator is said to be Special Honest Verifier Zero Knowledge. This property is one of the condition to apply the Strong Fiat Shamir transformation. The Special part of Special-Honest-Verifier-Zero-Knowledge is covered by the simulator being correct. The Honest part is not covered yet, the definition is informally adapted from the paper "How not to prove yourself": Furthermore, if the challenge c and response s where chosen uniformly at random from their respective domains then the triple (A, c, s) is distributed identically to that of an execution between the (honest) prover and the (honest) verifier (run prover c). where A = simulator c s -} record Special-Honest-Verifier-Zero-Knowledge (Σ-proto : Σ-Protocol) : Type where open Σ-Protocol Σ-proto field simulator : Simulator correct-simulator : Correct-simulator verifier simulator -- A pair of "Transcript"s such that the commitment is shared -- and the challenges are different. record Transcript² (verifier : Verifier) : Type where constructor mk field -- The commitment is shared get-A : Commitment -- The challenges... get-c₀ get-c₁ : Challenge -- ...are different c₀≢c₁ : get-c₀ ≢ get-c₁ -- The responses/proofs are arbitrary get-f₀ get-f₁ : Response -- The two transcripts t₀ : Transcript t₀ = mk get-A get-c₀ get-f₀ t₁ : Transcript t₁ = mk get-A get-c₁ get-f₁ field -- The transcripts verify verify₀ : verifier t₀ ≡ true verify₁ : verifier t₁ ≡ true -- Remark: What if the underlying witnesses are different? Nothing is enforced here. -- At least in the case of the Schnorr protocol it does not matter and yield a unique -- witness. Extractor : Verifier → Type Extractor verifier = Transcript² verifier → Witness Extract-Valid-Witness : (verifier : Verifier) → Extractor verifier → Type Extract-Valid-Witness verifier extractor = ∀ t² → ValidWitness (extractor t²) -- A Σ-protocol, more specifically a verifier which is equipped with -- a correct extractor is said to have the Special Soundness property. -- This property is one of the condition to apply the Strong Fiat Shamir -- transformation. record Special-Soundness Σ-proto : Type where open Σ-Protocol Σ-proto field -- TODO Challenge should exp large wrt the security param extractor : Extractor verifier extract-valid-witness : Extract-Valid-Witness verifier extractor record Special-Σ-Protocol : Type where field Σ-protocol : Σ-Protocol correct : Correct Σ-protocol shvzk : Special-Honest-Verifier-Zero-Knowledge Σ-protocol ssound : Special-Soundness Σ-protocol open Σ-Protocol Σ-protocol public open Special-Honest-Verifier-Zero-Knowledge shvzk public open Special-Soundness ssound public
Add ZK.SigmaProtocol.KnowStatement
Add ZK.SigmaProtocol.KnowStatement
Agda
bsd-3-clause
crypto-agda/crypto-agda
6419e6a499edf075accabe01063360bc7c867ef8
formalization/agda/Spire/Examples/CompLev.agda
formalization/agda/Spire/Examples/CompLev.agda
{-# OPTIONS --type-in-type #-} open import Data.Unit open import Data.Product hiding ( curry ; uncurry ) open import Data.List hiding ( concat ) open import Data.String open import Relation.Binary.PropositionalEquality open import Function module Spire.Examples.CompLev where ---------------------------------------------------------------------- Label : Set Label = String Enum : Set Enum = List Label data Tag : Enum → Set where here : ∀{l E} → Tag (l ∷ E) there : ∀{l E} → Tag E → Tag (l ∷ E) Branches : (E : Enum) (P : Tag E → Set) → Set Branches [] P = ⊤ Branches (l ∷ E) P = P here × Branches E (λ t → P (there t)) case : {E : Enum} (P : Tag E → Set) (cs : Branches E P) (t : Tag E) → P t case P (c , cs) here = c case P (c , cs) (there t) = case (λ t → P (there t)) cs t ---------------------------------------------------------------------- data Tel : Set where End : Tel Arg : (A : Set) (B : A → Tel) → Tel Elᵀ : Tel → Set Elᵀ End = ⊤ Elᵀ (Arg A B) = Σ A (λ a → Elᵀ (B a)) ---------------------------------------------------------------------- data Desc (I : Set) : Set where End : Desc I Rec : (i : I) (D : Desc I) → Desc I RecFun : (A : Set) (B : A → I) (D : Desc I) → Desc I Arg : (A : Set) (B : A → Desc I) → Desc I ---------------------------------------------------------------------- ISet : Set → Set ISet I = I → Set Elᴰ : {I : Set} (D : Desc I) → ISet I → Set Elᴰ End X = ⊤ Elᴰ (Rec j D) X = X j × Elᴰ D X Elᴰ (RecFun A B D) X = ((a : A) → X (B a)) × Elᴰ D X Elᴰ (Arg A B) X = Σ A (λ a → Elᴰ (B a) X) Hyps : {I : Set} (D : Desc I) (X : ISet I) (P : (i : I) → X i → Set) (xs : Elᴰ D X) → Set Hyps End X P tt = ⊤ Hyps (Rec i D) X P (x , xs) = P i x × Hyps D X P xs Hyps (RecFun A B D) X P (f , xs) = ((a : A) → P (B a) (f a)) × Hyps D X P xs Hyps (Arg A B) X P (a , xs) = Hyps (B a) X P xs ---------------------------------------------------------------------- data μ {I : Set} (R : I → Desc I) (i : I) : Set where init : Elᴰ (R i) (μ R) → μ R i ---------------------------------------------------------------------- ind : {I : Set} (R : I → Desc I) (M : (i : I) → μ R i → Set) (α : ∀ i (xs : Elᴰ (R i) (μ R)) (ihs : Hyps (R i) (μ R) M xs) → M i (init xs)) (i : I) (x : μ R i) → M i x prove : {I : Set} (D : Desc I) (R : I → Desc I) (M : (i : I) → μ R i → Set) (α : ∀ i (xs : Elᴰ (R i) (μ R)) (ihs : Hyps (R i) (μ R) M xs) → M i (init xs)) (xs : Elᴰ D (μ R)) → Hyps D (μ R) M xs ind R M α i (init xs) = α i xs (prove (R i) R M α xs) prove End R M α tt = tt prove (Rec j D) R M α (x , xs) = ind R M α j x , prove D R M α xs prove (RecFun A B D) R M α (f , xs) = (λ a → ind R M α (B a) (f a)) , prove D R M α xs prove (Arg A B) R M α (a , xs) = prove (B a) R M α xs ---------------------------------------------------------------------- DescE : Enum DescE = "End" ∷ "Rec" ∷ "Arg" ∷ [] DescT : Set DescT = Tag DescE -- EndT : DescT pattern EndT = here -- RecT : DescT pattern RecT = there here -- ArgT : DescT pattern ArgT = there (there here) DescR : Set → ⊤ → Desc ⊤ DescR I tt = Arg (Tag DescE) (case (λ _ → Desc ⊤) ( (Arg I λ i → End) , (Arg I λ i → Rec tt End) , (Arg Set λ A → RecFun A (λ a → tt) End) , tt )) `Desc : (I : Set) → Set `Desc I = μ (DescR I) tt -- `End : {I : Set} (i : I) → `Desc I pattern `End i = init (EndT , i , tt) -- `Rec : {I : Set} (i : I) (D : `Desc I) → `Desc I pattern `Rec i D = init (RecT , i , D , tt) -- `Arg : {I : Set} (A : Set) (B : A → `Desc I) → `Desc I pattern `Arg A B = init (ArgT , A , B , tt) ---------------------------------------------------------------------- FixI : (I : Set) → Set FixI I = I × `Desc I FixR' : (I : Set) (D : `Desc I) → I → `Desc I → Desc (FixI I) FixR' I D i (`End j) = Arg (j ≡ i) λ q → End FixR' I D i (`Rec j E) = Rec (j , D) (FixR' I D i E) FixR' I D i (`Arg A B) = Arg A λ a → FixR' I D i (B a) FixR' I D i (init (there (there (there ())) , xs)) FixR : (I : Set) (D : `Desc I) → FixI I → Desc (FixI I) FixR I D E,i = FixR' I D (proj₁ E,i) (proj₂ E,i) `Fix : (I : Set) (D : `Desc I) (i : I) → Set `Fix I D i = μ (FixR I D) (i , D) ----------------------------------------------------------------------
Fix internalized as a computational description.
Fix internalized as a computational description. The idea is that the core could have computatial descriptions, which do not mention things like which arguments are implicit, and Desc can be internalized as a description like the current primitive (non-computational) description that also mentions which arguments are implicit. Then you can define the fixpoint of that description as a computational description, parameterized by (I : Set) (D : DescI) and indexed by (i : I) (E : Desc I). It's cool that you can do this but I think it's one step too far in the direction of making the core type theory simple in exchange for more complicated derivable programs. If anything, defining `Desc, making an interpretation function for it, along with a toDesc function might be okay. But, again I think defining `Fix is probably not worthwhile.
Agda
bsd-3-clause
spire/spire
3be44d190ddb71b95417f9028965e046e7938081
agda/Language/Greek.agda
agda/Language/Greek.agda
module Language.Greek where data Maybe A : Set where none : Maybe A just : A → Maybe A data Unicode : Set where Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ′ μ ν ξ ο π ρ σ ς τ υ φ χ ψ ω : Unicode grave acute diaeresis smooth rough circumflex iotaSubscript : Unicode postulate Char : Set {-# BUILTIN CHAR Char #-} {-# COMPILED_TYPE Char Char #-} charToUnicode : Char -> Maybe Unicode charToUnicode 'Α' = just Α charToUnicode 'Β' = just Β charToUnicode 'Γ' = just Γ charToUnicode 'Δ' = just Δ charToUnicode 'Ε' = just Ε charToUnicode 'Ζ' = just Ζ charToUnicode 'Η' = just Η charToUnicode 'Θ' = just Θ charToUnicode 'Ι' = just Ι charToUnicode 'Κ' = just Κ charToUnicode 'Λ' = just Λ charToUnicode 'Μ' = just Μ charToUnicode 'Ν' = just Ν charToUnicode 'Ξ' = just Ξ charToUnicode 'Ο' = just Ο charToUnicode 'Π' = just Π charToUnicode 'Ρ' = just Ρ charToUnicode 'Σ' = just Σ charToUnicode 'Τ' = just Τ charToUnicode 'Υ' = just Υ charToUnicode 'Φ' = just Φ charToUnicode 'Χ' = just Χ charToUnicode 'Ψ' = just Ψ charToUnicode 'Ω' = just Ω charToUnicode 'α' = just α charToUnicode 'β' = just β charToUnicode 'γ' = just γ charToUnicode 'δ' = just δ charToUnicode 'ε' = just ε charToUnicode 'ζ' = just ζ charToUnicode 'η' = just η charToUnicode 'θ' = just θ charToUnicode 'ι' = just ι charToUnicode 'κ' = just κ charToUnicode 'λ' = just λ′ charToUnicode 'μ' = just μ charToUnicode 'ν' = just ν charToUnicode 'ξ' = just ξ charToUnicode 'ο' = just ο charToUnicode 'π' = just π charToUnicode 'ρ' = just ρ charToUnicode 'ς' = just ς charToUnicode 'σ' = just σ charToUnicode 'τ' = just τ charToUnicode 'υ' = just υ charToUnicode 'φ' = just φ charToUnicode 'χ' = just χ charToUnicode 'ψ' = just ψ charToUnicode 'ω' = just ω charToUnicode '\x0300' = just grave -- COMBINING GRAVE ACCENT charToUnicode '\x0301' = just acute -- COMBINING ACUTE ACCENT charToUnicode '\x0308' = just diaeresis -- COMBINING DIAERESIS charToUnicode '\x0313' = just smooth -- COMBINING COMMA ABOVE charToUnicode '\x0314' = just rough -- COMBINING REVERSED COMMA ABOVE charToUnicode '\x0342' = just circumflex -- COMBINING GREEK PERISPOMENI charToUnicode '\x0345' = just iotaSubscript -- COMBINING GREEK YPOGEGRAMMENI charToUnicode _ = none data UnicodeCategory : Set where letter mark : UnicodeCategory unicodeToCategory : Unicode → UnicodeCategory unicodeToCategory Α = letter unicodeToCategory Β = letter unicodeToCategory Γ = letter unicodeToCategory Δ = letter unicodeToCategory Ε = letter unicodeToCategory Ζ = letter unicodeToCategory Η = letter unicodeToCategory Θ = letter unicodeToCategory Ι = letter unicodeToCategory Κ = letter unicodeToCategory Λ = letter unicodeToCategory Μ = letter unicodeToCategory Ν = letter unicodeToCategory Ξ = letter unicodeToCategory Ο = letter unicodeToCategory Π = letter unicodeToCategory Ρ = letter unicodeToCategory Σ = letter unicodeToCategory Τ = letter unicodeToCategory Υ = letter unicodeToCategory Φ = letter unicodeToCategory Χ = letter unicodeToCategory Ψ = letter unicodeToCategory Ω = letter unicodeToCategory α = letter unicodeToCategory β = letter unicodeToCategory γ = letter unicodeToCategory δ = letter unicodeToCategory ε = letter unicodeToCategory ζ = letter unicodeToCategory η = letter unicodeToCategory θ = letter unicodeToCategory ι = letter unicodeToCategory κ = letter unicodeToCategory λ′ = letter unicodeToCategory μ = letter unicodeToCategory ν = letter unicodeToCategory ξ = letter unicodeToCategory ο = letter unicodeToCategory π = letter unicodeToCategory ρ = letter unicodeToCategory σ = letter unicodeToCategory ς = letter unicodeToCategory τ = letter unicodeToCategory υ = letter unicodeToCategory φ = letter unicodeToCategory χ = letter unicodeToCategory ψ = letter unicodeToCategory ω = letter unicodeToCategory grave = mark unicodeToCategory acute = mark unicodeToCategory diaeresis = mark unicodeToCategory smooth = mark unicodeToCategory rough = mark unicodeToCategory circumflex = mark unicodeToCategory iotaSubscript = mark data List A : Set where [] : List A _∷_ : A → List A -> List A infixr 6 _∷_ foldr : {A B : Set} → (A → B → B) → B → List A → B foldr f y [] = y foldr f y (x ∷ xs) = f x (foldr f y xs) data _And_ : (A : Set) → (B : Set) → Set₁ where _and_ : {A B : Set} → A → B → A And B data ConcreteLetter : Set where Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ′ μ ν ξ ο π ρ σ ς τ υ φ χ ψ ω : ConcreteLetter data ConcreteMark : Set where grave acute diaeresis smooth rough circumflex iotaSubscript : ConcreteMark
Add an initial start for an Agda model.
Add an initial start for an Agda model.
Agda
mit
scott-fleischman/greek-grammar,scott-fleischman/greek-grammar
8eb3bf726fb7d12e74f6c4c5fd3b4b9b641cfefd
lib/Algebra/Nearring.agda
lib/Algebra/Nearring.agda
{-# OPTIONS --without-K #-} open import Relation.Binary.PropositionalEquality.NP import Algebra.FunctionProperties.Eq open Algebra.FunctionProperties.Eq.Implicits open import Function.Extensionality open import Data.Product.NP open import Data.Nat.NP using (ℕ; zero; fold) renaming (suc to 1+) open import Data.Integer using (ℤ; +_; -[1+_]) open import Algebra.Raw open import Algebra.Monoid open import Algebra.Monoid.Commutative open import Algebra.Group open import Algebra.Group.Abelian open import HoTT module Algebra.Nearring where record Nearring+1-Struct {ℓ} {A : Set ℓ} (rng-ops : Ring-Ops A) : Set ℓ where open Ring-Ops rng-ops open ≡-Reasoning field +-grp-struct : Group-Struct +-grp-ops *-mon-struct : Monoid-Struct *-mon-ops *-+-distrʳ : _*_ DistributesOverʳ _+_ open Additive-Group-Struct +-grp-struct public -- 0−-involutive : Involutive 0−_ -- cancels-+-left : LeftCancel _+_ -- cancels-+-right : RightCancel _+_ -- ... open Multiplicative-Monoid-Struct *-mon-struct public open From-Ring-Ops rng-ops open From-+Group-1*Identity-DistributesOverʳ +-assoc 0+-identity +0-identity (snd 0−-inverse) 1*-identity *-+-distrʳ public +-grp : Group A +-grp = +-grp-ops , +-grp-struct module +-Grp = Group +-grp *-mon : Monoid A *-mon = *-mon-ops , *-mon-struct module *-Mon = Monoid *-mon record Nearring+1 {ℓ} (A : Set ℓ) : Set ℓ where field rng-ops : Ring-Ops A nearring+1-struct : Nearring+1-Struct rng-ops open Ring-Ops rng-ops public open Nearring+1-Struct nearring+1-struct public -- -} -- -} -- -} -- -} -- -}
Add Nearring+1
Add Nearring+1
Agda
bsd-3-clause
crypto-agda/agda-nplib
b5129ee5c0b5ffae12387ee403ca85c9cabd2fb1
lib/FFI/JS/BigI.agda
lib/FFI/JS/BigI.agda
open import FFI.JS hiding (toString) module FFI.JS.BigI where abstract BigI : Set BigI = JSValue BigI▹JSValue : BigI → JSValue BigI▹JSValue x = x unsafe-JSValue▹BigI : BigI → JSValue unsafe-JSValue▹BigI x = x postulate bigI : (x base : String) → BigI add : (x y : BigI) → BigI multiply : (x y : BigI) → BigI mod : (x y : BigI) → BigI modPow : (this e m : BigI) → BigI modInv : (this m : BigI) → BigI equals : (x y : BigI) → Bool toString : (x : BigI) → String fromHex : String → BigI toHex : BigI → String {-# COMPILED_JS bigI function(x) { return function (y) { return require("bigi")(x,y); }; } #-} {-# COMPILED_JS add function(x) { return function (y) { return x.add(y); }; } #-} {-# COMPILED_JS multiply function(x) { return function (y) { return x.multiply(y); }; } #-} {-# COMPILED_JS mod function(x) { return function (y) { return x.mod(y); }; } #-} {-# COMPILED_JS modPow function(x) { return function (y) { return function (z) { return x.modPow(y,z); }; }; } #-} {-# COMPILED_JS modInv function(x) { return function (y) { return x.modInverse(y); }; } #-} {-# COMPILED_JS equals function(x) { return function (y) { return x.equals(y); }; } #-} {-# COMPILED_JS toString function(x) { return x.toString(); } #-} {-# COMPILED_JS fromHex require("bigi").fromHex #-} {-# COMPILED_JS toHex function(x) { return x.toHex(); } #-} 0I 1I 2I : BigI 0I = bigI "0" "10" 1I = bigI "1" "10" 2I = bigI "2" "10"
Add FFI.JS.BigI
Add FFI.JS.BigI
Agda
bsd-3-clause
crypto-agda/agda-libjs,audreyt/agda-libjs
27acbf899d88340ad1d03042fa744d1a3b783e0c
Base/Change/Sums.agda
Base/Change/Sums.agda
module Base.Change.Sums where open import Relation.Binary.PropositionalEquality open import Level open import Base.Change.Algebra open import Base.Change.Equivalence open import Postulate.Extensionality open import Data.Sum module SumChanges ℓ (X Y : Set ℓ) {{CX : ChangeAlgebra ℓ X}} {{CY : ChangeAlgebra ℓ Y}} where open ≡-Reasoning data SumChange : X ⊎ Y → Set ℓ where ch₁ : ∀ {x} → (dx : Δ x) → SumChange (inj₁ x) rp₁₂ : ∀ {x} → (y : Y) → SumChange (inj₁ x) ch₂ : ∀ {y} → (dy : Δ y) → SumChange (inj₂ y) rp₂₁ : ∀ {y} → (x : X) → SumChange (inj₂ y) _⊕_ : (v : X ⊎ Y) → SumChange v → X ⊎ Y inj₁ x ⊕ ch₁ dx = inj₁ (x ⊞ dx) inj₂ y ⊕ ch₂ dy = inj₂ (y ⊞ dy) inj₁ x ⊕ rp₁₂ y = inj₂ y inj₂ y ⊕ rp₂₁ x = inj₁ x _⊝_ : ∀ (v₂ v₁ : X ⊎ Y) → SumChange v₁ inj₁ x₂ ⊝ inj₁ x₁ = ch₁ (x₂ ⊟ x₁) inj₂ y₂ ⊝ inj₂ y₁ = ch₂ (y₂ ⊟ y₁) inj₂ y₂ ⊝ inj₁ x₁ = rp₁₂ y₂ inj₁ x₂ ⊝ inj₂ y₁ = rp₂₁ x₂ s-nil : (v : X ⊎ Y) → SumChange v s-nil (inj₁ x) = ch₁ (nil x) s-nil (inj₂ y) = ch₂ (nil y) s-update-diff : ∀ (u v : X ⊎ Y) → v ⊕ (u ⊝ v) ≡ u s-update-diff (inj₁ x₂) (inj₁ x₁) = cong inj₁ (update-diff x₂ x₁) s-update-diff (inj₂ y₂) (inj₂ y₁) = cong inj₂ (update-diff y₂ y₁) s-update-diff (inj₁ x₂) (inj₂ y₁) = refl s-update-diff (inj₂ y₂) (inj₁ x₁) = refl s-update-nil : ∀ v → v ⊕ (s-nil v) ≡ v s-update-nil (inj₁ x) = cong inj₁ (update-nil x) s-update-nil (inj₂ y) = cong inj₂ (update-nil y) changeAlgebra : ChangeAlgebra ℓ (X ⊎ Y) changeAlgebra = record { Change = SumChange ; update = _⊕_ ; diff = _⊝_ ; nil = s-nil ; isChangeAlgebra = record { update-diff = s-update-diff ; update-nil = s-update-nil } } inj₁′ : (x : X) → (dx : Δ x) → Δ (inj₁ x) inj₁′ x dx = ch₁ dx inj₁′Derivative : Derivative inj₁ inj₁′ inj₁′Derivative x dx = refl inj₂′ : (y : Y) → (dy : Δ y) → Δ (inj₂ y) inj₂′ y dy = ch₂ dy inj₂′Derivative : Derivative inj₂ inj₂′ inj₂′Derivative y dy = refl -- Elimination form for sums. This is a less dependently-typed version of -- [_,_]. match : ∀ {Z : Set ℓ} → (X → Z) → (Y → Z) → X ⊎ Y → Z match f g (inj₁ x) = f x match f g (inj₂ y) = g y module _ {Z : Set ℓ} {{CZ : ChangeAlgebra ℓ Z}} where X→Z = FunctionChanges.changeAlgebra X Z --module ΔX→Z = FunctionChanges X Z {{CX}} {{CZ}} Y→Z = FunctionChanges.changeAlgebra Y Z --module ΔY→Z = FunctionChanges Y Z {{CY}} {{CZ}} X⊎Y→Z = FunctionChanges.changeAlgebra (X ⊎ Y) Z Y→Z→X⊎Y→Z = FunctionChanges.changeAlgebra (Y → Z) (X ⊎ Y → Z) open FunctionChanges using (apply; correct) match′₀-realizer : (f : X → Z) → Δ f → (g : Y → Z) → Δ g → (s : X ⊎ Y) → Δ s → Δ (match f g s) match′₀-realizer f df g dg (inj₁ x) (ch₁ dx) = apply df x dx match′₀-realizer f df g dg (inj₁ x) (rp₁₂ y) = ((g ⊞ dg) y) ⊟ (f x) match′₀-realizer f df g dg (inj₂ y) (rp₂₁ x) = ((f ⊞ df) x) ⊟ (g y) match′₀-realizer f df g dg (inj₂ y) (ch₂ dy) = apply dg y dy match′₀-realizer-correct : (f : X → Z) → (df : Δ f) → (g : Y → Z) → (dg : Δ g) → (s : X ⊎ Y) → (ds : Δ s) → match f g (s ⊕ ds) ⊞ match′₀-realizer f df g dg (s ⊕ ds) (nil (s ⊕ ds)) ≡ match f g s ⊞ match′₀-realizer f df g dg s ds match′₀-realizer-correct f df g dg (inj₁ x) (ch₁ dx) = correct df x dx match′₀-realizer-correct f df g dg (inj₂ y) (ch₂ dy) = correct dg y dy match′₀-realizer-correct f df g dg (inj₁ x) (rp₁₂ y) rewrite update-diff ((g ⊞ dg) y) (f x) = refl match′₀-realizer-correct f df g dg (inj₂ y) (rp₂₁ x) rewrite update-diff ((f ⊞ df) x) (g y) = refl match′₀ : (f : X → Z) → Δ f → (g : Y → Z) → Δ g → Δ (match f g) match′₀ f df g dg = record { apply = match′₀-realizer f df g dg ; correct = match′₀-realizer-correct f df g dg } match′-realizer-correct-body : (f : X → Z) → (df : Δ f) → (g : Y → Z) → (dg : Δ g) → (s : X ⊎ Y) → (match f (g ⊞ dg) ⊞ match′₀ f df (g ⊞ dg) (nil (g ⊞ dg))) s ≡ (match f g ⊞ match′₀ f df g dg) s match′-realizer-correct-body f df g dg (inj₁ x) = refl -- refl doesn't work here. That seems a *huge* bad smell. However, that's simply because we're only updating g, not f match′-realizer-correct-body f df g dg (inj₂ y) rewrite update-nil y = update-diff (g y ⊞ apply dg y (nil y)) (g y ⊞ apply dg y (nil y)) match′-realizer-correct : (f : X → Z) → (df : Δ f) → (g : Y → Z) → (dg : Δ g) → (match f (g ⊞ dg)) ⊞ match′₀ f df (g ⊞ dg) (nil (g ⊞ dg)) ≡ match f g ⊞ match′₀ f df g dg match′-realizer-correct f df g dg = ext (match′-realizer-correct-body f df g dg) match′ : (f : X → Z) → Δ f → Δ (match f) match′ f df = record { apply = λ g dg → match′₀ f df g dg ; correct = match′-realizer-correct f df }
Implement change structure for sum types
Implement change structure for sum types
Agda
mit
inc-lc/ilc-agda
98776944ea4983b6faeeced4116bc7798c5e3ebc
Crypto/Sig/Lamport.agda
Crypto/Sig/Lamport.agda
{-# OPTIONS --without-K #-} open import Function using (_∘_) open import Data.Nat.NP hiding (_==_) open import Data.Product.NP hiding (map) open import Data.Bit hiding (_==_) open import Data.Bits open import Data.Bits.Properties open import Data.Vec.NP open import Relation.Binary.PropositionalEquality.NP import Crypto.Sig.LamportOneBit module Crypto.Sig.Lamport (#digest : ℕ) (#seed : ℕ) (#secret : ℕ) (#message : ℕ) (hash-secret : Bits #secret → Bits #digest) (seed-expansion : Bits #seed → Bits (#message * 2* #secret)) where module OTS1 = Crypto.Sig.LamportOneBit #secret #digest hash-secret H = hash-secret #seckey1 = 2* #secret #pubkey1 = 2* #digest #signature1 = #secret #seckey = #message * #seckey1 #pubkey = #message * #pubkey1 #signature = #message * #signature1 Digest = Bits #digest Seed = Bits #seed Secret = Bits #secret SignKey = Bits #seckey Message = Bits #message Signature = Bits #signature VerifKey = Bits #pubkey verif-key : SignKey → VerifKey verif-key = map* #message OTS1.verif-key module verifkey (vk : VerifKey) where vk1s = group #message #pubkey1 vk module signkey (sk : SignKey) where sk1s = group #message #seckey1 sk vk = verif-key sk open verifkey vk public module signature (sig : Signature) where sig1s = group #message #signature1 sig key-gen : Seed → VerifKey × SignKey key-gen s = vk , sk module key-gen where sk = seed-expansion s vk = verif-key sk sign : SignKey → Message → Signature sign sk m = sig module sign where open signkey sk public sig1s = map OTS1.sign sk1s ⊛ m sig = concat sig1s verify : VerifKey → Message → Signature → Bit verify vk m sig = and (map OTS1.verify vk1s ⊛ m ⊛ sig1s) module verify where open verifkey vk public open signature sig public verify-correct-sig : ∀ sk m → verify (verif-key sk) m (sign sk m) ≡ 1b verify-correct-sig = lemma where module lemma {#m} sk b m where skL = take #seckey1 sk skH = drop #seckey1 sk vkL = OTS1.verif-key skL vkH = map* #m OTS1.verif-key skH sigL = OTS1.sign skL b sigH = concat (map OTS1.sign (group #m #seckey1 skH) ⊛ m) lemma : ∀ {#m} sk m → and (map OTS1.verify (group #m #pubkey1 (map* #m OTS1.verif-key sk)) ⊛ m ⊛ group #m #signature1 (concat (map OTS1.sign (group #m #seckey1 sk) ⊛ m))) ≡ 1b lemma sk [] = refl lemma sk (b ∷ m) rewrite (let open lemma sk b m in take-++ #pubkey1 vkL vkH) | (let open lemma sk b m in drop-++ #pubkey1 vkL vkH) | (let open lemma sk b m in take-++ #signature1 sigL sigH) | (let open lemma sk b m in drop-++ #signature1 sigL sigH) | (let open lemma sk b m in OTS1.verify-correct-sig skL b) | (let open lemma sk b m in lemma skH m) = refl -- -} -- -} -- -} -- -}
Add Crypto.Sig.Lamport
Add Crypto.Sig.Lamport
Agda
bsd-3-clause
crypto-agda/crypto-agda
128af4af6ee42b630e845312b9e05e5b42880cae
Control/Strategy/Utils.agda
Control/Strategy/Utils.agda
{-# OPTIONS --copatterns #-} open import Type open import Function open import Data.Product open import Control.Strategy renaming (map to mapS) module Control.Strategy.Utils where record Proto : ★₁ where constructor P[_,_] field Q : ★ R : Q → ★ Client : Proto → ★ → ★ Client P[ Q , R ] A = Strategy Q R A {- data Bisim {P P' A A'} (RA : A → A' → ★) : Client P A → Client P' A' → ★ where ask-nop : ∀ {q? cont clt} r → Bisim RA (cont r) clt → Bisim RA (ask q? cont) clt ask-ask : ∀ q₀ q₁ cont₀ cont₁ r₀ r₁ → ({!!} → Bisim RA (cont₀ r₀) (cont₁ r₁)) → Bisim RA (ask q₀ cont₀) (ask q₁ cont₁) -} module Unused where mapS' : ∀ {A B Q Q' R} (f : A → B) (g : Q → Q') → Strategy Q (R ∘ g) A → Strategy Q' R B mapS' f g (ask q cont) = ask (g q) (λ r → mapS' f g (cont r)) mapS' f g (done x) = done (f x) [_,_]=<<_ : ∀ {A B Q Q' R} (f : A → Strategy Q' R B) (g : Q → Q') → Strategy Q (R ∘ g) A → Strategy Q' R B [ f , g ]=<< ask q? cont = ask (g q?) (λ r → [ f , g ]=<< cont r) [ f , g ]=<< done x = f x module Rec {A B Q : ★} {R : Q → ★} {M : ★ → ★} (runAsk : ∀ {A} → (q : Q) → (R q → M A) → M A) (runDone : A → M B) where runMM : Strategy Q R A → M B runMM (ask q? cont) = runAsk q? (λ r → runMM (cont r)) runMM (done x) = runDone x module MM {A B Q : ★} {R : Q → ★} {M : ★ → ★} (_>>=M_ : ∀ {A B : ★} → M A → (A → M B) → M B) (runAsk : (q : Q) → M (R q)) (runDone : A → M B) where runMM : Strategy Q R A → M B runMM (ask q? cont) = runAsk q? >>=M (λ r → runMM (cont r)) runMM (done x) = runDone x module _ {A B Q Q' : ★} {R : Q → ★} {R'} (f : (q : Q) → Strategy Q' R' (R q)) (g : A → Strategy Q' R' B) where [_,_]=<<'_ : Strategy Q R A → Strategy Q' R' B [_,_]=<<'_ (ask q? cont) = f q? >>= λ r → [_,_]=<<'_ (cont r) [_,_]=<<'_ (done x) = g x record ServerResp (P : Proto) (q : Proto.Q P) (A : ★₀) : ★₀ where coinductive open Proto P field srv-resp : R q srv-cont : ∀ q → ServerResp P q A open ServerResp Server : Proto → ★₀ → ★₀ Server P A = ∀ q → ServerResp P q A OracleServer : Proto → ★₀ OracleServer P[ Q , R ] = (q : Q) → R q module _ {P : Proto} {A : ★} where open Proto P com : Server P A → Client P A → A com srv (ask q κc) = com (srv-cont r) (κc (srv-resp r)) where r = srv q com srv (done x) = x module _ {P P' : Proto} {A A' : ★} where module P = Proto P module P' = Proto P' record MITM : ★ where coinductive field hack-query : (q' : P'.Q) → Client P (P'.R q' × MITM) hack-result : A' → Client P A open MITM module WithOutBind where hacked-com-client : Server P A → MITM → Client P' A' → A hacked-com-mitm : ∀ {q'} → Server P A → Client P (P'.R q' × MITM) → (P'.R q' → Client P' A') → A hacked-com-srv-resp : ∀ {q q'} → ServerResp P q A → (P.R q → Client P (P'.R q' × MITM)) → (P'.R q' → Client P' A') → A hacked-com-srv-resp r mitm clt = hacked-com-mitm (srv-cont r) (mitm (srv-resp r)) clt hacked-com-mitm srv (ask q? mitm) clt = hacked-com-srv-resp (srv q?) mitm clt hacked-com-mitm srv (done (r' , mitm)) clt = hacked-com-client srv mitm (clt r') hacked-com-client srv mitm (ask q' κc) = hacked-com-mitm srv (hack-query mitm q') κc hacked-com-client srv mitm (done x) = com srv (hack-result mitm x) mitm-to-client-trans : MITM → Client P' A' → Client P A mitm-to-client-trans mitm (ask q? cont) = hack-query mitm q? >>= λ { (r' , mitm') → mitm-to-client-trans mitm' (cont r') } mitm-to-client-trans mitm (done x) = hack-result mitm x hacked-com : Server P A → MITM → Client P' A' → A hacked-com srv mitm clt = com srv (mitm-to-client-trans mitm clt) module _ (P : Proto) (A : ★) where open Proto P open MITM honest : MITM {P} {P} {A} {A} hack-query honest q = ask q λ r → done (r , honest) hack-result honest a = done a module _ (P : Proto) (A : ★) (Oracle : OracleServer P) where oracle-server : Server P A srv-resp (oracle-server q) = Oracle q srv-cont (oracle-server q) = oracle-server -- -} -- -} -- -} -- -} -- -} -- -} -- -} -- -} -- -}
Add Control.Strategy.Utils
Add Control.Strategy.Utils
Agda
bsd-3-clause
crypto-agda/crypto-agda
f4f6e7a3cad61d0a276de2905272032cf125b5eb
lib/Data/Product/Param/Binary.agda
lib/Data/Product/Param/Binary.agda
{-# OPTIONS --without-K #-} open import Level open import Data.Product renaming (proj₁ to fst; proj₂ to snd) open import Function.Param.Binary module Data.Product.Param.Binary where record ⟦Σ⟧ {a₁ a₂ b₂ b₁ aᵣ bᵣ} {A₁ : Set a₁} {A₂ : Set a₂} {B₁ : A₁ → Set b₁} {B₂ : A₂ → Set b₂} (Aᵣ : A₁ → A₂ → Set aᵣ) (Bᵣ : {x₁ : A₁} {x₂ : A₂} (xᵣ : Aᵣ x₁ x₂) → B₁ x₁ → B₂ x₂ → Set bᵣ) (p₁ : Σ A₁ B₁) (p₂ : Σ A₂ B₂) : Set (aᵣ ⊔ bᵣ) where constructor _⟦,⟧_ field ⟦fst⟧ : Aᵣ (fst p₁) (fst p₂) ⟦snd⟧ : Bᵣ ⟦fst⟧ (snd p₁) (snd p₂) open ⟦Σ⟧ public infixr 4 _⟦,⟧_ syntax ⟦Σ⟧ Aᵣ (λ xᵣ → e) = [ xᵣ ∶ Aᵣ ]⟦×⟧[ e ] ⟦∃⟧ : ∀ {a₁ a₂ b₂ b₁ aᵣ bᵣ} {A₁ : Set a₁} {A₂ : Set a₂} {Aᵣ : A₁ → A₂ → Set aᵣ} {B₁ : A₁ → Set b₁} {B₂ : A₂ → Set b₂} (Bᵣ : ⟦Pred⟧ bᵣ Aᵣ B₁ B₂) (p₁ : Σ A₁ B₁) (p₂ : Σ A₂ B₂) → Set _ ⟦∃⟧ = ⟦Σ⟧ _ syntax ⟦∃⟧ (λ xᵣ → e) = ⟦∃⟧[ xᵣ ] e _⟦×⟧_ : ∀ {a₁ a₂ b₂ b₁ aᵣ bᵣ} {A₁ : Set a₁} {A₂ : Set a₂} {B₁ : Set b₁} {B₂ : Set b₂} (Aᵣ : A₁ → A₂ → Set aᵣ) (Bᵣ : B₁ → B₂ → Set bᵣ) (p₁ : A₁ × B₁) (p₂ : A₂ × B₂) → Set (aᵣ ⊔ bᵣ) _⟦×⟧_ Aᵣ Bᵣ = ⟦Σ⟧ Aᵣ (λ _ → Bᵣ) {- _⟦×⟧_ : ∀ {a₁ a₂ aᵣ} {A₁ : Set a₁} {A₂ : Set a₂} (Aᵣ : A₁ → A₂ → Set aᵣ) {b₁ b₂ bᵣ} {B₁ : Set b₁} {B₂ : Set b₂} (Bᵣ : B₁ → B₂ → Set bᵣ) (p₁ : A₁ × B₁) (p₂ : A₂ × B₂) → Set _ _⟦×⟧_ Aᵣ Bᵣ = λ p₁ p₂ → Aᵣ (fst p₁) (fst p₂) × Bᵣ (snd p₁) (snd p₂) -} {- One can give these two types to ⟦_,_⟧: ⟦_,_⟧' : ∀ {a₁ a₂ b₁ b₂ aᵣ bᵣ} {A₁ : Set a₁} {A₂ : Set a₂} {B₁ : A₁ → Set b₁} {B₂ : A₂ → Set b₂} {Aᵣ : ⟦Set⟧ aᵣ A₁ A₂} {Bᵣ : ⟦Pred⟧ Aᵣ bᵣ B₁ B₂} {x₁ x₂ y₁ y₂} (xᵣ : Aᵣ x₁ x₂) (yᵣ : Bᵣ xᵣ y₁ y₂) → ⟦Σ⟧ Aᵣ Bᵣ (x₁ , y₁) (x₂ , y₂) ⟦_,_⟧' = ⟦_,_⟧ ⟦_,_⟧'' : ∀ {a₁ a₂ b₁ b₂ aᵣ bᵣ} {A₁ : Set a₁} {A₂ : Set a₂} {B₁ : A₁ → Set b₁} {B₂ : A₂ → Set b₂} {Aᵣ : ⟦Set⟧ aᵣ A₁ A₂} {Bᵣ : ⟦Pred⟧ Aᵣ bᵣ B₁ B₂} {p₁ p₂} (⟦fst⟧ : Aᵣ (fst p₁) (fst p₂)) (⟦snd⟧ : Bᵣ ⟦fst⟧ (snd p₁) (snd p₂)) → ⟦Σ⟧ Aᵣ Bᵣ p₁ p₂ ⟦_,_⟧'' = ⟦_,_⟧ -}
add Data.Product.Param.Binary
add Data.Product.Param.Binary
Agda
bsd-3-clause
np/agda-parametricity
8fd23013cafc4153d1b4a63b41e95bc6ecbbac7e
Crypto/Sig/LamportOneBit.agda
Crypto/Sig/LamportOneBit.agda
{-# OPTIONS --without-K #-} open import Data.Nat.NP hiding (_==_) open import Data.Product.NP hiding (map) open import Data.Bit hiding (_==_) open import Data.Bits open import Data.Bits.Properties open import Data.Vec.NP open import Relation.Binary.PropositionalEquality.NP module Crypto.Sig.LamportOneBit (#secret : ℕ) (#digest : ℕ) (hash : Bits #secret → Bits #digest) where #signkey = 2* #secret #verifkey = 2* #digest #signature = #secret Digest = Bits #digest Secret = Bits #secret SignKey = Bits #signkey Signature = Bits #signature VerifKey = Bits #verifkey module signkey (sk : SignKey) where skL = take #secret sk skH = drop #secret sk vkL = hash skL vkH = hash skH -- Derive the public key by hashing each secret verif-key : SignKey → VerifKey verif-key = map2* #secret #digest hash module verifkey (vk : VerifKey) where vkL = take #digest vk vkH = drop #digest vk -- Key generation key-gen : SignKey → VerifKey × SignKey key-gen sk = vk , sk module key-gen where vk = verif-key sk -- Sign a single bit message sign : SignKey → Bit → Signature sign sk b = take2* _ b sk -- Verify the signature of a single bit message verify : VerifKey → Bit → Signature → Bit verify vk b sig = take2* _ b vk == hash sig verify-correct-sig : ∀ sk b → verify (verif-key sk) b (sign sk b) ≡ 1b verify-correct-sig sk 0b = ==-reflexive (take-++ #digest (hash (take #secret sk)) _) verify-correct-sig sk 1b = ==-reflexive (drop-++ #digest (hash (take #secret sk)) _) import Algebra.FunctionProperties.Eq open Algebra.FunctionProperties.Eq.Implicits module Assuming-injectivity (hash-inj : Injective hash) where -- If one considers the hash function injective, then, so is verif-key verif-key-inj : ∀ {sk1 sk2} → verif-key sk1 ≡ verif-key sk2 → sk1 ≡ sk2 verif-key-inj {sk1} {sk2} e = take-drop= #secret sk1 sk2 (hash-inj (++-inj₁ e)) (hash-inj (++-inj₂ sk1.vkL sk2.vkL e)) where module sk1 = signkey sk1 module sk2 = signkey sk2 -- Therefor under this assumption, different secret keys means different public keys verif-key-corrolary : ∀ {sk1 sk2} → sk1 ≢ sk2 → verif-key sk1 ≢ verif-key sk2 verif-key-corrolary {sk1} {sk2} sk≢ vk= = sk≢ (verif-key-inj vk=) -- If one considers the hash function injective then there is -- only one signing key which can sign correctly all (0 and 1) -- the messages signkey-uniqness : ∀ sk1 sk2 → (∀ b → verify (verif-key sk1) b (sign sk2 b) ≡ 1b) → sk1 ≡ sk2 signkey-uniqness sk1 sk2 e = take-drop= #secret sk1 sk2 (lemmaL (e 0b)) (lemmaH (e 1b)) where module sk1 = signkey sk1 module sk2 = signkey sk2 lemmaL : verify (verif-key sk1) 0b (sign sk2 0b) ≡ 1b → sk1.skL ≡ sk2.skL lemmaL e0 rewrite take-++ #digest sk1.vkL sk1.vkH | hash-inj (==⇒≡ e0) = refl lemmaH : verify (verif-key sk1) 1b (sign sk2 1b) ≡ 1b → sk1.skH ≡ sk2.skH lemmaH e1 rewrite drop-++ #digest sk1.vkL sk1.vkH | hash-inj (==⇒≡ e1) = refl module Assuming-invertibility (unhash : Digest → Secret) (unhash-hash : ∀ x → unhash (hash x) ≡ x) (hash-unhash : ∀ x → hash (unhash x) ≡ x) where -- EXERCISES {- recover-signkey : VerifKey → SignKey recover-signkey = {!!} recover-signkey-correct : ∀ sk → recover-signkey (verif-key sk) ≡ sk recover-signkey-correct = {!!} forgesig : VerifKey → Bit → Signature forgesig = {!!} forgesig-correct : ∀ vk b → verify vk b (forgesig vk b) ≡ 1b forgesig-correct = {!!} -} -- -}
Add Crypto.Sig.LamportOneBit
Add Crypto.Sig.LamportOneBit
Agda
bsd-3-clause
crypto-agda/crypto-agda
fefd4590ac23e7cdf91cbc2277dcce1be57d736e
Control/Strategy.agda
Control/Strategy.agda
module Control.Strategy where open import Function open import Type using (★) open import Category.Monad open import Relation.Binary.PropositionalEquality.NP data Strategy (Q R A : ★) : ★ where ask : (q? : Q) (cont : R → Strategy Q R A) → Strategy Q R A done : A → Strategy Q R A infix 2 _≈_ data _≈_ {Q R A} : (s₀ s₁ : Strategy Q R A) → ★ where ask-ask : ∀ {k₀ k₁} → (q? : Q) (cont : ∀ r → k₀ r ≈ k₁ r) → ask q? k₀ ≈ ask q? k₁ done-done : ∀ x → done x ≈ done x ≈-refl : ∀ {Q R A} {s : Strategy Q R A} → s ≈ s ≈-refl {s = ask q? cont} = ask-ask q? (λ r → ≈-refl) ≈-refl {s = done x} = done-done x module _ {Q R : ★} where private M : ★ → ★ M = Strategy Q R _=<<_ : ∀ {A B} → (A → M B) → M A → M B f =<< ask q? cont = ask q? (λ r → f =<< cont r) f =<< done x = f x return : ∀ {A} → A → M A return = done map : ∀ {A B} → (A → B) → M A → M B map f s = (done ∘ f) =<< s join : ∀ {A} → M (M A) → M A join s = id =<< s _>>=_ : ∀ {A B} → M A → (A → M B) → M B _>>=_ = flip _=<<_ rawMonad : RawMonad M rawMonad = record { return = return; _>>=_ = _>>=_ } return-=<< : ∀ {A} (m : M A) → return =<< m ≈ m return-=<< (ask q? cont) = ask-ask q? (λ r → return-=<< (cont r)) return-=<< (done x) = done-done x return->>= : ∀ {A B} (x : A) (f : A → M B) → return x >>= f ≡ f x return->>= _ _ = refl >>=-assoc : ∀ {A B C} (mx : M A) (my : A → M B) (f : B → M C) → (mx >>= λ x → (my x >>= f)) ≈ (mx >>= my) >>= f >>=-assoc (ask q? cont) my f = ask-ask q? (λ r → >>=-assoc (cont r) my f) >>=-assoc (done x) my f = ≈-refl map-id : ∀ {A} (s : M A) → map id s ≈ s map-id = return-=<< map-∘ : ∀ {A B C} (f : A → B) (g : B → C) s → map (g ∘ f) s ≈ (map g ∘ map f) s map-∘ f g s = >>=-assoc s (done ∘ f) (done ∘ g) module EffectfulRun (E : ★ → ★) (_>>=E_ : ∀ {A B} → E A → (A → E B) → E B) (returnE : ∀ {A} → A → E A) (Oracle : Q → E R) where runE : ∀ {A} → M A → E A runE (ask q? cont) = Oracle q? >>=E (λ r → runE (cont r)) runE (done x) = returnE x module _ (Oracle : Q → R) where run : ∀ {A} → M A → A run (ask q? cont) = run (cont (Oracle q?)) run (done x) = x module _ {A B : ★} (f : A → M B) where run->>= : (s : M A) → run (s >>= f) ≡ run (f (run s)) run->>= (ask q? cont) = run->>= (cont (Oracle q?)) run->>= (done x) = refl module _ {A B : ★} (f : A → B) where run-map : (s : M A) → run (map f s) ≡ f (run s) run-map = run->>= (return ∘ f) module _ {A B : ★} where run-≈ : {s₀ s₁ : M A} → s₀ ≈ s₁ → run s₀ ≡ run s₁ run-≈ (ask-ask q? cont) = run-≈ (cont (Oracle q?)) run-≈ (done-done x) = refl
Add Control.Strategy
Add Control.Strategy
Agda
bsd-3-clause
crypto-agda/crypto-agda
962dded37d6c55fa91fe570fbfe0821e7c37241a
ttfp1.agda
ttfp1.agda
-- some excises for learning ttfp (type theory for functional programming). -- most of the code is *borrowed* from learn you an agda shamelessly -- Function composition _∘_ : {A : Set} { B : A -> Set} { C : (x : A) -> B x -> Set} (f : {x : A}(y : B x) -> C x y) (g : (x : A) -> B x) (x : A) -> C x (g x) (f ∘ g) x = f (g x) -- Conjuntion, ∏-type in haskell data _∧_ (α : Set) (β : Set) : Set where ∧-intro : α → β → (α ∧ β) ∧-elim₁ : {α β : Set} → (α ∧ β) → α ∧-elim₁ (∧-intro p q) = p ∧-elim₂ : {α β : Set} → (α ∧ β) → β ∧-elim₂ (∧-intro p q) = q _⇔_ : (α : Set) → (β : Set) → Set a ⇔ b = (a → b) ∧ (b → a) ∧-comm′ : {α β : Set} → (α ∧ β) → (β ∧ α) ∧-comm′ (∧-intro a b) = ∧-intro b a ∧-comm : {α β : Set} → (α ∧ β) ⇔ (β ∧ α) ∧-comm = ∧-intro ∧-comm′ ∧-comm′ -- type signature cannot be eliminated, was expecting type could be infered but it wasn't the case. e₁e₁ : { P Q R : Set} → ( (P ∧ Q) ∧ R ) → P e₁e₁ = ∧-elim₁ ∘ ∧-elim₁ e₂e₁ : { P Q R : Set} → ( (P ∧ Q) ∧ R) → Q e₂e₁ = ∧-elim₂ ∘ ∧-elim₁ ∧-assoc₁ : { P Q R : Set } → ((P ∧ Q) ∧ R) → (P ∧ (Q ∧ R)) ∧-assoc₁ = λ x → ∧-intro (∧-elim₁ (∧-elim₁ x)) (∧-intro (∧-elim₂ (∧-elim₁ x)) (∧-elim₂ x)) ∧-assoc₂ : {P Q R : Set} → (P ∧ (Q ∧ R)) → ((P ∧ Q) ∧ R) ∧-assoc₂ = λ x → ∧-intro (∧-intro (∧-elim₁ x) (∧-elim₁ (∧-elim₂ x))) (∧-elim₂ (∧-elim₂ x)) ∧-assoc : {P Q R : Set} → ((P ∧ Q) ∧ R) ⇔ (P ∧ (Q ∧ R)) ∧-assoc = ∧-intro ∧-assoc₁ ∧-assoc₂ -- Disjunctions, ∑-type in haskell data _∨_ (P Q : Set) : Set where ∨-intro₁ : P → P ∨ Q ∨-intro₂ : Q → P ∨ Q ∨-elim : {A B C : Set} → (A ∨ B) → (A → C) → (B → C) → C ∨-elim (∨-intro₁ a) ac bc = ac a ∨-elim (∨-intro₂ b) ac bc = bc b ∨-comm′ : {P Q : Set} → (P ∨ Q) → (Q ∨ P) ∨-comm′ (∨-intro₁ p) = ∨-intro₂ p ∨-comm′ (∨-intro₂ q) = ∨-intro₁ q ∨-comm : {P Q : Set} → (P ∨ Q) ⇔ (Q ∨ P) ∨-comm = ∧-intro ∨-comm′ ∨-comm′
Create ttfp1.agda
Create ttfp1.agda notes while learning ttfp
Agda
bsd-3-clause
wangbj/excises,wangbj/excises,wangbj/excises
38dc0e74c8050099800069c05d5282fdff28dced
incremental.agda
incremental.agda
module incremental where -- SIMPLE TYPES -- Syntax data Type : Set where _⇒_ : (τ₁ τ₂ : Type) → Type infixr 5 _⇒_ -- Semantics Dom⟦_⟧ : Type -> Set Dom⟦ τ₁ ⇒ τ₂ ⟧ = Dom⟦ τ₁ ⟧ → Dom⟦ τ₂ ⟧ -- TYPING CONTEXTS -- Syntax data Context : Set where ∅ : Context _•_ : (τ : Type) (Γ : Context) → Context infixr 9 _•_ -- Semantics data Empty : Set where ∅ : Empty data Bind A B : Set where _•_ : (v : A) (ρ : B) → Bind A B Env⟦_⟧ : Context → Set Env⟦ ∅ ⟧ = Empty Env⟦ τ • Γ ⟧ = Bind Dom⟦ τ ⟧ Env⟦ Γ ⟧ -- VARIABLES -- Syntax data Var : Context → Type → Set where this : ∀ {Γ τ} → Var (τ • Γ) τ that : ∀ {Γ τ τ′} → (x : Var Γ τ) → Var (τ′ • Γ) τ -- Semantics lookup⟦_⟧ : ∀ {Γ τ} → Var Γ τ → Env⟦ Γ ⟧ → Dom⟦ τ ⟧ lookup⟦ this ⟧ (v • ρ) = v lookup⟦ that x ⟧ (v • ρ) = lookup⟦ x ⟧ ρ -- TERMS -- Syntax data Term : Context → Type → Set where abs : ∀ {Γ τ₁ τ₂} → (t : Term (τ₁ • Γ) τ₂) → Term Γ (τ₁ ⇒ τ₂) app : ∀ {Γ τ₁ τ₂} → (t₁ : Term Γ (τ₁ ⇒ τ₂)) (t₂ : Term Γ τ₁) → Term Γ τ₂ var : ∀ {Γ τ} → (x : Var Γ τ) → Term Γ τ -- Semantics eval⟦_⟧ : ∀ {Γ τ} → Term Γ τ → Env⟦ Γ ⟧ → Dom⟦ τ ⟧ eval⟦ abs t ⟧ ρ = λ v → eval⟦ t ⟧ (v • ρ) eval⟦ app t₁ t₂ ⟧ ρ = (eval⟦ t₁ ⟧ ρ) (eval⟦ t₂ ⟧ ρ) eval⟦ var x ⟧ ρ = lookup⟦ x ⟧ ρ -- WEAKENING -- Extend a context to a super context infixr 10 _⋎_ _⋎_ : (Γ₁ Γ₁ : Context) → Context ∅ ⋎ Γ₂ = Γ₂ (τ • Γ₁) ⋎ Γ₂ = τ • Γ₁ ⋎ Γ₂ -- Lift a variable to a super context lift : ∀ {Γ₁ Γ₂ Γ₃ τ} → Var (Γ₁ ⋎ Γ₃) τ → Var (Γ₁ ⋎ Γ₂ ⋎ Γ₃) τ lift {∅} {∅} x = x lift {∅} {τ • Γ₂} x = that (lift {∅} {Γ₂} x) lift {τ • Γ₁} {Γ₂} this = this lift {τ • Γ₁} {Γ₂} (that x) = that (lift {Γ₁} {Γ₂} x) -- Weaken a term to a super context weaken : ∀ {Γ₁ Γ₂ Γ₃ τ} → Term (Γ₁ ⋎ Γ₃) τ → Term (Γ₁ ⋎ Γ₂ ⋎ Γ₃) τ weaken {Γ₁} {Γ₂} (abs {τ₁ = τ} t) = abs (weaken {τ • Γ₁} {Γ₂} t) weaken {Γ₁} {Γ₂} (app t₁ t₂) = app (weaken {Γ₁} {Γ₂} t₁) (weaken {Γ₁} {Γ₂} t₂) weaken {Γ₁} {Γ₂} (var x) = var (lift {Γ₁} {Γ₂} x) -- CHANGE TYPES Δ-Type : Type → Type Δ-Type (τ₁ ⇒ τ₂) = τ₁ ⇒ Δ-Type τ₂ apply : ∀ {τ Γ} → Term Γ (Δ-Type τ ⇒ τ ⇒ τ) apply {τ₁ ⇒ τ₂} = abs (abs (abs (app (app apply (app (var (that (that this))) (var this))) (app (var (that this)) (var this))))) -- λdf. λf. λx. apply ( df x ) ( f x ) compose : ∀ {τ Γ} → Term Γ (Δ-Type τ ⇒ Δ-Type τ ⇒ Δ-Type τ) compose {τ₁ ⇒ τ₂} = abs (abs (abs (app (app compose (app (var (that (that this))) (var this))) (app (var (that this)) (var this))))) -- λdf. λdg. λx. compose ( df x ) ( dg x ) -- Hey, apply is α-equivalent to compose, what's going on? -- Oh, and `Δ-Type` is the identity function? -- CHANGE CONTEXTS Δ-Context : Context → Context Δ-Context ∅ = ∅ Δ-Context (τ • Γ) = τ • Δ-Type τ • Γ -- CHANGING TERMS WHEN THE ENVIRONMENT CHANGES Δ-term : ∀ {Γ₁ Γ₂ τ} → Term (Γ₁ ⋎ Γ₂) τ → Term (Γ₁ ⋎ Δ-Context Γ₂) (Δ-Type τ) Δ-term {Γ} (abs {τ₁ = τ} t) = abs (Δ-term {τ • Γ} t) Δ-term {Γ} (app t₁ t₂) = {!!} Δ-term {Γ} (var x) = {!!}
Implement STLC in AGDA (fix #13).
Implement STLC in AGDA (fix #13). Old-commit-hash: 8c8d0d1e3a7f67f1a6640d7526542321b3a5a424
Agda
mit
inc-lc/ilc-agda
2824f8185e103bd7e2500937eff9fb9af1077e07
lib/Data/Nat/GCD/NP.agda
lib/Data/Nat/GCD/NP.agda
module Data.Nat.GCD.NP where open import Data.Nat open import Data.Nat.Properties open import Data.Nat.Divisibility as Div open import Relation.Binary private module P = Poset Div.poset open import Data.Product open import Relation.Binary.PropositionalEquality as PropEq using (_≡_) open import Induction open import Induction.Nat open import Induction.Lexicographic open import Function open import Data.Nat.GCD.Lemmas ------------------------------------------------------------------------ -- Greatest common divisor module GCD where -- Specification of the greatest common divisor (gcd) of two natural -- numbers. record GCD (m n gcd : ℕ) : Set where constructor is field -- The gcd is a common divisor. commonDivisor : gcd ∣ m × gcd ∣ n -- All common divisors divide the gcd, i.e. the gcd is the -- greatest common divisor according to the partial order _∣_. greatest : ∀ {d} → d ∣ m × d ∣ n → d ∣ gcd open GCD public -- The gcd is unique. unique : ∀ {d₁ d₂ m n} → GCD m n d₁ → GCD m n d₂ → d₁ ≡ d₂ unique d₁ d₂ = P.antisym (GCD.greatest d₂ (GCD.commonDivisor d₁)) (GCD.greatest d₁ (GCD.commonDivisor d₂)) -- The gcd relation is "symmetric". sym : ∀ {d m n} → GCD m n d → GCD n m d sym g = is (swap $ GCD.commonDivisor g) (GCD.greatest g ∘ swap) -- The gcd relation is "reflexive". refl : ∀ {n} → GCD n n n refl = is (P.refl , P.refl) proj₁ -- The GCD of 0 and n is n. base : ∀ {n} → GCD 0 n n base {n} = is (n ∣0 , P.refl) proj₂ -- If d is the gcd of n and k, then it is also the gcd of n and -- n + k. step : ∀ {n k d} → GCD n k d → GCD n (n + k) d step g with GCD.commonDivisor g step {n} {k} {d} g | (d₁ , d₂) = is (d₁ , ∣-+ d₁ d₂) greatest′ where greatest′ : ∀ {d′} → d′ ∣ n × d′ ∣ n + k → d′ ∣ d greatest′ (d₁ , d₂) = GCD.greatest g (d₁ , ∣-∸ d₂ d₁) open GCD public using (GCD) ------------------------------------------------------------------------ -- Calculating the gcd -- The calculation also proves Bézout's lemma. module Bézout where module Identity where -- If m and n have greatest common divisor d, then one of the -- following two equations is satisfied, for some numbers x and y. -- The proof is "lemma" below (Bézout's lemma). -- -- (If this identity was stated using integers instead of natural -- numbers, then it would not be necessary to have two equations.) data Identity (d m n : ℕ) : Set where -- +- : (x y : ℕ) (eq : d + y * n ≡ x * m) → Identity d m n -+ : (x y : ℕ) (eq : d + x * m ≡ y * n) → Identity d m n -- Various properties about Identity. {- sym : ∀ {d} → Symmetric (Identity d) sym (+- x y eq) = -+ y x eq sym (-+ x y eq) = +- y x eq -} refl : ∀ {d} → Identity d d d refl = -+ 0 1 PropEq.refl base : ∀ {d} → Identity d 0 d base = -+ 0 1 PropEq.refl private infixl 7 _⊕_ _⊕_ : ℕ → ℕ → ℕ m ⊕ n = 1 + m + n step : ∀ {d n k} → Identity d n k → Identity d n (n + k) {- step {d} (+- x y eq) with compare x y step {d} (+- .x .x eq) | equal x = +- (2 * x) x (lem₂ d x eq) step {d} (+- .x .(x ⊕ i) eq) | less x i = +- (2 * x ⊕ i) (x ⊕ i) (lem₃ d x eq) step {d} {n} (+- .(y ⊕ i) .y eq) | greater y i = +- (2 * y ⊕ i) y (lem₄ d y n eq) -} step {d} (-+ x y eq) with compare x y step {d} (-+ .x .x eq) | equal x = -+ (2 * x) x (lem₅ d x eq) step {d} (-+ .x .(x ⊕ i) eq) | less x i = -+ (2 * x ⊕ i) (x ⊕ i) (lem₆ d x eq) step {d} {n} (-+ .(y ⊕ i) .y eq) | greater y i = -+ (2 * y ⊕ i) y (lem₇ d y n eq) open Identity public using (Identity) -- ; +-; -+) module Lemma where -- This type packs up the gcd, the proof that it is a gcd, and the -- proof that it satisfies Bézout's identity. data Lemma (m n : ℕ) : Set where result : (d : ℕ) (g : GCD m n d) (b : Identity d m n) → Lemma m n -- Various properties about Lemma. {- sym : Symmetric Lemma sym (result d g b) = result d (GCD.sym g) (Identity.sym b) -} base : ∀ d → Lemma 0 d base d = result d GCD.base Identity.base refl : ∀ d → Lemma d d refl d = result d GCD.refl Identity.refl stepˡ : ∀ {n k} → Lemma n (suc k) → Lemma n (suc (n + k)) stepˡ {n} {k} (result d g b) = PropEq.subst (Lemma n) (lem₀ n k) $ result d (GCD.step g) (Identity.step b) {- stepʳ : ∀ {n k} → Lemma (suc k) n → Lemma (suc (n + k)) n stepʳ = sym ∘ stepˡ ∘ sym -} open Lemma public using (Lemma; result) -- Bézout's lemma proved using some variant of the extended -- Euclidean algorithm. lemma : (m n : ℕ) → Lemma m n lemma zero n = Lemma.base n lemma m zero = {!Lemma.sym (Lemma.base m)!} lemma (suc m) (suc n) = build [ <-rec-builder ⊗ <-rec-builder ] P gcd (m , n) where P : ℕ × ℕ → Set P (m , n) = Lemma (suc m) (suc n) gcd : ∀ p → (<-Rec ⊗ <-Rec) P p → P p gcd (m , n ) rec with compare m n gcd (m , .m ) rec | equal .m = Lemma.refl (suc m) gcd (m , .(suc m + k)) rec | less .m k = -- "gcd m k" -- k < n -- m < n -- n = suc m + k -- dist m n = suc k -- m + k < m + suc m + k -- k < suc m + k -- 0 < suc m Lemma.stepˡ $ proj₁ rec k (≤⇒≤′ (s≤s (≤-steps {k} {k} m (≤′⇒≤ ≤′-refl)))) gcd (.(suc n + k) , n) rec | greater .n k = -- "gcd k n" -- m > n -- m ≡ suc n + k -- dist m n = suc k -- k + n < suc n + k + n -- k < suc n + k -- 0 < suc n -- gcd n k {!Lemma.stepʳ $ proj₂ rec k (≤⇒≤′ (s≤s (≤-steps {k} {k} n (≤′⇒≤ ≤′-refl)))) n!} -- Bézout's identity can be recovered from the GCD. identity : ∀ {m n d} → GCD m n d → Identity d m n identity {m} {n} g with lemma m n identity g | result d g′ b with GCD.unique g g′ identity g | result d g′ b | PropEq.refl = b -- Calculates the gcd of the arguments. gcd : (m n : ℕ) → ∃ λ d → GCD m n d gcd m n with Bézout.lemma m n gcd m n | Bézout.result d g _ = (d , g) -- -} -- -} -- -} -- -} -- -}
Add a broken attempt at simplifying Nat.GCD: Nat.GCD.NP
Add a broken attempt at simplifying Nat.GCD: Nat.GCD.NP
Agda
bsd-3-clause
crypto-agda/agda-nplib
4995bc2a3bd988bcf90ed2efe5b614e17b5554a0
Game/IND-CPA-alt.agda
Game/IND-CPA-alt.agda
{-# OPTIONS --without-K #-} open import Type open import Data.Product open import Data.Bit module Game.IND-CPA-alt (PubKey : ★) (SecKey : ★) (Message : ★) (CipherText : ★) -- randomness supply for: encryption, key-generation, adversary, extensions (Rₑ Rₖ Rₐ : ★) (KeyGen : Rₖ → PubKey × SecKey) (Enc : PubKey → Message → Rₑ → CipherText) where M² = Bit → Message -- IND-CPA adversary in two parts Adv : ★ Adv = Rₐ → PubKey → (M² × (CipherText → Bit)) -- IND-CPA randomness supply R : ★ R = (Rₐ × Rₖ × Rₑ) -- IND-CPA games: -- * input: adversary and randomness supply -- * output b: adversary claims we are in game ⅁ b Game : ★ Game = Adv → R → Bit -- The game step by step: -- (pk) key-generation, only the public-key is needed -- (mb) send randomness, public-key and bit -- receive which message to encrypt -- (c) encrypt the message -- (b′) send randomness, public-key and ciphertext -- receive the guess from the adversary ⅁ : Bit → Game ⅁ b m (rₐ , rₖ , rₑ) = b′ where pk = proj₁ (KeyGen rₖ) ad = m rₐ pk mb = proj₁ ad b c = Enc pk mb rₑ b′ = proj₂ ad c ⅁₀ ⅁₁ : Game ⅁₀ = ⅁ 0b ⅁₁ = ⅁ 1b
Add alternative defintion for IND CPA
Add alternative defintion for IND CPA
Agda
bsd-3-clause
crypto-agda/crypto-agda
f9510280666609fdd9b8b35645bab6c0e17092c4
lib/FFI/JS.agda
lib/FFI/JS.agda
module FFI.JS where open import Data.Char.Base public using (Char) open import Data.String.Base public using (String) open import Data.Bool.Base public using (Bool; true; false) open import Data.List.Base using (List) open import Data.Product using (_×_) renaming (proj₁ to fst; proj₂ to snd) open import Control.Process.Type {-# COMPILED_JS Bool function (x,v) { return ((x)? v["true"]() : v["false"]()); } #-} {-# COMPILED_JS true true #-} {-# COMPILED_JS false false #-} data JSType : Set where array object number string bool null : JSType infixr 5 _++_ postulate Number : Set readNumber : String → Number zero : Number one : Number _+_ : Number → Number → Number _++_ : String → String → String reverse : String → String sort : String → String take-half : String → String drop-half : String → String String▹List : String → List Char List▹String : List Char → String Number▹String : Number → String JSValue : Set _+JS_ : JSValue → JSValue → JSValue _≤JS_ : JSValue → JSValue → Bool _===_ : JSValue → JSValue → Bool JSON-stringify : JSValue → String JSON-parse : String → JSValue toString : JSValue → String fromString : String → JSValue fromChar : Char → JSValue fromNumber : Number → JSValue objectFromList : {A : Set} → List A → (A → String) → (A → JSValue) → JSValue fromJSArray : {A : Set} → JSValue → (Number → JSValue → A) → List A fromJSArrayString : JSValue → List String castNumber : JSValue → Number castString : JSValue → String nullJS : JSValue trueJS : JSValue falseJS : JSValue readJSType : String → JSType showJSType : JSType → String typeof : JSValue → JSType _·[_] : JSValue → JSValue → JSValue onString : {A : Set} (f : String → A) → JSValue → A trace : {A B : Set} → String → A → (A → B) → B {-# COMPILED_JS zero 0 #-} {-# COMPILED_JS one 1 #-} {-# COMPILED_JS readNumber Number #-} {-# COMPILED_JS _+_ function(x) { return function(y) { return x + y; }; } #-} {-# COMPILED_JS _++_ function(x) { return function(y) { return x + y; }; } #-} {-# COMPILED_JS _+JS_ function(x) { return function(y) { return x + y; }; } #-} {-# COMPILED_JS reverse function(x) { return x.split("").reverse().join(""); } #-} {-# COMPILED_JS sort function(x) { return x.split("").sort().join(""); } #-} {-# COMPILED_JS take-half function(x) { return x.substring(0,x.length/2); } #-} {-# COMPILED_JS drop-half function(x) { return x.substring(x.length/2); } #-} {-# COMPILED_JS List▹String function(x) { return (require("libagda").fromList(x, function(y) { return y; })).join(""); } #-} {-# COMPILED_JS String▹List function(x) { return require("libagda").fromJSArrayString(x.split("")); } #-} {-# COMPILED_JS fromJSArray function (ty) { return require("libagda").fromJSArray; } #-} {-# COMPILED_JS fromJSArrayString require("libagda").fromJSArrayString #-} {-# COMPILED_JS _≤JS_ function(x) { return function(y) { return x <= y; }; } #-} {-# COMPILED_JS _===_ function(x) { return function(y) { return x === y; }; } #-} {-# COMPILED_JS JSON-stringify JSON.stringify #-} {-# COMPILED_JS JSON-parse JSON.parse #-} {-# COMPILED_JS toString function(x) { return x.toString(); } #-} {-# COMPILED_JS fromString function(x) { return x; } #-} {-# COMPILED_JS fromChar function(x) { return x; } #-} {-# COMPILED_JS fromNumber function(x) { return x; } #-} {-# COMPILED_JS Number▹String String #-} {-# COMPILED_JS castNumber Number #-} {-# COMPILED_JS castString String #-} {-# COMPILED_JS nullJS null #-} {-# COMPILED_JS trueJS true #-} {-# COMPILED_JS falseJS false #-} {-# COMPILED_JS typeof function(x) { return typeof(x); } #-} {-# COMPILED_JS _·[_] require("libagda").readProp #-} {-# COMPILED_JS onString function(t) { return require("libagda").onString; } #-} {-# COMPILED_JS trace require("libagda").trace #-} data Value : Set₀ where array : List Value → Value object : List (String × Value) → Value string : String → Value number : Number → Value bool : Bool → Value null : Value postulate fromValue : Value → JSValue {-# COMPILED_JS fromValue require("libagda").fromValue #-} data ValueView : Set₀ where array : List JSValue → ValueView object : List (String × JSValue) → ValueView string : String → ValueView number : Number → ValueView bool : Bool → ValueView null : ValueView {- postulate fromJSValue : JSValue → ValueView -} fromBool : Bool → JSValue fromBool true = trueJS fromBool false = falseJS Object = List (String × JSValue) fromObject : Object → JSValue fromObject o = objectFromList o fst snd _≤Char_ : Char → Char → Bool x ≤Char y = fromChar x ≤JS fromChar y _≤String_ : String → String → Bool x ≤String y = fromString x ≤JS fromString y _≤Number_ : Number → Number → Bool x ≤Number y = fromNumber x ≤JS fromNumber y _·«_» : JSValue → String → JSValue v ·« s » = v ·[ fromString s ] abstract URI = String showURI : URI → String showURI x = x readURI : String → URI readURI x = x JSProc = Proc URI JSValue data JSCmd : Set where server : (ip port : String) (proc : URI → JSProc) (callback : URI → JSCmd) → JSCmd client : JSProc → JSCmd → JSCmd end : JSCmd assert : Bool → JSCmd → JSCmd console_log : String → JSCmd → JSCmd process_argv : (List String → JSCmd) → JSCmd
Add FFI.JS
Add FFI.JS
Agda
bsd-3-clause
audreyt/agda-libjs,crypto-agda/agda-libjs
9236c772d09686e999993e80d77ce8bd225d16f5
lib/FFI/JS/SHA1.agda
lib/FFI/JS/SHA1.agda
module FFI.JS.SHA1 where open import Data.String.Base using (String) postulate SHA1 : String → String {-# COMPILED_JS SHA1 function (x) { return require("sha1")(x); } #-}
Add FFI.JS.SHA1
Add FFI.JS.SHA1
Agda
bsd-3-clause
audreyt/agda-libjs,crypto-agda/agda-libjs
d5f6beafc85ff125a91c2f035d2d29dd6409f54e
ZK/GroupHom/ElGamal/JS.agda
ZK/GroupHom/ElGamal/JS.agda
{-# OPTIONS --without-K #-} open import FFI.JS.BigI open import Data.Bool.Base using (Bool) open import SynGrp open import ZK.GroupHom.Types import ZK.GroupHom.ElGamal import ZK.GroupHom.JS module ZK.GroupHom.ElGamal.JS (p q : BigI)(g : ℤ[ p ]★) where module EG = ZK.GroupHom.ElGamal `ℤ[ q ]+ `ℤ[ p ]★ _`^_ g module known-enc-rnd (pk : EG.PubKey) (M : EG.Message) (ct : EG.CipherText) where module ker = EG.Known-enc-rnd pk M ct module zkh = `ZK-hom ker.zk-hom module zkp = ZK.GroupHom.JS q zkh.`φ zkh.y prover-commitment : (r : zkp.Randomness)(w : zkp.Witness) → zkp.Commitment prover-commitment r w = zkp.Prover-Interaction.get-A (zkp.prover r w) prover-response : (r : zkp.Randomness)(w : zkp.Witness)(c : zkp.Challenge) → zkp.Response prover-response r w c = zkp.Prover-Interaction.get-f (zkp.prover r w) c verify-transcript : (A : zkp.Commitment)(c : zkp.Challenge)(r : zkp.Response) → Bool verify-transcript A c r = zkp.verifier (zkp.Transcript.mk A c r) -- -} -- -} -- -} -- -}
Add ZK.GroupHom.ElGamal.JS, so far only known-enc-rnd
Add ZK.GroupHom.ElGamal.JS, so far only known-enc-rnd
Agda
bsd-3-clause
crypto-agda/crypto-agda
1ffd391240cdf755b930cf4216a8231b81aee07d
FunUniverse/Fin/Op/Abstract.agda
FunUniverse/Fin/Op/Abstract.agda
open import Type open import Function open import Data.Product using (proj₂) open import Data.Two renaming (mux to mux₂) open import Data.Nat.NP using (ℕ; zero; suc; _+_; _*_; module ℕ°) open import Data.Fin.NP as Fin using (Fin; inject+; raise; bound; free; zero; suc) open import Data.Vec.NP using (Vec; []; _∷_; lookup; tabulate) open import Data.Vec.Properties using (lookup∘tabulate) open import Data.Bits using (Bits; _→ᵇ_; RewireTbl{-; 0ⁿ; 1ⁿ-}) open import Relation.Binary.PropositionalEquality open import FunUniverse.Data open import FunUniverse.Core open import FunUniverse.Fin.Op open import FunUniverse.Rewiring.Linear open import FunUniverse.Category open import Language.Simple.Interface module FunUniverse.Fin.Op.Abstract where private module BF = Rewiring finOpRewiring module _ {E : ★ → ★} {Op} (lang : Lang Op 𝟚 E) where open Lang lang {- bits : ∀ {o} → Bits o → 0 →ᵉ o bits xs = 𝟚▹E ∘ flip Vec.lookup xs -} efinFunU : FunUniverse ℕ efinFunU = Bits-U , _→ᵉ_ module EFinFunUniverse = FunUniverse efinFunU efinCat : Category _→ᵉ_ efinCat = input , _∘ᵉ_ private open EFinFunUniverse module _ {A B C D} (f : A `→ C) (g : B `→ D) where <_×_> : (A `× B) `→ (C `× D) <_×_> x with Fin.cmp C D x <_×_> ._ | Fin.bound y = inject+ B <$> f y <_×_> ._ | Fin.free y = raise A <$> g y efinLin : LinRewiring efinFunU efinLin = mk efinCat (flip <_×_> input) (λ {A} → input ∘ BF.swap {A}) (λ {A} → input ∘ BF.assoc {A}) input input <_×_> (λ {A} → <_×_> {A} input) input input input input efinRewiring : Rewiring efinFunU efinRewiring = mk efinLin (λ()) (input ∘ BF.dup) (λ()) (λ f g → < f × g > ∘ᵉ (input ∘ BF.dup)) (input ∘ inject+ _) (λ {A} → input ∘ raise A) (λ f → input ∘ BF.rewire f) (λ f → input ∘ BF.rewireTbl f) {- efinFork : HasFork efinFunU efinFork = cond , λ f g → second {1} < f , g > ⁏ cond where open Rewiring efinRewiring cond : ∀ {A} → `Bit `× A `× A `→ A cond {A} x = {!mux (return zero) (input (raise 1 (inject+ _ x))) (input (raise 1 (raise A x)))!} 𝟚▹E = {!!} efinOps : FunOps efinFunU efinOps = mk efinRewiring efinFork (const (𝟚▹E 0₂)) (const (𝟚▹E 1₂)) open Cong-*1 _→ᵉ_ reify : ∀ {i o} → i →ᵇ o → i →ᵉ o reify = cong-*1′ ∘ FunOps.fromBitsFun efinOps -} {- eval-reify : eval (reify f) eval-reify = ? -} -- -}
Add FunUniverse/Fin/Op/Abstract.agda
Add FunUniverse/Fin/Op/Abstract.agda
Agda
bsd-3-clause
crypto-agda/crypto-agda
3887acc776498fc936c85a42b1ba8ed98dfe1593
Everything.agda
Everything.agda
module Everything where import Holes.Prelude import Holes.Term import Holes.Cong.Limited import Holes.Cong.General import Holes.Cong.Propositional
Add Everything file
Add Everything file
Agda
mit
bch29/agda-holes
22eab6635a40915cfce9e29a45fe31de8280bcbf
PLDI14-List-of-Theorems.agda
PLDI14-List-of-Theorems.agda
module PLDI14-List-of-Theorems where open import Function -- List of theorems in PLDI submission -- -- For hints about installation and execution, please refer -- to README.agda. -- -- Agda modules corresponding to definitions, lemmas and theorems -- are listed here with the most important name. For example, -- after this file type checks (C-C C-L), placing the cursor -- on the purple "Base.Change.Algebra" and pressing M-. will -- bring you to the file where change structures are defined. -- The name for change structures in that file is -- "ChangeAlgebra", given in the using-clause. -- Definition 2.1 (Change structures) -- (d) ChangeAlgebra.diff -- (e) IsChangeAlgebra.update-diff open import Base.Change.Algebra using (ChangeAlgebra) ---- Carrier in record ChangeAlgebra --(a) open Base.Change.Algebra.ChangeAlgebra using (Change) --(b) open Base.Change.Algebra.ChangeAlgebra using (update) --(c) open Base.Change.Algebra.ChangeAlgebra using (diff) --(d) open Base.Change.Algebra.IsChangeAlgebra using (update-diff)--(e) -- Definition 2.2 (Nil change) -- IsChangeAlgebra.nil open Base.Change.Algebra using (IsChangeAlgebra) -- Lemma 2.3 (Behavior of nil) -- IsChangeAlgebra.update-nil open Base.Change.Algebra using (IsChangeAlgebra) -- Definition 2.4 (Derivatives) open Base.Change.Algebra using (Derivative) -- Definition 2.5 (Carrier set of function changes) open Base.Change.Algebra.FunctionChanges -- Definition 2.6 (Operations on function changes) -- ChangeAlgebra.update FunctionChanges.changeAlgebra -- ChangeAlgebra.diff FunctionChanges.changeAlgebra open Base.Change.Algebra.FunctionChanges using (changeAlgebra) -- Theorem 2.7 (Function changes form a change structure) -- (In Agda, the proof of Theorem 2.7 has to be included in the -- definition of function changes, here -- FunctionChanges.changeAlgebra.) open Base.Change.Algebra.FunctionChanges using (changeAlgebra) -- Lemma 2.8 (Incrementalization) open Base.Change.Algebra.FunctionChanges using (incrementalization) -- Theorem 2.9 (Nil changes are derivatives) open Base.Change.Algebra.FunctionChanges using (nil-is-derivative) -- For each plugin requirement, we include its definition and -- a concrete instantiation called "Popl14" with integers and -- bags of integers as base types. -- Plugin Requirement 3.1 (Domains of base types) open import Parametric.Denotation.Value using (Structure) open import Popl14.Denotation.Value using (⟦_⟧Base) -- Definition 3.2 (Domains) open Parametric.Denotation.Value.Structure using (⟦_⟧Type) -- Plugin Requirement 3.3 (Evaluation of constants) open import Parametric.Denotation.Evaluation using (Structure) open import Popl14.Denotation.Evaluation using (⟦_⟧Const) -- Definition 3.4 (Environments) open import Base.Denotation.Environment using (⟦_⟧Context) -- Definition 3.5 (Evaluation) open Parametric.Denotation.Evaluation.Structure using (⟦_⟧Term) -- Plugin Requirement 3.6 (Changes on base types) open import Parametric.Change.Validity using (Structure) open import Popl14.Change.Validity using (change-algebra-base-family) -- Definition 3.7 (Changes) open Parametric.Change.Validity.Structure using (change-algebra) -- Definition 3.8 (Change environments) open Parametric.Change.Validity.Structure using (environment-changes) -- Plugin Requirement 3.9 (Change semantics for constants) open import Parametric.Change.Specification using (Structure) open import Popl14.Change.Specification using (specification-structure) -- Definition 3.10 (Change semantics) open Parametric.Change.Specification.Structure using (⟦_⟧Δ) -- Lemma 3.11 (Change semantics is the derivative of semantics) open Parametric.Change.Specification.Structure using (correctness) -- Definition 3.12 (Erasure) import Parametric.Change.Implementation open Parametric.Change.Implementation.Structure using (_≈_) open import Popl14.Change.Implementation using (implements-base) -- Lemma 3.13 (The erased version of a change is almost the same) open Parametric.Change.Implementation.Structure using (carry-over) -- Lemma 3.14 (⟦ t ⟧Δ erases to Derive(t)) import Parametric.Change.Correctness open Parametric.Change.Correctness.Structure using (main-theorem)
add list of theorems
add list of theorems Old-commit-hash: ae20c5bded5fecd55d9723e7870ba03979cd0880
Agda
mit
inc-lc/ilc-agda
dd18fcc5ba9cbb6d8cbf62d171887cf3a22893f5
Base/Change/Products.agda
Base/Change/Products.agda
module Base.Change.Products where open import Relation.Binary.PropositionalEquality open import Level open import Base.Change.Algebra open import Data.Product -- Also try defining sectioned change structures on the positives halves of -- groups? Or on arbitrary subsets? -- Restriction: we pair sets on the same level (because right now everything -- else would risk getting in the way). module ProductChanges ℓ (A B : Set ℓ) {{CA : ChangeAlgebra ℓ A}} {{CB : ChangeAlgebra ℓ B}} where open ≡-Reasoning -- The simplest possible definition of changes for products. -- The following is probably bullshit: -- Does not handle products of functions - more accurately, writing the -- derivative of fst and snd for products of functions is hard: fst' p dp must return the change of fst p PChange : A × B → Set ℓ PChange (a , b) = Δ a × Δ b _⊕_ : (v : A × B) → PChange v → A × B _⊕_ (a , b) (da , db) = a ⊞ da , b ⊞ db _⊝_ : A × B → (v : A × B) → PChange v _⊝_ (aNew , bNew) (a , b) = aNew ⊟ a , bNew ⊟ b p-update-diff : (u v : A × B) → v ⊕ (u ⊝ v) ≡ u p-update-diff (ua , ub) (va , vb) = let u = (ua , ub) v = (va , vb) in begin v ⊕ (u ⊝ v) ≡⟨⟩ (va ⊞ (ua ⊟ va) , vb ⊞ (ub ⊟ vb)) --v ⊕ ((ua ⊟ va , ub ⊟ vb)) ≡⟨ cong₂ _,_ (update-diff ua va) (update-diff ub vb)⟩ (ua , ub) ≡⟨⟩ u ∎ changeAlgebra : ChangeAlgebra ℓ (A × B) changeAlgebra = record { Change = PChange ; update = _⊕_ ; diff = _⊝_ ; isChangeAlgebra = record { update-diff = p-update-diff } } proj₁′ : (v : A × B) → Δ v → Δ (proj₁ v) proj₁′ (a , b) (da , db) = da proj₁′Derivative : Derivative proj₁ proj₁′ -- Implementation note: we do not need to pattern match on v and dv because -- they are records, hence Agda knows that pattern matching on records cannot -- fail. Technically, the required feature is the eta-rule on records. proj₁′Derivative v dv = refl -- An extended explanation. proj₁′Derivative₁ : Derivative proj₁ proj₁′ proj₁′Derivative₁ (a , b) (da , db) = let v = (a , b) dv = (da , db) in begin proj₁ v ⊞ proj₁′ v dv ≡⟨⟩ a ⊞ da ≡⟨⟩ proj₁ (v ⊞ dv) ∎ -- Same for the second extractor. proj₂′ : (v : A × B) → Δ v → Δ (proj₂ v) proj₂′ (a , b) (da , db) = db proj₂′Derivative : Derivative proj₂ proj₂′ proj₂′Derivative v dv = refl -- We should do the same for uncurry instead. -- What one could wrongly expect to be the derivative of the constructor: _,_′ : (a : A) → (da : Δ a) → (b : B) → (db : Δ b) → Δ (a , b) _,_′ a da b db = da , db -- That has the correct behavior, in a sense, and it would be in the -- subset-based formalization in the paper. -- -- But the above is not even a change, because it does not contain a proof of its own validity, and because after application it does not contain a proof -- As a consequence, proving that's a derivative seems too insanely hard. We -- might want to provide a proof schema for curried functions at once, -- starting from the right correctness equation. B→A×B = FunctionChanges.changeAlgebra {c = ℓ} {d = ℓ} B (A × B) A→B→A×B = FunctionChanges.changeAlgebra {c = ℓ} {d = ℓ} A (B → A × B) {{CA}} {{B→A×B}} module ΔBA×B = FunctionChanges B (A × B) {{CB}} {{changeAlgebra}} module ΔA→B→A×B = FunctionChanges A (B → A × B) {{CA}} {{B→A×B}} _,_′-real : Δ _,_ _,_′-real = nil _,_ module FCΔA→B→A×B = ΔA→B→A×B.FunctionChange _,_′-real-Derivative : Derivative {{CA}} {{B→A×B}} _,_ (FCΔA→B→A×B.apply _,_′-real) _,_′-real-Derivative = FunctionChanges.nil-is-derivative A (B → A × B) {{CA}} {{B→A×B}} _,_ {- _,_′′ : (a : A) → Δ a → Δ {{B→A×B}} (λ b → (a , b)) _,_′′ a da = record { apply = _,_′ a da ; correct = λ b db → begin (a , b ⊞ db) ⊞ (_,_′ a da) (b ⊞ db) (nil (b ⊞ db)) ≡⟨⟩ a ⊞ da , b ⊞ db ⊞ (nil (b ⊞ db)) ≡⟨ cong (λ □ → a ⊞ da , □) (update-nil (b ⊞ db)) ⟩ a ⊞ da , b ⊞ db ≡⟨⟩ (a , b) ⊞ (_,_′ a da) b db ∎ } _,_′′′ : Δ {{A→B→A×B}} _,_ _,_′′′ = record { apply = _,_′′ ; correct = λ a da → begin update (_,_ (a ⊞ da)) (_,_′′ (a ⊞ da) (nil (a ⊞ da))) ≡⟨ {!!} ⟩ update (_,_ a) (_,_′′ a da) --ChangeAlgebra.update B→A×B (_,_ a) (a , da ′′) ∎ } where open ChangeAlgebra B→A×B hiding (nil) {- {! begin (_,_ (a ⊞ da)) ⊞ _,_′′ (a ⊞ da) (nil (a ⊞ da)) {- ≡⟨⟩ a ⊞ da , b ⊞ db ⊞ (nil (b ⊞ db)) -} ≡⟨ ? ⟩ {-a ⊞ da , b ⊞ db ≡⟨⟩-} (_,_ a) ⊞ (_,_′′ a da) ∎!} } -} open import Postulate.Extensionality _,_′Derivative : Derivative {{CA}} {{B→A×B}} _,_ _,_′′ _,_′Derivative a da = begin _⊞_ {{B→A×B}} (_,_ a) (_,_′′ a da) ≡⟨⟩ (λ b → (a , b) ⊞ ΔBA×B.FunctionChange.apply (_,_′′ a da) b (nil b)) --ext (λ b → cong (λ □ → (a , b) ⊞ □) (update-nil {{?}} b)) ≡⟨ {!!} ⟩ (λ b → (a , b) ⊞ ΔBA×B.FunctionChange.apply (_,_′′ a da) b (nil b)) ≡⟨ sym {!ΔA→B→A×B.incrementalization _,_ _,_′′′ a da!} ⟩ --FunctionChanges.incrementalization A (B → A × B) {{CA}} {{{!B→A×B!}}} _,_ {!!} {!!} {!!} _,_ (a ⊞ da) ∎ where --open FunctionChanges B (A × B) {{CB}} {{changeAlgebra}} module ΔBA×B = FunctionChanges B (A × B) {{CB}} {{changeAlgebra}} module ΔA→B→A×B = FunctionChanges A (B → A × B) {{CA}} {{B→A×B}} -}
Define a change structure for products
Define a change structure for products Derivatives of curried functions seem challenging. Accessing nested records too, but seems easy to fix. Old-commit-hash: d89e6171d447aae6292cc025dc6db95ce2370b88
Agda
mit
inc-lc/ilc-agda
16e3c79c254b8edd7f64b46df9c7c746fa4194c2
Language/Simple/Free.agda
Language/Simple/Free.agda
{-# OPTIONS --without-K --copatterns #-} open import Level.NP open import Function hiding (_$_) open import Type open import Algebra open import Algebra.FunctionProperties open import Algebra.Structures open import Data.Nat using (ℕ; zero; suc; _+_; _≤?_) open import Data.Fin using (Fin; zero; suc) open import Data.Vec using (Vec; []; _∷_; _++_) open import Data.One open import Data.Two open import Data.Product.NP open import Relation.Nullary.Decidable open import Relation.Binary.NP open import Relation.Binary.PropositionalEquality.NP as ≡ using (_≡_; !_; _≗_; module ≡-Reasoning) open import Category.Monad.NP import Language.Simple.Abstract module Language.Simple.Free where module _ {Op : ℕ → ★} where open Language.Simple.Abstract Op renaming (E to T) data Ctx (X : ★) : ★ where hole : Ctx X op : ∀ {a b} → Op (a + (1 + b)) → Vec (T X) a → Ctx X → Vec (T X) b → Ctx X module _ {X : ★} where η : ∀ {X} → X → T X η = var _·_ : Ctx X → T X → T X hole · e = e op o ts E us · e = op o (ts ++ E · e ∷ us) open WithEvalOp open Monad monad public renaming (liftM to map-T) module Unused {X R : ★} (⊢_≡_ : T X → T X → ★) (eval-Op : ∀ {n} → Op n → Vec R n → R) (eval-X : X → R) (t u : T X) (⊢t≡u : ⊢ t ≡ u) where ev = eval eval-Op eval-X ≈ = ev t ≡ ev u module ℛ {X : ★} (⊢_≡_ : T X → T X → ★) where {- data _≋*_ : ∀ {a} (ts us : Vec (T X) a) → ★ data _≋_ : (t u : T X) → ★ data _≋*_ where [] : [] ≋* [] _∷_ : ∀ {t u a} {ts us : Vec _ a} → t ≋ u → ts ≋* us → (t ∷ ts) ≋* (u ∷ us) data _≋_ where η : ∀ {t u} → ⊢ t ≡ u → t ≋ u !η : ∀ {t u} → ⊢ t ≡ u → u ≋ t var : ∀ x → var x ≋ var x op : ∀ {a} (o : Op a) {ts us} → ts ≋* us → op o ts ≋ op o us -} module Unused2 where data Succ (X : ★) : ★ where old : X → Succ X new : Succ X infix 9 _$_ _$_ : T (Succ X) → T X → T X E $ t = E >>= (λ { new → t ; (old x) → var x }) infix 0 _≈_ data _≈_ : (t u : T X) → ★ where refl : Reflexive _≈_ sym : Symmetric _≈_ trans : Transitive _≈_ η≡ : ∀ {t u} → ⊢ t ≡ u → t ≈ u congCtx : ∀ E {t u} → t ≈ u → E · t ≈ E · u ≈-isEquivalence : IsEquivalence _≈_ ≈-isEquivalence = record { refl = refl ; sym = sym ; trans = trans } module FreeSemigroup where U = Semigroup.Carrier record _→ₛ_ (X Y : Semigroup ₀ ₀) : ★ where open Semigroup X renaming (_∙_ to _∙x_) open Semigroup Y renaming (_∙_ to _∙y_) field to : U X → U Y to-∙-cong : ∀ t u → to (t ∙x u) ≡ to t ∙y to u open _→ₛ_ public idₛ : ∀ {S} → S →ₛ S to idₛ = id to-∙-cong idₛ _ _ = ≡.refl module _ {X Y Z} where _∘ₛ_ : (Y →ₛ Z) → (X →ₛ Y) → X →ₛ Z to (f ∘ₛ g) = to f ∘ to g to-∙-cong (f ∘ₛ g) t u = to (f ∘ₛ g) (t ∙x u) ≡⟨ ≡.cong (to f) (to-∙-cong g _ _) ⟩ to f (to g t ∙y to g u) ≡⟨ to-∙-cong f _ _ ⟩ to (f ∘ₛ g) t ∙z to (f ∘ₛ g) u ∎ where open ≡-Reasoning open Semigroup X renaming (_∙_ to _∙x_) open Semigroup Y renaming (_∙_ to _∙y_) open Semigroup Z renaming (_∙_ to _∙z_) data Op : ℕ → ★ where `μ : Op 2 open Language.Simple.Abstract Op renaming (E to T) open Monad monad module _ {X : ★} where _∙_ : T X → T X → T X t ∙ u = op `μ (t ∷ u ∷ []) module _ (X : ★) where infix 0 ⊢_≡_ data ⊢_≡_ : T X → T X → ★ where ⊢-∙-assoc : ∀ x y z → ⊢ ((x ∙ y) ∙ z) ≡ (x ∙ (y ∙ z)) open ℛ ⊢_≡_ ∙-assoc : Associative _≈_ _∙_ ∙-assoc x y z = η≡ (⊢-∙-assoc x y z) open Equivalence-Reasoning ≈-isEquivalence ∙-cong : _∙_ Preserves₂ _≈_ ⟶ _≈_ ⟶ _≈_ ∙-cong {x} {y} {u} {v} p q = x ∙ u ≈⟨ congCtx (op `μ (x ∷ []) hole []) q ⟩ x ∙ v ≈⟨ congCtx (op `μ [] hole (v ∷ [])) p ⟩ y ∙ v ∎ T-IsSemigroup : IsSemigroup _≈_ _∙_ T-IsSemigroup = record { isEquivalence = ≈-isEquivalence ; assoc = ∙-assoc ; ∙-cong = ∙-cong } T-Semigroup : Semigroup ₀ ₀ T-Semigroup = record { Carrier = T X ; _≈_ = _≈_ ; _∙_ = _∙_ ; isSemigroup = T-IsSemigroup } map-T-∙-hom : ∀ {X Y : ★} (f : X → Y) t u → map-T f (t ∙ u) ≡ map-T f t ∙ map-T f u map-T-∙-hom _ _ _ = ≡.refl Tₛ = T-Semigroup Tₛ-hom : ∀ {X Y} (f : X → Y) → Tₛ X →ₛ Tₛ Y to (Tₛ-hom f) = map-T f to-∙-cong (Tₛ-hom f) = map-T-∙-hom f module WithSemigroup (S : Semigroup ₀ ₀) where module S = Semigroup S open S renaming (Carrier to S₀; _∙_ to _∙ₛ_) eval-Op : ∀ {n} → Op n → Vec S₀ n → S₀ eval-Op `μ (x ∷ y ∷ []) = x ∙ₛ y eval-T : T S₀ → S₀ eval-T = WithEvalOp.eval eval-Op id eval-T-var : ∀ x → eval-T (var x) ≡ x eval-T-var x = ≡.refl eval-T-∙ : ∀ t u → eval-T (t ∙ u) ≡ eval-T t ∙ₛ eval-T u eval-T-∙ t u = ≡.refl eval-Tₛ : Tₛ S₀ →ₛ S to eval-Tₛ = eval-T to-∙-cong eval-Tₛ t u = ≡.refl {- Tₛ : Sets ⟶ Semigroups U : Semigroups ⟶ Sets Tₛ ⊣ U Semigroups(Tₛ X, Y) ≅ Sets(X, U Y) -} module _ {X : ★} {Y : Semigroup ₀ ₀} where open WithSemigroup Y open Semigroup Y renaming (Carrier to Y₀; _∙_ to _∙Y_) φ : (Tₛ X →ₛ Y) → X → U Y φ f = to f ∘ var -- var is the unit (η) ψ : (f : X → U Y) → Tₛ X →ₛ Y ψ f = eval-Tₛ ∘ₛ Tₛ-hom f -- eval-Tₛ is the co-unit (ε) φ-ψ : ∀ f → φ (ψ f) ≡ f φ-ψ f = ≡.refl ψ-φ : ∀ f t → to (ψ (φ f)) t ≡ to f t ψ-φ f (var x) = ≡.refl ψ-φ f (op `μ (t ∷ u ∷ [])) = to (ψ (φ f)) (t ∙ u) ≡⟨ ≡.refl ⟩ eval-T (map-T (φ f) (t ∙ u)) ≡⟨ ≡.refl ⟩ eval-T (map-T (φ f) t ∙ map-T (φ f) u) ≡⟨ ≡.refl ⟩ eval-T (map-T (φ f) t) ∙Y eval-T (map-T (φ f) u) ≡⟨ ≡.refl ⟩ to (ψ (φ f)) t ∙Y to (ψ (φ f)) u ≡⟨ ≡.cong₂ _∙Y_ (ψ-φ f t) (ψ-φ f u) ⟩ to f t ∙Y to f u ≡⟨ ! (to-∙-cong f t u) ⟩ to f (t ∙ u) ∎ where open ≡-Reasoning module FreeMonoid where data Op : ℕ → ★ where `ε : Op 0 `μ : Op 2 open Language.Simple.Abstract Op renaming (E to T) ε : ∀ {X} → T X ε = op `ε [] _∙_ : ∀ {X} → T X → T X → T X t ∙ u = op `μ (t ∷ u ∷ []) infix 0 _⊢_≡_ data _⊢_≡_ (X : ★) : T X → T X → ★ where ⊢-ε∙x : ∀ x → X ⊢ ε ∙ x ≡ x ⊢-x∙ε : ∀ x → X ⊢ x ∙ ε ≡ x ⊢-∙-assoc : ∀ x y z → X ⊢ ((x ∙ y) ∙ z) ≡ (x ∙ (y ∙ z)) module _ (X : ★) where open ℛ (_⊢_≡_ X) {- TODO, share the proofs with FreeSemigroup above -} ∙-assoc : Associative _≈_ _∙_ ∙-assoc x y z = η≡ (⊢-∙-assoc x y z) open Equivalence-Reasoning ≈-isEquivalence ∙-cong : _∙_ Preserves₂ _≈_ ⟶ _≈_ ⟶ _≈_ ∙-cong {x} {y} {u} {v} p q = x ∙ u ≈⟨ congCtx (op `μ (x ∷ []) hole []) q ⟩ x ∙ v ≈⟨ congCtx (op `μ [] hole (v ∷ [])) p ⟩ y ∙ v ∎ monoid : Monoid ₀ ₀ monoid = record { Carrier = T X ; _≈_ = _≈_ ; _∙_ = _∙_ ; ε = ε ; isMonoid = record { isSemigroup = record { isEquivalence = ≈-isEquivalence ; assoc = ∙-assoc ; ∙-cong = ∙-cong } ; identity = (λ x → η≡ (⊢-ε∙x x)) , (λ x → η≡ (⊢-x∙ε x)) } } {- Free monoid as a functor F : Sets → Mon map-[] : map f [] ≡ [] map-++ : map f xs ++ map f ys = map f (xs ++ ys) F X = (List X , [] , _++_) F (f : Sets(X , Y)) : Mon(F X , F Y) = (map f , map-[] , map-++) -} module FreeGroup where data Op : ℕ → ★ where `ε : Op 0 `i : Op 1 `μ : Op 2 open Language.Simple.Abstract Op renaming (E to T) ε : ∀ {X} → T X ε = op `ε [] infix 9 −_ −_ : ∀ {X} → T X → T X − t = op `i (t ∷ []) infixr 6 _∙_ _∙_ : ∀ {X} → T X → T X → T X t ∙ u = op `μ (t ∷ u ∷ []) infix 0 _⊢_≡_ data _⊢_≡_ (X : ★) : T X → T X → ★ where ε∙x : ∀ x → X ⊢ ε ∙ x ≡ x x∙ε : ∀ x → X ⊢ x ∙ ε ≡ x ∙-assoc : ∀ x y z → X ⊢ (x ∙ (y ∙ z)) ≡ ((x ∙ y) ∙ z) −∙-inv : ∀ x → X ⊢ − x ∙ x ≡ ε ∙−-inv : ∀ x → X ⊢ x ∙ − x ≡ ε -- − (− t) ≡ t -- − t ∙ − (− t) ≡ ε ≡ − t ∙ t -- -} -- -} -- -} -- -}
Add Language.Simple.Free
Add Language.Simple.Free
Agda
bsd-3-clause
crypto-agda/crypto-agda
a2284fe9263eadf1deb8ce96940c9f0cc72949bb
ModalLogic.agda
ModalLogic.agda
module ModalLogic where -- Implement Frank Pfenning's lambda calculus based on modal logic S4, as -- described in "A Modal Analysis of Staged Computation". open import Denotational.Notation data BaseType : Set where Base : BaseType Next : BaseType → BaseType data Type : Set where base : BaseType → Type _⇒_ : Type → Type → Type □_ : Type → Type -- Reuse contexts, variables and weakening from Tillmann's library. open import Syntactic.Contexts Type -- No semantics for these types. data Term : Context → Context → Type → Set where abs : ∀ {τ₁ τ₂ Γ Δ} → (t : Term (τ₁ • Γ) Δ τ₂) → Term Γ Δ (τ₁ ⇒ τ₂) app : ∀ {τ₁ τ₂ Γ Δ} → (t₁ : Term Γ Δ (τ₁ ⇒ τ₂)) (t₂ : Term Γ Δ τ₁) → Term Γ Δ τ₂ ovar : ∀ {Γ Δ τ} → (x : Var Γ τ) → Term Γ Δ τ mvar : ∀ {Γ Δ τ} → (u : Var Δ τ) → Term Γ Δ τ -- Note the builtin weakening box : ∀ {Γ Δ τ} → Term ∅ Δ τ → Term Γ Δ (□ τ) let-box_in-_ : ∀ {τ₁ τ₂ Γ Δ} → (e₁ : Term Γ Δ (□ τ₁)) → (e₂ : Term Γ (τ₁ • Δ) τ₂) → Term Γ Δ τ₂ -- Lemma 1 includes weakening. -- Most of the proof can be generated by C-c C-a, but syntax errors must then be fixed. weaken : ∀ {Γ₁ Γ₂ Δ₁ Δ₂ τ} → (Γ′ : Γ₁ ≼ Γ₂) → (Δ′ : Δ₁ ≼ Δ₂) → Term Γ₁ Δ₁ τ → Term Γ₂ Δ₂ τ weaken Γ′ Δ′ (abs {τ₁} t) = abs (weaken (keep τ₁ • Γ′) Δ′ t) weaken Γ′ Δ′ (app t t₁) = app (weaken Γ′ Δ′ t) (weaken Γ′ Δ′ t₁) weaken Γ′ Δ′ (ovar x) = ovar (lift Γ′ x) weaken Γ′ Δ′ (mvar u) = mvar (lift Δ′ u) weaken Γ′ Δ′ (box t) = box (weaken ∅ Δ′ t) weaken Γ′ Δ′ (let-box_in-_ {τ₁} t t₁) = let-box weaken Γ′ Δ′ t in- weaken Γ′ (keep τ₁ • Δ′) t₁
Implement modal logic
Implement modal logic This doesn't belong here, but it reuses @Toxaris modular library. Old-commit-hash: 2f12ca949c8cb58e2b65b773607282bafbccb5c9
Agda
mit
inc-lc/ilc-agda
006fd9c825ad2011f95bb01a40c7f000d4fd4f30
bugs/Future.agda
bugs/Future.agda
module Future where open import Denotational.Notation -- Uses too much memory. -- open import Data.Integer open import Data.Product open import Data.Sum open import Data.Unit postulate ⟦Int⟧ : Set postulate ⟦Bag⟧ : Set → Set --mutual -- First, define a language of types, their denotations, and then the whole algebra of changes in the semantic domain data Type : Set ⟦_⟧Type : Type → Set data Type where Int : Type --Bag : Type → Type _⇒_ {- _⊠_ _⊞_ -} : Type → Type → Type Δ : (τ : Type) → (old : ⟦ τ ⟧Type) → Type -- meaningOfType : Meaning Type -- meaningOfType = meaning ⟦_⟧Type -- Try out Δ old here Change : (τ : Type) → ⟦ τ ⟧Type → Set Change Int old₁ = {!!} -- Change (Bag τ₁) old₁ = ⟦ Bag τ₁ ⟧Type ⊎ (Σ[ old ∈ (⟦ τ₁ ⟧Type) ] (⟦Bag⟧ ⟦ Δ τ₁ old ⟧Type)) Change (τ₁ ⇒ τ₂) oldF = ⟦ Δ τ₂ (oldF ?) ⟧Type -- oldF ? -- oldF ? -- (oldInput : ⟦ τ₁ ⟧Type) → ⟦ Δ τ₁ oldInput ⟧Type → ⟦ Δ τ₂ (oldF oldInput) ⟧Type -- Change (τ₁ ⊠ τ₂) old₁ = {!⟦ τ₁ ⟧Type × ⟦ τ₂ ⟧Type!} -- Change (τ₁ ⊞ τ₂) old₁ = {!!} Change (Δ τ₁ old₁) old₂ = {!!} ⟦ Int ⟧Type = ⟦Int⟧ -- ⟦ Bag τ ⟧Type = ⟦Bag⟧ ⟦ τ ⟧Type ⟦ σ ⇒ τ ⟧Type = ⟦ σ ⟧Type → ⟦ τ ⟧Type -- ⟦ σ ⊠ τ ⟧Type = ⟦ σ ⟧Type × ⟦ τ ⟧Type -- ⟦ σ ⊞ τ ⟧Type = ⟦ σ ⟧Type ⊎ ⟦ τ ⟧Type ⟦ Δ τ old ⟧Type = {- ⊤ ⊎ ⟦ τ ⟧Type ⊎ -} Change τ old
add another bug example
Agda: add another bug example Old-commit-hash: 82f681165ed59ccc36685cbf9c376026811e127f
Agda
mit
inc-lc/ilc-agda
9bb44c3e31a11725d740b2f59d40ebbe7e0917a2
FiniteField/JS.agda
FiniteField/JS.agda
{-# OPTIONS --without-K #-} open import Function.NP open import FFI.JS using (Number; Bool; true; false; String; warn-check; check; trace-call; _++_) open import FFI.JS.BigI open import Data.List.Base hiding (sum; _++_) {- open import Algebra.Raw open import Algebra.Field -} module FiniteField.JS (q : BigI) where abstract ℤq : Set ℤq = BigI private mod-q : BigI → ℤq mod-q x = mod x q -- There is two ways to go from BigI to ℤq: check and mod-q -- Use check for untrusted input data and mod-q for internal -- computation. BigI▹ℤq : BigI → ℤq BigI▹ℤq = -- trace-call "BigI▹ℤq " λ x → mod-q (warn-check (x <I q) (λ _ → "Not below the modulus: " ++ toString q ++ " < " ++ toString x) (warn-check (x ≥I 0I) (λ _ → "Should be positive: " ++ toString x ++ " < 0") x)) check-non-zero : ℤq → BigI check-non-zero = -- trace-call "check-non-zero " λ x → check (x >I 0I) (λ _ → "Should be non zero") x repr : ℤq → BigI repr x = x 0# 1# : ℤq 0# = 0I 1# = 1I 1/_ : Op₁ ℤq 1/ x = modInv (check-non-zero x) q _^_ : Op₂ ℤq x ^ y = modPow (repr x) (repr y) q _+_ _−_ _*_ _/_ : Op₂ ℤq x + y = mod-q (add (repr x) (repr y)) x − y = mod-q (subtract (repr x) (repr y)) x * y = mod-q (multiply (repr x) (repr y)) x / y = x * 1/ y 0−_ : Op₁ ℤq 0− x = mod-q (negate (repr x)) _==_ : (x y : ℤq) → Bool x == y = equals (repr x) (repr y) sum prod : List ℤq → ℤq sum = foldr _+_ 0# prod = foldr _*_ 1# {- +-mon-ops : Monoid-Ops ℤq +-mon-ops = _+_ , 0# +-grp-ops : Group-Ops ℤq +-grp-ops = +-mon-ops , 0−_ *-mon-ops : Monoid-Ops ℤq *-mon-ops = _*_ , 1# *-grp-ops : Group-Ops ℤq *-grp-ops = *-mon-ops , 1/_ fld-ops : Field-Ops ℤq fld-ops = +-grp-ops , *-grp-ops postulate fld-struct : Field-Struct fld-ops fld : Field ℤq fld = fld-ops , fld-struct -- -} -- -} -- -} -- -} -- -}
Add FiniteField/JS
Add FiniteField/JS
Agda
bsd-3-clause
crypto-agda/crypto-agda
a48ff25823603032db6b1a26e4605512aefd0561
notes/FOT/FOTC/Data/Conat/ConatSL.agda
notes/FOT/FOTC/Data/Conat/ConatSL.agda
------------------------------------------------------------------------------ -- Definition of FOTC Conat using Agda's co-inductive combinators ------------------------------------------------------------------------------ {-# OPTIONS --allow-unsolved-metas #-} {-# OPTIONS --no-universe-polymorphism #-} {-# OPTIONS --without-K #-} module FOT.FOTC.Data.Conat.ConatSL where open import FOTC.Base open import Coinduction ------------------------------------------------------------------------------ data Conat : D → Set where cozero : Conat zero cosucc : ∀ {n} → (∞ (Conat n)) → Conat (succ₁ n) Conat-unf : ∀ {n} → Conat n → n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n') Conat-unf cozero = inj₁ refl Conat-unf (cosucc {n} Cn) = inj₂ (n , ♭ Cn , refl) Conat-pre-fixed : ∀ {n} → (n ≡ zero ∨ (∃[ n' ] Conat n' ∧ n ≡ succ₁ n')) → Conat n Conat-pre-fixed (inj₁ h) = subst Conat (sym h) cozero Conat-pre-fixed (inj₂ (n , Cn , h)) = subst Conat (sym h) (cosucc (♯ Cn)) Conat-coind : ∀ (A : D → Set) {n} → (A n → n ≡ zero ∨ (∃[ n' ] A n' ∧ n ≡ succ₁ n')) → A n → Conat n Conat-coind A h An = {!!}
Add incomplete note on co-inductive natural numbers.
Add incomplete note on co-inductive natural numbers.
Agda
mit
asr/fotc,asr/fotc
a5cd381752071ba8ed39615ef66d857a850a76f0
autogen.ash
autogen.ash
#!/bin/ash echo "compiling... be patient" gccgo -o go `ls *.go | grep -v signal_notunix.go | grep -v _test.go | grep -v bootstrap | grep -v doc` -static-libgo
#!/bin/ash echo "compiling... be patient" gccgo -Wl,-t -v -o go `ls *.go | grep -v signal_notunix.go | grep -v _test.go | grep -v bootstrap | grep -v doc` -static-libgo
improve autogen
improve autogen
AGS Script
bsd-3-clause
michalliu/faux-go,michalliu/faux-go
9eb7bbb7bf83f8786c3c2722ec546f91fcb4078c
installation.ash
installation.ash
#!/bin/ash # # startscript: normaly run it only once # (c) 2015/2016 [email protected] www.sosyco.de # # enhance the repositories and update the system if ! [ -f "/etc/apk/repositories.org" ]; then cp /etc/apk/repositories /etc/apk/repositories.org sed -ni 'p; s/\/main/\/community/p' /etc/apk/repositories fi apk update apk upgrade apk add git sudo docker rc-update add docker boot # add new user "dockeradmin" without password # and generate sshkeys getent passwd dockeradmin > /dev/null 2&>1 if ! [ $? -eq 0 ]; then ssh-keygen -f dockeradmin -t rsa -b 4096 -C dockeradmin -N '' adduser -D dockeradmin mkdir -p /home/dockeradmin/.ssh/ cp dockeradmin.pub /home/dockeradmin/.ssh/authorized_keys chmod 700 -R /home/dockeradmin/.ssh chown dockeradmin.dockeradmin -R /home/dockeradmin/.ssh echo "dockeradmin ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers adduser dockeradmin docker fi sed -i "s/DOCKER_OPTS.*/DOCKER_OPTS=\"--bip=192.168.199.1\/24\"/" /etc/conf.d/docker echo "don't forget to save the private sshkey: dockeardmin"
#!/bin/ash # # startscript: normaly run it only once # (c) 2015/2016 [email protected] www.sosyco.de # # enhance the repositories and update the system if ! [ -f "/etc/apk/repositories.org" ]; then cp /etc/apk/repositories /etc/apk/repositories.org sed -ni 'p; s/\/main/\/community/p' /etc/apk/repositories fi apk update apk upgrade apk add git sudo docker rc-update add docker boot # add new user "dockeradmin" without password # and generate sshkeys getent passwd dockeradmin > /dev/null 2&>1 if ! [ $? -eq 0 ]; then ssh-keygen -f dockeradmin -t rsa -b 4096 -C dockeradmin -N '' adduser -D -S /bin/ash dockeradmin sed -i "s/dockeradmin\:!/dockeradmin\:/g" /etc/shadow mkdir -p /home/dockeradmin/.ssh/ cp dockeradmin.pub /home/dockeradmin/.ssh/authorized_keys chmod 700 -R /home/dockeradmin/.ssh chown dockeradmin.dockeradmin -R /home/dockeradmin/.ssh echo "dockeradmin ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers adduser dockeradmin docker fi sed -i "s/DOCKER_OPTS.*/DOCKER_OPTS=\"--bip=192.168.199.1\/24\"/" /etc/conf.d/docker echo "don't forget to save the private sshkey: dockeardmin" # generate containeradmin (if we need one) sh-keygen -f containeradmin -t rsa -b 4096 -C containeradmin -N '' mkdir -p /home/dockeradmin/container/ssh/containeradmin cp containeradmin.pub /home/dockeradmin/container/ssh/containeradmin/authorized_keys cp containeradmin /home/dockeradmin/.ssh/containeradmin chmod 700 -R /home/dockeradmin/.ssh chown dockeradmin.dockeradmin -R /home/dockeradmin/.ssh chmod 755 -R /home/dockeradmin/container/ssh/containeradmin
Update installation.ash
Update installation.ash add central containeradmin-account
AGS Script
apache-2.0
sosyco/alpine-dockerhost
552849e3d082430f92e2182d72c234c380f8fd1e
web/generate_ssl_cert.ash
web/generate_ssl_cert.ash
#!/usr/bin/env ash # Variables BITS=${BITS:-'2048'} CERT_DIR=${CERT_DIR:-'/etc/ssl/certs'} DAYS=${DAYS:-'365'} FQDN=${FQDN:-"example.churchoffoxx.net"} # Functions ## Create the PEM format file create_pem() { cat ${CERT_DIR}/${FQDN}.crt ${CERT_DIR}/${FQDN}.key | tee ${CERT_DIR}/${FQDN}.pem } ## Create the certificate generate_cert() { # Create the key and CSR openssl req -nodes \ -newkey rsa:${BITS} \ -keyout ${CERT_DIR}/${FQDN}.key \ -out ${CERT_DIR}/${FQDN}.csr \ -subj "/C=US/ST=State/L=Town/O=Church of Foxx/OU=Example/CN=${FQDN}" # Sign the CSR openssl x509 -req \ -days ${DAYS} \ -in ${CERT_DIR}/${FQDN}.csr \ -signkey ${CERT_DIR}/${FQDN}.key \ -out ${CERT_DIR}/${FQDN}.crt } ## Check if the cert directory exists make_cert_dir() { # Create the directory if it doesn't exist yet if [[ -n ${CERT_DIR} ]]; then mkdir -p ${CERT_DIR} fi } ## Display usage information usage() { echo "Usage: [Environment Variables] generate_ssl_cert.ash [options]" echo " Environment Variables:" echo " FQDN fully qualified domain name of the server (default: example.churchoffoxx.net)" } # Logic ## Argument parsing while [[ "$1" != "" ]]; do case $1 in -h | --help ) usage exit 0 ;; * ) usage exit 1 esac shift done make_cert_dir generate_cert create_pem
#!/usr/bin/env ash # Variables BITS=${BITS:-'2048'} CERT_DIR=${CERT_DIR:-'/etc/ssl/certs'} DAYS=${DAYS:-'365'} FQDN=${FQDN:-"example.churchoffoxx.net"} # Functions ## Create the PEM format file create_pem() { cat ${CERT_DIR}/${FQDN}.crt ${CERT_DIR}/${FQDN}.key | tee ${CERT_DIR}/${FQDN}.pem } ## Create the certificate generate_cert() { # Create the key and CSR openssl req -nodes \ -newkey rsa:${BITS} \ -keyout ${CERT_DIR}/${FQDN}.key \ -out ${CERT_DIR}/${FQDN}.csr \ -subj "/C=US/ST=State/L=Town/O=Church of Foxx/OU=Example/CN=${FQDN}" # Sign the CSR openssl x509 -req \ -days ${DAYS} \ -in ${CERT_DIR}/${FQDN}.csr \ -signkey ${CERT_DIR}/${FQDN}.key \ -out ${CERT_DIR}/${FQDN}.crt } ## Check if the cert directory exists make_cert_dir() { # Create the directory if it doesn't exist yet if [[ -n ${CERT_DIR} ]]; then mkdir -p ${CERT_DIR} fi } ## Display usage information usage() { echo "Usage: [Environment Variables] generate_ssl_cert.ash [options]" echo " Environment Variables:" echo " BITS bits for the certificate (default: '2048')" echo " CERT_DIR directory to output to (default: '/etc/ssl/certs')" echo " DAYS days the cert is valid for (default: '365')" echo " FQDN fully qualified domain name of the server (default: example.churchoffoxx.net)" } # Logic ## Argument parsing while [[ "$1" != "" ]]; do case $1 in -h | --help ) usage exit 0 ;; * ) usage exit 1 esac shift done make_cert_dir generate_cert create_pem
Update generate_ssl_cert.ash
Update generate_ssl_cert.ash
AGS Script
apache-2.0
frozenfoxx/util,frozenfoxx/util,frozenfoxx/util,frozenfoxx/util
c4144239f70b735503df9032a52d7af7bd60c799
autogen.ash
autogen.ash
#!/bin/ash echo "compiling... be patient" gccgo -o go `ls *.go | grep -v signal_notunix.go | grep -v _test.go | grep -v bootstrap | grep -v doc` -static-libgo
add autogen.ash
add autogen.ash
AGS Script
bsd-3-clause
michalliu/faux-go,michalliu/faux-go
e9761f45fc8540f3bd9ef379a8ed0797fe38c553
src/scripts/lar-forecasting/lar-coverage.ash
src/scripts/lar-forecasting/lar-coverage.ash
notify "LeaChim"; import "lar-forecasting.ash"; boolean [location] quest_relevant_locations = $locations[ the spooky forest, the dark neck of the woods, the dark heart of the woods, the dark elbow of the woods, the black forest, whitey's grove, the hidden temple, 8-bit realm, the old landfill, the hidden park, the hidden apartment building, the hidden office building, the hidden bowling alley, the hidden hospital, the sleazy back alley, the haunted pantry, the haunted kitchen, the haunted billiards room, the haunted library, the haunted conservatory, the haunted gallery, the haunted bathroom, the haunted bedroom, the haunted ballroom, the haunted laboratory, the haunted storage room, the haunted nursery, the haunted wine cellar, the haunted laundry room, the haunted boiler room, the outskirts of cobb's knob, the bat hole entrance, guano junction, the batrat and ratbat burrow, the beanbat chamber, cobb's knob barracks, cobb's knob kitchens, cobb's knob harem, cobb's knob treasury, the "fun" house, inside the palindome, the degrassi knoll restroom, the degrassi knoll gym, the degrassi knoll bakery, the degrassi knoll garage, the unquiet garves, the defiled nook, the defiled niche, the defiled cranny, the defiled alcove, the penultimate fantasy airship, the castle in the clouds in the sky (basement), the castle in the clouds in the sky (ground floor), the castle in the clouds in the sky (top floor), the hole in the sky, infernal rackets backstage, the laugh floor, pandamonium slums, the goatlet, Itznotyerzitz Mine, lair of the ninja snowmen, the extreme slope, the icy peak, the smut orc logging camp, a-boo peak, twin peak, the obligatory pirate's cove, barrrney's barrr, the f'c'le, the poop deck, belowdecks, frat house, frat house in disguise, wartime frat house, wartime frat house (hippy disguise), hippy camp, hippy camp in disguise, wartime hippy camp, wartime hippy camp (frat disguise), sonofa beach, next to that barrel with something burning in it, near an abandoned refrigerator, over where the old tires are, out by that rusted-out car, the battlefield (frat uniform), the battlefield (hippy uniform), the arid\, extra-dry desert, the oasis, the upper chamber, the middle chamber, ]; int desired_turns = 500; void main() { print("Coverage for " + desired_turns + " turns:"); print ("Location, Combat/non-combat, monster name (out of the combat encounters)"); foreach loc in quest_relevant_locations { int cnc_found = 0; int combat_found = 0; int monster_found = 0; for turn from 0 to desired_turns { if(lar_encounter_known_is_combat(loc, turn)) { cnc_found += 1; if(lar_encounter_is_combat(loc, turn)) { combat_found +=1; } if(lar_encounter_known_monster(loc, turn)) { monster_found += 1; } } } // Report print(loc + ": " + (cnc_found * 100 / desired_turns) + "%, " + (monster_found * 100 / (combat_found + 1)) + "%"); } }
Add coverage script, to keep tabs on how far along the data is
Add coverage script, to keep tabs on how far along the data is
AGS Script
apache-2.0
mikebryant/kolmafia-lar-forecasting,mikebryant/kolmafia-lar-forecasting
926cad3f2b2ac96b2896af2d0f717f1f1867c228
allopy/generate_test_target.als
allopy/generate_test_target.als
sig Person { love: Person } run { some x: Person { x.love.love = x } }
sig Person { love: Person } run { some x: Person { x.love.love = x } }
change indent
change indent
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
49964b487b1d7cd475454e3036ba7dd43667f10d
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } -- about rows or cols fact noOtherHeadsInRow { no c: Col, r: Row { c not in { c: Col | is_black_head[c, r, cols/prev]} is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in { r: Row | is_black_head[c, r, rows/prev]} is_black_head[c, r, rows/prev] } } pred headsSeqInRow (r: Row, s: seq Col) { s.elems = { c: Col | is_black_head[c, r, cols/prev]} all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = { r: Row | is_black_head[c, r, rows/prev]} // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } -- about rows or cols fact noOtherHeadsInRow { no c: Col, r: Row { c not in { c: Col | is_black_head[c, r, cols/prev]} is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in { r: Row | is_black_head[c, r, rows/prev]} is_black_head[c, r, rows/prev] } } pred headsSeqInRow (r: Row, s: seq Col) { sorted[ { c: Col | is_black_head[c, r, cols/prev]}.index, s.index] } pred headsSeqInCol (c: Col, s: seq Row) { sorted[ { r: Row | is_black_head[c, r, rows/prev]}.index, s.index] } pred sorted(xs: Int, s: seq Int){ // sの要素はxsと同一 s.elems = xs // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
add pred sorted
add pred sorted
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
60fc274c9d162a75d488841ada03ce5bf5438751
alloy/tutorial_questions.als
alloy/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate findModel below expresses that there exist black, yellow and final states pred findModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // The run command below checks to see if the predicate can be satisfied in scope 1 run findModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which findModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $findModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run findModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if its successors are empty. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run findModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
Update the alloy axercise
Update the alloy axercise
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
17052eca0df60cfe2faeffbe5dbc6c54cd7dbdd9
combinator.als
combinator.als
open util/ordering[Term] some abstract sig Term {} one sig K extends Term {} sig Apply extends Term { f, g: Term } fact { all x, y: Term | (x -> y) in (f + g) => y not in (x.prevs + x) } pred equal (x, y: Term) { x in Apply and x.f in Apply and x.f.f = K and y = x.f.g } fun apply(x, y: Term): Term{ {a: Apply | a.f = x and a.g = y } } run { some x, y: Term | equal[x, y] } for 5 Term
open util/ordering[Term] some abstract sig Term {} one sig K extends Term {} sig Apply extends Term { f, g: Term } fact { all x, y: Term | (x -> y) in (f + g) => y not in (x.prevs + x) } pred equal_k (x, y: Term) { x in Apply and x.f in Apply and x.f.f = K and y = x.f.g } pred equal_k2 (x, y: Term) { one a, b: Term | x = apply[apply[K, a], b] and y = a } check { some x, y: Term | equal_k[x, y] iff equal_k2[x, y] } //pred equal_s (x, y: Term) {} pred equal (x, y: Term) { equal_k[x, y]// or equal_s[x, y] } fun apply(x, y: Term): Term{ {a: Apply | a.f = x and a.g = y } } fact { all x, y: Term | lone apply[x, y] } run { some x, y: Term | equal[x, y] } for 5 Term
clean pred equal
clean pred equal
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
2237e8ad1fd93fdd535eb2cd435e5f5abf5f6515
files/alloy/AUTH_without_unvalid.als
files/alloy/AUTH_without_unvalid.als
--------------------Initial State--------------- pred init [t: Time] { no Track.op.t Current_window.is_in.t = aws.Login #List.elements.t = 0 } ---------------Generic AUTH Structure ---------- abstract sig Go, Login, Signup, Ok, Cancel, Logout extends Action_widget { } abstract sig User, Password, User_save, Password_save, Re_password, Field extends Input_widget { } fact { (User_save+Password_save+Re_password) in Property_required.requireds (User_save+Password_save) in Property_unique.uniques } ---------------Generic AUTH Semantics---------- one sig Property_unique{ uniques: set Input_widget } one sig Property_required{ requireds: set Input_widget } sig Object_inlist extends Object{ vs: Value lone -> Input_widget } one sig List { elements: Object_inlist set -> Time } pred fill_semantics [iw: Input_widget, t: Time, v: Value] { } pred fill_success_post [iw: Input_widget, t, t': Time, v: Value] { List.elements.t' = List.elements.t } pred fill_fail_post [iw: Input_widget, t, t': Time, v: Value] { List.elements.t' = List.elements.t } pred fill_pre[iw: Input_widget, t: Time, v: Value] { //#iw.content.(T/first) = 1 => not(v = none) } pred select_semantics [sw: Selectable_widget, t: Time, o: Object] { } pred select_success_post [sw: Selectable_widget, t, t': Time, o: Object] { //List.elements.t' = List.elements.t } pred select_fail_post [sw: Selectable_widget, t, t': Time, o: Object] { //List.elements.t' = List.elements.t } pred select_pre[sw: Selectable_widget, t: Time, o: Object] { } pred click_semantics [aw: Action_widget, t: Time] { Current_window.is_in.t' = aw.goes (aw in Login) => filled_login_test [t] and existing_test [t] (aw in Ok) => filled_required_test[t] and unique_fields_test [t] and same_pass_test [t] } pred click_success_post [aw: Action_widget, t, t': Time] { (aw in Ok) => add [t, t'] else List.elements.t' = List.elements.t (all iw: Input_widget | iw.content.t' = iw.content.(T/first)) } pred click_fail_post [aw: Action_widget, t, t': Time] { (all iw: Input_widget | iw.content.t' = iw.content.(T/first)) List.elements.t' = List.elements.t } pred click_pre[aw: Action_widget, t: Time] { } pred add [t, t': Time] { one o: Object_inlist |all iw: (User_save + Password_save + Field) | not(o in List.elements.t) and o.appeared = t' and o.vs.iw = iw.content.t and List.elements.t' = List.elements.t+o } pred filled_login_test [t: Time] { all iw: (User+Password)| #iw.content.t = 1 } pred existing_test [t: Time] { one o: List.elements.t | Password.content.t =o.vs.Password_save and User.content.t =o.vs.User_save } pred same_pass_test [t: Time] { Password_save.content.t = Re_password.content.t } pred filled_required_test [t: Time] { all iw: (User_save + Password_save + Re_password + Field)| (iw in Property_required.requireds) => #iw.content.t = 1 } pred unique_fields_test [t: Time] { all iw: (User_save + Password_save + Field) | all o: List.elements.t | (iw in Property_unique.uniques and (#o.vs.iw= 1)) => iw.content.t !=o.vs.iw }
--------------------Initial State--------------- pred init [t: Time] { no Track.op.t Current_window.is_in.t = aws.Login #List.elements.t = 0 } ---------------Generic AUTH Structure ---------- abstract sig Go, Login, Signup, Ok, Cancel, Logout extends Action_widget { } abstract sig User, Password, User_save, Password_save, Re_password, Field extends Input_widget { } fact { (User_save+Password_save+Re_password) in Property_required.requireds (User_save+Password_save) in Property_unique.uniques } ---------------Generic AUTH Semantics---------- one sig Property_unique{ uniques: set Input_widget } one sig Property_required{ requireds: set Input_widget } sig Object_inlist extends Object{ vs: Value lone -> Input_widget } one sig List { elements: Object_inlist set -> Time } pred fill_semantics [iw: Input_widget, t: Time, v: Value] { } pred fill_success_post [iw: Input_widget, t, t': Time, v: Value] { List.elements.t' = List.elements.t } pred fill_fail_post [iw: Input_widget, t, t': Time, v: Value] { List.elements.t' = List.elements.t } pred fill_pre[iw: Input_widget, t: Time, v: Value] { //#iw.content.(T/first) = 1 => not(v = none) } pred select_semantics [sw: Selectable_widget, t: Time, o: Object] { } pred select_success_post [sw: Selectable_widget, t, t': Time, o: Object] { //List.elements.t' = List.elements.t } pred select_fail_post [sw: Selectable_widget, t, t': Time, o: Object] { //List.elements.t' = List.elements.t } pred select_pre[sw: Selectable_widget, t: Time, o: Object] { } pred click_semantics [aw: Action_widget, t: Time] { (aw in Login) => filled_login_test [t] and existing_test [t] (aw in Ok) => filled_required_test[t] and unique_fields_test [t] and same_pass_test [t] } pred click_success_post [aw: Action_widget, t, t': Time] { Current_window.is_in.t' = aw.goes (aw in Ok) => add [t, t'] else List.elements.t' = List.elements.t (all iw: Input_widget | iw.content.t' = iw.content.(T/first)) } pred click_fail_post [aw: Action_widget, t, t': Time] { (all iw: Input_widget | iw.content.t' = iw.content.(T/first)) List.elements.t' = List.elements.t } pred click_pre[aw: Action_widget, t: Time] { } pred add [t, t': Time] { one o: Object_inlist |all iw: (User_save + Password_save + Field) | not(o in List.elements.t) and o.appeared = t' and o.vs.iw = iw.content.t and List.elements.t' = List.elements.t+o } pred filled_login_test [t: Time] { all iw: (User+Password)| #iw.content.t = 1 } pred existing_test [t: Time] { one o: List.elements.t | Password.content.t =o.vs.Password_save and User.content.t =o.vs.User_save } pred same_pass_test [t: Time] { Password_save.content.t = Re_password.content.t } pred filled_required_test [t: Time] { all iw: (User_save + Password_save + Re_password + Field)| (iw in Property_required.requireds) => #iw.content.t = 1 } pred unique_fields_test [t: Time] { all iw: (User_save + Password_save + Field) | all o: List.elements.t | (iw in Property_unique.uniques and (#o.vs.iw= 1)) => iw.content.t !=o.vs.iw }
fix in auth
fix in auth
Alloy
mit
danydunk/Augusto,danydunk/Augusto
6bbb9dbef6ae80e0b5230041f1009b1478de3722
tutorials/2017/wednesday/tutorial_questions.als
tutorials/2017/wednesday/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
Fix typo
Fix typo
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
743a9ab9d3cdedc4ea99ab56450d64221ba72b45
etude16.als
etude16.als
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, } abstract sig Man, Woman extends Person {} enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred step (t, t': Time) { some disj p1, p2 : Person { { // marrige p1.state.t = NotMarried and p2.state.t = NotMarried p1.state.t' = Married and p2.state.t' = Married } or { // divorce p1.state.t = Married and p2.state.t = Married p1.state.t' = NotMarried and p2.state.t' = NotMarried } } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 3 Person, 5 Time
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, } abstract sig Man, Woman extends Person {} enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred step (t, t': Time) { some disj p1 : Man, p2 : Woman { { // marrige p1.state.t = NotMarried and p2.state.t = NotMarried p1.state.t' = Married and p2.state.t' = Married } or { // divorce p1.state.t = Married and p2.state.t = Married p1.state.t' = NotMarried and p2.state.t' = NotMarried } } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 3 Person, 5 Time
make not to marry women
make not to marry women
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
45c8f608ddc12b021348c05aa0b48f3e0ab6a1df
alloy/tutorial_questions.als
alloy/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate findModel below expresses that there exist black, yellow and final states pred findModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // The run command below checks to see if the predicate can be satisfied in scope 1 run findModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which findModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $findModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run findModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if its successors are empty. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new fact,s run findModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate findModel below expresses that there exist black, yellow and final states pred findModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // The run command below checks to see if the predicate can be satisfied in scope 1 run findModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which findModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $findModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run findModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if its successors are empty. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run findModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
Fix typo in exercises
Fix typo in exercises
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
030b22e20b554947bf28db0f5a232fddfe04baf2
Workspace/RASD/Alloy/PowerEnjoy.als
Workspace/RASD/Alloy/PowerEnjoy.als
module PowEnj //SIGNATURES sig Position{} sig Email{} sig Code{} sig Plug{} abstract sig Bool{} sig False extends Bool{} sig True extends Bool{} abstract sig State{} sig FreeState extends State{} sig ReservedState extends State{} sig RentedState extends State{} sig DriverLicense{ code:one Code, expiration:Int } { expiration>0 } sig User { payInfo: some PaymentMethod, position: one Position, license: one DriverLicense, email:one Email } sig Reservation{ user:one User, time:Int, endTime:Int, car:one Car } { time>0 endTime>time } sig Rent { startTime: one Int, endTime:one Int, endRent:one Bool, applyDiscount:one Int, applyOvertax:one Int, totalCost:Int, passengers:one Int, reservation:one Reservation, payment:one PaymentMethod }{ passengers>=0 startTime>0 endTime>startTime applyOvertax>=0 applyDiscount>=0 } abstract sig Station{ parkedCar:set Car, positoin:one Position } sig Parking extends Station{ distanceFromCharge:Int }{ distanceFromCharge>0 } sig SafeArea extends Station { pluggedCar: set Car, plugAvailable: set Plug, } sig PaymentMethod { transactionCode: one Code } sig Car { position:one Position, battery: Int, plate: one Code, state:one State, readyToEnd:one Bool }{ battery>=0 and battery<=100 } //FACT fact{ //No useless paymentMethod User.payInfo=PaymentMethod //No useless Plug SafeArea.plugAvailable=Plug //No useless Email User.email=Email //No useless Position Car.position+User.position=Position //No useless Code Car.plate+PaymentMethod.transactionCode+DriverLicense.code=Code //No useless State Car.state=State //No useless Bool Rent.endRent=Bool //No useless License User.license=DriverLicense //No PaymentMethod with the same code all p1,p2:PaymentMethod| p1!=p2 implies p1.code!=p2.code //No car with the same plate all c1, c2: Car | c1!=c2 implies c1.plate!=c2.plate //No users with same email all u1,u2:User| u1!=u2 implies u1.email!=u2.email //No users with same license all u1,u2:User| u1!=u2 implies u1.license!=u2.license //No reservation for the same car in a time<1 all r1,r2:Reservation | (r1!=r2 and r1.car=r2.car) implies (r1.time>r2.time+1 or r2.time>r1.time+1) //If a car is reserved is in reserved state all r:Reservation,c:Car,rent:Rent| (r.car=c and !(rent.endRent=False and rent.reservation.car=c)) implies c.state=ReservedState //if a car is in use is in rentedState all c:Car,r:Rent| r.reservation.car=c and r.endRent=False implies c.state=RentedState //if a car is not rented or reserved is in free state and a reservation keep going for max 1 hour all c:Car,rent:Rent,res:Reservation| //if the car is not reserved ((res.car!=c or //or the reservation is expired (res.car=c and res.endTime>res.time+1)) and //and there is no rent on the car (rent.reservation.car!=c or //or the rent is finished (rent.endRent=True and rent.reservation.car=c))) implies c.state=FreeState //A rent can be done only after a reservation all rent:Rent,res:Reservation| rent.reservation=res implies rent.startTime>res.time and rent.startTime<=res.time+1 //Two different rent can't have the same reservation all r1,r2:Rent| r1!=r2 implies r1.reservation!=r2.reservation //There is just one rent not finish for each car all r1,r2:Rent|r1.endRent=False and r2.reservation.car=r1.reservation.car implies !(r2.endRent=False) //A rent can end only in a station all rent:Rent,c:Car,s:Station|rent.reservation.car=c and c.readyToEnd=True implies c.position=s.position //A rent has been concluded only in a station all rent:Rent,s:Station|rent.endRent=True implies rent.reservation.car.position=s.position //Discount for battery state applyed only if the rent in ended and the battery state is >50 all rent:Rent| rent.reservation.car.battery>50 and rent.endRent=True implies rent.applyDiscount=20 //Discount for passengers is applyed only if the rent is finished and more than 2 passengers were found all rent:Rent| rent.passengers>2 and rent.endRent=True implies rent.applyDiscount=20 //All the cars parked are free all car:Car,s:Station| car.position=s.position and car.state=FreeState implies car in s.parkedCar //If a car is plugged is also parked all s:SafeArea,car:Car|car in s.pluggedCar implies car in s.parkedCar //the user get a discount parking and plugging the car all car:Car,s:SafeArea,r1,r2:Rent| car in s.parkedCar and car in s.pluggedCar implies r1.applyDiscount=30 //Safe area overtax all car:Car,p:Parking, r1,r2:Rent | car in p.parkedCar and p.distanceFromCharge>3 implies r1.applyDiscount=0 and r1.applyOvertax=30 no s:SafeArea| #s.pluggedCar>#s.parkedCar //Overtaxes are 0 or 30 all rent:Rent| rent.applyOvertax=0 or rent.applyOvertax=30 all rent:Rent| rent.applyOvertax>0 or rent.applyDiscount>0 implies rent.endRent=True } //ASSUMPTION //A car can be reused after a rent assert CarReused{ all r1,r2:Rent| r1.endRent=True and r2.endRent=False and r1.reservation.car= r2.reservation.car implies r2.startTime>r1.endTime } //There are as many driver license as users assert DriverForEachDocument{ #DriverLicense = #User #User=#Email } assert UserPaymentMethod{ #User.payInfo<=#PaymentMethod } //The rent with taxes can't have a discount assert RentOverTaxes{ all rent:Rent| rent.applyOvertax>0 implies rent.applyDiscount<rent.applyOvertax } //the plugged car can't be in use assert PluggedCar{ all rent:Rent| rent.reservation.car in SafeArea.pluggedCar implies !rent.endRent=False } check PluggedCar check RentOverTaxes check UserPaymentMethod check CarReused for 5 check DriverForEachDocument for 5 pred SimpleWorld { #User <3 #Car < 4 #Station< 4 #Reservation < 4 #Rent <3 } pred RealWorld { #User > 2 #Car > 3 #SafeArea> 1 #Parking > 2 #Reservation > 2 #Rent > 1 } run SimpleWorld for 6 run RealWorld for 6
module PowEnj //SIGNATURES sig Position{} sig Email{} sig Code{} sig Plug{} abstract sig Bool{} sig False extends Bool{} sig True extends Bool{} abstract sig State{} sig FreeState extends State{} sig ReservedState extends State{} sig RentedState extends State{} sig DriverLicense{ code:one Code, expiration:Int } { expiration>0 } sig User { payInfo: some PaymentMethod, position: one Position, license: one DriverLicense, email:one Email } sig Reservation{ user:one User, time:Int, endTime:Int, car:one Car } { time>0 endTime>time } sig Rent { startTime: one Int, endTime:one Int, endRent:one Bool, applyDiscount:one Int, applyOvertax:one Int, totalCost:Int, passengers:one Int, reservation:one Reservation, payment:one PaymentMethod }{ passengers>=0 startTime>0 endTime>startTime applyOvertax>=0 applyDiscount>=0 } abstract sig Station{ parkedCar:set Car, positoin:one Position } sig Parking extends Station{ distanceFromCharge:Int }{ distanceFromCharge>0 } sig SafeArea extends Station { pluggedCar: set Car, plugAvailable: set Plug, } sig PaymentMethod { transactionCode: one Code } sig Car { position:one Position, battery: Int, plate: one Code, state:one State, readyToEnd:one Bool }{ battery>=0 and battery<=100 } //FACT fact{ //No useless paymentMethod User.payInfo=PaymentMethod //No useless Plug SafeArea.plugAvailable=Plug //No useless Email User.email=Email //No useless Position Car.position+User.position=Position //No useless Code Car.plate+PaymentMethod.transactionCode+DriverLicense.code=Code //No useless State Car.state=State //No useless Bool Rent.endRent=Bool //No useless License User.license=DriverLicense //No PaymentMethod with the same code all p1,p2:PaymentMethod| p1!=p2 implies p1.code!=p2.code //No car with the same plate all c1, c2: Car | c1!=c2 implies c1.plate!=c2.plate //No users with same email all u1,u2:User| u1!=u2 implies u1.email!=u2.email //No users with same license all u1,u2:User| u1!=u2 implies u1.license!=u2.license //No reservation for the same car in a time<1 all r1,r2:Reservation | (r1!=r2 and r1.car=r2.car) implies (r1.time>r2.time+1 or r2.time>r1.time+1) //If a car is reserved is in reserved state all r:Reservation,c:Car,rent:Rent| (r.car=c and !(rent.endRent=False and rent.reservation.car=c)) implies c.state=ReservedState //if a car is in use is in rentedState all c:Car,r:Rent| r.reservation.car=c and r.endRent=False implies c.state=RentedState //if a car is not rented or reserved is in free state and a reservation keep going for max 1 hour all c:Car,rent:Rent,res:Reservation| //if the car is not reserved ((res.car!=c or //or the reservation is expired (res.car=c and res.endTime>res.time+1)) and //and there is no rent on the car (rent.reservation.car!=c or //or the rent is finished (rent.endRent=True and rent.reservation.car=c))) implies c.state=FreeState //A rent can be done only after a reservation all rent:Rent,res:Reservation| rent.reservation=res implies rent.startTime>res.time and rent.startTime<=res.time+1 //Two different rent can't have the same reservation all r1,r2:Rent| r1!=r2 implies r1.reservation!=r2.reservation //There is just one rent not finish for each car all r1,r2:Rent|r1.endRent=False and r2.reservation.car=r1.reservation.car implies !(r2.endRent=False) //A rent can end only in a station all rent:Rent,c:Car,s:Station|rent.reservation.car=c and c.readyToEnd=True implies c.position=s.position //A rent has been concluded only in a station all rent:Rent,s:Station|rent.endRent=True implies rent.reservation.car.position=s.position //Discount for battery state applyed only if the rent in ended and the battery state is >50 all rent:Rent| rent.reservation.car.battery>50 and rent.endRent=True implies rent.applyDiscount=20 //Discount for passengers is applyed only if the rent is finished and more than 2 passengers were found all rent:Rent| rent.passengers>2 and rent.endRent=True implies rent.applyDiscount=20 //All the cars parked are free all car:Car,s:Station| car.position=s.position and car.state=FreeState implies car in s.parkedCar //If a car is plugged is also parked all s:SafeArea,car:Car|car in s.pluggedCar implies car in s.parkedCar //the user get a discount parking and plugging the car all car:Car,s:SafeArea,r1,r2:Rent| car in s.parkedCar and car in s.pluggedCar implies r1.applyDiscount=30 //Safe area overtax all car:Car,p:Parking, r1,r2:Rent | car in p.parkedCar and p.distanceFromCharge>3 implies r1.applyDiscount=0 and r1.applyOvertax=30 all car:Car| car.state=FreeState implies car in Station.parkedCar no s:SafeArea| #s.pluggedCar>#s.parkedCar //Overtaxes are 0 or 30 all rent:Rent| rent.applyOvertax=0 or rent.applyOvertax=30 //the bill is calculate only if the rent is finish all rent:Rent| rent.applyOvertax>0 or rent.applyDiscount>0 implies rent.endRent=True } //ASSUMPTION //A car can be reused after a rent assert CarReused{ all r1,r2:Rent| r1.endRent=True and r2.endRent=False and r1.reservation.car= r2.reservation.car implies r2.startTime>r1.endTime } //There are as many driver license as users assert DriverForEachDocument{ #DriverLicense = #User #User=#Email } assert UserPaymentMethod{ #User.payInfo<=#PaymentMethod } //The rent with taxes can't have a discount assert RentOverTaxes{ all rent:Rent| rent.applyOvertax>0 implies rent.applyDiscount<rent.applyOvertax } //the plugged car can't be in use assert PluggedCar{ all rent:Rent| rent.reservation.car in SafeArea.pluggedCar implies !rent.endRent=False } check PluggedCar check RentOverTaxes check UserPaymentMethod check CarReused for 5 check DriverForEachDocument for 5 pred SimpleWorld { #User <3 #Car < 4 #Station< 4 #Reservation < 4 #Rent <3 } pred RealWorld { #User > 2 #Car > 3 #SafeArea> 1 #Parking > 2 #Reservation > 2 #Rent > 1 } run SimpleWorld for 6 run RealWorld for 6
Edit alloy model
Edit alloy model
Alloy
mit
FrancescoZ/PowerEnJoy
d81b0551c008d203ab157c4243ac905cc66eac31
Perterson.als
Perterson.als
open util/ordering[Time] sig Time {} one sig Memory { turn: Int -> Time, flag: Int -> Int -> Time }{ all t: Time { one flag[0].t one flag[1].t } } one sig PC { proc: Int -> Int -> Time }{ all t: Time { one proc[0].t one proc[1].t } } fact { // 最初はメモリはみんな0 let t = first { Memory.turn.t = 0 Memory.flag[0].t = 0 Memory.flag[1].t = 0 // 最初はプログラムカウンタは0 PC.proc[0].t = 0 PC.proc[1].t = 0 } } pred store(t: Time, target: univ -> Time, value: univ){ one value target.t = value } pred must_wait(t: Time, pid: Int){ let other = (0 + 1) - pid { Memory.flag[other].t = 1 // otherがwaitしている Memory.turn.t = other // otherが優先権を持っている } } pred no_change(t: Time, changable: univ -> Time){ changable.t = changable.(t.prev) } pred step(t: Time) { // 各時刻でどちらかのプロセスが1命令実行する some pid: (0 + 1) { let pc = PC.proc[pid].(t.prev), nextpc = PC.proc[pid].t, other = (0 + 1) - pid { (pc = 0) => { // flag[0] = 1 store[t, Memory.flag[pid], 1] nextpc = 1 no_change[t, Memory.turn] } (pc = 1) => { // flag[0] = 1 store[t, Memory.turn, other] nextpc = 2 no_change[t, Memory.flag[pid]] } (pc = 2) => { // while( flag[1] && turn == 1 ); must_wait[t, pid] => { nextpc = 2 }else{ nextpc = 3 } no_change[t, Memory.turn] no_change[t, Memory.flag[pid]] } (pc = 3) => { // flag[0] = 0 store[t, Memory.flag[pid], 0] nextpc = 0 no_change[t, Memory.turn] } // no change no_change[t, PC.proc[other]] no_change[t, Memory.flag[other]] } } } fact { all t: Time - first { step[t] } } run { some t: Time { PC.proc[0].t = 3 PC.proc[1].t = 3 } } for 20 Time
add Peterson
add Peterson
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
7c590f18fad924f5b583f3807a736fb483e43cbc
Perterson.als
Perterson.als
open util/ordering[Time] sig Time {} one sig Memory { turn: Int -> Time, flag: Int -> Int -> Time }{ all t: Time { one flag[0].t one flag[1].t no flag[Int - 0 - 1].t } } one sig PC { proc: Int -> Int -> Time, current_pid: Int -> Time }{ all t: Time { one proc[0].t one proc[1].t no proc[Int - 0 - 1].t } } fact { // 最初はメモリはみんな0 let t = first { Memory.turn.t = 0 Memory.flag[0].t = 0 Memory.flag[1].t = 0 // 最初はプログラムカウンタは0 PC.proc[0].t = 0 PC.proc[1].t = 0 } } pred store(t: Time, target: univ -> Time, value: univ){ one value target.t = value } pred must_wait(t: Time, pid: Int){ let other = (0 + 1) - pid { Memory.flag[other].t = 1 // otherがwaitしている Memory.turn.t = other // otherが優先権を持っている } } pred no_change(t: Time, changable: univ -> Time){ changable.t = changable.(t.prev) } pred step(t: Time) { // 各時刻でどちらかのプロセスが1命令実行する some pid: (0 + 1) { PC.current_pid.t = pid let pc = PC.proc[pid].(t.prev), nextpc = PC.proc[pid].t, other = (0 + 1) - pid { (pc = 0) => { // flag[0] = 1 store[t, Memory.flag[pid], 1] nextpc = plus[pc, 1] no_change[t, Memory.turn] } (pc = 1) => { // flag[0] = 1 store[t, Memory.turn, other] nextpc = plus[pc, 1] no_change[t, Memory.flag[pid]] } (pc = 2) => { // while( flag[1] && turn == 1 ); must_wait[t, pid] => { nextpc = pc }else{ nextpc = plus[pc, 1] } no_change[t, Memory.turn] no_change[t, Memory.flag[pid]] } (pc = 3) => { // flag[0] = 0 store[t, Memory.flag[pid], 0] nextpc = 0 no_change[t, Memory.turn] } // no change no_change[t, PC.proc[other]] no_change[t, Memory.flag[other]] } } } check MutualExclusion { no t: Time { PC.proc[0].t = 3 PC.proc[1].t = 3 } } for 15 Time check BoundedWaiting_Bad { no t: Time, pid: Int { PC.proc[pid].t = 2 PC.proc[pid].(t.next) = 2 PC.proc[pid].(t.next.next) = 2 PC.proc[pid].(t.next.next.next) = 2 PC.proc[pid].(t.next.next.next.next) = 2 } } for 15 Time check BoundedWaiting { no t, t': Time, pid: Int { let range = Time - t.prevs - t'.nexts { // あるプロセスがずっと2(ロック待ち)で all t'': range | PC.proc[pid].t'' = 2 // その間、もう片方のプロセスが2回以上3(クリティカルセクション)を実行 #{t'': range | PC.proc[PC.current_pid.t''].t'' = 3 } >= 2 } } } for 15 Time fact { all t: Time - first { step[t] } } run { } for exactly 20 Time
open util/ordering[Time] sig Time {} one sig Memory { turn: Int -> Time, flag: Int -> Int -> Time }{ all t: Time { one flag[0].t one flag[1].t no flag[Int - 0 - 1].t } } one sig PC { proc: Int -> Int -> Time, current_pid: Int -> Time }{ all t: Time { one proc[0].t one proc[1].t no proc[Int - 0 - 1].t } } fact { // 最初はメモリはみんな0 let t = first { Memory.turn.t = 0 Memory.flag[0].t = 0 Memory.flag[1].t = 0 // 最初はプログラムカウンタは0 PC.proc[0].t = 0 PC.proc[1].t = 0 } } pred store(t: Time, target: univ -> Time, value: univ){ one value target.t = value } pred must_wait(t: Time, pid: Int){ let other = (0 + 1) - pid { Memory.flag[other].t = 1 // otherがwaitしている Memory.turn.t = other // otherが優先権を持っている } } pred no_change(t: Time, changable: univ -> Time){ changable.t = changable.(t.prev) } pred step(t: Time) { // 各時刻でどちらかのプロセスが1命令実行する some pid: (0 + 1) { PC.current_pid.t = pid let pc = PC.proc[pid].(t.prev), nextpc = PC.proc[pid].t, other = (0 + 1) - pid { (pc = 0) => { // flag[0] = 1 store[t, Memory.flag[pid], 1] nextpc = plus[pc, 1] no_change[t, Memory.turn] } (pc = 1) => { // turn = 1 store[t, Memory.turn, other] nextpc = plus[pc, 1] no_change[t, Memory.flag[pid]] } (pc = 2) => { // while( flag[1] && turn == 1 ); must_wait[t, pid] => { nextpc = pc }else{ nextpc = plus[pc, 1] } no_change[t, Memory.turn] no_change[t, Memory.flag[pid]] } (pc = 3) => { // flag[0] = 0 store[t, Memory.flag[pid], 0] nextpc = 0 no_change[t, Memory.turn] } // no change no_change[t, PC.proc[other]] no_change[t, Memory.flag[other]] } } } check MutualExclusion { no t: Time { PC.proc[0].t = 3 PC.proc[1].t = 3 } } for 15 Time check BoundedWaiting_Bad { no t: Time, pid: Int { PC.proc[pid].t = 2 PC.proc[pid].(t.next) = 2 PC.proc[pid].(t.next.next) = 2 PC.proc[pid].(t.next.next.next) = 2 PC.proc[pid].(t.next.next.next.next) = 2 } } for 15 Time check BoundedWaiting { no t, t': Time, pid: Int { let range = Time - t.prevs - t'.nexts { // あるプロセスがずっと2(ロック待ち)で all t'': range | PC.proc[pid].t'' = 2 // その間、もう片方のプロセスが2回以上3(クリティカルセクション)を実行 #{t'': range | PC.proc[PC.current_pid.t''].t'' = 3 } >= 2 } } } for 15 Time fact { all t: Time - first { step[t] } } run { } for exactly 20 Time
fix bug in comment
fix bug in comment
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
af2ce59dc2d8c72a71c67ab77f1c6ffa551c2531
models/Voting.als
models/Voting.als
-- (c) 2010-2011, Dermot Cochran, IT University of Copenhagen -- http://www.kindsoftware.com/about/people/dc -- http://www.itu.dk/people/dero module Voting open util/integer -- Note that all axioms should be expressed as facts appended to signatures -- Standalone facts will be ignored by the API, but not by the analyser /* There are four winner-outcomes and six loser-outcomes: Winner: (W1) elected in the first round of counting either by quota or plurality, QuotaWinner: (W2) elected with transfers from another candidate (STV only), CompromiseWinner: (W3) elected on the last round of counting without quota (STV only), TiedWinner: (W4) elected by tie breaker, TiedLoser: (L1) loses only by tie breaker but reaches the threshold, Loser: (L2) defeated on last round but reaches the minimum threshold of votes, TiedEarlyLoser: (L3) reaches threshold but eliminated by tie breaker (STV only), EarlyLoser: (L4) reaches threshold but is eliminated before last round (STV only), TiedSoreLoser: (L5) loses only by tie breaker but does not reach threshold, SoreLoser: (L6) does not even reach the mimimum threshold of votes. */ enum Event {Winner, QuotaWinner, CompromiseWinner, TiedWinner, TiedLoser, Loser, TiedEarlyLoser, EarlyLoser, TiedSoreLoser, SoreLoser} enum Method {Plurality, STV} -- An individual person standing for election sig Candidate { votes: set Ballot, -- First preference ballots assigned to this candidate transfers: set Ballot, -- Ballots received by transfer from another candidate surplus: set Ballot, -- Ballots given to another candidate (on election or elimination) outcome: Event } { no b: Ballot | b in votes & transfers all b: Ballot | b in votes + transfers implies this in b.assignees surplus in votes + transfers Election.method = Plurality implies #surplus = 0 and #transfers = 0 0 < #transfers implies Election.method = STV outcome = Winner and Election.method = STV implies Scenario.quota + #surplus = #votes outcome = Winner implies #transfers = 0 outcome = QuotaWinner implies surplus in transfers outcome = QuotaWinner implies Scenario.quota + #surplus = #votes + #transfers all b: Ballot | b in votes implies this in b.assignees 0 < #surplus implies (outcome = Winner or outcome = QuotaWinner) (outcome = EarlyLoser or outcome = TiedEarlyLoser) iff (this in Scenario.eliminated and not (#votes + #transfers < Scenario.threshold)) // All non-sore losers are above the threshold outcome = TiedLoser implies Scenario.threshold < #votes + #transfers outcome = Loser implies Scenario.threshold < #votes + #transfers outcome = EarlyLoser implies Scenario.threshold < #votes + #transfers outcome = TiedEarlyLoser implies Scenario.threshold < #votes + #transfers // Plurality outcomes Election.method = Plurality implies (outcome = Loser or outcome = SoreLoser or outcome = Winner or outcome = TiedWinner or outcome = TiedLoser or outcome = TiedSoreLoser) // PR-STV Winner has at least a quota of first preference votes (Election.method = STV and outcome = Winner) implies Scenario.quota <= #votes // Quota Winner has a least a quota of votes after transfers outcome = QuotaWinner implies Scenario.quota <= #votes + #transfers // Quota Winner does not have a quota of first preference votes outcome = QuotaWinner implies not Scenario.quota <= #votes // Compromise winners do not have a quota of votes outcome = CompromiseWinner implies not (Scenario.quota <= #votes + #transfers) // STV Tied Winners have less than a quota of votes (Election.method = STV and outcome = TiedWinner) implies not (Scenario.quota <= #votes + #transfers) // Sore Losers have less votes than the threshold outcome = SoreLoser implies #votes + #transfers < Scenario.threshold // Tied Sore Losers have less votes than the threshold outcome = TiedSoreLoser implies #votes + #transfers < Scenario.threshold // Size of surplus for each STV Winner and Quota Winner (outcome = QuotaWinner or (outcome = Winner and Election.method = STV)) implies (#surplus = #votes + #transfers - Scenario.quota) } -- A digital or paper artifact which accurately records the intentions of the voter sig Ballot { assignees: set Candidate, -- Candidates to which this ballot has been assigned preferences: seq Candidate -- Ranking of candidates } { assignees in preferences.elems not preferences.hasDups preferences.first in assignees Election.method = Plurality implies #preferences <= 1 0 <= #preferences // First preference all c: Candidate | preferences.first = c iff this in c.votes // Second and subsequent preferences all disj donor,receiver: Candidate | (donor + receiver in assignees and this in receiver.transfers and this in donor.surplus) implies (preferences.idxOf[donor] < preferences.idxOf[receiver] and receiver in preferences.rest.elems) // All ballot transfers are associated with the last candidate to receive the transfer all disj c,d: Candidate | this in c.transfers implies c in assignees and (d not in assignees or preferences.idxOf[d] < preferences.idxOf[c]) // Transfers to next continuing candidate all disj skipped, receiving: Candidate | preferences.idxOf[skipped] < preferences.idxOf[receiving] and receiving in assignees and (not skipped in assignees) implies (skipped in Scenario.eliminated or skipped.outcome = Winner or skipped.outcome = QuotaWinner) } -- An election result one sig Scenario { losers: set Candidate, winners: set Candidate, eliminated: set Candidate, -- Early and Sore Losers under STV rules threshold: Int, -- Minimum number of votes for a Loser or Early Loser quota: Int, -- Minimum number of votes for a STV Winner or Quota Winner fullQuota: Int -- Quota if all constituency seats were vacant } { all c: Candidate | c in winners + losers #winners = Election.seats no c: Candidate | c in losers & winners 0 < #losers all w: Candidate | all l: Candidate | l in losers and w in winners implies (#l.votes + #l.transfers <= #w.votes + #w.transfers) Election.method = STV implies threshold = 1 + fullQuota.div[4] eliminated in losers // All PR-STV losers have less votes than the quota all c: Candidate | (c in losers and Election.method = STV) implies #c.votes + #c.transfers < quota // Winners have more votes than all non-tied losers all disj c,d: Candidate | c in winners and (d.outcome = SoreLoser or d.outcome = EarlyLoser or d.outcome = Loser) implies (#d.votes + #d.transfers) < (#c.votes + #c.transfers) // Losers have less votes than all non-tied winners all disj c,d: Candidate | (c.outcome = CompromiseWinner or c.outcome = QuotaWinner or c.outcome = Winner) and d in losers implies #d.votes + #d.transfers < #c.votes + #c.transfers // Lowest candidate is eliminated first all disj c,d: Candidate | c in eliminated and d not in eliminated implies #c.votes + #c.transfers <= #d.votes + #d.transfers // A non-sore plurality loser must have received at least five percent of the total vote Election.method = Plurality implies threshold = 1 + BallotBox.size.div[20] // Winning outcomes all c: Candidate | c in winners iff (c.outcome = Winner or c.outcome = QuotaWinner or c.outcome = CompromiseWinner or c.outcome = TiedWinner) // Losing outcomes all c: Candidate | c in losers iff (c.outcome = Loser or c.outcome = EarlyLoser or c.outcome = SoreLoser or c.outcome = TiedLoser or c.outcome = TiedEarlyLoser or c.outcome = TiedSoreLoser) // STV election quotas Election.method = STV implies quota = 1 + BallotBox.size.div[Election.seats+1] and fullQuota = 1 + BallotBox.size.div[Election.constituencySeats + 1] Election.method = Plurality implies quota = 1 and fullQuota = 1 // All ties involve equality between at least one winner and at least one loser all w: Candidate | some l: Candidate | w.outcome = TiedWinner and (l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) implies (#l.votes + #l.transfers = #w.votes + #w.transfers) all s: Candidate | some w: Candidate | w.outcome = TiedWinner and (s.outcome = SoreLoser or s.outcome = TiedLoser or s.outcome = TiedEarlyLoser) implies (#s.votes = #w.votes) or (#s.votes + #s.transfers = #w.votes + #w.transfers) // When there is a tied sore loser then there are no non-sore losers no disj a,b: Candidate | a.outcome = TiedSoreLoser and (b.outcome = TiedLoser or b.outcome = TiedEarlyLoser or b.outcome=Loser or b.outcome=EarlyLoser) // For each Tied Winner there is a Tied Loser all w: Candidate | some l: Candidate | w.outcome = TiedWinner implies (l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) // Tied Winners and Tied Losers have an equal number of votes all disj l,w: Candidate | ((l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) and w.outcome = TiedWinner) implies #w.votes + #w.transfers = #l.votes + #l.transfers // Compromise winner must have more votes than any tied winners all disj c,t: Candidate | (c.outcome = CompromiseWinner and t.outcome = TiedWinner) implies #t.votes + #t.transfers < #c.votes + #c.transfers // Winners have more votes than non-tied losers all w,l: Candidate | w.outcome = Winner and (l.outcome = Loser or l.outcome = EarlyLoser or l.outcome = SoreLoser) implies ((#l.votes < #w.votes) or (#l.votes + #l.transfers < #w.votes + #w.transfers)) // For each Tied Loser there is at least one Tied Winner all c: Candidate | some w: Candidate | (c.outcome = TiedLoser or c.outcome = TiedSoreLoser or c.outcome = TiedEarlyLoser) implies w.outcome = TiedWinner } -- The Ballot Box one sig BallotBox { spoiltBallots: set Ballot, -- empty ballots excluded from count size: Int -- number of ballots counted } { size = #Ballot - #spoiltBallots all b: Ballot | b in spoiltBallots iff #b.preferences = 0 } -- An Electoral Constituency one sig Election { seats: Int, -- number of seats to be filled in this election constituencySeats: Int, -- full number of seats in this constituency method: Method } { 0 < seats and seats <= constituencySeats seats < #Candidate } -- Version Control for changes to model one sig Version { year, month, day: Int } { year = 11 month = 02 day = 14 }
-- (c) 2010-2011, Dermot Cochran, IT University of Copenhagen -- http://www.kindsoftware.com/about/people/dc -- http://www.itu.dk/people/dero module Voting open util/integer -- Note that all axioms should be expressed as facts appended to signatures -- Standalone facts will be ignored by the API, but not by the analyser /* There are four winner-outcomes and six loser-outcomes: Winner: (W1) elected in the first round of counting either by quota or plurality, QuotaWinner: (W2) elected with transfers from another candidate (STV only), CompromiseWinner: (W3) elected on the last round of counting without quota (STV only), TiedWinner: (W4) elected by tie breaker, TiedLoser: (L1) loses only by tie breaker but reaches the threshold, Loser: (L2) defeated on last round but reaches the minimum threshold of votes, TiedEarlyLoser: (L3) reaches threshold but eliminated by tie breaker (STV only), EarlyLoser: (L4) reaches threshold but is eliminated before last round (STV only), TiedSoreLoser: (L5) loses only by tie breaker but does not reach threshold, SoreLoser: (L6) does not even reach the mimimum threshold of votes. */ enum Event {Winner, QuotaWinner, CompromiseWinner, TiedWinner, TiedLoser, Loser, TiedEarlyLoser, EarlyLoser, TiedSoreLoser, SoreLoser} enum Method {Plurality, STV} -- An individual person standing for election sig Candidate { votes: set Ballot, -- First preference ballots assigned to this candidate transfers: set Ballot, -- Ballots received by transfer from another candidate surplus: set Ballot, -- Ballots given to another candidate (on election or elimination) outcome: Event } { no b: Ballot | b in votes & transfers all b: Ballot | b in votes + transfers implies this in b.assignees surplus in votes + transfers Election.method = Plurality implies #surplus = 0 and #transfers = 0 0 < #transfers implies Election.method = STV outcome = Winner and Election.method = STV implies Scenario.quota + #surplus = #votes outcome = Winner implies #transfers = 0 outcome = QuotaWinner implies surplus in transfers outcome = QuotaWinner implies Scenario.quota + #surplus = #votes + #transfers all b: Ballot | b in votes implies this in b.assignees 0 < #surplus implies (outcome = Winner or outcome = QuotaWinner) (outcome = EarlyLoser or outcome = TiedEarlyLoser) iff (this in Scenario.eliminated and not (#votes + #transfers < Scenario.threshold)) // All non-sore losers are above the threshold outcome = TiedLoser implies Scenario.threshold < #votes + #transfers outcome = Loser implies Scenario.threshold < #votes + #transfers outcome = EarlyLoser implies Scenario.threshold < #votes + #transfers outcome = TiedEarlyLoser implies Scenario.threshold < #votes + #transfers // Plurality outcomes Election.method = Plurality implies (outcome = Loser or outcome = SoreLoser or outcome = Winner or outcome = TiedWinner or outcome = TiedLoser or outcome = TiedSoreLoser) // PR-STV Winner has at least a quota of first preference votes (Election.method = STV and outcome = Winner) implies Scenario.quota <= #votes // Quota Winner has a least a quota of votes after transfers outcome = QuotaWinner implies Scenario.quota <= #votes + #transfers // Quota Winner does not have a quota of first preference votes outcome = QuotaWinner implies not Scenario.quota <= #votes // Compromise winners do not have a quota of votes outcome = CompromiseWinner implies not (Scenario.quota <= #votes + #transfers) // STV Tied Winners have less than a quota of votes (Election.method = STV and outcome = TiedWinner) implies not (Scenario.quota <= #votes + #transfers) // Sore Losers have less votes than the threshold outcome = SoreLoser implies #votes + #transfers < Scenario.threshold // Tied Sore Losers have less votes than the threshold outcome = TiedSoreLoser implies #votes + #transfers < Scenario.threshold // Size of surplus for each STV Winner and Quota Winner (outcome = QuotaWinner or (outcome = Winner and Election.method = STV)) implies (#surplus = #votes + #transfers - Scenario.quota) } -- A digital or paper artifact which accurately records the intentions of the voter sig Ballot { assignees: set Candidate, -- Candidates to which this ballot has been assigned preferences: seq Candidate -- Ranking of candidates } { assignees in preferences.elems not preferences.hasDups preferences.first in assignees Election.method = Plurality implies #preferences <= 1 0 <= #preferences // First preference all c: Candidate | preferences.first = c iff this in c.votes // Second and subsequent preferences all disj donor,receiver: Candidate | (donor + receiver in assignees and this in receiver.transfers and this in donor.surplus) implies (preferences.idxOf[donor] < preferences.idxOf[receiver] and receiver in preferences.rest.elems) // All ballot transfers are associated with the last candidate to receive the transfer all disj c,d: Candidate | this in c.transfers implies c in assignees and (d not in assignees or preferences.idxOf[d] < preferences.idxOf[c]) // Transfers to next continuing candidate all disj skipped, receiving: Candidate | preferences.idxOf[skipped] < preferences.idxOf[receiving] and receiving in assignees and (not skipped in assignees) implies (skipped in Scenario.eliminated or skipped.outcome = Winner or skipped.outcome = QuotaWinner) } -- An election result one sig Scenario { losers: set Candidate, winners: set Candidate, eliminated: set Candidate, -- Early and Sore Losers under STV rules threshold: Int, -- Minimum number of votes for a Loser or Early Loser quota: Int, -- Minimum number of votes for a STV Winner or Quota Winner fullQuota: Int -- Quota if all constituency seats were vacant } { all c: Candidate | c in winners + losers #winners = Election.seats no c: Candidate | c in losers & winners 0 < #losers all w: Candidate | all l: Candidate | l in losers and w in winners implies (#l.votes + #l.transfers <= #w.votes + #w.transfers) Election.method = STV implies threshold = 1 + fullQuota.div[4] eliminated in losers // All PR-STV losers have less votes than the quota all c: Candidate | (c in losers and Election.method = STV) implies #c.votes + #c.transfers < quota // Winners have more votes than all non-tied losers all disj c,d: Candidate | c in winners and (d.outcome = SoreLoser or d.outcome = EarlyLoser or d.outcome = Loser) implies (#d.votes + #d.transfers) < (#c.votes + #c.transfers) // Losers have less votes than all non-tied winners all disj c,d: Candidate | (c.outcome = CompromiseWinner or c.outcome = QuotaWinner or c.outcome = Winner) and d in losers implies #d.votes + #d.transfers < #c.votes + #c.transfers // Lowest candidate is eliminated first all disj c,d: Candidate | c in eliminated and d not in eliminated implies #c.votes + #c.transfers <= #d.votes + #d.transfers // A non-sore plurality loser must have received at least five percent of the total vote Election.method = Plurality implies threshold = 1 + BallotBox.size.div[20] // Winning outcomes all c: Candidate | c in winners iff (c.outcome = Winner or c.outcome = QuotaWinner or c.outcome = CompromiseWinner or c.outcome = TiedWinner) // Losing outcomes all c: Candidate | c in losers iff (c.outcome = Loser or c.outcome = EarlyLoser or c.outcome = SoreLoser or c.outcome = TiedLoser or c.outcome = TiedEarlyLoser or c.outcome = TiedSoreLoser) // STV election quotas Election.method = STV implies quota = 1 + BallotBox.size.div[Election.seats+1] and fullQuota = 1 + BallotBox.size.div[Election.constituencySeats + 1] Election.method = Plurality implies quota = 1 and fullQuota = 1 // All ties involve equality between at least one winner and at least one loser all w: Candidate | some l: Candidate | w.outcome = TiedWinner and (l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) implies (#l.votes + #l.transfers = #w.votes + #w.transfers) all s: Candidate | some w: Candidate | w.outcome = TiedWinner and (s.outcome = SoreLoser or s.outcome = TiedLoser or s.outcome = TiedEarlyLoser) implies (#s.votes = #w.votes) or (#s.votes + #s.transfers = #w.votes + #w.transfers) // When there is a tied sore loser then there are no non-sore losers no disj a,b: Candidate | a.outcome = TiedSoreLoser and (b.outcome = TiedLoser or b.outcome = TiedEarlyLoser or b.outcome=Loser or b.outcome=EarlyLoser) // For each Tied Winner there is a Tied Loser all w: Candidate | some l: Candidate | w.outcome = TiedWinner implies (l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) // Tied Winners and Tied Losers have an equal number of votes all disj l,w: Candidate | ((l.outcome = TiedLoser or l.outcome = TiedSoreLoser or l.outcome = TiedEarlyLoser) and w.outcome = TiedWinner) implies #w.votes + #w.transfers = #l.votes + #l.transfers // Compromise winner must have more votes than any tied winners all disj c,t: Candidate | (c.outcome = CompromiseWinner and t.outcome = TiedWinner) implies #t.votes + #t.transfers < #c.votes + #c.transfers // Winners have more votes than non-tied losers all w,l: Candidate | w.outcome = Winner and (l.outcome = Loser or l.outcome = EarlyLoser or l.outcome = SoreLoser) implies ((#l.votes < #w.votes) or (#l.votes + #l.transfers < #w.votes + #w.transfers)) // For each Tied Loser there is at least one Tied Winner all c: Candidate | some w: Candidate | (c.outcome = TiedLoser or c.outcome = TiedSoreLoser or c.outcome = TiedEarlyLoser) implies w.outcome = TiedWinner } -- The Ballot Box one sig BallotBox { spoiltBallots: set Ballot, -- empty ballots excluded from count nonTransferable: set Ballot, -- surplus ballots for which preferences are exhausted size: Int -- number of ballots counted } { size = #Ballot - #spoiltBallots all b: Ballot | b in spoiltBallots iff #b.preferences = 0 // All non-transferable ballots belong to an undistributed surplus all b: Ballot | some c: Candidate | b in nonTransferable implies b in c.surplus } -- An Electoral Constituency one sig Election { seats: Int, -- number of seats to be filled in this election constituencySeats: Int, -- full number of seats in this constituency method: Method } { 0 < seats and seats <= constituencySeats seats < #Candidate } -- Version Control for changes to model one sig Version { year, month, day: Int } { year = 11 month = 02 day = 18 }
Add concept of non-transferable ballots, as this path through the code has not been covered.
Add concept of non-transferable ballots, as this path through the code has not been covered. Incomplete - task : Coverage profiling of universal tests
Alloy
mit
GaloisInc/Votail,GaloisInc/Votail,GaloisInc/Votail
90efe81d660c504f16c2769ac870cb89c0cb80ac
illust_logic/illustlogic_not_work.als
illust_logic/illustlogic_not_work.als
// Illust Logic abstract sig Cell { color: Color, hnext: lone Cell, vnext: lone Cell } enum Color {Black, White} fun range(start, end : Cell, r: Cell -> Cell): Cell{ (start + start.^r) & (end.^(~r) + end) } pred all_black(cells : Cell, size: Int){ #cells = size all c: cells{ c.color = Black } } pred all_white(cells : Cell){ all c: cells{ c.color = White } } fun from(start: Cell, next: Cell -> Cell): Cell{ start + start.^next } one sig Cell_0_0 extends Cell {} one sig Cell_0_1 extends Cell {} one sig Cell_0_2 extends Cell {} one sig Cell_0_3 extends Cell {} one sig Cell_0_4 extends Cell {} one sig Cell_0_5 extends Cell {} one sig Cell_0_6 extends Cell {} one sig Cell_0_7 extends Cell {} one sig Cell_0_8 extends Cell {} one sig Cell_0_9 extends Cell {} one sig Cell_1_0 extends Cell {} one sig Cell_1_1 extends Cell {} one sig Cell_1_2 extends Cell {} one sig Cell_1_3 extends Cell {} one sig Cell_1_4 extends Cell {} one sig Cell_1_5 extends Cell {} one sig Cell_1_6 extends Cell {} one sig Cell_1_7 extends Cell {} one sig Cell_1_8 extends Cell {} one sig Cell_1_9 extends Cell {} one sig Cell_2_0 extends Cell {} one sig Cell_2_1 extends Cell {} one sig Cell_2_2 extends Cell {} one sig Cell_2_3 extends Cell {} one sig Cell_2_4 extends Cell {} one sig Cell_2_5 extends Cell {} one sig Cell_2_6 extends Cell {} one sig Cell_2_7 extends Cell {} one sig Cell_2_8 extends Cell {} one sig Cell_2_9 extends Cell {} one sig Cell_3_0 extends Cell {} one sig Cell_3_1 extends Cell {} one sig Cell_3_2 extends Cell {} one sig Cell_3_3 extends Cell {} one sig Cell_3_4 extends Cell {} one sig Cell_3_5 extends Cell {} one sig Cell_3_6 extends Cell {} one sig Cell_3_7 extends Cell {} one sig Cell_3_8 extends Cell {} one sig Cell_3_9 extends Cell {} one sig Cell_4_0 extends Cell {} one sig Cell_4_1 extends Cell {} one sig Cell_4_2 extends Cell {} one sig Cell_4_3 extends Cell {} one sig Cell_4_4 extends Cell {} one sig Cell_4_5 extends Cell {} one sig Cell_4_6 extends Cell {} one sig Cell_4_7 extends Cell {} one sig Cell_4_8 extends Cell {} one sig Cell_4_9 extends Cell {} one sig Cell_5_0 extends Cell {} one sig Cell_5_1 extends Cell {} one sig Cell_5_2 extends Cell {} one sig Cell_5_3 extends Cell {} one sig Cell_5_4 extends Cell {} one sig Cell_5_5 extends Cell {} one sig Cell_5_6 extends Cell {} one sig Cell_5_7 extends Cell {} one sig Cell_5_8 extends Cell {} one sig Cell_5_9 extends Cell {} one sig Cell_6_0 extends Cell {} one sig Cell_6_1 extends Cell {} one sig Cell_6_2 extends Cell {} one sig Cell_6_3 extends Cell {} one sig Cell_6_4 extends Cell {} one sig Cell_6_5 extends Cell {} one sig Cell_6_6 extends Cell {} one sig Cell_6_7 extends Cell {} one sig Cell_6_8 extends Cell {} one sig Cell_6_9 extends Cell {} one sig Cell_7_0 extends Cell {} one sig Cell_7_1 extends Cell {} one sig Cell_7_2 extends Cell {} one sig Cell_7_3 extends Cell {} one sig Cell_7_4 extends Cell {} one sig Cell_7_5 extends Cell {} one sig Cell_7_6 extends Cell {} one sig Cell_7_7 extends Cell {} one sig Cell_7_8 extends Cell {} one sig Cell_7_9 extends Cell {} one sig Cell_8_0 extends Cell {} one sig Cell_8_1 extends Cell {} one sig Cell_8_2 extends Cell {} one sig Cell_8_3 extends Cell {} one sig Cell_8_4 extends Cell {} one sig Cell_8_5 extends Cell {} one sig Cell_8_6 extends Cell {} one sig Cell_8_7 extends Cell {} one sig Cell_8_8 extends Cell {} one sig Cell_8_9 extends Cell {} one sig Cell_9_0 extends Cell {} one sig Cell_9_1 extends Cell {} one sig Cell_9_2 extends Cell {} one sig Cell_9_3 extends Cell {} one sig Cell_9_4 extends Cell {} one sig Cell_9_5 extends Cell {} one sig Cell_9_6 extends Cell {} one sig Cell_9_7 extends Cell {} one sig Cell_9_8 extends Cell {} one sig Cell_9_9 extends Cell {} fact matrix_adj { Cell_0_0.vnext = Cell_0_1 Cell_0_1.vnext = Cell_0_2 Cell_0_2.vnext = Cell_0_3 Cell_0_3.vnext = Cell_0_4 Cell_0_4.vnext = Cell_0_5 Cell_0_5.vnext = Cell_0_6 Cell_0_6.vnext = Cell_0_7 Cell_0_7.vnext = Cell_0_8 Cell_0_8.vnext = Cell_0_9 no Cell_0_9.vnext Cell_1_0.vnext = Cell_1_1 Cell_1_1.vnext = Cell_1_2 Cell_1_2.vnext = Cell_1_3 Cell_1_3.vnext = Cell_1_4 Cell_1_4.vnext = Cell_1_5 Cell_1_5.vnext = Cell_1_6 Cell_1_6.vnext = Cell_1_7 Cell_1_7.vnext = Cell_1_8 Cell_1_8.vnext = Cell_1_9 no Cell_1_9.vnext Cell_2_0.vnext = Cell_2_1 Cell_2_1.vnext = Cell_2_2 Cell_2_2.vnext = Cell_2_3 Cell_2_3.vnext = Cell_2_4 Cell_2_4.vnext = Cell_2_5 Cell_2_5.vnext = Cell_2_6 Cell_2_6.vnext = Cell_2_7 Cell_2_7.vnext = Cell_2_8 Cell_2_8.vnext = Cell_2_9 no Cell_2_9.vnext Cell_3_0.vnext = Cell_3_1 Cell_3_1.vnext = Cell_3_2 Cell_3_2.vnext = Cell_3_3 Cell_3_3.vnext = Cell_3_4 Cell_3_4.vnext = Cell_3_5 Cell_3_5.vnext = Cell_3_6 Cell_3_6.vnext = Cell_3_7 Cell_3_7.vnext = Cell_3_8 Cell_3_8.vnext = Cell_3_9 no Cell_3_9.vnext Cell_4_0.vnext = Cell_4_1 Cell_4_1.vnext = Cell_4_2 Cell_4_2.vnext = Cell_4_3 Cell_4_3.vnext = Cell_4_4 Cell_4_4.vnext = Cell_4_5 Cell_4_5.vnext = Cell_4_6 Cell_4_6.vnext = Cell_4_7 Cell_4_7.vnext = Cell_4_8 Cell_4_8.vnext = Cell_4_9 no Cell_4_9.vnext Cell_5_0.vnext = Cell_5_1 Cell_5_1.vnext = Cell_5_2 Cell_5_2.vnext = Cell_5_3 Cell_5_3.vnext = Cell_5_4 Cell_5_4.vnext = Cell_5_5 Cell_5_5.vnext = Cell_5_6 Cell_5_6.vnext = Cell_5_7 Cell_5_7.vnext = Cell_5_8 Cell_5_8.vnext = Cell_5_9 no Cell_5_9.vnext Cell_6_0.vnext = Cell_6_1 Cell_6_1.vnext = Cell_6_2 Cell_6_2.vnext = Cell_6_3 Cell_6_3.vnext = Cell_6_4 Cell_6_4.vnext = Cell_6_5 Cell_6_5.vnext = Cell_6_6 Cell_6_6.vnext = Cell_6_7 Cell_6_7.vnext = Cell_6_8 Cell_6_8.vnext = Cell_6_9 no Cell_6_9.vnext Cell_7_0.vnext = Cell_7_1 Cell_7_1.vnext = Cell_7_2 Cell_7_2.vnext = Cell_7_3 Cell_7_3.vnext = Cell_7_4 Cell_7_4.vnext = Cell_7_5 Cell_7_5.vnext = Cell_7_6 Cell_7_6.vnext = Cell_7_7 Cell_7_7.vnext = Cell_7_8 Cell_7_8.vnext = Cell_7_9 no Cell_7_9.vnext Cell_8_0.vnext = Cell_8_1 Cell_8_1.vnext = Cell_8_2 Cell_8_2.vnext = Cell_8_3 Cell_8_3.vnext = Cell_8_4 Cell_8_4.vnext = Cell_8_5 Cell_8_5.vnext = Cell_8_6 Cell_8_6.vnext = Cell_8_7 Cell_8_7.vnext = Cell_8_8 Cell_8_8.vnext = Cell_8_9 no Cell_8_9.vnext Cell_9_0.vnext = Cell_9_1 Cell_9_1.vnext = Cell_9_2 Cell_9_2.vnext = Cell_9_3 Cell_9_3.vnext = Cell_9_4 Cell_9_4.vnext = Cell_9_5 Cell_9_5.vnext = Cell_9_6 Cell_9_6.vnext = Cell_9_7 Cell_9_7.vnext = Cell_9_8 Cell_9_8.vnext = Cell_9_9 no Cell_9_9.vnext Cell_0_0.hnext = Cell_1_0 Cell_1_0.hnext = Cell_2_0 Cell_2_0.hnext = Cell_3_0 Cell_3_0.hnext = Cell_4_0 Cell_4_0.hnext = Cell_5_0 Cell_5_0.hnext = Cell_6_0 Cell_6_0.hnext = Cell_7_0 Cell_7_0.hnext = Cell_8_0 Cell_8_0.hnext = Cell_9_0 no Cell_9_0.hnext Cell_0_1.hnext = Cell_1_1 Cell_1_1.hnext = Cell_2_1 Cell_2_1.hnext = Cell_3_1 Cell_3_1.hnext = Cell_4_1 Cell_4_1.hnext = Cell_5_1 Cell_5_1.hnext = Cell_6_1 Cell_6_1.hnext = Cell_7_1 Cell_7_1.hnext = Cell_8_1 Cell_8_1.hnext = Cell_9_1 no Cell_9_1.hnext Cell_0_2.hnext = Cell_1_2 Cell_1_2.hnext = Cell_2_2 Cell_2_2.hnext = Cell_3_2 Cell_3_2.hnext = Cell_4_2 Cell_4_2.hnext = Cell_5_2 Cell_5_2.hnext = Cell_6_2 Cell_6_2.hnext = Cell_7_2 Cell_7_2.hnext = Cell_8_2 Cell_8_2.hnext = Cell_9_2 no Cell_9_2.hnext Cell_0_3.hnext = Cell_1_3 Cell_1_3.hnext = Cell_2_3 Cell_2_3.hnext = Cell_3_3 Cell_3_3.hnext = Cell_4_3 Cell_4_3.hnext = Cell_5_3 Cell_5_3.hnext = Cell_6_3 Cell_6_3.hnext = Cell_7_3 Cell_7_3.hnext = Cell_8_3 Cell_8_3.hnext = Cell_9_3 no Cell_9_3.hnext Cell_0_4.hnext = Cell_1_4 Cell_1_4.hnext = Cell_2_4 Cell_2_4.hnext = Cell_3_4 Cell_3_4.hnext = Cell_4_4 Cell_4_4.hnext = Cell_5_4 Cell_5_4.hnext = Cell_6_4 Cell_6_4.hnext = Cell_7_4 Cell_7_4.hnext = Cell_8_4 Cell_8_4.hnext = Cell_9_4 no Cell_9_4.hnext Cell_0_5.hnext = Cell_1_5 Cell_1_5.hnext = Cell_2_5 Cell_2_5.hnext = Cell_3_5 Cell_3_5.hnext = Cell_4_5 Cell_4_5.hnext = Cell_5_5 Cell_5_5.hnext = Cell_6_5 Cell_6_5.hnext = Cell_7_5 Cell_7_5.hnext = Cell_8_5 Cell_8_5.hnext = Cell_9_5 no Cell_9_5.hnext Cell_0_6.hnext = Cell_1_6 Cell_1_6.hnext = Cell_2_6 Cell_2_6.hnext = Cell_3_6 Cell_3_6.hnext = Cell_4_6 Cell_4_6.hnext = Cell_5_6 Cell_5_6.hnext = Cell_6_6 Cell_6_6.hnext = Cell_7_6 Cell_7_6.hnext = Cell_8_6 Cell_8_6.hnext = Cell_9_6 no Cell_9_6.hnext Cell_0_7.hnext = Cell_1_7 Cell_1_7.hnext = Cell_2_7 Cell_2_7.hnext = Cell_3_7 Cell_3_7.hnext = Cell_4_7 Cell_4_7.hnext = Cell_5_7 Cell_5_7.hnext = Cell_6_7 Cell_6_7.hnext = Cell_7_7 Cell_7_7.hnext = Cell_8_7 Cell_8_7.hnext = Cell_9_7 no Cell_9_7.hnext Cell_0_8.hnext = Cell_1_8 Cell_1_8.hnext = Cell_2_8 Cell_2_8.hnext = Cell_3_8 Cell_3_8.hnext = Cell_4_8 Cell_4_8.hnext = Cell_5_8 Cell_5_8.hnext = Cell_6_8 Cell_6_8.hnext = Cell_7_8 Cell_7_8.hnext = Cell_8_8 Cell_8_8.hnext = Cell_9_8 no Cell_9_8.hnext Cell_0_9.hnext = Cell_1_9 Cell_1_9.hnext = Cell_2_9 Cell_2_9.hnext = Cell_3_9 Cell_3_9.hnext = Cell_4_9 Cell_4_9.hnext = Cell_5_9 Cell_5_9.hnext = Cell_6_9 Cell_6_9.hnext = Cell_7_9 Cell_7_9.hnext = Cell_8_9 Cell_8_9.hnext = Cell_9_9 no Cell_9_9.hnext } fact { let next = hnext { some c1: from[Cell_0_0, next] { all_white[range[from[Cell_0_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 3] all_white[c2.^next] } } some c1: from[Cell_0_1, next] { all_white[range[from[Cell_0_1, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 2] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 2] all_white[c2.^next] } } } } some c1: from[Cell_0_2, next] { all_white[range[from[Cell_0_2, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 1] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 1] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 1] all_white[c2.^next] } } } } } } some c1: from[Cell_0_3, next] { all_white[range[from[Cell_0_3, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 3] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 3] all_white[c2.^next] } } } } some c1: from[Cell_0_4, next] { all_white[range[from[Cell_0_4, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 5] all_white[c2.^next] } } some c1: from[Cell_0_5, next] { all_white[range[from[Cell_0_5, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } some c1: from[Cell_0_6, next] { all_white[range[from[Cell_0_6, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } some c1: from[Cell_0_7, next] { all_white[range[from[Cell_0_7, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } some c1: from[Cell_0_8, next] { all_white[range[from[Cell_0_8, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } some c1: from[Cell_0_9, next] { all_white[range[from[Cell_0_9, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 5] all_white[c2.^next] } } } let next = vnext { some c1: from[Cell_0_0, next] { all_white[range[from[Cell_0_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 4] all_white[c2.^next] } } some c1: from[Cell_1_0, next] { all_white[range[from[Cell_1_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 6] all_white[c2.^next] } } some c1: from[Cell_2_0, next] { all_white[range[from[Cell_2_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } some c1: from[Cell_3_0, next] { all_white[range[from[Cell_3_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 9] all_white[c2.^next] } } some c1: from[Cell_4_0, next] { all_white[range[from[Cell_4_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 2] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 7] all_white[c2.^next] } } } } some c1: from[Cell_5_0, next] { all_white[range[from[Cell_5_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 1] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 6] all_white[c2.^next] } } } } some c1: from[Cell_6_0, next] { all_white[range[from[Cell_6_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 2] some c1: c2.next.^next { all_white[range[c2.next.^next, c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 4] all_white[c2.^next] } } } } some c1: from[Cell_7_0, next] { all_white[range[from[Cell_7_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 3] all_white[c2.^next] } } some c1: from[Cell_8_0, next] { all_white[range[from[Cell_8_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 1] all_white[c2.^next] } } some c1: from[Cell_9_0, next] { all_white[range[from[Cell_9_0, next], c1.~next, next]] some c2: c1.^next { all_black[range[c1, c2, next], 2] all_white[c2.^next] } } } } run{} for 1 but 5 int
add first version (not work)
add first version (not work)
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
55acd93d179d93478ac5d555680fba9179979ad9
Perterson.als
Perterson.als
open util/ordering[Time] sig Time {} one sig Memory { turn: Int -> Time, flag: Int -> Int -> Time }{ all t: Time { one flag[0].t one flag[1].t no flag[Int - 0 - 1].t } } one sig PC { proc: Int -> Int -> Time }{ all t: Time { one proc[0].t one proc[1].t no proc[Int - 0 - 1].t } } fact { // 最初はメモリはみんな0 let t = first { Memory.turn.t = 0 Memory.flag[0].t = 0 Memory.flag[1].t = 0 // 最初はプログラムカウンタは0 PC.proc[0].t = 0 PC.proc[1].t = 0 } } pred store(t: Time, target: univ -> Time, value: univ){ one value target.t = value } pred must_wait(t: Time, pid: Int){ let other = (0 + 1) - pid { Memory.flag[other].t = 1 // otherがwaitしている Memory.turn.t = other // otherが優先権を持っている } } pred no_change(t: Time, changable: univ -> Time){ changable.t = changable.(t.prev) } pred step(t: Time) { // 各時刻でどちらかのプロセスが1命令実行する some pid: (0 + 1) { let pc = PC.proc[pid].(t.prev), nextpc = PC.proc[pid].t, other = (0 + 1) - pid { (pc = 0) => { // flag[0] = 1 store[t, Memory.flag[pid], 1] nextpc = plus[pc, 1] no_change[t, Memory.turn] } (pc = 1) => { // flag[0] = 1 store[t, Memory.turn, other] nextpc = plus[pc, 1] no_change[t, Memory.flag[pid]] } (pc = 2) => { // while( flag[1] && turn == 1 ); must_wait[t, pid] => { nextpc = pc }else{ nextpc = plus[pc, 1] } no_change[t, Memory.turn] no_change[t, Memory.flag[pid]] } (pc = 3) => { // flag[0] = 0 store[t, Memory.flag[pid], 0] nextpc = 0 no_change[t, Memory.turn] } // no change no_change[t, PC.proc[other]] no_change[t, Memory.flag[other]] } } } check MutualExclusion { no t: Time { PC.proc[0].t = 3 PC.proc[1].t = 3 } } for 25 Time check BoundedWaiting { no t: Time, pid: Int { PC.proc[pid].t = 2 PC.proc[pid].(t.next) = 2 PC.proc[pid].(t.next.next) = 2 PC.proc[pid].(t.next.next.next) = 2 PC.proc[pid].(t.next.next.next.next) = 2 } } for 7 Time fact { all t: Time - first { step[t] } } run { } for exactly 20 Time
open util/ordering[Time] sig Time {} one sig Memory { turn: Int -> Time, flag: Int -> Int -> Time }{ all t: Time { one flag[0].t one flag[1].t no flag[Int - 0 - 1].t } } one sig PC { proc: Int -> Int -> Time, current_pid: Int -> Time }{ all t: Time { one proc[0].t one proc[1].t no proc[Int - 0 - 1].t } } fact { // 最初はメモリはみんな0 let t = first { Memory.turn.t = 0 Memory.flag[0].t = 0 Memory.flag[1].t = 0 // 最初はプログラムカウンタは0 PC.proc[0].t = 0 PC.proc[1].t = 0 } } pred store(t: Time, target: univ -> Time, value: univ){ one value target.t = value } pred must_wait(t: Time, pid: Int){ let other = (0 + 1) - pid { Memory.flag[other].t = 1 // otherがwaitしている Memory.turn.t = other // otherが優先権を持っている } } pred no_change(t: Time, changable: univ -> Time){ changable.t = changable.(t.prev) } pred step(t: Time) { // 各時刻でどちらかのプロセスが1命令実行する some pid: (0 + 1) { PC.current_pid.t = pid let pc = PC.proc[pid].(t.prev), nextpc = PC.proc[pid].t, other = (0 + 1) - pid { (pc = 0) => { // flag[0] = 1 store[t, Memory.flag[pid], 1] nextpc = plus[pc, 1] no_change[t, Memory.turn] } (pc = 1) => { // flag[0] = 1 store[t, Memory.turn, other] nextpc = plus[pc, 1] no_change[t, Memory.flag[pid]] } (pc = 2) => { // while( flag[1] && turn == 1 ); must_wait[t, pid] => { nextpc = pc }else{ nextpc = plus[pc, 1] } no_change[t, Memory.turn] no_change[t, Memory.flag[pid]] } (pc = 3) => { // flag[0] = 0 store[t, Memory.flag[pid], 0] nextpc = 0 no_change[t, Memory.turn] } // no change no_change[t, PC.proc[other]] no_change[t, Memory.flag[other]] } } } check MutualExclusion { no t: Time { PC.proc[0].t = 3 PC.proc[1].t = 3 } } for 15 Time check BoundedWaiting_Bad { no t: Time, pid: Int { PC.proc[pid].t = 2 PC.proc[pid].(t.next) = 2 PC.proc[pid].(t.next.next) = 2 PC.proc[pid].(t.next.next.next) = 2 PC.proc[pid].(t.next.next.next.next) = 2 } } for 15 Time check BoundedWaiting { no t, t': Time, pid: Int { let range = Time - t.prevs - t'.nexts { // あるプロセスがずっと2(ロック待ち)で all t'': range | PC.proc[pid].t'' = 2 // その間、もう片方のプロセスが2回以上3(クリティカルセクション)を実行 #{t'': range | PC.proc[PC.current_pid.t''].t'' = 3 } >= 2 } } } for 15 Time fact { all t: Time - first { step[t] } } run { } for exactly 20 Time
add correct assertion
add correct assertion
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
5f7c91b7de64c8a2ca447af29382ed60da23b254
etude16.als
etude16.als
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, } abstract sig Man, Woman extends Person {} enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred step (t, t': Time) { some disj p1 : Man, p2 : Woman { {{ // marrige p1.state.t = NotMarried and p2.state.t = NotMarried p1.state.t' = Married and p2.state.t' = Married } or { // divorce p1.state.t = Married and p2.state.t = Married p1.state.t' = NotMarried and p2.state.t' = NotMarried }} // others don't change their state let others = (Person - p1 - p2) { others.state.t = others.state.t' } } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for 3 Person, 5 Time
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, } abstract sig Man, Woman extends Person {} enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred change_state ( p1 : Man, p2 : Woman, t, t': Time, before, after : State){ p1.state.t = before p2.state.t = before p1.state.t' = after p2.state.t' = after // others don't change their state all other: (Person - p1 - p2) { other.state.t = other.state.t' } } pred step (t, t': Time) { some disj p1 : Man, p2 : Woman { change_state[p1, p2, t, t', NotMarried, Married] or change_state[p1, p2, t, t', Married, NotMarried] } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 4 Person, 4 Time
refactor and fix bug
refactor and fix bug
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
fadf0bf492792210518a9c9db6dc8d80a599b71a
tutorials/2017/thursday/tutorial_questions.als
tutorials/2017/thursday/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
Copy Alloy exercise for Thursday's tutorial
Copy Alloy exercise for Thursday's tutorial
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
a66c8712251409e409354d628e5a8be436f1e103
alloy/alloy_lecture_example.als
alloy/alloy_lecture_example.als
// A file system object in the file system sig FSObject { parent: lone Dir } // A directory in the file system sig Dir extends FSObject { contents: set FSObject } // A file in the file system sig File extends FSObject { } // There exists a root one sig Root extends Dir { } { no parent } //All file system objects are either files or directories fact { File + Dir = FSObject } // Every directory is the parent of each of its contents fact { all d: Dir, o: d.contents | o.parent = d } // Every file system object is in the hereditary contents of the root fact { all o: FSObject | o in Root.*contents } // Existence of a model with 3 Dirs and 3 Files pred ismodel [] { #Dir>2 && #File>2 } run ismodel for 6 // Check to see that file systems are acyclic assert acyclic { no d: Dir | d in d.^contents } check acyclic for 6 // This example is developed much further in the on-line Alloy tutorial: // http://alloy.mit.edu/alloy/tutorials/online/
// A file system object in the file system // Every object has at most one parent sig FSObject { parent: lone Dir } // The set of directories in the file system sig Dir extends FSObject { contents: set FSObject } // The set of files in the file system sig File extends FSObject { } // There exists a unique root one sig Root extends Dir { } { no parent } //All file system objects are either files or directories fact { File + Dir = FSObject } // Every directory is the parent of each of its contents fact { all d: Dir, o: d.contents | o.parent = d } // Property asserting a model has at least 3 Dirs and 3 Files pred ismodel { #Dir>2 && #File>2 } // Command to find a model of size at most 6 run ismodel for 6 // Comment out the above command to proceed futher // Uncomment the fact below to implement the axiom that // every file system object is in the hereditary contents of the root // fact { all o: FSObject | o in Root.*contents } // Check to see that file systems are acyclic assert acyclic { no d: Dir | d in d.^contents } check acyclic for 8 // This example is developed much further in the on-line Alloy tutorial: // http://alloy.mit.edu/alloy/tutorials/online/
Update lecture example
Update lecture example
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
5905888708041e550b4601f58fac68fd12198056
alloy/tutorial_questions.als
alloy/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate findModel below expresses that there exist black, yellow and final states pred findModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // The run command below checks to see if the predicate can be satisfied in scope 1 run findModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which findModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $findModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run findModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if its successors are empty. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run findModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors some sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate findModel below expresses that there exist black, yellow and final states pred findModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // The run command below checks to see if the predicate can be satisfied in scope 1 run findModel for 4 // *** EXERCISE 1 *** // (a) Find the smallest scope in which findModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $findModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run findModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if its successors are empty. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run findModel // in suitable scope and use the Next button to again explore the range of models available fact { {s: State | no s.successors} in Final} // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state fact { State in Initial.*successors } // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node fact { all s: Black | Initial in s.^successors } //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state fact { all s: Yellow | some Final & s.^successors } // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { all s: State | some Final & s.*successors } // Modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 4 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.) fact { no Final & Black.^(successors - (State -> Initial)) } // Additional requirement: a yellow state has a successor as a final state fact { some Yellow & successors.Final }
Add solutions from the tutorial
Add solutions from the tutorial
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
a599bbe13c5538619b3cb7884745a89b13e395fa
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region {} sig Col extends Region { cell: Row -> Cell } sig Row extends Region {} enum Cell { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- about rows pred blackHeadInRow (c: Col, r: Row) { c in first or cell[c.prev, r] in White cell[c, r] in Black } fun headsInRow (r: Row): set Col { { c: Col | blackHeadInRow[c, r] } } fact noOtherHeadsInRow { no c: Col, r: Row | c not in headsInRow[r] and blackHeadInRow[c, r] } pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Row (i: Int): Row { {r: Row | #(r.prevs) = i} } fun Row2Int (r: Row): Int { #(r.prevs) } pred rowHint (j: Int, sizes: seq Int) { let r = Int2Row[j] | some cs: seq Col { #sizes = #cs headsSeqInRow [r, cs] all i: sizes.inds | let start = cs [i], end = Int2Col [plus [Col2Int [start], minus[sizes [i], 1] ]] { some end all c: start.*cols/next - end.^cols/next | cell [c, r] in Black no end.next or cell [end.next, r] in White } } } -- about cols pred blackHeadInCol (c: Col, r: Row) { r in first or cell[c, r.prev] in White cell[c, r] in Black } fun headsInCol (c: Col): set Row { { r: Row | blackHeadInCol[c, r] } } fact noOtherHeadsInCol { no c: Col, r: Row | r not in headsInCol[c] and blackHeadInCol[c, r] } pred headsSeqInCol (c: Col, s: seq Row) { s.elems = headsInCol[c] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Col (i: Int): Col { {c: Col | #(c.prevs) = i} } fun Col2Int (c: Col): Int { #(c.prevs) } pred colHint (j: Int, sizes: seq Int) { let c = Int2Col[j] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds | let start = rs [i], end = Int2Row [plus [Row2Int [start], minus[sizes [i], 1] ]] { some end all r: start.*rows/next - end.^rows/next | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region {} sig Col extends Region { cell: Row -> Cell } sig Row extends Region {} enum Cell { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- about rows pred blackHeadInRow (c: Col, r: Row) { c in first or cell[c.prev, r] in White cell[c, r] in Black } fun headsInRow (r: Row): set Col { { c: Col | blackHeadInRow[c, r] } } fact noOtherHeadsInRow { no c: Col, r: Row | c not in headsInRow[r] and blackHeadInRow[c, r] } pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Row (i: Int): Row { {r: Row | #(r.prevs) = i} } fun Row2Int (r: Row): Int { #(r.prevs) } pred rowHint (j: Int, sizes: seq Int) { let r = Int2Row[j] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Int2Col [plus [Col2Int [start], minus[sizes [i], 1] ]] { // endが存在する some end // startからendまで全部黒 all c: start.*cols/next - end.^cols/next | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } -- about cols // c, rがブロックの先頭であるかどうか pred blackHeadInCol (c: Col, r: Row) { // 最初のRowであるか、または前のRowのセルが白い r in first or cell[c, r.prev] = White // このセルは黒い cell[c, r] in Black } // Col cの中の、ブロックの頭であるRowの集合 fun headsInCol (c: Col): set Row { { r: Row | blackHeadInCol[c, r] } } fact noOtherHeadsInCol { no c: Col, r: Row | r not in headsInCol[c] and blackHeadInCol[c, r] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = headsInCol[c] // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Col (i: Int): Col { {c: Col | #(c.prevs) = i} } fun Col2Int (c: Col): Int { #(c.prevs) } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } pred colHint (j: Int, sizes: seq Int) { let c = Int2Col[j] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Int2Row [plus [Row2Int [start], minus[sizes [i], 1] ]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
add comment etc
add comment etc
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
06f13901dc94e0f832eecdd79936f0d6d8cce84a
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } -- about rows or cols fact noOtherHeadsInRow { no c: Col, r: Row { c not in { c: Col | is_black_head[c, r, cols/prev]} is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in { r: Row | is_black_head[c, r, rows/prev]} is_black_head[c, r, rows/prev] } } pred headsSeqInRow (r: Row, s: seq Col) { sorted[ { c: Col | is_black_head[c, r, cols/prev]}.index, s.index] } pred headsSeqInCol (c: Col, s: seq Row) { sorted[ { r: Row | is_black_head[c, r, rows/prev]}.index, s.index] } pred sorted(xs: Int, s: seq Int){ // sの要素はxsと同一 s.elems = xs // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } pred sorted(xs: Int, s: seq Int){ // sの要素はxsと同一 s.elems = xs // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } -- about rows or cols pred headsSeqInRow (r: Row, s: seq Col) { sorted[ { c: Col | is_black_head[c, r, cols/prev]}.index, s.index] } pred headsSeqInCol (c: Col, s: seq Row) { sorted[ { r: Row | is_black_head[c, r, rows/prev]}.index, s.index] } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
remove noOtherHeadsIn* because they are not used
remove noOtherHeadsIn* because they are not used
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
db5973dec243e177440b5f4cefbbf85acaa47ab1
tutorials/2017/thursday/tutorial_questions.als
tutorials/2017/thursday/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors some sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 run nontrivModel for 5 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ fact { all q: State - Final | some q.successors } // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state fact { State in Initial.*successors } // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node fact { Black in ^successors.Initial } //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state fact { Yellow in ^successors.Final } // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { State in *successors.Final } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 5 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.) fact { no Black.^(successors - (State -> Initial)) & Final } // Aditional condition: no final state is successor to the initial state fact { not Initial in successors.Final }
Add Thursday's solutions
Add Thursday's solutions
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
14a02557c59fb8630e6529266520f24b99bbc9dc
etude16.als
etude16.als
open util/ordering[Time] sig Time {} sig Person { state: State -> Time, } enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred step (t, t': Time) { some disj p1, p2 : Person { { // marrige p1.state.t = NotMarried and p2.state.t = NotMarried p1.state.t' = Married and p2.state.t' = Married } or { // divorce p1.state.t = Married and p2.state.t = Married p1.state.t' = NotMarried and p2.state.t' = NotMarried } } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 3 Person, 5 Time
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, } abstract sig Man, Woman extends Person {} enum State {Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t = NotMarried } pred step (t, t': Time) { some disj p1, p2 : Person { { // marrige p1.state.t = NotMarried and p2.state.t = NotMarried p1.state.t' = Married and p2.state.t' = Married } or { // divorce p1.state.t = Married and p2.state.t = Married p1.state.t' = NotMarried and p2.state.t' = NotMarried } } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 3 Person, 5 Time
add names
add names
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
59e841b4220a473fc44fa0343818bd4298ee23ad
alloy/simple_maze.als
alloy/simple_maze.als
module maze_maker/simple_maze open util/ordering[Col] as cols open util/ordering[Row] as rows // 迷路のサイズ fun height : Int { 10 } fun width: Int { 10 } // 隣接する Cell fun adjacent (col: Col, row: Row) : Col -> Row { col.prev -> row + col.next -> row + col -> row.prev + col -> row.next } sig Col { paths: Row -> Col -> Row } { // 自分自身との接続はなし all row: Row | no (this -> row) & row.paths // 接続先は必ず隣接する(4近傍の) Cell all row: Row | row.paths in adjacent[this, row] } sig Row {} one sig entrance_x extends Col {} one sig entrance_y extends Row {} one sig exit_x extends Col {} one sig exit_y extends Row {} // 位置が盤の端 pred edge (col: Col, row: Row) { col = cols/first or col = cols/last or row = rows/first or row = rows/last } fact { // 全ての位置が paths に含まれている all col: Col, row: Row | (col -> row) in paths[Col, Row] // paths の連結は反射的 all c1, c2: Col, r1, r2: Row | (c1 -> r1 -> c2 -> r2) in paths => (c2 -> r2 -> c1 -> r1) in paths // 入口と出口はいずれも盤面の端に位置する edge[entrance_x, entrance_y] edge[exit_x, exit_y] } run { #Col = width[] #Row = height[] } for 10
module maze_maker/simple_maze open util/ordering[Col] as cols open util/ordering[Row] as rows // 隣接する Cell fun adjacent (col: Col, row: Row) : Col -> Row { col.prev -> row + col.next -> row + col -> row.prev + col -> row.next } sig Col { paths: Row -> Col -> Row } { // 自分自身との接続はなし all row: Row | no (this -> row) & row.paths // 接続先は必ず隣接する(4近傍の) Cell all row: Row | row.paths in adjacent[this, row] } sig Row {} one sig entrance_x extends Col {} one sig entrance_y extends Row {} one sig exit_x extends Col {} one sig exit_y extends Row {} // 位置が盤の端 pred edge (col: Col, row: Row) { col = cols/first or col = cols/last or row = rows/first or row = rows/last } fact { // 全ての位置が paths に含まれている all col: Col, row: Row | (col -> row) in paths[Col, Row] // paths の連結は反射的 all c1, c2: Col, r1, r2: Row | (c1 -> r1 -> c2 -> r2) in paths => (c2 -> r2 -> c1 -> r1) in paths // 入口と出口はいずれも盤面の端に位置する edge[entrance_x, entrance_y] edge[exit_x, exit_y] } run {} for exactly 10 Col, exactly 10 Row
use Scope to specify maze's size.
use Scope to specify maze's size.
Alloy
mit
nagachika/maze_maker,nagachika/maze_maker,nagachika/maze_maker
fe9e0ce63d7ff6272b2c01ac17124a5e99e9dbf5
manual/copying.als
manual/copying.als
Applied Logic Systems, Inc.'s "Copying ALS" This is the file "Copying ALS". It applies to files which are marked Copyright (c) xxxx Applied Logic Systems, Inc. Distribution rights per Copying ALS This document is Copyright (c) 1996-9 Applied Logic Systems, Inc., and may be distributed verbatim, but changing it is not permitted. You may freely copy, modify, and distribute any source file marked Copyright (c) xxxx Applied Logic Systems, Inc. Distribution rights per Copying ALS subject to the following restrictions: i) You must preserve intact any and all existing copyright and/or authorship information in any of the files you redistribute. If you modify a source file, you must add a notice to that effect to the authorship information in the source file. If you substantially merge one of the files into another file, you must transfer the existing copyright and/or authorship information to the newly merged file. ii) You may freely incorporate these files in a binary application distributed under the terms of the "ALS Binary License", either bound into the application, or as "obp" files to be loaded. Your are strongly encouraged to abide by the spirit of the free software concept, and to a) Provide authorship attributions as appropriate in your printed and/or on-line documentation, and on your start-up screen(s) if this is appropriate, and to b) Provide sufficient information so that the recepients of your programs can obtain the sources to the programs you incorporated. iii) No act of distribution and/or incorporation of any of these files, in whole or in part, will give you proprietary rights or ownership over these files, in whole or in part. Any attempt to exercise such rights will automatically abrogate your rights under this license. WARRANTY This program or code file is provided "as is " without warranty of any kind, either expressed or implied, including, but not limited to, implied warranties of merchantability and fitness for a particular purpose. You assume the entire risk as to the selection of this program to achieve your intended results and for the installation, use, performance, and results obtained through the use of this program or code.
Applied Logic Systems, Inc.'s "Copying ALS" This is the file "Copying ALS". It applies to files which are marked Copyright (c) xxxx Applied Logic Systems, Inc. Distribution rights per Copying ALS This document is Copyright (c) 1996-9 Applied Logic Systems, Inc., and may be distributed verbatim, but changing it is not permitted. You may freely copy, modify, and distribute any source file marked Copyright (c) xxxx Applied Logic Systems, Inc. Distribution rights per Copying ALS subject to the following restrictions: i) You must preserve intact any and all existing copyright and/or authorship information in any of the files you redistribute. If you modify a source file, you must add a notice to that effect to the authorship information in the source file. If you substantially merge one of the files into another file, you must transfer the existing copyright and/or authorship information to the newly merged file. ii) You may freely incorporate these files in a binary application distributed under the terms of the "ALS Binary License", either bound into the application, or as "obp" files to be loaded. Your are strongly encouraged to abide by the spirit of the free software concept, and to a) Provide authorship attributions as appropriate in your printed and/or on-line documentation, and on your start-up screen(s) if this is appropriate, and to b) Provide sufficient information so that the recepients of your programs can obtain the sources to the programs you incorporated. iii) No act of distribution and/or incorporation of any of these files, in whole or in part, will give you proprietary rights or ownership over these files, in whole or in part. Any attempt to exercise such rights will automatically abrogate your rights under this license. WARRANTY This program or code file is provided "as is " without warranty of any kind, either expressed or implied, including, but not limited to, implied warranties of merchantability and fitness for a particular purpose. You assume the entire risk as to the selection of this program to achieve your intended results and for the installation, use, performance, and results obtained through the use of this program or code.
Split long line
Split long line
Alloy
mit
AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog,AppliedLogicSystems/ALSProlog
9c7ddd8d5f48f30cdf4f3bfaba4359a00cc5cc45
Alloy/PowerEnjoy.als
Alloy/PowerEnjoy.als
module PowEnj //SIGNATURES sig Position { latitude:Int, //should be float longitude:Int //should be float } abstract sig User { rentedCar: one Car, //field that indicates which car the user is using at the moment payInfo: some Payment, position: one Position } fact driverIsUnique { //can’t exist two renters who rent the same car at the same time all r1,r2:Rent | (r1.Renter!=r2.Renter) => r1.rentedCar != r2.rentedCar and r1.startTime!=r2.startTime } fact applyDiscountForBattery { //if the battery at the end of the trip is at least at 50%, apply a discount //not sure if it’s possible to use this notation!! all c:Car, r:Rent | (c.battery>=50) => r.applyDiscount //alternatively, we can suppose that the attribute “isCharge” is set to a specific value for every kind of discount appliable all c:Car, r:Rent | (c.isCharge) => r.applyDiscount } fact applyDiscountForArea { //if the car at the end of trip is let in a service station, apply a discount all r:Rent, s:ServiceStation | (r.finalPosition=s.position) => r.applyDiscount } fact applyOvertax { all c:Car, r:Rent, s:ServiceStation | (!(c.isCharge)) => r.applyOvertax or ((s.position – c.position)>r.maxDistance) => r.applyOvertax } sig Rent { startTime = Int, //should be Float rentedCar: set Car, Renter: one User, applyDiscount: one User, applyOvertax: one User, carsAvailable: set Car, maxDistance: Int, //should be float initialPos: Position, finalPos: Position, passengers: set Passenger // don’t remember if the class (and consequently the signature) should exist or we decide to remove it; in this case, change Passenger with User } sig Car { user: one User, position:Position, battery: Int, plate: String }{#passengers>0} fact plateIsUnique { all c1,c2: Car | (c1 != c2) => c1.plate != c2.plate } sig Plug{} abstract sig safeArea {} sig serviceStation extends safeArea { carsToCharge: set Car, plugAvailable: set Plug, position:Position } sig Payment { transactionCode: Int, payInfo : set Payment } fact userIsUnique { all u1,u2: User | u1 != u2 => u1.email != u2.email } fact pathDriverHasAStartAndEnd { all r:Rent | (r.RentedCar) => r.InitialPosition and r.finalPosition } //30.10.2016 fact rentIfAvailable { all u:user, r:rent | r.startTime u.rentedCar in r.carsAvailable } fact noSafeAreaParkNoEndTrip { //I can terminate my trip if and only if my car’s position coincides with a parking position or a safa area position all c:Car, r:Rent, p:Parking, s:SafeArea | r.endTime <=> (c.position = p.position) or (c.position = s.position) } assert allCarsWithPosition { all c:Car | c.position } fact applyDiscountForPassNumb { //for every trip that involves a number of passengers >=3, apply a discount for the renter all r:Rent | (#r.passengers>= 3) => r.applyDiscount } assert userMustHaveAtLeastOnePaymentInfo { no u:User, p:Payment | u.payInfo not in p.payInfo }
module PowEnj //SIGNATURES sig Position { latitude:Int, //should be float longitude:Int //should be float } sig Visitor{ } sig DriverLicense{ code:String, expiration:Int, drivername:String, driversurname:String } sig User { rentedCar: one Car, //field that indicates which car the user is using at the moment payInfo: some Payment, position: one Position, name:String, surname:String, license: one DriverLicense, email:String } sig Rent { startTime = Int, //should be Float rentedCar: one Car, Renter: one User, applyDiscount: Int, applyOvertax: Int, carsAvailable: set Car, maxDistance: Int, //should be float initialPos: Position, finalPos: Position, totalCost:Int, passengers: Int // don’t remember if the class (and consequently the signature) should exist or we decide to remove it; in this case, change Passenger with User } sig Plug{} abstract sig Station{ parkedCar:set Car, positoin:one Position } sig Parking extends Station{ distanceFromCharge:Int } sig safeArea extends Station { carsToCharge: set Car, plugAvailable: set Plug, } sig Payment { transactionCode: Int, payInfo : set Payment } sig Car { user: one User, position:one Position, battery: Int, plate: String } fact driverIsUnique { //can’t exist two renters who rent the same car at the same time all r1,r2:Rent | (r1.Renter!=r2.Renter) => r1.rentedCar != r2.rentedCar and r1.startTime!=r2.startTime } fact applyDiscountForBattery { //if the battery at the end of the trip is at least at 50%, apply a discount //not sure if it’s possible to use this notation!! all c:Car, r:Rent | (c.battery>=50) => r.applyDiscount //alternatively, we can suppose that the attribute “isCharge” is set to a specific value for every kind of discount appliable all c:Car, r:Rent | (c.isCharge) => r.applyDiscount } fact applyDiscountForArea { //if the car at the end of trip is let in a service station, apply a discount all r:Rent, s:ServiceStation | (r.finalPosition=s.position) => r.applyDiscount } fact applyOvertax { all c:Car, r:Rent, s:Parking | (!(c.isCharge)) => r.applyOvertax or ((s.distanceFromCharge)>r.maxDistance) => r.applyOvertax } fact plateIsUnique { all c1,c2: Car | (c1 != c2) => c1.plate != c2.plate } fact userIsUnique { all u1,u2: User | u1 != u2 => u1.email != u2.email } fact pathDriverHasAStartAndEnd { all r:Rent | (r.RentedCar) => r.InitialPosition and r.finalPosition } //30.10.2016 fact rentIfAvailable { all u:user, r:rent | r.startTime u.rentedCar in r.carsAvailable } fact noSafeAreaParkNoEndTrip { //I can terminate my trip if and only if my car’s position coincides with a parking position or a safa area position all c:Car, r:Rent, s:Station | r.endTime <=> (c.position = s.position) } fact applyDiscountForPassNumb { //for every trip that involves a number of passengers >=3, apply a discount for the renter all r:Rent | (#r.passengers>= 3) => r.applyDiscount } assert userMustHaveAtLeastOnePaymentInfo { no u:User, p:Payment | u.payInfo not in p.payInfo }
Edit alloy model
Edit alloy model
Alloy
mit
FrancescoZ/PowerEnJoy
da8b5936c5115ae2636ab763e86f072a9849f3e7
mappings/c11_x86a.als
mappings/c11_x86a.als
open ../archs/exec_C[SE] as SW open ../archs/exec_x86[HE] as HW /* A C11-to-x86 mapping that implements SC atomics using atomic hardware events. Currently broken. */ module c11_x86a[SE,HE] fun myfr_init [X:HW/Exec_X86] : HE->HE { ((stor[X.R]) - ((~(X.rf)) . (X.rf))) . (X.sloc) . (stor[X.W]) } fun myfr [X:HW/Exec_X86] : HE->HE { (((myfr_init[X]) + ((~(X.rf)) . (X.co))) - iden) } pred apply_map[X:SW/Exec_C, X':HW/Exec_X86, map:SE->HE] { // two SW events cannot be compiled to a single HW event map in X.EV lone -> X'.EV // HW reads/writes cannot be invented by the compiler all e : X'.(R+W) | one e.~map // SW reads/writes cannot be discarded by the compiler all e : X.(R+W) | some e.map // a read compiles to a single non-locked read all e : X.(R - W) { one e.map e.map in X'.R - (X'.atom).univ } // a non-SC write compiles to a single non-locked write all e : X.((W - R) - SC) { one e.map e.map in X'.W - univ.(X'.atom) } // an SC write compiles to an RMW all e : X.((W - R) & SC) | some disj e1,e2 : X'.EV { e.map = e1 + e2 e1 in X'.R e2 in X'.W (e1 -> e2) in X'.atom & imm[X'.sb] // read does not observe a too-late value (e2 -> e1) not in ((X'.co) . (X'.rf)) // read does not observe a too-early value (e1 -> e2) not in ((myfr[X']) . (X'.co)) } // RMWs compile to locked RMWs all e : X.(R & W) | some disj e1, e2 : X'.EV { e.map = e1 + e2 e1 in X'.R e2 in X'.W (e1 -> e2) in X'.atom & imm[X'.sb] } // SC fences compile to full fences all e : X.(F & SC) { (X.sb) . (stor[e]) . (X.sb) = map . (mfence[none->none,X']) . ~map } // sb edges are preserved (but more may be introduced) X.sb in map . (X'.sb) . ~map // rf edges (except those entering the RMWs induced // by SC writes) are preserved let newR = X'.R & map[X.((W - R) & SC)] | X'.rf - (X'.EV -> newR) = ~map . (X.rf) . map // the mapping preserves co X.co = map . (X'.co) . ~map // the mapping preserves address dependencies X.ad = map . (X'.ad) . ~map // the mapping preserves data dependencies X.dd = map . (X'.dd) . ~map // the mapping preserves locations X.sloc = map . (X'.sloc) . ~map // the mapping preserves control dependencies X.cd in map . (X'.cd) . ~map // the mapping preserves threads X.sthd = map . (X'.sthd) . ~map // the mapping preserves transactions X.stxn = map . (X'.stxn) . ~map X.ftxn = map . (X'.ftxn) . ~map }
Revert "mappings: remove unused experiment"
Revert "mappings: remove unused experiment" This reverts commit e4da5cad5d3f7878bb65ab8b9704c9ab4a8951c0.
Alloy
mit
johnwickerson/memalloy,johnwickerson/memalloy,johnwickerson/memalloy
78198c963089b784f988f0babd3c8335daf9acbe
make_puzzle2.als
make_puzzle2.als
enum Person {X, Y, Z} enum Bool {T, F} // 制約 abstract sig Constrain{} // 「Xが『Yは嘘つきだ』と言った」という制約 sig is_liar extends Constrain { by: one Person, who: some Person } // 与えられたx, y, zの真偽値の対が制約を満たすかどうか返す // 引数を変えて試すため、述語にくくり出されている必要がある pred satisfy(cs: Constrain, x, y, z: Bool){ let p2b = (X -> x) + (Y -> y) + (Z -> z) { // only one liar one p2b.F // すべての制約について、発言者が正直なら充足される // 今は「whoは嘘つき」しかない all c: cs{ (c.by.p2b = T) => (c.who.p2b = F) } } } run { let answers = { x, y, z: Bool | satisfy[Constrain, x, y, z]}{ one answers } } fact { all c: Constrain { c.by not in c.who one c.who } }
enum Person {A, B, C, D, E} enum Bool {T, F} // 制約 abstract sig Constrain{} // 「Xが『Yは嘘つきだ』と言った」という制約 sig is_liar extends Constrain { by: one Person, who: one Person }{ by not in who } fact { // 違う人は違うことを言う all disj p1, p2: Person { by.p1 != by.p2 } // 一人の人は3人以上を嘘つき呼ばわりしない all p: Person { #{by.p} < 3 } } // 与えられたx, y, zの真偽値の対が制約を満たすかどうか返す // 引数を変えて試すため、述語にくくり出されている必要がある pred satisfy(cs: Constrain, a, b, c, d, e: Bool){ let p2b = (A -> a) + (B -> b) + (C -> c) + (D -> d) + (E -> e) { // 嘘つきの人数を指定 #{p2b.F} = 3 // すべての制約について、発言者が正直なら充足される // 今は「whoは嘘つき」しかない all c: cs{ (c.by.p2b = T) => (c.who.p2b = F) } } } run { let answers = { a, b, c, d, e: Bool | satisfy[Constrain, a, b, c, d, e]} { // 解は一つ one answers // どの制約を取り除いても解は一つではなくなる all x: Constrain { not one { a, b, c, d, e: Bool | satisfy[Constrain - x, a, b, c, d, e] } } } } for 10
make puzzle
make puzzle
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
8dedca93d5989ff5092d8b9cf1d3d083273814ee
demo_of_named_man.als
demo_of_named_man.als
open named_man_ja [Man] open named_woman_ja [Woman] abstract sig Person { love: Person } abstract sig Man extends Person { } abstract sig Woman extends Person { } run { #Man = 3 #Woman = 5 } for 10
add sample to use named_* module
add sample to use named_* module
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
211ecc55250422ad24b208a986ac841d33641fc8
etude17.als
etude17.als
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, }{ all t: Time | one state.t } abstract sig Man, Woman extends Person {} enum State {NotExist, Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t in NotMarried + NotExist } pred change_state ( target : Person, t, t': Time, before, after : State){ some target all p: target { p.state.t = before p.state.t' = after } // others don't change their state all other: (Person - target) { other.state.t = other.state.t' } } pred step (t, t': Time) { {some disj p1 : Man, p2 : Woman { // marriage change_state[p1 + p2, t, t', NotMarried, Married] or // divorce change_state[p1 + p2, t, t', Married, NotMarried] }} or some p: Person { // birth change_state[p, t, t', NotExist, NotMarried] } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run {} for exactly 4 Person, 4 Time
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, partner: Person -> Time, parent_bio: set Person }{ all t: Time | one state.t all t: Time | lone partner.t let p = parent_bio {no p or {one p & Man and one p & Woman}} } abstract sig Man, Woman extends Person {} enum State {NotExist, Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t in NotMarried + NotExist } pred change_state ( target : Person, t, t': Time, before, after : State){ some target all p: target { p.state.t = before p.state.t' = after } // others don't change their state all other: (Person - target) { other.state.t = other.state.t' } } pred step (t, t': Time) { {some disj p1 : Man, p2 : Woman { // marriage change_state[p1 + p2, t, t', NotMarried, Married] or // divorce change_state[p1 + p2, t, t', Married, NotMarried] }} or some p: Person { // birth change_state[p, t, t', NotExist, NotMarried] some father: p.parent_bio & Man {father.state.t != NotExist} some mother: p.parent_bio & Woman {mother.state.t != NotExist} } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run { some parent_bio } for exactly 4 Person, 4 Time
add parent
add parent
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
b39ab89eeeae8be460ac223f634fc8a71da6cd15
etude17.als
etude17.als
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time {} abstract sig Person { state: State -> Time, partner: Person -> Time, parent_bio: set Person }{ all t: Time | one state.t all t: Time | lone partner.t let p = parent_bio {no p or {one p & Man and one p & Woman}} } abstract sig Man, Woman extends Person {} enum State {NotExist, Married, NotMarried} pred init (t: Time) { all p: Person | p.state.t in NotMarried + NotExist } pred change_state ( target : Person, t, t': Time, before, after : State){ some target all p: target { p.state.t = before p.state.t' = after } // others don't change their state all other: (Person - target) { other.state.t = other.state.t' } } pred step (t, t': Time) { {some disj p1 : Man, p2 : Woman { // marriage change_state[p1 + p2, t, t', NotMarried, Married] or // divorce change_state[p1 + p2, t, t', Married, NotMarried] }} or some p: Person { // birth change_state[p, t, t', NotExist, NotMarried] some father: p.parent_bio & Man {father.state.t != NotExist} some mother: p.parent_bio & Woman {mother.state.t != NotExist} } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run { some parent_bio } for exactly 4 Person, 4 Time
open util/ordering[Time] open named_man_ja [Man] open named_woman_ja [Woman] sig Time { event: lone Event } fact { no first.event all t: Time - first {one t.event} } abstract sig Person { state: State -> Time, partner: Person -> Time, parent_bio: set Person }{ all t: Time | one state.t all t: Time | lone partner.t let p = parent_bio { no p or {state.first = NotExist and state.last != NotExist} } } abstract sig Man, Woman extends Person {} enum State {NotExist, Married, NotMarried} enum Event {Marriage, Divorce, Birth} pred init (t: Time) { all p: Person | p.state.t in NotMarried + NotExist } pred change_state ( target : Person, t, t': Time, before, after : State){ some target all p: target { p.state.t = before p.state.t' = after } // others don't change their state all other: (Person - target) { other.state.t = other.state.t' } } pred step (t, t': Time) { {some disj p1 : Man, p2 : Woman { { t'.event = Marriage change_state[p1 + p2, t, t', NotMarried, Married] } or { t'.event = Divorce change_state[p1 + p2, t, t', Married, NotMarried] } }} or some p: Person { // birth //t'.event = Birth change_state[p, t, t', NotExist, NotMarried] some father: p.parent_bio & Man {father.state.t != NotExist} some mother: p.parent_bio & Woman {mother.state.t != NotExist} } } fact Traces { init[first] all t: Time - last { step[t, t.next] } } run { some parent_bio } for exactly 4 Person, 4 Time
fix bug: parent works now
fix bug: parent works now
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
c2eba126be95e1fd1e57206138c2115fe34be63a
tutorials/2017/wednesday/tutorial_questions.als
tutorials/2017/wednesday/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final stated to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
Add Alloy exercise for Wednesday's tutorial
Add Alloy exercise for Wednesday's tutorial
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
95a459c61053f8ed3a817ecfb37615440b966c4b
alloy/simple_maze.als
alloy/simple_maze.als
module maze_maker/simple_maze open util/ordering[Col] as cols open util/ordering[Row] as rows // 迷路のサイズ fun height : Int { 3 } fun width: Int { 3 } // 隣接する Cell fun adjacent (col: Col, row: Row) : Col -> Row { col.prev -> row + col.next -> row + col -> row.prev + col -> row.next } sig Col { paths: Row -> Col -> Row } { // 自分自身との接続はなし all row: Row | no (this -> row) & row.paths // 接続先は必ず隣接する(4近傍の) Cell all row: Row | row.paths in adjacent[this, row] } sig Row {} one sig entrance_x extends Col {} one sig entrance_y extends Row {} one sig exit_x extends Col {} one sig exit_y extends Row {} // 位置が盤の端 pred edge (col: Col, row: Row) { col = cols/first or col = cols/last or row = rows/first or row = rows/last } fact { // 全ての位置が paths に含まれている all col: Col, row: Row | (col -> row) in paths[Col, Row] // paths の連結は反射的 all c1, c2: Col, r1, r2: Row | (c1 -> r1 -> c2 -> r2) in paths => (c2 -> r2 -> c1 -> r1) in paths // 入口と出口はいずれも盤面の端に位置する edge[entrance_x, entrance_y] edge[exit_x, exit_y] } run { #Col = width[] #Row = height[] } for 3
module maze_maker/simple_maze open util/ordering[Col] as cols open util/ordering[Row] as rows // 迷路のサイズ fun height : Int { 10 } fun width: Int { 10 } // 隣接する Cell fun adjacent (col: Col, row: Row) : Col -> Row { col.prev -> row + col.next -> row + col -> row.prev + col -> row.next } sig Col { paths: Row -> Col -> Row } { // 自分自身との接続はなし all row: Row | no (this -> row) & row.paths // 接続先は必ず隣接する(4近傍の) Cell all row: Row | row.paths in adjacent[this, row] } sig Row {} one sig entrance_x extends Col {} one sig entrance_y extends Row {} one sig exit_x extends Col {} one sig exit_y extends Row {} // 位置が盤の端 pred edge (col: Col, row: Row) { col = cols/first or col = cols/last or row = rows/first or row = rows/last } fact { // 全ての位置が paths に含まれている all col: Col, row: Row | (col -> row) in paths[Col, Row] // paths の連結は反射的 all c1, c2: Col, r1, r2: Row | (c1 -> r1 -> c2 -> r2) in paths => (c2 -> r2 -> c1 -> r1) in paths // 入口と出口はいずれも盤面の端に位置する edge[entrance_x, entrance_y] edge[exit_x, exit_y] } run { #Col = width[] #Row = height[] } for 10
increase maze size 3x3 -> 10x10.
increase maze size 3x3 -> 10x10.
Alloy
mit
nagachika/maze_maker,nagachika/maze_maker,nagachika/maze_maker
ef0a80a0983b91f920cff19c9b29374a63b2d4c2
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun headsInRow (r: Row): set Col { { c: Col | is_black_head[c, r, cols/prev]} } // Col cの中の、ブロックの頭であるRowの集合 fun headsInCol (c: Col): set Row { { r: Row | is_black_head[c, r, rows/prev]} } fact noOtherHeadsInRow { no c: Col, r: Row { c not in headsInRow[r] and is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in headsInCol[c] and is_black_head[c, r, rows/prev] } } -- about rows or cols pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = headsInCol[c] // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Row (i: Int): Row { index.i & Row } pred rowHint (j: Int, sizes: seq Int) { let r = Int2Row[j] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } -- about cols fun Int2Col (i: Int): Col { index.i & Col } pred colHint (j: Int, sizes: seq Int) { let c = Int2Col[j] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } -- about rows or cols fun headsInRow (r: Row): set Col { { c: Col | is_black_head[c, r, cols/prev]} } // Col cの中の、ブロックの頭であるRowの集合 fun headsInCol (c: Col): set Row { { r: Row | is_black_head[c, r, rows/prev]} } fact noOtherHeadsInRow { no c: Col, r: Row { c not in headsInRow[r] and is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in headsInCol[c] and is_black_head[c, r, rows/prev] } } pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = headsInCol[c] // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun IntTo(i: Int, R: Region): Region{ index.i & R } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
remove Int2*
remove Int2*
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
907e3b761e0c8df1d546137d0f78887a5e5437bc
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } pred sorted(xs: Int, s: seq Int){ // sの要素はxsと同一 s.elems = xs // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } -- about rows or cols pred headsSeqInRow (r: Row, s: seq Col) { sorted[ { c: Col | is_black_head[c, r, cols/prev]}.index, s.index] } pred headsSeqInCol (c: Col, s: seq Row) { sorted[ { r: Row | is_black_head[c, r, rows/prev]}.index, s.index] } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun IntTo(i: Int, R: Region): Region{ index.i & R } pred sorted(xs: Int, s: seq Int){ // sの要素はxsと同一 s.elems = xs // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } -- about rows or cols pred headsSeqInRow (r: Row, s: seq Col) { sorted[ { c: Col | is_black_head[c, r, cols/prev]}.index, s.index] } pred headsSeqInCol (c: Col, s: seq Row) { sorted[ { r: Row | is_black_head[c, r, rows/prev]}.index, s.index] } fun range(R: Region, start, end: Int): Region{ {r: R | start =< r.index and r.index =< end} } pred rowHint (j: Int, sizes: seq Int) { let r = IntTo[j, Row] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[Col, start.index, end.index] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred colHint (j: Int, sizes: seq Int) { let c = IntTo[j, Col] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[Row, start.index, end.index] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
refactor fun range
refactor fun range
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
a79d06c2d7b8dc1dfc073973e633ecc09632e57c
tutorials/2017/wednesday/tutorial_questions.als
tutorials/2017/wednesday/tutorial_questions.als
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 // run nontrivModel for 1 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. // check finishable for 1 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.)
// This tutorial models a certain kind of state machine in Alloy // A state machine is a set of states. // Each state q has a successor relation. // q.successors is the set of possible next states following state q sig State { successors: set State } // There is exactly one initial state one sig Initial extends State { } // There is a set of final states // Each final state has an empty set of successors some sig Final extends State { } { no successors } // The kind of state machine we are modelling has two other kinds of state: // yellow states and black states. // By using sig declarations in Alloy these sets are disjoint by default. // We add an axiom (a "fact") asserting that every state is initial, final, yellow or black sig Yellow extends State { } sig Black extends State { } fact { State = Initial + Final + Yellow + Black } // The 0-arity predicate nontrivModel below expresses that the model is "nontrivial" in the // sense that black, yellow and final states all exist. pred nontrivModel { #Final > 0 && #Black > 0 && #Yellow > 0 } // Uncomment the run command below to check to see if the predicate can be satisfied in scope 1 run nontrivModel for 5 // *** EXERCISE 1 *** // (a) Find the smallest scope in which nontrivModel is satisfiable // (b) Look at the model generated by clicking on Instance // To improve the display of the model click on Theme // Click on sig Black in the left-hand menu and colour Black states black // Similarly colour Yellow states yellow, the initial state green and final states red // Click on successors and delete the label from the text box in the top left corner // If there is a funny $nontrivModel relation displayed click on that and set "show as arcs" to off // Click on Apply and then Close // The model should now display nicely // (c) Look at further models by clicking on Next // Also run nontrivModel again in larger scope (not too large) to generate larger models // *** EXERCISE 2 *** // Say that a state is deadlocked if it has no successors. // The sig declaration for Final requires final states to be deadlocked // Add an axiom stating that only Final states can deadlock // (You may find it useful to use a comprehension term { q: A | P } // which defines the subset of those q in set A that satisfy property P) // For a good reference on the logic of Alloy look at the slides for Session 1 of: // http://alloy.mit.edu/alloy/tutorials/day-course/ fact { all q: State - Final | some q.successors } // After this, and all subsequent exercises involving the addition of new facts run nontrivModel // in suitable scope and use the Next button to again explore the range of models available // *** EXERCISE 3 *** // Add an axiom stating that every state is reachable from the initial state fact { State = Initial.*successors } // *** EXERCISE 4 *** // Black nodes are intended to represent error states. // When an execution reaches a black node it has to be corrected by eventually // resetting the system by returning it to the Initial node. // Add an axiom stating that the initial node is reachable from every black node fact { all q: Black | Initial in q.^successors } //*** EXERCISE 5 *** // Yellow states are intended to represent non-error intermediate states that // may be encountered en-route to arriving at a final state // Add an axiom stating that every yellow state has a path to a final state fact { all q: Yellow | some q': Final | q' in q.^successors } // *** EXERCISE 6 *** // In this exercise we use the "assert" command to state a property that we // hope follows from the axioms. // The property is that every state has a path to a final state // complete the assert command below by filling in the property // between the curly braces. assert finishable { all q: State | some q': Final | q' in q.*successors } // Uncomment and modify the check command below to check finishable in a sufficiently large scope to // be confident whether or not the property is true. check finishable for 5 // If the property is not true then can you fix the model to make it true? // *** EXERCISE 7 *** // There is one further property we want to axiomatize. // We want to force the system to reset after a Black state. // This can be achieved by requiring that // every path to a final state from a black state goes through the initial state. // Add this as an axiom. // (Hint, you might need to use set operators to define a derived relation.) fact { no Black.^(successors :> (State - Initial)) & Final } // Additional property: no final state is the successor of an initial state fact { not Initial in successors.Final }
Add solutions from Wednesday's tutorials
Add solutions from Wednesday's tutorials
Alloy
mit
jaanos/LVR-2016,jaanos/LVR-2016
ccedfcb547d48f97f50301ef72e28d7def6014a7
illust_logic/illustLogic.als
illust_logic/illustLogic.als
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } -- about rows fun headsInRow (r: Row): set Col { { c: Col | blackHeadInRow[c, r] } } fact noOtherHeadsInRow { no c: Col, r: Row | c not in headsInRow[r] and blackHeadInRow[c, r] } pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Row (i: Int): Row { index.i & Row } pred rowHint (j: Int, sizes: seq Int) { let r = Int2Row[j] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } pred blackHeadInCol (c: Col, r: Row) { is_black_head[c, r, rows/prev] } pred blackHeadInRow (c: Col, r: Row) { is_black_head[c, r, cols/prev] } -- about cols // Col cの中の、ブロックの頭であるRowの集合 fun headsInCol (c: Col): set Row { { r: Row | blackHeadInCol[c, r] } } fact noOtherHeadsInCol { no c: Col, r: Row | r not in headsInCol[c] and blackHeadInCol[c, r] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = headsInCol[c] // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Col (i: Int): Col { index.i & Col } pred colHint (j: Int, sizes: seq Int) { let c = Int2Col[j] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
open util/ordering[Col] as cols open util/ordering[Row] as rows abstract sig Region { index: Int } sig Col extends Region { cell: Row -> Color }{ index >= 0 index <= 9 } sig Row extends Region {}{ index >= 0 index <= 9 } fact { all r: Col - last { add[r.index, 1] = r.next.index } all r: Row - last { add[r.index, 1] = r.next.index } } enum Color { Black, White } fact { all c: Col, r: Row | one cell [c, r] } -- both Row and Col pred prev_is_white(c: Col, r: Row, prev: Region->Region) { // トリック: prevがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでin Whiteが成立するから cell[prev[c], r] + cell[c, prev[r]] in White } pred no_prev(c: Col, r: Row, prev: Region->Region) { // トリック: nextがCol->ColでもRowに使ってよい // なぜなら空集合が返るのでnoが成立するから no prev[c] and no prev[r] } // c, rがブロックの先頭であるかどうか pred is_black_head(c: Col, r: Row, prev: Region->Region) { // 最初のRowであるか、または前のRowのセルが白い no_prev[c, r, prev] or prev_is_white[c, r, prev] // このセルは黒い cell[c, r] in Black } fun range(start, end: Region, next: Region -> Region): Region{ start.*next - end.^next } fun get_block_end(start: Region, size: Int): Region{ plus[start.index, minus[size, 1]][index] } fun headsInRow (r: Row): set Col { { c: Col | is_black_head[c, r, cols/prev]} } // Col cの中の、ブロックの頭であるRowの集合 fun headsInCol (c: Col): set Row { { r: Row | is_black_head[c, r, rows/prev]} } fact noOtherHeadsInRow { no c: Col, r: Row { c not in headsInRow[r] and is_black_head[c, r, cols/prev] } } fact noOtherHeadsInCol { no c: Col, r: Row { r not in headsInCol[c] and is_black_head[c, r, rows/prev] } } -- about rows or cols pred headsSeqInRow (r: Row, s: seq Col) { s.elems = headsInRow[r] all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } pred headsSeqInCol (c: Col, s: seq Row) { // sの要素はブロック先頭の集合と同一 s.elems = headsInCol[c] // sは単調増加 all i: s.butlast.inds | lt [s[i], s[plus[i, 1]]] } fun Int2Row (i: Int): Row { index.i & Row } pred rowHint (j: Int, sizes: seq Int) { let r = Int2Row[j] | some cs: seq Col { #sizes = #cs // csは黒ブロックの先頭の位置のソートされたシークエンス headsSeqInRow [r, cs] all i: sizes.inds { // cs[i]をstart, startの位置にsize[i]を足して1を引いた位置にあるColをendと呼ぶ let start = cs [i], end = Col & get_block_end[start, sizes[i]] { // endが存在する some end // startからendまで全部黒 all c: range[start, end, cols/next] | cell [c, r] in Black // endの次がないか、または白 no end.next or cell [end.next, r] in White } } } } -- about cols fun Int2Col (i: Int): Col { index.i & Col } pred colHint (j: Int, sizes: seq Int) { let c = Int2Col[j] | some rs: seq Row { #sizes = #rs headsSeqInCol [c, rs] all i: sizes.inds { let start = rs [i], end = Row & get_block_end[start, sizes[i]] { some end all r: range[start, end, rows/next] | cell [c, r] in Black no end.next or cell [c, end.next] in White } } } } -- riddle from http://homepage1.nifty.com/sabo10/rulelog/illust.html solve: run { rowHint [0, 0 -> 3] rowHint [1, 0 -> 2 + 1 -> 2] rowHint [2, 0 -> 1 + 1 -> 1 + 2 -> 1] rowHint [3, 0 -> 3 + 1 -> 3] rowHint [4, 0 -> 5] rowHint [5, 0 -> 7] rowHint [6, 0 -> 7] rowHint [7, 0 -> 7] rowHint [8, 0 -> 7] rowHint [9, 0 -> 5] colHint [0, 0 -> 4] colHint [1, 0 -> 6] colHint [2, 0 -> 7] colHint [3, 0 -> 9] colHint [4, 0 -> 2 + 1 -> 7] colHint [5, 0 -> 1 + 1 -> 6] colHint [6, 0 -> 2 + 1 -> 4] colHint [7, 0 -> 3] colHint [8, 0 -> 1] colHint [9, 0 -> 2] } for 10 but 5 Int
remove blackHeadIn*
remove blackHeadIn*
Alloy
mit
nishio/learning_alloy,nishio/learning_alloy,nishio/learning_alloy
3334bdd3a0bfb5b3533ea6e36840926d24eea248
src/dot.g4
src/dot.g4
grammar dot; graph : (STRICT)? (GRAPH | DIGRAPH) (ID)? '{' stmt_list '}'; stmt_list : (stmt ';'?)* ; stmt : node_stmt | edge_stmt | attr_stmt | id '=' id | subgraph; attr_stmt : (GRAPH | NODE | EDGE) attr_list; attr_list : '[' ( a_list )? ']' (attr_list)?; a_list : id '=' id ( (';' | ',') )? ( a_list )?; edgeop : '-' ('-'|'>') ; edge_stmt : (node_id | subgraph) edgeRHS (attr_list)?; edgeRHS : edgeop (node_id | subgraph) (edgeRHS)?; node_stmt : node_id ( attr_list )?; node_id : id ( port )?; port : ':' id ( ':' compass_pt )? | ':' compass_pt; subgraph : ( SUBGRAPH ( id )? )? '{' stmt_list '}'; compass_pt : ('n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw' | 'c' | '_') ; id : ID //alphabetic chars, '_', or digits (but can't start with a digit) | NUMERAL // any number (can be negative or floating point) | QUOTED_STRING //any double-quoted string ("...") possibly containing escaped quotes (\") | HTML_STRING ; //html string (must be valid XML) STRICT : [Ss][Tt][Rr][Ii][Cc][Tt] ; GRAPH : [Gg][Rr][Aa][Pp][Hh] ; DIGRAPH : [Dd][Ii][Gg][Rr][Aa][Pp][Hh] ; NODE : [Nn][Oo][Dd][Ee] ; EDGE : [Ee][Dd][Gg][Ee] ; SUBGRAPH : [Ss][Uu][Bb][Gg][Rr][Aa][Pp][Hh] ; ID : [_a-zA-Z\u0080-\u00FF][_0-9a-zA-Z\u0080-\u00FF]* ; NUMERAL : '-'? ('.'[0-9]+ | [0-9]+ ('.'[0-9]*)? ); QUOTED_STRING : '"' ('\\"'|.)*? '"' ; HTML_STRING : '<' ('<' .*? '>'|~[<>])* '>' ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' .*? '\r'? '\n' -> skip ; PREPROC : '#' .*? '\n' -> skip ; WS : [ \t\r\n]+ -> skip ;
grammar dot; graph : STRICT? (GRAPH | DIGRAPH) id? '{' stmt_list '}'; stmt_list : (stmt ';'?)* ; stmt : node_stmt | edge_stmt | attr_stmt | id '=' id | subgraph; attr_stmt : (GRAPH | NODE | EDGE) attr_list; attr_list : ('[' a_list? ']')+; a_list : (id '=' id ( ';' | ',' )?)+ ; edgeop : '-' ('-'|'>') ; edge_stmt : (node_id | subgraph) edgeRHS attr_list?; edgeRHS : (edgeop (node_id | subgraph))+; node_stmt : node_id attr_list?; node_id : id port?; port : ':' id ( ':' id )?; subgraph : ( SUBGRAPH id? )? '{' stmt_list '}'; // compass_pt : ('n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw' | 'c' | '_') ; id : ID //alphabetic chars, '_', or digits (but can't start with a digit) | NUMERAL // any number (can be negative or floating point) | QUOTED_STRING //any double-quoted string ("...") possibly containing escaped quotes (\") | HTML_STRING ; //html string (must be valid XML) STRICT : [Ss][Tt][Rr][Ii][Cc][Tt] ; GRAPH : [Gg][Rr][Aa][Pp][Hh] ; DIGRAPH : [Dd][Ii][Gg][Rr][Aa][Pp][Hh] ; NODE : [Nn][Oo][Dd][Ee] ; EDGE : [Ee][Dd][Gg][Ee] ; SUBGRAPH : [Ss][Uu][Bb][Gg][Rr][Aa][Pp][Hh] ; ID : [_a-zA-Z\u0080-\u00FF][_0-9a-zA-Z\u0080-\u00FF]* ; NUMERAL : '-'? ('.'[0-9]+ | [0-9]+ ('.'[0-9]*)? ); QUOTED_STRING : '"' ('\\"'|.)*? '"' ; HTML_STRING : '<' ('<' .*? '>'|~[<>])* '>' ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' .*? '\r'? '\n' -> skip ; PREPROC : '#' .*? '\n' -> skip ; WS : [ \t\r\n]+ -> skip ;
Update dot grammar.
Update dot grammar.
ANTLR
mit
migulorama/AutoAnalyze,migulorama/AutoAnalyze
eee3c3f97bf170a8e7c31fd52aaf82b303831af5
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ',' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_clause_optional[$l] over_clause_optional[$l] { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // over clause over_clause_optional[ClawLanguage l] @init{ List<String> s = new ArrayList<>(); } : OVER '(' ids_or_colon_list[s] ')' { $l.setOverClause(s); } | /* empty */ ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // data clause or empty data_clause_optional[ClawLanguage l]: data_clause[$l] | /* empty */ ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ',' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add correct grammar for claw ignore and end ignore
Add correct grammar for claw ignore and end ignore
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
45b028c111014f2f20751d930c6abb6a4baae271
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
sharding-core/src/main/antlr4/io/shardingsphere/core/parsing/antlr/autogen/OracleStatement.g4
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser | alterUser | dropUser ;
grammar OracleStatement; import OracleKeyword, Keyword, OracleBase, OracleCreateIndex, OracleAlterIndex , OracleDropIndex, OracleCreateTable, OracleAlterTable, OracleDropTable, OracleTruncateTable , OracleTCLStatement, OracleDCLStatement ; execute : createIndex | alterIndex | dropIndex | createTable | alterTable | dropTable | truncateTable | setTransaction | commit | rollback | savepoint | grant | revoke | createUser | alterUser | dropUser | createRole ;
add create role statement
add create role statement
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
b8588d926c695b37dccc4c1e0201c086d98f2f81
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR_EOL: '|' [ \t]* '\r'? '\n' ; BAR: '|' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' ; CSV: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' -> skip, mode(ABBREVIATION); HASH1: '#' ; HASH2: '##' ; HASH3: '###' ; HASH4: '####' ; HASH5: '#####' ; HASH6: '######' ; TEST: 'Test:' [ \t]* -> mode(TEST_NAME); TABLE_CAPTION: '[' -> skip, mode(TABLE_NAME); SETUP: 'Setup' -> mode(PHASE_LEADING); EXERCISE: 'Exercise' -> mode(PHASE_LEADING); VERIFY: 'Verify' -> mode(PHASE_LEADING); TEARDOWN: 'Teardown' -> mode(PHASE_LEADING); BAR: '|' ; BAR_EOL: '|' [ \t]* '\r'? '\n' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; RULES: 'rules' ; IN: 'in' ; UTABLE: 'Table' ; CSV: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; OPEN_BACK_TICK: '`' -> skip, mode(IN_BACK_TICK) ; OPEN_DOUBLE_QUOTE: '"' -> skip, mode(IN_DOUBLE_QUOTE) ; OPEN_SINGLE_QUOTE: '\'' -> skip, mode(IN_SINGLE_QUOTE) ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]* ; RBRACKET_COLON: ']:' Spaces? -> skip, mode(LONG_NAME) ; mode LONG_NAME; LongName: ~[\r\n]* ; EXIT_LONG_NAME: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TEST_NAME; TestName: ~[\r\n]+ ; NEW_LINE_TEST_NAME: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode TABLE_NAME; TableName: ~[\]\r\n]+ ; RBRACKET_TABLE_NAME: ']' -> skip, mode(DEFAULT_MODE) ; mode PHASE_LEADING; COLON: ':' [ \t]* -> skip, mode(PHASE_DESCRIPTION) ; NEW_LINE_PHASE_LEADING: [ \t]* '\r'? '\n' -> skip, mode(DEFAULT_MODE) ; mode PHASE_DESCRIPTION; PhaseDescription: ~[\r\n]+ ; NEW_LINE_PHASE_DESCRIPTION: ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier5 : IdentStart IdentPart* -> type(Identifier) ; OPEN_BACK_TICK5: '`' -> skip, mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> skip, mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> skip, mode(DEFAULT_MODE) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA3: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; Identifier3 : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; CLOSE_BACK_TICK2: '`' -> skip, mode(DEFAULT_MODE) ; mode CLASS; DOT2: '.' -> type(DOT) ; Identifier4 : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; CLOSE_BACK_TICK3: '`' -> skip, mode(DEFAULT_MODE) ; mode IN_FILE_NAME; SingleQuoteName: (~['\r\n]|'\'\'')* ; CLOSE_SINGLE_QUOTE2: '\'' -> skip, mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; SingleQuoteName3: (~['\r\n]|'\'\'')* -> type(SingleQuoteName) ; CLOSE_SINGLE_QUOTE3: '\'' -> skip, mode(DEFAULT_MODE) ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
Arrange order of rules
Arrange order of rules
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
da613bc8244ad90c77a93ac2ea698d50dfeeb428
sharding-parser/sharding-parser-mysql/src/main/antlr4/imports/mysql/MySQLDMLStatement.g4
sharding-parser/sharding-parser-mysql/src/main/antlr4/imports/mysql/MySQLDMLStatement.g4
grammar MySQLDMLStatement; import MySQLKeyword, Keyword, Symbol, MySQLDQLStatement, MySQLBase, BaseRule, DataType; insert : INSERT (LOW_PRIORITY | DELAYED | HIGH_PRIORITY IGNORE)? INTO? tableName (PARTITION ignoredIdentifiers_)? (setClause | columnClause) onDuplicateKeyClause? ; columnClause : columnNames? (valueClause | select) ; valueClause : (VALUES | VALUE) assignmentValueList (COMMA_ assignmentValueList)* ; setClause : SET assignmentList ; onDuplicateKeyClause : ON DUPLICATE KEY UPDATE assignmentList ; update : updateClause setClause whereClause? orderByClause? limitClause? ; updateClause : UPDATE LOW_PRIORITY? IGNORE? tableReferences ; delete : deleteClause whereClause? orderByClause? limitClause? ; deleteClause : DELETE deleteSpec (fromMulti | fromSingle) ; fromSingle : FROM tableName (PARTITION columnNames)? ; fromMulti : fromMultiTables FROM tableReferences | FROM fromMultiTables USING tableReferences ; fromMultiTables : fromMultiTable (COMMA_ fromMultiTable)* ; fromMultiTable : tableName DOT_ASTERISK_? ; deleteSpec : LOW_PRIORITY? | QUICK? | IGNORE? ;
grammar MySQLDMLStatement; import MySQLKeyword, Keyword, Symbol, MySQLDQLStatement, MySQLBase, BaseRule, DataType; insert : INSERT (LOW_PRIORITY | DELAYED | HIGH_PRIORITY)? IGNORE? INTO? tableName (PARTITION ignoredIdentifiers_)? (setClause | columnClause) onDuplicateKeyClause? ; columnClause : columnNames? (valueClause | select) ; valueClause : (VALUES | VALUE) assignmentValueList (COMMA_ assignmentValueList)* ; setClause : SET assignmentList ; onDuplicateKeyClause : ON DUPLICATE KEY UPDATE assignmentList ; update : updateClause setClause whereClause? orderByClause? limitClause? ; updateClause : UPDATE LOW_PRIORITY? IGNORE? tableReferences ; delete : deleteClause whereClause? orderByClause? limitClause? ; deleteClause : DELETE LOW_PRIORITY? QUICK? IGNORE? (fromMulti | fromSingle) ; fromSingle : FROM tableName (PARTITION ignoredIdentifiers_)? ; fromMulti : fromMultiTables FROM tableReferences | FROM fromMultiTables USING tableReferences ; fromMultiTables : fromMultiTable (COMMA_ fromMultiTable)* ; fromMultiTable : tableName DOT_ASTERISK_? ;
refactor MySQLDMLStatement.g4
refactor MySQLDMLStatement.g4
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
07ab552eb3a92d88c26b178dd58f45c06a497826
src/main/antlr/WorkflowCatalogQueryLanguage.g4
src/main/antlr/WorkflowCatalogQueryLanguage.g4
grammar WorkflowCatalogQueryLanguage; @header { package org.ow2.proactive.workflow_catalog.rest.query; } clause: ATTRIBUTE OPERATOR VALUE ; clauses: clause ( CONJUNCTION clause )* ; statement: '(' clauses ')' | clauses ; ATTRIBUTE: ([a-z] | [A-Z])+ ([_.]+ ([a-z] | [A-Z] | [0-9])*)* ; CONJUNCTION: 'AND' | 'OR' ; OPERATOR: '!=' | '=' ; VALUE: '"' (~[\t\n])* '"' ; WHITESPACE: [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
grammar WorkflowCatalogQueryLanguage; @header { package org.ow2.proactive.workflow_catalog.rest.query; } // PARSER expression : and_expression ; and_expression : or_expression (AND or_expression)* ; or_expression : clause (OR clause)* ; clause : (AttributeLiteral COMPARE_OPERATOR StringLiteral) | LPAREN and_expression RPAREN ; // LEXER AND : 'AND' | '&&' ; OR : 'OR' | '||' ; COMPARE_OPERATOR : '!=' | '=' ; LPAREN : '(' ; RPAREN : ')' ; StringLiteral : '"' (~["\\\r\n] | '\\' (. | EOF))* '"' ; AttributeLiteral : LETTER (LETTER | DIGIT | '_' | '.')* ; WS : [ \t\r\n]+ -> skip ; fragment DIGIT: [0-9]; fragment LETTER: LOWERCASE | UPPERCASE; fragment LOWERCASE: [a-z]; fragment UPPERCASE: [A-Z];
Update grammar for our Workflow Catalog Query Language (WCQL)
Update grammar for our Workflow Catalog Query Language (WCQL)
ANTLR
agpl-3.0
ow2-proactive/catalog,laurianed/catalog,laurianed/catalog,gparanthoen/workflow-catalog,yinan-liu/workflow-catalog,lpellegr/workflow-catalog,ShatalovYaroslav/catalog,ow2-proactive/catalog,laurianed/workflow-catalog,ow2-proactive/workflow-catalog,laurianed/catalog,ow2-proactive/catalog,paraita/workflow-catalog,ShatalovYaroslav/catalog,ShatalovYaroslav/catalog
a2ceedcc2d68635f431e5b2b2b2ec30536a9bf11
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-oracle/src/main/antlr4/imports/oracle/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? LP_ indexExpr_ (COMMA_ indexExpr_)* RP_ ; indexExpr_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr ; columnSortClause_ : tableName alias? columnName (ASC | DESC)? ; tableProperties : columnProperties? (AS unionSelect)? ; unionSelect : matchNone ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : opColumnClause+ | renameColumnSpecification ; opColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnSpecification : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE tableName createDefinitionClause_ ; createIndex : CREATE createIndexSpecification_ INDEX indexName ON (tableIndexClause_ | bitmapJoinIndexClause_) ; alterTable : ALTER TABLE tableName (alterTableProperties | columnClauses | constraintClauses | alterExternalTable)? ; // TODO hongjun throw exeption when alter index on oracle alterIndex : ALTER INDEX indexName (RENAME TO indexName)? ; dropTable : DROP TABLE tableName ; dropIndex : DROP INDEX indexName ; truncateTable : TRUNCATE TABLE tableName ; createTableSpecification_ : (GLOBAL TEMPORARY)? ; tablespaceClauseWithParen : LP_ tablespaceClause RP_ ; tablespaceClause : TABLESPACE ignoredIdentifier_ ; domainIndexClause : indexTypeName ; createDefinitionClause_ : (LP_ relationalProperties RP_)? (ON COMMIT (DELETE | PRESERVE) ROWS)? ; relationalProperties : relationalProperty (COMMA_ relationalProperty)* ; relationalProperty : columnDefinition | virtualColumnDefinition | outOfLineConstraint | outOfLineRefConstraint ; columnDefinition : columnName dataType SORT? (VISIBLE | INVISIBLE)? (DEFAULT (ON NULL)? expr | identityClause)? (ENCRYPT encryptionSpecification_)? (inlineConstraint+ | inlineRefConstraint)? ; identityClause : GENERATED (ALWAYS | BY DEFAULT (ON NULL)?) AS IDENTITY LP_? (identityOptions+)? RP_? ; identityOptions : START WITH (NUMBER_ | LIMIT VALUE) | INCREMENT BY NUMBER_ | MAXVALUE NUMBER_ | NOMAXVALUE | MINVALUE NUMBER_ | NOMINVALUE | CYCLE | NOCYCLE | CACHE NUMBER_ | NOCACHE | ORDER | NOORDER ; encryptionSpecification_ : (USING STRING_)? (IDENTIFIED BY STRING_)? STRING_? (NO? SALT)? ; inlineConstraint : (CONSTRAINT ignoredIdentifier_)? (NOT? NULL | UNIQUE | primaryKey | referencesClause | CHECK LP_ expr RP_) constraintState* ; referencesClause : REFERENCES tableName columnNames? (ON DELETE (CASCADE | SET NULL))? ; constraintState : notDeferrable | initiallyClause | RELY | NORELY | usingIndexClause | ENABLE | DISABLE | VALIDATE | NOVALIDATE | exceptionsClause ; notDeferrable : NOT? DEFERRABLE ; initiallyClause : INITIALLY (IMMEDIATE | DEFERRED) ; exceptionsClause : EXCEPTIONS INTO tableName ; usingIndexClause : USING INDEX (indexName | LP_ createIndex RP_)? ; inlineRefConstraint : SCOPE IS tableName | WITH ROWID | (CONSTRAINT ignoredIdentifier_)? referencesClause constraintState* ; virtualColumnDefinition : columnName dataType? (GENERATED ALWAYS)? AS LP_ expr RP_ VIRTUAL? inlineConstraint* ; outOfLineConstraint : (CONSTRAINT ignoredIdentifier_)? (UNIQUE columnNames | primaryKey columnNames | FOREIGN KEY columnNames referencesClause | CHECK LP_ expr RP_ ) constraintState* ; outOfLineRefConstraint : SCOPE FOR LP_ lobItem RP_ IS tableName | REF LP_ lobItem RP_ WITH ROWID | (CONSTRAINT ignoredIdentifier_)? FOREIGN KEY lobItemList referencesClause constraintState* ; createIndexSpecification_ : (UNIQUE | BITMAP)? ; tableIndexClause_ : tableName alias? indexExpressions_ ; indexExpressions_ : LP_ indexExpression_ (COMMA_ indexExpression_)* RP_ ; indexExpression_ : (columnName | expr) (ASC | DESC)? ; bitmapJoinIndexClause_ : tableName LP_ columnSortClause_ (COMMA_ columnSortClause_)* RP_ FROM tableName alias? (COMMA_ tableName alias?)* WHERE expr ; columnSortClause_ : tableName alias? columnName (ASC | DESC)? ; tableProperties : columnProperties? (AS unionSelect)? ; unionSelect : matchNone ; alterTableProperties : renameTableSpecification_ | REKEY encryptionSpecification_ ; renameTableSpecification_ : RENAME TO newTableName ; newTableName : IDENTIFIER_ ; columnClauses : opColumnClause+ | renameColumnSpecification ; opColumnClause : addColumnSpecification | modifyColumnSpecification | dropColumnClause ; addColumnSpecification : ADD columnOrVirtualDefinitions columnProperties? ; columnOrVirtualDefinitions : LP_ columnOrVirtualDefinition (COMMA_ columnOrVirtualDefinition)* RP_ | columnOrVirtualDefinition ; columnOrVirtualDefinition : columnDefinition | virtualColumnDefinition ; modifyColumnSpecification : MODIFY (LP_? modifyColProperties (COMMA_ modifyColProperties)* RP_? | modifyColSubstitutable) ; modifyColProperties : columnName dataType? (DEFAULT expr)? (ENCRYPT encryptionSpecification_ | DECRYPT)? inlineConstraint* ; modifyColSubstitutable : COLUMN columnName NOT? SUBSTITUTABLE AT ALL LEVELS FORCE? ; dropColumnClause : SET UNUSED columnOrColumnList cascadeOrInvalidate* | dropColumnSpecification ; dropColumnSpecification : DROP columnOrColumnList cascadeOrInvalidate* checkpointNumber? ; columnOrColumnList : COLUMN columnName | LP_ columnName (COMMA_ columnName)* RP_ ; cascadeOrInvalidate : CASCADE CONSTRAINTS | INVALIDATE ; checkpointNumber : CHECKPOINT NUMBER_ ; renameColumnSpecification : RENAME COLUMN columnName TO columnName ; constraintClauses : addConstraintSpecification | modifyConstraintClause | renameConstraintClause | dropConstraintClause+ ; addConstraintSpecification : ADD (outOfLineConstraint+ | outOfLineRefConstraint) ; modifyConstraintClause : MODIFY constraintOption constraintState+ CASCADE? ; constraintWithName : CONSTRAINT ignoredIdentifier_ ; constraintOption : constraintWithName | constraintPrimaryOrUnique ; constraintPrimaryOrUnique : primaryKey | UNIQUE columnNames ; renameConstraintClause : RENAME constraintWithName TO ignoredIdentifier_ ; dropConstraintClause : DROP ( constraintPrimaryOrUnique CASCADE? ((KEEP | DROP) INDEX)? | (CONSTRAINT ignoredIdentifier_ CASCADE?) ) ; alterExternalTable : (addColumnSpecification | modifyColumnSpecification | dropColumnSpecification)+ ; objectProperties : objectProperty (COMMA_ objectProperty)* ; objectProperty : (columnName | attributeName) (DEFAULT expr)? (inlineConstraint* | inlineRefConstraint?) | outOfLineConstraint | outOfLineRefConstraint ; columnProperties : columnProperty+ ; columnProperty : objectTypeColProperties ; objectTypeColProperties : COLUMN columnName substitutableColumnClause ; substitutableColumnClause : ELEMENT? IS OF TYPE? LP_ ONLY? dataTypeName_ RP_ | NOT? SUBSTITUTABLE AT ALL LEVELS ;
add indexExpressions_
add indexExpressions_
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
0ae6e4fe1de63b85ed382a95c29d7d2f2f419542
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; index_list returns [List<String> indexes] @init{ $indexes = new ArrayList(); } : i=IDENTIFIER { $indexes.add($i.text); } | i=IDENTIFIER { $indexes.add($i.text); } COMMA index_list ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' index_list ')' | LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } | REMOVE { $language.setDirective(ClawDirective.REMOVE); } | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } ; group_option: GROUP '(' IDENTIFIER ')' | /* empty */ ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ; COMMA : ',' ; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import java.util.List; import java.util.ArrayList; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage language] @init{ $language = new ClawLanguage(); } : CLAW directive[$language] ; index_list returns [List<String> indexes] @init{ $indexes = new ArrayList(); } : i=IDENTIFIER { $indexes.add($i.text); } | i=IDENTIFIER { $indexes.add($i.text); } COMMA index_list ; directive[ClawLanguage language]: LFUSION { $language.setDirective(ClawDirective.LOOP_FUSION); } group_option | LINTERCHANGE { $language.setDirective(ClawDirective.LOOP_INTERCHANGE); } '(' index_list ')' | LEXTRACT { $language.setDirective(ClawDirective.LOOP_EXTRACT); } range_option | REMOVE { $language.setDirective(ClawDirective.REMOVE); } | END REMOVE { $language.setDirective(ClawDirective.END_REMOVE); } ; group_option: GROUP '(' IDENTIFIER ')' | /* empty */ ; range_option: RANGE '(' IDENTIFIER '=' ')' ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives LFUSION : 'loop-fusion'; LINTERCHANGE : 'loop-interchange'; LEXTRACT : 'loop-extract'; REMOVE : 'remove'; END : 'end'; // Options GROUP : 'group'; RANGE : 'range'; MAP : 'map'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9]* ; COMMA : ',' ; COLON : ':'; NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add options lexer rules
Add options lexer rules
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
1542a2e4ee4822111ecfd1f23b655ebaa3278151
sharding-core/src/main/antlr4/imports/Symbol.g4
sharding-core/src/main/antlr4/imports/Symbol.g4
lexer grammar Symbol; AND_: '&&'; OR_: '||'; NOT_: '!'; UNARY_BIT_COMPLEMENT: '~'; BIT_INCLUSIVE_OR: '|'; BIT_AND: '&'; SIGNED_LEFT_SHIFT: '<<'; SIGNED_RIGHT_SHIFT: '>>'; BIT_EXCLUSIVE_OR: '^'; MOD_: '%'; COLON:':'; PLUS: '+' ; MINUS: '-' ; ASTERISK: '*' ; SLASH: '/' ; DOT: '.'; SAFE_EQ: '<=>'; EQ: '=='; EQ_: '='; NEQ: '!='; NEQ_: '<>'; GT: '>'; GTE: '>='; LT: '<' ; LTE: '<=' ; POUND_: '#'; LP_: '('; RP_: ')'; LBE_: '{'; RBE_: '}'; LBT_:'['; RBT_:']'; COMMA: ','; DQ_: '"'; SQ_: '\''; BQ_: '`'; UL_: '_'; QUESTION: '?' ; AT_: '@'; fragment A: [Aa]; fragment B: [Bb]; fragment C: [Cc]; fragment D: [Dd]; fragment E: [Ee]; fragment F: [Ff]; fragment G: [Gg]; fragment H: [Hh]; fragment I: [Ii]; fragment J: [Jj]; fragment K: [Kk]; fragment L: [Ll]; fragment M: [Mm]; fragment N: [Nn]; fragment O: [Oo]; fragment P: [Pp]; fragment Q: [Qq]; fragment R: [Rr]; fragment S: [Ss]; fragment T: [Tt]; fragment U: [Uu]; fragment V: [Vv]; fragment W: [Ww]; fragment X: [Xx]; fragment Y: [Yy]; fragment Z: [Zz];
lexer grammar Symbol; AND_: '&&'; OR_: '||'; NOT_: '!'; UNARY_BIT_COMPLEMENT: '~'; BIT_INCLUSIVE_OR: '|'; BIT_AND: '&'; SIGNED_LEFT_SHIFT: '<<'; SIGNED_RIGHT_SHIFT: '>>'; BIT_EXCLUSIVE_OR: '^'; MOD_: '%'; COLON:':'; COLONCOLON:'::'; PLUS: '+' ; MINUS: '-' ; ASTERISK: '*' ; SLASH: '/' ; DOT: '.'; SAFE_EQ: '<=>'; EQ: '=='; EQ_: '='; NEQ: '!='; NEQ_: '<>'; GT: '>'; GTE: '>='; LT: '<' ; LTE: '<=' ; POUND_: '#'; LP_: '('; RP_: ')'; LBE_: '{'; RBE_: '}'; LBT_:'['; RBT_:']'; COMMA: ','; DQ_: '"'; SQ_: '\''; BQ_: '`'; UL_: '_'; QUESTION: '?' ; AT_: '@'; fragment A: [Aa]; fragment B: [Bb]; fragment C: [Cc]; fragment D: [Dd]; fragment E: [Ee]; fragment F: [Ff]; fragment G: [Gg]; fragment H: [Hh]; fragment I: [Ii]; fragment J: [Jj]; fragment K: [Kk]; fragment L: [Ll]; fragment M: [Mm]; fragment N: [Nn]; fragment O: [Oo]; fragment P: [Pp]; fragment Q: [Qq]; fragment R: [Rr]; fragment S: [Ss]; fragment T: [Tt]; fragment U: [Uu]; fragment V: [Vv]; fragment W: [Ww]; fragment X: [Xx]; fragment Y: [Yy]; fragment Z: [Zz];
add COLONCOLON
add COLONCOLON
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
e192c8253eaac1cf5ab596305515832690c66efb
src/main/antlr4/org/s1ck/gdl/GDL.g4
src/main/antlr4/org/s1ck/gdl/GDL.g4
/* * Copyright 2017 The GDL Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Graph Definition Language grammar GDL; // starting point for parsing a GDL script database : elementList EOF ; elementList : CREATE? definitions | query ; definitions : (definition ','?)+ ; definition : graph | path ; graph : header properties? (('[' (path ','?)* ']')) ; query : match where* ; match : MATCH (path ','?)+ ; path : vertex (edge vertex)* ; vertex : '(' header properties? ')' ; edge : '<-' edgeBody? '-' #incomingEdge | '-' edgeBody? '->' #outgoingEdge ; edgeBody : '[' header properties? edgeLength?']' ; edgeLength : '*' IntegerLiteral? ('..' IntegerLiteral)? ; header : Identifier? label* ; properties : '{' (property (',' property)*)? '}' ; property : Identifier Colon (literal | listLiteral) ; label : Colon Identifier ; where : ('where' | 'WHERE') expression ; expression : xorExpression ; xorExpression: andExpression ( XOR andExpression )* ; andExpression: orExpression ( AND orExpression )* ; orExpression: notExpression ( OR notExpression )* ; notExpression : ( NOT )* expression2 ; expression2 : atom ; atom : parenthesizedExpression | comparisonExpression ; comparisonExpression : comparisonElement ComparisonOP comparisonElement ; comparisonElement : Identifier | propertyLookup | literal ; parenthesizedExpression : '(' expression ')' ; propertyLookup : Identifier '.' Identifier ; listLiteral : '[' WS? literalList WS? ']' ; literalList : (literal (',' WS? literal)* )? ; literal : StringLiteral | BooleanLiteral | IntegerLiteral | FloatingPointLiteral | NaN | Null ; //------------------------------- // String Literal //------------------------------- StringLiteral : '"' ('\\"'|.)*? '"' | '\'' ('\\\''|.)*? '\'' ; //------------------------------- // Boolean Literal //------------------------------- BooleanLiteral : 'true' | 'TRUE' | 'false' | 'FALSE' ; //------------------------------- // Integer Literal //------------------------------- IntegerLiteral : DecimalIntegerLiteral ; fragment DecimalIntegerLiteral : DecimalNumeral IntegerTypeSuffix? ; fragment DecimalNumeral : '0' | '-'? NonZeroDigit Digit* ; fragment IntegerTypeSuffix : [lL] ; //------------------------------- // Floating Point Literal //------------------------------- FloatingPointLiteral : DecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral : (DecimalFloatingPointNumeral '.' Digits) | (DecimalFloatingPointNumeral? '.' Digits) FloatTypeSuffix? ; fragment DecimalFloatingPointNumeral : '0' | '-'? Digits ; fragment FloatTypeSuffix : [fFdD] ; //------------------------------- // Comparison //------------------------------- AND : ('a'|'A')('n'|'N')('d'|'D') ; OR : ('o'|'O')('r'|'R') ; XOR : ('x'|'X')('o'|'O')('r'|'R') ; NOT : ('N'|'n')('o'|'O')('t'|'T') ; ComparisonOP : '=' | '!=' | '<>' | '>' | '<' | '>=' | '<=' ; //------------------------------- // General fragments //------------------------------- MATCH : 'MATCH' ; CREATE : 'CREATE' ; NaN : 'NaN' ; Null : 'NULL' ; //------------------------------- // Identifier //------------------------------- Identifier : (UnderScore | LowerCaseLetter | UpperCaseLetter) (UnderScore | Character)* // e.g. _temp, _0, t_T, g0, alice, birthTown ; Characters : Character+ ; Character : UpperCaseLetter | LowerCaseLetter | Digit ; UpperCaseLetters : UpperCaseLetter+ ; UpperCaseLetter : [A-Z] ; LowerCaseLetters : LowerCaseLetter+ ; LowerCaseLetter : [a-z] ; fragment Digits : Digit+ ; fragment Digit : [0-9] ; fragment NonZeroDigit : [1-9] ; fragment UnderScore : '_' ; Colon : ':' ; PERIOD : '.' ; WS : [ \t\n\r]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
/* * Copyright 2017 The GDL Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Graph Definition Language grammar GDL; // starting point for parsing a GDL script database : elementList EOF | EOF ; elementList : CREATE? definitions | query ; definitions : (definition ','?)+ ; definition : graph | path ; graph : header properties? (('[' (path ','?)* ']')) ; query : match where* ; match : MATCH (path ','?)+ ; path : vertex (edge vertex)* ; vertex : '(' header properties? ')' ; edge : '<-' edgeBody? '-' #incomingEdge | '-' edgeBody? '->' #outgoingEdge ; edgeBody : '[' header properties? edgeLength?']' ; edgeLength : '*' IntegerLiteral? ('..' IntegerLiteral)? ; header : Identifier? label* ; properties : '{' (property (',' property)*)? '}' ; property : Identifier Colon (literal | listLiteral) ; label : Colon Identifier ; where : ('where' | 'WHERE') expression ; expression : xorExpression ; xorExpression: andExpression ( XOR andExpression )* ; andExpression: orExpression ( AND orExpression )* ; orExpression: notExpression ( OR notExpression )* ; notExpression : ( NOT )* expression2 ; expression2 : atom ; atom : parenthesizedExpression | comparisonExpression ; comparisonExpression : comparisonElement ComparisonOP comparisonElement ; comparisonElement : Identifier | propertyLookup | literal ; parenthesizedExpression : '(' expression ')' ; propertyLookup : Identifier '.' Identifier ; listLiteral : '[' WS? literalList WS? ']' ; literalList : (literal (',' WS? literal)* )? ; literal : StringLiteral | BooleanLiteral | IntegerLiteral | FloatingPointLiteral | NaN | Null ; //------------------------------- // String Literal //------------------------------- StringLiteral : '"' ('\\"'|.)*? '"' | '\'' ('\\\''|.)*? '\'' ; //------------------------------- // Boolean Literal //------------------------------- BooleanLiteral : 'true' | 'TRUE' | 'false' | 'FALSE' ; //------------------------------- // Integer Literal //------------------------------- IntegerLiteral : DecimalIntegerLiteral ; fragment DecimalIntegerLiteral : DecimalNumeral IntegerTypeSuffix? ; fragment DecimalNumeral : '0' | '-'? NonZeroDigit Digit* ; fragment IntegerTypeSuffix : [lL] ; //------------------------------- // Floating Point Literal //------------------------------- FloatingPointLiteral : DecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral : (DecimalFloatingPointNumeral '.' Digits) | (DecimalFloatingPointNumeral? '.' Digits) FloatTypeSuffix? ; fragment DecimalFloatingPointNumeral : '0' | '-'? Digits ; fragment FloatTypeSuffix : [fFdD] ; //------------------------------- // Comparison //------------------------------- AND : ('a'|'A')('n'|'N')('d'|'D') ; OR : ('o'|'O')('r'|'R') ; XOR : ('x'|'X')('o'|'O')('r'|'R') ; NOT : ('N'|'n')('o'|'O')('t'|'T') ; ComparisonOP : '=' | '!=' | '<>' | '>' | '<' | '>=' | '<=' ; //------------------------------- // General fragments //------------------------------- MATCH : 'MATCH' ; CREATE : 'CREATE' ; NaN : 'NaN' ; Null : 'NULL' ; //------------------------------- // Identifier //------------------------------- Identifier : (UnderScore | LowerCaseLetter | UpperCaseLetter) (UnderScore | Character)* // e.g. _temp, _0, t_T, g0, alice, birthTown ; Characters : Character+ ; Character : UpperCaseLetter | LowerCaseLetter | Digit ; UpperCaseLetters : UpperCaseLetter+ ; UpperCaseLetter : [A-Z] ; LowerCaseLetters : LowerCaseLetter+ ; LowerCaseLetter : [a-z] ; fragment Digits : Digit+ ; fragment Digit : [0-9] ; fragment NonZeroDigit : [1-9] ; fragment UnderScore : '_' ; Colon : ':' ; PERIOD : '.' ; WS : [ \t\n\r]+ -> skip ; COMMENT : '/*' .*? '*/' -> skip ; LINE_COMMENT : '//' ~[\r\n]* -> skip ;
Allow single EOL in GDL input
Allow single EOL in GDL input
ANTLR
apache-2.0
s1ck/gdl
0d2f8f3a48e0609dd4ae7996237dca056f0944a4
objc/ObjectiveCParser.g4
objc/ObjectiveCParser.g4
/* Objective-C grammar. The MIT License (MIT). Copyright (c) 2016-2017, Alex Petuschak ([email protected]). Copyright (c) 2016-2017, Ivan Kochurkin ([email protected]). Converted to ANTLR 4 by Terence Parr; added @property and a few others. Updated June 2014, Carlos Mejia. Fix try-catch, add support for @( @{ @[ and blocks June 2008 Cedric Cuche Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ parser grammar ObjectiveCParser; options { tokenVocab=ObjectiveCLexer; } translationUnit : topLevelDeclaration* EOF ; topLevelDeclaration : importDeclaration | functionDeclaration | declaration | classInterface | classImplementation | categoryInterface | categoryImplementation | protocolDeclaration | protocolDeclarationList | classDeclarationList | functionDefinition ; importDeclaration : '@import' identifier ';' ; classInterface : IB_DESIGNABLE? '@interface' className=genericTypeSpecifier (':' superclassName=identifier)? (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; categoryInterface : '@interface' categoryName=genericTypeSpecifier LP className=identifier? RP (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; classImplementation : '@implementation' className=genericTypeSpecifier (':' superclassName=identifier)? instanceVariables? implementationDefinitionList? '@end' ; categoryImplementation : '@implementation' categoryName=genericTypeSpecifier LP className=identifier RP implementationDefinitionList? '@end' ; genericTypeSpecifier : identifier ((LT protocolList GT) | genericsSpecifier)? ; protocolDeclaration : '@protocol' protocolName (LT protocolList GT)? protocolDeclarationSection* '@end' ; protocolDeclarationSection : modifier=(REQUIRED | OPTIONAL) interfaceDeclarationList* | interfaceDeclarationList+ ; protocolDeclarationList : '@protocol' protocolList ';' ; classDeclarationList : '@class' identifier (',' identifier)* ';' ; protocolList : protocolName (',' protocolName)* ; propertyDeclaration : '@property' (LP propertyAttributesList RP)? ibOutletQualifier? IB_INSPECTABLE? fieldDeclaration ; propertyAttributesList : propertyAttribute (',' propertyAttribute)* ; propertyAttribute : ATOMIC | NONATOMIC | STRONG | WEAK | RETAIN | ASSIGN | UNSAFE_UNRETAINED | COPY | READONLY | READWRITE | GETTER '=' identifier | SETTER '=' identifier ':' | nullabilitySpecifier | identifier ; protocolName : LT protocolList GT | ('__covariant' | '__contravariant')? identifier ; instanceVariables : '{' visibilitySection* '}' ; visibilitySection : accessModifier fieldDeclaration* | fieldDeclaration+ ; accessModifier : PRIVATE | PROTECTED | PACKAGE | PUBLIC ; interfaceDeclarationList : (declaration | classMethodDeclaration | instanceMethodDeclaration | propertyDeclaration | functionDeclaration)+ ; classMethodDeclaration : '+' methodDeclaration ; instanceMethodDeclaration : '-' methodDeclaration ; methodDeclaration : methodType? methodSelector macro? ';' ; implementationDefinitionList : (functionDefinition | declaration | classMethodDefinition | instanceMethodDefinition | propertyImplementation )+; classMethodDefinition : '+' methodDefinition ; instanceMethodDefinition : '-' methodDefinition ; methodDefinition : methodType? methodSelector initDeclaratorList? ';'? compoundStatement ; methodSelector : selector | keywordDeclarator+ (',' '...')? ; keywordDeclarator : selector? ':' methodType* arcBehaviourSpecifier? identifier ; selector : identifier | 'return' ; methodType : LP typeName RP ; propertyImplementation : '@synthesize' propertySynthesizeList ';' | '@dynamic' propertySynthesizeList ';' ; propertySynthesizeList : propertySynthesizeItem (',' propertySynthesizeItem)* ; propertySynthesizeItem : identifier ('=' identifier)? ; blockType : nullabilitySpecifier? typeSpecifier nullabilitySpecifier? LP '^' (nullabilitySpecifier | typeSpecifier)? RP blockParameters? ; genericsSpecifier : LT (typeSpecifierWithPrefixes (',' typeSpecifierWithPrefixes)*)? GT ; typeSpecifierWithPrefixes : typePrefix* typeSpecifier ; dictionaryExpression : '@' '{' (dictionaryPair (',' dictionaryPair)* ','?)? '}' ; dictionaryPair : castExpression ':' expression ; arrayExpression : '@' '[' (expressions ','?)? ']' ; boxExpression : '@' LP expression RP | '@' (constant | identifier) ; blockParameters : LP ((typeVariableDeclaratorOrName | 'void') (',' typeVariableDeclaratorOrName)*)? RP ; typeVariableDeclaratorOrName : typeVariableDeclarator | typeName ; blockExpression : '^' typeSpecifier? nullabilitySpecifier? blockParameters? compoundStatement ; messageExpression : '[' receiver messageSelector ']' ; receiver : expression | typeSpecifier ; messageSelector : selector | keywordArgument+ ; keywordArgument : selector? ':' keywordArgumentType (',' keywordArgumentType)* ; keywordArgumentType : expressions nullabilitySpecifier? ('{' initializerList '}')? ; selectorExpression : '@selector' LP selectorName RP ; selectorName : selector | (selector? ':')+ ; protocolExpression : '@protocol' LP protocolName RP ; encodeExpression : '@encode' LP typeName RP ; typeVariableDeclarator : declarationSpecifiers declarator ; throwStatement : '@throw' LP identifier RP | '@throw' expression ; tryBlock : '@try' tryStatement=compoundStatement catchStatement* ('@finally' finallyStatement=compoundStatement)? ; catchStatement : '@catch' LP typeVariableDeclarator RP compoundStatement ; synchronizedStatement : '@synchronized' LP expression RP compoundStatement ; autoreleaseStatement : '@autoreleasepool' compoundStatement ; functionDeclaration : functionSignature ';' ; functionDefinition : functionSignature compoundStatement ; functionSignature : declarationSpecifiers? identifier (LP parameterList? RP) attributeSpecifier? ; attribute : attributeName attributeParameters? ; attributeName : 'const' | identifier ; attributeParameters : LP attributeParameterList? RP ; attributeParameterList : attributeParameter (',' attributeParameter)* ; attributeParameter : attribute | constant | stringLiteral | attributeParameterAssignment ; attributeParameterAssignment : attributeName '=' (constant | attributeName | stringLiteral) ; declaration : functionCallExpression | enumDeclaration | varDeclaration | typedefDeclaration ; functionCallExpression : attributeSpecifier? identifier attributeSpecifier? LP directDeclarator RP ';' ; enumDeclaration : attributeSpecifier? TYPEDEF? enumSpecifier identifier? ';' ; varDeclaration : (declarationSpecifiers initDeclaratorList | declarationSpecifiers) ';' ; typedefDeclaration : attributeSpecifier? TYPEDEF (declarationSpecifiers typeDeclaratorList | declarationSpecifiers) ';' ; typeDeclaratorList : typeDeclarator (',' typeDeclarator)* ; typeDeclarator : pointer? directDeclarator ; declarationSpecifiers : (storageClassSpecifier | attributeSpecifier | arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; attributeSpecifier : '__attribute__' LP LP attribute (',' attribute)* RP RP ; initDeclaratorList : initDeclarator (',' initDeclarator)* ; initDeclarator : declarator ('=' initializer)? ; structOrUnionSpecifier : ('struct' | 'union') (identifier | identifier? '{' fieldDeclaration+ '}') ; fieldDeclaration : specifierQualifierList fieldDeclaratorList macro? ';' ; specifierQualifierList : (arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; ibOutletQualifier : IB_OUTLET_COLLECTION LP identifier RP | IB_OUTLET ; arcBehaviourSpecifier : WEAK_QUALIFIER | STRONG_QUALIFIER | AUTORELEASING_QUALIFIER | UNSAFE_UNRETAINED_QUALIFIER ; nullabilitySpecifier : NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE ; storageClassSpecifier : AUTO | REGISTER | STATIC | EXTERN ; typePrefix : BRIDGE | BRIDGE_TRANSFER | BRIDGE_RETAINED | BLOCK | INLINE | NS_INLINE | KINDOF ; typeQualifier : CONST | VOLATILE | RESTRICT | protocolQualifier ; protocolQualifier : 'in' | 'out' | 'inout' | 'bycopy' | 'byref' | 'oneway' ; typeSpecifier : 'void' | 'char' | 'short' | 'int' | 'long' | 'float' | 'double' | 'signed' | 'unsigned' | typeofExpression | genericTypeSpecifier | structOrUnionSpecifier | enumSpecifier | identifier pointer? ; typeofExpression : TYPEOF (LP expression RP) ; fieldDeclaratorList : fieldDeclarator (',' fieldDeclarator)* ; fieldDeclarator : declarator | declarator? ':' constant ; enumSpecifier : 'enum' (identifier? ':' typeName)? (identifier ('{' enumeratorList '}')? | '{' enumeratorList '}') | ('NS_OPTIONS' | 'NS_ENUM') LP typeName ',' identifier RP '{' enumeratorList '}' ; enumeratorList : enumerator (',' enumerator)* ','? ; enumerator : enumeratorIdentifier ('=' expression)? ; enumeratorIdentifier : identifier | 'default' ; directDeclarator : (identifier | LP declarator RP) declaratorSuffix* | LP '^' nullabilitySpecifier? identifier? RP blockParameters ; declaratorSuffix : '[' constantExpression? ']' ; parameterList : parameterDeclarationList (',' '...')? ; pointer : '*' declarationSpecifiers? pointer? ; macro : identifier (LP primaryExpression (',' primaryExpression)* RP)? ; arrayInitializer : '{' (expressions ','?)? '}' ; structInitializer : '{' ('.' expression (',' '.' expression)* ','?)? '}' ; initializerList : initializer (',' initializer)* ','? ; typeName : specifierQualifierList abstractDeclarator? | blockType ; abstractDeclarator : pointer abstractDeclarator? | LP abstractDeclarator? RP abstractDeclaratorSuffix+ | ('[' constantExpression? ']')+ ; abstractDeclaratorSuffix : '[' constantExpression? ']' | LP parameterDeclarationList? RP ; parameterDeclarationList : parameterDeclaration (',' parameterDeclaration)* ; parameterDeclaration : declarationSpecifiers declarator | 'void' ; declarator : pointer? directDeclarator ; statement : labeledStatement ';'? | compoundStatement ';'? | selectionStatement ';'? | iterationStatement ';'? | jumpStatement ';'? | synchronizedStatement ';'? | autoreleaseStatement ';'? | throwStatement ';'? | tryBlock ';'? | expressions ';'? | ';' ; labeledStatement : identifier ':' statement ; rangeExpression : constantExpression ('...' constantExpression)? ; compoundStatement : '{' (declaration | statement)* '}' ; selectionStatement : IF LP expression RP ifBody=statement (ELSE elseBody=statement)? | switchStatement ; switchStatement : 'switch' LP expression RP switchBlock ; switchBlock : '{' switchSection* '}' ; switchSection : switchLabel+ statement+ ; switchLabel : 'case' (rangeExpression | LP rangeExpression RP) ':' | 'default' ':' ; iterationStatement : whileStatement | doStatement | forStatement | forInStatement ; whileStatement : 'while' LP expression RP statement ; doStatement : 'do' statement 'while' LP expression RP ';' ; forStatement : 'for' LP forLoopInitializer? ';' expression? ';' expressions? RP statement ; forLoopInitializer : declarationSpecifiers initDeclaratorList | expressions ; forInStatement : 'for' LP typeVariableDeclarator 'in' expression? RP statement ; jumpStatement : GOTO identifier | CONTINUE | BREAK | RETURN expression? ; expressions : expression (',' expression)* ; expression : castExpression | expression op=(MUL | DIV | MOD) expression | expression op=(ADD | SUB) expression | expression (LT LT | GT GT) expression | expression op=(LE | GE | LT | GT) expression | expression op=(NOTEQUAL | EQUAL) expression | expression op=BITAND expression | expression op=BITXOR expression | expression op=BITOR expression | expression op=AND expression | expression op=OR expression | expression QUESTION trueExpression=expression? COLON falseExpression=expression | LP compoundStatement RP | unaryExpression assignmentOperator assignmentExpression=expression ; assignmentOperator : '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' ; castExpression : unaryExpression | (LP typeName RP) (castExpression | initializer) ; initializer : expression | arrayInitializer | structInitializer ; constantExpression : identifier | constant ; unaryExpression : postfixExpression | SIZEOF (unaryExpression | LP typeSpecifier RP) | op=(INC | DEC) unaryExpression | unaryOperator castExpression ; unaryOperator : '&' | '*' | '+' | '-' | '~' | BANG ; postfixExpression : primaryExpression postfix* | postfixExpression (DOT | STRUCTACCESS) identifier postfix* // TODO: get rid of property and postfix expression. ; postfix : LBRACK expression RBRACK | LP argumentExpressionList? RP | LP (COMMA | macroArguments+=~RP)+ RP | op=(INC | DEC) ; argumentExpressionList : argumentExpression (',' argumentExpression)* ; argumentExpression : expression | typeSpecifier ; primaryExpression : identifier | constant | stringLiteral | LP expression RP | messageExpression | selectorExpression | protocolExpression | encodeExpression | dictionaryExpression | arrayExpression | boxExpression | blockExpression ; constant : HEX_LITERAL | OCTAL_LITERAL | BINARY_LITERAL | ('+' | '-')? DECIMAL_LITERAL | ('+' | '-')? FLOATING_POINT_LITERAL | CHARACTER_LITERAL | NIL | NULL_ | YES | NO | TRUE | FALSE ; stringLiteral : (STRING_START (STRING_VALUE | STRING_NEWLINE)* STRING_END)+ ; identifier : IDENTIFIER | BOOL | Class | BYCOPY | BYREF | ID | IMP | IN | INOUT | ONEWAY | OUT | PROTOCOL_ | SEL | SELF | SUPER | ATOMIC | NONATOMIC | RETAIN | AUTORELEASING_QUALIFIER | BLOCK | BRIDGE_RETAINED | BRIDGE_TRANSFER | COVARIANT | CONTRAVARIANT | DEPRECATED | KINDOF | UNUSED | NS_INLINE | NS_ENUM | NS_OPTIONS | NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE | ASSIGN | COPY | GETTER | SETTER | STRONG | READONLY | READWRITE | WEAK | UNSAFE_UNRETAINED | IB_OUTLET | IB_OUTLET_COLLECTION | IB_INSPECTABLE | IB_DESIGNABLE ;
/* Objective-C grammar. The MIT License (MIT). Copyright (c) 2016-2017, Alex Petuschak ([email protected]). Copyright (c) 2016-2017, Ivan Kochurkin ([email protected]). Converted to ANTLR 4 by Terence Parr; added @property and a few others. Updated June 2014, Carlos Mejia. Fix try-catch, add support for @( @{ @[ and blocks June 2008 Cedric Cuche Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ parser grammar ObjectiveCParser; options { tokenVocab=ObjectiveCLexer; } translationUnit : topLevelDeclaration* EOF ; topLevelDeclaration : importDeclaration | functionDeclaration | declaration | classInterface | classImplementation | categoryInterface | categoryImplementation | protocolDeclaration | protocolDeclarationList | classDeclarationList | functionDefinition ; importDeclaration : '@import' identifier ';' ; classInterface : IB_DESIGNABLE? '@interface' className=genericTypeSpecifier (':' superclassName=identifier)? (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; categoryInterface : '@interface' categoryName=genericTypeSpecifier LP className=identifier? RP (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; classImplementation : '@implementation' className=genericTypeSpecifier (':' superclassName=identifier)? instanceVariables? implementationDefinitionList? '@end' ; categoryImplementation : '@implementation' categoryName=genericTypeSpecifier LP className=identifier RP implementationDefinitionList? '@end' ; genericTypeSpecifier : identifier ((LT protocolList GT) | genericsSpecifier)? ; protocolDeclaration : '@protocol' protocolName (LT protocolList GT)? protocolDeclarationSection* '@end' ; protocolDeclarationSection : modifier=(REQUIRED | OPTIONAL) interfaceDeclarationList* | interfaceDeclarationList+ ; protocolDeclarationList : '@protocol' protocolList ';' ; classDeclarationList : '@class' identifier (',' identifier)* ';' ; protocolList : protocolName (',' protocolName)* ; propertyDeclaration : '@property' (LP propertyAttributesList RP)? ibOutletQualifier? IB_INSPECTABLE? fieldDeclaration ; propertyAttributesList : propertyAttribute (',' propertyAttribute)* ; propertyAttribute : ATOMIC | NONATOMIC | STRONG | WEAK | RETAIN | ASSIGN | UNSAFE_UNRETAINED | COPY | READONLY | READWRITE | GETTER '=' identifier | SETTER '=' identifier ':' | nullabilitySpecifier | identifier ; protocolName : LT protocolList GT | ('__covariant' | '__contravariant')? identifier ; instanceVariables : '{' visibilitySection* '}' ; visibilitySection : accessModifier fieldDeclaration* | fieldDeclaration+ ; accessModifier : PRIVATE | PROTECTED | PACKAGE | PUBLIC ; interfaceDeclarationList : (declaration | classMethodDeclaration | instanceMethodDeclaration | propertyDeclaration | functionDeclaration)+ ; classMethodDeclaration : '+' methodDeclaration ; instanceMethodDeclaration : '-' methodDeclaration ; methodDeclaration : methodType? methodSelector macro? ';' ; implementationDefinitionList : (functionDefinition | declaration | classMethodDefinition | instanceMethodDefinition | propertyImplementation )+; classMethodDefinition : '+' methodDefinition ; instanceMethodDefinition : '-' methodDefinition ; methodDefinition : methodType? methodSelector initDeclaratorList? ';'? compoundStatement ; methodSelector : selector | keywordDeclarator+ (',' '...')? ; keywordDeclarator : selector? ':' methodType* arcBehaviourSpecifier? identifier ; selector : identifier | 'return' ; methodType : LP typeName RP ; propertyImplementation : '@synthesize' propertySynthesizeList ';' | '@dynamic' propertySynthesizeList ';' ; propertySynthesizeList : propertySynthesizeItem (',' propertySynthesizeItem)* ; propertySynthesizeItem : identifier ('=' identifier)? ; blockType : nullabilitySpecifier? typeSpecifier nullabilitySpecifier? LP '^' (nullabilitySpecifier | typeSpecifier)? RP blockParameters? ; genericsSpecifier : LT (typeSpecifierWithPrefixes (',' typeSpecifierWithPrefixes)*)? GT ; typeSpecifierWithPrefixes : typePrefix* typeSpecifier | typeName ; dictionaryExpression : '@' '{' (dictionaryPair (',' dictionaryPair)* ','?)? '}' ; dictionaryPair : castExpression ':' expression ; arrayExpression : '@' '[' (expressions ','?)? ']' ; boxExpression : '@' LP expression RP | '@' (constant | identifier) ; blockParameters : LP ((typeVariableDeclaratorOrName | 'void') (',' typeVariableDeclaratorOrName)*)? RP ; typeVariableDeclaratorOrName : typeVariableDeclarator | typeName ; blockExpression : '^' typeSpecifier? nullabilitySpecifier? blockParameters? compoundStatement ; messageExpression : '[' receiver messageSelector ']' ; receiver : expression | typeSpecifier ; messageSelector : selector | keywordArgument+ ; keywordArgument : selector? ':' keywordArgumentType (',' keywordArgumentType)* ; keywordArgumentType : expressions nullabilitySpecifier? ('{' initializerList '}')? ; selectorExpression : '@selector' LP selectorName RP ; selectorName : selector | (selector? ':')+ ; protocolExpression : '@protocol' LP protocolName RP ; encodeExpression : '@encode' LP typeName RP ; typeVariableDeclarator : declarationSpecifiers declarator ; throwStatement : '@throw' LP identifier RP | '@throw' expression ; tryBlock : '@try' tryStatement=compoundStatement catchStatement* ('@finally' finallyStatement=compoundStatement)? ; catchStatement : '@catch' LP typeVariableDeclarator RP compoundStatement ; synchronizedStatement : '@synchronized' LP expression RP compoundStatement ; autoreleaseStatement : '@autoreleasepool' compoundStatement ; functionDeclaration : functionSignature ';' ; functionDefinition : functionSignature compoundStatement ; functionSignature : declarationSpecifiers? identifier (LP parameterList? RP) attributeSpecifier? ; attribute : attributeName attributeParameters? ; attributeName : 'const' | identifier ; attributeParameters : LP attributeParameterList? RP ; attributeParameterList : attributeParameter (',' attributeParameter)* ; attributeParameter : attribute | constant | stringLiteral | attributeParameterAssignment ; attributeParameterAssignment : attributeName '=' (constant | attributeName | stringLiteral) ; declaration : functionCallExpression | enumDeclaration | varDeclaration | typedefDeclaration ; functionCallExpression : attributeSpecifier? identifier attributeSpecifier? LP directDeclarator RP ';' ; enumDeclaration : attributeSpecifier? TYPEDEF? enumSpecifier identifier? ';' ; varDeclaration : (declarationSpecifiers initDeclaratorList | declarationSpecifiers) ';' ; typedefDeclaration : attributeSpecifier? TYPEDEF (declarationSpecifiers typeDeclaratorList | declarationSpecifiers) ';' ; typeDeclaratorList : typeDeclarator (',' typeDeclarator)* ; typeDeclarator : pointer? directDeclarator ; declarationSpecifiers : (storageClassSpecifier | attributeSpecifier | arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; attributeSpecifier : '__attribute__' LP LP attribute (',' attribute)* RP RP ; initDeclaratorList : initDeclarator (',' initDeclarator)* ; initDeclarator : declarator ('=' initializer)? ; structOrUnionSpecifier : ('struct' | 'union') (identifier | identifier? '{' fieldDeclaration+ '}') ; fieldDeclaration : specifierQualifierList fieldDeclaratorList macro? ';' ; specifierQualifierList : (arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; ibOutletQualifier : IB_OUTLET_COLLECTION LP identifier RP | IB_OUTLET ; arcBehaviourSpecifier : WEAK_QUALIFIER | STRONG_QUALIFIER | AUTORELEASING_QUALIFIER | UNSAFE_UNRETAINED_QUALIFIER ; nullabilitySpecifier : NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE ; storageClassSpecifier : AUTO | REGISTER | STATIC | EXTERN ; typePrefix : BRIDGE | BRIDGE_TRANSFER | BRIDGE_RETAINED | BLOCK | INLINE | NS_INLINE | KINDOF ; typeQualifier : CONST | VOLATILE | RESTRICT | protocolQualifier ; protocolQualifier : 'in' | 'out' | 'inout' | 'bycopy' | 'byref' | 'oneway' ; typeSpecifier : 'void' | 'char' | 'short' | 'int' | 'long' | 'float' | 'double' | 'signed' | 'unsigned' | typeofExpression | genericTypeSpecifier | structOrUnionSpecifier | enumSpecifier | identifier pointer? ; typeofExpression : TYPEOF (LP expression RP) ; fieldDeclaratorList : fieldDeclarator (',' fieldDeclarator)* ; fieldDeclarator : declarator | declarator? ':' constant ; enumSpecifier : 'enum' (identifier? ':' typeName)? (identifier ('{' enumeratorList '}')? | '{' enumeratorList '}') | ('NS_OPTIONS' | 'NS_ENUM') LP typeName ',' identifier RP '{' enumeratorList '}' ; enumeratorList : enumerator (',' enumerator)* ','? ; enumerator : enumeratorIdentifier ('=' expression)? ; enumeratorIdentifier : identifier | 'default' ; directDeclarator : (identifier | LP declarator RP) declaratorSuffix* | LP '^' nullabilitySpecifier? identifier? RP blockParameters ; declaratorSuffix : '[' constantExpression? ']' ; parameterList : parameterDeclarationList (',' '...')? ; pointer : '*' declarationSpecifiers? pointer? ; macro : identifier (LP primaryExpression (',' primaryExpression)* RP)? ; arrayInitializer : '{' (expressions ','?)? '}' ; structInitializer : '{' ('.' expression (',' '.' expression)* ','?)? '}' ; initializerList : initializer (',' initializer)* ','? ; typeName : specifierQualifierList abstractDeclarator? | blockType ; abstractDeclarator : pointer abstractDeclarator? | LP abstractDeclarator? RP abstractDeclaratorSuffix+ | ('[' constantExpression? ']')+ ; abstractDeclaratorSuffix : '[' constantExpression? ']' | LP parameterDeclarationList? RP ; parameterDeclarationList : parameterDeclaration (',' parameterDeclaration)* ; parameterDeclaration : declarationSpecifiers declarator | 'void' ; declarator : pointer? directDeclarator ; statement : labeledStatement ';'? | compoundStatement ';'? | selectionStatement ';'? | iterationStatement ';'? | jumpStatement ';'? | synchronizedStatement ';'? | autoreleaseStatement ';'? | throwStatement ';'? | tryBlock ';'? | expressions ';'? | ';' ; labeledStatement : identifier ':' statement ; rangeExpression : constantExpression ('...' constantExpression)? ; compoundStatement : '{' (declaration | statement)* '}' ; selectionStatement : IF LP expression RP ifBody=statement (ELSE elseBody=statement)? | switchStatement ; switchStatement : 'switch' LP expression RP switchBlock ; switchBlock : '{' switchSection* '}' ; switchSection : switchLabel+ statement+ ; switchLabel : 'case' (rangeExpression | LP rangeExpression RP) ':' | 'default' ':' ; iterationStatement : whileStatement | doStatement | forStatement | forInStatement ; whileStatement : 'while' LP expression RP statement ; doStatement : 'do' statement 'while' LP expression RP ';' ; forStatement : 'for' LP forLoopInitializer? ';' expression? ';' expressions? RP statement ; forLoopInitializer : declarationSpecifiers initDeclaratorList | expressions ; forInStatement : 'for' LP typeVariableDeclarator 'in' expression? RP statement ; jumpStatement : GOTO identifier | CONTINUE | BREAK | RETURN expression? ; expressions : expression (',' expression)* ; expression : castExpression | expression op=(MUL | DIV | MOD) expression | expression op=(ADD | SUB) expression | expression (LT LT | GT GT) expression | expression op=(LE | GE | LT | GT) expression | expression op=(NOTEQUAL | EQUAL) expression | expression op=BITAND expression | expression op=BITXOR expression | expression op=BITOR expression | expression op=AND expression | expression op=OR expression | expression QUESTION trueExpression=expression? COLON falseExpression=expression | LP compoundStatement RP | unaryExpression assignmentOperator assignmentExpression=expression ; assignmentOperator : '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' ; castExpression : unaryExpression | (LP typeName RP) (castExpression | initializer) ; initializer : expression | arrayInitializer | structInitializer ; constantExpression : identifier | constant ; unaryExpression : postfixExpression | SIZEOF (unaryExpression | LP typeSpecifier RP) | op=(INC | DEC) unaryExpression | unaryOperator castExpression ; unaryOperator : '&' | '*' | '+' | '-' | '~' | BANG ; postfixExpression : primaryExpression postfix* | postfixExpression (DOT | STRUCTACCESS) identifier postfix* // TODO: get rid of property and postfix expression. ; postfix : LBRACK expression RBRACK | LP argumentExpressionList? RP | LP (COMMA | macroArguments+=~RP)+ RP | op=(INC | DEC) ; argumentExpressionList : argumentExpression (',' argumentExpression)* ; argumentExpression : expression | typeSpecifier ; primaryExpression : identifier | constant | stringLiteral | LP expression RP | messageExpression | selectorExpression | protocolExpression | encodeExpression | dictionaryExpression | arrayExpression | boxExpression | blockExpression ; constant : HEX_LITERAL | OCTAL_LITERAL | BINARY_LITERAL | ('+' | '-')? DECIMAL_LITERAL | ('+' | '-')? FLOATING_POINT_LITERAL | CHARACTER_LITERAL | NIL | NULL_ | YES | NO | TRUE | FALSE ; stringLiteral : (STRING_START (STRING_VALUE | STRING_NEWLINE)* STRING_END)+ ; identifier : IDENTIFIER | BOOL | Class | BYCOPY | BYREF | ID | IMP | IN | INOUT | ONEWAY | OUT | PROTOCOL_ | SEL | SELF | SUPER | ATOMIC | NONATOMIC | RETAIN | AUTORELEASING_QUALIFIER | BLOCK | BRIDGE_RETAINED | BRIDGE_TRANSFER | COVARIANT | CONTRAVARIANT | DEPRECATED | KINDOF | UNUSED | NS_INLINE | NS_ENUM | NS_OPTIONS | NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE | ASSIGN | COPY | GETTER | SETTER | STRONG | READONLY | READWRITE | WEAK | UNSAFE_UNRETAINED | IB_OUTLET | IB_OUTLET_COLLECTION | IB_INSPECTABLE | IB_DESIGNABLE ;
Add nest generic type support, such as ’NSDictionary<NSNumber *, NSArray<NSString *> *>’.
Add nest generic type support, such as ’NSDictionary<NSNumber *, NSArray<NSString *> *>’.
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
7232d121c70396086c6d3c9b75dda14c98d7c248
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
sharding-core/src/main/antlr4/imports/SQLServerKeyword.g4
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; ALGORITHM : A L G O R I T H M ; ALLOW_PAGE_LOCKS : A L L O W UL_ P A G E UL_ L O C K S ; ALLOW_ROW_LOCKS : A L L O W UL_ R O W UL_ L O C K S ; ALL_SPARSE_COLUMNS : A L L UL_ S P A R S E UL_ C O L U M N S ; AUTO : A U T O ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; COLUMNSTORE : C O L U M N S T O R E ; COLUMNSTORE_ARCHIVE : C O L U M N S T O R E UL_ A R C H I V E ; COLUMN_ENCRYPTION_KEY : C O L U M N UL_ E N C R Y P T I O N UL_ K E Y ; COLUMN_SET : C O L U M N UL_ S E T ; COMPRESSION_DELAY : C O M P R E S S I O N UL_ D E L A Y ; CONTENT : C O N T E N T ; CONVERT : C O N V E R T ; CURRENT : C U R R E N T ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L T ; DATA_COMPRESSION : D A T A UL_ C O M P R E S S I O N ; DATA_CONSISTENCY_CHECK : D A T A UL_ C O N S I S T E N C Y UL_ C H E C K ; DAY : D A Y ; DAYS : D A Y S ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; ENCRYPTED : E N C R Y P T E D ; ENCRYPTION_TYPE : E N C R Y P T I O N UL_ T Y P E ; END : E N D ; FILESTREAM : F I L E S T R E A M ; FILESTREAM_ON : F I L E S T R E A M UL_ O N ; FILETABLE : F I L E T A B L E ; FILETABLE_COLLATE_FILENAME : F I L E T A B L E UL_ C O L L A T E UL_ F I L E N A M E ; FILETABLE_DIRECTORY : F I L E T A B L E UL_ D I R E C T O R Y ; FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME : F I L E T A B L E UL_ F U L L P A T H UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E ; FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME : F I L E T A B L E UL_ P R I M A R Y UL_ K E Y UL_ C O N S T R A I N T UL_ N A M E ; FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME : F I L E T A B L E UL_ S T R E A M I D UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; HASH : H A S H ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; HISTORY_RETENTION_PERIOD : H I S T O R Y UL_ R E T E N T I O N UL_ P E R I O D ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; IGNORE_DUP_KEY : I G N O R E UL_ D U P UL_ K E Y ; INBOUND : I N B O U N D ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; MEMORY_OPTIMIZED : M E M O R Y UL_ O P T I M I Z E D ; MIGRATION_STATE : M I G R A T I O N UL_ S T A T E ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OFF : O F F ; ONLINE : O N L I N E ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; PAD_INDEX : P A D UL_ I N D E X ; PAGE : P A G E ; PARTITIONS : P A R T I T I O N S ; PAUSED : P A U S E D ; PERIOD : P E R I O D ; PERSISTED : P E R S I S T E D ; PRECEDING : P R E C E D I N G ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; RIGHT : R I G H T ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA_AND_DATA : S C H E M A UL_ A N D UL_ D A T A ; SCHEMA_ONLY : S C H E M A UL_ O N L Y ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; STATISTICS_INCREMENTAL : S T A T I S T I C S UL_ I N C R E M E N T A L ; STATISTICS_NORECOMPUTE : S T A T I S T I C S UL_ N O R E C O M P U T E ; SWITCH : S W I T C H ; SYSTEM_TIME : S Y S T E M UL_ T I M E ; SYSTEM_VERSIONING : S Y S T E M UL_ V E R S I O N I N G ; TEXTIMAGE_ON : T E X T I M A G E UL_ O N ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UPDATE : U P D A T E ; VALUES : V A L U E S ; WAIT_AT_LOW_PRIORITY : W A I T UL_ A T UL_ L O W UL_ P R I O R I T Y ; WEEK : W E E K ; WEEKS : W E E K S ; YEARS : Y E A R S ; ZONE : Z O N E ;
lexer grammar SQLServerKeyword; import Symbol; ABORT_AFTER_WAIT : A B O R T UL_ A F T E R UL_ W A I T ; ACTION : A C T I O N ; ALGORITHM : A L G O R I T H M ; ALLOW_PAGE_LOCKS : A L L O W UL_ P A G E UL_ L O C K S ; ALLOW_ROW_LOCKS : A L L O W UL_ R O W UL_ L O C K S ; ALL_SPARSE_COLUMNS : A L L UL_ S P A R S E UL_ C O L U M N S ; AUTO : A U T O ; BEGIN : B E G I N ; BLOCKERS : B L O C K E R S ; BUCKET_COUNT : B U C K E T UL_ C O U N T ; CAST : C A S T ; CLUSTERED : C L U S T E R E D ; COLLATE : C O L L A T E ; COLONCOLON : C O L O N C O L O N ; COLUMNSTORE : C O L U M N S T O R E ; COLUMNSTORE_ARCHIVE : C O L U M N S T O R E UL_ A R C H I V E ; COLUMN_ENCRYPTION_KEY : C O L U M N UL_ E N C R Y P T I O N UL_ K E Y ; COLUMN_SET : C O L U M N UL_ S E T ; COMPRESSION_DELAY : C O M P R E S S I O N UL_ D E L A Y ; CONTENT : C O N T E N T ; CONVERT : C O N V E R T ; CURRENT : C U R R E N T ; DATABASE : D A T A B A S E ; DATABASE_DEAULT : D A T A B A S E UL_ D E A U L T ; DATA_COMPRESSION : D A T A UL_ C O M P R E S S I O N ; DATA_CONSISTENCY_CHECK : D A T A UL_ C O N S I S T E N C Y UL_ C H E C K ; DAY : D A Y ; DAYS : D A Y S ; DELAYED_DURABILITY : D E L A Y E D UL_ D U R A B I L I T Y ; DETERMINISTIC : D E T E R M I N I S T I C ; DISTRIBUTION : D I S T R I B U T I O N ; DOCUMENT : D O C U M E N T ; DROP_EXISTING : D R O P UL_ E X I S T I N G ; DURABILITY : D U R A B I L I T Y ; DW : D W ; ENCRYPTED : E N C R Y P T E D ; ENCRYPTION_TYPE : E N C R Y P T I O N UL_ T Y P E ; END : E N D ; FILESTREAM : F I L E S T R E A M ; FILESTREAM_ON : F I L E S T R E A M UL_ O N ; FILETABLE : F I L E T A B L E ; FILETABLE_COLLATE_FILENAME : F I L E T A B L E UL_ C O L L A T E UL_ F I L E N A M E ; FILETABLE_DIRECTORY : F I L E T A B L E UL_ D I R E C T O R Y ; FILETABLE_FULLPATH_UNIQUE_CONSTRAINT_NAME : F I L E T A B L E UL_ F U L L P A T H UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E ; FILETABLE_PRIMARY_KEY_CONSTRAINT_NAME : F I L E T A B L E UL_ P R I M A R Y UL_ K E Y UL_ C O N S T R A I N T UL_ N A M E ; FILETABLE_STREAMID_UNIQUE_CONSTRAINT_NAME : F I L E T A B L E UL_ S T R E A M I D UL_ U N I Q U E UL_ C O N S T R A I N T UL_ N A M E ; FILLFACTOR : F I L L F A C T O R ; FILTER_PREDICATE : F I L T E R UL_ P R E D I C A T E ; FOLLOWING : F O L L O W I N G ; FOR : F O R ; FUNCTION : F U N C T I O N ; GRANT : G R A N T ; HASH : H A S H ; HEAP : H E A P ; HIDDEN_ : H I D D E N UL_ ; HISTORY_RETENTION_PERIOD : H I S T O R Y UL_ R E T E N T I O N UL_ P E R I O D ; HISTORY_TABLE : H I S T O R Y UL_ T A B L E ; IDENTITY : I D E N T I T Y ; IGNORE_DUP_KEY : I G N O R E UL_ D U P UL_ K E Y ; INBOUND : I N B O U N D ; INFINITE : I N F I N I T E ; LEFT : L E F T ; LEFT_BRACKET : L E F T UL_ B R A C K E T ; LOCK_ESCALATION : L O C K UL_ E S C A L A T I O N ; LOGIN : L O G I N ; MARK : M A R K ; MASKED : M A S K E D ; MAX : M A X ; MAXDOP : M A X D O P ; MAX_DURATION : M A X UL_ D U R A T I O N ; MEMORY_OPTIMIZED : M E M O R Y UL_ O P T I M I Z E D ; MIGRATION_STATE : M I G R A T I O N UL_ S T A T E ; MINUTES : M I N U T E S ; MONTH : M O N T H ; MONTHS : M O N T H S ; MOVE : M O V E ; NOCHECK : N O C H E C K ; NONCLUSTERED : N O N C L U S T E R E D ; NONE : N O N E ; OBJECT : O B J E C T ; OFF : O F F ; ONLINE : O N L I N E ; OPTION : O P T I O N ; OUTBOUND : O U T B O U N D ; OVER : O V E R ; PAD_INDEX : P A D UL_ I N D E X ; PAGE : P A G E ; PARTITIONS : P A R T I T I O N S ; PAUSED : P A U S E D ; PERIOD : P E R I O D ; PERSISTED : P E R S I S T E D ; PRECEDING : P R E C E D I N G ; PRIVILEGES : P R I V I L E G E S ; RANDOMIZED : R A N D O M I Z E D ; RANGE : R A N G E ; REBUILD : R E B U I L D ; REMOTE_DATA_ARCHIVE : R E M O T E UL_ D A T A UL_ A R C H I V E ; REPEATABLE : R E P E A T A B L E ; REPLICATE : R E P L I C A T E ; REPLICATION : R E P L I C A T I O N ; RESUMABLE : R E S U M A B L E ; RIGHT : R I G H T ; RIGHT_BRACKET : R I G H T UL_ B R A C K E T ; ROLE : R O L E ; ROUND_ROBIN : R O U N D UL_ R O B I N ; ROWGUIDCOL : R O W G U I D C O L ; ROWS : R O W S ; SAVE : S A V E ; SCHEMA : S C H E M A ; SCHEMA_AND_DATA : S C H E M A UL_ A N D UL_ D A T A ; SCHEMA_ONLY : S C H E M A UL_ O N L Y ; SELF : S E L F ; SNAPSHOT : S N A P S H O T ; SORT_IN_TEMPDB : S O R T UL_ I N UL_ T E M P D B ; SPARSE : S P A R S E ; STATISTICS_INCREMENTAL : S T A T I S T I C S UL_ I N C R E M E N T A L ; STATISTICS_NORECOMPUTE : S T A T I S T I C S UL_ N O R E C O M P U T E ; SWITCH : S W I T C H ; SYSTEM_TIME : S Y S T E M UL_ T I M E ; SYSTEM_VERSIONING : S Y S T E M UL_ V E R S I O N I N G ; TEXTIMAGE_ON : T E X T I M A G E UL_ O N ; TRAN : T R A N ; TRIGGER : T R I G G E R ; UNBOUNDED : U N B O U N D E D ; UNCOMMITTED : U N C O M M I T T E D ; UPDATE : U P D A T E ; USER : U S E R ; VALUES : V A L U E S ; WAIT_AT_LOW_PRIORITY : W A I T UL_ A T UL_ L O W UL_ P R I O R I T Y ; WEEK : W E E K ; WEEKS : W E E K S ; YEARS : Y E A R S ; ZONE : Z O N E ;
add keyword
add keyword
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere
c5b5ec60ca76d3ac7df15118252591f63d36618c
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
src/main/antlr/com/github/oreissig/footran1/parser/Footran.g4
grammar Footran; @header { package com.github.oreissig.footran1.parser; } @lexer::members { /** * FORTRAN-I encapsulates type information in its identifiers, but * unfortunately there are cases that require context to be certain: * IDs with 4 or more characters ending with 'F' may either denote a * non-subscripted variable or a function. * * @param text the ID to analyze * @return true if we know for sure, that text is a variable ID */ private boolean isVariable(String text) { return text.length() < 4 || !text.endsWith("F"); } } // parser rules program : card*; card : STMTNUM? statement NEWCARD?; statement : arithmeticFormula // TODO more to come ; arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression; subscript : VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression)?)? ')'; subscriptExpression : VAR_ID | uintConst | subscriptSum; subscriptSum : subscriptMult (sign uintConst)?; subscriptMult : (uintConst '*')? VAR_ID; expression : VAR_ID | call | intConst | fpConst; // treat subscripted variables as function calls call : FUNC_CANDIDATE '(' expression (',' expression)* ')'; uintConst : NUMBER ; intConst : sign? unsigned=uintConst ; ufpConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=intConst)? ; fpConst : sign? unsigned=ufpConst ; sign : (PLUS|MINUS); // lexer rules // prefix area processing COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ; STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ; CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ; // body processing fragment DIGIT : {getCharPositionInLine() > 5}? [0-9]; fragment LETTER : {getCharPositionInLine() > 5}? [A-Z]; fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9]; NUMBER : DIGIT+ ; // use a separate token to avoid recognizing the float exponential E as ID FLOAT_FRAC : NUMBER 'E'; VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ; // function candidate refers to either a function or a non-subscripted variable FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ; PLUS : '+'; MINUS : '-'; // return newlines to parser NEWCARD : '\r'? '\n' ; // skip spaces and tabs WS : ' '+ -> skip ;
/* * A grammar for the original version of FORTRAN as described * by IBM's programmer's reference manual from 1956: * http://www.fortran.com/FortranForTheIBM704.pdf * * This grammar tries to keep its wording close to the original * language reference, e.g. an array is called subscripted * variable. */ grammar Footran; @header { package com.github.oreissig.footran1.parser; } @lexer::members { /** * FORTRAN-I encapsulates type information in its identifiers, but * unfortunately there are cases that require context to be certain: * IDs with 4 or more characters ending with 'F' may either denote a * non-subscripted variable or a function. * * @param text the ID to analyze * @return true if we know for sure, that text is a variable ID */ private boolean isVariable(String text) { return text.length() < 4 || !text.endsWith("F"); } } // parser rules program : card*; card : STMTNUM? statement NEWCARD?; statement : arithmeticFormula // TODO more to come ; arithmeticFormula : (VAR_ID | FUNC_CANDIDATE | subscript) '=' expression; subscript : VAR_ID '(' subscriptExpression (',' subscriptExpression (',' subscriptExpression)?)? ')'; subscriptExpression : VAR_ID | uintConst | subscriptSum; subscriptSum : subscriptMult (sign uintConst)?; subscriptMult : (uintConst '*')? VAR_ID; expression : VAR_ID | call | intConst | fpConst; // treat subscripted variables as function calls call : FUNC_CANDIDATE '(' expression (',' expression)* ')'; uintConst : NUMBER ; intConst : sign? unsigned=uintConst ; ufpConst : integer=NUMBER? '.' (fraction=NUMBER | fractionE=FLOAT_FRAC exponent=intConst)? ; fpConst : sign? unsigned=ufpConst ; sign : (PLUS|MINUS); // lexer rules // prefix area processing COMMENT : {getCharPositionInLine() == 0}? 'C' ~('\n')* '\n'? -> skip ; STMTNUM : {getCharPositionInLine() < 5}? [0-9]+ ; CONTINUE : NEWCARD . . . . . ~[' '|'0'] -> skip ; // body processing fragment DIGIT : {getCharPositionInLine() > 5}? [0-9]; fragment LETTER : {getCharPositionInLine() > 5}? [A-Z]; fragment ALFNUM : {getCharPositionInLine() > 5}? [A-Z0-9]; NUMBER : DIGIT+ ; // use a separate token to avoid recognizing the float exponential E as ID FLOAT_FRAC : NUMBER 'E'; VAR_ID : LETTER ALFNUM* {isVariable(getText())}? ; // function candidate refers to either a function or a non-subscripted variable FUNC_CANDIDATE : LETTER ALFNUM+ {!isVariable(getText())}? ; PLUS : '+'; MINUS : '-'; // return newlines to parser NEWCARD : '\r'? '\n' ; // skip spaces and tabs WS : ' '+ -> skip ;
add description to grammar
add description to grammar
ANTLR
isc
oreissig/FOOTRAN-I
5996409186a27badff87fb586039362c03633f12
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
sharding-core/sharding-core-parse/sharding-core-parse-mysql/src/main/antlr4/imports/mysql/DDLStatement.g4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createSpecification_ TABLE notExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE (UNIQUE | FULLTEXT | SPATIAL)? INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createSpecification_ : TEMPORARY? ; notExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnName (COMMA_ columnName)* | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ grammar DDLStatement; import Symbol, Keyword, Literals, BaseRule; createTable : CREATE createTableSpecification_ TABLE notExistClause_ tableName (createDefinitionClause_ | createLikeClause_) ; createIndex : CREATE createIndexSpecification_ INDEX indexName indexType_? ON tableName ; alterTable : ALTER TABLE tableName alterSpecifications_? ; dropTable : DROP TEMPORARY? TABLE (IF EXISTS)? tableName (COMMA_ tableName)* ; dropIndex : DROP INDEX (ONLINE | OFFLINE)? indexName ON tableName ; truncateTable : TRUNCATE TABLE? tableName ; createTableSpecification_ : TEMPORARY? ; notExistClause_ : (IF NOT EXISTS)? ; createDefinitionClause_ : LP_ createDefinitions_ RP_ ; createDefinitions_ : createDefinition_ (COMMA_ createDefinition_)* ; createDefinition_ : columnDefinition | indexDefinition_ | constraintDefinition_ | checkConstraintDefinition_ ; columnDefinition : columnName dataType (inlineDataType_* | generatedDataType_*) ; inlineDataType_ : commonDataTypeOption_ | AUTO_INCREMENT | DEFAULT (literals | expr) | COLUMN_FORMAT (FIXED | DYNAMIC | DEFAULT) | STORAGE (DISK | MEMORY | DEFAULT) ; commonDataTypeOption_ : primaryKey | UNIQUE KEY? | NOT? NULL | collateName_ | checkConstraintDefinition_ | referenceDefinition_ | COMMENT STRING_ ; checkConstraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? CHECK expr (NOT? ENFORCED)? ; referenceDefinition_ : REFERENCES tableName keyParts_ (MATCH FULL | MATCH PARTIAL | MATCH SIMPLE)? (ON (UPDATE | DELETE) referenceOption_)* ; referenceOption_ : RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT ; generatedDataType_ : commonDataTypeOption_ | (GENERATED ALWAYS)? AS expr | (VIRTUAL | STORED) ; indexDefinition_ : (FULLTEXT | SPATIAL)? (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; indexType_ : USING (BTREE | HASH) ; keyParts_ : LP_ keyPart_ (COMMA_ keyPart_)* RP_ ; keyPart_ : (columnName (LP_ NUMBER_ RP_)? | expr) (ASC | DESC)? ; indexOption_ : KEY_BLOCK_SIZE EQ_? NUMBER_ | indexType_ | WITH PARSER identifier_ | COMMENT STRING_ | VISIBLE | INVISIBLE ; constraintDefinition_ : (CONSTRAINT ignoredIdentifier_?)? (primaryKeyOption_ | uniqueOption_ | foreignKeyOption_) ; primaryKeyOption_ : primaryKey indexType_? columnNames indexOption_* ; primaryKey : PRIMARY? KEY ; uniqueOption_ : UNIQUE (INDEX | KEY)? indexName? indexType_? keyParts_ indexOption_* ; foreignKeyOption_ : FOREIGN KEY indexName? columnNames referenceDefinition_ ; createLikeClause_ : LP_? LIKE tableName RP_? ; createIndexSpecification_ : (UNIQUE | FULLTEXT | SPATIAL)? ; alterSpecifications_ : alterSpecification_ (COMMA_ alterSpecification_)* ; alterSpecification_ : tableOptions_ | addColumnSpecification | addIndexSpecification | addConstraintSpecification | ADD checkConstraintDefinition_ | DROP CHECK ignoredIdentifier_ | ALTER CHECK ignoredIdentifier_ NOT? ENFORCED | ALGORITHM EQ_? (DEFAULT | INSTANT | INPLACE | COPY) | ALTER COLUMN? columnName (SET DEFAULT literals | DROP DEFAULT) | ALTER INDEX indexName (VISIBLE | INVISIBLE) | changeColumnSpecification | DEFAULT? characterSet_ collateClause_? | CONVERT TO characterSet_ collateClause_? | (DISABLE | ENABLE) KEYS | (DISCARD | IMPORT_) TABLESPACE | dropColumnSpecification | dropIndexSpecification | dropPrimaryKeySpecification | DROP FOREIGN KEY ignoredIdentifier_ | FORCE | LOCK EQ_? (DEFAULT | NONE | SHARED | EXCLUSIVE) | modifyColumnSpecification // TODO hongjun investigate ORDER BY col_name [, col_name] ... | ORDER BY columnName (COMMA_ columnName)* | renameColumnSpecification | renameIndexSpecification | renameTableSpecification_ | (WITHOUT | WITH) VALIDATION | ADD PARTITION LP_ partitionDefinition_ RP_ | DROP PARTITION ignoredIdentifiers_ | DISCARD PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | IMPORT_ PARTITION (ignoredIdentifiers_ | ALL) TABLESPACE | TRUNCATE PARTITION (ignoredIdentifiers_ | ALL) | COALESCE PARTITION NUMBER_ | REORGANIZE PARTITION ignoredIdentifiers_ INTO partitionDefinitions_ | EXCHANGE PARTITION ignoredIdentifier_ WITH TABLE tableName ((WITH | WITHOUT) VALIDATION)? | ANALYZE PARTITION (ignoredIdentifiers_ | ALL) | CHECK PARTITION (ignoredIdentifiers_ | ALL) | OPTIMIZE PARTITION (ignoredIdentifiers_ | ALL) | REBUILD PARTITION (ignoredIdentifiers_ | ALL) | REPAIR PARTITION (ignoredIdentifiers_ | ALL) | REMOVE PARTITIONING | UPGRADE PARTITIONING ; tableOptions_ : tableOption_ (COMMA_? tableOption_)* ; tableOption_ : AUTO_INCREMENT EQ_? NUMBER_ | AVG_ROW_LENGTH EQ_? NUMBER_ | DEFAULT? (characterSet_ | collateClause_) | CHECKSUM EQ_? NUMBER_ | COMMENT EQ_? STRING_ | COMPRESSION EQ_? STRING_ | CONNECTION EQ_? STRING_ | (DATA | INDEX) DIRECTORY EQ_? STRING_ | DELAY_KEY_WRITE EQ_? NUMBER_ | ENCRYPTION EQ_? STRING_ | ENGINE EQ_? ignoredIdentifier_ | INSERT_METHOD EQ_? (NO | FIRST | LAST) | KEY_BLOCK_SIZE EQ_? NUMBER_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | PACK_KEYS EQ_? (NUMBER_ | DEFAULT) | PASSWORD EQ_? STRING_ | ROW_FORMAT EQ_? (DEFAULT | DYNAMIC | FIXED | COMPRESSED | REDUNDANT | COMPACT) | STATS_AUTO_RECALC EQ_? (DEFAULT | NUMBER_) | STATS_PERSISTENT EQ_? (DEFAULT | NUMBER_) | STATS_SAMPLE_PAGES EQ_? NUMBER_ | TABLESPACE ignoredIdentifier_ (STORAGE (DISK | MEMORY | DEFAULT))? | UNION EQ_? LP_ tableName (COMMA_ tableName)* RP_ ; addColumnSpecification : ADD COLUMN? (columnDefinition firstOrAfterColumn? | LP_ columnDefinition (COMMA_ columnDefinition)* RP_) ; firstOrAfterColumn : FIRST | AFTER columnName ; addIndexSpecification : ADD indexDefinition_ ; addConstraintSpecification : ADD constraintDefinition_ ; changeColumnSpecification : CHANGE COLUMN? columnName columnDefinition firstOrAfterColumn? ; dropColumnSpecification : DROP COLUMN? columnName ; dropIndexSpecification : DROP (INDEX | KEY) indexName ; dropPrimaryKeySpecification : DROP primaryKey ; modifyColumnSpecification : MODIFY COLUMN? columnDefinition firstOrAfterColumn? ; // TODO hongjun: parse renameColumnSpecification and refresh meta, but throw exception if is sharding column renameColumnSpecification : RENAME COLUMN columnName TO columnName ; // TODO hongjun: should support renameIndexSpecification on mysql renameIndexSpecification : RENAME (INDEX | KEY) indexName TO indexName ; // TODO hongjun: parse renameTableSpecification_ and refresh meta, but throw exception if is sharding table renameTableSpecification_ : RENAME (TO | AS)? newTableName ; newTableName : identifier_ ; partitionDefinitions_ : LP_ partitionDefinition_ (COMMA_ partitionDefinition_)* RP_ ; partitionDefinition_ : PARTITION identifier_ (VALUES (LESS THAN partitionLessThanValue_ | IN LP_ partitionValueList_ RP_))? partitionDefinitionOption_* (LP_ subpartitionDefinition_ (COMMA_ subpartitionDefinition_)* RP_)? ; partitionLessThanValue_ : LP_ (expr | partitionValueList_) RP_ | MAXVALUE ; partitionValueList_ : literals (COMMA_ literals)* ; partitionDefinitionOption_ : STORAGE? ENGINE EQ_? identifier_ | COMMENT EQ_? STRING_ | DATA DIRECTORY EQ_? STRING_ | INDEX DIRECTORY EQ_? STRING_ | MAX_ROWS EQ_? NUMBER_ | MIN_ROWS EQ_? NUMBER_ | TABLESPACE EQ_? identifier_ ; subpartitionDefinition_ : SUBPARTITION identifier_ partitionDefinitionOption_* ;
rename to createTableSpecification_
rename to createTableSpecification_
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
987b2ae6cca339a474c6eb50775c4f6969531d4f
omni-cx2x/src/cx2x/translator/language/Claw.g4
omni-cx2x/src/cx2x/translator/language/Claw.g4
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
/* * This file is released under terms of BSD license * See LICENSE file for more information */ /** * ANTLR 4 Grammar file for the CLAW directive language. * * @author clementval */ grammar Claw; @header { import cx2x.translator.common.ClawConstant; import cx2x.translator.misc.Utility; } /*---------------------------------------------------------------------------- * PARSER RULES *----------------------------------------------------------------------------*/ /* * Entry point for the analyzis of a CLAW directive. * Return a CLawLanguage object with all needed information. */ analyze returns [ClawLanguage l] @init{ $l = new ClawLanguage(); } : CLAW directive[$l] EOF ; directive[ClawLanguage l] @init{ List<ClawMapping> m = new ArrayList<>(); List<String> o = new ArrayList<>(); List<String> s = new ArrayList<>(); List<Integer> i = new ArrayList<>(); } : // loop-fusion directive LFUSION group_clause_optional[$l] collapse_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_FUSION); } // loop-interchange directive | LINTERCHANGE indexes_option[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_INTERCHANGE); } // loop-extract directive | LEXTRACT range_option mapping_option_list[m] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.LOOP_EXTRACT); $l.setRange($range_option.r); $l.setMappings(m); } // remove directive | REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); } | END REMOVE EOF { $l.setDirective(ClawDirective.REMOVE); $l.setEndPragma(); } // Kcache directive | KCACHE data_clause[$l] offset_list_optional[i] private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); } | KCACHE data_clause[$l] offset_list_optional[i] INIT private_optional[$l] EOF { $l.setDirective(ClawDirective.KCACHE); $l.setOffsets(i); $l.setInitClause(); } // Array notation transformation directive | ARRAY_TRANS induction_optional[$l] fusion_optional[$l] parallel_optional[$l] acc_optional[$l] EOF { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); } | END ARRAY_TRANS { $l.setDirective(ClawDirective.ARRAY_TRANSFORM); $l.setEndPragma(); } // loop-hoist directive | LHOIST '(' ids_list[o] ')' reshape_optional[$l] interchange_optional[$l] EOF { $l.setHoistInductionVars(o); $l.setDirective(ClawDirective.LOOP_HOIST); } | END LHOIST EOF { $l.setDirective(ClawDirective.LOOP_HOIST); $l.setEndPragma(); } // on the fly directive | ARRAY_TO_CALL array_name=IDENTIFIER '=' fct_name=IDENTIFIER '(' identifiers_list[o] ')' { $l.setDirective(ClawDirective.ARRAY_TO_CALL); $l.setFctParams(o); $l.setFctName($fct_name.text); $l.setArrayName($array_name.text); } // parallelize directive | define_option[$l]* PARALLELIZE data_over_clause[$l]* { $l.setDirective(ClawDirective.PARALLELIZE); } | PARALLELIZE FORWARD { $l.setDirective(ClawDirective.PARALLELIZE); $l.setForwardClause(); } | END PARALLELIZE { $l.setDirective(ClawDirective.PARALLELIZE); $l.setEndPragma(); } // ignore directive | IGNORE { $l.setDirective(ClawDirective.IGNORE); } | END IGNORE { $l.setDirective(ClawDirective.IGNORE); $l.setEndPragma(); } ; // Comma-separated identifiers list ids_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_list[$ids] ; // Comma-separated identifiers or colon symbol list ids_or_colon_list[List<String> ids] : i=IDENTIFIER { $ids.add($i.text); } | ':' { $ids.add(":"); } | i=IDENTIFIER { $ids.add($i.text); } ',' ids_or_colon_list[$ids] | ':' { $ids.add(":"); } ',' ids_or_colon_list[$ids] ; // data over clause used in parallelize directive data_over_clause[ClawLanguage l] @init{ List<String> overLst = new ArrayList<>(); List<String> dataLst = new ArrayList<>(); } : DATA '(' ids_list[dataLst] ')' OVER '(' ids_or_colon_list[overLst] ')' { $l.setDataClause(dataLst); $l.setOverClause(overLst); } ; // group clause group_clause_optional[ClawLanguage l]: GROUP '(' group_name=IDENTIFIER ')' { $l.setGroupClause($group_name.text); } | /* empty */ ; // collapse clause collapse_optional[ClawLanguage l]: COLLAPSE '(' n=NUMBER ')' { $l.setCollapseClause($n.text); } | /* empty */ ; // fusion clause fusion_optional[ClawLanguage l]: FUSION group_clause_optional[$l] { $l.setFusionClause(); } | /* empty */ ; // parallel clause parallel_optional[ClawLanguage l]: PARALLEL { $l.setParallelClause(); } | /* empty */ ; // acc clause acc_optional[ClawLanguage l] @init{ List<String> tempAcc = new ArrayList<>(); } : ACC '(' identifiers[tempAcc] ')' { $l.setAcceleratorClauses(Utility.join(" ", tempAcc)); } | /* empty */ ; // interchange clause interchange_optional[ClawLanguage l]: INTERCHANGE indexes_option[$l] { $l.setInterchangeClause(); } | /* empty */ ; // induction clause induction_optional[ClawLanguage l] @init{ List<String> temp = new ArrayList<>(); } : INDUCTION '(' ids_list[temp] ')' { $l.setInductionClause(temp); } | /* empty */ ; // data clause data_clause[ClawLanguage l] @init { List<String> temp = new ArrayList<>(); } : DATA '(' ids_list[temp] ')' { $l.setDataClause(temp); } ; // private clause private_optional[ClawLanguage l]: PRIVATE { $l.setPrivateClause(); } | /* empty */ ; // reshape clause reshape_optional[ClawLanguage l] @init{ List<ClawReshapeInfo> r = new ArrayList(); } : RESHAPE '(' reshape_list[r] ')' { $l.setReshapeClauseValues(r); } | /* empty */ ; // reshape clause reshape_element returns [ClawReshapeInfo i] @init{ List<Integer> temp = new ArrayList(); } : array_name=IDENTIFIER '(' target_dim=NUMBER ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } | array_name=IDENTIFIER '(' target_dim=NUMBER ',' integers_list[temp] ')' { $i = new ClawReshapeInfo($array_name.text, Integer.parseInt($target_dim.text), temp); } ; reshape_list[List<ClawReshapeInfo> r]: info=reshape_element { $r.add($info.i); } ',' reshape_list[$r] | info=reshape_element { $r.add($info.i); } ; identifiers[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } identifiers[$ids] ; identifiers_list[List<String> ids]: i=IDENTIFIER { $ids.add($i.text); } | i=IDENTIFIER { $ids.add($i.text); } ',' identifiers_list[$ids] ; integers[List<Integer> ints]: ; integers_list[List<Integer> ints]: i=NUMBER { $ints.add(Integer.parseInt($i.text)); } | i=NUMBER { $ints.add(Integer.parseInt($i.text)); } ',' integers[$ints] ; indexes_option[ClawLanguage l] @init{ List<String> indexes = new ArrayList(); } : '(' ids_list[indexes] ')' { $l.setIndexes(indexes); } | /* empty */ ; offset_list_optional[List<Integer> offsets]: OFFSET '(' offset_list[$offsets] ')' | /* empty */ ; offset_list[List<Integer> offsets]: offset[$offsets] | offset[$offsets] ',' offset_list[$offsets] ; offset[List<Integer> offsets]: n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } | '-' n=NUMBER { $offsets.add(-Integer.parseInt($n.text)); } | '+' n=NUMBER { $offsets.add(Integer.parseInt($n.text)); } ; range_option returns [ClawRange r] @init{ $r = new ClawRange(); } : RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep(ClawConstant.DEFAULT_STEP_VALUE); } | RANGE '(' induction=IDENTIFIER '=' lower=range_id ',' upper=range_id ',' step=range_id ')' { $r.setInductionVar($induction.text); $r.setLowerBound($lower.text); $r.setUpperBound($upper.text); $r.setStep($step.text); } ; range_id returns [String text]: n=NUMBER { $text = $n.text; } | i=IDENTIFIER { $text = $i.text; } ; mapping_var returns [ClawMappingVar mappingVar]: lhs=IDENTIFIER '/' rhs=IDENTIFIER { $mappingVar = new ClawMappingVar($lhs.text, $rhs.text); } | i=IDENTIFIER { $mappingVar = new ClawMappingVar($i.text, $i.text); } ; mapping_var_list[List<ClawMappingVar> vars]: mv=mapping_var { $vars.add($mv.mappingVar); } | mv=mapping_var { $vars.add($mv.mappingVar); } ',' mapping_var_list[$vars] ; mapping_option returns [ClawMapping mapping] @init{ $mapping = new ClawMapping(); List<ClawMappingVar> listMapped = new ArrayList<ClawMappingVar>(); List<ClawMappingVar> listMapping = new ArrayList<ClawMappingVar>(); $mapping.setMappedVariables(listMapped); $mapping.setMappingVariables(listMapping); } : MAP '(' mapping_var_list[listMapped] ':' mapping_var_list[listMapping] ')' ; mapping_option_list[List<ClawMapping> mappings]: m=mapping_option { $mappings.add($m.mapping); } | m=mapping_option { $mappings.add($m.mapping); } mapping_option_list[$mappings] ; define_option[ClawLanguage l]: DEFINE DIMENSION id=IDENTIFIER '(' lower=range_id ':' upper=range_id ')' { ClawDimension cd = new ClawDimension($id.text, $lower.text, $upper.text); $l.addDimension(cd); } ; /*---------------------------------------------------------------------------- * LEXER RULES *----------------------------------------------------------------------------*/ // Start point CLAW : 'claw'; // Directives ARRAY_TRANS : 'array-transform'; ARRAY_TO_CALL: 'call'; DEFINE : 'define'; END : 'end'; KCACHE : 'kcache'; LEXTRACT : 'loop-extract'; LFUSION : 'loop-fusion'; LHOIST : 'loop-hoist'; LINTERCHANGE : 'loop-interchange'; PARALLELIZE : 'parallelize'; REMOVE : 'remove'; IGNORE : 'ignore'; // Clauses ACC : 'acc'; COLLAPSE : 'collapse'; DATA : 'data'; DIMENSION : 'dimension'; FORWARD : 'forward'; FUSION : 'fusion'; GROUP : 'group'; INDUCTION : 'induction'; INIT : 'init'; INTERCHANGE : 'interchange'; MAP : 'map'; OFFSET : 'offset'; OVER : 'over'; PARALLEL : 'parallel'; PRIVATE : 'private'; RANGE : 'range'; RESHAPE : 'reshape'; // Special elements IDENTIFIER : [a-zA-Z_$] [a-zA-Z_$0-9-]* ; NUMBER : (DIGIT)+ ; fragment DIGIT : [0-9] ; // Skip whitspaces WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { skip(); };
Add EOF add the end of rules
Add EOF add the end of rules
ANTLR
bsd-2-clause
clementval/claw-compiler,clementval/claw-compiler
3e881a3d78eee053cebd556e8c375a5fea914b04
objc/ObjectiveCParser.g4
objc/ObjectiveCParser.g4
/* Objective-C grammar. The MIT License (MIT). Copyright (c) 2016-2017, Alex Petuschak ([email protected]). Copyright (c) 2016-2017, Ivan Kochurkin ([email protected]). Converted to ANTLR 4 by Terence Parr; added @property and a few others. Updated June 2014, Carlos Mejia. Fix try-catch, add support for @( @{ @[ and blocks June 2008 Cedric Cuche Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ parser grammar ObjectiveCParser; options { tokenVocab=ObjectiveCLexer; } translationUnit : topLevelDeclaration* EOF ; topLevelDeclaration : importDeclaration | functionDeclaration | declaration | classInterface | classImplementation | categoryInterface | categoryImplementation | protocolDeclaration | protocolDeclarationList | classDeclarationList | functionDefinition ; importDeclaration : '@import' identifier ';' ; classInterface : IB_DESIGNABLE? '@interface' className=genericTypeSpecifier (':' superclassName=identifier)? (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; categoryInterface : '@interface' categoryName=genericTypeSpecifier LP className=identifier? RP (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; classImplementation : '@implementation' className=genericTypeSpecifier (':' superclassName=identifier)? instanceVariables? implementationDefinitionList? '@end' ; categoryImplementation : '@implementation' categoryName=genericTypeSpecifier LP className=identifier RP implementationDefinitionList? '@end' ; genericTypeSpecifier : identifier ((LT protocolList GT) | genericsSpecifier)? ; protocolDeclaration : '@protocol' protocolName (LT protocolList GT)? protocolDeclarationSection* '@end' ; protocolDeclarationSection : modifier=(REQUIRED | OPTIONAL) interfaceDeclarationList* | interfaceDeclarationList+ ; protocolDeclarationList : '@protocol' protocolList ';' ; classDeclarationList : '@class' identifier (',' identifier)* ';' ; protocolList : protocolName (',' protocolName)* ; propertyDeclaration : '@property' (LP propertyAttributesList RP)? ibOutletQualifier? IB_INSPECTABLE? fieldDeclaration ; propertyAttributesList : propertyAttribute (',' propertyAttribute)* ; propertyAttribute : ATOMIC | NONATOMIC | STRONG | WEAK | RETAIN | ASSIGN | UNSAFE_UNRETAINED | COPY | READONLY | READWRITE | GETTER '=' identifier | SETTER '=' identifier ':' | nullabilitySpecifier | identifier ; protocolName : LT protocolList GT | ('__covariant' | '__contravariant')? identifier ; instanceVariables : '{' visibilitySection* '}' ; visibilitySection : accessModifier fieldDeclaration* | fieldDeclaration+ ; accessModifier : PRIVATE | PROTECTED | PACKAGE | PUBLIC ; interfaceDeclarationList : (declaration | classMethodDeclaration | instanceMethodDeclaration | propertyDeclaration | functionDeclaration)+ ; classMethodDeclaration : '+' methodDeclaration ; instanceMethodDeclaration : '-' methodDeclaration ; methodDeclaration : methodType? methodSelector macro? ';' ; implementationDefinitionList : (functionDefinition | declaration | classMethodDefinition | instanceMethodDefinition | propertyImplementation )+; classMethodDefinition : '+' methodDefinition ; instanceMethodDefinition : '-' methodDefinition ; methodDefinition : methodType? methodSelector initDeclaratorList? ';'? compoundStatement ; methodSelector : selector | keywordDeclarator+ (',' '...')? ; keywordDeclarator : selector? ':' methodType* arcBehaviourSpecifier? identifier ; selector : identifier | 'return' ; methodType : LP typeName RP ; propertyImplementation : '@synthesize' propertySynthesizeList ';' | '@dynamic' propertySynthesizeList ';' ; propertySynthesizeList : propertySynthesizeItem (',' propertySynthesizeItem)* ; propertySynthesizeItem : identifier ('=' identifier)? ; blockType : nullabilitySpecifier? typeSpecifier nullabilitySpecifier? LP '^' (nullabilitySpecifier | typeSpecifier)? RP blockParameters? ; genericsSpecifier : LT (typeSpecifierWithPrefixes (',' typeSpecifierWithPrefixes)*)? GT ; typeSpecifierWithPrefixes : typePrefix* typeSpecifier ; dictionaryExpression : '@' '{' (dictionaryPair (',' dictionaryPair)* ','?)? '}' ; dictionaryPair : castExpression ':' expression ; arrayExpression : '@' '[' (expressions ','?)? ']' ; boxExpression : '@' LP expression RP | '@' (constant | identifier) ; blockParameters : LP ((typeVariableDeclaratorOrName | 'void') (',' typeVariableDeclaratorOrName)*)? RP ; typeVariableDeclaratorOrName : typeVariableDeclarator | typeName ; blockExpression : '^' typeSpecifier? nullabilitySpecifier? blockParameters? compoundStatement ; messageExpression : '[' receiver messageSelector ']' ; receiver : expression | typeSpecifier ; messageSelector : selector | keywordArgument+ ; keywordArgument : selector? ':' keywordArgumentType (',' keywordArgumentType)* ; keywordArgumentType : expressions nullabilitySpecifier? ('{' initializerList '}')? ; selectorExpression : '@selector' LP selectorName RP ; selectorName : selector | (selector? ':')+ ; protocolExpression : '@protocol' LP protocolName RP ; encodeExpression : '@encode' LP typeName RP ; typeVariableDeclarator : declarationSpecifiers declarator ; throwStatement : '@throw' LP identifier RP | '@throw' expression ; tryBlock : '@try' tryStatement=compoundStatement catchStatement* ('@finally' finallyStatement=compoundStatement)? ; catchStatement : '@catch' LP typeVariableDeclarator RP compoundStatement ; synchronizedStatement : '@synchronized' LP expression RP compoundStatement ; autoreleaseStatement : '@autoreleasepool' compoundStatement ; functionDeclaration : functionSignature ';' ; functionDefinition : functionSignature compoundStatement ; functionSignature : declarationSpecifiers? identifier (LP parameterList? RP) attributeSpecifier? ; attribute : attributeName attributeParameters? ; attributeName : 'const' | identifier ; attributeParameters : LP attributeParameterList? RP ; attributeParameterList : attributeParameter (',' attributeParameter)* ; attributeParameter : attribute | constant | stringLiteral | attributeParameterAssignment ; attributeParameterAssignment : attributeName '=' (constant | attributeName | stringLiteral) ; declaration : functionCallExpression | enumDeclaration | varDeclaration | typedefDeclaration ; functionCallExpression : attributeSpecifier? identifier attributeSpecifier? LP directDeclarator RP ';' ; enumDeclaration : attributeSpecifier? TYPEDEF? enumSpecifier identifier? ';' ; varDeclaration : (declarationSpecifiers initDeclaratorList | declarationSpecifiers) ';' ; typedefDeclaration : attributeSpecifier? TYPEDEF (declarationSpecifiers typeDeclaratorList | declarationSpecifiers) ';' ; typeDeclaratorList : typeDeclarator (',' typeDeclarator)* ; typeDeclarator : pointer? directDeclarator ; declarationSpecifiers : (storageClassSpecifier | attributeSpecifier | arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; attributeSpecifier : '__attribute__' LP LP attribute (',' attribute)* RP RP ; initDeclaratorList : initDeclarator (',' initDeclarator)* ; initDeclarator : declarator ('=' initializer)? ; structOrUnionSpecifier : ('struct' | 'union') (identifier | identifier? '{' fieldDeclaration+ '}') ; fieldDeclaration : specifierQualifierList fieldDeclaratorList macro? ';' ; specifierQualifierList : (arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; ibOutletQualifier : IB_OUTLET_COLLECTION LP identifier RP | IB_OUTLET ; arcBehaviourSpecifier : WEAK_QUALIFIER | STRONG_QUALIFIER | AUTORELEASING_QUALIFIER | UNSAFE_UNRETAINED_QUALIFIER ; nullabilitySpecifier : NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE ; storageClassSpecifier : AUTO | REGISTER | STATIC | EXTERN ; typePrefix : BRIDGE | BRIDGE_TRANSFER | BRIDGE_RETAINED | BLOCK | INLINE | NS_INLINE | KINDOF ; typeQualifier : CONST | VOLATILE | RESTRICT | protocolQualifier ; protocolQualifier : 'in' | 'out' | 'inout' | 'bycopy' | 'byref' | 'oneway' ; typeSpecifier : 'void' | 'char' | 'short' | 'int' | 'long' | 'float' | 'double' | 'signed' | 'unsigned' | typeofExpression | genericTypeSpecifier | structOrUnionSpecifier | enumSpecifier | identifier pointer? ; typeofExpression : TYPEOF (LP expression RP) ; fieldDeclaratorList : fieldDeclarator (',' fieldDeclarator)* ; fieldDeclarator : declarator | declarator? ':' constant ; enumSpecifier : 'enum' (identifier? ':' typeName)? (identifier ('{' enumeratorList '}')? | '{' enumeratorList '}') | ('NS_OPTIONS' | 'NS_ENUM') LP typeName ',' identifier RP '{' enumeratorList '}' ; enumeratorList : enumerator (',' enumerator)* ','? ; enumerator : enumeratorIdentifier ('=' expression)? ; enumeratorIdentifier : identifier | 'default' ; directDeclarator : (identifier | LP declarator RP) declaratorSuffix* | LP '^' nullabilitySpecifier? identifier? RP blockParameters ; declaratorSuffix : '[' constantExpression? ']' ; parameterList : parameterDeclarationList (',' '...')? ; pointer : '*' declarationSpecifiers? pointer? ; macro : identifier (LP primaryExpression (',' primaryExpression)* RP)? ; arrayInitializer : '{' (expressions ','?)? '}' ; structInitializer : '{' ('.' expression (',' '.' expression)* ','?)? '}' ; initializerList : initializer (',' initializer)* ','? ; typeName : specifierQualifierList abstractDeclarator? | blockType ; abstractDeclarator : pointer abstractDeclarator? | LP abstractDeclarator? RP abstractDeclaratorSuffix+ | ('[' constantExpression? ']')+ ; abstractDeclaratorSuffix : '[' constantExpression? ']' | LP parameterDeclarationList? RP ; parameterDeclarationList : parameterDeclaration (',' parameterDeclaration)* ; parameterDeclaration : declarationSpecifiers declarator | 'void' ; declarator : pointer? directDeclarator ; statement : labeledStatement ';'? | compoundStatement ';'? | selectionStatement ';'? | iterationStatement ';'? | jumpStatement ';'? | synchronizedStatement ';'? | autoreleaseStatement ';'? | throwStatement ';'? | tryBlock ';'? | expressions ';'? | ';' ; labeledStatement : identifier ':' statement ; rangeExpression : constantExpression ('...' constantExpression)? ; compoundStatement : '{' (declaration | statement)* '}' ; selectionStatement : IF LP expression RP ifBody=statement (ELSE elseBody=statement)? | switchStatement ; switchStatement : 'switch' LP expression RP switchBlock ; switchBlock : '{' switchSection* '}' ; switchSection : switchLabel+ statement+ ; switchLabel : 'case' (rangeExpression | LP rangeExpression RP) ':' | 'default' ':' ; iterationStatement : whileStatement | doStatement | forStatement | forInStatement ; whileStatement : 'while' LP expression RP statement ; doStatement : 'do' statement 'while' LP expression RP ';' ; forStatement : 'for' LP forLoopInitializer? ';' expression? ';' expressions? RP statement ; forLoopInitializer : declarationSpecifiers initDeclaratorList | expressions ; forInStatement : 'for' LP typeVariableDeclarator 'in' expression? RP statement ; jumpStatement : GOTO identifier | CONTINUE | BREAK | RETURN expression? ; expressions : expression (',' expression)* ; expression : castExpression | expression op=(MUL | DIV | MOD) expression | expression op=(ADD | SUB) expression | expression (LT LT | GT GT) expression | expression op=(LE | GE | LT | GT) expression | expression op=(NOTEQUAL | EQUAL) expression | expression op=BITAND expression | expression op=BITXOR expression | expression op=BITOR expression | expression op=AND expression | expression op=OR expression | expression QUESTION trueExpression=expression? COLON falseExpression=expression | unaryExpression assignmentOperator assignmentExpression=expression ; assignmentOperator : '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' ; castExpression : unaryExpression | (LP typeName RP) (castExpression | initializer) ; initializer : expression | arrayInitializer | structInitializer ; constantExpression : identifier | constant ; unaryExpression : postfixExpression | SIZEOF (unaryExpression | LP typeSpecifier RP) | op=(INC | DEC) unaryExpression | unaryOperator castExpression ; unaryOperator : '&' | '*' | '+' | '-' | '~' | BANG ; postfixExpression : primaryExpression postfix* | postfixExpression (DOT | STRUCTACCESS) identifier postfix* // TODO: get rid of property and postfix expression. ; postfix : LBRACK expression RBRACK | LP argumentExpressionList? RP | LP (COMMA | macroArguments+=~RP)+ RP | op=(INC | DEC) ; argumentExpressionList : argumentExpression (',' argumentExpression)* ; argumentExpression : expression | typeSpecifier ; primaryExpression : identifier | constant | stringLiteral | LP expression RP | messageExpression | selectorExpression | protocolExpression | encodeExpression | dictionaryExpression | arrayExpression | boxExpression | blockExpression ; constant : HEX_LITERAL | OCTAL_LITERAL | BINARY_LITERAL | ('+' | '-')? DECIMAL_LITERAL | ('+' | '-')? FLOATING_POINT_LITERAL | CHARACTER_LITERAL | NIL | NULL | YES | NO | TRUE | FALSE ; stringLiteral : (STRING_START (STRING_VALUE | STRING_NEWLINE)* STRING_END)+ ; identifier : IDENTIFIER | BOOL | Class | BYCOPY | BYREF | ID | IMP | IN | INOUT | ONEWAY | OUT | PROTOCOL_ | SEL | SELF | SUPER | ATOMIC | NONATOMIC | RETAIN | AUTORELEASING_QUALIFIER | BLOCK | BRIDGE_RETAINED | BRIDGE_TRANSFER | COVARIANT | CONTRAVARIANT | DEPRECATED | KINDOF | UNUSED | NS_INLINE | NS_ENUM | NS_OPTIONS | NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE | ASSIGN | COPY | GETTER | SETTER | STRONG | READONLY | READWRITE | WEAK | UNSAFE_UNRETAINED | IB_OUTLET | IB_OUTLET_COLLECTION | IB_INSPECTABLE | IB_DESIGNABLE ;
/* Objective-C grammar. The MIT License (MIT). Copyright (c) 2016-2017, Alex Petuschak ([email protected]). Copyright (c) 2016-2017, Ivan Kochurkin ([email protected]). Converted to ANTLR 4 by Terence Parr; added @property and a few others. Updated June 2014, Carlos Mejia. Fix try-catch, add support for @( @{ @[ and blocks June 2008 Cedric Cuche Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ parser grammar ObjectiveCParser; options { tokenVocab=ObjectiveCLexer; } translationUnit : topLevelDeclaration* EOF ; topLevelDeclaration : importDeclaration | functionDeclaration | declaration | classInterface | classImplementation | categoryInterface | categoryImplementation | protocolDeclaration | protocolDeclarationList | classDeclarationList | functionDefinition ; importDeclaration : '@import' identifier ';' ; classInterface : IB_DESIGNABLE? '@interface' className=genericTypeSpecifier (':' superclassName=identifier)? (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; categoryInterface : '@interface' categoryName=genericTypeSpecifier LP className=identifier? RP (LT protocolList GT)? instanceVariables? interfaceDeclarationList? '@end' ; classImplementation : '@implementation' className=genericTypeSpecifier (':' superclassName=identifier)? instanceVariables? implementationDefinitionList? '@end' ; categoryImplementation : '@implementation' categoryName=genericTypeSpecifier LP className=identifier RP implementationDefinitionList? '@end' ; genericTypeSpecifier : identifier ((LT protocolList GT) | genericsSpecifier)? ; protocolDeclaration : '@protocol' protocolName (LT protocolList GT)? protocolDeclarationSection* '@end' ; protocolDeclarationSection : modifier=(REQUIRED | OPTIONAL) interfaceDeclarationList* | interfaceDeclarationList+ ; protocolDeclarationList : '@protocol' protocolList ';' ; classDeclarationList : '@class' identifier (',' identifier)* ';' ; protocolList : protocolName (',' protocolName)* ; propertyDeclaration : '@property' (LP propertyAttributesList RP)? ibOutletQualifier? IB_INSPECTABLE? fieldDeclaration ; propertyAttributesList : propertyAttribute (',' propertyAttribute)* ; propertyAttribute : ATOMIC | NONATOMIC | STRONG | WEAK | RETAIN | ASSIGN | UNSAFE_UNRETAINED | COPY | READONLY | READWRITE | GETTER '=' identifier | SETTER '=' identifier ':' | nullabilitySpecifier | identifier ; protocolName : LT protocolList GT | ('__covariant' | '__contravariant')? identifier ; instanceVariables : '{' visibilitySection* '}' ; visibilitySection : accessModifier fieldDeclaration* | fieldDeclaration+ ; accessModifier : PRIVATE | PROTECTED | PACKAGE | PUBLIC ; interfaceDeclarationList : (declaration | classMethodDeclaration | instanceMethodDeclaration | propertyDeclaration | functionDeclaration)+ ; classMethodDeclaration : '+' methodDeclaration ; instanceMethodDeclaration : '-' methodDeclaration ; methodDeclaration : methodType? methodSelector macro? ';' ; implementationDefinitionList : (functionDefinition | declaration | classMethodDefinition | instanceMethodDefinition | propertyImplementation )+; classMethodDefinition : '+' methodDefinition ; instanceMethodDefinition : '-' methodDefinition ; methodDefinition : methodType? methodSelector initDeclaratorList? ';'? compoundStatement ; methodSelector : selector | keywordDeclarator+ (',' '...')? ; keywordDeclarator : selector? ':' methodType* arcBehaviourSpecifier? identifier ; selector : identifier | 'return' ; methodType : LP typeName RP ; propertyImplementation : '@synthesize' propertySynthesizeList ';' | '@dynamic' propertySynthesizeList ';' ; propertySynthesizeList : propertySynthesizeItem (',' propertySynthesizeItem)* ; propertySynthesizeItem : identifier ('=' identifier)? ; blockType : nullabilitySpecifier? typeSpecifier nullabilitySpecifier? LP '^' (nullabilitySpecifier | typeSpecifier)? RP blockParameters? ; genericsSpecifier : LT (typeSpecifierWithPrefixes (',' typeSpecifierWithPrefixes)*)? GT ; typeSpecifierWithPrefixes : typePrefix* typeSpecifier ; dictionaryExpression : '@' '{' (dictionaryPair (',' dictionaryPair)* ','?)? '}' ; dictionaryPair : castExpression ':' expression ; arrayExpression : '@' '[' (expressions ','?)? ']' ; boxExpression : '@' LP expression RP | '@' (constant | identifier) ; blockParameters : LP ((typeVariableDeclaratorOrName | 'void') (',' typeVariableDeclaratorOrName)*)? RP ; typeVariableDeclaratorOrName : typeVariableDeclarator | typeName ; blockExpression : '^' typeSpecifier? nullabilitySpecifier? blockParameters? compoundStatement ; messageExpression : '[' receiver messageSelector ']' ; receiver : expression | typeSpecifier ; messageSelector : selector | keywordArgument+ ; keywordArgument : selector? ':' keywordArgumentType (',' keywordArgumentType)* ; keywordArgumentType : expressions nullabilitySpecifier? ('{' initializerList '}')? ; selectorExpression : '@selector' LP selectorName RP ; selectorName : selector | (selector? ':')+ ; protocolExpression : '@protocol' LP protocolName RP ; encodeExpression : '@encode' LP typeName RP ; typeVariableDeclarator : declarationSpecifiers declarator ; throwStatement : '@throw' LP identifier RP | '@throw' expression ; tryBlock : '@try' tryStatement=compoundStatement catchStatement* ('@finally' finallyStatement=compoundStatement)? ; catchStatement : '@catch' LP typeVariableDeclarator RP compoundStatement ; synchronizedStatement : '@synchronized' LP expression RP compoundStatement ; autoreleaseStatement : '@autoreleasepool' compoundStatement ; functionDeclaration : functionSignature ';' ; functionDefinition : functionSignature compoundStatement ; functionSignature : declarationSpecifiers? identifier (LP parameterList? RP) attributeSpecifier? ; attribute : attributeName attributeParameters? ; attributeName : 'const' | identifier ; attributeParameters : LP attributeParameterList? RP ; attributeParameterList : attributeParameter (',' attributeParameter)* ; attributeParameter : attribute | constant | stringLiteral | attributeParameterAssignment ; attributeParameterAssignment : attributeName '=' (constant | attributeName | stringLiteral) ; declaration : functionCallExpression | enumDeclaration | varDeclaration | typedefDeclaration ; functionCallExpression : attributeSpecifier? identifier attributeSpecifier? LP directDeclarator RP ';' ; enumDeclaration : attributeSpecifier? TYPEDEF? enumSpecifier identifier? ';' ; varDeclaration : (declarationSpecifiers initDeclaratorList | declarationSpecifiers) ';' ; typedefDeclaration : attributeSpecifier? TYPEDEF (declarationSpecifiers typeDeclaratorList | declarationSpecifiers) ';' ; typeDeclaratorList : typeDeclarator (',' typeDeclarator)* ; typeDeclarator : pointer? directDeclarator ; declarationSpecifiers : (storageClassSpecifier | attributeSpecifier | arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; attributeSpecifier : '__attribute__' LP LP attribute (',' attribute)* RP RP ; initDeclaratorList : initDeclarator (',' initDeclarator)* ; initDeclarator : declarator ('=' initializer)? ; structOrUnionSpecifier : ('struct' | 'union') (identifier | identifier? '{' fieldDeclaration+ '}') ; fieldDeclaration : specifierQualifierList fieldDeclaratorList macro? ';' ; specifierQualifierList : (arcBehaviourSpecifier | nullabilitySpecifier | ibOutletQualifier | typePrefix | typeQualifier | typeSpecifier)+ ; ibOutletQualifier : IB_OUTLET_COLLECTION LP identifier RP | IB_OUTLET ; arcBehaviourSpecifier : WEAK_QUALIFIER | STRONG_QUALIFIER | AUTORELEASING_QUALIFIER | UNSAFE_UNRETAINED_QUALIFIER ; nullabilitySpecifier : NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE ; storageClassSpecifier : AUTO | REGISTER | STATIC | EXTERN ; typePrefix : BRIDGE | BRIDGE_TRANSFER | BRIDGE_RETAINED | BLOCK | INLINE | NS_INLINE | KINDOF ; typeQualifier : CONST | VOLATILE | RESTRICT | protocolQualifier ; protocolQualifier : 'in' | 'out' | 'inout' | 'bycopy' | 'byref' | 'oneway' ; typeSpecifier : 'void' | 'char' | 'short' | 'int' | 'long' | 'float' | 'double' | 'signed' | 'unsigned' | typeofExpression | genericTypeSpecifier | structOrUnionSpecifier | enumSpecifier | identifier pointer? ; typeofExpression : TYPEOF (LP expression RP) ; fieldDeclaratorList : fieldDeclarator (',' fieldDeclarator)* ; fieldDeclarator : declarator | declarator? ':' constant ; enumSpecifier : 'enum' (identifier? ':' typeName)? (identifier ('{' enumeratorList '}')? | '{' enumeratorList '}') | ('NS_OPTIONS' | 'NS_ENUM') LP typeName ',' identifier RP '{' enumeratorList '}' ; enumeratorList : enumerator (',' enumerator)* ','? ; enumerator : enumeratorIdentifier ('=' expression)? ; enumeratorIdentifier : identifier | 'default' ; directDeclarator : (identifier | LP declarator RP) declaratorSuffix* | LP '^' nullabilitySpecifier? identifier? RP blockParameters ; declaratorSuffix : '[' constantExpression? ']' ; parameterList : parameterDeclarationList (',' '...')? ; pointer : '*' declarationSpecifiers? pointer? ; macro : identifier (LP primaryExpression (',' primaryExpression)* RP)? ; arrayInitializer : '{' (expressions ','?)? '}' ; structInitializer : '{' ('.' expression (',' '.' expression)* ','?)? '}' ; initializerList : initializer (',' initializer)* ','? ; typeName : specifierQualifierList abstractDeclarator? | blockType ; abstractDeclarator : pointer abstractDeclarator? | LP abstractDeclarator? RP abstractDeclaratorSuffix+ | ('[' constantExpression? ']')+ ; abstractDeclaratorSuffix : '[' constantExpression? ']' | LP parameterDeclarationList? RP ; parameterDeclarationList : parameterDeclaration (',' parameterDeclaration)* ; parameterDeclaration : declarationSpecifiers declarator | 'void' ; declarator : pointer? directDeclarator ; statement : labeledStatement ';'? | compoundStatement ';'? | selectionStatement ';'? | iterationStatement ';'? | jumpStatement ';'? | synchronizedStatement ';'? | autoreleaseStatement ';'? | throwStatement ';'? | tryBlock ';'? | expressions ';'? | ';' ; labeledStatement : identifier ':' statement ; rangeExpression : constantExpression ('...' constantExpression)? ; compoundStatement : '{' (declaration | statement)* '}' ; selectionStatement : IF LP expression RP ifBody=statement (ELSE elseBody=statement)? | switchStatement ; switchStatement : 'switch' LP expression RP switchBlock ; switchBlock : '{' switchSection* '}' ; switchSection : switchLabel+ statement+ ; switchLabel : 'case' (rangeExpression | LP rangeExpression RP) ':' | 'default' ':' ; iterationStatement : whileStatement | doStatement | forStatement | forInStatement ; whileStatement : 'while' LP expression RP statement ; doStatement : 'do' statement 'while' LP expression RP ';' ; forStatement : 'for' LP forLoopInitializer? ';' expression? ';' expressions? RP statement ; forLoopInitializer : declarationSpecifiers initDeclaratorList | expressions ; forInStatement : 'for' LP typeVariableDeclarator 'in' expression? RP statement ; jumpStatement : GOTO identifier | CONTINUE | BREAK | RETURN expression? ; expressions : expression (',' expression)* ; expression : castExpression | expression op=(MUL | DIV | MOD) expression | expression op=(ADD | SUB) expression | expression (LT LT | GT GT) expression | expression op=(LE | GE | LT | GT) expression | expression op=(NOTEQUAL | EQUAL) expression | expression op=BITAND expression | expression op=BITXOR expression | expression op=BITOR expression | expression op=AND expression | expression op=OR expression | expression QUESTION trueExpression=expression? COLON falseExpression=expression | LP compoundStatement RP | unaryExpression assignmentOperator assignmentExpression=expression ; assignmentOperator : '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' ; castExpression : unaryExpression | (LP typeName RP) (castExpression | initializer) ; initializer : expression | arrayInitializer | structInitializer ; constantExpression : identifier | constant ; unaryExpression : postfixExpression | SIZEOF (unaryExpression | LP typeSpecifier RP) | op=(INC | DEC) unaryExpression | unaryOperator castExpression ; unaryOperator : '&' | '*' | '+' | '-' | '~' | BANG ; postfixExpression : primaryExpression postfix* | postfixExpression (DOT | STRUCTACCESS) identifier postfix* // TODO: get rid of property and postfix expression. ; postfix : LBRACK expression RBRACK | LP argumentExpressionList? RP | LP (COMMA | macroArguments+=~RP)+ RP | op=(INC | DEC) ; argumentExpressionList : argumentExpression (',' argumentExpression)* ; argumentExpression : expression | typeSpecifier ; primaryExpression : identifier | constant | stringLiteral | LP expression RP | messageExpression | selectorExpression | protocolExpression | encodeExpression | dictionaryExpression | arrayExpression | boxExpression | blockExpression ; constant : HEX_LITERAL | OCTAL_LITERAL | BINARY_LITERAL | ('+' | '-')? DECIMAL_LITERAL | ('+' | '-')? FLOATING_POINT_LITERAL | CHARACTER_LITERAL | NIL | NULL | YES | NO | TRUE | FALSE ; stringLiteral : (STRING_START (STRING_VALUE | STRING_NEWLINE)* STRING_END)+ ; identifier : IDENTIFIER | BOOL | Class | BYCOPY | BYREF | ID | IMP | IN | INOUT | ONEWAY | OUT | PROTOCOL_ | SEL | SELF | SUPER | ATOMIC | NONATOMIC | RETAIN | AUTORELEASING_QUALIFIER | BLOCK | BRIDGE_RETAINED | BRIDGE_TRANSFER | COVARIANT | CONTRAVARIANT | DEPRECATED | KINDOF | UNUSED | NS_INLINE | NS_ENUM | NS_OPTIONS | NULL_UNSPECIFIED | NULLABLE | NONNULL | NULL_RESETTABLE | ASSIGN | COPY | GETTER | SETTER | STRONG | READONLY | READWRITE | WEAK | UNSAFE_UNRETAINED | IB_OUTLET | IB_OUTLET_COLLECTION | IB_INSPECTABLE | IB_DESIGNABLE ;
Support nested statement expression for ObjectiveCParser
Support nested statement expression for ObjectiveCParser like, self.attr = ({ 1 + 1 });
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
fc580611c3edc6f9ff346d085644f45e0c562a72
src/main/antlr4/YokohamaUnitLexer.g4
src/main/antlr4/YokohamaUnitLexer.g4
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' [ \t]* -> mode(ABBREVIATION); HASHES: Hashes [ \t]* -> mode(UNTIL_EOL) ; TEST: Hashes [ \t]* 'Test:' [ \t]* -> mode(UNTIL_EOL); SETUP: Hashes [ \t]* 'Setup:' [ \t]* -> mode(UNTIL_EOL); EXERCISE: Hashes [ \t]* 'Exercise:' [ \t]* -> mode(UNTIL_EOL); VERIFY: Hashes [ \t]* 'Verify:' [ \t]* -> mode(UNTIL_EOL); TEARDOWN: Hashes [ \t]* 'Teardown:' [ \t]* -> mode(UNTIL_EOL); SETUP_NO_DESC: Hashes [ \t]* 'Setup' -> type(SETUP) ; EXERCISE_NO_DESC: Hashes [ \t]* 'Exercise' -> type(EXERCISE) ; VERIFY_NO_DESC: Hashes [ \t]* 'Verify' -> type(VERIFY) ; TEARDOWN_NO_DESC: Hashes [ \t]* 'Teardown' -> type(TEARDOWN) ; LBRACKET_DEFAULT_MODE: '[' -> type(LBRACKET), mode(ANCHOR); BAR: '|' ; BAR_EOL: '|' [ \t]* '\r'? '\n' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; IN: 'in' ; UTABLE: 'Table' ; CSV_SINGLE_QUOTE: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV_SINGLE_QUOTE: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL_SINGLE_QUOTE: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; DO: 'Do' ; A_STUB_OF_BACK_TICK: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD_BACK_TICK: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF_BACK_TICK: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF_BACK_TICK: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; INVOKE_TICK: 'Invoke' Spaces? '`' -> mode (METHOD_PATTERN) ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; BACK_TICK: '`' -> mode(IN_BACK_TICK) ; DOUBLE_QUOTE: '"' -> mode(IN_DOUBLE_QUOTE) ; SINGLE_QUOTE: '\'' -> mode(IN_SINGLE_QUOTE) ; BACK_TICKS: '```' -> mode(IN_FENCE_3) ; BACK_TICKS4: '````' -> mode(IN_FENCE_4), type(BACK_TICKS) ; BACK_TICKS5: '`````' -> mode(IN_FENCE_5), type(BACK_TICKS) ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]+ ; RBRACKET_COLON: ']:' [ \t]* -> mode(UNTIL_EOL) ; mode UNTIL_EOL; Line: ~[ \t\r\n]+ ([ \t]+ ~[ \t\r\n]+)* ; //exclude trailing spaces NEW_LINE: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode ANCHOR; Anchor: ~[\]\r\n]+ ; RBRACKET_ANCHOR: ']' -> type(RBRACKET), mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier_AFTER_AN_INSTANCE : IdentStart IdentPart* -> type(Identifier) ; BACK_TICK_AFTER_AN_INSTANCE: '`' -> type(BACK_TICK), mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> type(DOUBLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FENCE_3; CLOSE_BACK_TICKS_3: '```' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine: ~[\r\n]* '\r'? '\n' ; mode IN_FENCE_4; CLOSE_BACK_TICKS_4: '````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine4: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode IN_FENCE_5; CLOSE_BACK_TICKS_5: '`````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine5: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA_METHOD_PATTERN: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; HASH: '#' ; Identifier_METHOD_PATTERN : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; BACK_TICK_METHOD_PATTERN: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode CLASS; DOT_CLASS: '.' -> type(DOT) ; Identifier_CLASS : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; BACK_TICK_CLASS: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FILE_NAME; FileName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_FILE_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; BookName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_BOOK_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; fragment Hashes: '#' | '##' | '###' | '####' | '#####' | '######' ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
lexer grammar YokohamaUnitLexer; STAR_LBRACKET: '*[' [ \t]* -> mode(ABBREVIATION); HASHES: Hashes [ \t]* -> mode(UNTIL_EOL) ; TEST: Hashes [ \t]* 'Test:' [ \t]* -> mode(UNTIL_EOL); SETUP: Hashes [ \t]* 'Setup:' [ \t]* -> mode(UNTIL_EOL); EXERCISE: Hashes [ \t]* 'Exercise:' [ \t]* -> mode(UNTIL_EOL); VERIFY: Hashes [ \t]* 'Verify:' [ \t]* -> mode(UNTIL_EOL); TEARDOWN: Hashes [ \t]* 'Teardown:' [ \t]* -> mode(UNTIL_EOL); SETUP_NO_DESC: Hashes [ \t]* 'Setup' -> type(SETUP) ; EXERCISE_NO_DESC: Hashes [ \t]* 'Exercise' -> type(EXERCISE) ; VERIFY_NO_DESC: Hashes [ \t]* 'Verify' -> type(VERIFY) ; TEARDOWN_NO_DESC: Hashes [ \t]* 'Teardown' -> type(TEARDOWN) ; LBRACKET_DEFAULT_MODE: '[' -> type(LBRACKET), mode(ANCHOR); BAR: '|' ; BAR_EOL: '|' [ \t]* '\r'? '\n' ; HBAR: '|' [|\-=\:\.\+ \t]* '|' [ \t]* '\r'? '\n' ; ASSERT: 'Assert' ; THAT: 'that' ; STOP: '.' ; AND: 'and' ; IS: 'is' ; NOT: 'not' ; THROWS: 'throws' ; FOR: 'for' ; ALL: 'all' ; COMMA: ',' ; IN: 'in' ; UTABLE: 'Table' ; CSV_SINGLE_QUOTE: 'CSV' Spaces? '\'' -> mode(IN_FILE_NAME) ; TSV_SINGLE_QUOTE: 'TSV' Spaces? '\''-> mode(IN_FILE_NAME) ; EXCEL_SINGLE_QUOTE: 'Excel' Spaces? '\'' -> mode(IN_BOOK_NAME) ; WHERE: 'where' ; EQ: '=' ; LET: 'Let' ; BE: 'be' ; ANY_OF: 'any' Spaces? 'of' ; OR: 'or' ; DO: 'Do' ; A_STUB_OF_BACK_TICK: 'a' Spaces 'stub' Spaces 'of' Spaces? '`' -> mode(CLASS) ; SUCH: 'such' ; METHOD_BACK_TICK: 'method' Spaces? '`' -> mode(METHOD_PATTERN) ; RETURNS: 'returns' ; AN_INSTANCE_OF_BACK_TICK: 'an' Spaces 'instance' Spaces 'of' Spaces? '`' -> mode(CLASS) ; AN_INSTANCE: 'an' Spaces 'instance' -> mode(AFTER_AN_INSTANCE) ; AN_INVOCATION_OF_BACK_TICK: 'an' Spaces 'invocation' Spaces 'of' Spaces? '`' -> mode(METHOD_PATTERN) ; ON: 'on' ; WITH: 'with' ; INVOKE_TICK: 'Invoke' Spaces? '`' -> mode (METHOD_PATTERN) ; NULL: 'null' ; NOTHING: 'nothing' ; TRUE: 'true' ; FALSE: 'false' ; Identifier: IdentStart IdentPart* ; Integer: IntegerLiteral ; FloatingPoint: FloatingPointLiteral ; MINUS: '-' ; EMPTY_STRING: '""' ; BACK_TICK: '`' -> mode(IN_BACK_TICK) ; DOUBLE_QUOTE: '"' -> mode(IN_DOUBLE_QUOTE) ; SINGLE_QUOTE: '\'' -> mode(IN_SINGLE_QUOTE) ; BACK_TICKS: '```' -> mode(IN_FENCE_3) ; BACK_TICKS4: '````' -> mode(IN_FENCE_4), type(BACK_TICKS) ; BACK_TICKS5: '`````' -> mode(IN_FENCE_5), type(BACK_TICKS) ; WS : Spaces -> skip ; mode ABBREVIATION; ShortName: ~[\]\r\n]+ ; RBRACKET_COLON: ']:' [ \t]* -> mode(UNTIL_EOL) ; mode UNTIL_EOL; Line: ~[ \t\r\n]+ ([ \t]+ ~[ \t\r\n]+)* ; //exclude trailing spaces NEW_LINE: [ \t]* ('\r'? '\n')+ -> skip, mode(DEFAULT_MODE) ; mode ANCHOR; Anchor: ~[\]\r\n]+ ; RBRACKET_ANCHOR: ']' -> type(RBRACKET), mode(DEFAULT_MODE) ; mode AFTER_AN_INSTANCE; OF: 'of' ; Identifier_AFTER_AN_INSTANCE : IdentStart IdentPart* -> type(Identifier) ; BACK_TICK_AFTER_AN_INSTANCE: '`' -> type(BACK_TICK), mode(CLASS) ; WS_AFTER_AN_INSTANCE: Spaces -> skip ; mode IN_DOUBLE_QUOTE; Str: (~["\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_DOUBLE_QUOTE: '"' -> type(DOUBLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_SINGLE_QUOTE; Char: (~['\\\r\n] | UnicodeEscape | EscapeSequence)+ ; CLOSE_SINGLE_QUOTE: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BACK_TICK; Expr: ~[`]+ ; CLOSE_BACK_TICK: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FENCE_3; CLOSE_BACK_TICKS_3: '```' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine: ~[\r\n]* '\r'? '\n' ; mode IN_FENCE_4; CLOSE_BACK_TICKS_4: '````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine4: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode IN_FENCE_5; CLOSE_BACK_TICKS_5: '`````' [ \t]* ('\r'? '\n' | EOF) -> type(BACK_TICKS), mode(DEFAULT_MODE) ; CodeLine5: ~[\r\n]* '\r'? '\n' -> type(CodeLine) ; mode METHOD_PATTERN; BOOLEAN: 'boolean' ; BYTE: 'byte' ; SHORT: 'short' ; INT: 'int' ; LONG: 'long' ; CHAR: 'char' ; FLOAT: 'float' ; DOUBLE: 'double' ; COMMA_METHOD_PATTERN: ',' -> type(COMMA); THREEDOTS: '...' ; DOT: '.' ; LPAREN: '(' ; RPAREN: ')' ; LBRACKET: '[' ; RBRACKET: ']' ; HASH: '#' ; Identifier_METHOD_PATTERN : IdentStart IdentPart* -> type(Identifier); WS_METHOD_PATTERN: Spaces -> skip ; BACK_TICK_METHOD_PATTERN: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode CLASS; DOT_CLASS: '.' -> type(DOT) ; Identifier_CLASS : IdentStart IdentPart* -> type(Identifier) ; WS_CLASS: Spaces -> skip ; BACK_TICK_CLASS: '`' -> type(BACK_TICK), mode(DEFAULT_MODE) ; mode IN_FILE_NAME; FileName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_FILE_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; mode IN_BOOK_NAME; BookName: (~['\r\n]|'\'\'')+ ; CLOSE_SINGLE_QUOTE_IN_BOOK_NAME: '\'' -> type(SINGLE_QUOTE), mode(DEFAULT_MODE) ; fragment Hashes: '#' | '##' | '###' | '####' | '#####' | '######' ; fragment Spaces: [ \t\r\n]+ ; fragment IdentStart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierStart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IdentPart: ~[\uD800-\uDBFF] {Character.isJavaIdentifierPart(_input.LA(-1))}? | [\uD800-\uDBFF] [\uDC00-\uDFFF] {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? ; fragment IntegerLiteral: DecimalIntegerLiteral | HexIntegerLiteral | OctalIntegerLiteral | BinaryIntegerLiteral ; fragment DecimalIntegerLiteral: DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral: HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral: OctalNumeral IntegerTypeSuffix? ; fragment BinaryIntegerLiteral: BinaryNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix: [lL] ; fragment DecimalNumeral: '0' | [1-9] ([_0-9]* [0-9])? ; fragment HexNumeral: '0' [xX] HexDigits ; fragment HexDigits: [0-9a-fA-F] ([_0-9a-fA-F]* [0-9a-fA-F])? ; fragment OctalNumeral: '0' [_0-7]* [0-7] ; fragment BinaryNumeral: '0' [bB] [01] ([_01]* [01])? ; fragment FloatingPointLiteral: DecimalFloatingPointLiteral | HexadecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral: Digits '.' Digits ExponentPart? FloatTypeSuffix? | Digits '.' ExponentPart FloatTypeSuffix? | Digits '.' ExponentPart? FloatTypeSuffix /* the above rules differ from the Java spec: fp literals which end with dot are not allowd */ | '.' Digits ExponentPart? FloatTypeSuffix? | Digits ExponentPart FloatTypeSuffix? | Digits ExponentPart? FloatTypeSuffix ; fragment Digits: [0-9] ([_0-9]* [0-9])? ; fragment ExponentPart: [eE] SignedInteger ; fragment SignedInteger: ('+' | '-')? Digits ; fragment FloatTypeSuffix: [fFdD] ; fragment HexadecimalFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffix? ; fragment HexSignificand: HexNumeral '.'? | '0' [xX] HexDigits? . HexDigits ; fragment BinaryExponent: [pP] SignedInteger ; fragment UnicodeEscape: '\\' 'u'+ [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] ; fragment EscapeSequence: '\\b' // (backspace BS, Unicode \u0008) | '\\t' // (horizontal tab HT, Unicode \u0009) | '\\n' // (linefeed LF, Unicode \u000a) | '\\f' // (form feed FF, Unicode \u000c) | '\\r' // (carriage return CR, Unicode \u000d) | '\\"' // (double quote ", Unicode \u0022) | '\\\'' // (single quote ', Unicode \u0027) | '\\\\' // (backslash \, Unicode \u005c) | OctalEscape // (octal value, Unicode \u0000 to \u00ff) ; fragment OctalEscape: '\\' [0-7] | '\\' [0-7] [0-7] | '\\' [0-3] [0-7] [0-7] ;
Add 'any of' and 'or' tokens
Add 'any of' and 'or' tokens
ANTLR
mit
tkob/yokohamaunit,tkob/yokohamaunit
955dc5eb41bffdd7ab9dcf2230083dfb2da271ed
src/net/hillsdon/reviki/wiki/renderer/creole/parser/Creole.g4
src/net/hillsdon/reviki/wiki/renderer/creole/parser/Creole.g4
/* Todo: * - Inline html [<html>]foo[</html>] * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; } @members { public boolean nobreaks = false; } /* ***** Top level elements ***** */ creole : (block ParBreak*)* EOF ; block : heading | ulist | olist | hrule | table | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt WS? inline HEnd? ; paragraph : inline ; ulist : ulist1+ ; ulist1 : U1 (WS ulist | olist | inline) ulist2* ; ulist2 : U2 (WS ulist | olist | inline) ulist3* ; ulist3 : U3 (WS ulist | olist | inline) ulist4* ; ulist4 : U4 (WS ulist | olist | inline) ulist5* ; ulist5 : U5 (WS ulist | olist | inline) ; olist : olist1+ ; olist1 : O1 (WS olist | ulist | inline) olist2* ; olist2 : O2 (WS olist | ulist | inline) olist3* ; olist3 : O3 (WS olist | ulist | inline) olist4* ; olist4 : O4 (WS olist | ulist | inline) olist5* ; olist5 : O5 (WS olist | ulist | inline) ; hrule : Rule ; table : {nobreaks=true;} (trow LineBreak)* trow (LineBreak | EOF) {nobreaks=false;}; trow : tcell+ CellSep?; tcell : th | td ; th : ThStart inline? ; td : CellSep inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | imglink | wikiwlink | rawlink | preformat | linebreak | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink Sep InLink LiEnd ; imglink : ImSt InLink Sep InLink ImEnd ; wikiwlink : WikiWords ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : InlineBrk ({!nobreaks}? LineBreak)? ; any : Any | WS | {!nobreaks}? LineBreak ;
/* Todo: * - Inline html [<html>]foo[</html>] * - Comments justifying and explaining every rule. * - Allow arbitrarily-nested lists (see actions/attributes) */ parser grammar Creole; options { tokenVocab=CreoleTokens; } @members { public boolean nobreaks = false; } /* ***** Top level elements ***** */ creole : (block (LineBreak | ParBreak)*)* EOF ; block : heading | ulist | olist | hrule | table | nowiki | paragraph ; /* ***** Block Elements ***** */ heading : HSt WS? inline HEnd? ; paragraph : inline ; ulist : ulist1+ ; ulist1 : U1 (WS ulist | olist | inline) ulist2* ; ulist2 : U2 (WS ulist | olist | inline) ulist3* ; ulist3 : U3 (WS ulist | olist | inline) ulist4* ; ulist4 : U4 (WS ulist | olist | inline) ulist5* ; ulist5 : U5 (WS ulist | olist | inline) ; olist : olist1+ ; olist1 : O1 (WS olist | ulist | inline) olist2* ; olist2 : O2 (WS olist | ulist | inline) olist3* ; olist3 : O3 (WS olist | ulist | inline) olist4* ; olist4 : O4 (WS olist | ulist | inline) olist5* ; olist5 : O5 (WS olist | ulist | inline) ; hrule : Rule ; table : {nobreaks=true;} (trow LineBreak)* trow (LineBreak | EOF) {nobreaks=false;}; trow : tcell+ CellSep?; tcell : th | td ; th : ThStart inline? ; td : CellSep inline? ; nowiki : NoWiki EndNoWikiBlock ; /* ***** Inline Elements ***** */ inline : inlinestep+ ; inlinestep : bold | italic | sthrough | link | titlelink | imglink | wikiwlink | rawlink | preformat | linebreak | any ; bold : BSt inline? BEnd ; italic : ISt inline? IEnd ; sthrough : SSt inline? SEnd ; link : LiSt InLink LiEnd ; titlelink : LiSt InLink Sep InLink LiEnd ; imglink : ImSt InLink Sep InLink ImEnd ; wikiwlink : WikiWords ; rawlink : RawUrl ; preformat : NoWiki EndNoWikiInline ; linebreak : InlineBrk ({!nobreaks}? LineBreak)? ; any : Any | WS | {!nobreaks}? LineBreak ;
Handle trailing linebreaks after a block
Handle trailing linebreaks after a block
ANTLR
apache-2.0
ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,strr/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki
ea08d9eaad422214e83ddf10db1873faaa577559
sharding-core/src/main/antlr4/imports/MySQLComments.g4
sharding-core/src/main/antlr4/imports/MySQLComments.g4
lexer grammar MySQLComments; import Symbol; BLOCK_COMMENT : SLASH_ ASTERISK_ .*? ASTERISK_ SLASH_ -> channel(HIDDEN) ; SL_COMMENT : MINUS_ MINUS_ ~[\r\n]* -> channel(HIDDEN) ;
lexer grammar MySQLComments; import Symbol; BLOCK_COMMENT: SLASH_ ASTERISK_ .*? ASTERISK_ SLASH_ -> channel(HIDDEN); INLINE_COMMENT: MINUS_ MINUS_ ~[\r\n]* -> channel(HIDDEN);
update MySQLComments.g4
update MySQLComments.g4
ANTLR
apache-2.0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
cbd8393a4593acf8c6739b8801c81aae230d5e17
vrj.g4
vrj.g4
/** * MIT License * * Copyright (c) 2017 Franco Montenegro * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ grammar vrj; init : (topDeclaration | NL)* EOF ; topDeclaration : libraryDeclaration | structDeclaration | typeDeclaration | nativeDeclaration | functionDeclaration | globalDeclaration ; visibility : 'private' | 'public' ; name : ID ; type : expression | 'nothing' ; param : type name ; paramList : (param (',' param)*) | 'nothing' ; typeDeclaration : 'type' typeName=name ('extends' typeExtends=name)? NL ; functionSignature : name 'takes' paramList 'returns' type NL ; nativeDeclaration : ('constant')? 'native' functionSignature ; arguments : '(' expressionList? ')' ; expression : '(' expression ')' #ParenthesisExpression | left=expression '.' right=expression #ChainExpression | variable=name ('[' index=expression ']')? #VariableExpression | function=name arguments #FunctionExpression | '-' expression #NegativeExpression | 'not' expression #NotExpression | left=expression '%' right=expression #ModuloExpression | left=expression operator=('/' | '*') right=expression #DivMultExpression | left=expression operator=('+' | '-') right=expression #SumSubExpression | left=expression operator=('==' | '!=' | '<=' | '<' | '>' | '>=') right=expression #ComparisonExpression | left=expression operator=('or' | 'and') right=expression #LogicalExpression | 'function' code=expression #CodeExpression | ('true' | 'false') #BooleanExpression | 'null' #NullExpression | STRING #StringExpression | REAL #RealExpression | INT #IntegerExpression ; expressionList : expression (',' expression)* ; variableDeclaration : type 'array' name NL #ArrayVariableDeclaration | type name ('=' value=expression)? NL #NonArrayVariableDeclaration ; globalVariableDeclaration : visibility? (constant='constant')? variableDeclaration ; globalDeclaration : 'globals' NL (globalVariableDeclaration | NL)* 'endglobals' NL ; loopStatement : 'loop' NL statements 'endloop' NL ; elseIfStatement : 'elseif' condition=expression 'then' NL statements ; elseStatement : 'else' NL statements ; ifStatement : (sstatic='static')? 'if' condition=expression 'then' NL statements elseIfStatement* elseStatement? 'endif' NL ; localVariableDeclaration : 'local' variableDeclaration ; setVariableStatement : 'set' variable=expression '=' value=expression NL ; exitWhenStatement : 'exitwhen' condition=expression NL ; functionCallStatement : 'call' function=expression NL ; returnStatement : 'return' expression? NL ; statement : localVariableDeclaration | setVariableStatement | exitWhenStatement | functionCallStatement | returnStatement | ifStatement | loopStatement ; statements : (statement | NL)* ; functionDeclaration : visibility? 'function' functionSignature statements 'endfunction' NL ; libraryRequirementsExpression : name (',' name)* ; libraryBody : ( globalDeclaration | functionDeclaration | structDeclaration | NL )* ; libraryDeclaration : 'library' name ('initializer' initializer=name)? ('requires' libraryRequirementsExpression)? NL libraryBody 'endlibrary' NL ; propertyDeclaration : visibility? (sstatic='static')? variableDeclaration ; methodDeclaration : visibility? (sstatic='static')? 'method' (operator='operator')? functionSignature statements 'endmethod' NL ; extendsFromExpression : 'array' | expression ; structBody : ( propertyDeclaration | methodDeclaration | NL )* ; structDeclaration : visibility? 'struct' name ('extends' extendsFromExpression)? NL structBody 'endstruct' NL ; STRING : '"' .*? '"' ; // Credits to WurstScript REAL : [0-9]+ '.' [0-9]* | '.'[0-9]+ ; // Credits to WurstScript INT : [0-9]+ | '0x' [0-9a-fA-F]+ | '\'' . . . . '\'' | '\'' . '\'' ; NL : [\r\n]+ ; ID : [a-zA-Z_][a-zA-Z0-9_]* ; WS : [ \t]+ -> channel(HIDDEN) ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
/** * MIT License * * Copyright (c) 2017 Franco Montenegro * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ grammar vrj; init : (topDeclaration | NL)* EOF ; topDeclaration : libraryDeclaration | scopeDeclaration | structDeclaration | typeDeclaration | nativeDeclaration | functionDeclaration | globalDeclaration ; visibility : 'private' | 'public' ; name : ID ; type : expression | 'nothing' ; param : type name ; paramList : (param (',' param)*) | 'nothing' ; typeDeclaration : 'type' typeName=name ('extends' typeExtends=name)? NL ; functionSignature : name 'takes' paramList 'returns' type NL ; nativeDeclaration : ('constant')? 'native' functionSignature ; arguments : '(' expressionList? ')' ; expression : '(' expression ')' #ParenthesisExpression | left=expression '.' right=expression #ChainExpression | variable=name ('[' index=expression ']')? #VariableExpression | function=name arguments #FunctionExpression | '-' expression #NegativeExpression | 'not' expression #NotExpression | left=expression '%' right=expression #ModuloExpression | left=expression operator=('/' | '*') right=expression #DivMultExpression | left=expression operator=('+' | '-') right=expression #SumSubExpression | left=expression operator=('==' | '!=' | '<=' | '<' | '>' | '>=') right=expression #ComparisonExpression | left=expression operator=('or' | 'and') right=expression #LogicalExpression | 'function' code=expression #CodeExpression | ('true' | 'false') #BooleanExpression | 'null' #NullExpression | STRING #StringExpression | REAL #RealExpression | INT #IntegerExpression ; expressionList : expression (',' expression)* ; variableDeclaration : type 'array' name NL #ArrayVariableDeclaration | type name ('=' value=expression)? NL #NonArrayVariableDeclaration ; globalVariableDeclaration : visibility? (constant='constant')? variableDeclaration ; globalDeclaration : 'globals' NL (globalVariableDeclaration | NL)* 'endglobals' NL ; loopStatement : 'loop' NL statements 'endloop' NL ; elseIfStatement : 'elseif' condition=expression 'then' NL statements ; elseStatement : 'else' NL statements ; ifStatement : (sstatic='static')? 'if' condition=expression 'then' NL statements elseIfStatement* elseStatement? 'endif' NL ; localVariableDeclaration : 'local' variableDeclaration ; setVariableStatement : 'set' variable=expression '=' value=expression NL ; exitWhenStatement : 'exitwhen' condition=expression NL ; functionCallStatement : 'call' function=expression NL ; returnStatement : 'return' expression? NL ; statement : localVariableDeclaration | setVariableStatement | exitWhenStatement | functionCallStatement | returnStatement | ifStatement | loopStatement ; statements : (statement | NL)* ; functionDeclaration : visibility? 'function' functionSignature statements 'endfunction' NL ; libraryRequirementsExpression : name (',' name)* ; libraryBody : ( globalDeclaration | functionDeclaration | structDeclaration | scopeDeclaration | NL )* ; libraryDeclaration : 'library' name ('initializer' initializer=name)? ('requires' libraryRequirementsExpression)? NL libraryBody 'endlibrary' NL ; scopeBody : ( functionDeclaration | structDeclaration | globalDeclaration | scopeDeclaration | NL )* ; scopeDeclaration : 'scope' name ('initializer' initializer=name)? NL scopeBody 'endscope' NL ; propertyDeclaration : visibility? (sstatic='static')? variableDeclaration ; methodDeclaration : visibility? (sstatic='static')? 'method' (operator='operator')? functionSignature statements 'endmethod' NL ; extendsFromExpression : 'array' | expression ; structBody : ( propertyDeclaration | methodDeclaration | NL )* ; structDeclaration : visibility? 'struct' name ('extends' extendsFromExpression)? NL structBody 'endstruct' NL ; STRING : '"' .*? '"' ; // Credits to WurstScript REAL : [0-9]+ '.' [0-9]* | '.'[0-9]+ ; // Credits to WurstScript INT : [0-9]+ | '0x' [0-9a-fA-F]+ | '\'' . . . . '\'' | '\'' . '\'' ; NL : [\r\n]+ ; ID : [a-zA-Z_][a-zA-Z0-9_]* ; WS : [ \t]+ -> channel(HIDDEN) ; COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN);
Add scope to grammar
Add scope to grammar
ANTLR
mit
Ruk33/vrJASS2
7b2595a389d97b31ac054e962281358a3c3c0d43
refal/refal.g4
refal/refal.g4
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett 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. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : '$EXTERNAL' f_name_list | '$EXTERN' f_name_list | '$EXTRN' f_name_list ; f_name_list : f_name | f_name ',' f_name_list ';' ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions '=' right_side | left_side conditions ',' block_ending ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | ('\\x' [0-9] [0-9]) ; WS : [ \r\n\t]+ -> skip ;
/* BSD License Copyright (c) 2021, Tom Everett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Tom Everett 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. */ grammar refal; program : f_definition (';'? program)? | external_decl ';' program | program external_decl ';' ; f_definition : f_name '{' block_ '}' | '$ENTRY' f_name '{' block_ '}' ; external_decl : ('$EXTERNAL' | '$EXTERN' | '$EXTRN') f_name_list ; f_name_list : f_name | f_name ',' f_name_list ';' ; f_name : identifier ; block_ : sentence | sentence ';' | sentence ';' block_ ; sentence : left_side conditions '=' right_side | left_side conditions ',' block_ending ; left_side : pattern ; conditions : (',' arg_ ':' pattern conditions)? ; pattern : expression_ ; arg_ : expression_ ; right_side : expression_ ; expression_ : (term_ expression_)? ; term_ : symbol | variable | '<' expression_ '>' ; block_ending : arg_ ':' '{' block_ '}' ; symbol : identifier | DIGITS | STRING | STRING2 | CHAR ; identifier : IDENTIFER | STRING ; variable : svar | tvar | evar ; svar : 's' '.' index ; tvar : 't' '.' index ; evar : 'e' '.' index ; index : identifier | DIGITS ; DIGITS : [0-9]+ ; IDENTIFER : [a-zA-Z] [a-zA-Z0-9_-]* ; STRING : '"' ~ '"'* '"' ; STRING2 : '\'' ~ '\''* '\'' ; CHAR : '\\\'' | '\\"' | '\\\\' | '\\n' | '\\r' | '\\t' | ('\\x' [0-9] [0-9]) ; WS : [ \r\n\t]+ -> skip ;
Update refal/refal.g4
Update refal/refal.g4 Co-authored-by: Ivan Kochurkin <[email protected]>
ANTLR
mit
antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4,antlr/grammars-v4
3a47b466ee59198445eeacd1e107cdfcbbcdc934
src/net/hillsdon/reviki/wiki/renderer/creole/parser/CreoleTokens.g4
src/net/hillsdon/reviki/wiki/renderer/creole/parser/CreoleTokens.g4
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int olistLevel = 0; public int ulistLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doUlist(int level) { ulistLevel = level; seek(-1); setStart(); } public void doOlist(int level) { olistLevel = level; seek(-1); setStart(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || (last+next).equals(". ") || (last+next).equals(", ")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* ('\r'? '\n' {seek(-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ; U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ; U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ; U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ; U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ; O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ; O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ; O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ; O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ; O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {resetFormatting();} ; /* ***** Tables ***** */ CellSep : '|' {resetFormatting();} ; TdStart : '|' {resetFormatting();} ; ThStart : '|=' {resetFormatting();} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {resetFormatting();} ; LineBreak : '\r'? '\n'+? ; /* ***** Links ***** */ RawUrl : ('http' | 'ftp') '://' (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ -> skip ; fragment START : {start}? | LINE ; fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?); fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : ']]' -> mode(DEFAULT_MODE) ; ImEnd : '}}' -> mode(DEFAULT_MODE) ; Sep : '|' ; InLink : ~(']'|'}'|'|')+ ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : {getCharPositionInLine()==0}? '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : {getCharPositionInLine()==0}? '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : {getCharPositionInLine()==0}? '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : {getCharPositionInLine()==0}? '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : {getCharPositionInLine()==0}? '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : {getCharPositionInLine()==0}? '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
/* Todo: * - Comments justifying and explaining every rule. */ lexer grammar CreoleTokens; options { superClass=ContextSensitiveLexer; } @members { Formatting bold; Formatting italic; Formatting strike; public void setupFormatting() { bold = new Formatting("**"); italic = new Formatting("//"); strike = new Formatting("--"); inlineFormatting.add(bold); inlineFormatting.add(italic); inlineFormatting.add(strike); } public boolean inHeader = false; public boolean start = false; public int olistLevel = 0; public int ulistLevel = 0; boolean nowiki = false; boolean cpp = false; boolean html = false; boolean java = false; boolean xhtml = false; boolean xml = false; public void doHdr() { String prefix = getText().trim(); boolean seekback = false; if(!prefix.substring(prefix.length() - 1).equals("=")) { prefix = prefix.substring(0, prefix.length() - 1); seekback = true; } if(prefix.length() <= 6) { if(seekback) { seek(-1); } setText(prefix); inHeader = true; } else { setType(Any); } } public void setStart() { String next1 = next(); String next2 = get(1); start = (next1.equals("*") && !next2.equals("*")) || (next1.equals("#") && !next2.equals("#")); } public void doUlist(int level) { ulistLevel = level; seek(-1); setStart(); } public void doOlist(int level) { olistLevel = level; seek(-1); setStart(); } public void doUrl() { String url = getText(); String last = url.substring(url.length()-1); String next = next(); if((last + next).equals("//") || (last+next).equals(". ") || (last+next).equals(", ")) { seek(-1); setText(url.substring(0, url.length() - 1)); } } } /* ***** Headings ***** */ HSt : LINE '='+ ~'=' WS? {doHdr();} ; HEnd : ' '* '='* ('\r'? '\n' {seek(-1);} | EOF) {inHeader}? {inHeader = false; resetFormatting();} ; /* ***** Lists ***** */ U1 : START '*' ~'*' {doUlist(1); resetFormatting();} ; U2 : START '**' ~'*' {ulistLevel >= 1}? {doUlist(2); resetFormatting();} ; U3 : START '***' ~'*' {ulistLevel >= 2}? {doUlist(3); resetFormatting();} ; U4 : START '****' ~'*' {ulistLevel >= 3}? {doUlist(4); resetFormatting();} ; U5 : START '*****' ~'*' {ulistLevel >= 4}? {doUlist(5); resetFormatting();} ; O1 : START '#' ~'#' {doOlist(1); resetFormatting();} ; O2 : START '##' ~'#' {olistLevel >= 1}? {doOlist(2); resetFormatting();} ; O3 : START '###' ~'#' {olistLevel >= 2}? {doOlist(3); resetFormatting();} ; O4 : START '####' ~'#' {olistLevel >= 3}? {doOlist(4); resetFormatting();} ; O5 : START '#####' ~'#' {olistLevel >= 4}? {doOlist(5); resetFormatting();} ; /* ***** Horizontal Rules ***** */ Rule : LINE '---' '-'+? {resetFormatting();} ; /* ***** Tables ***** */ CellSep : '|' {resetFormatting();} ; TdStart : '|' {resetFormatting();} ; ThStart : '|=' {resetFormatting();} ; /* ***** Inline Formatting ***** */ BSt : '**' {!bold.active}? {setFormatting(bold, Any);} ; ISt : '//' {!italic.active}? {setFormatting(italic, Any);} ; SSt : '--' {!strike.active}? {setFormatting(strike, Any);} ; BEnd : '**' {bold.active}? {unsetFormatting(bold);} ; IEnd : '//' {italic.active}? {unsetFormatting(italic);} ; SEnd : '--' {strike.active}? {unsetFormatting(strike);} ; NoWiki : '{{{' {nowiki=true;} -> mode(CODE_INLINE) ; StartCpp : '[<c++>]' {cpp=true;} -> mode(CODE_INLINE) ; StartHtml : '[<html>]' {html=true;} -> mode(CODE_INLINE) ; StartJava : '[<java>]' {java=true;} -> mode(CODE_INLINE) ; StartXhtml : '[<xhtml>]' {xhtml=true;} -> mode(CODE_INLINE) ; StartXml : '[<xml>]' {xml=true;} -> mode(CODE_INLINE) ; /* ***** Links ***** */ LiSt : '[[' -> mode(LINK) ; ImSt : '{{' -> mode(LINK) ; /* ***** Breaks ***** */ InlineBrk : '\\\\' ; ParBreak : LineBreak LineBreak+ {resetFormatting();} ; LineBreak : '\r'? '\n'+? ; /* ***** Links ***** */ RawUrl : ('http://' | 'ftp://' | 'mailto:') (~(' '|'\t'|'\r'|'\n'|'/')+ '/'?)+ {doUrl();}; WikiWords : (ALNUM+ ':')? (UPPER ((ALNUM|'.')* ALNUM)*) (UPPER ((ALNUM|'.')* ALNUM)*)+; /* ***** Miscellaneous ***** */ Any : . ; WS : (' '|'\t'|'\r'|'\n')+ -> skip ; fragment START : {start}? | LINE ; fragment LINE : ({getCharPositionInLine()==0}? WS? | LineBreak WS?); fragment ALNUM : (ALPHA | DIGIT) ; fragment ALPHA : (UPPER | LOWER) ; fragment UPPER : ('A'..'Z') ; fragment LOWER : ('a'..'z') ; fragment DIGIT : ('0'..'9') ; /* ***** Contextual stuff ***** */ mode LINK; LiEnd : ']]' -> mode(DEFAULT_MODE) ; ImEnd : '}}' -> mode(DEFAULT_MODE) ; Sep : '|' ; InLink : ~(']'|'}'|'|')+ ; mode CODE_INLINE; AnyInline : ~('\r'|'\n') -> more; OopsItsABlock : ('\r'|'\n') -> mode(CODE_BLOCK), more ; EndNoWikiInline : '}}}' (~'}' {seek(-1);} | EOF) {nowiki}? -> mode(DEFAULT_MODE) ; EndCppInline : '[</c++>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlInline : '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaInline : '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlInline : '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlInline : '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ; mode CODE_BLOCK; AnyText : . -> more ; EndNoWikiBlock : {getCharPositionInLine()==0}? '}}}' {nowiki}? {nowiki=false;} -> mode(DEFAULT_MODE) ; EndCppBlock : {getCharPositionInLine()==0}? '[</cpp>]' {cpp}? {cpp=false;} -> mode(DEFAULT_MODE) ; EndHtmlBlock : {getCharPositionInLine()==0}? '[</html>]' {html}? {html=false;} -> mode(DEFAULT_MODE) ; EndJavaBlock : {getCharPositionInLine()==0}? '[</java>]' {java}? {java=false;} -> mode(DEFAULT_MODE) ; EndXhtmlBlock : {getCharPositionInLine()==0}? '[</xhtml>]' {xhtml}? {xhtml=false;} -> mode(DEFAULT_MODE) ; EndXmlBlock : {getCharPositionInLine()==0}? '[</xml>]' {xml}? {xml=false;} -> mode(DEFAULT_MODE) ;
Allow mailto: to start a raw url
Allow mailto: to start a raw url
ANTLR
apache-2.0
ashirley/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,strr/reviki,ashirley/reviki,strr/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki
e1961a5e4752d9bab5bc9ad09bda4daa546f675f
sharding-core/src/main/antlr4/imports/PostgreKeyword.g4
sharding-core/src/main/antlr4/imports/PostgreKeyword.g4
lexer grammar PostgreKeyword; import Symbol; ACTION : A C T I O N ; ARRAY : A R R A Y ; BIT : B I T ; BRIN : B R I N ; BTREE : B T R E E ; CACHE : C A C H E ; CAST : C A S T ; CHARACTER : C H A R A C T E R ; COLLATE : C O L L A T E ; COMMENTS : C O M M E N T S ; CONCURRENTLY : C O N C U R R E N T L Y ; CONSTRAINTS : C O N S T R A I N T S ; CURRENT : C U R R E N T ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; CYCLE : C Y C L E ; DATA : D A T A ; DAY : D A Y ; DEFAULTS : D E F A U L T S ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DEPENDS : D E P E N D S ; DISTINCT : D I S T I N C T ; DOUBLE : D O U B L E ; EXCLUDING : E X C L U D I N G ; EXTENSION : E X T E N S I O N ; EXTRACT : E X T R A C T ; FILTER : F I L T E R ; FIRST : F I R S T ; FOLLOWING : F O L L O W I N G ; FULL : F U L L ; GIN : G I N ; GIST : G I S T ; GLOBAL : G L O B A L ; HASH : H A S H ; HOUR : H O U R ; IDENTITY : I D E N T I T Y ; IMMEDIATE : I M M E D I A T E ; INCLUDING : I N C L U D I N G ; INCREMENT : I N C R E M E N T ; INDEXES : I N D E X E S ; INHERIT : I N H E R I T ; INHERITS : I N H E R I T S ; INITIALLY : I N I T I A L L Y ; LAST : L A S T ; LOCAL : L O C A L ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MINUTE : M I N U T E ; MINVALUE : M I N V A L U E ; MONTH : M O N T H ; NOTHING : N O T H I N G ; NULLS : N U L L S ; OF : O F ; ONLY : O N L Y ; OVER : O V E R ; OWNED : O W N E D ; PARTIAL : P A R T I A L ; PRECEDING : P R E C E D I N G ; PRECISION : P R E C I S I O N ; RANGE : R A N G E ; RENAME : R E N A M E ; REPLICA : R E P L I C A ; RESTRICT : R E S T R I C T ; ROWS : R O W S ; SECOND : S E C O N D ; SIMPLE : S I M P L E ; SPGIST : S P G I S T ; START : S T A R T ; STATISTICS : S T A T I S T I C S ; STORAGE : S T O R A G E ; TABLESPACE : T A B L E S P A C E ; TEMP : T E M P ; TEMPORARY : T E M P O R A R Y ; TYPE : T Y P E ; UNBOUNDED : U N B O U N D E D ; UNLOGGED : U N L O G G E D ; UPDATE : U P D A T E ; USING : U S I N G ; VALID : V A L I D ; VALIDATE : V A L I D A T E ; VARYING : V A R Y I N G ; WITHIN : W I T H I N ; WITHOUT : W I T H O U T ; ZONE : Z O N E ;
lexer grammar PostgreKeyword; import Symbol; ACTION : A C T I O N ; ARRAY : A R R A Y ; BIT : B I T ; BRIN : B R I N ; BTREE : B T R E E ; CACHE : C A C H E ; CAST : C A S T ; CHARACTER : C H A R A C T E R ; CLUSTER : C L U S T E R ; COLLATE : C O L L A T E ; COMMENTS : C O M M E N T S ; CONCURRENTLY : C O N C U R R E N T L Y ; CONSTRAINTS : C O N S T R A I N T S ; CURRENT : C U R R E N T ; CURRENT_TIMESTAMP : C U R R E N T UL_ T I M E S T A M P ; CURRENT_USER : C U R R E N T UL_ U S E R ; CYCLE : C Y C L E ; DATA : D A T A ; DAY : D A Y ; DEFAULTS : D E F A U L T S ; DEFERRABLE : D E F E R R A B L E ; DEFERRED : D E F E R R E D ; DEPENDS : D E P E N D S ; DISABLE : D I S A B L E ; DISTINCT : D I S T I N C T ; DOUBLE : D O U B L E ; ENABLE : E N A B L E ; EXCLUDING : E X C L U D I N G ; EXTENDED : E X T E N D E D ; EXTENSION : E X T E N S I O N ; EXTERNAL : E X T E R N A L ; EXTRACT : E X T R A C T ; FILTER : F I L T E R ; FIRST : F I R S T ; FOLLOWING : F O L L O W I N G ; FORCE : F O R C E ; FULL : F U L L ; GIN : G I N ; GIST : G I S T ; GLOBAL : G L O B A L ; HASH : H A S H ; HOUR : H O U R ; IDENTITY : I D E N T I T Y ; IMMEDIATE : I M M E D I A T E ; INCLUDING : I N C L U D I N G ; INCREMENT : I N C R E M E N T ; INDEXES : I N D E X E S ; INHERIT : I N H E R I T ; INHERITS : I N H E R I T S ; INITIALLY : I N I T I A L L Y ; LAST : L A S T ; LEVEL : L E V E L ; LOCAL : L O C A L ; LOGGED : L O G G E D ; MAIN : M A I N ; MATCH : M A T C H ; MAXVALUE : M A X V A L U E ; MINUTE : M I N U T E ; MINVALUE : M I N V A L U E ; MONTH : M O N T H ; NOTHING : N O T H I N G ; NULLS : N U L L S ; OF : O F ; OIDS : O I D S ; ONLY : O N L Y ; OVER : O V E R ; OWNED : O W N E D ; OWNER : O W N E R ; PARTIAL : P A R T I A L ; PLAIN : P L A I N ; PRECEDING : P R E C E D I N G ; PRECISION : P R E C I S I O N ; RANGE : R A N G E ; RENAME : R E N A M E ; REPLICA : R E P L I C A ; RESET : R E S E T ; RESTART : R E S T A R T ; RESTRICT : R E S T R I C T ; ROWS : R O W S ; RULE : R U L E ; SECOND : S E C O N D ; SECURITY : S E C U R I T Y ; SESSION_USER : S E S S I O N UL_ U S E R ; SIMPLE : S I M P L E ; SPGIST : S P G I S T ; START : S T A R T ; STATISTICS : S T A T I S T I C S ; STORAGE : S T O R A G E ; TABLESPACE : T A B L E S P A C E ; TEMP : T E M P ; TEMPORARY : T E M P O R A R Y ; TRIGGER : T R I G G E R ; TYPE : T Y P E ; UNBOUNDED : U N B O U N D E D ; UNLOGGED : U N L O G G E D ; UPDATE : U P D A T E ; USER : U S E R ; USING : U S I N G ; VALID : V A L I D ; VALIDATE : V A L I D A T E ; VARYING : V A R Y I N G ; WITHIN : W I T H I N ; WITHOUT : W I T H O U T ; ZONE : Z O N E ;
Add missiong Keyword
Add missiong Keyword
ANTLR
apache-2.0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
b10b053d6a1fa11ec3aeac4b3b56e0d4fd32aedb
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
reo-compiler/src/main/antlr4/nl/cwi/reo/parse/Reo.g4
grammar Reo; /** * Generic structure */ file : (comp | defn)* EOF ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' comp* '}' # defnComposed ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' comp* '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | cam # atomCAM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID # nodesName | ID '[' expr ']' # nodesIndex | ID '[' expr '...' expr ']' # nodesRange ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | INT ID # exprScalar | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ casm : '#CASM' casm_stmt* ; casm_stmt : ID '--' sync_const ',' casm_dc '->' ID ; casm_dc : 'true' # casm_dcTrue | casm_term '==' casm_term # casm_dcEql ; casm_term : STRING # casm_termData | 'd(' ID ')' # casm_termPort | ID # casm_termMemoryCurr | ID '\'' # casm_termMemoryNext ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID ':' wa_jc # wa_stmtInvar | ID '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
grammar Reo; /** * Generic structure */ file : (comp | defn)* EOF ; defn : 'define' ID params? portset '{' atom '}' # defnAtomic | 'define' ID params? nodeset '{' comp* '}' # defnComposed ; comp : ID assign? nodeset # compReference | 'for' ID '=' expr '...' expr '{' comp* '}' # compForLoop ; atom : java # atomJava | c # atomC | pa # atomPA | cam # atomCAM | wa # atomWA ; params : '<' ID (',' ID)* '>' ; assign : '<' value (',' value)* '>' ; value : ID | INT | STRING ; nodeset : '(' ')' | '(' nodes (',' nodes)* ')' ; nodes : ID # nodesName | ID '[' expr ']' # nodesIndex | ID '[' expr '...' expr ']' # nodesRange ; portset : '(' port (',' port)* ')' ; port : ID '?' # portInput | ID '!' # portOutput ; expr : ID # exprParameter | INT # exprInteger | INT ID # exprScalar | '-' expr # exprUnaryMin | expr '+' expr # exprAddition | expr '-' expr # exprDifference ; /** * Java */ java : '#Java' FUNC ; /** * C */ c : '#C' FUNC ; /** * Port Automata */ pa : '#PA' pa_stmt* ; pa_stmt : ID '--' sync_const '->' ID ; sync_const : '{' '}' | '{' ID (',' ID)* '}' ; /** * Constraint Automata with State Memory */ cam : '#CAM' cam_stmt* ; cam_stmt : ID '--' sync_const ',' cam_dc '->' ID ; cam_dc : 'true' # cam_dcTrue | cam_term '==' cam_term # cam_dcEql ; cam_term : STRING # cam_termData | 'd(' ID ')' # cam_termPort | ID # cam_termMemoryCurr | ID '\'' # cam_termMemoryNext ; /** * Work Automata */ wa : '#WA' wa_stmt* ; wa_stmt : ID ':' wa_jc # wa_stmtInvar | ID '--' sync_const ',' wa_jc '->' ID # wa_stmtTrans ; wa_jc : 'true' # wa_jcTrue | ID '==' INT # wa_jcEql | ID '<=' INT # wa_jcLeq | wa_jc '&' wa_jc # wa_jcAnd ; /** * Tokens */ ID : [a-zA-Z] [a-zA-Z0-9]* ; INT : ( '0' | [1-9] [0-9]* ) ; STRING : '\'' .*? '\'' ; FUNC : [a-zA-Z] [a-zA-Z0-9_-.:]* ; SPACES : [ \t\r\n]+ -> skip ; SL_COMM : '//' .*? ('\n'|EOF) -> skip ; ML_COMM : '/*' .*? '*/' -> skip ;
Update Reo.g4
Update Reo.g4
ANTLR
mit
kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo-compiler,kasperdokter/Reo,kasperdokter/Reo-compiler,kasperdokter/Reo
9cd32f36b4ba3c331b3d9d751ac41b46661b5a3b
runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.g4
runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.g4
lexer grammar XPathLexer; @header {package org.antlr.v4.runtime.tree.xpath;} tokens { TOKEN_REF, RULE_REF } // "//|/|//[!]|/\\[!]|\\w+|'.+?'|[*]" // TODO: handle escapes in strings? /* path : separator? word (separator word)* EOF ; separator : '/' '!' | '//' '!' | '/' | '//' ; word: TOKEN_REF | RULE_REF | STRING | '*' ; */ ANYWHERE : '//' ; ROOT : '/' ; WILDCARD : '*' ; BANG : '!' ; ID : NameStartChar NameChar* { String text = getText(); if ( Character.isUpperCase(text.charAt(0)) ) setType(TOKEN_REF); else setType(RULE_REF); } ; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; STRING : '\'' .*? '\'' ; //WS : [ \t\r\n]+ -> skip ;
lexer grammar XPathLexer; tokens { TOKEN_REF, RULE_REF } /* path : separator? word (separator word)* EOF ; separator : '/' '!' | '//' '!' | '/' | '//' ; word: TOKEN_REF | RULE_REF | STRING | '*' ; */ ANYWHERE : '//' ; ROOT : '/' ; WILDCARD : '*' ; BANG : '!' ; ID : NameStartChar NameChar* { String text = getText(); if ( Character.isUpperCase(text.charAt(0)) ) setType(TOKEN_REF); else setType(RULE_REF); } ; fragment NameChar : NameStartChar | '0'..'9' | '_' | '\u00B7' | '\u0300'..'\u036F' | '\u203F'..'\u2040' ; fragment NameStartChar : 'A'..'Z' | 'a'..'z' | '\u00C0'..'\u00D6' | '\u00D8'..'\u00F6' | '\u00F8'..'\u02FF' | '\u0370'..'\u037D' | '\u037F'..'\u1FFF' | '\u200C'..'\u200D' | '\u2070'..'\u218F' | '\u2C00'..'\u2FEF' | '\u3001'..'\uD7FF' | '\uF900'..'\uFDCF' | '\uFDF0'..'\uFFFD' ; // ignores | ['\u10000-'\uEFFFF] ; STRING : '\'' .*? '\'' ; //WS : [ \t\r\n]+ -> skip ;
remove comment and package spec from grammar
remove comment and package spec from grammar
ANTLR
bsd-3-clause
joshids/antlr4,parrt/antlr4,krzkaczor/antlr4,worsht/antlr4,cocosli/antlr4,ericvergnaud/antlr4,supriyantomaftuh/antlr4,sidhart/antlr4,joshids/antlr4,hce/antlr4,chienjchienj/antlr4,hce/antlr4,krzkaczor/antlr4,chandler14362/antlr4,parrt/antlr4,chienjchienj/antlr4,parrt/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,Distrotech/antlr4,worsht/antlr4,joshids/antlr4,cocosli/antlr4,ericvergnaud/antlr4,wjkohnen/antlr4,supriyantomaftuh/antlr4,antlr/antlr4,lncosie/antlr4,wjkohnen/antlr4,cooperra/antlr4,wjkohnen/antlr4,Pursuit92/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,Pursuit92/antlr4,joshids/antlr4,joshids/antlr4,Distrotech/antlr4,antlr/antlr4,Distrotech/antlr4,cocosli/antlr4,antlr/antlr4,mcanthony/antlr4,jvanzyl/antlr4,lncosie/antlr4,antlr/antlr4,sidhart/antlr4,wjkohnen/antlr4,cooperra/antlr4,parrt/antlr4,joshids/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,mcanthony/antlr4,cooperra/antlr4,krzkaczor/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,chienjchienj/antlr4,Pursuit92/antlr4,parrt/antlr4,antlr/antlr4,cocosli/antlr4,chandler14362/antlr4,sidhart/antlr4,sidhart/antlr4,mcanthony/antlr4,antlr/antlr4,jvanzyl/antlr4,wjkohnen/antlr4,parrt/antlr4,lncosie/antlr4,jvanzyl/antlr4,chienjchienj/antlr4,joshids/antlr4,parrt/antlr4,antlr/antlr4,lncosie/antlr4,chandler14362/antlr4,worsht/antlr4,hce/antlr4,jvanzyl/antlr4,parrt/antlr4,lncosie/antlr4,worsht/antlr4,antlr/antlr4,mcanthony/antlr4,chandler14362/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,worsht/antlr4,chandler14362/antlr4,antlr/antlr4,wjkohnen/antlr4,antlr/antlr4,joshids/antlr4,supriyantomaftuh/antlr4,Pursuit92/antlr4,mcanthony/antlr4,sidhart/antlr4,hce/antlr4,parrt/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,chienjchienj/antlr4,chandler14362/antlr4,Distrotech/antlr4,supriyantomaftuh/antlr4,cooperra/antlr4,ericvergnaud/antlr4,krzkaczor/antlr4,supriyantomaftuh/antlr4,Distrotech/antlr4,ericvergnaud/antlr4,Pursuit92/antlr4,parrt/antlr4,wjkohnen/antlr4,chandler14362/antlr4,ericvergnaud/antlr4