Skip to content

Add advanced selector types and options for Foresta.js AST engine #7

Description

@joelmartinez

Overview

Expand Foresta.js selector engine to support advanced selector types and options, inspired by CSS selectors and attribute syntax. These enhancements will enable even more powerful queries on JavaScript ASTs, supporting use-cases like attribute querying, logical compounds, structural queries, and more.


Requirements

Implement the following selector types/options with comprehensive unit tests covering all syntax examples and ensuring correctness across lexical scopes, closures, async contexts, promises, etc. The implementation should work seamlessly with all ASTs generated by Esprima.

1. Property Value Attribute Selectors

  • Literal[value=42] // match Literal nodes with value 42
  • Identifier[name^="is"] // match identifiers with names starting with 'is'

2. Negations

  • VariableDeclarator:not(#foo) // match VariableDeclarators not named 'foo'

3. Ancestor & Structural Selectors

  • FunctionDeclaration VariableDeclaration // VariableDeclaration within a function
  • BlockStatement > VariableDeclaration // VariableDeclaration as direct child of a block
  • Property + Property // Sibling properties within an object expression

4. Pseudo-Classes

  • :first-child, :last-child, :nth-child(n)
  • :empty (node has no children)
  • :has(selector) for parent nodes containing a match

5. Logical & Group Compound Selectors

  • VariableDeclaration, FunctionDeclaration // OR
  • (VariableDeclarator[name=foo] FunctionExpression) // AND/grouping

6. Reference & Usage Queries

  • CallExpression[callee.name=fetch] // Find all fetch() calls

7. Scope Queries

  • Scope filtering: match variables limited to global, local, or block

8. Control Flow/Contextual Selectors

  • IfStatement > ReturnStatement // Return inside if
  • SwitchCase > Literal // Literal inside case

9. Pattern Selectors (RegExp)

  • Identifier[name~/^get[A-Z]/] // Identifiers starting with 'get' followed by a capital

10. Source Location Selectors

  • :range[10:15-10:30] // Nodes covering character/line range

11. JSDoc or Export Selectors

  • ExportNamedDeclaration > FunctionDeclaration // Top-level export functions

PR/Validation

  • Add Jest unit tests for all new selector syntaxes and edge cases, including block scopes, async/await, closures, and promise chains
  • Ensure all new selectors work on code samples with nested/complex scopes
  • Update the README with usage examples for each new selector type

Notes

  • Follow existing code and test conventions
  • See discussion in (README and examples/basic.js) for design history

Please implement with GitHub Copilot, referencing this issue, and assign to @joelmartinez.

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions