官方文档
https://codeql.github.com/docs/ql-language-reference/predicates/

QL中的谓词用来声明逻辑关系。感觉谓词跟”函数”概念非常相似。
image.png
谓词isCountry相当于一元数组{("Belgium"),("Germany"),("France")}
谓词hasCapital相当于两元数组{("Belgium","Brussels"),("Germany","Berlin"),("France","Paris")}

内置谓词

https://codeql.github.com/docs/ql-language-reference/ql-language-specification/#built-ins
不同的数据类型拥有不同的内置谓词

定义谓词

1\ 对于没有返回值的谓词使用predicate关键字标记,拥有返回值的谓词使用返回值对应的数据类型标记。
2\ 谓词的名称,使用小写字母开头的标识符。
3\ 谓词的参数,使用逗号分隔。需要指定参数类型。
4\ 谓词体本身,用大括号包裹起来。

定义没有result的谓词

  1. predicate isCountry(string country) {
  2. country = "Germany"
  3. or
  4. country = "Belgium"
  5. or
  6. country = "France"
  7. }

定义有result的谓词

  1. int getSuccessor(int i) {
  2. result = i + 1
  3. }

谓词的嵌套

谓词的种类

非成员谓词、成员谓词、特征谓词
非成员变量定义在类外

  1. // 1. 非成员谓词
  2. int getSuccessor(int i) {
  3. result = i + 1 and
  4. i in [1 .. 9]
  5. }
  6. class FavoriteNumbers extends int {
  7. // 2. 特征谓词
  8. FavoriteNumbers() {
  9. this = 1 or
  10. this = 4 or
  11. this = 9
  12. }
  13. // 3. FavoriteNumbers类的成员谓词
  14. string getName() {
  15. this = 1 and result = "one"
  16. or
  17. this = 4 and result = "four"
  18. or
  19. this = 9 and result = "nine"
  20. }
  21. }

绑定行为

无限谓词,指不受限制的任意数量的值。

  1. int multiplyBy4(int i) {
  2. result = i * 4
  3. }

无限谓词会引发错误
可以在谓词上面使用bindingset注解表示限定了某个参数的集合

  1. bindingset[i]
  2. int multiplyBy4(int i) {
  3. result = i * 4
  4. }
  5. from int i
  6. where i in [1 .. 10]
  7. select multiplyBy4(i)

数据库谓词