Repository navigation
Description
Proposal: compiled glob matching and streaming file selection
Background and motivation
.NET has simple filename wildcard matching and the Microsoft.Extensions.FileSystemGlobbing package, but no common API that combines reusable span-based glob matching with streaming, composable filesystem selection. Callers need to match text without I/O, reuse patterns across walks, and include or exclude files without constructing a result path for each rejected file.
Existing FileSystemEnumerable<TResult> predicates can already filter using spans before projecting a result. A custom FileSystemEnumerator<TResult> can also manage directory-completion and disposal callbacks. The gap is a reusable contract for independent matchers, hosts, and rule composition - not an inability to implement a fast filter today.
This proposal responds to dotnet/runtime#132060, including the questions about the natural FileSystemGlobbing extension, the need for a matching abstraction, and non-filesystem uses.
Recommendation and review units
Add the APIs beside the existing Matcher in the Microsoft.Extensions.FileSystemGlobbing package. Review them separately:
- Compiled text matching in
Microsoft.Extensions.Globbing: one small, explicitly specified .NET grammar, with flat or configurable segmented matching. - File selection in
Microsoft.Extensions.FileSystemGlobbing.Enumeration: reusable definitions, sessions, composition, and streaming enumeration. AGlobfacade supplies the common one-shot operations.
The second unit depends on the first, not the reverse; compilation and matching perform no I/O. Initially expose the new surface in .NET 8-and-later package assets and leave existing downlevel assets unchanged, subject to package-compatibility review. This placement keeps the immediate API out of the BCL, but pure-text callers must reference a filesystem-named package. An inbox protocol would be needed if a future inbox API must accept these matchers; System.IO cannot depend on Microsoft.Extensions.
Design principles and goals
- Simple common use: offer a direct way to match or enumerate one pattern and an explicitly reusable compiled form for repeated matching.
- Independent lifetimes: separate root-independent compiled patterns and reusable matcher definitions from mutable state owned by one enumeration.
- Streaming and low allocation: pass directory and name spans through matching and composition; reject files before constructing result paths or objects. Allow projection to metadata instead of a path.
- Sound pruning: distinguish no possible matching descendant, an unknown or mixed subtree, and all descendants matching. Compose those proofs conservatively, including ordered re-inclusion.
- Explicit semantics: specify the initial grammar, comparison, separators, errors, and traversal defaults. Do not claim compatibility with a product's dialect without its required policy and tests.
- Host neutrality: allow a physical filesystem enumerator or another host to drive the same session contract without manufacturing a
FileSystemEntry. - Bounded, reviewable behavior: avoid hidden unbounded caches and require a verified resource story for untrusted input. Treat uncertainty as a reason to do more work, not as evidence of safety.
The first release does not parse .gitignore files, reproduce MSBuild policy, return directories or FSG stems, provide watcher invalidation, parse URLs, or enforce filesystem confinement. None of those is implied by matching path text.
Why these layers exist
| Layer | Responsibility | Why it is separate |
|---|---|---|
| Compiled pattern | Immutable text matching | Reuse compilation without I/O, a root, or traversal state. |
| Matcher definition | Reusable selection rule | Compose glob and non-glob rules without binding them to a particular walk. |
| Matcher session | Mutable state for one walk | Cache directory work and release it independently for concurrent walks or roots. |
| Directory/name spans | Borrowed host input | Filter before projection without joining a path; an independent host need not construct a FileSystemEntry. |
| Three-state proof | Descendant classification | Composition can invert an all descendants exclusion proof without treating an unknown result as a reason to discard files. |
| Enumerator or other host | Traversal and result projection | Let physical, replay, or archive hosts retain control of I/O, scheduling, and output. |
These are not speculative abstractions: Touki's history introduced per-enumeration sessions and role-neutral proofs in 9d92503, and later separated the text object from its filesystem adapter in ea3ff4a. They do not prove that the exact public shape below is already implemented or fast enough.
Compilation also resolves syntax and pattern shape once, allowing literal or suffix fast paths alongside a general engine. Those strategies are implementation details, not public bytecode or parser plug-ins. Eliminating per-walk state can repeat directory alignment work; putting that state on a shared definition risks interference between walks. A custom enumerator can instead manage equivalent private state. Replacing the three-state result with one role-neutral Boolean cannot express the universal proof needed to invert exclusions.
Proposed API
These are API-review declarations, not implementations. GlobPattern has no filesystem dependency. Compile once for repeated use; the span overloads copy the pattern into owned storage. Pattern retains the original text for inspection, at the cost of one retained string per compiled pattern.
Unit 1: compiled text matching
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Extensions.Globbing
{
public enum GlobCompileErrorCode
{
None = 0,
InvalidSyntax = 1,
PatternTooLong = 2
}
public readonly struct GlobCompileError
{
public GlobCompileErrorCode Code { get; }
public int Position { get; }
public string Message { get; }
}
public sealed class GlobPattern
{
private GlobPattern();
// A null separator selects flat matching; '/' selects path-like segments.
public static GlobPattern Compile(
string pattern,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
public static GlobPattern Compile(
ReadOnlySpan<char> pattern,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
// Format failures are returned; invalid arguments still throw.
public static bool TryCompile(
string pattern,
[NotNullWhen(true)] out GlobPattern? result,
out GlobCompileError error,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
public static bool TryCompile(
ReadOnlySpan<char> pattern,
[NotNullWhen(true)] out GlobPattern? result,
out GlobCompileError error,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
public string Pattern { get; }
public char? Separator { get; }
public StringComparison Comparison { get; }
// Concurrent calls are supported; no caller-owned span is retained.
public bool IsMatch(string input);
public bool IsMatch(ReadOnlySpan<char> input);
}
}Unit 2: convenience, sessions, composition, and enumeration
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using Microsoft.Extensions.Globbing;
namespace Microsoft.Extensions.FileSystemGlobbing
{
public static class Glob
{
// One-shot matching compiles each time; use GlobPattern for reuse.
public static bool IsMatch(
string pattern,
string input,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
public static bool IsMatch(
string pattern,
ReadOnlySpan<char> input,
char? separator = '/',
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
// Streams '/'-separated paths relative to rootDirectory, not full paths.
public static IEnumerable<string> EnumerateFiles(
string rootDirectory,
string pattern,
EnumerationOptions? options = null,
StringComparison comparison = StringComparison.Ordinal,
int maxPatternLength = 4096);
}
}
namespace Microsoft.Extensions.FileSystemGlobbing.Enumeration
{
public enum DirectoryMatchType
{
MayContainMatchingFiles = 0,
NoDescendantFilesMatch = 1,
AllDescendantFilesMatch = 2
}
public interface IFileSystemMatcher
{
// Creates caller-owned state for one root and one walk.
IFileSystemMatcherSession CreateSession(string rootDirectory);
}
public interface IFileSystemMatcherSession : IDisposable
{
bool MatchesFile(ReadOnlySpan<char> currentDirectory, ReadOnlySpan<char> fileName);
// Classifies descendant files, not the directory entry itself.
DirectoryMatchType ClassifyDescendants(
ReadOnlySpan<char> currentDirectory,
ReadOnlySpan<char> directoryName);
void DirectoryFinished(ReadOnlySpan<char> directory);
}
public delegate bool FileSystemMatchPredicate(
ReadOnlySpan<char> currentDirectory,
ReadOnlySpan<char> fileName);
public delegate bool PathMatchPredicate(ReadOnlySpan<char> rootRelativePath);
public enum FileSystemMatchAction
{
Include = 0,
Exclude = 1
}
public sealed class FileSystemMatchRule
{
public FileSystemMatchRule(IFileSystemMatcher matcher, FileSystemMatchAction action);
public IFileSystemMatcher Matcher { get; }
public FileSystemMatchAction Action { get; }
}
public static class FileSystemMatcher
{
// Adapts a '/'-segmented pattern without joining a path per file.
public static IFileSystemMatcher FromGlob(GlobPattern pattern);
// File predicates cannot prove a subtree, so both adapters return May.
public static IFileSystemMatcher Create(FileSystemMatchPredicate predicate);
public static IFileSystemMatcher CreatePath(PathMatchPredicate predicate);
// Any include, unless any exclude matches; includes must be nonempty.
public static IFileSystemMatcher CreateExclusionWins(
IReadOnlyList<IFileSystemMatcher> includes,
IReadOnlyList<IFileSystemMatcher>? excludes = null);
// The last matching rule wins; unmatched files use includeUnmatched.
public static IFileSystemMatcher CreateOrdered(
IReadOnlyList<FileSystemMatchRule> rules,
bool includeUnmatched = false);
public static IEnumerable<string> EnumerateFiles(
string rootDirectory,
IFileSystemMatcher matcher,
EnumerationOptions? options = null);
// The optional entry predicate runs after matching, before projection.
public static IEnumerable<TResult> Enumerate<TResult>(
string rootDirectory,
IFileSystemMatcher matcher,
FileSystemEnumerable<TResult>.FindTransform transform,
FileSystemEnumerable<TResult>.FindPredicate? includeEntry = null,
EnumerationOptions? options = null);
}
}Pattern semantics and limits
The initial language is a new .NET grammar, not a claim of POSIX, Bash, Git, MSBuild, PowerShell, or existing FSG compatibility. Matching is anchored to the entire input.
| Construct | Meaning |
|---|---|
| Literal | Matches itself under the selected ordinal comparison. |
* |
Zero or more UTF-16 code units within one segment, or anywhere in flat mode. |
? |
Exactly one UTF-16 code unit within one segment, or anywhere in flat mode. |
[abc], [a-z], [!0-9], [^0-9] |
One code unit from a set, range, or negated set; never a separator. |
** as an entire segment |
Zero or more segments. App.**.Title matches App.Title and App.Dialog.Title. |
| Backslash | Quotes the next pattern code unit; it cannot quote the active separator. |
With separator: null there are no segments and adjacent stars act like one ordinary *. With a separator, ** is recursive only when it is a complete segment; a**b acts like a*b, and *** acts like *. Because a whole-segment ** can consume zero segments, obj/** matches the lexical input obj as well as obj/file.cs. In file enumeration that also means a file named obj can match. Existing FSG Matcher does not match that standalone file with obj/**.
The default separator is /. A caller may choose another single UTF-16 code unit, such as . or :, or select flat mode with null. NUL, surrogate code units, backslash, *, ?, [, ], !, ^, and - are invalid separators because they are sentinels or grammar characters. Separator recognition is exact, even with OrdinalIgnoreCase. There is no implicit slash/backslash translation.
Inputs and patterns are split into segments without filesystem normalization. Leading, trailing, and repeated separators produce empty segments; splitting an empty string produces one empty segment. A separator cannot appear inside a character class. The compiler does not interpret . or .., drives, roots, or URIs. Filesystem adapters separately supply canonical root-relative paths, so actual file components are nonempty and are not . or ...
An unescaped initial ! or ^ negates a class; escape it to use it as the first literal member. An unescaped - at either end is literal; otherwise it forms an inclusive ordinal range. Escape a literal ], -, backslash, or [ with backslash when needed in a class. An unmatched ] outside a class is literal. Empty or unterminated classes, reversed or chained ranges, an unescaped [ within a class, and dangling escapes are syntax errors. Braces, parentheses, |, and leading ! have no special meaning outside a class: there is no extglob, brace expansion, or Git rule negation. Wildcards may match leading dots.
Only StringComparison.Ordinal and OrdinalIgnoreCase are accepted. Literal runs use that comparison; a class first defines a set of UTF-16 code units and, for ignore-case matching, includes each one-unit ordinal-ignore-case equivalent before negation. There is no Unicode normalization, culture-specific comparison, filesystem casing inference, or guarantee that one ? consumes one Unicode scalar or grapheme.
Compile throws FormatException for malformed or over-limit pattern text. TryCompile returns false, a null result, and a diagnostic for those failures only. Null strings throw ArgumentNullException; invalid separators, comparisons, and negative limits throw ArgumentOutOfRangeException in both methods. A successful TryCompile returns default error: Code == None, Position == -1, and an empty message. For an over-limit pattern, Position is the first disallowed index, equal to the bound. Positions are UTF-16 indices; messages are descriptive, not a parsing contract. A default input span is empty; a null string input throws.
The proposed default maximum is 4,096 pattern code units. A nonnegative caller-selected limit can raise or lower it; int.MaxValue is an explicit choice without a practical pattern-length cap. The limit is checked before retaining or parsing the pattern, including through one-shot helpers. This number is a proposal to validate against real workloads, not a measured optimum. Allocation failures and checked arithmetic failures propagate rather than changing a match into false.
The implementation must use non-recursive bounded-state matching: for pattern length P and input length N, compilation uses O(P + 1) work and storage, and matching uses at most O((P + 1) * (N + 1)) work and O(P + 1) temporary storage. These are proposed acceptance requirements, not measured properties of the prototype. Applications must still bound total request and traversal work.
FileSystemMatcher.FromGlob accepts only /-segmented patterns and throws ArgumentException otherwise. This prevents a dot-delimited resource-key pattern from silently treating dots in filenames as directories. It interprets native Windows directory separators as / without translating a Unix filename's literal backslash. For every file, its split-span result must equal pattern.IsMatch on the equivalent canonical root-relative path. Direct text matching does not translate Windows paths; callers supply the intended representation. For a flat filename predicate, use Create; for a deliberate root-relative joined-span predicate, use CreatePath. The latter may use temporary stack or pooled storage, never exposes the span beyond the callback, and throws PathTooLongException on an unrepresentable joined length instead of returning a nonmatch. A built-in composition constructs at most one joined span per file for compatible CreatePath children; split-only compositions do not join. Opaque custom matchers have no such guarantee.
Configurable non-filesystem separators are new and unverified. Touki currently exposes only slash/backslash choices, and its filesystem normalization and escape handling cannot be assumed correct for .. Implement and test this neutral grammar rather than treating a separator field as proof that the feature already works.
Session, path, and ownership contract
The physical host resolves the conceptual root with Path.GetFullPath once when the sequence is created. It removes a trailing directory separator unless the path is itself a filesystem root. Each active enumeration owns an independent session. Completion, failure, or disposal of the enumerator disposes it; a caller that stops early must dispose the enumerator. Definitions and compiled patterns are reusable, but sessions are single-threaded. A parallel host uses independent sessions with the same conceptual root; rebasing at a partition changes which paths match.
Each callback receives the absolute native-separated current directory and one nonempty entry name. The directory is the root or a descendant retaining the root's exact lexical prefix; the entry name is one component, not . or ... The root's own name is not part of the match. On Unix, a backslash in a name is data. Callback spans are borrowed only for the duration of the call; a matcher that retains data must copy it.
All callbacks for a directory form a contiguous group. On normal exhaustion, the host calls DirectoryFinished before starting the next group. This reports completion of the directory's immediate entries, not completion of its descendants. No completion callback is promised for an unopened directory or an interrupted group; disposal is always required. A host need not classify the root or call ClassifyDescendants before matching files. Match results must not depend on callback count or order, although a session may cache directory work. An ordinary watcher stream does not meet these grouping and invalidation requirements without an adapter.
Built-in sessions reject null or non-normalized roots and perform no filesystem lookup when created. Callback paths must obey the host invariants rather than being fully revalidated for every entry. Disposal is idempotent; use after disposal is invalid. Each successful CreateSession must return a fresh session. Built-in compositions reject null or aliased child sessions with InvalidOperationException and dispose each distinct created session once. Factories snapshot rule lists and borrow their definition objects, while a composite session owns its child sessions. A failed construction or traversal must clean up every child it created; callback and cleanup failures are surfaced, never converted into a nonmatch. If internal work and cleanup both fail, an AggregateException contains the original failure first; multiple cleanup failures are also aggregated. Exceptions from a consumer's foreach body follow normal language disposal rules. Delegate captures remain the caller's responsibility and must be stable and thread-safe for concurrent use.
The contract describes lexical paths. Normalization does not resolve links, establish physical identity, or confine traversal to a security boundary.
Sound pruning and rule composition
For a candidate directory, the classification describes all possible descendant files, not the directory entry itself:
| Result | Assertion |
|---|---|
NoDescendantFilesMatch |
None can match; a final composed result may prune the subtree. |
MayContainMatchingFiles |
Unknown or mixed; do not prune on matching grounds. This is always safe. |
AllDescendantFilesMatch |
Every descendant file matches; this is a proof for composition, not a result to return. |
MayContainMatchingFiles is the zero enum value and the fallback for an unrecognized value. Matchers must return May unless they can establish a sound universal proof; a missed prune costs time, while a false None loses results. Attribute filters, inaccessible entries, and a currently empty directory do not strengthen a language-level proof.
Exclusion-wins composition evaluates OR(includes) AND NOT OR(excludes). Negation exchanges None and All and leaves May unchanged. An ordered rule set starts from includeUnmatched; each matching rule replaces the file result, so the last matching rule wins. For a subtree, an All rule replaces the set of possible results and a May rule adds its action's result. The final set is None, All, or May according to whether it contains only false, only true, or both.
For example, including **/*.cs, excluding **/obj/**, and then including **/obj/keep.cs must not prune obj: the later rule can rescue that file. Without the later include, a sound All proof for the exclusion permits pruning obj. Ordered rules alone are not .gitignore semantics.
Exclusion-wins requires at least one include; null or empty excludes exclude nothing. Ordered composition accepts an empty list and uses includeUnmatched. Null required arguments throw ArgumentNullException; an empty required include list or null element throws ArgumentException; an undefined rule action throws ArgumentOutOfRangeException. Built-in compositions may short-circuit and must not require stack depth proportional to nested caller-supplied composition.
The built-in glob adapter must prove None for an impossible anchored literal prefix, such as docs under src/**/*.cs, and All for a subtree wholly covered by **/obj/**. Any case it cannot prove safely returns May.
Enumeration behavior and defaults
The sequence factories validate arguments, compile a one-shot pattern, normalize the root, and snapshot supplied options when called; filesystem I/O begins during enumeration. Sequences are restartable: each active enumeration owns a new session and traversal. Concurrent enumeration is supported when any custom definitions and delegate captures are also safe for it. Ordering is unspecified, and one visited file is returned at most once regardless of how many include rules match it.
options: null deliberately means recursive traversal with IgnoreInaccessible = true and AttributesToSkip = Hidden | System; other properties keep their new EnumerationOptions() defaults. A supplied options object is copied without merging. In particular, new EnumerationOptions() is nonrecursive. To include hidden entries or report inaccessible paths, set those properties explicitly. Neither default skips reparse points, and no link-cycle detection or confinement is promised.
MatchCasing and MatchType do not override the compiled matcher; choose the pattern's comparison and grammar at compilation. Special . and .. directories are never returned or traversed, even if requested by enumeration options. Recursion, maximum depth, and attribute settings otherwise control which entries reach the matcher.
EnumerateFiles returns files only, as root-relative strings using / between components and no leading slash. A Unix backslash inside a filename is preserved. These strings are data, not escaped glob patterns. Enumerate<TResult> passes the live FileSystemEntry to its optional metadata predicate after the matcher accepts a file and to its transform only if that predicate also accepts it. The predicate is always applied even when a matcher has an All proof. Neither delegate may retain entry-backed spans.
The APIs do not promise a filesystem snapshot or sorted order. File access and matcher exceptions propagate under the chosen traversal policy. IgnoreInaccessible = true can omit entries; set it to false when those errors matter. Accepted result strings, directory paths and queues, operating-system buffers, and pool misses may allocate.
Examples
These are proposed usage examples, not reports of executed filesystem walks.
Compile once and match without I/O
using System;
using Microsoft.Extensions.Globbing;
using Microsoft.Extensions.FileSystemGlobbing;
GlobPattern sources = GlobPattern.Compile(
"src/**/*.cs",
comparison: StringComparison.OrdinalIgnoreCase);
string[] inputs = ["src/Parser.cs", "src/Core/Parser.CS", "docs/readme.md"];
// Expected: true, true, false.
foreach (string input in inputs)
{
Console.WriteLine(sources.IsMatch(input));
}
// One-shot matching compiles for this call.
Console.WriteLine(Glob.IsMatch("*.cs", "Program.cs"));
if (GlobPattern.TryCompile(
"src/[ab]/**/*.cs",
out GlobPattern? bounded,
out GlobCompileError error,
maxPatternLength: 1024))
{
Console.WriteLine(bounded.IsMatch("src/a/Parser.cs"));
}
else
{
Console.Error.WriteLine($"{error.Code} at {error.Position}: {error.Message}");
}Stream includes and excludes
using System;
using System.IO;
using System.IO.Enumeration;
using Microsoft.Extensions.Globbing;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.FileSystemGlobbing.Enumeration;
string root = Environment.CurrentDirectory;
static IFileSystemMatcher Rule(string pattern) =>
FileSystemMatcher.FromGlob(GlobPattern.Compile(pattern, comparison: StringComparison.OrdinalIgnoreCase));
IFileSystemMatcher sources = Rule("**/*.cs");
IFileSystemMatcher obj = Rule("**/obj/**");
IFileSystemMatcher bin = Rule("**/bin/**");
IFileSystemMatcher selected = FileSystemMatcher.CreateExclusionWins([sources], [obj, bin]);
EnumerationOptions options = new()
{
RecurseSubdirectories = true,
IgnoreInaccessible = false,
AttributesToSkip = FileAttributes.ReparsePoint
};
foreach (string relativePath in FileSystemMatcher.EnumerateFiles(root, selected, options))
{
Console.WriteLine(relativePath);
}
// Project metadata without creating a result path; filter empty files first.
long totalLength = 0;
foreach (long length in FileSystemMatcher.Enumerate<long>(
root,
selected,
static (ref FileSystemEntry entry) => entry.Length,
static (ref FileSystemEntry entry) => entry.Length > 0,
options))
{
totalLength += length;
}
Console.WriteLine(totalLength);
// A later include rescues obj/keep.cs, so the ordered matcher cannot prune obj.
IFileSystemMatcher ordered = FileSystemMatcher.CreateOrdered(
[
new(sources, FileSystemMatchAction.Include),
new(obj, FileSystemMatchAction.Exclude),
new(Rule("**/obj/keep.cs"), FileSystemMatchAction.Include)
]);
foreach (string path in FileSystemMatcher.EnumerateFiles(root, ordered, options))
{
Console.WriteLine(path);
}
// For one pattern, compilation and the matcher adapter are implicit.
foreach (string path in Glob.EnumerateFiles(root, "**/*.md", options))
{
Console.WriteLine(path);
}The explicit options include hidden/system entries while skipping descendant reparse points. The built-in obj and bin exclusions can prove every descendant matches, so exclusion-wins can prune those subtrees before visiting their files.
Custom matcher with a sound subtree proof
This exclusion matches every file under a root-relative component named scratch. It returns All for that subtree and May elsewhere; the root's own name is not a component of the match.
using System;
using System.IO;
using Microsoft.Extensions.Globbing;
using Microsoft.Extensions.FileSystemGlobbing.Enumeration;
string root = Environment.CurrentDirectory;
IFileSystemMatcher sources = FileSystemMatcher.FromGlob(GlobPattern.Compile("**/*.cs"));
IFileSystemMatcher selected = FileSystemMatcher.CreateExclusionWins([sources], [new ScratchSubtree()]);
foreach (string path in FileSystemMatcher.EnumerateFiles(root, selected))
{
Console.WriteLine(path);
}
sealed class ScratchSubtree : IFileSystemMatcher
{
public IFileSystemMatcherSession CreateSession(string rootDirectory)
{
ArgumentNullException.ThrowIfNull(rootDirectory);
return new Session(rootDirectory.Length);
}
private sealed class Session(int rootLength) : IFileSystemMatcherSession
{
public bool MatchesFile(ReadOnlySpan<char> currentDirectory, ReadOnlySpan<char> fileName) =>
UnderScratch(currentDirectory);
public DirectoryMatchType ClassifyDescendants(
ReadOnlySpan<char> currentDirectory,
ReadOnlySpan<char> directoryName) =>
UnderScratch(currentDirectory) || directoryName.SequenceEqual("scratch".AsSpan())
? DirectoryMatchType.AllDescendantFilesMatch
: DirectoryMatchType.MayContainMatchingFiles;
public void DirectoryFinished(ReadOnlySpan<char> directory)
{
}
public void Dispose()
{
}
private bool UnderScratch(ReadOnlySpan<char> directory)
{
ReadOnlySpan<char> relative = directory[rootLength..];
if (!relative.IsEmpty && relative[0] == Path.DirectorySeparatorChar)
{
relative = relative[1..];
}
while (!relative.IsEmpty)
{
int separator = relative.IndexOf(Path.DirectorySeparatorChar);
ReadOnlySpan<char> component = separator < 0 ? relative : relative[..separator];
if (component.SequenceEqual("scratch".AsSpan()))
{
return true;
}
if (separator < 0)
{
break;
}
relative = relative[(separator + 1)..];
}
return false;
}
}
}The matcher's ordinal, case-sensitive component comparison is deliberate. When the exclusion classifies scratch as All, the composite returns None and may prune it. The same session interface can be driven by a replay or archive host that satisfies the root and callback-group contract.
Match dot-separated keys without a filesystem
using System;
using Microsoft.Extensions.Globbing;
GlobPattern oneLevel = GlobPattern.Compile("App.*.Title", separator: '.');
GlobPattern anyDepth = GlobPattern.Compile("App.**.Title", separator: '.');
GlobPattern flat = GlobPattern.Compile("App.*.Title", separator: null);
// Expected: true, false, true, true, true.
Console.WriteLine(oneLevel.IsMatch("App.Dialog.Title"));
Console.WriteLine(oneLevel.IsMatch("App.Dialog.Nested.Title"));
Console.WriteLine(anyDepth.IsMatch("App.Title"));
Console.WriteLine(anyDepth.IsMatch("App.Dialog.Nested.Title"));
Console.WriteLine(flat.IsMatch("App.Dialog.Nested.Title"));
GlobPattern domain = GlobPattern.Compile(
"**.example.com",
separator: '.',
comparison: StringComparison.OrdinalIgnoreCase);
// Both are true.
Console.WriteLine(domain.IsMatch("example.com"));
Console.WriteLine(domain.IsMatch("EU.API.EXAMPLE.COM"));This is whole-string suffix matching, not right-to-left traversal, URL parsing, or IDN normalization. A host whose tree is ordered by reversed hostname labels needs its own mapping and traversal strategy.
Alternatives and reviewer questions
FSG already matches in-memory paths through MatcherExtensions.Match, using an in-memory tree and rich result. A natural extension for existing FSG users is an immutable Matcher.Compile() snapshot with span-based Boolean matching and streaming enumeration. It can filter before result materialization just as this proposal can. It would need to preserve FSG's pattern grammar, comparison, filter order, and root handling; subsequent builder mutations must not change the snapshot. That bridge is useful to consider separately, not evidence that the adjacent API must build an in-memory tree or rich result. The existing FSG optimization draft already filters physical entries as spans before constructing accepted result paths.
| Alternative | Why not selected | Reconsider when |
|---|---|---|
Only a compiled FSG Matcher snapshot |
The existing builder is a good compatibility entry point, but is a rule-set and filesystem-oriented entry point for one neutral text expression. Its grammar is different. | FSG migration is the primary scenario and snapshot/fallback behavior is specified. |
System.Text.Globbing plus an inbox System.IO.Enumeration protocol |
Avoids the filesystem-named package dependency and permits future inbox consumers; also freezes more BCL surface before a concrete inbox consumer is accepted. | An inbox consumer and independent hosts establish a stable shared contract. No automatic migration from the Extensions namespace is promised. |
| Ship all eight Touki dialects or name v1 POSIX/Bash/Git | Names imply their policies and edge cases, not just wildcard characters. The prototype has documented divergences and extglob resource questions. | A dialect has a pinned specification, parity corpus, explicit deviations, bounded execution, and an owner. |
Fixed / and flat text only |
Flat matching lets * cross dots, so it cannot express the requested one-segment resource-key match. |
Defer configurable separators if their escaping, normalization, and performance tests cannot be satisfied before release. |
Directory.EnumerateFiles(root, IFileSystemMatcher, ...) |
An optional trailing parameter makes existing Directory.EnumerateFiles(root, null) calls ambiguous with the string overload. Its usual root-prefixed output also differs from these root-relative results. |
A distinct inbox name/signature and result contract are approved without the ambiguity. |
| One Boolean directory callback | A role-neutral Boolean cannot distinguish a partial exclude from an exclude covering every descendant; careless inversion can lose files. | An equally expressive proof representation replaces the three states. |
Use FileSystemEntry as the session input |
Independent hosts cannot publicly initialize a meaningful entry from their own path and name spans. | Another representation preserves independent hosts and the split-span fast path. |
| Require joined paths or global pattern caching | Joining every file adds work to rejection; a global cache adds hidden retention, contention, and admission policy. | A bounded, measured alternative is needed for a concrete scenario. CreatePath already makes joining opt-in. |
| Public matcher-aware enumerator subclass | The factory supports metadata filtering and projection; advanced hosts can drive sessions from an ordinary FileSystemEnumerator<TResult>. |
Measurements or a concrete lifecycle hook show the smaller factory cannot meet a real use case. |
| Cancellation or asynchronous enumeration | Not included in this initial synchronous surface. Stopping between results does not interrupt a long MoveNext or a blocked operating-system call. |
A concrete cancellation requirement justifies a separately specified token and its hot-path cost. |
| Translate every pattern to regex | Syntax fidelity, construction cost, and worst-case behavior still require proof. | A translation demonstrates the same semantics, resource bounds, and matched-workload performance. Regex can already be wrapped as a predicate. |
The merged MSBuild change uses its own compatibility and cached-enumeration machinery. This proposal does not claim MSBuild parity or require replacing that host's parallelism, root planning, or policy. Raw watcher events likewise need their own invalidation model; they are not automatically valid session callbacks.
Changes and gaps relative to the prototype
- Package-first placement and one neutral grammar replace the original inbox proposal and eight named dialects. This is a new API contract, not an in-place change to existing FSG behavior.
- Configurable dot separators, strict validation, the 4,096 default bound, and the proposed generic predicate/transform factory are not established prototype behavior. The prototype currently has an unbounded sentinel and some invalid values fall back instead of throwing.
- A general
**/obj/**universal proof is required here but is not produced by the prototype's ordinary non-Git path in the relevant cases. Wildcard leading-dot rules must be included in anyAllproof. - The source-derived supplementary-Unicode prefix concern remains unverified end to end. Until a proof path implements the same comparison as matching, it must return
May. - The filesystem side adapts a compiled text pattern rather than making that pattern implement the filesystem interface.
FileSystemMatchRuleis a class, avoiding an invalid default struct with a null matcher.
Required validation and performance gates
These are release criteria, not results for an implementation of this proposal:
- Language and parity: test the specified grammar, separator and escaping boundaries, comparison modes, malformed patterns, resource limits, and flat versus session results. Do not claim compatibility with another dialect without that dialect's own pinned oracle corpus.
- Pruning: generate descendant paths and verify that
Nonenever hides a matching file andAllnever covers a nonmatch. Exercise exclusion inversion, ordered re-inclusion, unknown enum values, empty inputs, and nested compositions. The useful**/obj/**exclusion must be able to proveAllunderobjwithout making the same claim for partial exclusions such as**/obj/*.txt. - Unicode: verify that prefix proofs use the same effective ordinal comparison as file matching. Touki's current prefix path folds individual UTF-16 characters while literal matching uses full
OrdinalIgnoreCase; supplementary-plane casing exposes a discrepancy in those primitives. An end-to-end false prune has not been reproduced. - Lifetime and hosts: test separate roots and concurrent sessions, directory-group completion, early disposal, callback and construction failures, and physical and independently driven hosts. Preserve the conceptual root across host partitions.
- Resources: test long and adversarial patterns and inputs, checked growth, bounded working memory, deep composition without unbounded stack recursion, and cleanup when callbacks fail. A pattern-length limit alone is not a time budget; applications handling untrusted inputs must also limit candidate lengths, rule counts, concurrency, and walk scope.
- Matched-workload performance: compare the public design with an equivalent direct enumerator using the same patterns, options, result set, and projection. Measure construction separately from reuse and report runtime/JIT, allocations, directories visited, and run-to-run noise. The built-in split-span path must not create result paths or objects for rejected files, and its normal warm path must not add per-rejected-file managed allocations. A repeatable throughput regression above the measured noise needs an explicit allocation or functionality justification, not a presumed speedup.
- Deployment: verify the modern-asset API and downlevel compatibility, plus trimming and NativeAOT smoke tests for the shipped implementation.
Directory queues, accepted result strings, native buffers, and exceptional pool growth can still allocate. The earlier Boolean-versus-rich-result numbers compare different work and do not establish this proposal's speedup. Test both direct traversal and a host with cached or replayed entries; preserve host parallelism rather than requiring a new traversal driver.
Evidence and draft checks
- dotnet/runtime#132060, including the questions about the FSG extension, the matcher abstraction, and non-filesystem inputs.
- dotnet/runtime#132192 and dotnet/msbuild#14663, for the existing FSG optimization and the separate MSBuild integration.
- Touki at
3c58c6a: glob pruning, separator handling, filesystem normalization, and enumerator integration. - The fuzz-driven extglob rewrite motivates the explicit resource gate; it does not establish a bound for this draft.
The proposed declarations and all four examples were compiled against .NET 8 references with throw-only API stubs. The custom matcher was also exercised against its stub interface for root handling and 16 generated descendant directories. These checks do not implement or test the proposed glob engine, a real filesystem walk, package compatibility, or performance.
Activity
dotnet-policy-service commentedon Nov 20, 2026
Tagging subscribers to this area: @dotnet/area-system-io
See info in area-owners.md if you want to be subscribed.