Skip to content

Instantly share code, notes, and snippets.

@gagbo

gagbo/README.md Secret

Last active June 13, 2023 14:52
Show Gist options
  • Save gagbo/f9e9ff04633391408064068356bca4c6 to your computer and use it in GitHub Desktop.
Save gagbo/f9e9ff04633391408064068356bca4c6 to your computer and use it in GitHub Desktop.
Tree-sitter queries help

Tree-sitter Query question

I'd like to reuse the capture from a first pattern to filter the second pattern.

The first sub-pattern extracts the name of an import, and the second sub-pattern is supposed to find the arguments of the calls to the second pattern, whichever nesting level.

You can test the query on https://tree-sitter.github.io/tree-sitter/playground if you find a solution.

Expected result

The funcName captures only match badRoute, rootRoute, asyncRoute.

Actual result

The funcName capture also match req and res on line 7, but it shouldn't.

image

(
(import_statement
(import_clause
(named_imports
(import_specifier
name: (identifier) @wrapperAtName)))
source: (string (string_fragment) @libAtName))
(#eq? @libAtName "@autometrics/autometrics")
)
(
(call_expression
function: (identifier) @wrapperAtCall
arguments: (arguments (identifier) @funcName))
(#eq? @wrapperAtCall @wrapperAtName)
)
import express from "express";
import { autometrics } from "@autometrics/autometrics";
const badRouteMetrics = autometrics(badRoute); // Should match `badRoute` as funcName
app.get("/", autometrics(rootRoute)); // Should match `rootRoute` as funcName
app.get("/bad", (req, res) => badRouteMetrics(req, res)); // Should _not_ match anything
app.get("/async", autometrics(asyncRoute)); // Should match `asyncRoute` as funcName
@Kennobi19
Copy link

import express from "express";
import { autometrics } from "@autometrics/autometrics";

const badRouteMetrics = autometrics(badRoute); // Should match badRoute as funcName

app.get("/", autometrics(rootRoute)); // Should match rootRoute as funcName
app.get("/bad", (req, res) => badRouteMetrics(req, res)); // Should not match anything
app.get("/async", autometrics(asyncRoute)); // Should match asyncRoute as funcName

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment