{"version":3,"file":"parsing.cjs","sources":["../../../src/querybuilder/parsing.ts"],"sourcesContent":["// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/plugins/datasource/prometheus/querybuilder/parsing.ts\nimport { type SyntaxNode } from '@lezer/common';\nimport {\n  AggregateExpr,\n  AggregateModifier,\n  AggregateOp,\n  BinaryExpr,\n  BoolModifier,\n  FunctionCall,\n  FunctionCallBody,\n  FunctionIdentifier,\n  GroupingLabels,\n  Identifier,\n  LabelName,\n  QuotedLabelName,\n  MatchingModifierClause,\n  MatchOp,\n  NumberDurationLiteral,\n  On,\n  ParenExpr,\n  parser,\n  StringLiteral,\n  QuotedLabelMatcher,\n  UnquotedLabelMatcher,\n  VectorSelector,\n  Without,\n} from '@prometheus-io/lezer-promql';\n\nimport { t } from '@grafana/i18n';\n\nimport { binaryScalarOperatorToOperatorName } from './binaryScalarOperations';\nimport {\n  ErrorId,\n  getAllByType,\n  getLeftMostChild,\n  getString,\n  isFunctionOrAggregation,\n  makeBinOp,\n  makeError,\n  replaceBuiltInVariable,\n  replaceVariables,\n  returnBuiltInVariable,\n} from './parsingUtils';\nimport { type QueryBuilderLabelFilter, type QueryBuilderOperation } from './shared/types';\nimport { type PromVisualQuery, type PromVisualQueryBinary } from './types';\n\n/**\n * Parses a PromQL query into a visual query model.\n *\n * It traverses the tree and uses sort of state machine to update the query model.\n * The query model is modified during the traversal and sent to each handler as context.\n */\nexport function buildVisualQueryFromString(expr: string): Omit<Context, 'replacements'> {\n  expr = replaceBuiltInVariable(expr);\n  const { replacedExpr, replacedVariables } = replaceVariables(expr);\n  const tree = parser.parse(replacedExpr);\n  const node = tree.topNode;\n\n  // This will be modified in the handlers.\n  const visQuery: PromVisualQuery = {\n    metric: '',\n    labels: [],\n    operations: [],\n  };\n  const context: Context = {\n    query: visQuery,\n    errors: [],\n    replacements: replacedVariables,\n  };\n\n  try {\n    handleExpression(replacedExpr, node, context);\n  } catch (err) {\n    // Not ideal to log it here, but otherwise we would lose the stack trace.\n    console.error(err);\n    if (err instanceof Error) {\n      context.errors.push({\n        text: err.message,\n      });\n    }\n  }\n\n  // If we have empty query, we want to reset errors\n  if (isEmptyQuery(context.query)) {\n    context.errors = [];\n  }\n\n  // No need to return replaced variables\n  delete context.replacements;\n\n  return context;\n}\n\ninterface ParsingError {\n  text: string;\n  from?: number;\n  to?: number;\n  parentType?: string;\n}\n\ninterface Context {\n  query: PromVisualQuery;\n  errors: ParsingError[];\n  replacements?: Record<string, string>;\n}\n\n/**\n * Handler for default state. It will traverse the tree and call the appropriate handler for each node. The node\n * handled here does not necessarily need to be of type == Expr.\n * @param expr\n * @param node\n * @param context\n */\nfunction handleExpression(expr: string, node: SyntaxNode, context: Context) {\n  const visQuery = context.query;\n\n  switch (node.type.id) {\n    case Identifier: {\n      // Expectation is that there is only one of those per query.\n      visQuery.metric = getString(expr, node);\n      break;\n    }\n\n    case QuotedLabelName: {\n      // Usually we got the metric name above in the Identifier case.\n      // If we didn't get the name that's potentially we have it in curly braces as quoted string.\n      // It must be quoted because that's how utf8 metric names should be defined\n      // See proposal https://github.com/prometheus/proposals/blob/main/proposals/2023-08-21-utf8.md\n      if (visQuery.metric === '') {\n        const strLiteral = node.getChild(StringLiteral);\n        const quotedMetric = getString(expr, strLiteral);\n        visQuery.metric = quotedMetric.slice(1, -1);\n      }\n      break;\n    }\n\n    case QuotedLabelMatcher: {\n      const quotedLabel = getLabel(expr, node, QuotedLabelName);\n      quotedLabel.label = quotedLabel.label.slice(1, -1);\n      visQuery.labels.push(quotedLabel);\n      const err = node.getChild(ErrorId);\n      if (err) {\n        context.errors.push(makeError(expr, err));\n      }\n      break;\n    }\n\n    case UnquotedLabelMatcher: {\n      // Same as MetricIdentifier should be just one per query.\n      visQuery.labels.push(getLabel(expr, node, LabelName));\n      const err = node.getChild(ErrorId);\n      if (err) {\n        context.errors.push(makeError(expr, err));\n      }\n      break;\n    }\n\n    case FunctionCall: {\n      handleFunction(expr, node, context);\n      break;\n    }\n\n    case AggregateExpr: {\n      handleAggregation(expr, node, context);\n      break;\n    }\n\n    case BinaryExpr: {\n      handleBinary(expr, node, context);\n      break;\n    }\n\n    case ErrorId: {\n      if (isIntervalVariableError(node)) {\n        break;\n      }\n      context.errors.push(makeError(expr, node));\n      break;\n    }\n\n    default: {\n      if (node.type.id === ParenExpr) {\n        // We don't support parenthesis in the query to group expressions.\n        // We just report error but go on with the parsing.\n        context.errors.push(makeError(expr, node));\n      }\n      // Any other nodes we just ignore and go to its children. This should be fine as there are lots of wrapper\n      // nodes that can be skipped.\n      // TODO: there are probably cases where we will just skip nodes we don't support and we should be able to\n      //  detect those and report back.\n      let child = node.firstChild;\n      while (child) {\n        handleExpression(expr, child, context);\n        child = child.nextSibling;\n      }\n    }\n  }\n}\n\n// TODO check if we still need this\nfunction isIntervalVariableError(node: SyntaxNode) {\n  return node.prevSibling?.firstChild?.type.id === VectorSelector;\n}\n\nfunction getLabel(\n  expr: string,\n  node: SyntaxNode,\n  labelType: typeof LabelName | typeof QuotedLabelName\n): QueryBuilderLabelFilter {\n  const label = getString(expr, node.getChild(labelType));\n  const op = getString(expr, node.getChild(MatchOp));\n  const value = getString(expr, node.getChild(StringLiteral)).replace(/^[\"'`]|[\"'`]$/g, '');\n  return {\n    label,\n    op,\n    value,\n  };\n}\n\nconst rangeFunctions = ['changes', 'rate', 'irate', 'increase', 'delta'];\n\n/**\n * Handle function call which is usually and identifier and its body > arguments.\n * @param expr\n * @param node\n * @param context\n */\nfunction handleFunction(expr: string, node: SyntaxNode, context: Context) {\n  const visQuery = context.query;\n  const nameNode = node.getChild(FunctionIdentifier);\n  const funcName = getString(expr, nameNode);\n\n  // Visual query builder doesn't support nested queries and so info function.\n  if (funcName === 'info') {\n    context.errors.push({\n      text: t(\n        'grafana-prometheus.querybuilder.handle-function.text.query-parsing-is-ambiguous',\n        'Query parsing is ambiguous.'\n      ),\n      from: node.from,\n      to: node.to,\n    });\n  }\n\n  const body = node.getChild(FunctionCallBody);\n  const params = [];\n  let interval = '';\n\n  // This is a bit of a shortcut to get the interval argument. Reasons are\n  // - interval is not part of the function args per promQL grammar but we model it as argument for the function in\n  //   the query model.\n  // - it is easier to handle template variables this way as template variable is an error for the parser\n  if (rangeFunctions.includes(funcName) || funcName.endsWith('_over_time')) {\n    let match = getString(expr, node).match(/\\[(.+)\\]/);\n    if (match?.[1]) {\n      interval = match[1];\n      // We were replaced the builtin variables to prevent errors\n      // Here we return those back\n      params.push(returnBuiltInVariable(match[1]));\n    }\n  }\n\n  const op = { id: funcName, params };\n  // We unshift operations to keep the more natural order that we want to have in the visual query editor.\n  visQuery.operations.unshift(op);\n\n  if (body) {\n    if (getString(expr, body) === '([' + interval + '])') {\n      // This is a special case where we have a function with a single argument and it is the interval.\n      // This happens when you start adding operations in query builder and did not set a metric yet.\n      return;\n    }\n    updateFunctionArgs(expr, body, context, op);\n  }\n}\n\n/**\n * Handle aggregation as they are distinct type from other functions.\n * @param expr\n * @param node\n * @param context\n */\nfunction handleAggregation(expr: string, node: SyntaxNode, context: Context) {\n  const visQuery = context.query;\n  const nameNode = node.getChild(AggregateOp);\n  let funcName = getString(expr, nameNode);\n\n  const modifier = node.getChild(AggregateModifier);\n  const labels = [];\n\n  if (modifier) {\n    const byModifier = modifier.getChild(`By`);\n    if (byModifier && funcName) {\n      funcName = `__${funcName}_by`;\n    }\n\n    const withoutModifier = modifier.getChild(Without);\n    if (withoutModifier) {\n      funcName = `__${funcName}_without`;\n    }\n\n    labels.push(...getAllByType(expr, modifier, LabelName), ...getAllByType(expr, modifier, QuotedLabelName));\n  }\n\n  const body = node.getChild(FunctionCallBody);\n\n  const op: QueryBuilderOperation = { id: funcName, params: [] };\n  visQuery.operations.unshift(op);\n  updateFunctionArgs(expr, body, context, op);\n  // We add labels after params in the visual query editor.\n  op.params.push(...labels);\n}\n\n/**\n * Handle (probably) all types of arguments that function or aggregation can have.\n *\n * We cannot just get all the children and iterate them as arguments we have to again recursively traverse through\n *  them.\n *\n * @param expr\n * @param node\n * @param context\n * @param op - We need the operation to add the params to as an additional context.\n */\nfunction updateFunctionArgs(expr: string, node: SyntaxNode | null, context: Context, op: QueryBuilderOperation) {\n  if (!node) {\n    return;\n  }\n  switch (node.type.id) {\n    case FunctionCallBody: {\n      let child = node.firstChild;\n\n      while (child) {\n        updateFunctionArgs(expr, child, context, op);\n        child = child.nextSibling;\n      }\n      break;\n    }\n\n    case NumberDurationLiteral: {\n      op.params.push(parseFloat(getString(expr, node)));\n      break;\n    }\n\n    case StringLiteral: {\n      op.params.push(getString(expr, node).replace(/\"/g, ''));\n      break;\n    }\n\n    case VectorSelector: {\n      // When we replace a custom variable to prevent errors during parsing we receive VectorSelector and Identifier in it.\n      // But this is also a normal case for a normal function body. i.e. topk(5, http_requests_total{})\n      // In such cases we got identifier as http_requests_total. So we shouldn't push this as param.\n      // So we check whether the given VectorSelector is something we replaced earlier.\n      if (context.replacements?.[expr.substring(node.from, node.to)]) {\n        const identifierNode = node.getChild(Identifier);\n        const customVarName = getString(expr, identifierNode);\n        op.params.push(customVarName);\n        break;\n      }\n    }\n\n    default: {\n      // Means we get to something that does not seem like simple function arg and is probably nested query so jump\n      // back to main context\n      handleExpression(expr, node, context);\n    }\n  }\n}\n\n/**\n * Right now binary expressions can be represented in 2 way in visual query. As additional operation in case it is\n * just operation with scalar or it creates a binaryQuery when it's 2 queries.\n * @param expr\n * @param node\n * @param context\n */\nfunction handleBinary(expr: string, node: SyntaxNode, context: Context, idx = 0) {\n  const visQuery = context.query;\n  const left = node.firstChild!;\n  const op = getString(expr, left.nextSibling);\n  const binModifier = getBinaryModifier(expr, node.getChild(BoolModifier) ?? node.getChild(MatchingModifierClause));\n\n  const right = node.lastChild!;\n\n  const opDef = binaryScalarOperatorToOperatorName[op];\n\n  const leftNumber = left.type.id === NumberDurationLiteral;\n  const rightNumber = right.type.id === NumberDurationLiteral;\n\n  const rightBinary = right.type.id === BinaryExpr;\n\n  // binary operations that are part of a function argument do not get processed and added to the query until the end, this index helps keep track\n  // of where to add the operation in the list rather than just appending it to the end. If the binary operation is just part of a nested binary exp,\n  // we append at the end\n  const parent = node.parent;\n  const child = node.firstChild;\n  const shouldOffsetTail =\n    parent && !parent.type.isTop && (isFunctionOrAggregation(parent) || (child && isFunctionOrAggregation(child)));\n  if (shouldOffsetTail) {\n    idx += 1;\n  }\n  if (leftNumber) {\n    // TODO: this should be already handled in case parent is binary expression as it has to be added to parent\n    //  if query starts with a number that isn't handled now.\n  } else {\n    // If this is binary we don't really know if there is a query or just chained scalars. So\n    // we have to traverse a bit deeper to know\n    handleExpression(expr, left, context);\n  }\n\n  // in the case we have an expression like func(...) / 2 or func(...) + 5, the binary expression will be at the top of the tree\n  // in which case, the idx will be 0. In this case it means that the binary operation must be added to the end of the array, and\n\n  const newIdx = idx === 0 ? visQuery.operations.length : -idx;\n  if (rightNumber) {\n    visQuery.operations.splice(newIdx, 0, makeBinOp(opDef, expr, right, !!binModifier?.isBool));\n  } else if (rightBinary) {\n    // Due to the way binary ops are parsed we can get a binary operation on the right that starts with a number which\n    // is a factor for a current binary operation. So we have to add it as an operation now.\n    const leftMostChild = getLeftMostChild(right);\n    if (leftMostChild?.type.id === NumberDurationLiteral) {\n      visQuery.operations.splice(newIdx, 0, makeBinOp(opDef, expr, leftMostChild, !!binModifier?.isBool));\n    }\n\n    // If we added the first number literal as operation here we still can continue and handle the rest as the first\n    // number will be just skipped.\n    handleExpression(expr, right, context);\n  } else {\n    visQuery.binaryQueries = visQuery.binaryQueries || [];\n    const binQuery: PromVisualQueryBinary = {\n      operator: op,\n      query: {\n        metric: '',\n        labels: [],\n        operations: [],\n      },\n    };\n    if (binModifier?.isMatcher) {\n      binQuery.vectorMatchesType = binModifier.matchType;\n      binQuery.vectorMatches = binModifier.matches;\n    }\n    visQuery.binaryQueries.push(binQuery);\n    handleExpression(expr, right, {\n      query: binQuery.query,\n      errors: context.errors,\n      replacements: context.replacements,\n    });\n  }\n}\n\n// TODO revisit this function.\nfunction getBinaryModifier(\n  expr: string,\n  node: SyntaxNode | null\n):\n  | { isBool: true; isMatcher: false }\n  | { isBool: false; isMatcher: true; matches: string; matchType: 'ignoring' | 'on' }\n  | undefined {\n  if (!node) {\n    return undefined;\n  }\n  if (node.getChild('Bool')) {\n    return { isBool: true, isMatcher: false };\n  } else {\n    let labels = '';\n    const groupingLabels = node.getChild(GroupingLabels);\n    if (groupingLabels) {\n      labels = getAllByType(expr, groupingLabels, LabelName).join(', ');\n    }\n\n    return {\n      isMatcher: true,\n      isBool: false,\n      matches: labels,\n      matchType: node.getChild(On) ? 'on' : 'ignoring',\n    };\n  }\n}\n\nfunction isEmptyQuery(query: PromVisualQuery) {\n  if (query.labels.length === 0 && query.operations.length === 0 && !query.metric) {\n    return true;\n  }\n  return false;\n}\n"],"names":["replaceBuiltInVariable","replaceVariables","parser","Identifier","getString","QuotedLabelName","StringLiteral","QuotedLabelMatcher","ErrorId","makeError","UnquotedLabelMatcher","LabelName","FunctionCall","AggregateExpr","BinaryExpr","ParenExpr","VectorSelector","MatchOp","FunctionIdentifier","t","FunctionCallBody","returnBuiltInVariable","AggregateOp","AggregateModifier","Without","getAllByType","NumberDurationLiteral","BoolModifier","MatchingModifierClause","binaryScalarOperatorToOperatorName","isFunctionOrAggregation","makeBinOp","getLeftMostChild","GroupingLabels","On"],"mappings":";;;;;;;;;;AAoDO,SAAS,2BAA2B,IAAA,EAA6C;AACtF,EAAA,IAAA,GAAOA,oCAAuB,IAAI,CAAA;AAClC,EAAA,MAAM,EAAE,YAAA,EAAc,iBAAA,EAAkB,GAAIC,8BAAiB,IAAI,CAAA;AACjE,EAAA,MAAM,IAAA,GAAOC,kBAAA,CAAO,KAAA,CAAM,YAAY,CAAA;AACtC,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA;AAGlB,EAAA,MAAM,QAAA,GAA4B;AAAA,IAChC,MAAA,EAAQ,EAAA;AAAA,IACR,QAAQ,EAAC;AAAA,IACT,YAAY;AAAC,GACf;AACA,EAAA,MAAM,OAAA,GAAmB;A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