Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

501 lines · 13.2 KiB · Go

Last changed by

Not known.

History of this file

Take it

1package fzf23import (4	"fmt"5	"regexp"6	"strings"78	"github.com/junegunn/fzf/src/algo"9	"github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^prefix-exact15// suffix-exact$16// !inverse-exact17// !'inverse-fuzzy18// !^inverse-prefix-exact19// !inverse-suffix-exact$2021type termType int2223const (24	termFuzzy termType = iota25	termExact26	termExactBoundary27	termPrefix28	termSuffix29	termEqual30)3132type term struct {33	typ           termType34	inv           bool35	text          []rune36	caseSensitive bool37	normalize     bool38}3940// String returns the string representation of a term.41func (t term) String() string {42	return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)43}4445type termSet []term4647// Pattern represents search pattern48type Pattern struct {49	fuzzy         bool50	fuzzyAlgo     algo.Algo51	extended      bool52	caseSensitive bool53	normalize     bool54	forward       bool55	withPos       bool56	text          []rune57	termSets      []termSet58	sortable      bool59	cacheable     bool60	cacheKey      string61	delimiter     Delimiter62	nth           []Range63	revision      revision64	procFun       [6]algo.Algo65	cache         *ChunkCache66	denylist      map[int32]struct{}67	startIndex    int3268	directAlgo    algo.Algo69	directTerm    *term70}7172var _splitRegex *regexp.Regexp7374func init() {75	_splitRegex = regexp.MustCompile(" +")76}7778// BuildPattern builds Pattern object from the given arguments79func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,80	withPos bool, cacheable bool, nth []Range, delimiter Delimiter, revision revision, runes []rune, denylist map[int32]struct{}, startIndex int32) *Pattern {8182	var asString string83	if extended {84		asString = strings.TrimLeft(string(runes), " ")85		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {86			asString = asString[:len(asString)-1]87		}88	} else {89		asString = string(runes)90	}9192	// We can uniquely identify the pattern for a given string since93	// search mode and caseMode do not change while the program is running94	cached, found := patternCache[asString]95	if found {96		return cached97	}9899	caseSensitive := true100	sortable := true101	termSets := []termSet{}102103	if extended {104		termSets = parseTerms(fuzzy, caseMode, normalize, asString)105		// We should not sort the result if there are only inverse search terms106		sortable = false107	Loop:108		for _, termSet := range termSets {109			for idx, term := range termSet {110				if !term.inv {111					sortable = true112				}113				// If the query contains inverse search terms or OR operators,114				// we cannot cache the search scope115				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {116					cacheable = false117					if sortable {118						// Can't break until we see at least one non-inverse term119						break Loop120					}121				}122			}123		}124	} else {125		lowerString := strings.ToLower(asString)126		normalize = normalize &&127			lowerString == string(algo.NormalizeRunes([]rune(lowerString)))128		caseSensitive = caseMode == CaseRespect ||129			caseMode == CaseSmart && lowerString != asString130		if !caseSensitive {131			asString = lowerString132		}133	}134135	ptr := &Pattern{136		fuzzy:         fuzzy,137		fuzzyAlgo:     fuzzyAlgo,138		extended:      extended,139		caseSensitive: caseSensitive,140		normalize:     normalize,141		forward:       forward,142		withPos:       withPos,143		text:          []rune(asString),144		termSets:      termSets,145		sortable:      sortable,146		cacheable:     cacheable,147		nth:           nth,148		revision:      revision,149		delimiter:     delimiter,150		cache:         cache,151		denylist:      denylist,152		startIndex:    startIndex,153	}154155	ptr.cacheKey = ptr.buildCacheKey()156	ptr.directAlgo, ptr.directTerm = ptr.buildDirectAlgo(fuzzyAlgo)157	ptr.procFun[termFuzzy] = fuzzyAlgo158	ptr.procFun[termEqual] = algo.EqualMatch159	ptr.procFun[termExact] = algo.ExactMatchNaive160	ptr.procFun[termExactBoundary] = algo.ExactMatchBoundary161	ptr.procFun[termPrefix] = algo.PrefixMatch162	ptr.procFun[termSuffix] = algo.SuffixMatch163164	patternCache[asString] = ptr165	return ptr166}167168func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {169	str = strings.ReplaceAll(str, "\\ ", "\t")170	tokens := _splitRegex.Split(str, -1)171	sets := []termSet{}172	set := termSet{}173	switchSet := false174	afterBar := false175	for _, token := range tokens {176		typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")177		lowerText := strings.ToLower(text)178		caseSensitive := caseMode == CaseRespect ||179			caseMode == CaseSmart && text != lowerText180		normalizeTerm := normalize &&181			lowerText == string(algo.NormalizeRunes([]rune(lowerText)))182		if !caseSensitive {183			text = lowerText184		}185		if !fuzzy {186			typ = termExact187		}188189		if len(set) > 0 && !afterBar && text == "|" {190			switchSet = false191			afterBar = true192			continue193		}194		afterBar = false195196		if strings.HasPrefix(text, "!") {197			inv = true198			typ = termExact199			text = text[1:]200		}201202		if text != "$" && strings.HasSuffix(text, "$") {203			typ = termSuffix204			text = text[:len(text)-1]205		}206207		if len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {208			typ = termExactBoundary209			text = text[1 : len(text)-1]210		} else if strings.HasPrefix(text, "'") {211			// Flip exactness212			if fuzzy && !inv {213				typ = termExact214			} else {215				typ = termFuzzy216			}217			text = text[1:]218		} else if strings.HasPrefix(text, "^") {219			if typ == termSuffix {220				typ = termEqual221			} else {222				typ = termPrefix223			}224			text = text[1:]225		}226227		if len(text) > 0 {228			if switchSet {229				sets = append(sets, set)230				set = termSet{}231			}232			textRunes := []rune(text)233			if normalizeTerm {234				textRunes = algo.NormalizeRunes(textRunes)235			}236			set = append(set, term{237				typ:           typ,238				inv:           inv,239				text:          textRunes,240				caseSensitive: caseSensitive,241				normalize:     normalizeTerm})242			switchSet = true243		}244	}245	if len(set) > 0 {246		sets = append(sets, set)247	}248	return sets249}250251// IsEmpty returns true if the pattern is effectively empty252func (p *Pattern) IsEmpty() bool {253	if len(p.denylist) > 0 {254		return false255	}256	if !p.extended {257		return len(p.text) == 0258	}259	return len(p.termSets) == 0260}261262// AsString returns the search query in string type263func (p *Pattern) AsString() string {264	return string(p.text)265}266267func (p *Pattern) buildCacheKey() string {268	if !p.extended {269		return p.AsString()270	}271	cacheableTerms := []string{}272	for _, termSet := range p.termSets {273		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {274			cacheableTerms = append(cacheableTerms, string(termSet[0].text))275		}276	}277	return strings.Join(cacheableTerms, "\t")278}279280// buildDirectAlgo returns the algo function and term for the direct fast path281// in matchChunk. Returns (nil, nil) if the pattern is not suitable.282// Requirements: extended mode, single term set with single non-inverse fuzzy term, no nth.283func (p *Pattern) buildDirectAlgo(fuzzyAlgo algo.Algo) (algo.Algo, *term) {284	if !p.extended || len(p.nth) > 0 {285		return nil, nil286	}287	if len(p.termSets) == 1 && len(p.termSets[0]) == 1 {288		t := &p.termSets[0][0]289		if !t.inv && t.typ == termFuzzy {290			return fuzzyAlgo, t291		}292	}293	return nil, nil294}295296// CacheKey is used to build string to be used as the key of result cache297func (p *Pattern) CacheKey() string {298	return p.cacheKey299}300301// Match returns the list of matches Items in the given Chunk302func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {303	cacheKey := p.CacheKey()304305	// Bitmap cache: exact match or prefix/suffix306	var cachedBitmap *ChunkBitmap307	if p.cacheable {308		cachedBitmap = p.cache.Lookup(chunk, cacheKey)309	}310	if cachedBitmap == nil {311		cachedBitmap = p.cache.Search(chunk, cacheKey)312	}313314	matches, bitmap := p.matchChunk(chunk, cachedBitmap, slab)315316	if p.cacheable {317		p.cache.Add(chunk, cacheKey, bitmap, len(matches))318	}319	return matches320}321322func (p *Pattern) matchChunk(chunk *Chunk, cachedBitmap *ChunkBitmap, slab *util.Slab) ([]Result, ChunkBitmap) {323	matches := []Result{}324	var bitmap ChunkBitmap325326	// Skip header items in chunks that contain them327	startIdx := 0328	if p.startIndex > 0 && chunk.count > 0 && chunk.items[0].Index() < p.startIndex {329		startIdx = int(p.startIndex - chunk.items[0].Index())330		if startIdx >= chunk.count {331			return matches, bitmap332		}333	}334335	hasCachedBitmap := cachedBitmap != nil336337	// Fast path: single fuzzy term, no nth, no denylist.338	// Calls the algo function directly, bypassing MatchItem/extendedMatch/iter339	// and avoiding per-match []Offset heap allocation.340	if p.directAlgo != nil && len(p.denylist) == 0 {341		t := p.directTerm342		for idx := startIdx; idx < chunk.count; idx++ {343			if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {344				continue345			}346			res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,347				&chunk.items[idx].text, t.text, p.withPos, slab)348			if res.Start >= 0 {349				bitmap[idx/64] |= uint64(1) << (idx % 64)350				matches = append(matches, buildResultFromBounds(351					&chunk.items[idx], res.Score,352					int(res.Start), int(res.End), int(res.End), true))353			}354		}355		return matches, bitmap356	}357358	if len(p.denylist) == 0 {359		for idx := startIdx; idx < chunk.count; idx++ {360			if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {361				continue362			}363			if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {364				bitmap[idx/64] |= uint64(1) << (idx % 64)365				matches = append(matches, match)366			}367		}368		return matches, bitmap369	}370371	for idx := startIdx; idx < chunk.count; idx++ {372		if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {373			continue374		}375		if _, prs := p.denylist[chunk.items[idx].Index()]; prs {376			continue377		}378		if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {379			bitmap[idx/64] |= uint64(1) << (idx % 64)380			matches = append(matches, match)381		}382	}383	return matches, bitmap384}385386// MatchItem returns the match result if the Item is a match.387// A zero-value Result (with item == nil) indicates no match.388func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (Result, []Offset, *[]int) {389	if p.extended {390		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {391			return buildResult(item, offsets, bonus), offsets, pos392		}393		return Result{}, nil, nil394	}395	offset, bonus, pos := p.basicMatch(item, withPos, slab)396	if sidx := offset[0]; sidx >= 0 {397		offsets := []Offset{offset}398		return buildResult(item, offsets, bonus), offsets, pos399	}400	return Result{}, nil, nil401}402403func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {404	var input []Token405	if len(p.nth) == 0 {406		input = []Token{{text: &item.text, prefixLength: 0}}407	} else {408		input = p.transformInput(item)409	}410	if p.fuzzy {411		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)412	}413	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)414}415416func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {417	var input []Token418	if len(p.nth) == 0 {419		input = []Token{{text: &item.text, prefixLength: 0}}420	} else {421		input = p.transformInput(item)422	}423	offsets := []Offset{}424	var totalScore int425	var allPos *[]int426	if withPos {427		allPos = &[]int{}428	}429	for _, termSet := range p.termSets {430		var offset Offset431		var currentScore int432		matched := false433		for _, term := range termSet {434			pfun := p.procFun[term.typ]435			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)436			if sidx := off[0]; sidx >= 0 {437				if term.inv {438					continue439				}440				offset, currentScore = off, score441				matched = true442				if withPos {443					if pos != nil {444						*allPos = append(*allPos, *pos...)445					} else {446						for idx := off[0]; idx < off[1]; idx++ {447							*allPos = append(*allPos, int(idx))448						}449					}450				}451				break452			} else if term.inv {453				offset, currentScore = Offset{0, 0}, 0454				matched = true455				continue456			}457		}458		if matched {459			offsets = append(offsets, offset)460			totalScore += currentScore461		}462	}463	return offsets, totalScore, allPos464}465466func (p *Pattern) transformInput(item *Item) []Token {467	if item.transformed != nil {468		transformed := *item.transformed469		if transformed.revision == p.revision {470			return transformed.tokens471		}472	}473474	tokens := Tokenize(item.text.ToString(), p.delimiter)475	ret := Transform(tokens, p.nth)476	// Strip the last delimiter to allow suffix match477	if len(ret) > 0 && !p.delimiter.IsAwk() {478		chars := ret[len(ret)-1].text479		stripped := StripLastDelimiter(chars.ToString(), p.delimiter)480		newChars := util.ToChars(stringBytes(stripped))481		ret[len(ret)-1].text = &newChars482	}483	item.transformed = &transformed{p.revision, ret}484	return ret485}486487func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {488	for _, part := range tokens {489		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {490			sidx := int32(res.Start) + part.prefixLength491			eidx := int32(res.End) + part.prefixLength492			if pos != nil {493				for idx := range *pos {494					(*pos)[idx] += int(part.prefixLength)495				}496			}497			return Offset{sidx, eidx}, res.Score, pos498		}499	}500	return Offset{-1, -1}, 0, nil501}