statementPosition.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { LinkedToken } from '../../monarch/LinkedToken';
  2. import { StatementPosition } from '../../monarch/types';
  3. import { MetricMathTokenTypes } from './types';
  4. export function getStatementPosition(currentToken: LinkedToken | null): StatementPosition {
  5. const previousNonWhiteSpace = currentToken?.getPreviousNonWhiteSpaceToken();
  6. if (currentToken && currentToken.isString()) {
  7. return StatementPosition.WithinString;
  8. }
  9. if (currentToken && previousNonWhiteSpace) {
  10. const currentFunction = currentToken.getPreviousOfType(MetricMathTokenTypes.Function);
  11. const isAfterComma = previousNonWhiteSpace.is(MetricMathTokenTypes.Delimiter, ',');
  12. const isWithinSearch = currentFunction && currentFunction.value === 'SEARCH';
  13. const allTokensAfterStartOfSearch =
  14. currentToken.getPreviousUntil(MetricMathTokenTypes.Function, [], 'SEARCH') || [];
  15. if (isWithinSearch) {
  16. // if there's only one ' then we're still within the first arg
  17. if (allTokensAfterStartOfSearch.filter(({ value }) => value === "'").length === 1) {
  18. return StatementPosition.WithinString;
  19. }
  20. // if there was a , before the last , and it happened after the start of SEARCH
  21. const lastComma = previousNonWhiteSpace.getPreviousOfType(MetricMathTokenTypes.Delimiter, ',');
  22. if (lastComma) {
  23. const lastCommaIsAfterSearch =
  24. lastComma.range.startColumn > currentFunction.range.startColumn &&
  25. lastComma.range.startLineNumber >= currentFunction.range.startLineNumber;
  26. if (lastCommaIsAfterSearch) {
  27. return StatementPosition.SearchFuncThirdArg;
  28. }
  29. }
  30. // otherwise assume it's the second arg
  31. return StatementPosition.SearchFuncSecondArg;
  32. }
  33. if (!isWithinSearch && isAfterComma) {
  34. return StatementPosition.PredefinedFuncSecondArg;
  35. }
  36. }
  37. if (previousNonWhiteSpace?.endsWith(')')) {
  38. return StatementPosition.AfterFunction;
  39. }
  40. if (!currentToken || !currentToken.isString()) {
  41. return StatementPosition.PredefinedFunction;
  42. }
  43. return StatementPosition.Unknown;
  44. }