hegemonic / catharsis

A JavaScript parser for Google Closure Compiler and JSDoc type expressions.
MIT License
54 stars 14 forks source link

Implement TypeTuple #70

Open kungfooman opened 2 years ago

kungfooman commented 2 years ago

Hi @hegemonic,

I would like to see tuple support, which is requested since 2015 and 2017 you mentioned you are open for a PR: https://github.com/jsdoc/jsdoc/issues/1073#issuecomment-312524697

So this is the first step. As soon as catharsis returns a proper AST, JSDoc can correctly implement the documentation for it.

The AST naming is inspired by TypeScript:

Input 1:

const catharsis = require("./catharsis");
const ret = catharsis.parse("[a: string, b: number]", {jsdoc: true});
console.log(JSON.stringify(ret, null, 2));

Output 1:

{
  "type": "TypeTuple",
  "elements": [
    {
      "type": "NamedTupleMember",
      "key": "a",
      "value": {
        "type": "NameExpression",
        "name": "string"
      }
    },
    {
      "type": "NamedTupleMember",
      "key": "b",
      "value": {
        "type": "NameExpression",
        "name": "number"
      }
    }
  ]
}

Input 2:

const catharsis = require("./catharsis");
const ret = catharsis.parse("[action: string, id: 1|2|3]", {jsdoc: true});
console.log(JSON.stringify(ret, null, 2));

Output 2:

{
  "type": "TypeTuple",
  "elements": [
    {
      "type": "NamedTupleMember",
      "key": "action",
      "value": {
        "type": "NameExpression",
        "name": "string"
      }
    },
    {
      "type": "NamedTupleMember",
      "key": "id",
      "value": {
        "type": "TypeUnion",
        "elements": [
          {
            "type": "NameExpression",
            "name": "1"
          },
          {
            "type": "NameExpression",
            "name": "2"
          },
          {
            "type": "NameExpression",
            "name": "3"
          }
        ]
      }
    }
  ]
}

Input 3:

const catharsis = require("./catharsis");
const ret = catharsis.parse("[number, string, Date]", {jsdoc: true});
console.log(JSON.stringify(ret, null, 2));

Output 3:

{
  "type": "TypeTuple",
  "elements": [
    {
      "type": "NameExpression",
      "name": "number"
    },
    {
      "type": "NameExpression",
      "name": "string"
    },
    {
      "type": "NameExpression",
      "name": "Date"
    }
  ]
}