Code coverage report for lib/ast.js

Statements: 7.11% (29 / 408)      Branches: 0% (0 / 228)      Functions: 0% (0 / 40)      Lines: 7.14% (29 / 406)      Ignored: none     

All files » lib/ » ast.js
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 32 33 34 35 36 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 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 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 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 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 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 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 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 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 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 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 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091          1 1 1 1 1 1 1 1 1 1 1 1 1       1       1                         1               1                                     1                                           1                                                                                                                                                   1             1                                                                                                                                                                                                                                                                                                                                                                                             1                       1                                                                                                                                                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1                     1       1 1 1  
 
/**
 * @module firedoc
 */
 
const _ = require('underscore');
const fs = require('graceful-fs');
const path = require('path');
const utils = require('./utils');
const debug = require('debug')('firedoc:ast');
const ParserContext = require('./context').ParserContext;
const CWD = process.cwd();
const REGEX_TYPE = /(.*?)\{(.*?)\}(.*)/;
const REGEX_LINES = /\r\n|\n/;
const REGEX_GLOBAL_LINES = /\r\n|\n/g;
const REGEX_FIRSTWORD = /^\s*?(\[([^\[\]]+)\]\*?|[^\s]+)\s*\-?\s*(.*)/;
const REGEX_OPTIONAL = /^\[(.*)\]$/;
const REGEX_START_COMMENT = {
  js: /^\s*\/\*\*/,
  coffee: /^\s*###\*/
};
const REGEX_END_COMMENT = {
  js: /\*\/\s*$/,
  coffee: /###\s*$/
};
const REGEX_LINE_HEAD_CHAR = {
  js: /^\s*\*/,
  coffee: /^\s*[#\*]/
};
 
/**
 * A list of ignored tags. These tags should be ignored because there is
 * likely to be used for purposes other than JSDoc tags in JavaScript comments.
 * @property IGNORE_TAGLIST
 * @type Array
 * @final
 * @for DocParser
 */
const IGNORE_TAGLIST = ['media'];
 
/**
 * Common errors will get scrubbed instead of being ignored.
 * @property CORRECTIONS
 * @type Object
 * @final
 */
const CORRECTIONS = {
  'augments': 'uses', // YUI convention for prototype mixins
  'depreciated': 'deprecated', // subtle difference
  'desciption': 'description', // shouldn't need the @description tag at all
  'extend': 'extends', // typo
  'function': 'method', // we may want standalone inner functions at some point
  'member': 'method', // probably meant method
  'parm': 'param', // typo
  'params': 'param', // typo
  'pamra': 'param', // typo
  'parma': 'param', // typo
  'propery': 'property', // typo
  'prop': 'property', // probably meant property
  'returns': 'return' // need to standardize on one or the other
};
 
/**
 *
 */
const SHORT_TAGS = {
  'async': 1,
  'beta': 1,
  'chainable': 1,
  'extends': 1,
  'final': 1,
  'static': 1,
  'optional': 1,
  'required': 1
};
 
 
/**
 * A list of known tags.  This populates a member variable
 * during initialization, and will be updated if additional
 * digesters are added.
 *
 * @property TAGLIST
 * @type Array
 * @final
 * @for DocParser
 */
const TAGLIST = [
  "async",        // bool, custom events can fire the listeners in a setTimeout
  "author",       // author best for projects and modules, but can be used anywhere // multi
  "attribute",    // YUI attributes -- get/set with change notification, etc
  "beta",         // module maturity identifier
  "broadcast",    // bool, events
  "bubbles",      // custom events that bubble
  "callback",     // callback defines
  "category",     // modules can be in multiple categories
  "chainable",    // methods that return the host object
  "class",        // pseudo class
  "conditional",  // conditional module
  "config",       // a config param (not an attribute, so no change events)
  "const",        // not standardized yet, converts to final property
  "constructs",   // factory methods (not yet used)
  "constructor",  // this is a constructor
  "contributor",  // like author
  "default",      // property/attribute default value
  "deprecated",   // please specify what to use instead
  "description",  // can also be free text at the beginning of a comment is
  "emitfacade",   // bool, YUI custom event can have a dom-like event facade
  "enum",         // pseudo enum
  "event",        // YUI custom event
  "evil",         // uses eval
  "extension",    // this is an extension for [entity]
  "extensionfor", // this is an extension for [entity]
  "extension_for",// this is an extension for [entity]
  "example",      // 0..n code snippets.  snippets can also be embedded in the desc
  "experimental", // module maturity identifier
  "extends",      // pseudo inheritance
  "file",         // file name (used by the parser)
  "final",        // not meant to be changed
  "fireonce",     // bool, YUI custom event config allows
  "for",          // used to change class context
  "global",       // declare your globals
  "icon",         // project icon(s)
  "in",           // indicates module this lives in (obsolete now)
  "initonly",     // attribute writeonce value
  "injects",      // injects {HTML|script|CSS}
  "knownissue",   // 0..n known issues for your consumption
  "line",         // line number for the comment block (used by the parser)
  "method",       // a method
  "module",       // YUI module name
  "main",         // Description for the module
  "optional",     // For optional attributes
  "required",     // For required attributes
  "param",        // member param
  "plugin",       // this is a plugin for [entityl]
  "preventable",  // YUI custom events can be preventable ala DOM events
  "private",      // > access
  'process',      // instance runtime
  "project",      // project definition, one per source tree allowed
  'logo',         // project logo
  "property",     // a regular-ole property
  "protected",    // > access
  "public",       // > access
  "queuable",     // bool, events
  "readonly",     // YUI attribute config
  "requires",     // YUI module requirements
  "return",       // {type} return desc -- returns is converted to this
  "see",          // 0..n things to look at
  "since",        // when it was introduced
  "static",       // static
  "submodule",    // YUI submodule
  "throws",       // {execption type} description
  "title",        // this should be something for the project description
  "todo",         // 0..n things to revisit eventually (hopefully)
  "type",         // the var type
  "url",          // project url(s)
  "uses",         // 0..n compents mixed (usually, via augment) into the prototype
  "value",        // the value of a constant
  "writeonce"     // YUI attribute config
];
 
var InitialAST;
 
/**
 * The AST(Abstract syntax tree) of the comment
 *
 * @class AST
 */
var AST = {
  
  /**
   * @property {Object} project - About the project
   */
  project: {},
 
  /**
   * @property {Object} files - The files
   */
  files: {},
 
  /**
   * @property {Object} codes - The source codes
   */
  codes: {},
 
  /**
   * @property {Object} modules - The modules
   */
  modules: {},
 
  /**
   * @property {Object} classes - The classes
   */
  classes: {},
 
  /**
   * @property {Array} members - The members
   */
  members: [],
 
  /**
   * @property {Array} inheritedMembers - The inherited members
   */
  inheritedMembers: [],
 
  /**
   * @property {Object} namespacesMap - The namespaces map object
   */
  namespacesMap: {},
 
  /**
   * @property {Object} commentsMap - The comments map object
   */
  commentsMap: {},
 
  /**
   * @property {String} syntaxType - The syntax type
   */
  syntaxType: 'js',
 
  /**
   * @property {Context} context - The context object
   */
  context: null,
 
  /**
   * @proerty {Array} warnings - The parser warnings
   */
  warnings: [],
 
  /**
   * Create a AST object
   *
   * @method create
   * @param {Object} files - The files
   * @param {Object} dirs - The directorys
   * @param {String} [syntaxType] - The syntax type: `coffee` or `js`
   * @return {AST} the created AST object
   */
  create: function (files, dirs, syntaxType) {
    var instance = AST;
    instance.syntaxType = syntaxType || instance.syntaxType;
    instance.context = ParserContext;
    instance.context.ast = instance;
    instance.extract(files, dirs);
    instance.transform();
    return instance;
  },
 
  /**
   * Reset the AST instance
   *
   * @method reset
   */
  reset: function () {
    AST.project = {};
    AST.files = {};
    AST.codes = {};
    AST.modules = {};
    AST.classes = {};
    AST.members = [];
    AST.inheritedMembers = [];
    AST.commentsMap = {};
    AST.syntaxType = 'js';
    AST.warnings = [];
    if (AST.context && AST.context.reset) {
      AST.context.reset();
      AST.context = null;
    }
    return AST;
  },
 
  /**
   *
   * @method oncomment
   * @param {String} comment
   * @param {String} filename
   * @param {String} linenum
   * @return {Object}
   */
  oncomment: function (comment, filename, linenum) {
    var lines = comment.split(REGEX_LINES);
    const len = lines.length;
    const lineHeadCharRegex = REGEX_LINE_HEAD_CHAR[this.syntaxType];
    const hasLineHeadChar = lines[0] && lineHeadCharRegex.test(lines[0]);
    const r = new RegExp('(?:^|\\n)\\s*((?!@' + IGNORE_TAGLIST.join(')(?!@') + ')@\\w*)');
 
    var results = [
      {
        'tag': 'file',
        'value': filename
      },
      {
        'tag': 'line',
        'value': linenum
      }
    ];
 
    if (hasLineHeadChar) {
      lines = _.map(lines, function (line) {
        return line.trim().replace(lineHeadCharRegex, '');
      });
    }
 
    const unidented = utils.unindent(lines.join('\n'));
    const parts = unidented.split(r);
 
    var cursor = 0;
    for (; cursor < parts.length; cursor++) {
      var skip;
      var val = '';
      var part = parts[cursor];
      if (part === '') continue;
 
      skip = false;
      // the first token may be the description, otherwise it should be a tag
      if (cursor === 0 && part.substr(0, 1) !== '@') {
        if (part) {
          tag = '@description';
          val = part;
        } else {
          skip = true;
        }
      } else {
        tag = part;
        // lookahead for the tag value
        var peek = parts[cursor + 1];
        if (peek) {
          val = peek;
          cursor += 1;
        }
      }
      if (!skip && tag) {
        results.push({
          tag: tag.substr(1).toLowerCase(),
          value: val || ''
        });
      }
    }
    return results;
  },
 
  /**
   * Processes all the tags in a single comment block
   * @method onblock
   * @param {Array} an array of the tag/text pairs
   */
  onblock: function (block) {
    this.context.block = {
      'self': block,
      'target': {
        'file': this.context.file,
        'line': block[1].value,
        '_raw': _.reduce(block, onreduce, {})
      },
      'host': null,
      'digesters': []
    };
 
    function onreduce (map, item) {
      var key = utils.safetrim(item.tag);
      var val = utils.safetrim(item.value);
      map[key] = _.isString(val) ? utils.safetrim(val) : val;
      return map;
    }
 
    // handle tags and push digesters to context.block.digesters
    _.each(block, this.ontag, this);
    // run digiesters
    _.each(this.context.block.digesters, ondigester, this);
 
    function ondigester (ctx) {
      var ret = ctx.fn.call(this, ctx.name, ctx.value,
        this.context.block.target, this.context.block.self);
      this.context.block.host = this.context.block.host || ret;
    }
 
    // post process
    if (this.context.block.host) {
      _.extend(this.context.block.host, this.context.block.target);
    } else {
      var target = this.context.block.target;
      target.clazz = this.context.clazz;
      target.module = this.context.module;
      target.isGlobal = (this.context.clazz === '');
      target.submodule = this.context.submodule;
 
      // set namespace
      var ns = utils.getNamespace(target);
      if (ns) {
        this.namespacesMap[ns] = target;
        target.namespace = ns;
 
        var parent = this.classes[target.clazz] || this.modules[target.module];
        Object.defineProperty(target, 'parent', {
          enumerable: true,
          get: function () {
            return parent;
          }
        });
 
        target.process = target.process || parent.process;
      }
 
      if (target.itemtype) {
        this.members.push(target);
      } else if (target.isTypeDef) {
        var parent = this.classes[this.context.clazz] ||
          this.modules[this.context.module];
        if (!parent) return;
        parent.types[target.name] = target;
      }
    }
  },
 
  /**
   * Process tag
   * @method ontag
   * @param {Object} item
   * @param {String} item.tag
   * @param {Object} item.value
   */
  ontag: function (item) {
    var name = utils.safetrim(item.tag);
    var value = utils.safetrim(item.value);
 
    if (SHORT_TAGS[name] && value === '') {
      value = 1;
    }
 
    if (TAGLIST.indexOf(name) === -1) {
      if (_.has(CORRECTIONS, name)) {
        // correction part
        // TODO(Yorkie): log the correction
        name = CORRECTIONS[name];
        item.tag = name;
      } else {
        // TODO(Yorkie): report the unknown correction
      }
    }
 
    if (_.has(DIGESTERS, name) === -1) {
      this.context.block.target[name] = value;
    } else {
      var digest = DIGESTERS[name];
      if (_.isString(digest)) {
        digest = DIGESTERS[digest];
      }
      var block = this.context.block;
      _.each(block.self, function (item) {
        if (item.tag === 'description') {
          block.target.description = item.value;
        } else if (item.tag === 'type') {
          block.target.type = utils.fixType(item.value);
        } else if (item.tag === 'extends') {
          block.target.extends = utils.fixType(item.value);
        }
      });
      if (_.isFunction(digest)) {
        // here we only push and run later
        // because CORRECTION perhaps doesn't apply the later tags.
        block.digesters.push({
          fn: digest,
          name: name,
          value: value
        });
      }
    }
  },
 
  /**
   * Accepts a map of filenames to file content.  Returns
   * a map of filenames to an array of API comment block
   * text.  This expects the comment to start with / **
   * on its own line, and end with * / on its own
   * line.  Override this function to provide an
   * alternative comment parser.
   *
   * @method extract
   * @param {Object} files
   * @param {Object} dirs
   */
  extract: function (files, dirs) {
    _.each(files, function (code, filename) {
      filename = path.relative(CWD, filename);
      this.codes[filename] = code;
      const lines = code.split(REGEX_LINES);
      const len = lines.length;
      var comment;
      var cursor = 0;
      for (; cursor < len; cursor++) {
        var line = lines[cursor];
        if (REGEX_START_COMMENT[this.syntaxType].test(line)) {
          var comments = [];
          var linenum = cursor + 1;
          while (cursor < len &&
            (!REGEX_END_COMMENT[this.syntaxType].test(line))) {
            comments.push(line);
            cursor += 1;
            line = lines[cursor];
          }
          comments.shift();
          comment = comments.join('\n');
          this.commentsMap[filename] = this.commentsMap[filename] || [];
          this.commentsMap[filename].push(this.oncomment(comment, filename, linenum));
        }
      }
    }, this);
  },
 
  /**
   * Transforms a map of filenames to arrays of comment blocks into a
   * JSON structure that represents the entire processed API doc info
   * and relationships between elements for the entire project.
   *
   * @method transform
   * @param {Object} commentmap The hash of files and parsed comment blocks
   * @return {Object} The transformed data for the project
   */
  transform: function () {
    _.each(this.commentsMap, function (blocks, filename) {
      this.context.file = filename;
      _.each(blocks, this.onblock, this);
    }, this);
  }
 
};
 
/**
 * A map of the default tag processors, keyed by the
 * tag name.  Multiple tags can use the same digester
 * by supplying the string name that points to the
 * implementation rather than a function.
 * @property DIGESTERS
 * @type Object
 * @final
 * @for DocParser
 */
const DIGESTERS = {
  'param': function (tagname, value, target, block) {
    target.params = target.params || [];
    if (!value) {
      this.warnings.push({
        message: 'param name/type/descript missing',
        line: utils.stringlog(block)
      });
      console.warn('param name/type/descript missing: ' + utils.stringlog(block));
      return;
    }
 
    var type, name, parts, optional, optdefault, parent, multiple, len, result,
      desc = implodeString(utils.safetrim(value)),
      match = REGEX_TYPE.exec(desc),
      host = target.params,
      type_;
 
    // Extract {type}
    if (match) {
      type_ = utils.safetrim(match[2]);
      type = utils.safetrim(match[2]);
      desc = utils.safetrim(match[1] + match[3]);
    }
 
    // extract the first word, this is the param name
    match = REGEX_FIRSTWORD.exec(desc);
    if (match) {
      name = utils.safetrim(explodeString(match[1]));
      desc = utils.safetrim(match[3]);
    }
 
    if (!name) {
      if (value && value.match(/callback/i)) {
        this.warnings.push({
          message: 'Fixing missing name for callback',
          line: utils.stringlog(block)
        });
        console.warn('Fixing missing name for callback:' + utils.stringlog(block));
        name = 'callback';
        type = 'Callback';
      } else {
        this.warnings.push({
          message: 'param name missing: ' + value,
          line: utils.stringlog(block)
        });
        console.warn('param name missing: ' + value + ':' + utils.stringlog(block));
        name = 'UNKNOWN';
      }
    }
 
    len = name.length - 1;
    if (name.charAt(len) === '*') {
        multiple = true;
        name = name.substr(0, len);
    }
 
    // extract [name], optional param
    if (name.indexOf('[') > -1) {
      match = REGEX_OPTIONAL.exec(name);
      if (match) {
        optional = true;
        name = utils.safetrim(match[1]);
        // extract optional=defaultvalue
        parts = name.split('=');
        if (parts.length > 1) {
          name = parts[0];
          optdefault = parts[1];
          //Add some shortcuts for object/array defaults
          if (optdefault.toLowerCase() === 'object') {
            optdefault = '{}';
          }
          if (optdefault.toLowerCase() === 'array') {
            optdefault = '[]';
          }
        }
      }
    }
 
    // This should run after the check for optional parameters
    // and before the check for child parameters
    // because the signature for 0..n params is [...args]
    if (name.substr(0, 3) === '...') {
      multiple = true;
      name = name.substr(3);
    }
 
    // parse object.prop, indicating a child property for object
    if (name.indexOf('.') > -1) {
      match = name.split('.');
      parent = utils.safetrim(match[0]);
      _.each(target.params, function (param) {
        if (param.name === parent) {
          param.props = param.props || [];
          host = param.props;
          match.shift();
          name = utils.safetrim(match.join('.'));
          if (match.length > 1) {
            var pname = name.split('.')[0], par;
            _.each(param.props, function (o) {
              if (o.name === pname) {
                par = o;
              }
            });
            if (par) {
              match = name.split('.');
              match.shift();
              name = match.join('.');
              par.props = par.props || [];
              host = par.props;
            }
          }
        }
      });
    }
 
    result = {
      name: name,
      description: explodeString(desc)
    };
 
    if (type) {
      // find types from classitems
      var item = _.findWhere(this.members, {'name': type});
      if (!item && this.context.clazz) {
        item = this.classes[this.context.clazz].types[type];
      }
      if (!item && this.context.module) {
        item = this.modules[this.context.module].types[type];
      }
      // finded the type
      if (item && item.params) {
        // Dont remove the clone, because the item.params will be
        // used by multiple results, so that we need to clone a new
        // one for its own usage.
        result.description = result.description || item.description;
        result.props = _.clone(item.params);
        result.type = type_;
      } else {
        result.type = type;
      }
    }
 
    if (optional) {
      result.optional = true;
      if (optdefault) {
        result.optdefault = optdefault;
      }
    }
 
    if (multiple) {
      result.multiple = true;
    }
 
    // localize the description
    result.description = utils.localize(result.description);
 
    // push localized result to host
    host.push(result);
  },
 
  // @return {type} description // methods
  // @returns {type} description // methods
  // @injects {HTML|CSS|script} description
  // can be used by anthing that has an optional {type} and a description
  'return': function (tagname, value, target, block) {
    var desc = implodeString(utils.safetrim(value)),
      type,
      match = REGEX_TYPE.exec(desc),
      result = {};
 
    if (match) {
      type = utils.safetrim(match[2]);
      desc = utils.safetrim(match[1] + match[3]);
    }
 
    result = {
      description: utils.unindent(explodeString(desc))
    };
 
    if (type) {
      result.type = type;
    }
 
    // remove the fist char '-' for @return tag
    result.description = result.description.replace(/^\s?-\s?/, '');
 
    // localize the description
    result.description = utils.localize(result.description);
 
    target[tagname] = result;
  },
 
  // @throws {type} description
  'throws': 'return',
 
  'injects': 'return',
 
  // trying to overwrite the constructor value is a bad idea
  'constructor': function (tagname, value, target, block) {
    target.isConstructor = true;
  },
 
  // A key bock type for declaring modules and submodules
  // subsequent class and member blocks will be assigned
  // to this module.
  'module': function (tagname, value, target, block) {
    this.context.module = value;
    if (target._raw.process) {
      target.process = utils.fmtProcess(target._raw.process);
    }
    if (!target._raw.submodule) {
      if (!this.context.mainModule) {
        this.context.mainModule = {
          tag: tagname,
          name: value,
          file: target.file,
          line: target.line,
          type: 'modules',
          description: utils.localize(target.description)
        };
      }
      target.file = this.context.mainModule.file;
      target.line = this.context.mainModule.line;
      return this.modules[value];
    }
    return null;
  },
 
  //Setting the description for the module..
  'main': function (tagname, value, target, block) {
    var o = target;
    o.mainName = value;
    o.tag = tagname;
    o.itemtype = 'main';
    o.description = utils.localize(o.description);
    o._main = true;
    this.context.mainModule = o;
  },
 
  // accepts a single project definition for the source tree
  'project': function (tagname, value, target, block) {
    this.project.name = value;
    this.project.description = this.project.description || value;
  },
  
  // accepts a single project logo definition
  'logo': function (tagname, value, target, block) {
    this.project.logo = value;
  },
 
  // A key bock type for declaring submodules.  subsequent class and
  // member blocks will be assigned to this submodule.
  'submodule': function (tagname, value, target, block) {
    this.context.submodule = value;
 
    var host = this.modules[value];
    var clazz = this.context.clazz;
    var parent = this.context.module;
    if (parent) {
      host.module = parent;
      var parentModule = this.context.ast.modules[parent];
      if (parentModule) {
        this.context.ast.modules[parent].submodules[host.name] = host;
      }
    }
    if (clazz && this.classes[clazz]) {
      this.classes[clazz].submodule = value;
    }
    return host;
  },
 
  // this is a way to abstract the definitions of callback arguments
  'callback': function (tagname, value, target, block) {
    target.name = value;
    target.isTypeDef = true;
  },
 
  // A key bock type for declaring classes, subsequent
  // member blocks will be assigned to this class
  'class': function (tagname, value, target, block) {
    var self = this;
    var fullname, host, parent;
 
    // set the process and attach the process on `target`
    if (target._raw.process) {
      target.process = utils.fmtProcess(target._raw.process);
    } else {
      var modProcess = this.modules[this.context.module].process;
      target.process = modProcess;
    }
 
    if (target._raw.extends) {
      var extended = target._raw.extends;
      if (!extended) {
        console.warn('usage: `@extends <class>`, but only found `@extends`');
      } else if (!this.inheritedMembers.length) {
        this.inheritedMembers.push([extended, value]);
      } else {
        var needNewItem = true;
        var item, at;
        _.some(this.inheritedMembers, function (member) {
          item = member;
          at = member.indexOf(extended);
          if (member.length - 1 === at) {
            return true;  // break
          }
          if (member[at + 1] === value) {
            needNewItem = false;
            return true;
          }
          if (at !== -1) {
            return true;
          }
        }, this);
        if (needNewItem) {
          if (extended !== item[item.length - 1]) {
            var newItem = item.slice(0, at + 1);
            newItem.push(value);
            self.inheritedMembers.push(newItem);
          } else {
            item.push(value);
          }
        }
      }
    }
    
    this.context.clazz = value;
 
    fullname = this.context.clazz;
    host = this.classes[fullname];
    parent = this.context.module;
 
    if (parent) {
      host.module = parent;
    }
 
    // set `is_enum` when the tagname is "enum"
    if (tagname === 'enum') {
      host.isEnum = true;
      host.type = 'enums';
    } else {
      host.isEnum = false;
      host.type = 'classes';
    }
 
    //Merge host and target in case the class was defined in a "for" tag
    //before it was defined in a "class" tag
    host = _.extend(host, target);
    this.classes[fullname] = host;
    parent = this.context.submodule;
    if (parent) {
      host.submodule = parent;
    }
 
    // localize
    host.description = utils.localize(host.description);
    return host;
  },
 
  // just defer from class in their names
  'enum': 'class',
 
  // change 'const' to final property
  'const': function (tagname, value, target, block) {
    target.itemtype = 'property';
    target.name = value;
    /*jshint sub:true */
    target['final'] = '';
  },
 
  // supported classitems
  'property': function (tagname, value, target, block) {
    var match, name, desc, type;
 
    target.itemtype = tagname;
    target.name = value;
 
    if (target._raw.process) {
      target.process = utils.fmtProcess(target._raw.process);
    }
 
    if (tagname === 'property') {
      var propM = value.match(/^\{(.+)\} ([a-zA-Z0-9_]+)\s*\-?\s*(.+)?$/);
      if (propM && propM.length === 4) {
        value = propM[2];
        target.type = propM[1];
        target.name = propM[2];
        target.description = propM[3];
      }
    }
 
    if (!target.type) {
      desc = implodeString(utils.safetrim(value));
      match = REGEX_TYPE.exec(desc);
 
      // Extract {type}
      if (match) {
        type = trim(match[2]);
        name = trim(match[1] + match[3]);
        target.type = type;
        target.name = name;
      }
    }
 
    // localize the description
    target.description = utils.localize(target.description);
  },
  'method': 'property',
  'attribute': 'property',
  'config': 'property',
  'event': 'property',
 
  // access fields
  'public': function (tagname, value, target, block) {
    target.access = tagname;
    target.tagname = value;
  },
  'private': 'public',
  'protected': 'public',
  'inner': 'public',
 
  // tags that can have multiple occurances in a single block
  'todo': function (tagname, value, target, block) {
    if (!_.isArray(target[tagname])) {
      target[tagname] = [];
    }
    //If the item is @tag one,two
    if (value.indexOf(',') > -1) {
      value = value.split(',');
    } else {
      value = [value];
    }
 
    value.forEach(function (v) {
      v = utils.safetrim(v);
      target[tagname].push(v);
    });
  },
  'extension_for': 'extensionfor',
  'extensionfor': function (tagname, value, target, block) {
    var clazz = this.context.clazz;
    if (this.classes[clazz]) {
      this.classes[clazz].extension_for.push(value);
    }
  },
  'example': function (tagname, value, target, block) {
    if (value) {
      var linkMatch = value.match(/\{@link (.+)\}/);
      if (linkMatch && linkMatch.length === 2) {
        var relative = utils.safetrim(linkMatch[1]);
        var examplePath = process.cwd() + '/' + relative;
        if (fs.existsSync(examplePath)) {
          value = fs.readFileSync(examplePath, 'utf8');
          value = '```' + value;
        } else {
          value = '```Not found for the example path: ' + relative;
        }
      }
    }
 
    if (!_.isArray(target[tagname])) {
      target[tagname] = [];
    }
 
    var e = value;
    block.forEach(function (v) {
      if (v.tag === 'example') {
        if (v.value.indexOf(value) > -1) {
          e = v.value;
        }
      }
    });
 
    target[tagname].push(e);
  },
  'url': 'todo',
  'icon': 'todo',
  'see': 'todo',
  'requires': 'todo',
  'knownissue': 'todo',
  'uses': 'todo',
  'category': 'todo',
  'unimplemented': 'todo',
 
  genericValueTag: function (tagname, value, target, block) {
    target[tagname] = value;
  },
 
  'author': 'genericValueTag',
  'contributor': 'genericValueTag',
  'since': 'genericValueTag',
 
  'deprecated': function (tagname, value, target, block) {
    target.deprecated = true;
    if (typeof value === 'string' && value.length) {
      target.deprecationMessage = value;
    }
  },
 
  // updates the current class only (doesn't create
  // a new class definition)
  'for': function (tagname, value, target, block) {
    var ns, file, mod;
    this.context.clazz = value;
 
    ns = ((this.classes[value]) ? this.classes[value].namespace : '');
    this.context.namespace = ns;
 
    file = this.context.file;
    if (file) {
      this.files[file].fors[value] = 1;
    }
 
    mod = this.context.module;
    if (mod) {
      this.modules[mod].fors[value] = 1;
    }
 
    mod = this.context.submodule;
    if (mod) {
      this.modules[mod].fors[value] = 1;
    }
  }
 
};
 
/**
 * Flatten a string, remove all line breaks and replace them with a token
 * @method implodeString
 * @private
 * @param {String} str The string to operate on
 * @return {String} The modified string
 */
function implodeString (str) {
  return (str || '').replace(REGEX_GLOBAL_LINES, '!~FIREDOC_LINE~!');
}
 
/**
 * Un-flatten a string, replace tokens injected with `implodeString`
 * @method implodeString
 * @private
 * @param {String} str The string to operate on
 * @return {String} The modified string
 */
function explodeString (str) {
  return (str || '').replace(/!~FIREDOC_LINE~!/g, '\n');
}
 
exports.InitialAST = _.clone(AST);
exports.AST = AST;
exports.DIGESTERS = DIGESTERS;