javascript - How to parse C# code then serialize it back to text file -
i found there c# antlr4 grammar. build antlr4 parser c# grammar. works. can walk parse tree , see there nodes have children.
now generate c# source code parse tree.
can somehow generate (out of grammar) inverse of antlr parser instead of parsing, when given parse tree generate source code result in parse tree?
edit:
my current attempt in coffeescript walk source tree decorating pieces of source code using original source , start , stop positions antlr puts in nodes, , walk again print source code. problem multiple nodes start @ same space in source code. deal have nasty logic put source pieces in deepest node:
antlr = require 'antlr4' {csharp4parser} = require './csharp4parser' {csharp4lexer} = require './csharp4lexer' input = "namespace { class b {}; class c {} }" cstream = new antlr.inputstream(input) lexer = new csharp4lexer(cstream) tstream = new antlr.commontokenstream(lexer) parser = new csharp4parser(tstream) parser.buildparsetrees = true ; tree = parser.compilation_unit(); decoratewithsource = new antlr.tree.parsetreelistener(); start = prev: null stop = prev: null o = (msg) -> process.stdout.write(msg) decoratewithsource.entereveryrule = (a) -> if start.prev start.prev.before = input.substr(start.prev.start.start, a.start.start - start.prev.start.start) if stop.prev stop.prev.after = input.substr(stop.prev.stop.start, a.start.start - stop.prev.stop.start) start.prev = stop.prev = null decoratewithsource.exiteveryrule = (a) -> if start.prev start.prev.before = input.substr(start.prev.start.start, a.stop.start - start.prev.start.start) if stop.prev stop.prev.after = input.substr(stop.prev.stop.start, a.stop.start - stop.prev.stop.start) start.prev = null stop.prev = walker = new antlr.tree.parsetreewalker(); walker.walk(decoratewithsource, tree); stop.prev.after = input.substr(stop.prev.stop.start) printout = new antlr.tree.parsetreelistener(); printout.entereveryrule = (a) -> o (a.before || ''), ' -> '+parser.rulenames[a.ruleindex] printout.exiteveryrule = (a) -> o (a.after || ''), ' < '+parser.rulenames[a.ruleindex] walker.walk(printout, tree);
what i'm trying read c# source file (that comes recompiled botched things) tree, pass through transformer written in ometa (that narrows down environment languages have ometa implementation c#, js or coffeescript, possibly others) , write fixed source code.
maybe manually walking parse tree generate code enough me.
not easily; antlr isn't designed this.
you can investigate stringtemplates, let walk tree , spit out code right.
if want regenerate source in detail, isn't enough. see answer on how build prettyprinter.
Comments
Post a Comment