benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.91k stars 347 forks source link

Optional chaining (?.) #1394

Closed JakeCigar closed 4 months ago

JakeCigar commented 4 months ago

Is it supported with any parser? Is it planned?

I get /Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:1995 throw this.unexpectedTokenError(token, message); ^ Error: Line 299: Unexpected token . at ErrorHandler.constructError (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:5012:22) at ErrorHandler.createError (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:5028:27) at Parser.unexpectedTokenError (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:1985:39) at Parser.throwUnexpectedToken (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:1995:21) at Parser.parsePrimaryExpression (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:2366:38) at JSXParser.parsePrimaryExpression (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:466:97) at Parser.inheritCoverGrammar (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:2285:37) at Parser.parseLeftHandSideExpressionAllowCall (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:2899:26) at Parser.inheritCoverGrammar (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:2285:37) at Parser.parseUpdateExpression (/Library/WebServer/Documents/play/dropDir/node_modules/esprima/dist/esprima.js:3004:26) { index: 11111, lineNumber: 299, description: 'Unexpected token .' }

when I code ITEM?.getAsEntry?.() ?? ITEM?.webkitGetAsEntry?.()

JakeCigar commented 4 months ago

I found that esprima-next handles it pretty well.

Is there a reason it is not bundled with recast?

eventualbuddha commented 4 months ago

It works fine with Babel:

import { parse } from "recast";
import * as babel from "recast/parsers/babel";

const code = `ITEM?.getAsEntry?.() ?? ITEM?.webkitGetAsEntry?.()`;

console.log(parse(code, { parser: babel }));
/*
prints:
Node {
  original: Node {
    type: "File",
    start: 0,
    end: 50,
    loc: SourceLocation {
    …
*/
JakeCigar commented 4 months ago

Babel worked 99% for my first test. It converted… editedImg.onload=e=>{ makeBlurred(ctx,editedImg).then(_=>{ // console.log("makeBlurred editedImg",figure) }) delete editedImg.onload } to editedImg.onload = (e) => { makeBlurred(ctx, editedImg).then((_) => {}); delete editedImg.onload; }; It lost a comment.