TyrealHu / acorn-typescript

Alternative, TypeScript parser
https://www.npmjs.com/package/acorn-typescript?activeTab=readme
MIT License
145 stars 18 forks source link

Type assertion error #47

Open git-denial opened 1 year ago

git-denial commented 1 year ago

This is the parser code that I used

const node = acorn.Parser.extend(tsPlugin.tsPlugin({dts:false})).parse(file, { sourceType: 'module', ecmaVersion: 'latest', locations: true   })

The source code file contains the Secret type assertion which cause the parser to fail:

desensitizedAdmin.token = jwt.sign({
            authenticated: true,
            admin_id: admin.id,
            username: admin.username,
            role: admin.role
        }, <Secret>process.env.TOKEN_SECRET, {
            expiresIn: 10
        })

Error:

SyntaxError: Unexpected token (175:21)
    at e.pp$4.raise (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn\dist\acorn.js:3560:15)
    at e.p.raiseCommonCheck (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:101327)
    at e.p.raise (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:101481)
    at e.pp$9.unexpected (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn\dist\acorn.js:768:10)
    at e.pp$9.expect (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn\dist\acorn.js:762:28)
    at e.s.jsx_parseExpressionContainer (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:20515)
    at e.s.jsx_parseElementAt (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:21886)
    at e.s.jsx_parseElement (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:22474)
    at e.p.parseExprAtom (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn-typescript\lib\index.js:1:72076)
    at e.pp$5.parseExprSubscripts (C:\Users\orang\Documents\Work\Project\misc\swagger\node_modules\acorn\dist\acorn.js:2708:21) {
  pos: 5110,
  loc: Position { line: 175, column: 21 },
  raisedAt: 5111
}

Are there some additional options that I need to enable to make this work ?

TyrealHu commented 1 year ago

I try it in ts playground. Get a lot of errors.Could u check this code?

git-denial commented 1 year ago

Actually I run the AST parser in a javascript file. Here is a simpler version of the code:

const acorn = require("acorn")
const tsPlugin = require("acorn-typescript")

let source = `
import {NextFunction, Request, Response} from "express";
import {
    BadParamIdError,
    BadRequestError,
    EntityNotFoundError,
    InternalServerError,
    UnauthorizedError
} from "../errors/RequestErrorCollection";

export async function getById(req: Request, res: Response, next: NextFunction) {

  try {

    let id = parseInt(<string>req.params.id)
    if (isNaN(id)) return next(new BadParamIdError)

    return res.send(id)

  } catch (e) {
      next(new InternalServerError(e))
  }
}
`

let node = acorn.Parser.extend(tsPlugin.tsPlugin({dts:false})).parse(source, { sourceType: 'module', ecmaVersion: 'latest', locations: true   })

console.log(node)

The point is, the error occurs whenever there is any type assertion in the code be it : <number> , <string>, <boolean>, etc...

bpstrngr commented 1 year ago

This is a very ambiguous syntax between JSX and TS. You can see in the stack trace that it's being treated as JSX. We could expect independent parsers to accomdate the growing complexity created by these heterogenous semiotics, but i think it would be even preferrable to favor a simpler syntax of type casting (process.env.TOKEN_SECRET as Secret) in this case when its possible if you have means to edit. not just me saying it: https://stackoverflow.com/questions/49818305/what-are-the-difference-between-these-type-assertion-or-casting-methods-in-types "there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use 'as' for consistency"

git-denial commented 1 year ago

This is a very ambiguous syntax between JSX and TS. You can see in the stack trace that it's being treated as JSX. We could expect independent parsers to accomdate the growing complexity created by these heterogenous semiotics, but i think it would be even preferrable to favor a simpler syntax of type casting (process.env.TOKEN_SECRET as Secret) in this case when its possible if you have means to edit. not just me saying it: https://stackoverflow.com/questions/49818305/what-are-the-difference-between-these-type-assertion-or-casting-methods-in-types "there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use 'as' for consistency"

I haven't tried the type casting approach but that seems to be a valid temporary solution. However, changing all of the type assertion to type casting would seems to be a pretty tedious work in a large codebase. I don't really need the type assertion in the return response for now, so my temporary solution for now is to delete the type assertion before being parsed by the AST parser.