Skip to content
This repository has been archived by the owner on Nov 25, 2021. It is now read-only.

AST Printer with comments? #6

Open
mohsen1 opened this issue Jun 10, 2019 · 3 comments
Open

AST Printer with comments? #6

mohsen1 opened this issue Jun 10, 2019 · 3 comments

Comments

@mohsen1
Copy link

mohsen1 commented Jun 10, 2019

I would like to use this package to pars and then pretty print JSON with comments. How can I do that? Using AST.JsonDocument.toJSON(ast) and similar methods does not sustain comments

@neuroo
Copy link
Owner

neuroo commented Jun 12, 2019

toJSON will return the actual JSON object that can be passed to JSON.stringify. If you want to print comments, you need to implement a Visitor that will output them, e.g.:

class MyVisitor extends Visitor {
  constructor() { super(); };

  // pretty printer for all nodes and then for comments:
  comment(commentNode) {
    console.log('[COMMENT]', commentNode.value);
  };
};

@mohsen1
Copy link
Author

mohsen1 commented Jun 12, 2019

I would like to maintain comment locations as much as possible. I will try using the visitor to print. Do you have an example of printer written with the visitor?

@char0n
Copy link

char0n commented Apr 17, 2020

@mohsen1 here is an example of CommentVisitor doing printing:

'use strict';

const { parse, Visitor, AST } = require('./index');

const json = `
// before-everything - 1
{"a": "b"}
// after-everything - 1
`;

class CommentVisitor extends Visitor {
  constructor() {
    super();
  }

  comment(commentNode) {
    console.log(`Comment intercepted: ${commentNode.value}`);
    console.log(`Position: ${commentNode.position.human}`);
    console.log('---------------------')
  }
}

const ast = parse(json, {verbose: true, junker: true});
const visitor = new CommentVisitor();
ast.accept(visitor);

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

No branches or pull requests

3 participants