Skip to content

Add callsite information to the MacroContext #132

@johnpyp

Description

@johnpyp

Clear and concise description of the problem

I'd love to be able to get information about the callsite of the macro inside of the macro. At a basic level, this would be something like { filepath: string, lineNumber: number }, but I imagine could include additional information such as surrounding AST.

An example of what this would be useful for is to inject callsite information automatically into OpenTelemtetry without having to do the expensive and inaccurate (in the case of bundling) operation of retrieving a stacktrace at runtime.

Motivating examples:

// src/myfile.ts
import { $autoFunctionLabel, $autoCallsite, $autoLine, $autoSmartAssertCondition } from 'my-lib' with { type: 'macro' }

class MyClass {
  myFunction() {
    const span = tracer.startSpan($autoFunctionLabel())
    span.setAttribute("callsite", $autoCallsite())

    const x = 5;
    const y = 10;

    assert(x == y, `Assertion failed! Context: "${$autoLine()}"`)
    // a more intelligent variant
    assert(x == y, `Assertion failed! Condition: "${$autoSmartAssertCondition()}"`)
  }
}

// transforms into

class MyClass {
  myFunction() {
    const span = tracer.startSpan("MyClass.myFunction")
    span.setAttribute("callsite", "src/myfile.ts:42")

    const x = 5;
    const y = 10;

    assert(x == y, `Assertion failed! Context: "assert(x == y, \`Assertion failed! Context: \${$autoLine()}\`)"`)
    // a more intelligent variant
    assert(x == y, `Assertion failed! Condition: "x == y"`)
  }
}

Suggested solution

Expose callsite information in the MacroContext.

  • absolute file path to the file on disk being transformed
  • line number
  • line contents
  • AST and a pointer to the callsite or something?

Alternative

N/A

Additional context

N/A

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions