Typechecker簡(jiǎn)介

2018-10-27 11:20 更新

Hack typechecker是使Hack成為一種獨(dú)特語(yǔ)言的主要工具。在運(yùn)行時(shí)間之前,typechecker會(huì)分析與程序相關(guān)的所有與各種打字錯(cuò)誤相關(guān)的代碼,從而防止可能只在運(yùn)行時(shí)暴露的惡作劇。

沒(méi)有typechecker,這個(gè)簡(jiǎn)單的例子將在運(yùn)行時(shí)失敗。

<?php

namespace Hack\UserDocumentation\TypeChecker\Intro\Examples\RuntimeFail;

class A {
  public function foo() { return 2; }
}

function failing($x) {
  $a = new A();
  if ($x === 4) {
    $a = null;
  }
  // $a being null would only be caught at runtime
  // Fatal error: Uncaught exception 'BadMethodCallException' with message
  // 'Call to a member function foo() on a non-object (NULL)'
  $a->foo();
}

failing(4);

Output

Fatal error: Uncaught exception 'BadMethodCallException' with message 'Call to a member function foo() on a non-object (null)' in /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/runtime-fail.php:17
Stack trace:
#0 /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/runtime-fail.php(20): Hack\UserDocumentation\TypeChecker\Intro\Examples\RuntimeFail\failing()
#1 {main}

但是,在運(yùn)行代碼之前使用typechecker,您可以在部署之前捕獲錯(cuò)誤,從而將用戶從可能發(fā)生的惡意致命中保存。

<?hh

namespace Hack\UserDocumentation\TypeChecker\Intro\Examples\TypecheckerCatch;

class A {
  public function foo() { return 2; }
}

function failing($x) {
  $a = new A();
  if ($x === 4) {
    $a = null;
  }
  // $a being null would only be caught BEFORE runtime
  //   typechecker-catch.php:21:7,9: You are trying to access the member foo
  //                                 but this object can be null. (Typing[4064])
  //   typechecker-catch.php:12:10,13: This is what makes me believe it can be
  //                                   null
  //
  $a->foo();
}

failing(4);

Output

Fatal error: Uncaught exception 'BadMethodCallException' with message 'Call to a member function foo() on a non-object (null)' in /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/typechecker-catch.php.type-errors:20
Stack trace:
#0 /data/users/joelm/user-documentation/guides/hack/25-typechecker/01-introduction-examples/typechecker-catch.php.type-errors(23): Hack\UserDocumentation\TypeChecker\Intro\Examples\TypecheckerCatch\failing()
#1 {main}

typechecker靜態(tài)分析您的程序,捕捉代碼所有路徑中的問(wèn)題。這不是匯編。它是對(duì)程序中可能出現(xiàn)的各種狀態(tài)的超快速反饋,因此您可以在代碼運(yùn)行之前處理它們。Typechecker可以實(shí)時(shí)監(jiān)控代碼的更改并相應(yīng)地更新其分析。

結(jié)合類型注釋的功能,Typechecker是一個(gè)強(qiáng)大的錯(cuò)誤捕獲工具。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)