Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] How to query out all the properties and methods from a class? #223

Open
liaodalin19903 opened this issue Aug 22, 2024 · 0 comments

Comments

@liaodalin19903
Copy link

How to query out all the properties and methods from a class?

I tried to match a class for getting all the properties and methods:

const Parser = require("tree-sitter")
const TypeScript = require("tree-sitter-typescript").typescript

const { Query } = Parser 

const parser = new Parser()
parser.setLanguage(TypeScript)

/*
const query = new Query(
  TypeScript,
  `
    (class_declaration 
      name: (identifier) @class-name
      (class_heritage (extends_clause value: (identifier)))
      )
  `
);
*/

//(class_declaration name: (identifier) @class-name)
const query = new Query(
  TypeScript,
  `
    (class_declaration 
      name: (type_identifier) @class-name
      body: (class_body
        (method_definition
          name: (property_identifier) @the-method-name)))
  `
);


const tree = parser.parse(`
class AnimalBase {
  readonly skeleton: number
  readonly blood: 'red' | 'blue' | 'transparent'
}

abstract class Animal extends AnimalBase {

  readonly age: number = 0
  abstract shout (): void  

}

class Cat extends Animal {
  shout() {
      console.log('mew mew')
  }
}

class Dog extends Animal {
  shout() {
      console.log('bark bark')
  }
  shout2() {
      console.log('bark bark')
  }
}
    `);

const matches = query.matches(tree.rootNode);

//console.log(matches[1].captures[0].node.text)  // Dog 

console.log(matches[1].captures)

but I only get one class and one method:

[
  {
    name: 'class-name',
    node: TypeIdentifierNode {
      type: type_identifier,
      startPosition: {row: 19, column: 6},
      endPosition: {row: 19, column: 9},
      childCount: 0,
    }
  },
  {
    name: 'the-method-name',
    node: PropertyIdentifierNode {
      type: property_identifier,
      startPosition: {row: 20, column: 2},
      endPosition: {row: 20, column: 7},
      childCount: 0,
    }
  }
]

How to get the class Dog's all properties and methods?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant