All files lexer.js

100% Statements 270/270
95.27% Branches 141/148
100% Functions 14/14
100% Lines 240/240

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3411x   1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 156x 156x 156x 156x 156x 156x 156x 156x 2130x 2130x 2130x     156x 94x 94x 94x     156x 10x 10x 10x 10x   34x 34x 10x 10x 24x 1x 23x 10x 10x 10x 84x   10x 10x   10x 10x   64x   84x 84x 84x   10x 10x 10x 9x 9x 9x 9x       10x 10x   13x       10x     156x 32x 22x 22x 22x     156x 9x 9x 3x 3x 3x   9x   156x 3x 3x 3x 3x 14x 14x 7x 7x 7x 4x 4x 4x   3x 3x 3x   14x 12x   2x 2x 2x     156x   97x   92x 92x 8x 8x   84x   83x 83x   74x   74x 74x 74x   55x 12x 1x 11x 12x 12x     43x 43x 43x       156x 704x 704x 704x     156x 563x 563x 563x     156x 31x 31x 31x     156x 436x 436x 436x     156x 448x 448x 448x     156x 1905x 1905x 1038x 1028x   156x 1911x 1911x   10x 10x   27x 17x 27x   42x 42x   3x 3x 3x   4x 4x 4x 3x   31x 17x 17x   31x   18x 18x 18x 17x   28x 28x 28x   29x 29x 29x 29x 28x   49x 49x   32x 32x   76x 67x 67x 9x 6x   76x   30x 3x   27x   29x   9x 8x 9x   6x 4x 6x   20x 8x 8x 12x 7x 20x   2x 2x   2x 2x   42x 41x 42x                     85x 85x   704x 704x   2x 2x 2x   97x 97x 97x 97x 96x   563x 1x 562x   1905x   150x 30x 30x   150x 150x 150x 150x 150x 3153x 702x 702x   2451x     150x     1x  
const { list } = require("../../index");
 
const strPattern = /^(?:"(?:[^"]|\\")*"|'(?:[^']|\\')*')/;
const numPattern = /^-?(?:[0-9][\d_]*)(?:\.[\d_]+)?(?:[eE][+-]?[\d_]+)?/;
 
const keywordPattern = /^(?:if|else|fn|await|import|as|from|export|and|or|not|by|in)(?=\s|$)|^else(?=:)|^await(?=])/;
const symbolPattern = /^(?:[a-z_$][0-9a-z_$]*)/i; // Should we allow unicode?
const parameterPattern = /^@(?:[a-z_$][0-9a-z_$]*)/i; // Should we allow unicode?
const commentPattern = /^--.*?(?=\n|$)/;
const blockCommentPattern = /^([^+-]|\+[^-]|-[^+])+?(?=(-\+|\+-))/;
const manPattern = /^ *(\n|\n\r|\r\n)(fn |export fn )/;
const awaitAllPattern = /^\[await\]/;
 
const whites = ["space", "lineBreak", "indent", "outdent", "slicer", "format"];
const wraps = ["lCurly", "lSquare", "lParen"];
const zsIgnore = [...whites, "dot", "ranger", ...wraps];
 
const lex = (source, file, startLine = 1, startColumn = 0) => {
  const tokens = list([]);
  const levels = [0];
  let line = startLine; // Mozilla SourceMap library is 1-based, unfortunately
  let column = startColumn;
  let squares = 0;
  let curlies = 0;
  let parens = 0;
  const token = (type, value = "", length = value.length) => {
    tokens.push({ type, value, line, column, file });
    source = source.slice(length);
    column += length;
  };
  // ยง a single number
  const number = () => {
    const match = source.match(numPattern);
    if (match) token("number", match[0]);
    return !!match;
  };
  // lex a formatted string
  const formattedString = () => {
    const match = source.match(strPattern);
    Eif (match) {
      token("fmtStart", '"', 1);
      while (source[0]) {
        // Match an escape, { or *, or end of string
        const point = source.match(/^("|([^\\{"])+|\\.|{)/);
        if (point[0] == '"') {
          token("fmtEnd", '"', 1);
          break;
        } else if (point[0][0] == "\\") {
          token("strEscape", point[0], 2);
        } else if (point[0] == "{") {
          let curls = 0;
          let inner = "";
          while (source[0]) {
            switch (source[0]) {
              case "{":
                curls++;
                break;
              case "}":
                curls--;
                break;
              default:
                break;
            }
            inner += source[0];
            source = source.slice(1);
            if (curls == 0) break;
          }
          token("fmtExprStart", "", 0);
          const fmtTokens = lex(inner.slice(1, -1), file, line, column);
          if (fmtTokens.last?.prev?.prev) {
            fmtTokens.last = fmtTokens.last.prev.prev;
            tokens.last.next = fmtTokens.first;
            fmtTokens.first.prev = tokens.last;
            tokens.last = fmtTokens.last;
          } else {
            // Empty
          }
          token("ender", "", 0);
          token("fmtExprEnd", "", 0);
        } else {
          token("fmtStr", point[0]);
        }
      }
    }
    return !!match;
  };
  // match a string
  const string = () => {
    if (tokens.last?.item?.type == "format") return formattedString();
    const match = source.match(strPattern);
    Eif (match) token("string", match[0]);
    return !!match;
  };
  // match a comment
  const comment = () => {
    const match = source.match(commentPattern);
    if (match) {
      source = source.slice(match[0].length);
      const man = source.match(manPattern);
      if (man) token("comment", match[0], 0);
    }
    return !!match;
  };
  const blockComment = () => {
    let comment = source.slice(0, 2);
    source = source.slice(2);
    let open = 1;
    while (true) {
      const match = source.match(blockCommentPattern);
      if (match) {
        comment += match[0];
        source = source.slice(match[0].length);
      } else if (source.slice(0, 2) == "-+") {
        open--;
        comment += "-+";
        source = source.slice(2);
      } else {
        open++;
        comment += "+-";
        source = source.slice(2);
      }
      if (!open) break;
      if (!source && open) throw "Unbalanced comment blocks"; // FIXME
    }
    const man = source.match(manPattern);
    Eif (man) token("comment", comment, 0);
    return true;
  };
  // indent / outdent
  const indents = () => {
    // check if we're in an array or parentheses
    if (squares || curlies || parens) return;
    // check for math
    const isMath = source.match(/^ *[-+*\/%]/);
    if (isMath) {
      Eif (tokens.last.prev) tokens.last = tokens.last.prev;
      return;
    }
    if (tokens.last.prev?.item?.type?.endsWith?.("Op")) return;
    // check if this isn't an empty line
    const isEmpty = source.match(/^ *(?=[\r\n])/);
    if (isEmpty) return;
    // check if there are spaces
    const match = source.match(/^ */);
    // check if level is changed
    const level = match[0].length;
    const currLevel = levels[0];
    if (level == currLevel) return;
    // insert outdent / indent token
    if (level < currLevel) {
      if (levels.indexOf(level) == -1)
        throw new Error("Inconsistent indentation");
      while (levels[0] != level) {
        levels.shift();
        token("outdent");
      }
    } else {
      levels.unshift(level);
      Eif (tokens.last.prev) tokens.last = tokens.last.prev;
      token("indent");
    }
  };
  // match white spaces
  const space = () => {
    const match = source.match(/ +/);
    Eif (match) token("space", match[0]);
    return !!match;
  };
  // match a keyword
  const keyword = () => {
    const match = source.match(keywordPattern);
    if (match) token(match[0], match[0]);
    return !!match;
  };
  // match await all
  const awaitAll = () => {
    const match = source.match(awaitAllPattern);
    if (match) token("awaitAll", match[0]);
    return !!match;
  };
  // match a symbol
  const symbol = () => {
    const match = source.match(symbolPattern);
    if (match) token("symbol", match[0]);
    return !!match;
  };
  // match a parameter
  const parameter = () => {
    const match = source.match(parameterPattern);
    if (match) token("parameter", match[0]);
    return !!match;
  };
  // match a zero-space
  const zeroSpace = () => {
    const shouldIgnire = zsIgnore.includes(tokens.last?.item?.type);
    if (shouldIgnire) return;
    if (source[0] == '"') token("format", "", 0);
    else if (source[0] == "[") token("slicer", "", 0);
  };
  while (source.length) {
    const char = source[0];
    switch (char) {
      case "#":
        token("hash", char, 1);
        break;
      case ".":
        if (source[1] == ".") token("ranger", "..", 2);
        else token("dot", char, 1);
        break;
      case "|":
        token("pike", char, 1);
        break;
      case "{":
        token("lCurly", char, 1);
        curlies++;
        break;
      case "}":
        token("rCurly", char, 1);
        curlies--;
        if (curlies < 0) throw new Error("Unbalanced curly braces");
        break;
      case "[":
        if (!awaitAll()) {
          token("lSquare", char, 1);
          squares++;
        }
        break;
      case "]":
        token("rSquare", char, 1);
        squares--;
        if (squares < 0) throw new Error("Unbalanced square braces");
        break;
      case "(":
        token("lParen", char, 1);
        parens++;
        break;
      case ")":
        token("ender", "", 0);
        token("rParen", char, 1);
        parens--;
        if (parens < 0) throw new Error("Unbalanced parentheses");
        break;
      case ":":
        token("colon", char, 1);
        break;
      case '"':
        string();
        break;
      case "-":
        if (source[1] == ">") {
          token("ender", "", 0);
          token("arrow", "->", 2);
        } else if (!number() && !comment()) {
          token("subOp", char, 1);
        }
        break;
      case "+":
        if (source[1] == "-") {
          blockComment();
        } else {
          token("addOp", char, 1);
        }
        break;
      case ">":
        if (source[1] == "=") token("gte", ">=", 2);
        else token("gt", char, 1);
        break;
      case "<":
        if (source[1] == "=") token("lte", "<=", 2);
        else token("lt", char, 1);
        break;
      case "=":
        if (source[1] == ">") {
          token("ender", "", 0);
          token("fatArrow", "=>", 2);
        } else if (source[1] == "=") token("eq", "==", 2);
        else token("assign", char, 1);
        break;
      case "/":
        token("divOp", char, 1);
        break;
      case "%":
        token("modOp", char, 1);
        break;
      case "*":
        if (source[1] == "*") token("powOp", "**", 2);
        else token("mulOp", "*", 1);
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        number();
        break;
      case " ":
        space();
        break;
      case "\r":
        source = source.slice(1);
        column++;
        break;
      case "\n":
        token("lineBreak", "\n", 1);
        line++;
        column = 0;
        indents();
        break;
      default:
        if (!keyword() && !parameter() && !symbol())
          throw new Error(`Unsupported character ${char}!`);
        break;
    }
    zeroSpace();
  }
  while (levels.shift()) {
    tokens.push({ type: "lineBreak" });
    tokens.push({ type: "outdent" });
  }
  tokens.push({ type: "lineBreak" });
  tokens.push({ type: "eof" });
  const { current } = tokens;
  let node = current;
  while (node) {
    if (node.item.type == "space") {
      node.unlink();
      node = node.prev || node.next;
    } else {
      node = node.next;
    }
  }
  return tokens;
};
 
module.exports = lex;