/[jscoverage]/trunk/instrument-js.c
ViewVC logotype

Diff of /trunk/instrument-js.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2 by siliconforks, Wed Aug 1 13:51:53 2007 UTC revision 352 by siliconforks, Fri Oct 24 16:18:18 2008 UTC
# Line 1  Line 1 
1  /*  /*
2      instrument-js.c - JavaScript instrumentation routines      instrument-js.c - JavaScript instrumentation routines
3      Copyright (C) 2007 siliconforks.com      Copyright (C) 2007, 2008 siliconforks.com
4    
5      This program is free software; you can redistribute it and/or modify      This program is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published by      it under the terms of the GNU General Public License as published by
# Line 17  Line 17 
17      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */  */
19    
20    #include <config.h>
21    
22  #include "instrument-js.h"  #include "instrument-js.h"
23    
24  #include <assert.h>  #include <assert.h>
# Line 24  Line 26 
26  #include <string.h>  #include <string.h>
27    
28  #include <jsapi.h>  #include <jsapi.h>
29    #include <jsarena.h>
30  #include <jsatom.h>  #include <jsatom.h>
31    #include <jsemit.h>
32    #include <jsexn.h>
33  #include <jsfun.h>  #include <jsfun.h>
34  #include <jsinterp.h>  #include <jsinterp.h>
35    #include <jsiter.h>
36  #include <jsparse.h>  #include <jsparse.h>
37  #include <jsregexp.h>  #include <jsregexp.h>
38  #include <jsscope.h>  #include <jsscope.h>
39  #include <jsstr.h>  #include <jsstr.h>
40    
41    #include "encoding.h"
42    #include "global.h"
43    #include "highlight.h"
44    #include "resource-manager.h"
45  #include "util.h"  #include "util.h"
46    
47    struct IfDirective {
48      const jschar * condition_start;
49      const jschar * condition_end;
50      uint16_t start_line;
51      uint16_t end_line;
52      struct IfDirective * next;
53    };
54    
55    static bool * exclusive_directives = NULL;
56    
57  static JSRuntime * runtime = NULL;  static JSRuntime * runtime = NULL;
58  static JSContext * context = NULL;  static JSContext * context = NULL;
59  static JSObject * global = NULL;  static JSObject * global = NULL;
60    static JSVersion js_version = JSVERSION_ECMA_3;
61    
62  /*  /*
63  JSParseNode objects store line numbers starting from 1.  JSParseNode objects store line numbers starting from 1.
# Line 44  Line 65 
65  */  */
66  static const char * file_id = NULL;  static const char * file_id = NULL;
67  static char * lines = NULL;  static char * lines = NULL;
68    static uint16_t num_lines = 0;
69    
70    void jscoverage_set_js_version(const char * version) {
71      js_version = atoi(version);
72    }
73    
74  void jscoverage_init(void) {  void jscoverage_init(void) {
75    runtime = JS_NewRuntime(8L * 1024L * 1024L);    runtime = JS_NewRuntime(8L * 1024L * 1024L);
# Line 56  Line 82 
82      fatal("cannot create context");      fatal("cannot create context");
83    }    }
84    
85      JS_SetVersion(context, js_version);
86    
87    global = JS_NewObject(context, NULL, NULL, NULL);    global = JS_NewObject(context, NULL, NULL, NULL);
88    if (global == NULL) {    if (global == NULL) {
89      fatal("cannot create global object");      fatal("cannot create global object");
# Line 71  Line 99 
99    JS_DestroyRuntime(runtime);    JS_DestroyRuntime(runtime);
100  }  }
101    
102  static void print_string(JSString * s, FILE * f) {  static void print_javascript(const jschar * characters, size_t num_characters, Stream * f) {
103    for (int i = 0; i < s->length; i++) {    for (size_t i = 0; i < num_characters; i++) {
104      char c = s->chars[i];      jschar c = characters[i];
105      fputc(c, f);      /*
106        XXX does not handle no-break space, other unicode "space separator"
107        */
108        switch (c) {
109        case 0x9:
110        case 0xB:
111        case 0xC:
112          Stream_write_char(f, c);
113          break;
114        default:
115          if (32 <= c && c <= 126) {
116            Stream_write_char(f, c);
117          }
118          else {
119            Stream_printf(f, "\\u%04x", c);
120          }
121          break;
122        }
123      }
124    }
125    
126    static void print_string(JSString * s, Stream * f) {
127      size_t length = JSSTRING_LENGTH(s);
128      jschar * characters = JSSTRING_CHARS(s);
129      for (size_t i = 0; i < length; i++) {
130        jschar c = characters[i];
131        if (32 <= c && c <= 126) {
132          switch (c) {
133          case '"':
134            Stream_write_string(f, "\\\"");
135            break;
136    /*
137          case '\'':
138            Stream_write_string(f, "\\'");
139            break;
140    */
141          case '\\':
142            Stream_write_string(f, "\\\\");
143            break;
144          default:
145            Stream_write_char(f, c);
146            break;
147          }
148        }
149        else {
150          switch (c) {
151          case 0x8:
152            Stream_write_string(f, "\\b");
153            break;
154          case 0x9:
155            Stream_write_string(f, "\\t");
156            break;
157          case 0xa:
158            Stream_write_string(f, "\\n");
159            break;
160          /* IE doesn't support this */
161          /*
162          case 0xb:
163            Stream_write_string(f, "\\v");
164            break;
165          */
166          case 0xc:
167            Stream_write_string(f, "\\f");
168            break;
169          case 0xd:
170            Stream_write_string(f, "\\r");
171            break;
172          default:
173            Stream_printf(f, "\\u%04x", c);
174            break;
175          }
176        }
177    }    }
178  }  }
179    
180  static void print_string_atom(JSAtom * atom, FILE * f) {  static void print_string_atom(JSAtom * atom, Stream * f) {
181    assert(ATOM_IS_STRING(atom));    assert(ATOM_IS_STRING(atom));
182    JSString * s = ATOM_TO_STRING(atom);    JSString * s = ATOM_TO_STRING(atom);
183    print_string(s, f);    print_string(s, f);
184  }  }
185    
186  static void print_string_jsval(jsval value, FILE * f) {  static void print_regex(jsval value, Stream * f) {
187    assert(JSVAL_IS_STRING(value));    assert(JSVAL_IS_STRING(value));
188    JSString * s = JSVAL_TO_STRING(value);    JSString * s = JSVAL_TO_STRING(value);
189    print_string(s, f);    size_t length = JSSTRING_LENGTH(s);
190      jschar * characters = JSSTRING_CHARS(s);
191      for (size_t i = 0; i < length; i++) {
192        jschar c = characters[i];
193        if (32 <= c && c <= 126) {
194          Stream_write_char(f, c);
195        }
196        else {
197          Stream_printf(f, "\\u%04x", c);
198        }
199      }
200  }  }
201    
202  static void print_quoted_string_atom(JSAtom * atom, FILE * f) {  static void print_quoted_string_atom(JSAtom * atom, Stream * f) {
203    assert(ATOM_IS_STRING(atom));    assert(ATOM_IS_STRING(atom));
204    JSString * s = ATOM_TO_STRING(atom);    JSString * s = ATOM_TO_STRING(atom);
205    JSString * quoted = js_QuoteString(context, s, '"');    Stream_write_char(f, '"');
206    print_string(quoted, f);    print_string(s, f);
207      Stream_write_char(f, '"');
208  }  }
209    
210  static const char * get_op(uint8 op) {  static const char * get_op(uint8 op) {
211    switch(op) {    switch(op) {
212      case JSOP_OR:
213        return "||";
214      case JSOP_AND:
215        return "&&";
216    case JSOP_BITOR:    case JSOP_BITOR:
217      return "|";      return "|";
218    case JSOP_BITXOR:    case JSOP_BITXOR:
# Line 109  Line 223 
223      return "==";      return "==";
224    case JSOP_NE:    case JSOP_NE:
225      return "!=";      return "!=";
226    case JSOP_NEW_EQ:    case JSOP_STRICTEQ:
227      return "===";      return "===";
228    case JSOP_NEW_NE:    case JSOP_STRICTNE:
229      return "!==";      return "!==";
230    case JSOP_LT:    case JSOP_LT:
231      return "<";      return "<";
# Line 142  Line 256 
256    }    }
257  }  }
258    
259  static void instrument_expression(JSParseNode * node, FILE * f);  static void instrument_expression(JSParseNode * node, Stream * f);
260  static void instrument_statement(JSParseNode * node, FILE * f, int indent);  static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if);
261    static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if);
262    
263    enum FunctionType {
264      FUNCTION_NORMAL,
265      FUNCTION_GETTER_OR_SETTER
266    };
267    
268    static void output_for_in(JSParseNode * node, Stream * f) {
269      assert(node->pn_type == TOK_FOR);
270      assert(node->pn_arity == PN_BINARY);
271      Stream_write_string(f, "for ");
272      if (node->pn_iflags & JSITER_FOREACH) {
273        Stream_write_string(f, "each ");
274      }
275      Stream_write_char(f, '(');
276      instrument_expression(node->pn_left, f);
277      Stream_write_char(f, ')');
278    }
279    
280  static void instrument_function(JSParseNode * node, FILE * f, int indent) {  static void instrument_function(JSParseNode * node, Stream * f, int indent, enum FunctionType type) {
281      assert(node->pn_arity == PN_FUNC);    assert(node->pn_type == TOK_FUNCTION);
282      assert(ATOM_IS_OBJECT(node->pn_funAtom));    assert(node->pn_arity == PN_FUNC);
283      JSObject * object = ATOM_TO_OBJECT(node->pn_funAtom);    JSObject * object = node->pn_funpob->object;
284      assert(JS_ObjectIsFunction(context, object));    assert(JS_ObjectIsFunction(context, object));
285      JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);    JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
286      assert(function);    assert(function);
287      assert(object == function->object);    assert(object == &function->object);
288      fprintf(f, "%*s", indent, "");    Stream_printf(f, "%*s", indent, "");
289      fprintf(f, "function");    if (type == FUNCTION_NORMAL) {
290        Stream_write_string(f, "function");
291      /* function name */    }
292      if (function->atom) {  
293        fputc(' ', f);    /* function name */
294        print_string_atom(function->atom, f);    if (function->atom) {
295      }      Stream_write_char(f, ' ');
296        print_string_atom(function->atom, f);
297      /* function parameters */    }
298      fprintf(f, "(");  
299      JSAtom ** params = xmalloc(function->nargs * sizeof(JSAtom *));    /*
300      for (int i = 0; i < function->nargs; i++) {    function parameters - see JS_DecompileFunction in jsapi.cpp, which calls
301        /* initialize to NULL for sanity check */    js_DecompileFunction in jsopcode.cpp
302        params[i] = NULL;    */
303      }    Stream_write_string(f, "(");
304      JSScope * scope = OBJ_SCOPE(object);    JSArenaPool pool;
305      for (JSScopeProperty * scope_property = SCOPE_LAST_PROP(scope); scope_property != NULL; scope_property = scope_property->parent) {    JS_INIT_ARENA_POOL(&pool, "instrument_function", 256, 1, &context->scriptStackQuota);
306        if (scope_property->getter != js_GetArgument) {    jsuword * local_names = NULL;
307          continue;    if (JS_GET_LOCAL_NAME_COUNT(function)) {
308        }      local_names = js_GetLocalNameArray(context, function, &pool);
309        assert(scope_property->flags & SPROP_HAS_SHORTID);      if (local_names == NULL) {
310        assert((uint16) scope_property->shortid < function->nargs);        fatal("out of memory");
       assert(JSID_IS_ATOM(scope_property->id));  
       params[(uint16) scope_property->shortid] = JSID_TO_ATOM(scope_property->id);  
311      }      }
312      for (int i = 0; i < function->nargs; i++) {    }
313        assert(params[i] != NULL);    for (int i = 0; i < function->nargs; i++) {
314        if (i > 0) {      if (i > 0) {
315          fprintf(f, ", ");        Stream_write_string(f, ", ");
316        }      }
317        if (ATOM_IS_STRING(params[i])) {      JSAtom * param = JS_LOCAL_NAME_TO_ATOM(local_names[i]);
318          print_string_atom(params[i], f);      if (param == NULL) {
319        }        fatal("unsupported parameter type for function: %s", file_id);
320      }      }
321      fprintf(f, ") {\n");      print_string_atom(param, f);
322      free(params);    }
323      JS_FinishArenaPool(&pool);
324      Stream_write_string(f, ") {\n");
325    
326      /* function body */    /* function body */
327      instrument_statement(node->pn_body, f, indent + 2);    if (function->flags & JSFUN_EXPR_CLOSURE) {
328        /* expression closure */
329        output_statement(node->pn_body, f, indent + 2, false);
330      }
331      else {
332        instrument_statement(node->pn_body, f, indent + 2, false);
333      }
334    
335      fprintf(f, "}\n");    Stream_write_string(f, "}\n");
336  }  }
337    
338  static void instrument_function_call(JSParseNode * node, FILE * f) {  static void instrument_function_call(JSParseNode * node, Stream * f) {
339    instrument_expression(node->pn_head, f);    JSParseNode * function_node = node->pn_head;
340    fputc('(', f);    if (function_node->pn_type == TOK_FUNCTION) {
341    for (struct JSParseNode * p = node->pn_head->pn_next; p != NULL; p = p->pn_next) {      JSObject * object = function_node->pn_funpob->object;
342        assert(JS_ObjectIsFunction(context, object));
343        JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
344        assert(function);
345        assert(object == &function->object);
346    
347        if (function_node->pn_flags & TCF_GENEXP_LAMBDA) {
348          /* it's a generator expression */
349          JSParseNode * lexical_scope_node = function_node->pn_body;
350          assert(lexical_scope_node->pn_type == TOK_LEXICALSCOPE);
351          assert(lexical_scope_node->pn_arity == PN_NAME);
352          JSParseNode * for_node = lexical_scope_node->pn_body;
353          assert(for_node->pn_type == TOK_FOR);
354          assert(for_node->pn_arity == PN_BINARY);
355          JSParseNode * if_node = NULL;
356          JSParseNode * semi_node;
357          switch (for_node->pn_right->pn_type) {
358          case TOK_SEMI:
359            semi_node = for_node->pn_right;
360            break;
361          case TOK_IF:
362            if_node = for_node->pn_right;
363            assert(if_node->pn_arity == PN_TERNARY);
364            semi_node = if_node->pn_kid2;
365            assert(semi_node->pn_type == TOK_SEMI);
366            break;
367          default:
368            abort();
369            break;
370          }
371          assert(semi_node->pn_arity == PN_UNARY);
372          JSParseNode * yield_node = semi_node->pn_kid;
373          assert(yield_node->pn_type == TOK_YIELD);
374          Stream_write_char(f, '(');
375          instrument_expression(yield_node->pn_kid, f);
376          Stream_write_char(f, ' ');
377          output_for_in(for_node, f);
378          if (if_node) {
379            Stream_write_string(f, " if (");
380            instrument_expression(if_node->pn_kid1, f);
381            Stream_write_char(f, ')');
382          }
383          Stream_write_char(f, ')');
384          return;
385        }
386        else {
387          Stream_write_char(f, '(');
388          instrument_expression(function_node, f);
389          Stream_write_char(f, ')');
390        }
391      }
392      else {
393        instrument_expression(function_node, f);
394      }
395      Stream_write_char(f, '(');
396      for (struct JSParseNode * p = function_node->pn_next; p != NULL; p = p->pn_next) {
397      if (p != node->pn_head->pn_next) {      if (p != node->pn_head->pn_next) {
398        fprintf(f, ", ");        Stream_write_string(f, ", ");
399      }      }
400      instrument_expression(p, f);      instrument_expression(p, f);
401    }    }
402    fputc(')', f);    Stream_write_char(f, ')');
403    }
404    
405    static void instrument_declarations(JSParseNode * list, Stream * f) {
406      assert(list->pn_arity == PN_LIST);
407      for (JSParseNode * p = list->pn_head; p != NULL; p = p->pn_next) {
408        switch (p->pn_type) {
409        case TOK_NAME:
410          assert(p->pn_arity == PN_NAME);
411          if (p != list->pn_head) {
412            Stream_write_string(f, ", ");
413          }
414          print_string_atom(p->pn_atom, f);
415          if (p->pn_expr != NULL) {
416            Stream_write_string(f, " = ");
417            instrument_expression(p->pn_expr, f);
418          }
419          break;
420        case TOK_ASSIGN:
421        case TOK_RB:
422        case TOK_RC:
423          /* destructuring */
424          instrument_expression(p, f);
425          break;
426        default:
427          abort();
428          break;
429        }
430      }
431  }  }
432    
433  /*  /*
# Line 222  Line 443 
443  TOK_INSTANCEOF  binary  TOK_INSTANCEOF  binary
444  TOK_IN          binary  TOK_IN          binary
445  */  */
446  static void instrument_expression(JSParseNode * node, FILE * f) {  static void instrument_expression(JSParseNode * node, Stream * f) {
447    switch (node->pn_type) {    switch (node->pn_type) {
448    case TOK_FUNCTION:    case TOK_FUNCTION:
449      instrument_function(node, f, 0);      instrument_function(node, f, 0, FUNCTION_NORMAL);
450      break;      break;
451    case TOK_COMMA:    case TOK_COMMA:
452      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
453        if (p != node->pn_head) {        if (p != node->pn_head) {
454          fprintf(f, ", ");          Stream_write_string(f, ", ");
455        }        }
456        instrument_expression(p, f);        instrument_expression(p, f);
457      }      }
458      break;      break;
459    case TOK_ASSIGN:    case TOK_ASSIGN:
460      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
461      fputc(' ', f);      Stream_write_char(f, ' ');
462      switch (node->pn_op) {      switch (node->pn_op) {
463      case JSOP_ADD:      case JSOP_ADD:
464      case JSOP_SUB:      case JSOP_SUB:
# Line 250  Line 471 
471      case JSOP_BITOR:      case JSOP_BITOR:
472      case JSOP_BITXOR:      case JSOP_BITXOR:
473      case JSOP_DIV:      case JSOP_DIV:
474        fprintf(f, "%s", get_op(node->pn_op));        Stream_printf(f, "%s", get_op(node->pn_op));
475        break;        break;
476      default:      default:
477        /* do nothing - it must be a simple assignment */        /* do nothing - it must be a simple assignment */
478        break;        break;
479      }      }
480      fprintf(f, "= ");      Stream_write_string(f, "= ");
481      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
482      break;      break;
483    case TOK_HOOK:    case TOK_HOOK:
484      instrument_expression(node->pn_kid1, f);      instrument_expression(node->pn_kid1, f);
485      fprintf(f, "? ");      Stream_write_string(f, "? ");
486      instrument_expression(node->pn_kid2, f);      instrument_expression(node->pn_kid2, f);
487      fprintf(f, ": ");      Stream_write_string(f, ": ");
488      instrument_expression(node->pn_kid3, f);      instrument_expression(node->pn_kid3, f);
489      break;      break;
490    case TOK_OR:    case TOK_OR:
     instrument_expression(node->pn_left, f);  
     fprintf(f, " || ");  
     instrument_expression(node->pn_right, f);  
     break;  
491    case TOK_AND:    case TOK_AND:
     instrument_expression(node->pn_left, f);  
     fprintf(f, " && ");  
     instrument_expression(node->pn_right, f);  
     break;  
492    case TOK_BITOR:    case TOK_BITOR:
493    case TOK_BITXOR:    case TOK_BITXOR:
494    case TOK_BITAND:    case TOK_BITAND:
# Line 289  Line 502 
502      switch (node->pn_arity) {      switch (node->pn_arity) {
503      case PN_BINARY:      case PN_BINARY:
504        instrument_expression(node->pn_left, f);        instrument_expression(node->pn_left, f);
505        fprintf(f, " %s ", get_op(node->pn_op));        Stream_printf(f, " %s ", get_op(node->pn_op));
506        instrument_expression(node->pn_right, f);        instrument_expression(node->pn_right, f);
507        break;        break;
508      case PN_LIST:      case PN_LIST:
509        for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {        for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
510          if (p != node->pn_head) {          if (p != node->pn_head) {
511            fprintf(f, " %s ", get_op(node->pn_op));            Stream_printf(f, " %s ", get_op(node->pn_op));
512          }          }
513          instrument_expression(p, f);          instrument_expression(p, f);
514        }        }
# Line 307  Line 520 
520    case TOK_UNARYOP:    case TOK_UNARYOP:
521      switch (node->pn_op) {      switch (node->pn_op) {
522      case JSOP_NEG:      case JSOP_NEG:
523        fputc('-', f);        Stream_write_char(f, '-');
524        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
525        break;        break;
526      case JSOP_POS:      case JSOP_POS:
527        fputc('+', f);        Stream_write_char(f, '+');
528        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
529        break;        break;
530      case JSOP_NOT:      case JSOP_NOT:
531        fputc('!', f);        Stream_write_char(f, '!');
532        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
533        break;        break;
534      case JSOP_BITNOT:      case JSOP_BITNOT:
535        fputc('~', f);        Stream_write_char(f, '~');
536        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
537        break;        break;
538      case JSOP_TYPEOF:      case JSOP_TYPEOF:
539        fprintf(f, "typeof ");        Stream_write_string(f, "typeof ");
540        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
541        break;        break;
542      case JSOP_VOID:      case JSOP_VOID:
543        fprintf(f, "void ");        Stream_write_string(f, "void ");
544        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
545        break;        break;
546      default:      default:
# Line 344  Line 557 
557      case JSOP_INCNAME:      case JSOP_INCNAME:
558      case JSOP_INCPROP:      case JSOP_INCPROP:
559      case JSOP_INCELEM:      case JSOP_INCELEM:
560        fprintf(f, "++");        Stream_write_string(f, "++");
561        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
562        break;        break;
563      case JSOP_DECNAME:      case JSOP_DECNAME:
564      case JSOP_DECPROP:      case JSOP_DECPROP:
565      case JSOP_DECELEM:      case JSOP_DECELEM:
566        fprintf(f, "--");        Stream_write_string(f, "--");
567        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
568        break;        break;
569      case JSOP_NAMEINC:      case JSOP_NAMEINC:
570      case JSOP_PROPINC:      case JSOP_PROPINC:
571      case JSOP_ELEMINC:      case JSOP_ELEMINC:
572        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
573        fprintf(f, "++");        Stream_write_string(f, "++");
574        break;        break;
575      case JSOP_NAMEDEC:      case JSOP_NAMEDEC:
576      case JSOP_PROPDEC:      case JSOP_PROPDEC:
577      case JSOP_ELEMDEC:      case JSOP_ELEMDEC:
578        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
579        fprintf(f, "--");        Stream_write_string(f, "--");
580        break;        break;
581      default:      default:
582        abort();        abort();
# Line 371  Line 584 
584      }      }
585      break;      break;
586    case TOK_NEW:    case TOK_NEW:
587      fprintf(f, "new ");      Stream_write_string(f, "new ");
588      instrument_function_call(node, f);      instrument_function_call(node, f);
589      break;      break;
590    case TOK_DELETE:    case TOK_DELETE:
591      fprintf(f, "delete ");      Stream_write_string(f, "delete ");
592      instrument_expression(node->pn_kid, f);      instrument_expression(node->pn_kid, f);
593      break;      break;
594    case TOK_DOT:    case TOK_DOT:
# Line 385  Line 598 
598      the dot syntax.      the dot syntax.
599      */      */
600      instrument_expression(node->pn_expr, f);      instrument_expression(node->pn_expr, f);
601      /*      assert(ATOM_IS_STRING(node->pn_atom));
602      fputc('.', f);      {
603      print_string_atom(node->pn_atom, f);        JSString * s = ATOM_TO_STRING(node->pn_atom);
604      */        bool must_quote;
605      fputc('[', f);        if (JSSTRING_LENGTH(s) == 0) {
606      print_quoted_string_atom(node->pn_atom, f);          must_quote = true;
607      fputc(']', f);        }
608          else if (js_CheckKeyword(JSSTRING_CHARS(s), JSSTRING_LENGTH(s)) != TOK_EOF) {
609            must_quote = true;
610          }
611          else if (! js_IsIdentifier(s)) {
612            must_quote = true;
613          }
614          else {
615            must_quote = false;
616          }
617          if (must_quote) {
618            Stream_write_char(f, '[');
619            print_quoted_string_atom(node->pn_atom, f);
620            Stream_write_char(f, ']');
621          }
622          else {
623            Stream_write_char(f, '.');
624            print_string_atom(node->pn_atom, f);
625          }
626        }
627      break;      break;
628    case TOK_LB:    case TOK_LB:
629      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
630      fputc('[', f);      Stream_write_char(f, '[');
631      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
632      fputc(']', f);      Stream_write_char(f, ']');
633      break;      break;
634    case TOK_LP:    case TOK_LP:
635      instrument_function_call(node, f);      instrument_function_call(node, f);
636      break;      break;
637    case TOK_RB:    case TOK_RB:
638      fputc('[', f);      Stream_write_char(f, '[');
639      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
640        if (p != node->pn_head) {        if (p != node->pn_head) {
641          fprintf(f, ", ");          Stream_write_string(f, ", ");
642        }        }
643        /* TOK_COMMA is a special case: a hole in the array */        /* TOK_COMMA is a special case: a hole in the array */
644        if (p->pn_type != TOK_COMMA) {        if (p->pn_type != TOK_COMMA) {
# Line 414  Line 646 
646        }        }
647      }      }
648      if (node->pn_extra == PNX_ENDCOMMA) {      if (node->pn_extra == PNX_ENDCOMMA) {
649        fputc(',', f);        Stream_write_char(f, ',');
650      }      }
651      fputc(']', f);      Stream_write_char(f, ']');
652      break;      break;
653    case TOK_RC:    case TOK_RC:
654      fputc('{', f);      Stream_write_char(f, '{');
655      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_head; p != NULL; p = p->pn_next) {
656        assert(p->pn_type == TOK_COLON);        assert(p->pn_type == TOK_COLON);
657        if (p != node->pn_head) {        if (p != node->pn_head) {
658          fprintf(f, ", ");          Stream_write_string(f, ", ");
659          }
660    
661          /* check whether this is a getter or setter */
662          switch (p->pn_op) {
663          case JSOP_GETTER:
664          case JSOP_SETTER:
665            if (p->pn_op == JSOP_GETTER) {
666              Stream_write_string(f, "get ");
667            }
668            else {
669              Stream_write_string(f, "set ");
670            }
671            instrument_expression(p->pn_left, f);
672            if (p->pn_right->pn_type != TOK_FUNCTION) {
673              fatal("parse error: expected function");
674            }
675            instrument_function(p->pn_right, f, 0, FUNCTION_GETTER_OR_SETTER);
676            break;
677          default:
678            instrument_expression(p->pn_left, f);
679            Stream_write_string(f, ": ");
680            instrument_expression(p->pn_right, f);
681            break;
682        }        }
       instrument_expression(p->pn_left, f);  
       fprintf(f, ": ");  
       instrument_expression(p->pn_right, f);  
683      }      }
684      fputc('}', f);      Stream_write_char(f, '}');
685      break;      break;
686    case TOK_RP:    case TOK_RP:
687      fputc('(', f);      Stream_write_char(f, '(');
688      instrument_expression(node->pn_kid, f);      instrument_expression(node->pn_kid, f);
689      fputc(')', f);      Stream_write_char(f, ')');
690      break;      break;
691    case TOK_NAME:    case TOK_NAME:
692      print_string_atom(node->pn_atom, f);      print_string_atom(node->pn_atom, f);
# Line 442  Line 694 
694    case TOK_STRING:    case TOK_STRING:
695      print_quoted_string_atom(node->pn_atom, f);      print_quoted_string_atom(node->pn_atom, f);
696      break;      break;
697    case TOK_OBJECT:    case TOK_REGEXP:
698      switch (node->pn_op) {      assert(node->pn_op == JSOP_REGEXP);
699      case JSOP_OBJECT:      {
700        /* I assume this is JSOP_REGEXP */        JSObject * object = node->pn_pob->object;
701        abort();        jsval result;
702        break;        js_regexp_toString(context, object, &result);
703      case JSOP_REGEXP:        print_regex(result, f);
       assert(ATOM_IS_OBJECT(node->pn_atom));  
       {  
         JSObject * object = ATOM_TO_OBJECT(node->pn_atom);  
         jsval result;  
         js_regexp_toString(context, object, 0, NULL, &result);  
         print_string_jsval(result, f);  
       }  
       break;  
     default:  
       abort();  
       break;  
704      }      }
705      break;      break;
706    case TOK_NUMBER:    case TOK_NUMBER:
# Line 470  Line 711 
711      To keep the output simple, special-case zero.      To keep the output simple, special-case zero.
712      */      */
713      if (node->pn_dval == 0.0) {      if (node->pn_dval == 0.0) {
714        fprintf(f, "0");        Stream_write_string(f, "0");
715      }      }
716      else {      else {
717        fprintf(f, "%.15g", node->pn_dval);        Stream_printf(f, "%.15g", node->pn_dval);
718      }      }
719      break;      break;
720    case TOK_PRIMARY:    case TOK_PRIMARY:
721      switch (node->pn_op) {      switch (node->pn_op) {
722      case JSOP_TRUE:      case JSOP_TRUE:
723        fprintf(f, "true");        Stream_write_string(f, "true");
724        break;        break;
725      case JSOP_FALSE:      case JSOP_FALSE:
726        fprintf(f, "false");        Stream_write_string(f, "false");
727        break;        break;
728      case JSOP_NULL:      case JSOP_NULL:
729        fprintf(f, "null");        Stream_write_string(f, "null");
730        break;        break;
731      case JSOP_THIS:      case JSOP_THIS:
732        fprintf(f, "this");        Stream_write_string(f, "this");
733        break;        break;
734      /* jsscan.h mentions `super' ??? */      /* jsscan.h mentions `super' ??? */
735      default:      default:
# Line 497  Line 738 
738      break;      break;
739    case TOK_INSTANCEOF:    case TOK_INSTANCEOF:
740      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
741      fprintf(f, " instanceof ");      Stream_write_string(f, " instanceof ");
742      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
743      break;      break;
744    case TOK_IN:    case TOK_IN:
745      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
746      fprintf(f, " in ");      Stream_write_string(f, " in ");
747      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
748      break;      break;
749      case TOK_LEXICALSCOPE:
750        assert(node->pn_arity == PN_NAME);
751        assert(node->pn_expr->pn_type == TOK_LET);
752        assert(node->pn_expr->pn_arity == PN_BINARY);
753        Stream_write_string(f, "let(");
754        assert(node->pn_expr->pn_left->pn_type == TOK_LP);
755        assert(node->pn_expr->pn_left->pn_arity == PN_LIST);
756        instrument_declarations(node->pn_expr->pn_left, f);
757        Stream_write_string(f, ") ");
758        instrument_expression(node->pn_expr->pn_right, f);
759        break;
760      case TOK_YIELD:
761        assert(node->pn_arity == PN_UNARY);
762        Stream_write_string(f, "yield ");
763        instrument_expression(node->pn_kid, f);
764        break;
765      case TOK_ARRAYCOMP:
766        assert(node->pn_arity == PN_LIST);
767        {
768          JSParseNode * block_node;
769          switch (node->pn_count) {
770          case 1:
771            block_node = node->pn_head;
772            break;
773          case 2:
774            block_node = node->pn_head->pn_next;
775            break;
776          default:
777            abort();
778            break;
779          }
780          assert(block_node->pn_type == TOK_LEXICALSCOPE);
781          assert(block_node->pn_arity == PN_NAME);
782          JSParseNode * for_node = block_node->pn_expr;
783          assert(for_node->pn_type == TOK_FOR);
784          assert(for_node->pn_arity == PN_BINARY);
785          JSParseNode * if_node = NULL;
786          JSParseNode * push_node;
787          switch (for_node->pn_right->pn_type) {
788          case TOK_ARRAYPUSH:
789            push_node = for_node->pn_right;
790            assert(push_node->pn_arity == PN_UNARY);
791            break;
792          case TOK_IF:
793            if_node = for_node->pn_right;
794            assert(if_node->pn_arity == PN_TERNARY);
795            push_node = if_node->pn_kid2;
796            break;
797          default:
798            abort();
799            break;
800          }
801          Stream_write_char(f, '[');
802          instrument_expression(push_node->pn_kid, f);
803          Stream_write_char(f, ' ');
804          output_for_in(for_node, f);
805          if (if_node) {
806            Stream_write_string(f, " if (");
807            instrument_expression(if_node->pn_kid1, f);
808            Stream_write_char(f, ')');
809          }
810          Stream_write_char(f, ']');
811        }
812        break;
813      case TOK_VAR:
814        assert(node->pn_arity == PN_LIST);
815        Stream_write_string(f, "var ");
816        instrument_declarations(node, f);
817        break;
818      case TOK_LET:
819        assert(node->pn_arity == PN_LIST);
820        Stream_write_string(f, "let ");
821        instrument_declarations(node, f);
822        break;
823    default:    default:
824      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);
825    }    }
826  }  }
827    
828  static void instrument_var_statement(JSParseNode * node, FILE * f, int indent) {  static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
   assert(node->pn_arity == PN_LIST);  
   fprintf(f, "%*s", indent, "");  
   fprintf(f, "var ");  
   for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {  
     assert(p->pn_type == TOK_NAME);  
     assert(p->pn_arity == PN_NAME);  
     if (p != node->pn_head) {  
       fprintf(f, ", ");  
     }  
     print_string_atom(p->pn_atom, f);  
     if (p->pn_expr != NULL) {  
       fprintf(f, " = ");  
       instrument_expression(p->pn_expr, f);  
     }  
   }  
 }  
   
 static void output_statement(JSParseNode * node, FILE * f, int indent) {  
829    switch (node->pn_type) {    switch (node->pn_type) {
830    case TOK_FUNCTION:    case TOK_FUNCTION:
831      instrument_function(node, f, indent);      instrument_function(node, f, indent, FUNCTION_NORMAL);
832      break;      break;
833    case TOK_LC:    case TOK_LC:
834      assert(node->pn_arity == PN_LIST);      assert(node->pn_arity == PN_LIST);
835  /*  /*
836      fprintf(f, "{\n");      Stream_write_string(f, "{\n");
837  */  */
838      for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {      for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {
839        instrument_statement(p, f, indent);        instrument_statement(p, f, indent, false);
840      }      }
841  /*  /*
842      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
843      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
844  */  */
845      break;      break;
846    case TOK_IF:    case TOK_IF:
847      {
848      assert(node->pn_arity == PN_TERNARY);      assert(node->pn_arity == PN_TERNARY);
849      fprintf(f, "%*s", indent, "");  
850      fprintf(f, "if (");      uint16_t line = node->pn_pos.begin.lineno;
851        if (! is_jscoverage_if) {
852          if (line > num_lines) {
853            fatal("%s: script contains more than 65,535 lines", file_id);
854          }
855          if (line >= 2 && exclusive_directives[line - 2]) {
856            is_jscoverage_if = true;
857          }
858        }
859    
860        Stream_printf(f, "%*s", indent, "");
861        Stream_write_string(f, "if (");
862      instrument_expression(node->pn_kid1, f);      instrument_expression(node->pn_kid1, f);
863      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
864      instrument_statement(node->pn_kid2, f, indent + 2);      if (is_jscoverage_if && node->pn_kid3) {
865      fprintf(f, "%*s", indent, "");        uint16_t else_start = node->pn_kid3->pn_pos.begin.lineno;
866      fprintf(f, "}\n");        uint16_t else_end = node->pn_kid3->pn_pos.end.lineno + 1;
867      if (node->pn_kid3) {        Stream_printf(f, "%*s", indent + 2, "");
868        fprintf(f, "%*s", indent, "");        Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, else_start, else_end);
869        fprintf(f, "else {\n");      }
870        instrument_statement(node->pn_kid3, f, indent + 2);      instrument_statement(node->pn_kid2, f, indent + 2, false);
871        fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
872        fprintf(f, "}\n");      Stream_write_string(f, "}\n");
873    
874        if (node->pn_kid3 || is_jscoverage_if) {
875          Stream_printf(f, "%*s", indent, "");
876          Stream_write_string(f, "else {\n");
877    
878          if (is_jscoverage_if) {
879            uint16_t if_start = node->pn_kid2->pn_pos.begin.lineno + 1;
880            uint16_t if_end = node->pn_kid2->pn_pos.end.lineno + 1;
881            Stream_printf(f, "%*s", indent + 2, "");
882            Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_start, if_end);
883          }
884    
885          if (node->pn_kid3) {
886            instrument_statement(node->pn_kid3, f, indent + 2, is_jscoverage_if);
887          }
888    
889          Stream_printf(f, "%*s", indent, "");
890          Stream_write_string(f, "}\n");
891      }      }
892    
893      break;      break;
894      }
895    case TOK_SWITCH:    case TOK_SWITCH:
896      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
897      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
898      fprintf(f, "switch (");      Stream_write_string(f, "switch (");
899      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
900      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
901      for (struct JSParseNode * p = node->pn_right->pn_head; p != NULL; p = p->pn_next) {      {
902        fprintf(f, "%*s", indent, "");        JSParseNode * list = node->pn_right;
903        switch (p->pn_type) {        if (list->pn_type == TOK_LEXICALSCOPE) {
904        case TOK_CASE:          list = list->pn_expr;
905          fprintf(f, "case ");        }
906          instrument_expression(p->pn_left, f);        for (struct JSParseNode * p = list->pn_head; p != NULL; p = p->pn_next) {
907          fprintf(f, ":\n");          Stream_printf(f, "%*s", indent, "");
908          break;          switch (p->pn_type) {
909        case TOK_DEFAULT:          case TOK_CASE:
910          fprintf(f, "default:\n");            Stream_write_string(f, "case ");
911          break;            instrument_expression(p->pn_left, f);
912        default:            Stream_write_string(f, ":\n");
913          abort();            break;
914          break;          case TOK_DEFAULT:
915              Stream_write_string(f, "default:\n");
916              break;
917            default:
918              abort();
919              break;
920            }
921            instrument_statement(p->pn_right, f, indent + 2, false);
922        }        }
       instrument_statement(p->pn_right, f, indent + 2);  
923      }      }
924      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
925      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
926      break;      break;
927    case TOK_CASE:    case TOK_CASE:
928    case TOK_DEFAULT:    case TOK_DEFAULT:
# Line 595  Line 930 
930      break;      break;
931    case TOK_WHILE:    case TOK_WHILE:
932      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
933      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
934      fprintf(f, "while (");      Stream_write_string(f, "while (");
935      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
936      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
937      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
938      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
939      break;      break;
940    case TOK_DO:    case TOK_DO:
941      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
942      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
943      fprintf(f, "do {\n");      Stream_write_string(f, "do {\n");
944      instrument_statement(node->pn_left, f, indent + 2);      instrument_statement(node->pn_left, f, indent + 2, false);
945      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
946      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
947      fprintf(f, "while (");      Stream_write_string(f, "while (");
948      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
949      fprintf(f, ");\n");      Stream_write_string(f, ");\n");
950      break;      break;
951    case TOK_FOR:    case TOK_FOR:
952      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
953      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
     fprintf(f, "for (");  
954      switch (node->pn_left->pn_type) {      switch (node->pn_left->pn_type) {
955      case TOK_IN:      case TOK_IN:
956        /* for/in */        /* for/in */
957        assert(node->pn_left->pn_arity == PN_BINARY);        assert(node->pn_left->pn_arity == PN_BINARY);
958        switch (node->pn_left->pn_left->pn_type) {        output_for_in(node, f);
       case TOK_VAR:  
         instrument_var_statement(node->pn_left->pn_left, f, 0);  
         break;  
       case TOK_NAME:  
         instrument_expression(node->pn_left->pn_left, f);  
         break;  
       default:  
         /* this is undocumented: for (x.value in y) */  
         instrument_expression(node->pn_left->pn_left, f);  
         break;  
 /*  
       default:  
         fprintf(stderr, "unexpected node type: %d\n", node->pn_left->pn_left->pn_type);  
         abort();  
         break;  
 */  
       }  
       fprintf(f, " in ");  
       instrument_expression(node->pn_left->pn_right, f);  
959        break;        break;
960      case TOK_RESERVED:      case TOK_RESERVED:
961        /* for (;;) */        /* for (;;) */
962        assert(node->pn_left->pn_arity == PN_TERNARY);        assert(node->pn_left->pn_arity == PN_TERNARY);
963          Stream_write_string(f, "for (");
964        if (node->pn_left->pn_kid1) {        if (node->pn_left->pn_kid1) {
965          if (node->pn_left->pn_kid1->pn_type == TOK_VAR) {          instrument_expression(node->pn_left->pn_kid1, f);
           instrument_var_statement(node->pn_left->pn_kid1, f, 0);  
         }  
         else {  
           instrument_expression(node->pn_left->pn_kid1, f);  
         }  
966        }        }
967        fprintf(f, ";");        Stream_write_string(f, ";");
968        if (node->pn_left->pn_kid2) {        if (node->pn_left->pn_kid2) {
969          fputc(' ', f);          Stream_write_char(f, ' ');
970          instrument_expression(node->pn_left->pn_kid2, f);          instrument_expression(node->pn_left->pn_kid2, f);
971        }        }
972        fprintf(f, ";");        Stream_write_string(f, ";");
973        if (node->pn_left->pn_kid3) {        if (node->pn_left->pn_kid3) {
974          fputc(' ', f);          Stream_write_char(f, ' ');
975          instrument_expression(node->pn_left->pn_kid3, f);          instrument_expression(node->pn_left->pn_kid3, f);
976        }        }
977          Stream_write_char(f, ')');
978        break;        break;
979      default:      default:
980        abort();        abort();
981        break;        break;
982      }      }
983      fprintf(f, ") {\n");      Stream_write_string(f, " {\n");
984      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
985      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
986      break;      break;
987    case TOK_THROW:    case TOK_THROW:
988      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
989      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
990      fprintf(f, "throw ");      Stream_write_string(f, "throw ");
991      instrument_expression(node->pn_u.unary.kid, f);      instrument_expression(node->pn_u.unary.kid, f);
992      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
993      break;      break;
994    case TOK_TRY:    case TOK_TRY:
995      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
996      fprintf(f, "try {\n");      Stream_write_string(f, "try {\n");
997      instrument_statement(node->pn_kid1, f, indent + 2);      instrument_statement(node->pn_kid1, f, indent + 2, false);
998      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
999      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
1000      {      if (node->pn_kid2) {
1001        for (JSParseNode * catch = node->pn_kid2; catch != NULL; catch = catch->pn_kid2) {        assert(node->pn_kid2->pn_type == TOK_RESERVED);
1002          for (JSParseNode * scope = node->pn_kid2->pn_head; scope != NULL; scope = scope->pn_next) {
1003            assert(scope->pn_type == TOK_LEXICALSCOPE);
1004            JSParseNode * catch = scope->pn_expr;
1005          assert(catch->pn_type == TOK_CATCH);          assert(catch->pn_type == TOK_CATCH);
1006          fprintf(f, "%*s", indent, "");          Stream_printf(f, "%*s", indent, "");
1007          fprintf(f, "catch (");          Stream_write_string(f, "catch (");
1008            /* this may not be a name - destructuring assignment */
1009            /*
1010          assert(catch->pn_kid1->pn_arity == PN_NAME);          assert(catch->pn_kid1->pn_arity == PN_NAME);
1011          print_string_atom(catch->pn_kid1->pn_atom, f);          print_string_atom(catch->pn_kid1->pn_atom, f);
1012          if (catch->pn_kid1->pn_expr) {          */
1013            fprintf(f, " if ");          instrument_expression(catch->pn_kid1, f);
1014            instrument_expression(catch->pn_kid1->pn_expr, f);          if (catch->pn_kid2) {
1015          }            Stream_write_string(f, " if ");
1016          fprintf(f, ") {\n");            instrument_expression(catch->pn_kid2, f);
1017          instrument_statement(catch->pn_kid3, f, indent + 2);          }
1018          fprintf(f, "%*s", indent, "");          Stream_write_string(f, ") {\n");
1019          fprintf(f, "}\n");          instrument_statement(catch->pn_kid3, f, indent + 2, false);
1020            Stream_printf(f, "%*s", indent, "");
1021            Stream_write_string(f, "}\n");
1022        }        }
1023      }      }
1024      if (node->pn_kid3) {      if (node->pn_kid3) {
1025        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
1026        fprintf(f, "finally {\n");        Stream_write_string(f, "finally {\n");
1027        instrument_statement(node->pn_kid3, f, indent + 2);        instrument_statement(node->pn_kid3, f, indent + 2, false);
1028        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
1029        fprintf(f, "}\n");        Stream_write_string(f, "}\n");
1030      }      }
1031      break;      break;
1032    case TOK_CATCH:    case TOK_CATCH:
# Line 716  Line 1035 
1035    case TOK_BREAK:    case TOK_BREAK:
1036    case TOK_CONTINUE:    case TOK_CONTINUE:
1037      assert(node->pn_arity == PN_NAME || node->pn_arity == PN_NULLARY);      assert(node->pn_arity == PN_NAME || node->pn_arity == PN_NULLARY);
1038      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1039      fputs(node->pn_type == TOK_BREAK? "break": "continue", f);      Stream_write_string(f, node->pn_type == TOK_BREAK? "break": "continue");
1040      JSAtom * atom = node->pn_u.name.atom;      JSAtom * atom = node->pn_u.name.atom;
1041      if (atom != NULL) {      if (atom != NULL) {
1042        fputc(' ', f);        Stream_write_char(f, ' ');
1043        print_string_atom(node->pn_atom, f);        print_string_atom(node->pn_atom, f);
1044      }      }
1045      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
1046      break;      break;
1047    case TOK_WITH:    case TOK_WITH:
1048      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
1049      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1050      fprintf(f, "with (");      Stream_write_string(f, "with (");
1051      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
1052      fprintf(f, ") {\n");      Stream_write_string(f, ") {\n");
1053      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
1054      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1055      fprintf(f, "}\n");      Stream_write_string(f, "}\n");
1056      break;      break;
1057    case TOK_VAR:    case TOK_VAR:
1058      instrument_var_statement(node, f, indent);      Stream_printf(f, "%*s", indent, "");
1059      fprintf(f, ";\n");      instrument_expression(node, f);
1060        Stream_write_string(f, ";\n");
1061      break;      break;
1062    case TOK_RETURN:    case TOK_RETURN:
1063      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
1064      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1065      fprintf(f, "return");      Stream_write_string(f, "return");
1066      if (node->pn_kid != NULL) {      if (node->pn_kid != NULL) {
1067        fprintf(f, " ");        Stream_write_char(f, ' ');
1068        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
1069      }      }
1070      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
1071      break;      break;
1072    case TOK_SEMI:    case TOK_SEMI:
1073      assert(node->pn_arity == PN_UNARY);      assert(node->pn_arity == PN_UNARY);
1074      fprintf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1075      if (node->pn_kid != NULL) {      if (node->pn_kid != NULL) {
1076        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
1077      }      }
1078      fprintf(f, ";\n");      Stream_write_string(f, ";\n");
1079      break;      break;
1080    case TOK_COLON:    case TOK_COLON:
1081      assert(node->pn_arity == PN_NAME);      assert(node->pn_arity == PN_NAME);
# Line 763  Line 1083 
1083      This one is tricky: can't output instrumentation between the label and the      This one is tricky: can't output instrumentation between the label and the
1084      statement it's supposed to label ...      statement it's supposed to label ...
1085      */      */
1086      fprintf(f, "%*s", indent < 2? 0: indent - 2, "");      Stream_printf(f, "%*s", indent < 2? 0: indent - 2, "");
1087      print_string_atom(node->pn_atom, f);      print_string_atom(node->pn_atom, f);
1088      fprintf(f, ":\n");      Stream_write_string(f, ":\n");
1089      /*      /*
1090      ... use output_statement instead of instrument_statement.      ... use output_statement instead of instrument_statement.
1091      */      */
1092      output_statement(node->pn_expr, f, indent);      output_statement(node->pn_expr, f, indent, false);
1093        break;
1094      case TOK_LEXICALSCOPE:
1095        /* let statement */
1096        assert(node->pn_arity == PN_NAME);
1097        switch (node->pn_expr->pn_type) {
1098        case TOK_LET:
1099          /* let statement */
1100          assert(node->pn_expr->pn_arity == PN_BINARY);
1101          instrument_statement(node->pn_expr, f, indent, false);
1102          break;
1103        case TOK_LC:
1104          /* block */
1105          Stream_printf(f, "%*s", indent, "");
1106          Stream_write_string(f, "{\n");
1107          instrument_statement(node->pn_expr, f, indent + 2, false);
1108          Stream_printf(f, "%*s", indent, "");
1109          Stream_write_string(f, "}\n");
1110          break;
1111        case TOK_FOR:
1112          instrument_statement(node->pn_expr, f, indent, false);
1113          break;
1114        default:
1115          abort();
1116          break;
1117        }
1118        break;
1119      case TOK_LET:
1120        switch (node->pn_arity) {
1121        case PN_BINARY:
1122          /* let statement */
1123          Stream_printf(f, "%*s", indent, "");
1124          Stream_write_string(f, "let (");
1125          assert(node->pn_left->pn_type == TOK_LP);
1126          assert(node->pn_left->pn_arity == PN_LIST);
1127          instrument_declarations(node->pn_left, f);
1128          Stream_write_string(f, ") {\n");
1129          instrument_statement(node->pn_right, f, indent + 2, false);
1130          Stream_printf(f, "%*s", indent, "");
1131          Stream_write_string(f, "}\n");
1132          break;
1133        case PN_LIST:
1134          /* let definition */
1135          Stream_printf(f, "%*s", indent, "");
1136          instrument_expression(node, f);
1137          Stream_write_string(f, ";\n");
1138          break;
1139        default:
1140          abort();
1141          break;
1142        }
1143        break;
1144      case TOK_DEBUGGER:
1145        Stream_printf(f, "%*s", indent, "");
1146        Stream_write_string(f, "debugger;\n");
1147      break;      break;
1148    default:    default:
1149      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);
# Line 781  Line 1155 
1155  TOK_FUNCTION is handled as a statement and as an expression.  TOK_FUNCTION is handled as a statement and as an expression.
1156  TOK_EXPORT, TOK_IMPORT are not handled.  TOK_EXPORT, TOK_IMPORT are not handled.
1157  */  */
1158  static void instrument_statement(JSParseNode * node, FILE * f, int indent) {  static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
1159    if (node->pn_type != TOK_LC) {    if (node->pn_type != TOK_LC && node->pn_type != TOK_LEXICALSCOPE) {
1160      int line = node->pn_pos.begin.lineno;      uint16_t line = node->pn_pos.begin.lineno;
1161        if (line > num_lines) {
1162          fatal("%s: script contains more than 65,535 lines", file_id);
1163        }
1164    
1165      /* the root node has line number 0 */      /* the root node has line number 0 */
1166      if (line != 0) {      if (line != 0) {
1167        fprintf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
1168        fprintf(f, "_$jscoverage['%s'][%d]++;\n", file_id, line);        Stream_printf(f, "_$jscoverage['%s'][%d]++;\n", file_id, line);
1169        lines[line - 1] = 1;        lines[line - 1] = 1;
1170      }      }
1171    }    }
1172    output_statement(node, f, indent);    output_statement(node, f, indent, is_jscoverage_if);
1173  }  }
1174    
1175  static void instrument_js_stream(const char * id, int line, FILE * input, FILE * output) {  static bool characters_start_with(const jschar * characters, size_t line_start, size_t line_end, const char * prefix) {
1176    file_id = id;    const jschar * characters_end = characters + line_end;
1177      const jschar * cp = characters + line_start;
1178      const char * bp = prefix;
1179      for (;;) {
1180        if (*bp == '\0') {
1181          return true;
1182        }
1183        else if (cp == characters_end) {
1184          return false;
1185        }
1186        else if (*cp != *bp) {
1187          return false;
1188        }
1189        bp++;
1190        cp++;
1191      }
1192    }
1193    
1194    /* scan the javascript */  static bool characters_are_white_space(const jschar * characters, size_t line_start, size_t line_end) {
1195    JSTokenStream * token_stream = js_NewFileTokenStream(context, NULL, input);    /* XXX - other Unicode space */
1196    if (token_stream == NULL) {    const jschar * end = characters + line_end;
1197      fatal("cannot create token stream from file: %s", file_id);    for (const jschar * p = characters + line_start; p < end; p++) {
1198        jschar c = *p;
1199        if (c == 0x9 || c == 0xB || c == 0xC || c == 0x20 || c == 0xA0) {
1200          continue;
1201        }
1202        else {
1203          return false;
1204        }
1205    }    }
1206      return true;
1207    }
1208    
1209    static void error_reporter(JSContext * context, const char * message, JSErrorReport * report) {
1210      fprintf(stderr, "jscoverage: parse error: line %u: %s\n", report->lineno, message);
1211    }
1212    
1213    void jscoverage_instrument_js(const char * id, const uint16_t * characters, size_t num_characters, Stream * output) {
1214      file_id = id;
1215    
1216    /* parse the javascript */    /* parse the javascript */
1217    JSParseNode * node = js_ParseTokenStream(context, global, token_stream);    JSParseContext parse_context;
1218      if (! js_InitParseContext(context, &parse_context, NULL, NULL, characters, num_characters, NULL, NULL, 1)) {
1219        fatal("cannot create token stream from file: %s", file_id);
1220      }
1221      JSErrorReporter old_error_reporter = JS_SetErrorReporter(context, error_reporter);
1222      JSParseNode * node = js_ParseScript(context, global, &parse_context);
1223    if (node == NULL) {    if (node == NULL) {
1224        js_ReportUncaughtException(context);
1225      fatal("parse error in file: %s", file_id);      fatal("parse error in file: %s", file_id);
1226    }    }
1227    int num_lines = node->pn_pos.end.lineno;    JS_SetErrorReporter(context, old_error_reporter);
1228      num_lines = node->pn_pos.end.lineno;
1229    lines = xmalloc(num_lines);    lines = xmalloc(num_lines);
1230    for (int i = 0; i < num_lines; i++) {    for (unsigned int i = 0; i < num_lines; i++) {
1231      lines[i] = 0;      lines[i] = 0;
1232    }    }
1233    
1234      /* search code for conditionals */
1235      exclusive_directives = xnew(bool, num_lines);
1236      for (unsigned int i = 0; i < num_lines; i++) {
1237        exclusive_directives[i] = false;
1238      }
1239    
1240      bool has_conditionals = false;
1241      struct IfDirective * if_directives = NULL;
1242      size_t line_number = 0;
1243      size_t i = 0;
1244      while (i < num_characters) {
1245        if (line_number == UINT16_MAX) {
1246          fatal("%s: script has more than 65,535 lines", file_id);
1247        }
1248        line_number++;
1249        size_t line_start = i;
1250        jschar c;
1251        bool done = false;
1252        while (! done && i < num_characters) {
1253          c = characters[i];
1254          switch (c) {
1255          case '\r':
1256          case '\n':
1257          case 0x2028:
1258          case 0x2029:
1259            done = true;
1260            break;
1261          default:
1262            i++;
1263          }
1264        }
1265        size_t line_end = i;
1266        if (i < num_characters) {
1267          i++;
1268          if (c == '\r' && i < num_characters && characters[i] == '\n') {
1269            i++;
1270          }
1271        }
1272    
1273        if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_IF")) {
1274          has_conditionals = true;
1275    
1276          if (characters_are_white_space(characters, line_start + 16, line_end)) {
1277            exclusive_directives[line_number - 1] = true;
1278          }
1279          else {
1280            struct IfDirective * if_directive = xnew(struct IfDirective, 1);
1281            if_directive->condition_start = characters + line_start + 16;
1282            if_directive->condition_end = characters + line_end;
1283            if_directive->start_line = line_number;
1284            if_directive->end_line = 0;
1285            if_directive->next = if_directives;
1286            if_directives = if_directive;
1287          }
1288        }
1289        else if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_ENDIF")) {
1290          for (struct IfDirective * p = if_directives; p != NULL; p = p->next) {
1291            if (p->end_line == 0) {
1292              p->end_line = line_number;
1293              break;
1294            }
1295          }
1296        }
1297      }
1298    
1299    /*    /*
1300    Create a temporary file - we can't write directly to the output because we    An instrumented JavaScript file has 4 sections:
1301    need to know the line number info first.    1. initialization
1302      2. instrumented source code
1303      3. conditionals
1304      4. original source code
1305    */    */
   FILE * temporary = tmpfile();  
   if (temporary == NULL) {  
     fatal("cannot create temporary file for script: %s", file_id);  
   }  
1306    
1307    /* write instrumented javascript to the temporary */    Stream * instrumented = Stream_new(0);
1308    instrument_statement(node, temporary, 0);    instrument_statement(node, instrumented, 0, false);
1309      js_FinishParseContext(context, &parse_context);
1310    
1311    /* write line number info to the output */    /* write line number info to the output */
1312    fprintf(output, "/* automatically generated by JSCoverage - do not edit */\n");    Stream_write_string(output, "/* automatically generated by JSCoverage - do not edit */\n");
1313    fprintf(output, "if (! top._$jscoverage) {\n  top._$jscoverage = {};\n}\n");    Stream_write_string(output, "if (! top._$jscoverage) {\n  top._$jscoverage = {};\n}\n");
1314    fprintf(output, "var _$jscoverage = top._$jscoverage;\n");    Stream_write_string(output, "var _$jscoverage = top._$jscoverage;\n");
1315    fprintf(output, "if (! _$jscoverage['%s']) {\n", file_id);    Stream_printf(output, "if (! _$jscoverage['%s']) {\n", file_id);
1316    fprintf(output, "  _$jscoverage['%s'] = [];\n", file_id);    Stream_printf(output, "  _$jscoverage['%s'] = [];\n", file_id);
1317    for (int i = 0; i < num_lines; i++) {    for (int i = 0; i < num_lines; i++) {
1318      if (lines[i]) {      if (lines[i]) {
1319        fprintf(output, "  _$jscoverage['%s'][%d] = 0;\n", file_id, i + 1);        Stream_printf(output, "  _$jscoverage['%s'][%d] = 0;\n", file_id, i + 1);
1320      }      }
1321    }    }
1322    fprintf(output, "}\n");    Stream_write_string(output, "}\n");
1323      free(lines);
1324    lines = NULL;    lines = NULL;
1325      free(exclusive_directives);
1326      exclusive_directives = NULL;
1327    
1328      /* conditionals */
1329      if (has_conditionals) {
1330        Stream_printf(output, "_$jscoverage['%s'].conditionals = [];\n", file_id);
1331      }
1332    
1333      /* copy the instrumented source code to the output */
1334      Stream_write(output, instrumented->data, instrumented->length);
1335    
1336      /* conditionals */
1337      for (struct IfDirective * if_directive = if_directives; if_directive != NULL; if_directive = if_directive->next) {
1338        Stream_write_string(output, "if (!(");
1339        print_javascript(if_directive->condition_start, if_directive->condition_end - if_directive->condition_start, output);
1340        Stream_write_string(output, ")) {\n");
1341        Stream_printf(output, "  _$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_directive->start_line, if_directive->end_line);
1342        Stream_write_string(output, "}\n");
1343      }
1344    
1345      /* free */
1346      while (if_directives != NULL) {
1347        struct IfDirective * if_directive = if_directives;
1348        if_directives = if_directives->next;
1349        free(if_directive);
1350      }
1351    
1352    /* copy the temporary to the output */    /* copy the original source to the output */
1353    fseek(temporary, 0, SEEK_SET);    Stream_printf(output, "_$jscoverage['%s'].source = ", file_id);
1354    copy_stream(temporary, output);    jscoverage_write_source(id, characters, num_characters, output);
1355      Stream_printf(output, ";\n");
1356    
1357    fclose(temporary);    Stream_delete(instrumented);
1358    
1359    file_id = NULL;    file_id = NULL;
1360  }  }
1361    
1362  void jscoverage_instrument_js(const char * id, FILE * input, FILE * output) {  void jscoverage_write_source(const char * id, const jschar * characters, size_t num_characters, Stream * output) {
1363    instrument_js_stream(id, 0, input, output);    Stream_write_string(output, "[");
1364      if (jscoverage_highlight) {
1365        Stream * highlighted_stream = Stream_new(num_characters);
1366        jscoverage_highlight_js(context, id, characters, num_characters, highlighted_stream);
1367        size_t i = 0;
1368        while (i < highlighted_stream->length) {
1369          if (i > 0) {
1370            Stream_write_char(output, ',');
1371          }
1372    
1373          Stream_write_char(output, '"');
1374          bool done = false;
1375          while (! done) {
1376            char c = highlighted_stream->data[i];
1377            switch (c) {
1378            case 0x8:
1379              /* backspace */
1380              Stream_write_string(output, "\\b");
1381              break;
1382            case 0x9:
1383              /* horizontal tab */
1384              Stream_write_string(output, "\\t");
1385              break;
1386            case 0xa:
1387              /* line feed (new line) */
1388              done = true;
1389              break;
1390            /* IE doesn't support this */
1391            /*
1392            case 0xb:
1393              Stream_write_string(output, "\\v");
1394              break;
1395            */
1396            case 0xc:
1397              /* form feed */
1398              Stream_write_string(output, "\\f");
1399              break;
1400            case 0xd:
1401              /* carriage return */
1402              done = true;
1403              if (i + 1 < highlighted_stream->length && highlighted_stream->data[i + 1] == '\n') {
1404                i++;
1405              }
1406              break;
1407            case '"':
1408              Stream_write_string(output, "\\\"");
1409              break;
1410            case '\\':
1411              Stream_write_string(output, "\\\\");
1412              break;
1413            default:
1414              Stream_write_char(output, c);
1415              break;
1416            }
1417            i++;
1418            if (i >= highlighted_stream->length) {
1419              done = true;
1420            }
1421          }
1422          Stream_write_char(output, '"');
1423        }
1424        Stream_delete(highlighted_stream);
1425      }
1426      else {
1427        size_t i = 0;
1428        while (i < num_characters) {
1429          if (i > 0) {
1430            Stream_write_char(output, ',');
1431          }
1432    
1433          Stream_write_char(output, '"');
1434          bool done = false;
1435          while (! done) {
1436            jschar c = characters[i];
1437            switch (c) {
1438            case 0x8:
1439              /* backspace */
1440              Stream_write_string(output, "\\b");
1441              break;
1442            case 0x9:
1443              /* horizontal tab */
1444              Stream_write_string(output, "\\t");
1445              break;
1446            case 0xa:
1447              /* line feed (new line) */
1448              done = true;
1449              break;
1450            /* IE doesn't support this */
1451            /*
1452            case 0xb:
1453              Stream_write_string(output, "\\v");
1454              break;
1455            */
1456            case 0xc:
1457              /* form feed */
1458              Stream_write_string(output, "\\f");
1459              break;
1460            case 0xd:
1461              /* carriage return */
1462              done = true;
1463              if (i + 1 < num_characters && characters[i + 1] == '\n') {
1464                i++;
1465              }
1466              break;
1467            case '"':
1468              Stream_write_string(output, "\\\"");
1469              break;
1470            case '\\':
1471              Stream_write_string(output, "\\\\");
1472              break;
1473            case '&':
1474              Stream_write_string(output, "&amp;");
1475              break;
1476            case '<':
1477              Stream_write_string(output, "&lt;");
1478              break;
1479            case '>':
1480              Stream_write_string(output, "&gt;");
1481              break;
1482            case 0x2028:
1483            case 0x2029:
1484              done = true;
1485              break;
1486            default:
1487              if (32 <= c && c <= 126) {
1488                Stream_write_char(output, c);
1489              }
1490              else {
1491                Stream_printf(output, "&#%d;", c);
1492              }
1493              break;
1494            }
1495            i++;
1496            if (i >= num_characters) {
1497              done = true;
1498            }
1499          }
1500          Stream_write_char(output, '"');
1501        }
1502      }
1503      Stream_write_string(output, "]");
1504    }
1505    
1506    void jscoverage_copy_resources(const char * destination_directory) {
1507      copy_resource("jscoverage.html", destination_directory);
1508      copy_resource("jscoverage.css", destination_directory);
1509      copy_resource("jscoverage.js", destination_directory);
1510      copy_resource("jscoverage-ie.css", destination_directory);
1511      copy_resource("jscoverage-throbber.gif", destination_directory);
1512      copy_resource("jscoverage-highlight.css", destination_directory);
1513    }
1514    
1515    /*
1516    coverage reports
1517    */
1518    
1519    struct FileCoverageList {
1520      FileCoverage * file_coverage;
1521      struct FileCoverageList * next;
1522    };
1523    
1524    struct Coverage {
1525      JSHashTable * coverage_table;
1526      struct FileCoverageList * coverage_list;
1527    };
1528    
1529    static int compare_strings(const void * p1, const void * p2) {
1530      return strcmp(p1, p2) == 0;
1531    }
1532    
1533    Coverage * Coverage_new(void) {
1534      Coverage * result = xmalloc(sizeof(Coverage));
1535      result->coverage_table = JS_NewHashTable(1024, JS_HashString, compare_strings, NULL, NULL, NULL);
1536      if (result->coverage_table == NULL) {
1537        fatal("cannot create hash table");
1538      }
1539      result->coverage_list = NULL;
1540      return result;
1541    }
1542    
1543    void Coverage_delete(Coverage * coverage) {
1544      JS_HashTableDestroy(coverage->coverage_table);
1545      struct FileCoverageList * p = coverage->coverage_list;
1546      while (p != NULL) {
1547        free(p->file_coverage->coverage_lines);
1548        if (p->file_coverage->source_lines != NULL) {
1549          for (uint32 i = 0; i < p->file_coverage->num_source_lines; i++) {
1550            free(p->file_coverage->source_lines[i]);
1551          }
1552          free(p->file_coverage->source_lines);
1553        }
1554        free(p->file_coverage->id);
1555        free(p->file_coverage);
1556        struct FileCoverageList * q = p;
1557        p = p->next;
1558        free(q);
1559      }
1560      free(coverage);
1561    }
1562    
1563    struct EnumeratorArg {
1564      CoverageForeachFunction f;
1565      void * p;
1566    };
1567    
1568    static intN enumerator(JSHashEntry * entry, intN i, void * arg) {
1569      struct EnumeratorArg * enumerator_arg = arg;
1570      enumerator_arg->f(entry->value, i, enumerator_arg->p);
1571      return 0;
1572    }
1573    
1574    void Coverage_foreach_file(Coverage * coverage, CoverageForeachFunction f, void * p) {
1575      struct EnumeratorArg enumerator_arg;
1576      enumerator_arg.f = f;
1577      enumerator_arg.p = p;
1578      JS_HashTableEnumerateEntries(coverage->coverage_table, enumerator, &enumerator_arg);
1579    }
1580    
1581    int jscoverage_parse_json(Coverage * coverage, const uint8_t * json, size_t length) {
1582      int result = 0;
1583    
1584      jschar * base = js_InflateString(context, (char *) json, &length);
1585      if (base == NULL) {
1586        fatal("out of memory");
1587      }
1588    
1589      jschar * parenthesized_json = xnew(jschar, addst(length, 2));
1590      parenthesized_json[0] = '(';
1591      memcpy(parenthesized_json + 1, base, mulst(length, sizeof(jschar)));
1592      parenthesized_json[length + 1] = ')';
1593    
1594      JS_free(context, base);
1595    
1596      JSParseContext parse_context;
1597      if (! js_InitParseContext(context, &parse_context, NULL, NULL, parenthesized_json, length + 2, NULL, NULL, 1)) {
1598        free(parenthesized_json);
1599        return -1;
1600      }
1601      JSParseNode * root = js_ParseScript(context, global, &parse_context);
1602      free(parenthesized_json);
1603      if (root == NULL) {
1604        result = -1;
1605        goto done;
1606      }
1607    
1608      /* root node must be TOK_LC */
1609      if (root->pn_type != TOK_LC) {
1610        result = -1;
1611        goto done;
1612      }
1613      JSParseNode * semi = root->pn_u.list.head;
1614    
1615      /* the list must be TOK_SEMI and it must contain only one element */
1616      if (semi->pn_type != TOK_SEMI || semi->pn_next != NULL) {
1617        result = -1;
1618        goto done;
1619      }
1620      JSParseNode * parenthesized = semi->pn_kid;
1621    
1622      /* this must be a parenthesized expression */
1623      if (parenthesized->pn_type != TOK_RP) {
1624        result = -1;
1625        goto done;
1626      }
1627      JSParseNode * object = parenthesized->pn_kid;
1628    
1629      /* this must be an object literal */
1630      if (object->pn_type != TOK_RC) {
1631        result = -1;
1632        goto done;
1633      }
1634    
1635      for (JSParseNode * p = object->pn_head; p != NULL; p = p->pn_next) {
1636        /* every element of this list must be TOK_COLON */
1637        if (p->pn_type != TOK_COLON) {
1638          result = -1;
1639          goto done;
1640        }
1641    
1642        /* the key must be a string representing the file */
1643        JSParseNode * key = p->pn_left;
1644        if (key->pn_type != TOK_STRING || ! ATOM_IS_STRING(key->pn_atom)) {
1645          result = -1;
1646          goto done;
1647        }
1648        char * id_bytes = JS_GetStringBytes(ATOM_TO_STRING(key->pn_atom));
1649    
1650        /* the value must be an object literal OR an array */
1651        JSParseNode * value = p->pn_right;
1652        if (! (value->pn_type == TOK_RC || value->pn_type == TOK_RB)) {
1653          result = -1;
1654          goto done;
1655        }
1656    
1657        JSParseNode * array = NULL;
1658        JSParseNode * source = NULL;
1659        if (value->pn_type == TOK_RB) {
1660          /* an array */
1661          array = value;
1662        }
1663        else if (value->pn_type == TOK_RC) {
1664          /* an object literal */
1665          if (value->pn_count != 2) {
1666            result = -1;
1667            goto done;
1668          }
1669          for (JSParseNode * element = value->pn_head; element != NULL; element = element->pn_next) {
1670            if (element->pn_type != TOK_COLON) {
1671              result = -1;
1672              goto done;
1673            }
1674            JSParseNode * left = element->pn_left;
1675            if (left->pn_type != TOK_STRING || ! ATOM_IS_STRING(left->pn_atom)) {
1676              result = -1;
1677              goto done;
1678            }
1679            const char * s = JS_GetStringBytes(ATOM_TO_STRING(left->pn_atom));
1680            if (strcmp(s, "coverage") == 0) {
1681              array = element->pn_right;
1682              if (array->pn_type != TOK_RB) {
1683                result = -1;
1684                goto done;
1685              }
1686            }
1687            else if (strcmp(s, "source") == 0) {
1688              source = element->pn_right;
1689              if (source->pn_type != TOK_RB) {
1690                result = -1;
1691                goto done;
1692              }
1693            }
1694            else {
1695              result = -1;
1696              goto done;
1697            }
1698          }
1699        }
1700        else {
1701          result = -1;
1702          goto done;
1703        }
1704    
1705        if (array == NULL) {
1706          result = -1;
1707          goto done;
1708        }
1709    
1710        /* look up the file in the coverage table */
1711        FileCoverage * file_coverage = JS_HashTableLookup(coverage->coverage_table, id_bytes);
1712        if (file_coverage == NULL) {
1713          /* not there: create a new one */
1714          char * id = xstrdup(id_bytes);
1715          file_coverage = xmalloc(sizeof(FileCoverage));
1716          file_coverage->id = id;
1717          file_coverage->num_coverage_lines = array->pn_count;
1718          file_coverage->coverage_lines = xnew(int, array->pn_count);
1719          file_coverage->source_lines = NULL;
1720    
1721          /* set coverage for all lines */
1722          uint32 i = 0;
1723          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1724            if (element->pn_type == TOK_NUMBER) {
1725              file_coverage->coverage_lines[i] = (int) element->pn_dval;
1726            }
1727            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1728              file_coverage->coverage_lines[i] = -1;
1729            }
1730            else {
1731              result = -1;
1732              goto done;
1733            }
1734          }
1735          assert(i == array->pn_count);
1736    
1737          /* add to the hash table */
1738          JS_HashTableAdd(coverage->coverage_table, id, file_coverage);
1739          struct FileCoverageList * coverage_list = xmalloc(sizeof(struct FileCoverageList));
1740          coverage_list->file_coverage = file_coverage;
1741          coverage_list->next = coverage->coverage_list;
1742          coverage->coverage_list = coverage_list;
1743        }
1744        else {
1745          /* sanity check */
1746          assert(strcmp(file_coverage->id, id_bytes) == 0);
1747          if (file_coverage->num_coverage_lines != array->pn_count) {
1748            result = -2;
1749            goto done;
1750          }
1751    
1752          /* merge the coverage */
1753          uint32 i = 0;
1754          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1755            if (element->pn_type == TOK_NUMBER) {
1756              if (file_coverage->coverage_lines[i] == -1) {
1757                result = -2;
1758                goto done;
1759              }
1760              file_coverage->coverage_lines[i] += (int) element->pn_dval;
1761            }
1762            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1763              if (file_coverage->coverage_lines[i] != -1) {
1764                result = -2;
1765                goto done;
1766              }
1767            }
1768            else {
1769              result = -1;
1770              goto done;
1771            }
1772          }
1773          assert(i == array->pn_count);
1774        }
1775    
1776        /* if this JSON file has source, use it */
1777        if (file_coverage->source_lines == NULL && source != NULL) {
1778          file_coverage->num_source_lines = source->pn_count;
1779          file_coverage->source_lines = xnew(char *, source->pn_count);
1780          uint32 i = 0;
1781          for (JSParseNode * element = source->pn_head; element != NULL; element = element->pn_next, i++) {
1782            if (element->pn_type != TOK_STRING) {
1783              result = -1;
1784              goto done;
1785            }
1786            file_coverage->source_lines[i] = xstrdup(JS_GetStringBytes(ATOM_TO_STRING(element->pn_atom)));
1787          }
1788          assert(i == source->pn_count);
1789        }
1790      }
1791    
1792    done:
1793      js_FinishParseContext(context, &parse_context);
1794      return result;
1795  }  }

Legend:
Removed from v.2  
changed lines
  Added in v.352

  ViewVC Help
Powered by ViewVC 1.1.24