diff --git a/src/AngleSharp.XPath.Tests/XPathConfigurationTests.cs b/src/AngleSharp.XPath.Tests/XPathConfigurationTests.cs index e31b2ee..6080d63 100644 --- a/src/AngleSharp.XPath.Tests/XPathConfigurationTests.cs +++ b/src/AngleSharp.XPath.Tests/XPathConfigurationTests.cs @@ -1,4 +1,7 @@ using NUnit.Framework; +using AngleSharp.Css.Parser; +using System.Linq; +using System.Threading; using System.Threading.Tasks; using Shouldly; @@ -42,4 +45,89 @@ public async Task RunXPathQueryFromDocumentWithSelectSingleSpecialN() element.TagName.ShouldBe("LI"); element.ClassName.ShouldBe("two"); } + + [Test] + public async Task RunXPathQueryAgainAfterAppendingAnElement() + { + const string source = ""; + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var document = await context.OpenAsync(res => res.Content(source)); + document.QuerySelectorAll("*[xpath>'//li']").Length.ShouldBe(3); + document.QuerySelector("ul").AppendChild(document.CreateElement("li")); + document.QuerySelectorAll("*[xpath>'//li']").Length.ShouldBe(4); + } + + [Test] + public async Task RunXPathQueryWithManyMatchesAgainAfterAppendingAnElement() + { + var source = ""; + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var document = await context.OpenAsync(res => res.Content(source)); + document.QuerySelectorAll("*[xpath>'//li']").Length.ShouldBe(20); + document.QuerySelector("ul").AppendChild(document.CreateElement("li")); + document.QuerySelectorAll("*[xpath>'//li']").Length.ShouldBe(21); + } + + [Test] + public async Task RunXPathQueryAgainAfterChangingAnAttribute() + { + const string source = ""; + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var document = await context.OpenAsync(res => res.Content(source)); + document.QuerySelectorAll("*[xpath>'//li[@class=\"two\"]']").Length.ShouldBe(1); + document.QuerySelector("li").ClassName = "two"; + document.QuerySelectorAll("*[xpath>'//li[@class=\"two\"]']").Length.ShouldBe(2); + } + + [Test] + public async Task RunXPathQueryMatchesOnlyTheSelectedOfLookAlikeElements() + { + const string source = "

"; + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var document = await context.OpenAsync(res => res.Content(source)); + var elements = document.QuerySelectorAll("*[xpath>'(//p)[1]']"); + elements.Length.ShouldBe(1); + elements[0].ShouldBeSameAs(document.QuerySelector("p")); + } + + [Test] + public async Task RunXPathQueryOnTwoDocumentsInParallel() + { + const int rounds = 200; + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var first = await context.OpenAsync(res => res.Content("")); + var second = await context.OpenAsync(res => res.Content("")); + using var barrier = new Barrier(2); + + int[] Query(Dom.IDocument document) + { + var counts = new int[rounds]; + + for (var i = 0; i < rounds; i++) + { + barrier.SignalAndWait(); + counts[i] = document.QuerySelectorAll("*[xpath>'//li']").Length; + } + + return counts; + } + + var results = await Task.WhenAll(Task.Run(() => Query(first)), Task.Run(() => Query(second))); + results[0].ShouldAllBe(count => count == 3); + results[1].ShouldAllBe(count => count == 2); + } + + [Test] + public void XPathSelectorTextIsTheSelectorAsWritten() + { + var config = Configuration.Default.WithXPath(); + var context = BrowsingContext.New(config); + var parser = context.GetService(); + parser.ParseSelector("*[xpath>'//li']").Text.ShouldBe("*[xpath>'//li']"); + } } diff --git a/src/AngleSharp.XPath/XPathAttrSelector.cs b/src/AngleSharp.XPath/XPathAttrSelector.cs index 9a24002..26f02c4 100644 --- a/src/AngleSharp.XPath/XPathAttrSelector.cs +++ b/src/AngleSharp.XPath/XPathAttrSelector.cs @@ -3,20 +3,27 @@ using AngleSharp.Dom; using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; namespace AngleSharp.XPath; sealed class XPathAttrSelector : ISelector { private readonly String _value; - private IElement _scope; - private List _result; + + // AngleSharp caches parsed selectors, so one instance serves every query and thread of a + // context. The last result answers the elements of one query without a lookup; the table + // keeps a result per scope once a second scope shows up, so queries on different scopes + // do not keep replacing each other's result. + private Result _last; + private ConditionalWeakTable _results; public XPathAttrSelector(String value) => _value = value; public Priority Specificity => Priority.OneClass; - public String Text => $"[xpath>'${_value}']"; + public String Text => $"[xpath>'{_value}']"; public void Accept(ISelectorVisitor visitor) { @@ -24,12 +31,112 @@ public void Accept(ISelectorVisitor visitor) public Boolean Match(IElement element, IElement scope) { - if (_scope != scope) + var version = GetMutationVersion(scope); + var result = Volatile.Read(ref _last); + + if (result == null || result.Scope != scope || result.Version != version) { - _scope = scope; - _result = scope.SelectNodes(_value); + result = GetResult(scope, version, result); + Volatile.Write(ref _last, result); } - return _result.Contains(element); + return result.Contains(element); + } + + private Result GetResult(IElement scope, Int64 version, Result last) + { + // A first scope, or the last one after a change: no other scope needs keeping yet + if (last == null || (last.Scope == scope && Volatile.Read(ref _results) == null)) + { + return Evaluate(scope, version); + } + + var results = Volatile.Read(ref _results); + + if (results == null) + { + Interlocked.CompareExchange(ref _results, new ConditionalWeakTable(), null); + results = Volatile.Read(ref _results); + results.GetOrCreateValue(last.Scope).Result = last; + } + + var holder = results.GetOrCreateValue(scope); + var result = Volatile.Read(ref holder.Result); + + if (result == null || result.Version != version) + { + result = Evaluate(scope, version); + Volatile.Write(ref holder.Result, result); + } + + return result; + } + + private Result Evaluate(IElement scope, Int64 version) => new(scope, version, scope.SelectNodes(_value)); + + // The document's counter advances with every change to its tree, so an equal reading means the + // result still holds. Other IDocument implementations have no counter and keep their result. + private static Int64 GetMutationVersion(IElement scope) => + scope.Owner is Document document ? document.MutationVersion : 0; + + private sealed class ResultHolder + { + public Result Result; + } + + private sealed class Result + { + // Up to this many nodes, comparing references one by one is cheaper than hashing + private const Int32 MaxScanned = 8; + + private readonly INode[] _scanned; + private readonly HashSet _hashed; + + public Result(IElement scope, Int64 version, List nodes) + { + Scope = scope; + Version = version; + + if (nodes.Count <= MaxScanned) + { + _scanned = nodes.ToArray(); + } + else + { + _hashed = new HashSet(nodes, ReferenceComparer.Instance); + } + } + + public IElement Scope { get; } + + public Int64 Version { get; } + + public Boolean Contains(INode node) + { + if (_hashed != null) + { + return _hashed.Contains(node); + } + + foreach (var scanned in _scanned) + { + if (ReferenceEquals(scanned, node)) + { + return true; + } + } + + return false; + } + } + + // Node.Equals(INode) compares structure, so look-alike nodes must not count as the same one. + private sealed class ReferenceComparer : IEqualityComparer + { + public static readonly ReferenceComparer Instance = new(); + + public Boolean Equals(INode x, INode y) => ReferenceEquals(x, y); + + public Int32 GetHashCode(INode obj) => RuntimeHelpers.GetHashCode(obj); } }