简介
TLA+ 是一门形式规格说明语言(formal specification language),主要用来验证系统的设计和算法的正确性
小example:
问题:您正在为银行编写软件。你有 Alice 和 Bob 作为客户,每个人的账户里都有一定数量的钱。Alice想寄一些钱给Bob。你如何建模?假设您只关心他们的银行账户
--- MODULE transfer ----
EXTENDS Naturals, TLC
(* --algorithm transfer
variables alice_account = 10, bob_account = 10, money = 5;
begin
A: alice_account := alice_account - money;
B: bob_account := bob_account + money;
end algorithm *)
====
- TLA+基于数学,包括时间逻辑(temporal logic)LTL
- TLA+中的时间算子(temproal operators)G和F记为[]和<>
- Gp可以写成[]p,Fp 可以写成<>p
思考问题: - 我们如何用TLA+对transition system进行建模
- 我们需要model states和transitions
- 根据vending machine的例子给出答案
以下是一个简单的转换系统
----------------------- MODULE SimpleTransitionSystem -----------------------
VARIABLES tsstate
TSTypeOK == /\ tsstate \in {"0", "1","2","3","4"}
0to1 == /\ tsstate = "0"
/\ tsstate'= "1"
1to2 == /\ tsstate = "1"
/\ tsstate'= "2"
1to3 == /\ tsstate = "1"
/\ tsstate'= "3"
2to4 == /\ tsstate = "2"
/\ tsstate'= "4"
3to4 == /\ tsstate = "3"
/\ tsstate'= "4"
Init == /\ tsstate = "0"
Next == 0to1 \/ 1to2 \/ 1to3 \/ 2to4 \/ 3to4
TSSpec == Init /\ [][Next]_tsstate /\ WF_tsstate(Next)
============================================================================
上面的代码代表的transition system如下
- {“0”, “1”,“2”,“3”,“4”}代表的是states
- 0to1;1to2等代表TRANSITIONS
Init == /\ tsstate = "0"
指定了初始stateNext == 0to1 \/ 1to2 \/ 1to3 \/ 2to4 \/ 3to4
指定了所有转换
这就是最终结果
check some property of the system
若我们想检查system中的某些性质(property),例如:
property: “it is not possible from the initial state to reach the state 4”
in TLA+ syntax that is : ~<> (tsstate = “4”)
又state4显然可以从0到达,因此公式为假,因此TLA+将返回一个反例,即从0到4的路径。
在toolbox中操作
toolbox结果
这个结果显示了一个counterexample:0-1-2-4
Kripke transition systems
- 在刚才看到的transition systems中,我们只有一个状态变量,然而当考虑Kripke transition systems时,通常有几个变量涉及。这在TLA+中也不难做到
- 一个考虑Cost-benefit analysis的例子:here in each state there is a
variable “cost” and a variable “benefit” whose value change according to the transition
代码如下:
---------------------------- MODULE CostBenefit ------------------------
EXTENDS Integers
VARIABLES
state, cost, benefit
TSTypeOK == /\ cost \in {0..100} /\ benefit \in {0..100} /\ state \in {0..4}
vars == <<cost,benefit,state>>
Init == /\ cost = 0 /\ benefit =0 /\ state=0
0to1 == /\ state = 0 /\ stat