All files / src/excellent ExcellentParser.ts

69.71% Statements 244/350
90.24% Branches 74/82
70% Functions 7/10
69.71% Lines 244/350

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 341 342 343 344 345 346 347 348 349 350 351109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 449x 449x 109x 109x 109x 109x 109x 175x 175x 175x 175x 175x 175x 175x 37x 175x 138x 138x 138x 138x 113x 449x 112x 112x 449x 59x 25x 25x 1x 1x 175x 109x 109x 109x 109x 109x 2003x 2003x 334x 334x 221x 2003x 2003x 109x 109x 109x 109x 109x 2x 2x 2x 14x     14x 2x 2x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 218x 218x 218x 109x 109x 109x 109x 109x                               109x 109x 109x 109x 109x 109x                                                                                                                                       109x 109x 109x 109x 109x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x     12x 12x 6x 2x 2x 6x   4x 2x 2x     12x 6x 4x 6x 2x 2x 6x         12x   2x 109x 109x                         109x 109x 109x 109x 109x 756x 756x 756x 756x 756x 756x 155733x 155733x 155733x 155733x 155733x 155733x 155733x 153500x 153500x 176x 153500x 175x 175x 175x 175x 175x 175x 175x 175x 153325x 1x 153325x 1x 1x 155733x 174x 137x 174x 37x 37x 37x 37x 174x 2233x 1411x 2059x 524x 21x 524x 53x 503x 6x 6x 524x 524x 524x 524x 524x 34x 34x 648x 123x 6x 6x 123x 124x 1x 1x 155733x 155733x 155733x 155733x 155733x 155733x 1548x 1548x 1523x 1548x 25x 25x 1548x 155733x 155733x 155733x 2407x 155733x 175x 175x 175x 175x 175x 175x 175x 175x 174x 174x 174x 174x 174x 175x 175x 175x 175x 155733x 756x 756x 756x 109x  
const STATE_BODY = 0; // not in a expression
const STATE_PREFIX = 1; // '@' prefix that denotes the start of an expression
const STATE_IDENTIFIER = 2; // the identifier part, e.g. 'contact.age' in '@contact.age'
const STATE_BALANCED = 3; // the balanced parentheses delimited part, e.g. '(1 + 2)' in '@(1 + 2)'
const STATE_STRING_LITERAL = 4; // a string literal which could contain )
const STATE_ESCAPED_PREFIX = 5; // a '@' prefix preceded by another '@'
const STATE_IGNORE = 6;
 
export interface Expression {
  start: number;
  end: number;
  text: string;
  closed: boolean;
}
 
/**
 * Determines whether the given string starts with the given text
 */
const startsWith = (str: string, start: string): boolean => {
  return str.indexOf(start, 0) === 0;
};
 
/**
 * Checks the parsed (possibly partial) expression to determine if it's valid based on how it starts
 */
const isValidStart = (
  partialExpression: string,
  allowedTopLevels: string[],
  allowIncomplete: boolean
): boolean => {
  const body = partialExpression.substring(1); // strip prefix
 
  if (body[0] === '(') {
    return true;
  } else {
    // if expression doesn't start with ( then check it's an allowed top level context reference
    const topLevel = body.split('.')[0].toLowerCase();
 
    if (allowIncomplete) {
      for (const allowed of allowedTopLevels) {
        if (startsWith(allowed, topLevel)) {
          return true;
        }
      }
    } else {
      return allowedTopLevels.indexOf(topLevel) >= 0;
    }
    return false;
  }
};
 
/**
 * Determines whether the given character is a word character, i.e. \w in a regex
 */
export const isWordChar = (ch: string | 0): boolean => {
  return (
    (ch >= 'a' && ch <= 'z') ||
    (ch >= 'A' && ch <= 'Z') ||
    (ch >= '0' && ch <= '9') ||
    ch === '_'
  );
};
 
/**
 * Determines whether we are in a string literal
 */
const isInStringLiteral = (partialExpression: string): boolean => {
  // count number quotation marks
  let numQuotes = 0;
  for (const pos of partialExpression) {
    if (pos === '"') {
      numQuotes++;
    }
  }
  return numQuotes % 2 !== 0; // odd means last string literal is open
};
 
export default class ExcellentParser {
  private expressionPrefix: string;
  private allowedTopLevels: string[];
 
  /**
   * Creates a new parser
   * @param expressionPrefix the prefix for expressions, e.g. '@'
   * @param allowedTopLevels the context names that are allowed without parentheses, e.g. ["contact", "flow", ...]
   */
  constructor(expressionPrefix: string, allowedTopLevels: string[]) {
    this.expressionPrefix = expressionPrefix;
    this.allowedTopLevels = allowedTopLevels;
  }
 
  /**
   * Given the text up to the caret position, returns the expression currently being edited, without its prefix
   */
  public expressionContext(textToCaret: string): string {
    const expressions = this.findExpressions(textToCaret);
    if (expressions.length === 0) {
      // no expressions found
      return null;
    }

    const lastExpression = expressions[expressions.length - 1];

    // has last expression already ended or is it closed (i.e. has balanced parentheses)
    if (lastExpression.end < textToCaret.length || lastExpression.closed) {
      return null;
    }

    return lastExpression.text.substring(1); // return without prefix
  }
 
  /**
   * Given the partial expression currently being edited, returns the current auto-completable identifier
   * which may be a function name or a context reference.
   */
  public autoCompleteContext(partialExpression: string): string {
    if (isInStringLiteral(partialExpression)) {
      return null;
    }

    const neededParentheses = [];
    let fragment = '';
    let skipChar = false;
    let inQuotes = false;
    let prependFlag = '';

    for (let pos = partialExpression.length - 1; pos >= 0; pos--) {
      const ch = partialExpression[pos];

      if (ch === ' ') {
        skipChar = true;
      }

      if (ch === ',') {
        skipChar = true;
        if (neededParentheses[neededParentheses.length - 1] !== '(') {
          neededParentheses.push('(');
        }
      }

      if (ch === ')' && !inQuotes) {
        skipChar = true;
        neededParentheses.push('(');
        neededParentheses.push('(');
      }

      if (ch === '"') {
        inQuotes = !inQuotes;
      }

      if (skipChar) {
        if (ch === '(' && !inQuotes) {
          if (neededParentheses[neededParentheses.length - 1] === '(') {
            neededParentheses.pop();
          }

          if (neededParentheses.length === 0) {
            skipChar = false;
          }
        }
      }

      if (ch === '(' && fragment === '') {
        prependFlag = '#';
      }

      if (skipChar || inQuotes || (ch === '(' && fragment === '')) {
        continue;
      }

      if (isWordChar(ch) || ch === '.') {
        fragment = ch + fragment;
      } else {
        break;
      }
    }

    if (fragment.match(/[A-Za-z][\w]*(\.[\w]+)*/)) {
      return prependFlag + fragment;
    } else {
      return null;
    }
  }
 
  /**
   * TODO find the function context
   */
  public functionContext(partialExpression: string): string {
    const inString = isInStringLiteral(partialExpression);
 
    // initial state is string literal if number of quotes is odd
    let state = inString ? STATE_STRING_LITERAL : STATE_IGNORE;
    let identifier = '';
    let parenthesesLevel = partialExpression[-1] === '(' ? 0 : 1;
 
    for (let pos = partialExpression.length - 1; pos >= 0; pos--) {
      const ch = partialExpression[pos];
 
      if (ch === '@') {
        return '';
      }
 
      if (state === STATE_IGNORE) {
        if (parenthesesLevel === 0 && (isWordChar(ch) || ch === '.')) {
          state = STATE_IDENTIFIER;
          identifier = ch + identifier;
        } else if (ch === '"') {
          state = STATE_STRING_LITERAL;
        } else if (ch === '(') {
          parenthesesLevel--;
        } else if (ch === ')') {
          parenthesesLevel++;
        }
      } else if (state === STATE_IDENTIFIER) {
        if (isWordChar(ch) || ch === '.') {
          identifier = ch + identifier;
        } else {
          return identifier;
        }
      } else if (state === STATE_STRING_LITERAL) {
        if (ch === '"') {
          state = STATE_IGNORE;
        }
      }
    }
    return '';
  }
 
  public getContactFields(text: string): string[] {
    const fields = {};
    const re = /((parent|child\.)*contact\.)*fields\.([a-z0-9_]+)/g;
    const expressions = this.findExpressions(text);
    for (const expression of expressions) {
      let match;
      // tslint:disable-next-line:no-conditional-assignment
      while ((match = re.exec(expression.text))) {
        (fields as any)[match[3]] = true;
      }
    }
    return Object.keys(fields);
  }
 
  /**
   * Finds all expressions in the given text, including any partially complete expression at the end of the input
   */
  public findExpressions(text: string): Expression[] {
    const expressions: Expression[] = [];
    let state = STATE_BODY;
    let currentExpression: Expression = null;
    let parenthesesLevel = 0;
 
    for (let pos = 0; pos < text.length; pos++) {
      const ch = text[pos];
      // in order to determine if the b in a.b terminates an identifier, we have to peek two characters ahead as
      // it could be a.b. (b terminates) or a.b.c (b doesn't terminate)
      const nextCh = pos < text.length - 1 ? text[pos + 1] : 0;
      const nextNextCh = pos < text.length - 2 ? text[pos + 2] : 0;
 
      if (state === STATE_BODY) {
        if (
          ch === this.expressionPrefix &&
          (isWordChar(nextCh) || nextCh === '(')
        ) {
          state = STATE_PREFIX;
          currentExpression = {
            start: pos,
            end: null,
            text: ch,
            closed: false
          };
        } else if (
          ch === this.expressionPrefix &&
          nextCh === this.expressionPrefix
        ) {
          state = STATE_ESCAPED_PREFIX;
        }
      } else if (state === STATE_PREFIX) {
        if (isWordChar(ch)) {
          state = STATE_IDENTIFIER; // we're parsing an expression like @XXX
        } else if (ch === '(') {
          // we're parsing an expression like @(1 + 2)
          state = STATE_BALANCED;
          parenthesesLevel += 1;
        }
        currentExpression.text += ch;
      } else if (state === STATE_IDENTIFIER) {
        currentExpression.text += ch;
      } else if (state === STATE_BALANCED) {
        if (ch === '(') {
          parenthesesLevel += 1;
        } else if (ch === ')') {
          parenthesesLevel -= 1;
        } else if (ch === '"') {
          state = STATE_STRING_LITERAL;
        }
 
        currentExpression.text += ch;
 
        // expression terminates if parentheses balance
        if (parenthesesLevel === 0) {
          currentExpression.end = pos + 1;
        }
      } else if (state === STATE_STRING_LITERAL) {
        if (ch === '"') {
          state = STATE_BALANCED;
        }
        currentExpression.text += ch;
      } else if (state === STATE_ESCAPED_PREFIX) {
        state = STATE_BODY;
      }
 
      // identifier can terminate expression in 3 ways:
      //  1. next char is null (i.e. end of the input)
      //  2. next char is not a word character or period
      //  3. next char is a period, but it's not followed by a word character
      if (state === STATE_IDENTIFIER) {
        if (
          (!isWordChar(nextCh) && nextCh !== '.') ||
          (nextCh === '.' && !isWordChar(nextNextCh))
        ) {
          currentExpression.end = pos + 1;
        }
      }
 
      if (
        currentExpression != null &&
        (currentExpression.end != null || nextCh === 0)
      ) {
        const allowIncomplete = nextCh === 0; // if we're at the end of the input, allow incomplete expressions
        if (
          isValidStart(
            currentExpression.text,
            this.allowedTopLevels,
            allowIncomplete
          )
        ) {
          currentExpression.closed =
            currentExpression.text[1] === '(' && parenthesesLevel === 0;
          currentExpression.end = pos + 1;
          expressions.push(currentExpression);
        }
 
        currentExpression = null;
        state = STATE_BODY;
      }
    }
 
    return expressions;
  }
}