1. 程式人生 > >【Static Program Analysis - Chapter 3】Type Analysis

【Static Program Analysis - Chapter 3】Type Analysis

stat strong solution gen pointer image out ons 我們

類型分析,個人理解就是(通過靜態分析技術)分析出代碼中,哪些地方只能是某種或某幾種數據類型,這是一種約束。

?

例如,給定一個程序:

技術分享圖片

其中,我們可以很直接地得到一些約束:

技術分享圖片

最後,經過簡化可以得到:

技術分享圖片

對於給定的變量類型,如果他們不符合這個約束,則說明,他們是不合法的。

那麽,怎麽去提取以及維護這些約束呢?

采用一種“並查集”的結構:一個有向圖,每個節點有一條邊指向父節點(父節點則指向自己)。如果兩個節點具有相同的父節點,那麽,這個兩節點就認為是等價的,即含有相同的數據類型。

以下是並查集的基本算法:

技術分享圖片

The unification algorithm uses union-find by associating a node with each term (including sub-terms) in the constraint system.

For each term τ we initially invoke MakeSet(τ ).

Note that each term at this point is either a type variable or a proper type (i.e. integer, heap pointer, or function); μ terms are only produced for presenting solutions to constraints, as explained below.

For each constraint τ1 = τ2 we invoke Unify(

τ1, τ2), which unifies the two terms if possible and enforces the general term equality axiom by unifiying sub-terms recursively:?

技術分享圖片

技術分享圖片

Unification fails if attempting to unify two terms with different constructor (where function constructors are considered different if they have different arity).?

再來看個例子:

技術分享圖片

技術分享圖片

技術分享圖片

對於遞歸:

技術分享圖片

Limitations of the Type Analysis?

例子:

技術分享圖片?

運行的時候沒問題,但是,遵循之前的方法會報錯,之前的方法並不考慮程序的順序執行給數據類型轉換的影響。即X=42在X=alloc之後,因此,最終返回的一定是int型。

另一個例子:

技術分享圖片





【Static Program Analysis - Chapter 3】Type Analysis