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

Diff of /trunk/instrument-js.cpp

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

revision 92 by siliconforks, Wed May 7 04:21:22 2008 UTC revision 355 by siliconforks, Fri Oct 24 16:19:11 2008 UTC
# 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_javascript(const jschar * characters, size_t num_characters, Stream * f) {
103      for (size_t i = 0; i < num_characters; i++) {
104        jschar c = characters[i];
105        /*
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) {  static void print_string(JSString * s, Stream * f) {
127    for (int i = 0; i < s->length; i++) {    size_t length = JSSTRING_LENGTH(s);
128      char c = s->chars[i];    jschar * characters = JSSTRING_CHARS(s);
129      Stream_write_char(f, c);    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    
# Line 84  Line 183 
183    print_string(s, f);    print_string(s, f);
184  }  }
185    
186  static void print_string_jsval(jsval value, Stream * 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, Stream * 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 143  Line 257 
257  }  }
258    
259  static void instrument_expression(JSParseNode * node, Stream * f);  static void instrument_expression(JSParseNode * node, Stream * f);
260  static void instrument_statement(JSParseNode * node, Stream * 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  static void instrument_function(JSParseNode * node, Stream * f, int indent) {  enum FunctionType {
264      assert(node->pn_arity == PN_FUNC);    FUNCTION_NORMAL,
265      assert(ATOM_IS_OBJECT(node->pn_funAtom));    FUNCTION_GETTER_OR_SETTER
266      JSObject * object = ATOM_TO_OBJECT(node->pn_funAtom);  };
267      assert(JS_ObjectIsFunction(context, object));  
268      JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);  static void output_for_in(JSParseNode * node, Stream * f) {
269      assert(function);    assert(node->pn_type == TOK_FOR);
270      assert(object == function->object);    assert(node->pn_arity == PN_BINARY);
271      Stream_printf(f, "%*s", indent, "");    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, Stream * f, int indent, enum FunctionType type) {
281      assert(node->pn_type == TOK_FUNCTION);
282      assert(node->pn_arity == PN_FUNC);
283      JSObject * object = node->pn_funpob->object;
284      assert(JS_ObjectIsFunction(context, object));
285      JSFunction * function = (JSFunction *) JS_GetPrivate(context, object);
286      assert(function);
287      assert(object == &function->object);
288      Stream_printf(f, "%*s", indent, "");
289      if (type == FUNCTION_NORMAL) {
290      Stream_write_string(f, "function");      Stream_write_string(f, "function");
291      }
292    
293      /* function name */    /* function name */
294      if (function->atom) {    if (function->atom) {
295        Stream_write_char(f, ' ');      Stream_write_char(f, ' ');
296        print_string_atom(function->atom, f);      print_string_atom(function->atom, f);
297      }    }
298    
299      /* function parameters */    /*
300      Stream_write_string(f, "(");    function parameters - see JS_DecompileFunction in jsapi.cpp, which calls
301      JSAtom ** params = xmalloc(function->nargs * sizeof(JSAtom *));    js_DecompileFunction in jsopcode.cpp
302      for (int i = 0; i < function->nargs; i++) {    */
303        /* initialize to NULL for sanity check */    Stream_write_string(f, "(");
304        params[i] = NULL;    JSArenaPool pool;
305      }    JS_INIT_ARENA_POOL(&pool, "instrument_function", 256, 1, &context->scriptStackQuota);
306      JSScope * scope = OBJ_SCOPE(object);    jsuword * local_names = NULL;
307      for (JSScopeProperty * scope_property = SCOPE_LAST_PROP(scope); scope_property != NULL; scope_property = scope_property->parent) {    if (JS_GET_LOCAL_NAME_COUNT(function)) {
308        if (scope_property->getter != js_GetArgument) {      local_names = js_GetLocalNameArray(context, function, &pool);
309          continue;      if (local_names == NULL) {
310        }        fatal("out of memory");
       assert(scope_property->flags & SPROP_HAS_SHORTID);  
       assert((uint16) scope_property->shortid < function->nargs);  
       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          Stream_write_string(f, ", ");        Stream_write_string(f, ", ");
       }  
       if (ATOM_IS_STRING(params[i])) {  
         print_string_atom(params[i], f);  
       }  
316      }      }
317      Stream_write_string(f, ") {\n");      JSAtom * param = JS_LOCAL_NAME_TO_ATOM(local_names[i]);
318      free(params);      if (param == NULL) {
319          fatal("unsupported parameter type for function: %s", file_id);
320        }
321        print_string_atom(param, f);
322      }
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      Stream_write_string(f, "}\n");    Stream_write_string(f, "}\n");
336  }  }
337    
338  static void instrument_function_call(JSParseNode * node, Stream * f) {  static void instrument_function_call(JSParseNode * node, Stream * f) {
339    instrument_expression(node->pn_head, f);    JSParseNode * function_node = node->pn_head;
340      if (function_node->pn_type == TOK_FUNCTION) {
341        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, '(');    Stream_write_char(f, '(');
396    for (struct JSParseNode * p = node->pn_head->pn_next; p != NULL; p = p->pn_next) {    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        Stream_write_string(f, ", ");        Stream_write_string(f, ", ");
399      }      }
# Line 209  Line 402 
402    Stream_write_char(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  /*  /*
434  See <Expressions> in jsparse.h.  See <Expressions> in jsparse.h.
435  TOK_FUNCTION is handled as a statement and as an expression.  TOK_FUNCTION is handled as a statement and as an expression.
# Line 225  Line 446 
446  static void instrument_expression(JSParseNode * node, Stream * 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) {
# Line 267  Line 488 
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);  
     Stream_write_string(f, " || ");  
     instrument_expression(node->pn_right, f);  
     break;  
491    case TOK_AND:    case TOK_AND:
     instrument_expression(node->pn_left, f);  
     Stream_write_string(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 331  Line 544 
544        instrument_expression(node->pn_kid, f);        instrument_expression(node->pn_kid, f);
545        break;        break;
546      default:      default:
547        abort();        fatal("%s: unknown operator (%d) in file", file_id, node->pn_op);
548        break;        break;
549      }      }
550      break;      break;
# Line 388  Line 601 
601      assert(ATOM_IS_STRING(node->pn_atom));      assert(ATOM_IS_STRING(node->pn_atom));
602      {      {
603        JSString * s = ATOM_TO_STRING(node->pn_atom);        JSString * s = ATOM_TO_STRING(node->pn_atom);
604        /* XXX - semantics changed in 1.7 */        bool must_quote;
605        if (! ATOM_KEYWORD(node->pn_atom) && js_IsIdentifier(s)) {        if (JSSTRING_LENGTH(s) == 0) {
606          Stream_write_char(f, '.');          must_quote = true;
607          print_string_atom(node->pn_atom, 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 {        else {
615            must_quote = false;
616          }
617          if (must_quote) {
618          Stream_write_char(f, '[');          Stream_write_char(f, '[');
619          print_quoted_string_atom(node->pn_atom, f);          print_quoted_string_atom(node->pn_atom, f);
620          Stream_write_char(f, ']');          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:
# Line 428  Line 653 
653    case TOK_RC:    case TOK_RC:
654      Stream_write_char(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);        if (p->pn_type != TOK_COLON) {
657            fatal("unsupported node type in file %s: %d", file_id, p->pn_type);
658          }
659        if (p != node->pn_head) {        if (p != node->pn_head) {
660          Stream_write_string(f, ", ");          Stream_write_string(f, ", ");
661        }        }
662        instrument_expression(p->pn_left, f);  
663        Stream_write_string(f, ": ");        /* check whether this is a getter or setter */
664        instrument_expression(p->pn_right, f);        switch (p->pn_op) {
665          case JSOP_GETTER:
666          case JSOP_SETTER:
667            if (p->pn_op == JSOP_GETTER) {
668              Stream_write_string(f, "get ");
669            }
670            else {
671              Stream_write_string(f, "set ");
672            }
673            instrument_expression(p->pn_left, f);
674            if (p->pn_right->pn_type != TOK_FUNCTION) {
675              fatal("parse error: expected function");
676            }
677            instrument_function(p->pn_right, f, 0, FUNCTION_GETTER_OR_SETTER);
678            break;
679          default:
680            instrument_expression(p->pn_left, f);
681            Stream_write_string(f, ": ");
682            instrument_expression(p->pn_right, f);
683            break;
684          }
685      }      }
686      Stream_write_char(f, '}');      Stream_write_char(f, '}');
687      break;      break;
# Line 449  Line 696 
696    case TOK_STRING:    case TOK_STRING:
697      print_quoted_string_atom(node->pn_atom, f);      print_quoted_string_atom(node->pn_atom, f);
698      break;      break;
699    case TOK_OBJECT:    case TOK_REGEXP:
700      switch (node->pn_op) {      assert(node->pn_op == JSOP_REGEXP);
701      case JSOP_OBJECT:      {
702        /* I assume this is JSOP_REGEXP */        JSObject * object = node->pn_pob->object;
703        abort();        jsval result;
704        break;        js_regexp_toString(context, object, &result);
705      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;  
706      }      }
707      break;      break;
708    case TOK_NUMBER:    case TOK_NUMBER:
# Line 512  Line 748 
748      Stream_write_string(f, " in ");      Stream_write_string(f, " in ");
749      instrument_expression(node->pn_right, f);      instrument_expression(node->pn_right, f);
750      break;      break;
751    default:    case TOK_LEXICALSCOPE:
752      fatal("unsupported node type in file %s: %d", file_id, node->pn_type);      assert(node->pn_arity == PN_NAME);
753    }      assert(node->pn_expr->pn_type == TOK_LET);
754  }      assert(node->pn_expr->pn_arity == PN_BINARY);
755        Stream_write_string(f, "let(");
756  static void instrument_var_statement(JSParseNode * node, Stream * f, int indent) {      assert(node->pn_expr->pn_left->pn_type == TOK_LP);
757    assert(node->pn_arity == PN_LIST);      assert(node->pn_expr->pn_left->pn_arity == PN_LIST);
758    Stream_printf(f, "%*s", indent, "");      instrument_declarations(node->pn_expr->pn_left, f);
759    Stream_write_string(f, "var ");      Stream_write_string(f, ") ");
760    for (struct JSParseNode * p = node->pn_u.list.head; p != NULL; p = p->pn_next) {      instrument_expression(node->pn_expr->pn_right, f);
761      assert(p->pn_type == TOK_NAME);      break;
762      assert(p->pn_arity == PN_NAME);    case TOK_YIELD:
763      if (p != node->pn_head) {      assert(node->pn_arity == PN_UNARY);
764        Stream_write_string(f, ", ");      Stream_write_string(f, "yield");
765        if (node->pn_kid != NULL) {
766          Stream_write_char(f, ' ');
767          instrument_expression(node->pn_kid, f);
768      }      }
769      print_string_atom(p->pn_atom, f);      break;
770      if (p->pn_expr != NULL) {    case TOK_ARRAYCOMP:
771        Stream_write_string(f, " = ");      assert(node->pn_arity == PN_LIST);
772        instrument_expression(p->pn_expr, f);      {
773          JSParseNode * block_node;
774          switch (node->pn_count) {
775          case 1:
776            block_node = node->pn_head;
777            break;
778          case 2:
779            block_node = node->pn_head->pn_next;
780            break;
781          default:
782            abort();
783            break;
784          }
785          assert(block_node->pn_type == TOK_LEXICALSCOPE);
786          assert(block_node->pn_arity == PN_NAME);
787          JSParseNode * for_node = block_node->pn_expr;
788          assert(for_node->pn_type == TOK_FOR);
789          assert(for_node->pn_arity == PN_BINARY);
790          JSParseNode * if_node = NULL;
791          JSParseNode * push_node;
792          switch (for_node->pn_right->pn_type) {
793          case TOK_ARRAYPUSH:
794            push_node = for_node->pn_right;
795            assert(push_node->pn_arity == PN_UNARY);
796            break;
797          case TOK_IF:
798            if_node = for_node->pn_right;
799            assert(if_node->pn_arity == PN_TERNARY);
800            push_node = if_node->pn_kid2;
801            break;
802          default:
803            abort();
804            break;
805          }
806          Stream_write_char(f, '[');
807          instrument_expression(push_node->pn_kid, f);
808          Stream_write_char(f, ' ');
809          output_for_in(for_node, f);
810          if (if_node) {
811            Stream_write_string(f, " if (");
812            instrument_expression(if_node->pn_kid1, f);
813            Stream_write_char(f, ')');
814          }
815          Stream_write_char(f, ']');
816      }      }
817        break;
818      case TOK_VAR:
819        assert(node->pn_arity == PN_LIST);
820        Stream_write_string(f, "var ");
821        instrument_declarations(node, f);
822        break;
823      case TOK_LET:
824        assert(node->pn_arity == PN_LIST);
825        Stream_write_string(f, "let ");
826        instrument_declarations(node, f);
827        break;
828      default:
829        fatal("unsupported node type in file %s: %d", file_id, node->pn_type);
830    }    }
831  }  }
832    
833  static void output_statement(JSParseNode * node, Stream * f, int indent) {  static void output_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
834    switch (node->pn_type) {    switch (node->pn_type) {
835    case TOK_FUNCTION:    case TOK_FUNCTION:
836      instrument_function(node, f, indent);      instrument_function(node, f, indent, FUNCTION_NORMAL);
837      break;      break;
838    case TOK_LC:    case TOK_LC:
839      assert(node->pn_arity == PN_LIST);      assert(node->pn_arity == PN_LIST);
# Line 546  Line 841 
841      Stream_write_string(f, "{\n");      Stream_write_string(f, "{\n");
842  */  */
843      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) {
844        instrument_statement(p, f, indent);        instrument_statement(p, f, indent, false);
845      }      }
846  /*  /*
847      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
# Line 554  Line 849 
849  */  */
850      break;      break;
851    case TOK_IF:    case TOK_IF:
852      {
853      assert(node->pn_arity == PN_TERNARY);      assert(node->pn_arity == PN_TERNARY);
854    
855        uint16_t line = node->pn_pos.begin.lineno;
856        if (! is_jscoverage_if) {
857          if (line > num_lines) {
858            fatal("%s: script contains more than 65,535 lines", file_id);
859          }
860          if (line >= 2 && exclusive_directives[line - 2]) {
861            is_jscoverage_if = true;
862          }
863        }
864    
865      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
866      Stream_write_string(f, "if (");      Stream_write_string(f, "if (");
867      instrument_expression(node->pn_kid1, f);      instrument_expression(node->pn_kid1, f);
868      Stream_write_string(f, ") {\n");      Stream_write_string(f, ") {\n");
869      instrument_statement(node->pn_kid2, f, indent + 2);      if (is_jscoverage_if && node->pn_kid3) {
870          uint16_t else_start = node->pn_kid3->pn_pos.begin.lineno;
871          uint16_t else_end = node->pn_kid3->pn_pos.end.lineno + 1;
872          Stream_printf(f, "%*s", indent + 2, "");
873          Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, else_start, else_end);
874        }
875        instrument_statement(node->pn_kid2, f, indent + 2, false);
876      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
877      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
878      if (node->pn_kid3) {  
879        if (node->pn_kid3 || is_jscoverage_if) {
880        Stream_printf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
881        Stream_write_string(f, "else {\n");        Stream_write_string(f, "else {\n");
882        instrument_statement(node->pn_kid3, f, indent + 2);  
883          if (is_jscoverage_if) {
884            uint16_t if_start = node->pn_kid2->pn_pos.begin.lineno + 1;
885            uint16_t if_end = node->pn_kid2->pn_pos.end.lineno + 1;
886            Stream_printf(f, "%*s", indent + 2, "");
887            Stream_printf(f, "_$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_start, if_end);
888          }
889    
890          if (node->pn_kid3) {
891            instrument_statement(node->pn_kid3, f, indent + 2, is_jscoverage_if);
892          }
893    
894        Stream_printf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
895        Stream_write_string(f, "}\n");        Stream_write_string(f, "}\n");
896      }      }
897    
898      break;      break;
899      }
900    case TOK_SWITCH:    case TOK_SWITCH:
901      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
902      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
903      Stream_write_string(f, "switch (");      Stream_write_string(f, "switch (");
904      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
905      Stream_write_string(f, ") {\n");      Stream_write_string(f, ") {\n");
906      for (struct JSParseNode * p = node->pn_right->pn_head; p != NULL; p = p->pn_next) {      {
907        Stream_printf(f, "%*s", indent, "");        JSParseNode * list = node->pn_right;
908        switch (p->pn_type) {        if (list->pn_type == TOK_LEXICALSCOPE) {
909        case TOK_CASE:          list = list->pn_expr;
910          Stream_write_string(f, "case ");        }
911          instrument_expression(p->pn_left, f);        for (struct JSParseNode * p = list->pn_head; p != NULL; p = p->pn_next) {
912          Stream_write_string(f, ":\n");          Stream_printf(f, "%*s", indent, "");
913          break;          switch (p->pn_type) {
914        case TOK_DEFAULT:          case TOK_CASE:
915          Stream_write_string(f, "default:\n");            Stream_write_string(f, "case ");
916          break;            instrument_expression(p->pn_left, f);
917        default:            Stream_write_string(f, ":\n");
918          abort();            break;
919          break;          case TOK_DEFAULT:
920              Stream_write_string(f, "default:\n");
921              break;
922            default:
923              abort();
924              break;
925            }
926            instrument_statement(p->pn_right, f, indent + 2, false);
927        }        }
       instrument_statement(p->pn_right, f, indent + 2);  
928      }      }
929      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
930      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
# Line 606  Line 939 
939      Stream_write_string(f, "while (");      Stream_write_string(f, "while (");
940      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
941      Stream_write_string(f, ") {\n");      Stream_write_string(f, ") {\n");
942      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
943      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
944      break;      break;
945    case TOK_DO:    case TOK_DO:
946      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
947      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
948      Stream_write_string(f, "do {\n");      Stream_write_string(f, "do {\n");
949      instrument_statement(node->pn_left, f, indent + 2);      instrument_statement(node->pn_left, f, indent + 2, false);
950      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
951      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
952      Stream_write_string(f, "while (");      Stream_write_string(f, "while (");
# Line 623  Line 956 
956    case TOK_FOR:    case TOK_FOR:
957      assert(node->pn_arity == PN_BINARY);      assert(node->pn_arity == PN_BINARY);
958      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
     Stream_write_string(f, "for (");  
959      switch (node->pn_left->pn_type) {      switch (node->pn_left->pn_type) {
960      case TOK_IN:      case TOK_IN:
961        /* for/in */        /* for/in */
962        assert(node->pn_left->pn_arity == PN_BINARY);        assert(node->pn_left->pn_arity == PN_BINARY);
963        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;  
 */  
       }  
       Stream_write_string(f, " in ");  
       instrument_expression(node->pn_left->pn_right, f);  
964        break;        break;
965      case TOK_RESERVED:      case TOK_RESERVED:
966        /* for (;;) */        /* for (;;) */
967        assert(node->pn_left->pn_arity == PN_TERNARY);        assert(node->pn_left->pn_arity == PN_TERNARY);
968          Stream_write_string(f, "for (");
969        if (node->pn_left->pn_kid1) {        if (node->pn_left->pn_kid1) {
970          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);  
         }  
971        }        }
972        Stream_write_string(f, ";");        Stream_write_string(f, ";");
973        if (node->pn_left->pn_kid2) {        if (node->pn_left->pn_kid2) {
# Line 670  Line 979 
979          Stream_write_char(f, ' ');          Stream_write_char(f, ' ');
980          instrument_expression(node->pn_left->pn_kid3, f);          instrument_expression(node->pn_left->pn_kid3, f);
981        }        }
982          Stream_write_char(f, ')');
983        break;        break;
984      default:      default:
985        abort();        abort();
986        break;        break;
987      }      }
988      Stream_write_string(f, ") {\n");      Stream_write_string(f, " {\n");
989      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
990      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
991      break;      break;
992    case TOK_THROW:    case TOK_THROW:
# Line 689  Line 999 
999    case TOK_TRY:    case TOK_TRY:
1000      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1001      Stream_write_string(f, "try {\n");      Stream_write_string(f, "try {\n");
1002      instrument_statement(node->pn_kid1, f, indent + 2);      instrument_statement(node->pn_kid1, f, indent + 2, false);
1003      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1004      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
1005      {      if (node->pn_kid2) {
1006        for (JSParseNode * catch = node->pn_kid2; catch != NULL; catch = catch->pn_kid2) {        assert(node->pn_kid2->pn_type == TOK_RESERVED);
1007          for (JSParseNode * scope = node->pn_kid2->pn_head; scope != NULL; scope = scope->pn_next) {
1008            assert(scope->pn_type == TOK_LEXICALSCOPE);
1009            JSParseNode * catch = scope->pn_expr;
1010          assert(catch->pn_type == TOK_CATCH);          assert(catch->pn_type == TOK_CATCH);
1011          Stream_printf(f, "%*s", indent, "");          Stream_printf(f, "%*s", indent, "");
1012          Stream_write_string(f, "catch (");          Stream_write_string(f, "catch (");
1013            /* this may not be a name - destructuring assignment */
1014            /*
1015          assert(catch->pn_kid1->pn_arity == PN_NAME);          assert(catch->pn_kid1->pn_arity == PN_NAME);
1016          print_string_atom(catch->pn_kid1->pn_atom, f);          print_string_atom(catch->pn_kid1->pn_atom, f);
1017          if (catch->pn_kid1->pn_expr) {          */
1018            instrument_expression(catch->pn_kid1, f);
1019            if (catch->pn_kid2) {
1020            Stream_write_string(f, " if ");            Stream_write_string(f, " if ");
1021            instrument_expression(catch->pn_kid1->pn_expr, f);            instrument_expression(catch->pn_kid2, f);
1022          }          }
1023          Stream_write_string(f, ") {\n");          Stream_write_string(f, ") {\n");
1024          instrument_statement(catch->pn_kid3, f, indent + 2);          instrument_statement(catch->pn_kid3, f, indent + 2, false);
1025          Stream_printf(f, "%*s", indent, "");          Stream_printf(f, "%*s", indent, "");
1026          Stream_write_string(f, "}\n");          Stream_write_string(f, "}\n");
1027        }        }
# Line 712  Line 1029 
1029      if (node->pn_kid3) {      if (node->pn_kid3) {
1030        Stream_printf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
1031        Stream_write_string(f, "finally {\n");        Stream_write_string(f, "finally {\n");
1032        instrument_statement(node->pn_kid3, f, indent + 2);        instrument_statement(node->pn_kid3, f, indent + 2, false);
1033        Stream_printf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
1034        Stream_write_string(f, "}\n");        Stream_write_string(f, "}\n");
1035      }      }
# Line 738  Line 1055 
1055      Stream_write_string(f, "with (");      Stream_write_string(f, "with (");
1056      instrument_expression(node->pn_left, f);      instrument_expression(node->pn_left, f);
1057      Stream_write_string(f, ") {\n");      Stream_write_string(f, ") {\n");
1058      instrument_statement(node->pn_right, f, indent + 2);      instrument_statement(node->pn_right, f, indent + 2, false);
1059      Stream_printf(f, "%*s", indent, "");      Stream_printf(f, "%*s", indent, "");
1060      Stream_write_string(f, "}\n");      Stream_write_string(f, "}\n");
1061      break;      break;
1062    case TOK_VAR:    case TOK_VAR:
1063      instrument_var_statement(node, f, indent);      Stream_printf(f, "%*s", indent, "");
1064        instrument_expression(node, f);
1065      Stream_write_string(f, ";\n");      Stream_write_string(f, ";\n");
1066      break;      break;
1067    case TOK_RETURN:    case TOK_RETURN:
# Line 776  Line 1094 
1094      /*      /*
1095      ... use output_statement instead of instrument_statement.      ... use output_statement instead of instrument_statement.
1096      */      */
1097      output_statement(node->pn_expr, f, indent);      output_statement(node->pn_expr, f, indent, false);
1098        break;
1099      case TOK_LEXICALSCOPE:
1100        /* let statement */
1101        assert(node->pn_arity == PN_NAME);
1102        switch (node->pn_expr->pn_type) {
1103        case TOK_LET:
1104          /* let statement */
1105          assert(node->pn_expr->pn_arity == PN_BINARY);
1106          instrument_statement(node->pn_expr, f, indent, false);
1107          break;
1108        case TOK_LC:
1109          /* block */
1110          Stream_printf(f, "%*s", indent, "");
1111          Stream_write_string(f, "{\n");
1112          instrument_statement(node->pn_expr, f, indent + 2, false);
1113          Stream_printf(f, "%*s", indent, "");
1114          Stream_write_string(f, "}\n");
1115          break;
1116        case TOK_FOR:
1117          instrument_statement(node->pn_expr, f, indent, false);
1118          break;
1119        default:
1120          abort();
1121          break;
1122        }
1123        break;
1124      case TOK_LET:
1125        switch (node->pn_arity) {
1126        case PN_BINARY:
1127          /* let statement */
1128          Stream_printf(f, "%*s", indent, "");
1129          Stream_write_string(f, "let (");
1130          assert(node->pn_left->pn_type == TOK_LP);
1131          assert(node->pn_left->pn_arity == PN_LIST);
1132          instrument_declarations(node->pn_left, f);
1133          Stream_write_string(f, ") {\n");
1134          instrument_statement(node->pn_right, f, indent + 2, false);
1135          Stream_printf(f, "%*s", indent, "");
1136          Stream_write_string(f, "}\n");
1137          break;
1138        case PN_LIST:
1139          /* let definition */
1140          Stream_printf(f, "%*s", indent, "");
1141          instrument_expression(node, f);
1142          Stream_write_string(f, ";\n");
1143          break;
1144        default:
1145          abort();
1146          break;
1147        }
1148        break;
1149      case TOK_DEBUGGER:
1150        Stream_printf(f, "%*s", indent, "");
1151        Stream_write_string(f, "debugger;\n");
1152      break;      break;
1153    default:    default:
1154      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 788  Line 1160 
1160  TOK_FUNCTION is handled as a statement and as an expression.  TOK_FUNCTION is handled as a statement and as an expression.
1161  TOK_EXPORT, TOK_IMPORT are not handled.  TOK_EXPORT, TOK_IMPORT are not handled.
1162  */  */
1163  static void instrument_statement(JSParseNode * node, Stream * f, int indent) {  static void instrument_statement(JSParseNode * node, Stream * f, int indent, bool is_jscoverage_if) {
1164    if (node->pn_type != TOK_LC) {    if (node->pn_type != TOK_LC && node->pn_type != TOK_LEXICALSCOPE) {
1165      int line = node->pn_pos.begin.lineno;      uint16_t line = node->pn_pos.begin.lineno;
1166        if (line > num_lines) {
1167          fatal("%s: script contains more than 65,535 lines", file_id);
1168        }
1169    
1170      /* the root node has line number 0 */      /* the root node has line number 0 */
1171      if (line != 0) {      if (line != 0) {
1172        Stream_printf(f, "%*s", indent, "");        Stream_printf(f, "%*s", indent, "");
# Line 798  Line 1174 
1174        lines[line - 1] = 1;        lines[line - 1] = 1;
1175      }      }
1176    }    }
1177    output_statement(node, f, indent);    output_statement(node, f, indent, is_jscoverage_if);
1178  }  }
1179    
1180  void jscoverage_instrument_js(const char * id, Stream * input, Stream * output) {  static bool characters_start_with(const jschar * characters, size_t line_start, size_t line_end, const char * prefix) {
1181    file_id = id;    const jschar * characters_end = characters + line_end;
1182      const jschar * cp = characters + line_start;
1183    /* scan the javascript */    const char * bp = prefix;
1184    size_t input_length = input->length;    for (;;) {
1185    jschar * base = js_InflateString(context, input->data, &input_length);      if (*bp == '\0') {
1186    if (base == NULL) {        return true;
1187      fatal("out of memory");      }
1188        else if (cp == characters_end) {
1189          return false;
1190        }
1191        else if (*cp != *bp) {
1192          return false;
1193        }
1194        bp++;
1195        cp++;
1196    }    }
1197    JSTokenStream * token_stream = js_NewTokenStream(context, base, input_length, NULL, 1, NULL);  }
1198    if (token_stream == NULL) {  
1199      fatal("cannot create token stream from file: %s", file_id);  static bool characters_are_white_space(const jschar * characters, size_t line_start, size_t line_end) {
1200      /* XXX - other Unicode space */
1201      const jschar * end = characters + line_end;
1202      for (const jschar * p = characters + line_start; p < end; p++) {
1203        jschar c = *p;
1204        if (c == 0x9 || c == 0xB || c == 0xC || c == 0x20 || c == 0xA0) {
1205          continue;
1206        }
1207        else {
1208          return false;
1209        }
1210    }    }
1211      return true;
1212    }
1213    
1214    static void error_reporter(JSContext * context, const char * message, JSErrorReport * report) {
1215      fprintf(stderr, "jscoverage: parse error: line %u: %s\n", report->lineno, message);
1216    }
1217    
1218    void jscoverage_instrument_js(const char * id, const uint16_t * characters, size_t num_characters, Stream * output) {
1219      file_id = id;
1220    
1221    /* parse the javascript */    /* parse the javascript */
1222    JSParseNode * node = js_ParseTokenStream(context, global, token_stream);    JSParseContext parse_context;
1223      if (! js_InitParseContext(context, &parse_context, NULL, NULL, characters, num_characters, NULL, NULL, 1)) {
1224        fatal("cannot create token stream from file: %s", file_id);
1225      }
1226      JSErrorReporter old_error_reporter = JS_SetErrorReporter(context, error_reporter);
1227      JSParseNode * node = js_ParseScript(context, global, &parse_context);
1228    if (node == NULL) {    if (node == NULL) {
1229        js_ReportUncaughtException(context);
1230      fatal("parse error in file: %s", file_id);      fatal("parse error in file: %s", file_id);
1231    }    }
1232    int num_lines = node->pn_pos.end.lineno;    JS_SetErrorReporter(context, old_error_reporter);
1233      num_lines = node->pn_pos.end.lineno;
1234    lines = xmalloc(num_lines);    lines = xmalloc(num_lines);
1235    for (int i = 0; i < num_lines; i++) {    for (unsigned int i = 0; i < num_lines; i++) {
1236      lines[i] = 0;      lines[i] = 0;
1237    }    }
1238    
1239      /* search code for conditionals */
1240      exclusive_directives = xnew(bool, num_lines);
1241      for (unsigned int i = 0; i < num_lines; i++) {
1242        exclusive_directives[i] = false;
1243      }
1244    
1245      bool has_conditionals = false;
1246      struct IfDirective * if_directives = NULL;
1247      size_t line_number = 0;
1248      size_t i = 0;
1249      while (i < num_characters) {
1250        if (line_number == UINT16_MAX) {
1251          fatal("%s: script has more than 65,535 lines", file_id);
1252        }
1253        line_number++;
1254        size_t line_start = i;
1255        jschar c;
1256        bool done = false;
1257        while (! done && i < num_characters) {
1258          c = characters[i];
1259          switch (c) {
1260          case '\r':
1261          case '\n':
1262          case 0x2028:
1263          case 0x2029:
1264            done = true;
1265            break;
1266          default:
1267            i++;
1268          }
1269        }
1270        size_t line_end = i;
1271        if (i < num_characters) {
1272          i++;
1273          if (c == '\r' && i < num_characters && characters[i] == '\n') {
1274            i++;
1275          }
1276        }
1277    
1278        if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_IF")) {
1279          has_conditionals = true;
1280    
1281          if (characters_are_white_space(characters, line_start + 16, line_end)) {
1282            exclusive_directives[line_number - 1] = true;
1283          }
1284          else {
1285            struct IfDirective * if_directive = xnew(struct IfDirective, 1);
1286            if_directive->condition_start = characters + line_start + 16;
1287            if_directive->condition_end = characters + line_end;
1288            if_directive->start_line = line_number;
1289            if_directive->end_line = 0;
1290            if_directive->next = if_directives;
1291            if_directives = if_directive;
1292          }
1293        }
1294        else if (characters_start_with(characters, line_start, line_end, "//#JSCOVERAGE_ENDIF")) {
1295          for (struct IfDirective * p = if_directives; p != NULL; p = p->next) {
1296            if (p->end_line == 0) {
1297              p->end_line = line_number;
1298              break;
1299            }
1300          }
1301        }
1302      }
1303    
1304    /*    /*
1305    An instrumented JavaScript file has 3 sections:    An instrumented JavaScript file has 4 sections:
1306    1. initialization    1. initialization
1307    2. instrumented source code    2. instrumented source code
1308    3. original source code (TODO)    3. conditionals
1309      4. original source code
1310    */    */
1311    
1312    Stream * instrumented = Stream_new(0);    Stream * instrumented = Stream_new(0);
1313    instrument_statement(node, instrumented, 0);    instrument_statement(node, instrumented, 0, false);
1314      js_FinishParseContext(context, &parse_context);
1315    
1316    /* write line number info to the output */    /* write line number info to the output */
1317    Stream_write_string(output, "/* automatically generated by JSCoverage - do not edit */\n");    Stream_write_string(output, "/* automatically generated by JSCoverage - do not edit */\n");
# Line 850  Line 1327 
1327    Stream_write_string(output, "}\n");    Stream_write_string(output, "}\n");
1328    free(lines);    free(lines);
1329    lines = NULL;    lines = NULL;
1330      free(exclusive_directives);
1331      exclusive_directives = NULL;
1332    
1333      /* conditionals */
1334      if (has_conditionals) {
1335        Stream_printf(output, "_$jscoverage['%s'].conditionals = [];\n", file_id);
1336      }
1337    
1338    /* copy the instrumented source code to the output */    /* copy the instrumented source code to the output */
1339    Stream_write(output, instrumented->data, instrumented->length);    Stream_write(output, instrumented->data, instrumented->length);
1340    
1341      /* conditionals */
1342      for (struct IfDirective * if_directive = if_directives; if_directive != NULL; if_directive = if_directive->next) {
1343        Stream_write_string(output, "if (!(");
1344        print_javascript(if_directive->condition_start, if_directive->condition_end - if_directive->condition_start, output);
1345        Stream_write_string(output, ")) {\n");
1346        Stream_printf(output, "  _$jscoverage['%s'].conditionals[%d] = %d;\n", file_id, if_directive->start_line, if_directive->end_line);
1347        Stream_write_string(output, "}\n");
1348      }
1349    
1350      /* free */
1351      while (if_directives != NULL) {
1352        struct IfDirective * if_directive = if_directives;
1353        if_directives = if_directives->next;
1354        free(if_directive);
1355      }
1356    
1357      /* copy the original source to the output */
1358      Stream_printf(output, "_$jscoverage['%s'].source = ", file_id);
1359      jscoverage_write_source(id, characters, num_characters, output);
1360      Stream_printf(output, ";\n");
1361    
1362    Stream_delete(instrumented);    Stream_delete(instrumented);
1363    
1364      file_id = NULL;
1365    }
1366    
1367    void jscoverage_write_source(const char * id, const jschar * characters, size_t num_characters, Stream * output) {
1368      Stream_write_string(output, "[");
1369      if (jscoverage_highlight) {
1370        Stream * highlighted_stream = Stream_new(num_characters);
1371        jscoverage_highlight_js(context, id, characters, num_characters, highlighted_stream);
1372        size_t i = 0;
1373        while (i < highlighted_stream->length) {
1374          if (i > 0) {
1375            Stream_write_char(output, ',');
1376          }
1377    
1378          Stream_write_char(output, '"');
1379          bool done = false;
1380          while (! done) {
1381            char c = highlighted_stream->data[i];
1382            switch (c) {
1383            case 0x8:
1384              /* backspace */
1385              Stream_write_string(output, "\\b");
1386              break;
1387            case 0x9:
1388              /* horizontal tab */
1389              Stream_write_string(output, "\\t");
1390              break;
1391            case 0xa:
1392              /* line feed (new line) */
1393              done = true;
1394              break;
1395            /* IE doesn't support this */
1396            /*
1397            case 0xb:
1398              Stream_write_string(output, "\\v");
1399              break;
1400            */
1401            case 0xc:
1402              /* form feed */
1403              Stream_write_string(output, "\\f");
1404              break;
1405            case 0xd:
1406              /* carriage return */
1407              done = true;
1408              if (i + 1 < highlighted_stream->length && highlighted_stream->data[i + 1] == '\n') {
1409                i++;
1410              }
1411              break;
1412            case '"':
1413              Stream_write_string(output, "\\\"");
1414              break;
1415            case '\\':
1416              Stream_write_string(output, "\\\\");
1417              break;
1418            default:
1419              Stream_write_char(output, c);
1420              break;
1421            }
1422            i++;
1423            if (i >= highlighted_stream->length) {
1424              done = true;
1425            }
1426          }
1427          Stream_write_char(output, '"');
1428        }
1429        Stream_delete(highlighted_stream);
1430      }
1431      else {
1432        size_t i = 0;
1433        while (i < num_characters) {
1434          if (i > 0) {
1435            Stream_write_char(output, ',');
1436          }
1437    
1438          Stream_write_char(output, '"');
1439          bool done = false;
1440          while (! done) {
1441            jschar c = characters[i];
1442            switch (c) {
1443            case 0x8:
1444              /* backspace */
1445              Stream_write_string(output, "\\b");
1446              break;
1447            case 0x9:
1448              /* horizontal tab */
1449              Stream_write_string(output, "\\t");
1450              break;
1451            case 0xa:
1452              /* line feed (new line) */
1453              done = true;
1454              break;
1455            /* IE doesn't support this */
1456            /*
1457            case 0xb:
1458              Stream_write_string(output, "\\v");
1459              break;
1460            */
1461            case 0xc:
1462              /* form feed */
1463              Stream_write_string(output, "\\f");
1464              break;
1465            case 0xd:
1466              /* carriage return */
1467              done = true;
1468              if (i + 1 < num_characters && characters[i + 1] == '\n') {
1469                i++;
1470              }
1471              break;
1472            case '"':
1473              Stream_write_string(output, "\\\"");
1474              break;
1475            case '\\':
1476              Stream_write_string(output, "\\\\");
1477              break;
1478            case '&':
1479              Stream_write_string(output, "&amp;");
1480              break;
1481            case '<':
1482              Stream_write_string(output, "&lt;");
1483              break;
1484            case '>':
1485              Stream_write_string(output, "&gt;");
1486              break;
1487            case 0x2028:
1488            case 0x2029:
1489              done = true;
1490              break;
1491            default:
1492              if (32 <= c && c <= 126) {
1493                Stream_write_char(output, c);
1494              }
1495              else {
1496                Stream_printf(output, "&#%d;", c);
1497              }
1498              break;
1499            }
1500            i++;
1501            if (i >= num_characters) {
1502              done = true;
1503            }
1504          }
1505          Stream_write_char(output, '"');
1506        }
1507      }
1508      Stream_write_string(output, "]");
1509    }
1510    
1511    void jscoverage_copy_resources(const char * destination_directory) {
1512      copy_resource("jscoverage.html", destination_directory);
1513      copy_resource("jscoverage.css", destination_directory);
1514      copy_resource("jscoverage.js", destination_directory);
1515      copy_resource("jscoverage-ie.css", destination_directory);
1516      copy_resource("jscoverage-throbber.gif", destination_directory);
1517      copy_resource("jscoverage-highlight.css", destination_directory);
1518    }
1519    
1520    /*
1521    coverage reports
1522    */
1523    
1524    struct FileCoverageList {
1525      FileCoverage * file_coverage;
1526      struct FileCoverageList * next;
1527    };
1528    
1529    struct Coverage {
1530      JSHashTable * coverage_table;
1531      struct FileCoverageList * coverage_list;
1532    };
1533    
1534    static int compare_strings(const void * p1, const void * p2) {
1535      return strcmp(p1, p2) == 0;
1536    }
1537    
1538    Coverage * Coverage_new(void) {
1539      Coverage * result = xmalloc(sizeof(Coverage));
1540      result->coverage_table = JS_NewHashTable(1024, JS_HashString, compare_strings, NULL, NULL, NULL);
1541      if (result->coverage_table == NULL) {
1542        fatal("cannot create hash table");
1543      }
1544      result->coverage_list = NULL;
1545      return result;
1546    }
1547    
1548    void Coverage_delete(Coverage * coverage) {
1549      JS_HashTableDestroy(coverage->coverage_table);
1550      struct FileCoverageList * p = coverage->coverage_list;
1551      while (p != NULL) {
1552        free(p->file_coverage->coverage_lines);
1553        if (p->file_coverage->source_lines != NULL) {
1554          for (uint32 i = 0; i < p->file_coverage->num_source_lines; i++) {
1555            free(p->file_coverage->source_lines[i]);
1556          }
1557          free(p->file_coverage->source_lines);
1558        }
1559        free(p->file_coverage->id);
1560        free(p->file_coverage);
1561        struct FileCoverageList * q = p;
1562        p = p->next;
1563        free(q);
1564      }
1565      free(coverage);
1566    }
1567    
1568    struct EnumeratorArg {
1569      CoverageForeachFunction f;
1570      void * p;
1571    };
1572    
1573    static intN enumerator(JSHashEntry * entry, intN i, void * arg) {
1574      struct EnumeratorArg * enumerator_arg = arg;
1575      enumerator_arg->f(entry->value, i, enumerator_arg->p);
1576      return 0;
1577    }
1578    
1579    void Coverage_foreach_file(Coverage * coverage, CoverageForeachFunction f, void * p) {
1580      struct EnumeratorArg enumerator_arg;
1581      enumerator_arg.f = f;
1582      enumerator_arg.p = p;
1583      JS_HashTableEnumerateEntries(coverage->coverage_table, enumerator, &enumerator_arg);
1584    }
1585    
1586    int jscoverage_parse_json(Coverage * coverage, const uint8_t * json, size_t length) {
1587      int result = 0;
1588    
1589      jschar * base = js_InflateString(context, (char *) json, &length);
1590      if (base == NULL) {
1591        fatal("out of memory");
1592      }
1593    
1594      jschar * parenthesized_json = xnew(jschar, addst(length, 2));
1595      parenthesized_json[0] = '(';
1596      memcpy(parenthesized_json + 1, base, mulst(length, sizeof(jschar)));
1597      parenthesized_json[length + 1] = ')';
1598    
1599    JS_free(context, base);    JS_free(context, base);
1600    
1601    file_id = NULL;    JSParseContext parse_context;
1602      if (! js_InitParseContext(context, &parse_context, NULL, NULL, parenthesized_json, length + 2, NULL, NULL, 1)) {
1603        free(parenthesized_json);
1604        return -1;
1605      }
1606      JSParseNode * root = js_ParseScript(context, global, &parse_context);
1607      free(parenthesized_json);
1608      if (root == NULL) {
1609        result = -1;
1610        goto done;
1611      }
1612    
1613      /* root node must be TOK_LC */
1614      if (root->pn_type != TOK_LC) {
1615        result = -1;
1616        goto done;
1617      }
1618      JSParseNode * semi = root->pn_u.list.head;
1619    
1620      /* the list must be TOK_SEMI and it must contain only one element */
1621      if (semi->pn_type != TOK_SEMI || semi->pn_next != NULL) {
1622        result = -1;
1623        goto done;
1624      }
1625      JSParseNode * parenthesized = semi->pn_kid;
1626    
1627      /* this must be a parenthesized expression */
1628      if (parenthesized->pn_type != TOK_RP) {
1629        result = -1;
1630        goto done;
1631      }
1632      JSParseNode * object = parenthesized->pn_kid;
1633    
1634      /* this must be an object literal */
1635      if (object->pn_type != TOK_RC) {
1636        result = -1;
1637        goto done;
1638      }
1639    
1640      for (JSParseNode * p = object->pn_head; p != NULL; p = p->pn_next) {
1641        /* every element of this list must be TOK_COLON */
1642        if (p->pn_type != TOK_COLON) {
1643          result = -1;
1644          goto done;
1645        }
1646    
1647        /* the key must be a string representing the file */
1648        JSParseNode * key = p->pn_left;
1649        if (key->pn_type != TOK_STRING || ! ATOM_IS_STRING(key->pn_atom)) {
1650          result = -1;
1651          goto done;
1652        }
1653        char * id_bytes = JS_GetStringBytes(ATOM_TO_STRING(key->pn_atom));
1654    
1655        /* the value must be an object literal OR an array */
1656        JSParseNode * value = p->pn_right;
1657        if (! (value->pn_type == TOK_RC || value->pn_type == TOK_RB)) {
1658          result = -1;
1659          goto done;
1660        }
1661    
1662        JSParseNode * array = NULL;
1663        JSParseNode * source = NULL;
1664        if (value->pn_type == TOK_RB) {
1665          /* an array */
1666          array = value;
1667        }
1668        else if (value->pn_type == TOK_RC) {
1669          /* an object literal */
1670          if (value->pn_count != 2) {
1671            result = -1;
1672            goto done;
1673          }
1674          for (JSParseNode * element = value->pn_head; element != NULL; element = element->pn_next) {
1675            if (element->pn_type != TOK_COLON) {
1676              result = -1;
1677              goto done;
1678            }
1679            JSParseNode * left = element->pn_left;
1680            if (left->pn_type != TOK_STRING || ! ATOM_IS_STRING(left->pn_atom)) {
1681              result = -1;
1682              goto done;
1683            }
1684            const char * s = JS_GetStringBytes(ATOM_TO_STRING(left->pn_atom));
1685            if (strcmp(s, "coverage") == 0) {
1686              array = element->pn_right;
1687              if (array->pn_type != TOK_RB) {
1688                result = -1;
1689                goto done;
1690              }
1691            }
1692            else if (strcmp(s, "source") == 0) {
1693              source = element->pn_right;
1694              if (source->pn_type != TOK_RB) {
1695                result = -1;
1696                goto done;
1697              }
1698            }
1699            else {
1700              result = -1;
1701              goto done;
1702            }
1703          }
1704        }
1705        else {
1706          result = -1;
1707          goto done;
1708        }
1709    
1710        if (array == NULL) {
1711          result = -1;
1712          goto done;
1713        }
1714    
1715        /* look up the file in the coverage table */
1716        FileCoverage * file_coverage = JS_HashTableLookup(coverage->coverage_table, id_bytes);
1717        if (file_coverage == NULL) {
1718          /* not there: create a new one */
1719          char * id = xstrdup(id_bytes);
1720          file_coverage = xmalloc(sizeof(FileCoverage));
1721          file_coverage->id = id;
1722          file_coverage->num_coverage_lines = array->pn_count;
1723          file_coverage->coverage_lines = xnew(int, array->pn_count);
1724          file_coverage->source_lines = NULL;
1725    
1726          /* set coverage for all lines */
1727          uint32 i = 0;
1728          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1729            if (element->pn_type == TOK_NUMBER) {
1730              file_coverage->coverage_lines[i] = (int) element->pn_dval;
1731            }
1732            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1733              file_coverage->coverage_lines[i] = -1;
1734            }
1735            else {
1736              result = -1;
1737              goto done;
1738            }
1739          }
1740          assert(i == array->pn_count);
1741    
1742          /* add to the hash table */
1743          JS_HashTableAdd(coverage->coverage_table, id, file_coverage);
1744          struct FileCoverageList * coverage_list = xmalloc(sizeof(struct FileCoverageList));
1745          coverage_list->file_coverage = file_coverage;
1746          coverage_list->next = coverage->coverage_list;
1747          coverage->coverage_list = coverage_list;
1748        }
1749        else {
1750          /* sanity check */
1751          assert(strcmp(file_coverage->id, id_bytes) == 0);
1752          if (file_coverage->num_coverage_lines != array->pn_count) {
1753            result = -2;
1754            goto done;
1755          }
1756    
1757          /* merge the coverage */
1758          uint32 i = 0;
1759          for (JSParseNode * element = array->pn_head; element != NULL; element = element->pn_next, i++) {
1760            if (element->pn_type == TOK_NUMBER) {
1761              if (file_coverage->coverage_lines[i] == -1) {
1762                result = -2;
1763                goto done;
1764              }
1765              file_coverage->coverage_lines[i] += (int) element->pn_dval;
1766            }
1767            else if (element->pn_type == TOK_PRIMARY && element->pn_op == JSOP_NULL) {
1768              if (file_coverage->coverage_lines[i] != -1) {
1769                result = -2;
1770                goto done;
1771              }
1772            }
1773            else {
1774              result = -1;
1775              goto done;
1776            }
1777          }
1778          assert(i == array->pn_count);
1779        }
1780    
1781        /* if this JSON file has source, use it */
1782        if (file_coverage->source_lines == NULL && source != NULL) {
1783          file_coverage->num_source_lines = source->pn_count;
1784          file_coverage->source_lines = xnew(char *, source->pn_count);
1785          uint32 i = 0;
1786          for (JSParseNode * element = source->pn_head; element != NULL; element = element->pn_next, i++) {
1787            if (element->pn_type != TOK_STRING) {
1788              result = -1;
1789              goto done;
1790            }
1791            file_coverage->source_lines[i] = xstrdup(JS_GetStringBytes(ATOM_TO_STRING(element->pn_atom)));
1792          }
1793          assert(i == source->pn_count);
1794        }
1795      }
1796    
1797    done:
1798      js_FinishParseContext(context, &parse_context);
1799      return result;
1800  }  }

Legend:
Removed from v.92  
changed lines
  Added in v.355

  ViewVC Help
Powered by ViewVC 1.1.24