@@ -188,7 +188,7 @@ function beautifyCode(code) {
188
188
} ) ;
189
189
code = escodegen . generate ( ast , {
190
190
format : {
191
- newline : "\r\ n" ,
191
+ newline : "\n" ,
192
192
quotes : "double"
193
193
}
194
194
} ) ;
@@ -202,16 +202,60 @@ function beautifyCode(code) {
202
202
return code ;
203
203
}
204
204
205
+ var renameVars = {
206
+ "Writer" : "$Writer" ,
207
+ "Reader" : "$Reader" ,
208
+ "util" : "$util"
209
+ } ;
210
+
205
211
function buildFunction ( type , functionName , gen , scope ) {
206
212
var code = gen . str ( functionName )
207
- . replace ( / t h i s \. c t o r / g, " $root" + type . fullName ) // types: construct directly instead of using reflected ctor
208
- . replace ( / ( t y p e s \[ \d + ] ) ( \. v a l u e s ) / g, "$1" ) // enums: use types[N] instead of reflected types[N].values
209
- . replace ( / \b (? ! \. ) W r i t e r \b / g, "$Writer" ) // use common aliases instead of binding through an iife
210
- . replace ( / \b (? ! \. ) R e a d e r \b / g, "$Reader" ) // "
211
- . replace ( / \b (? ! \. ) u t i l \. \b / g, "$util." ) // "
212
- . replace ( / \b (? ! \. ) t y p e s \[ ( \d + ) \] / g, function ( $0 , $1 ) {
213
- return "$root" + type . fieldsArray [ $1 ] . resolvedType . fullName ;
214
- } ) ;
213
+ . replace ( / ( (? ! \. ) t y p e s \[ \d + ] ) ( \. v a l u e s ) / g, "$1" ) ; // enums: use types[N] instead of reflected types[N].values
214
+
215
+ var ast = espree . parse ( code ) ;
216
+ estraverse . replace ( ast , {
217
+ enter : function ( node , parent ) {
218
+ // rename vars
219
+ if (
220
+ node . type === "Identifier" && renameVars [ node . name ]
221
+ && (
222
+ ( parent . type === "MemberExpression" && parent . object === node )
223
+ || ( parent . type === "BinaryExpression" && parent . right === node )
224
+ )
225
+ )
226
+ return {
227
+ "type" : "Identifier" ,
228
+ "name" : renameVars [ node . name ]
229
+ } ;
230
+ // replace this.ctor with the actual ctor
231
+ if (
232
+ node . type === "MemberExpression"
233
+ && node . object . type === "ThisExpression"
234
+ && node . property . type === "Identifier" && node . property . name === "ctor"
235
+ )
236
+ return {
237
+ "type" : "Identifier" ,
238
+ "name" : "$root " + type . fullName
239
+ } ;
240
+ // replace types[N] with the field's actual type
241
+ if (
242
+ node . type === "MemberExpression"
243
+ && node . object . type === "Identifier" && node . object . name === "types"
244
+ && node . property . type === "Literal"
245
+ )
246
+ return {
247
+ "type" : "Identifier" ,
248
+ "name" : "$root" + type . fieldsArray [ node . property . value ] . resolvedType . fullName
249
+ } ;
250
+ return undefined ;
251
+ }
252
+ } ) ;
253
+ code = escodegen . generate ( ast , {
254
+ format : {
255
+ newline : "\n" ,
256
+ quotes : "double"
257
+ }
258
+ } ) ;
215
259
216
260
if ( config . beautify )
217
261
code = beautifyCode ( code ) ;
0 commit comments