You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ast-grep规则问题:function_definition内call_expression匹配失败

ast-grep规则匹配问题解决

问题背景

用户尝试使用ast-grep编写规则,期望匹配位于以t_开头的函数定义(如t_a)内部、调用以t_开头的函数(如t_b())的call_expression,但当前规则未匹配到任何内容。

代码示例

void t_b() {
}

void t_a() {
    t_b();
}

void foo() {
    t_b();
}

当前规则表达式

id: t_scope_check
language: c
rule:
  any:
    - pattern:
        context: $T_FUNCTION($$$);
        selector: call_expression
      inside:
        kind: function_definition
        # Once it works without has, try with has please
        #has:
        #  kind: function_declarator
        #  regex: ^t_
        #  stopBy: end

constraints:
  T_FUNCTION:
    regex: '^t_.*'

补充说明

  • 预期匹配t_a内部的t_b(),因为t_b以t_开头且处于t_a内部;
  • 移除inside部分后,规则可匹配所有t_b();
  • 目前注释了has条件,后续需要启用该条件;
  • 已通过AST确认t_b()是t_a()内部的函数调用;

问题分析与修正规则

当前规则的核心问题是inside的语法位置错误,且any包裹属于冗余写法。修正后的规则如下:

id: t_scope_check
language: c
rule:
  pattern:
    context: $T_FUNCTION($$$);
    selector: call_expression
  inside:
    kind: function_definition
    has:
      kind: function_declarator
      regex: ^t_
      stopBy: end

constraints:
  T_FUNCTION:
    regex: '^t_.*'

修正要点

  1. 将inside从any子项中移出,作为rule的直接约束,确保调用表达式的上下文检查生效;
  2. 启用has条件,通过function_declarator匹配以t_开头的函数名,stopBy: end限定检查范围为当前函数定义的声明部分;
  3. 移除不必要的any包裹,简化规则结构;

修正后规则可精准匹配t_a内部的t_b(),同时排除foo内部的t_b()调用。

内容的提问来源于stack exchange,提问作者Ilan Schemoul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 04:04:50