Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

518 lines · 13.6 KiB · Go

Last changed by

Add direct algo fast path in matchChunkJunegunn Choibefore adoption3e751c4

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       map[termType]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		procFun:       make(map[termType]algo.Algo)}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	// ChunkCache: Exact match304	cacheKey := p.CacheKey()305	if p.cacheable {306		if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {307			return cached308		}309	}310311	// Prefix/suffix cache312	space := p.cache.Search(chunk, cacheKey)313314	matches := p.matchChunk(chunk, space, slab)315316	if p.cacheable {317		p.cache.Add(chunk, cacheKey, matches)318	}319	return matches320}321322func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {323	matches := []Result{}324325	// Skip header items in chunks that contain them326	startIdx := 0327	if p.startIndex > 0 && chunk.count > 0 && chunk.items[0].Index() < p.startIndex {328		startIdx = int(p.startIndex - chunk.items[0].Index())329		if startIdx >= chunk.count {330			return matches331		}332	}333334	// Fast path: single fuzzy term, no nth, no denylist.335	// Calls the algo function directly, bypassing MatchItem/extendedMatch/iter336	// and avoiding per-match []Offset heap allocation.337	if p.directAlgo != nil && len(p.denylist) == 0 {338		t := p.directTerm339		if space == nil {340			for idx := startIdx; idx < chunk.count; idx++ {341				res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,342					&chunk.items[idx].text, t.text, p.withPos, slab)343				if res.Start >= 0 {344					matches = append(matches, buildResultFromBounds(345						&chunk.items[idx], res.Score,346						int(res.Start), int(res.End), int(res.End), true))347				}348			}349		} else {350			for _, result := range space {351				res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,352					&result.item.text, t.text, p.withPos, slab)353				if res.Start >= 0 {354					matches = append(matches, buildResultFromBounds(355						result.item, res.Score,356						int(res.Start), int(res.End), int(res.End), true))357				}358			}359		}360		return matches361	}362363	if len(p.denylist) == 0 {364		// Huge code duplication for minimizing unnecessary map lookups365		if space == nil {366			for idx := startIdx; idx < chunk.count; idx++ {367				if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {368					matches = append(matches, match)369				}370			}371		} else {372			for _, result := range space {373				if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match.item != nil {374					matches = append(matches, match)375				}376			}377		}378		return matches379	}380381	if space == nil {382		for idx := startIdx; idx < chunk.count; idx++ {383			if _, prs := p.denylist[chunk.items[idx].Index()]; prs {384				continue385			}386			if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {387				matches = append(matches, match)388			}389		}390	} else {391		for _, result := range space {392			if _, prs := p.denylist[result.item.Index()]; prs {393				continue394			}395			if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match.item != nil {396				matches = append(matches, match)397			}398		}399	}400	return matches401}402403// MatchItem returns the match result if the Item is a match.404// A zero-value Result (with item == nil) indicates no match.405func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (Result, []Offset, *[]int) {406	if p.extended {407		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {408			return buildResult(item, offsets, bonus), offsets, pos409		}410		return Result{}, nil, nil411	}412	offset, bonus, pos := p.basicMatch(item, withPos, slab)413	if sidx := offset[0]; sidx >= 0 {414		offsets := []Offset{offset}415		return buildResult(item, offsets, bonus), offsets, pos416	}417	return Result{}, nil, nil418}419420func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {421	var input []Token422	if len(p.nth) == 0 {423		input = []Token{{text: &item.text, prefixLength: 0}}424	} else {425		input = p.transformInput(item)426	}427	if p.fuzzy {428		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)429	}430	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)431}432433func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {434	var input []Token435	if len(p.nth) == 0 {436		input = []Token{{text: &item.text, prefixLength: 0}}437	} else {438		input = p.transformInput(item)439	}440	offsets := []Offset{}441	var totalScore int442	var allPos *[]int443	if withPos {444		allPos = &[]int{}445	}446	for _, termSet := range p.termSets {447		var offset Offset448		var currentScore int449		matched := false450		for _, term := range termSet {451			pfun := p.procFun[term.typ]452			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)453			if sidx := off[0]; sidx >= 0 {454				if term.inv {455					continue456				}457				offset, currentScore = off, score458				matched = true459				if withPos {460					if pos != nil {461						*allPos = append(*allPos, *pos...)462					} else {463						for idx := off[0]; idx < off[1]; idx++ {464							*allPos = append(*allPos, int(idx))465						}466					}467				}468				break469			} else if term.inv {470				offset, currentScore = Offset{0, 0}, 0471				matched = true472				continue473			}474		}475		if matched {476			offsets = append(offsets, offset)477			totalScore += currentScore478		}479	}480	return offsets, totalScore, allPos481}482483func (p *Pattern) transformInput(item *Item) []Token {484	if item.transformed != nil {485		transformed := *item.transformed486		if transformed.revision == p.revision {487			return transformed.tokens488		}489	}490491	tokens := Tokenize(item.text.ToString(), p.delimiter)492	ret := Transform(tokens, p.nth)493	// Strip the last delimiter to allow suffix match494	if len(ret) > 0 && !p.delimiter.IsAwk() {495		chars := ret[len(ret)-1].text496		stripped := StripLastDelimiter(chars.ToString(), p.delimiter)497		newChars := util.ToChars(stringBytes(stripped))498		ret[len(ret)-1].text = &newChars499	}500	item.transformed = &transformed{p.revision, ret}501	return ret502}503504func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {505	for _, part := range tokens {506		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {507			sidx := int32(res.Start) + part.prefixLength508			eidx := int32(res.End) + part.prefixLength509			if pos != nil {510				for idx := range *pos {511					(*pos)[idx] += int(part.prefixLength)512				}513			}514			return Offset{sidx, eidx}, res.Score, pos515		}516	}517	return Offset{-1, -1}, 0, nil518}