import { SyntaxNode } from '@lezer/common' ; import { EqlRegex , EqlSingle , LabelName , MatchOp , Neq , NeqRegex , StringLiteral } from '../grammar/parser.terms' ; import { EditorState } from '@codemirror/state' ; import { Matcher } from '../types' ; function createMatcher ( labelMatcher , state ) { const matcher = new Matcher ( 0 , '' , '' ) ; const cursor = labelMatcher . cursor ; if ( ! cursor . next ( ) ) { return matcher ; } do { switch ( cursor . type . id ) { case LabelName : matcher . name = state . sliceDoc ( cursor . from , cursor . to ) ; break ; case MatchOp : const ope = cursor . node . firstChild ; if ( ope ) { matcher . type = ope . type . id ; } break ; case StringLiteral : matcher . value = state . sliceDoc ( cursor . from , cursor . to ) . slice ( 1 , - 1 ) ; break ; } } while ( cursor . nextSibling ( ) ) ; return matcher ; } export function buildLabelMatchers ( labelMatchers , state ) { const matchers = [ ] ; labelMatchers . forEach ( ( value ) => { matchers . push ( createMatcher ( value , state ) ) ; } ) ; return matchers ; } export function labelMatchersToString ( metricName , matchers ? , labelName ? ) { if ( ! matchers || matchers . length === 0 ) { return metricName ; } let matchersAsString = '' ; for ( const matcher of matchers ) { if ( matcher . name === labelName || matcher . value === '' ) { continue ; } let type = '' ; switch ( matcher . type ) { case EqlSingle : type = '=' ; break ; case Neq : type = '!=' ; break ; case NeqRegex : type = '!~' ; break ; case EqlRegex : type = '=~' ; break ; default : type = '=' ; } const m = `${ matcher . name }${ type }"${ matcher . value }"` ; if ( matchersAsString === '' ) { matchersAsString = m ; } else { matchersAsString = `${ matchersAsString },${ m }` ; } } return `${ metricName }{${ matchersAsString }}` ; }