Skip to content

Instantly share code, notes, and snippets.

@itsananderson
Created November 6, 2025 19:08
Show Gist options
  • Select an option

  • Save itsananderson/dfd4750af129338e61358ecc2a772a14 to your computer and use it in GitHub Desktop.

Select an option

Save itsananderson/dfd4750af129338e61358ecc2a772a14 to your computer and use it in GitHub Desktop.
Scanning for forward declarations

Let's say you want to scan for C++ forward declarations in a codebase. Specifically the Chromium codebase.

This Gist captures some details about how to do that with ast-grep. You may also want jq for a few of the commands.

Setup

  • Make sure you have ast-grep and jq installed
  • Copy sgconfig.yml to the root of the Chromium repo
  • Create a folder at the root of the Chromium repo called ast-grep-rules
  • Copy forward-declaration.yaml into that folder

Usage

  • Basic usage: ast-grep scan
  • Collect files with forward declarations, sorted by forward declaration count: ast-grep scan --json=stream | jq -r '.file' | sort | uniq -c | sort -nr
  • Collect forward declaration names, sorted by count: ast-grep scan --json=stream | jq -r '.metaVariables.single.IMPT.text' | sort | uniq -c | sort -nr
id: 'forward-declaration'
language: "C++"
rule:
pattern: $IMPT
any:
- kind: type_identifier
not:
inside:
stopBy: neighbor
any:
# If the type_identifier is inside a qualified identifier, we match that rather than the type_identifier
- kind: qualified_identifier
- kind: qualified_identifier
all:
- inside:
stopBy: neighbor
all:
# Looking for a type_identifier inside a class specifier
- kind: class_specifier
- not:
# but ignore if that class_specifier is inside a type_descriptor
inside:
stopBy: neighbor
kind: type_descriptor
- not:
any:
- precedes:
stopBy: neighbor
any:
- kind: field_declaration_list # Ignore class declarations
- kind: base_class_clause # Ignore class declarations with base class
- kind: virtual_specifier # Ignore class declarations with "final" etc.
- regex: '[A-Z]_EXPORT' # Ignore _EXPORT macros
- regex: '[A-Z]_EXPORT_PRIVATE' # Ignore _EXPORT_PRIVATE macros
languageGlobs:
cpp: ['*.h']
ruleDirs:
- ast-grep-rules
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment