yohhoyの日記

技術的メモをしていきたい日記

独自診断メッセージ diagnose_if属性

Clangコンパイラはユーザ定義のコンパイル警告/エラーメッセージ出力を行うdiagnose_if属性を提供する。

The diagnose_if attribute can be placed on function declarations to emit warnings or errors at compile-time if calls to the attributed function meet certain user-defined criteria. For example:

void abs(int a)
  __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
void must_abs(int a)
  __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));

int val = abs(1); // warning: Redundant abs call
int val2 = must_abs(1); // error: Redundant abs call
int val3 = abs(val);
int val4 = must_abs(val); // Because run-time checks are not emitted for
                          // diagnose_if attributes, this executes without
                          // issue.
https://releases.llvm.org/5.0.0/tools/clang/docs/AttributeReference.html#diagnose-if

C++標準ライブラリlibcxxでは、このdiagnose_if属性を利用してC++標準ライブラリ要件(requirements)診断を部分的に行っている。