d8.js 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

String.prototype.startsWith = function (str) {
  if (str.length > this.length)
    return false;
  return this.substr(0, str.length) == str;
32 33 34 35 36
}

function log10(num) {
  return Math.log(num)/Math.log(10);
}
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

function ToInspectableObject(obj) {
  if (!obj && typeof obj === 'object') {
    return void 0;
  } else {
    return Object(obj);
  }
}

function GetCompletions(global, last, full) {
  var full_tokens = full.split();
  full = full_tokens.pop();
  var parts = full.split('.');
  parts.pop();
  var current = global;
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    var next = current[part];
    if (!next)
      return [];
    current = next;
  }
  var result = [];
  current = ToInspectableObject(current);
  while (typeof current !== 'undefined') {
    var mirror = new $debug.ObjectMirror(current);
    var properties = mirror.properties();
    for (var i = 0; i < properties.length; i++) {
      var name = properties[i].name();
      if (typeof name === 'string' && name.startsWith(last))
        result.push(name);
    }
    current = ToInspectableObject(current.__proto__);
  }
  return result;
}
73 74 75 76 77 78 79


// Global object holding debugger related constants and state.
const Debug = {};


// Debug events which can occour in the V8 JavaScript engine. These originate
80
// from the API include file v8-debug.h.
81 82 83 84 85 86 87 88 89 90 91 92 93
Debug.DebugEvent = { Break: 1,
                     Exception: 2,
                     NewFunction: 3,
                     BeforeCompile: 4,
                     AfterCompile: 5 };


// The different types of scripts matching enum ScriptType in objects.h.
Debug.ScriptType = { Native: 0,
                     Extension: 1,
                     Normal: 2 };


94 95 96 97 98 99 100
// The different types of script compilations matching enum
// Script::CompilationType in objects.h.
Debug.ScriptCompilationType = { Host: 0,
                                Eval: 1,
                                JSON: 2 };


101 102 103 104 105 106 107
// The different types of scopes matching constants runtime.cc.
Debug.ScopeType = { Global: 0,
                    Local: 1,
                    With: 2,
                    Closure: 3 };


108 109 110 111 112 113
// Current debug state.
const kNoFrame = -1;
Debug.State = {
  currentFrame: kNoFrame,
  currentSourceLine: -1
}
114
var trace_compile = false;  // Tracing all compile events?
115 116


117 118 119 120
// Process a debugger JSON message into a display text and a running status.
// This function returns an object with properties "text" and "running" holding
// this information.
function DebugMessageDetails(message) {
121
  // Convert the JSON string to an object.
122 123 124 125 126 127 128 129 130 131 132 133 134 135
  var response = new ProtocolPackage(message);

  if (response.type() == 'event') {
    return DebugEventDetails(response);
  } else {
    return DebugResponseDetails(response);
  }
}

function DebugEventDetails(response) {
  details = {text:'', running:false}

  // Get the running state.
  details.running = response.running();
136 137

  var body = response.body();
138
  var result = '';
139 140 141
  switch (response.event()) {
    case 'break':
      if (body.breakpoints) {
142
        result += 'breakpoint';
143
        if (body.breakpoints.length > 1) {
144
          result += 's';
145
        }
146
        result += ' #';
147
        for (var i = 0; i < body.breakpoints.length; i++) {
148
          if (i > 0) {
149
            result += ', #';
150
          }
151
          result += body.breakpoints[i];
152
        }
153
      } else {
154
        result += 'break';
155
      }
156 157 158 159 160 161
      result += ' in ';
      result += body.invocationText;
      result += ', ';
      result += SourceInfo(body);
      result += '\n';
      result += SourceUnderline(body.sourceLineText, body.sourceColumn);
162
      Debug.State.currentSourceLine = body.sourceLine;
163
      Debug.State.currentFrame = 0;
164 165
      details.text = result;
      break;
166 167 168
      
    case 'exception':
      if (body.uncaught) {
169
        result += 'Uncaught: ';
170
      } else {
171
        result += 'Exception: ';
172
      }
173 174 175
      result += '"';
      result += body.exception.text;
      result += '"';
176
      if (body.sourceLine >= 0) {
177 178 179 180
        result += ', ';
        result += SourceInfo(body);
        result += '\n';
        result += SourceUnderline(body.sourceLineText, body.sourceColumn);
181
        Debug.State.currentSourceLine = body.sourceLine;
182 183
        Debug.State.currentFrame = 0;
      } else {
184
        result += ' (empty stack)';
185 186 187
        Debug.State.currentSourceLine = -1;
        Debug.State.currentFrame = kNoFrame;
      }
188 189
      details.text = result;
      break;
190 191

    case 'afterCompile':
192
      if (trace_compile) {
193
        result = 'Source ' + body.script.name + ' compiled:\n'
194
        var source = body.script.source;
195
        if (!(source[source.length - 1] == '\n')) {
196
          result += source;
197
        } else {
198
          result += source.substring(0, source.length - 1);
199 200
        }
      }
201 202 203 204 205
      details.text = result;
      break;

    default:
      details.text = 'Unknown debug event ' + response.event();
206
  }
207 208

  return details;
209 210 211
};


212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
function SourceInfo(body) {
  var result = '';
  
  if (body.script) {
    if (body.script.name) {
      result += body.script.name;
    } else {
      result += '[unnamed]';
    }
  }
  result += ' line ';
  result += body.sourceLine + 1;
  result += ' column ';
  result += body.sourceColumn + 1;
  
  return result;
}


231 232 233 234 235
function SourceUnderline(source_text, position) {
  if (!source_text) {
    return;
  }

236 237 238
  // Create an underline with a caret pointing to the source position. If the
  // source contains a tab character the underline will have a tab character in
  // the same place otherwise the underline will have a space character.
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  var underline = '';
  for (var i = 0; i < position; i++) {
    if (source_text[i] == '\t') {
      underline += '\t';
    } else {
      underline += ' ';
    }
  }
  underline += '^';

  // Return the source line text with the underline beneath.
  return source_text + '\n' + underline;
};


// Converts a text command to a JSON request.
function DebugCommandToJSONRequest(cmd_line) {
  return new DebugRequest(cmd_line).JSONRequest();
};


function DebugRequest(cmd_line) {
  // If the very first character is a { assume that a JSON request have been
  // entered as a command. Converting that to a JSON request is trivial.
  if (cmd_line && cmd_line.length > 0 && cmd_line.charAt(0) == '{') {
    this.request_ = cmd_line;
    return;
  }

  // Trim string for leading and trailing whitespace.
  cmd_line = cmd_line.replace(/^\s+|\s+$/g, '');

  // Find the command.
  var pos = cmd_line.indexOf(' ');
  var cmd;
  var args;
  if (pos == -1) {
    cmd = cmd_line;
    args = '';
  } else {
    cmd = cmd_line.slice(0, pos);
    args = cmd_line.slice(pos).replace(/^\s+|\s+$/g, '');
  }

  // Switch on command.
  switch (cmd) {
    case 'continue':
    case 'c':
      this.request_ = this.continueCommandToJSONRequest_(args);
      break;

    case 'step':
    case 's':
      this.request_ = this.stepCommandToJSONRequest_(args);
      break;

    case 'backtrace':
    case 'bt':
      this.request_ = this.backtraceCommandToJSONRequest_(args);
      break;
      
    case 'frame':
    case 'f':
      this.request_ = this.frameCommandToJSONRequest_(args);
      break;
      
305 306 307 308 309 310 311 312
    case 'scopes':
      this.request_ = this.scopesCommandToJSONRequest_(args);
      break;
      
    case 'scope':
      this.request_ = this.scopeCommandToJSONRequest_(args);
      break;
      
313 314 315 316 317
    case 'print':
    case 'p':
      this.request_ = this.printCommandToJSONRequest_(args);
      break;

318 319 320 321
    case 'dir':
      this.request_ = this.dirCommandToJSONRequest_(args);
      break;

322 323 324 325 326 327 328 329
    case 'references':
      this.request_ = this.referencesCommandToJSONRequest_(args);
      break;

    case 'instances':
      this.request_ = this.instancesCommandToJSONRequest_(args);
      break;

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    case 'source':
      this.request_ = this.sourceCommandToJSONRequest_(args);
      break;
      
    case 'scripts':
      this.request_ = this.scriptsCommandToJSONRequest_(args);
      break;
      
    case 'break':
    case 'b':
      this.request_ = this.breakCommandToJSONRequest_(args);
      break;
      
    case 'clear':
      this.request_ = this.clearCommandToJSONRequest_(args);
      break;

347 348 349 350
    case 'threads':
      this.request_ = this.threadsCommandToJSONRequest_(args);
      break;

351 352 353 354 355 356
    case 'trace':
      // Return undefined to indicate command handled internally (no JSON).
      this.request_ = void 0;
      this.traceCommand_(args);
      break;

357 358 359
    case 'help':
    case '?':
      this.helpCommand_(args);
360 361
      // Return undefined to indicate command handled internally (no JSON).
      this.request_ = void 0;
362 363 364 365 366
      break;

    default:
      throw new Error('Unknown command "' + cmd + '"');
  }
367 368
  
  last_cmd = cmd;
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
}

DebugRequest.prototype.JSONRequest = function() {
  return this.request_;
}


function RequestPacket(command) {
  this.seq = 0;
  this.type = 'request';
  this.command = command;
}


RequestPacket.prototype.toJSONProtocol = function() {
  // Encode the protocol header.
  var json = '{';
  json += '"seq":' + this.seq;
  json += ',"type":"' + this.type + '"';
  if (this.command) {
    json += ',"command":' + StringToJSON_(this.command);
  }
  if (this.arguments) {
    json += ',"arguments":';
    // Encode the arguments part.
    if (this.arguments.toJSONProtocol) {
      json += this.arguments.toJSONProtocol()
    } else {
      json += SimpleObjectToJSON_(this.arguments);
    }
  }
  json += '}';
  return json;
}


DebugRequest.prototype.createRequest = function(command) {
  return new RequestPacket(command);
};


410 411
// Create a JSON request for the evaluation command.
DebugRequest.prototype.makeEvaluateJSONRequest_ = function(expression) {
412 413
  // Global varaible used to store whether a handle was requested.
  lookup_handle = null;
414 415 416
  // Check if the expression is a handle id in the form #<handle>#.
  var handle_match = expression.match(/^#([0-9]*)#$/);
  if (handle_match) {
417 418
    // Remember the handle requested in a global variable.
    lookup_handle = parseInt(handle_match[1]);
419
    // Build a lookup request.
420 421
    var request = this.createRequest('lookup');
    request.arguments = {};
422
    request.arguments.handles = [ lookup_handle ];
423 424 425 426 427 428
    return request.toJSONProtocol();
  } else {
    // Build an evaluate request.
    var request = this.createRequest('evaluate');
    request.arguments = {};
    request.arguments.expression = expression;
429 430 431 432
    // Request a global evaluation if there is no current frame.
    if (Debug.State.currentFrame == kNoFrame) {
      request.arguments.global = true;
    }
433 434 435 436 437
    return request.toJSONProtocol();
  }
};


438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
// Create a JSON request for the references/instances command.
DebugRequest.prototype.makeReferencesJSONRequest_ = function(handle, type) {
  // Build a references request.
  var handle_match = handle.match(/^#([0-9]*)#$/);
  if (handle_match) {
    var request = this.createRequest('references');
    request.arguments = {};
    request.arguments.type = type;
    request.arguments.handle = parseInt(handle_match[1]);
    return request.toJSONProtocol();
  } else {
    throw new Error('Invalid object id.');
  }
};

453

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
// Create a JSON request for the continue command.
DebugRequest.prototype.continueCommandToJSONRequest_ = function(args) {
  var request = this.createRequest('continue');
  return request.toJSONProtocol();
};


// Create a JSON request for the step command.
DebugRequest.prototype.stepCommandToJSONRequest_ = function(args) {
  // Requesting a step is through the continue command with additional
  // arguments.
  var request = this.createRequest('continue');
  request.arguments = {};

  // Process arguments if any.
  if (args && args.length > 0) {
    args = args.split(/\s*[ ]+\s*/g);

    if (args.length > 2) {
      throw new Error('Invalid step arguments.');
    }

    if (args.length > 0) {
      // Get step count argument if any.
      if (args.length == 2) {
        var stepcount = parseInt(args[1]);
        if (isNaN(stepcount) || stepcount <= 0) {
          throw new Error('Invalid step count argument "' + args[0] + '".');
        }
        request.arguments.stepcount = stepcount;
      }

      // Get the step action.
      switch (args[0]) {
        case 'in':
        case 'i':
          request.arguments.stepaction = 'in';
          break;
          
        case 'min':
        case 'm':
          request.arguments.stepaction = 'min';
          break;
          
        case 'next':
        case 'n':
          request.arguments.stepaction = 'next';
          break;
          
        case 'out':
        case 'o':
          request.arguments.stepaction = 'out';
          break;
          
        default:
          throw new Error('Invalid step argument "' + args[0] + '".');
      }
    }
  } else {
    // Default is step next.
    request.arguments.stepaction = 'next';
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the backtrace command.
DebugRequest.prototype.backtraceCommandToJSONRequest_ = function(args) {
  // Build a backtrace request from the text command.
  var request = this.createRequest('backtrace');
525 526 527 528 529 530
  
  // Default is to show top 10 frames.
  request.arguments = {};
  request.arguments.fromFrame = 0;
  request.arguments.toFrame = 10;

531
  args = args.split(/\s*[ ]+\s*/g);
532 533 534 535 536 537 538 539 540 541 542 543 544
  if (args.length == 1 && args[0].length > 0) {
    var frameCount = parseInt(args[0]);
    if (frameCount > 0) {
      // Show top frames.
      request.arguments.fromFrame = 0;
      request.arguments.toFrame = frameCount;
    } else {
      // Show bottom frames.
      request.arguments.fromFrame = 0;
      request.arguments.toFrame = -frameCount;
      request.arguments.bottom = true;
    }
  } else if (args.length == 2) {
545 546 547 548 549 550 551 552 553 554 555 556
    var fromFrame = parseInt(args[0]);
    var toFrame = parseInt(args[1]);
    if (isNaN(fromFrame) || fromFrame < 0) {
      throw new Error('Invalid start frame argument "' + args[0] + '".');
    }
    if (isNaN(toFrame) || toFrame < 0) {
      throw new Error('Invalid end frame argument "' + args[1] + '".');
    }
    if (fromFrame > toFrame) {
      throw new Error('Invalid arguments start frame cannot be larger ' +
                      'than end frame.');
    }
557
    // Show frame range.
558 559
    request.arguments.fromFrame = fromFrame;
    request.arguments.toFrame = toFrame + 1;
560 561
  } else if (args.length > 2) {
    throw new Error('Invalid backtrace arguments.');
562
  }
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
  return request.toJSONProtocol();
};


// Create a JSON request for the frame command.
DebugRequest.prototype.frameCommandToJSONRequest_ = function(args) {
  // Build a frame request from the text command.
  var request = this.createRequest('frame');
  args = args.split(/\s*[ ]+\s*/g);
  if (args.length > 0 && args[0].length > 0) {
    request.arguments = {};
    request.arguments.number = args[0];
  }
  return request.toJSONProtocol();
};


581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
// Create a JSON request for the scopes command.
DebugRequest.prototype.scopesCommandToJSONRequest_ = function(args) {
  // Build a scopes request from the text command.
  var request = this.createRequest('scopes');
  return request.toJSONProtocol();
};


// Create a JSON request for the scope command.
DebugRequest.prototype.scopeCommandToJSONRequest_ = function(args) {
  // Build a scope request from the text command.
  var request = this.createRequest('scope');
  args = args.split(/\s*[ ]+\s*/g);
  if (args.length > 0 && args[0].length > 0) {
    request.arguments = {};
    request.arguments.number = args[0];
  }
  return request.toJSONProtocol();
};


602 603
// Create a JSON request for the print command.
DebugRequest.prototype.printCommandToJSONRequest_ = function(args) {
604
  // Build an evaluate request from the text command.
605 606 607
  if (args.length == 0) {
    throw new Error('Missing expression.');
  }
608 609
  return this.makeEvaluateJSONRequest_(args);
};
610 611


612 613 614 615 616 617 618
// Create a JSON request for the dir command.
DebugRequest.prototype.dirCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing expression.');
  }
  return this.makeEvaluateJSONRequest_(args);
619 620 621
};


622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
// Create a JSON request for the references command.
DebugRequest.prototype.referencesCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing object id.');
  }
  
  return this.makeReferencesJSONRequest_(args, 'referencedBy');
};


// Create a JSON request for the instances command.
DebugRequest.prototype.instancesCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing object id.');
  }
  
  // Build a references request.
  return this.makeReferencesJSONRequest_(args, 'constructedBy');
};


645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
// Create a JSON request for the source command.
DebugRequest.prototype.sourceCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('source');

  // Default is ten lines starting five lines before the current location.
  var from = Debug.State.currentSourceLine - 5;
  var lines = 10;

  // Parse the arguments.
  args = args.split(/\s*[ ]+\s*/g);
  if (args.length > 1 && args[0].length > 0 && args[1].length > 0) {
    from = parseInt(args[0]) - 1;
    lines = parseInt(args[1]);
  } else if (args.length > 0 && args[0].length > 0) {
    from = parseInt(args[0]) - 1;
  }

  if (from < 0) from = 0;
  if (lines < 0) lines = 10;

  // Request source arround current source location.
  request.arguments = {};
  request.arguments.fromLine = from;
  request.arguments.toLine = from + lines;

  return request.toJSONProtocol();
};


// Create a JSON request for the scripts command.
DebugRequest.prototype.scriptsCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('scripts');

  // Process arguments if any.
  if (args && args.length > 0) {
    args = args.split(/\s*[ ]+\s*/g);

    if (args.length > 1) {
      throw new Error('Invalid scripts arguments.');
    }

    request.arguments = {};
    switch (args[0]) {
      case 'natives':
        request.arguments.types = ScriptTypeFlag(Debug.ScriptType.Native);
        break;
        
      case 'extensions':
        request.arguments.types = ScriptTypeFlag(Debug.ScriptType.Extension);
        break;
        
      case 'all':
        request.arguments.types =
            ScriptTypeFlag(Debug.ScriptType.Normal) |
            ScriptTypeFlag(Debug.ScriptType.Native) |
            ScriptTypeFlag(Debug.ScriptType.Extension);
        break;
        
      default:
        throw new Error('Invalid argument "' + args[0] + '".');
    }
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the break command.
DebugRequest.prototype.breakCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('setbreakpoint');

  // Process arguments if any.
  if (args && args.length > 0) {
    var target = args;
722 723 724
    var type = 'function';
    var line;
    var column;
725
    var condition;
726
    var pos;
727

728 729
    // Check for breakpoint condition.
    pos = args.indexOf(' ');
730 731 732 733 734
    if (pos > 0) {
      target = args.substring(0, pos);
      condition = args.substring(pos + 1, args.length);
    }

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
    // Check for script breakpoint (name:line[:column]). If no ':' in break
    // specification it is considered a function break point.
    pos = target.indexOf(':');
    if (pos > 0) {
      type = 'script';
      var tmp = target.substring(pos + 1, target.length);
      target = target.substring(0, pos);
      
      // Check for both line and column.
      pos = tmp.indexOf(':');
      if (pos > 0) {
        column = parseInt(tmp.substring(pos + 1, tmp.length)) - 1;
        line = parseInt(tmp.substring(0, pos)) - 1;
      } else {
        line = parseInt(tmp) - 1;
      }
    } else if (target[0] == '#' && target[target.length - 1] == '#') {
      type = 'handle';
      target = target.substring(1, target.length - 1);
    } else {
      type = 'function';
    }
  
758
    request.arguments = {};
759
    request.arguments.type = type;
760
    request.arguments.target = target;
761 762
    request.arguments.line = line;
    request.arguments.column = column;
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
    request.arguments.condition = condition;
  } else {
    throw new Error('Invalid break arguments.');
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the clear command.
DebugRequest.prototype.clearCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('clearbreakpoint');

  // Process arguments if any.
  if (args && args.length > 0) {
    request.arguments = {};
    request.arguments.breakpoint = parseInt(args);
  } else {
    throw new Error('Invalid break arguments.');
  }

  return request.toJSONProtocol();
};


789 790 791 792 793 794 795 796
// Create a JSON request for the threads command.
DebugRequest.prototype.threadsCommandToJSONRequest_ = function(args) {
  // Build a threads request from the text command.
  var request = this.createRequest('threads');
  return request.toJSONProtocol();
};


797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
// Handle the trace command.
DebugRequest.prototype.traceCommand_ = function(args) {
  // Process arguments.
  if (args && args.length > 0) {
    if (args == 'compile') {
      trace_compile = !trace_compile;
      print('Tracing of compiled scripts ' + (trace_compile ? 'on' : 'off'));
    } else {
      throw new Error('Invalid trace arguments.');
    }
  } else {
    throw new Error('Invalid trace arguments.');
  }
}

// Handle the help command.
813 814 815 816 817 818 819
DebugRequest.prototype.helpCommand_ = function(args) {
  // Help os quite simple.
  if (args && args.length > 0) {
    print('warning: arguments to \'help\' are ignored');
  }

  print('break location [condition]');
820 821 822
  print('  break on named function: location is a function name');
  print('  break on function: location is #<id>#');
  print('  break on script position: location is name:line[:column]');
823
  print('clear <breakpoint #>');
824
  print('backtrace [n] | [-n] | [from to]');
825
  print('frame <frame #>');
826 827
  print('scopes');
  print('scope <scope #>');
828 829
  print('step [in | next | out| min [step count]]');
  print('print <expression>');
830
  print('dir <expression>');
831 832 833
  print('source [from line [num lines]]');
  print('scripts');
  print('continue');
834
  print('trace compile');
835 836 837 838
  print('help');
}


839
function formatHandleReference_(value) {
840 841 842 843 844
  if (value.handle() >= 0) {
    return '#' + value.handle() + '#';
  } else {
    return '#Transient#';
  }
845 846 847
}


848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
function formatObject_(value, include_properties) {
  var result = '';
  result += formatHandleReference_(value);
  result += ', type: object'
  result += ', constructor ';
  var ctor = value.constructorFunctionValue();
  result += formatHandleReference_(ctor);
  result += ', __proto__ ';
  var proto = value.protoObjectValue();
  result += formatHandleReference_(proto);
  result += ', ';
  result += value.propertyCount();
  result +=  ' properties.';
  if (include_properties) {
    result +=  '\n';
    for (var i = 0; i < value.propertyCount(); i++) {
      result += '  ';
      result += value.propertyName(i);
      result += ': ';
      var property_value = value.propertyValue(i);
868
      if (property_value instanceof ProtocolReference) {
869
        result += '<no type>';
870 871 872 873 874 875
      } else {
        if (property_value && property_value.type()) {
          result += property_value.type();
        } else {
          result += '<no type>';
        }
876 877 878 879 880 881 882 883 884 885
      }
      result += ' ';
      result += formatHandleReference_(property_value);
      result += '\n';
    }
  }
  return result;
}


886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
function formatScope_(scope) {
  var result = '';
  var index = scope.index;
  result += '#' + (index <= 9 ? '0' : '') + index;
  result += ' ';
  switch (scope.type) {
    case Debug.ScopeType.Global:
      result += 'Global, ';
      result += '#' + scope.object.ref + '#';
      break;
    case Debug.ScopeType.Local:
      result += 'Local';
      break;
    case Debug.ScopeType.With:
      result += 'With, ';
      result += '#' + scope.object.ref + '#';
      break;
    case Debug.ScopeType.Closure:
      result += 'Closure';
      break;
    default:
      result += 'UNKNOWN';
  }
  return result;
}


913
// Convert a JSON response to text for display in a text based debugger.
914
function DebugResponseDetails(response) {
915 916 917
  details = {text:'', running:false}

  try {
918 919
    if (!response.success()) {
      details.text = response.message();
920 921 922 923
      return details;
    }

    // Get the running state.
924
    details.running = response.running();
925

926 927 928
    var body = response.body();
    var result = '';
    switch (response.command()) {
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
      case 'setbreakpoint':
        result = 'set breakpoint #';
        result += body.breakpoint;
        details.text = result;
        break;
        
      case 'clearbreakpoint':
        result = 'cleared breakpoint #';
        result += body.breakpoint;
        details.text = result;
        break;
        
      case 'backtrace':
        if (body.totalFrames == 0) {
          result = '(empty stack)';
        } else {
          var result = 'Frames #' + body.fromFrame + ' to #' +
              (body.toFrame - 1) + ' of ' + body.totalFrames + '\n';
          for (i = 0; i < body.frames.length; i++) {
            if (i != 0) result += '\n';
            result += body.frames[i].text;
          }
        }
        details.text = result;
        break;
        
      case 'frame':
956 957 958 959
        details.text = SourceUnderline(body.sourceLineText,
                                       body.column);
        Debug.State.currentSourceLine = body.line;
        Debug.State.currentFrame = body.index;
960 961
        break;
        
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
      case 'scopes':
        if (body.totalScopes == 0) {
          result = '(no scopes)';
        } else {
          result = 'Scopes #' + body.fromScope + ' to #' +
                   (body.toScope - 1) + ' of ' + body.totalScopes + '\n';
          for (i = 0; i < body.scopes.length; i++) {
            if (i != 0) {
              result += '\n';
            }
            result += formatScope_(body.scopes[i]);
          }
        }
        details.text = result;
        break;

      case 'scope':
        result += formatScope_(body);
        result += '\n';
        var scope_object_value = response.lookup(body.object.ref);
        result += formatObject_(scope_object_value, true);
        details.text = result;
        break;
      
986
      case 'evaluate':
987 988
      case 'lookup':
        if (last_cmd == 'p' || last_cmd == 'print') {
989
          result = body.text;
990
        } else {
991 992 993 994 995 996
          var value;
          if (lookup_handle) {
            value = response.bodyValue(lookup_handle);
          } else {
            value = response.bodyValue();
          }
997
          if (value.isObject()) {
998
            result += formatObject_(value, true);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
          } else {
            result += 'type: ';
            result += value.type();
            if (!value.isUndefined() && !value.isNull()) {
              result += ', ';
              if (value.isString()) {
                result += '"';
              }
              result += value.value();
              if (value.isString()) {
                result += '"';
              }
            }
            result += '\n';
          }
        }
        details.text = result;
1016
        break;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

      case 'references':
        var count = body.length;
        result += 'found ' + count + ' objects';
        result += '\n';
        for (var i = 0; i < count; i++) {
          var value = response.bodyValue(i);
          result += formatObject_(value, false);
          result += '\n';
        }
        details.text = result;
        break;
1029 1030 1031
        
      case 'source':
        // Get the source from the response.
1032 1033
        var source = body.source;
        var from_line = body.fromLine + 1;
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
        var lines = source.split('\n');
        var maxdigits = 1 + Math.floor(log10(from_line + lines.length));
        if (maxdigits < 3) {
          maxdigits = 3;
        }
        var result = '';
        for (var num = 0; num < lines.length; num++) {
          // Check if there's an extra newline at the end.
          if (num == (lines.length - 1) && lines[num].length == 0) {
            break;
          }

          var current_line = from_line + num;
          spacer = maxdigits - (1 + Math.floor(log10(current_line)));
          if (current_line == Debug.State.currentSourceLine + 1) {
            for (var i = 0; i < maxdigits; i++) {
              result += '>';
            }
            result += '  ';
          } else {
            for (var i = 0; i < spacer; i++) {
              result += ' ';
            }
            result += current_line + ': ';
          }
          result += lines[num];
          result += '\n';
        }
        details.text = result;
        break;
        
      case 'scripts':
        var result = '';
1067
        for (i = 0; i < body.length; i++) {
1068
          if (i != 0) result += '\n';
1069 1070 1071 1072 1073 1074
          if (body[i].id) {
            result += body[i].id;
          } else {
            result += '[no id]';
          }
          result += ', ';
1075 1076
          if (body[i].name) {
            result += body[i].name;
1077
          } else {
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
            if (body[i].compilationType == Debug.ScriptCompilationType.Eval) {
              result += 'eval from ';
              var script_value = response.lookup(body[i].evalFromScript.ref);
              result += ' ' + script_value.field('name');
              result += ':' + (body[i].evalFromLocation.line + 1);
              result += ':' + body[i].evalFromLocation.column;
            } else if (body[i].compilationType ==
                       Debug.ScriptCompilationType.JSON) {
              result += 'JSON ';
            } else {  // body[i].compilation == Debug.ScriptCompilationType.Host
              result += '[unnamed] ';
            }
1090 1091
          }
          result += ' (lines: ';
1092
          result += body[i].lineCount;
1093
          result += ', length: ';
1094 1095
          result += body[i].sourceLength;
          if (body[i].type == Debug.ScriptType.Native) {
1096
            result += ', native';
1097
          } else if (body[i].type == Debug.ScriptType.Extension) {
1098 1099
            result += ', extension';
          }
1100 1101 1102 1103 1104 1105 1106
          result += '), [';
          var sourceStart = body[i].sourceStart;
          if (sourceStart.length > 40) {
            sourceStart = sourceStart.substring(0, 37) + '...';
          }
          result += sourceStart;
          result += ']';
1107 1108 1109 1110
        }
        details.text = result;
        break;

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
      case 'threads':
        var result = 'Active V8 threads: ' + body.totalThreads + '\n';
        body.threads.sort(function(a, b) { return a.id - b.id; });
        for (i = 0; i < body.threads.length; i++) {
          result += body.threads[i].current ? '*' : ' ';
          result += ' ';
          result += body.threads[i].id;
          result += '\n';
        }
        details.text = result;
        break;

1123 1124 1125 1126
      case 'continue':
        details.text = "(running)";
        break;
        
1127 1128
      default:
        details.text =
1129 1130
            'Response for unknown command \'' + response.command + '\'' +
            ' (' + json_response + ')';
1131 1132 1133 1134 1135 1136 1137 1138 1139
    }
  } catch (e) {
    details.text = 'Error: "' + e + '" formatting response';
  }
  
  return details;
};


1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
/**
 * Protocol packages send from the debugger.
 * @param {string} json - raw protocol packet as JSON string.
 * @constructor
 */
function ProtocolPackage(json) {
  this.packet_ = eval('(' + json + ')');
  this.refs_ = [];
  if (this.packet_.refs) {
    for (var i = 0; i < this.packet_.refs.length; i++) {
      this.refs_[this.packet_.refs[i].handle] = this.packet_.refs[i];
    }
  }
}


/**
 * Get the packet type.
 * @return {String} the packet type
 */
ProtocolPackage.prototype.type = function() {
  return this.packet_.type;
}


/**
 * Get the packet event.
 * @return {Object} the packet event
 */
ProtocolPackage.prototype.event = function() {
  return this.packet_.event;
}


/**
 * Get the packet request sequence.
 * @return {number} the packet request sequence
 */
ProtocolPackage.prototype.requestSeq = function() {
  return this.packet_.request_seq;
}


/**
 * Get the packet request sequence.
 * @return {number} the packet request sequence
 */
ProtocolPackage.prototype.running = function() {
  return this.packet_.running ? true : false;
}


ProtocolPackage.prototype.success = function() {
  return this.packet_.success ? true : false;
}


ProtocolPackage.prototype.message = function() {
  return this.packet_.message;
}


ProtocolPackage.prototype.command = function() {
  return this.packet_.command;
}


ProtocolPackage.prototype.body = function() {
  return this.packet_.body;
}


1212
ProtocolPackage.prototype.bodyValue = function(index) {
1213
  if (index != null) {
1214
    return new ProtocolValue(this.packet_.body[index], this);
1215 1216
  } else {
    return new ProtocolValue(this.packet_.body, this);
1217
  }
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
}


ProtocolPackage.prototype.body = function() {
  return this.packet_.body;
}


ProtocolPackage.prototype.lookup = function(handle) {
  var value = this.refs_[handle];
  if (value) {
    return new ProtocolValue(value, this);
  } else {
    return new ProtocolReference(handle);
  }
}


function ProtocolValue(value, packet) {
  this.value_ = value;
  this.packet_ = packet;
}


/**
 * Get the value type.
 * @return {String} the value type
 */
ProtocolValue.prototype.type = function() {
  return this.value_.type;
}


1251 1252 1253 1254 1255 1256 1257 1258 1259
/**
 * Get a metadata field from a protocol value. 
 * @return {Object} the metadata field value
 */
ProtocolValue.prototype.field = function(name) {
  return this.value_[name];
}


1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
/**
 * Check is the value is a primitive value.
 * @return {boolean} true if the value is primitive
 */
ProtocolValue.prototype.isPrimitive = function() {
  return this.isUndefined() || this.isNull() || this.isBoolean() ||
         this.isNumber() || this.isString();
}


/**
 * Get the object handle.
 * @return {number} the value handle
 */
ProtocolValue.prototype.handle = function() {
  return this.value_.handle;
}


/**
 * Check is the value is undefined.
 * @return {boolean} true if the value is undefined
 */
ProtocolValue.prototype.isUndefined = function() {
  return this.value_.type == 'undefined';
}


/**
 * Check is the value is null.
 * @return {boolean} true if the value is null
 */
ProtocolValue.prototype.isNull = function() {
  return this.value_.type == 'null';
}


/**
 * Check is the value is a boolean.
 * @return {boolean} true if the value is a boolean
 */
ProtocolValue.prototype.isBoolean = function() {
  return this.value_.type == 'boolean';
}


/**
 * Check is the value is a number.
 * @return {boolean} true if the value is a number
 */
ProtocolValue.prototype.isNumber = function() {
  return this.value_.type == 'number';
}


/**
 * Check is the value is a string.
 * @return {boolean} true if the value is a string
 */
ProtocolValue.prototype.isString = function() {
  return this.value_.type == 'string';
}


/**
 * Check is the value is an object.
 * @return {boolean} true if the value is an object
 */
ProtocolValue.prototype.isObject = function() {
  return this.value_.type == 'object' || this.value_.type == 'function' ||
         this.value_.type == 'error' || this.value_.type == 'regexp';
}


/**
 * Get the constructor function
 * @return {ProtocolValue} constructor function
 */
ProtocolValue.prototype.constructorFunctionValue = function() {
  var ctor = this.value_.constructorFunction;
  return this.packet_.lookup(ctor.ref);
}


/**
 * Get the __proto__ value
 * @return {ProtocolValue} __proto__ value
 */
ProtocolValue.prototype.protoObjectValue = function() {
  var proto = this.value_.protoObject;
  return this.packet_.lookup(proto.ref);
}


/**
 * Get the number og properties.
 * @return {number} the number of properties
 */
ProtocolValue.prototype.propertyCount = function() {
  return this.value_.properties ? this.value_.properties.length : 0;
}


/**
 * Get the specified property name.
 * @return {string} property name
 */
ProtocolValue.prototype.propertyName = function(index) {
  var property = this.value_.properties[index];
  return property.name;
}


/**
 * Return index for the property name.
 * @param name The property name to look for
 * @return {number} index for the property name
 */
ProtocolValue.prototype.propertyIndex = function(name) {
  for (var i = 0; i < this.propertyCount(); i++) {
    if (this.value_.properties[i].name == name) {
      return i;
    }
  }
  return null;
}


/**
 * Get the specified property value.
 * @return {ProtocolValue} property value
 */
ProtocolValue.prototype.propertyValue = function(index) {
  var property = this.value_.properties[index];
  return this.packet_.lookup(property.ref);
}


/**
 * Check is the value is a string.
 * @return {boolean} true if the value is a string
 */
ProtocolValue.prototype.value = function() {
  return this.value_.value;
}


function ProtocolReference(handle) {
  this.handle_ = handle;
}


ProtocolReference.prototype.handle = function() {
  return this.handle_;
}


1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
function MakeJSONPair_(name, value) {
  return '"' + name + '":' + value;
}


function ArrayToJSONObject_(content) {
  return '{' + content.join(',') + '}';
}


function ArrayToJSONArray_(content) {
  return '[' + content.join(',') + ']';
}


function BooleanToJSON_(value) {
  return String(value); 
}


function NumberToJSON_(value) {
  return String(value); 
}


// Mapping of some control characters to avoid the \uXXXX syntax for most
// commonly used control cahracters.
const ctrlCharMap_ = {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '"' : '\\"',
  '\\': '\\\\'
};


// Regular expression testing for ", \ and control characters (0x00 - 0x1F).
const ctrlCharTest_ = new RegExp('["\\\\\x00-\x1F]');


// Regular expression matching ", \ and control characters (0x00 - 0x1F)
// globally.
const ctrlCharMatch_ = new RegExp('["\\\\\x00-\x1F]', 'g');


/**
 * Convert a String to its JSON representation (see http://www.json.org/). To
 * avoid depending on the String object this method calls the functions in
 * string.js directly and not through the value.
 * @param {String} value The String value to format as JSON
 * @return {string} JSON formatted String value
 */
function StringToJSON_(value) {
  // Check for" , \ and control characters (0x00 - 0x1F). No need to call
  // RegExpTest as ctrlchar is constructed using RegExp.
  if (ctrlCharTest_.test(value)) {
    // Replace ", \ and control characters (0x00 - 0x1F).
    return '"' +
      value.replace(ctrlCharMatch_, function (char) {
        // Use charmap if possible.
        var mapped = ctrlCharMap_[char];
        if (mapped) return mapped;
        mapped = char.charCodeAt();
        // Convert control character to unicode escape sequence.
        return '\\u00' +
          '0' + // TODO %NumberToRadixString(Math.floor(mapped / 16), 16) +
          '0' // TODO %NumberToRadixString(mapped % 16, 16);
      })
    + '"';
  }

  // Simple string with no special characters.
  return '"' + value + '"';
}


/**
 * Convert a Date to ISO 8601 format. To avoid depending on the Date object
 * this method calls the functions in date.js directly and not through the
 * value.
 * @param {Date} value The Date value to format as JSON
 * @return {string} JSON formatted Date value
 */
function DateToISO8601_(value) {
  function f(n) {
    return n < 10 ? '0' + n : n;
  }
  function g(n) {
    return n < 10 ? '00' + n : n < 100 ? '0' + n : n;
  }
  return builtins.GetUTCFullYearFrom(value)         + '-' +
          f(builtins.GetUTCMonthFrom(value) + 1)    + '-' +
          f(builtins.GetUTCDateFrom(value))         + 'T' +
          f(builtins.GetUTCHoursFrom(value))        + ':' +
          f(builtins.GetUTCMinutesFrom(value))      + ':' +
          f(builtins.GetUTCSecondsFrom(value))      + '.' +
          g(builtins.GetUTCMillisecondsFrom(value)) + 'Z';
}


/**
 * Convert a Date to ISO 8601 format. To avoid depending on the Date object
 * this method calls the functions in date.js directly and not through the
 * value.
 * @param {Date} value The Date value to format as JSON
 * @return {string} JSON formatted Date value
 */
function DateToJSON_(value) {
  return '"' + DateToISO8601_(value) + '"';
}


/**
 * Convert an Object to its JSON representation (see http://www.json.org/).
 * This implementation simply runs through all string property names and adds
 * each property to the JSON representation for some predefined types. For type
 * "object" the function calls itself recursively unless the object has the
 * function property "toJSONProtocol" in which case that is used. This is not
 * a general implementation but sufficient for the debugger. Note that circular
 * structures will cause infinite recursion.
 * @param {Object} object The object to format as JSON
 * @return {string} JSON formatted object value
 */
function SimpleObjectToJSON_(object) {
  var content = [];
  for (var key in object) {
    // Only consider string keys.
    if (typeof key == 'string') {
      var property_value = object[key];

      // Format the value based on its type.
      var property_value_json;
      switch (typeof property_value) {
        case 'object':
          if (typeof property_value.toJSONProtocol == 'function') {
            property_value_json = property_value.toJSONProtocol(true)
          } else if (property_value.constructor.name == 'Array'){
            property_value_json = SimpleArrayToJSON_(property_value);
          } else {
            property_value_json = SimpleObjectToJSON_(property_value);
          }
          break;

        case 'boolean':
          property_value_json = BooleanToJSON_(property_value);
          break;

        case 'number':
          property_value_json = NumberToJSON_(property_value);
          break;

        case 'string':
          property_value_json = StringToJSON_(property_value);
          break;

        default:
          property_value_json = null;
      }

      // Add the property if relevant.
      if (property_value_json) {
        content.push(StringToJSON_(key) + ':' + property_value_json);
      }
    }
  }

  // Make JSON object representation.
  return '{' + content.join(',') + '}';
}


/**
 * Convert an array to its JSON representation. This is a VERY simple
 * implementation just to support what is needed for the debugger.
 * @param {Array} arrya The array to format as JSON
 * @return {string} JSON formatted array value
 */
function SimpleArrayToJSON_(array) {
  // Make JSON array representation.
  var json = '[';
  for (var i = 0; i < array.length; i++) {
    if (i != 0) {
      json += ',';
    }
    var elem = array[i];
    if (elem.toJSONProtocol) {
      json += elem.toJSONProtocol(true)
    } else if (typeof(elem) === 'object')  {
      json += SimpleObjectToJSON_(elem);
    } else if (typeof(elem) === 'boolean')  {
      json += BooleanToJSON_(elem);
    } else if (typeof(elem) === 'number')  {
      json += NumberToJSON_(elem);
    } else if (typeof(elem) === 'string')  {
      json += StringToJSON_(elem);
    } else {
      json += elem;
    }
  }
  json += ']';
  return json;
}