Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 201 additions & 0 deletions src/Hl7.Fhir.Base/ElementModel/PocoElementNode2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
using Hl7.Fhir.Model;
using Hl7.Fhir.Specification;
using Hl7.Fhir.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;

namespace Hl7.Fhir.ElementModel;

#nullable enable

public abstract record PocoElementNode2(SinglePocoElementNode? Parent, string Name) : IEnumerable<SinglePocoElementNode>
{
public abstract IEnumerator<SinglePocoElementNode> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

public record SinglePocoElementNode(Base Poco, SinglePocoElementNode? Parent, int? Index, string? Name)
: PocoElementNode2(Parent, Name ?? Poco.TypeName), IScopedNode, IFhirValueProvider, IResourceTypeSupplier, IAnnotated
{
public IEnumerable<PocoElementNode2> Children() =>
Poco.GetElementPairs()
.Select<KeyValuePair<string, object>, PocoElementNode2>(ep =>
nodeFor(ep.Key, ep.Value)
);

public PocoElementNode2? Child(string name) => Poco.TryGetValue(name, out var result)
? nodeFor(name, result)
: null;

private PocoElementNode2 nodeFor(string name, object value) =>
value switch
{
PrimitiveType primitive => new SinglePrimitiveElementNode<PrimitiveType>(primitive, name) { Parent = this },
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved
Base b => new SinglePocoElementNode(b, this, null, name),
IEnumerable<PrimitiveType> primitiveList => new RepeatingPrimitiveElementNode<PrimitiveType>(primitiveList.ToList(), name) { Parent = this },
IEnumerable<Base> list => new RepeatingPocoElementNode(list.ToList(), this, name),
_ => throw new InvalidOperationException("Unexpected element in child list")
};

private IEnumerable<SinglePocoElementNode> asList() => [this];

public override IEnumerator<SinglePocoElementNode> GetEnumerator() => asList().GetEnumerator();

public string ShortPath => (Index, Parent) switch
{
// if we have an index, we have a parent.
({ } idx, { } parent) => $"{parent.ShortPath}.{Name}[{idx}]",
// Note that we omit indices here.
(_, { } parent) => $"{parent.ShortPath}.{Name}",
// if we have neither, we are the root. Note that we omit indices here.
_ => Name
};

public Base FhirValue => Poco;
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved

public string? ResourceType => Poco is Resource
? InstanceType
: null;

public IEnumerable<object> Annotations(Type type)
{
if (type == typeof(ITypedElement) || type == typeof(IShortPathGenerator) || type == typeof(IScopedNode))
return [this];
if (type == typeof(IFhirValueProvider))
return [this];
if (type == typeof(IResourceTypeSupplier))
return [this];
return Poco.Annotations(type);
}

#region ITypedElement

public string? InstanceType =>
Poco switch
{
BackboneElement => "BackboneElement",
Element when Poco.TypeName.Contains('.') => "Element",
_ => Poco.TypeName
};

// needed for ITE
public virtual object? Value => null;

public string Location => (Index, Parent) switch
{
// if we have an index, write it
({ } idx, { } parent) => $"{parent.Location}.{Name}[{idx}]",
// if we do not, write 0 as idx
(_, { } parent) => $"{parent.Location}.{Name}[0]",
// if we have neither, we are the root.
_ => Name
};

// needed for ITE
public IElementDefinitionSummary? Definition => null;

IEnumerable<ITypedElement> ITypedElement.Children(string? name) => (this as IScopedNode).Children(name);

#endregion

#region IScopedNode

IScopedNode? IScopedNode.Parent => Parent;

IEnumerable<IScopedNode> IScopedNode.Children(string? name) => name is null
? Children().SelectMany(node => node)
: Child(name) ?? Enumerable.Empty<SinglePocoElementNode>();

[TemporarilyChanged] // we should investigate whether we want to even use this anymore. If we do, we should make this implementation explicit.
public NodeType Type => Poco switch
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved
{
Bundle => NodeType.Bundle | NodeType.Resource,
PrimitiveType => NodeType.Primitive,
DomainResource => NodeType.DomainResource | NodeType.Resource,
Resource => NodeType.Resource,
ResourceReference or Canonical or CodeableReference => NodeType.Reference,
Quantity => NodeType.Quantity,
_ => 0
};

public bool TryResolveBundleEntry(string fullUrl, [NotNullWhen(true)] out IScopedNode? result)
{
result = Poco is Bundle
? this
.Child<RepeatingPocoElementNode>("entry")
?.FirstOrDefault<Bundle.EntryComponent>(entry =>
entry.FullUrl == fullUrl)
?.Child<SinglePocoElementNode>("resource")
: null;
return result is not null;
}

public bool TryResolveContainedEntry(string id, [NotNullWhen(true)] out IScopedNode? result)
{
result = Poco is DomainResource
? this
.Child<RepeatingPocoElementNode>("contained")
?.FirstOrDefault<Resource>(contained => $"#{contained.Id}" == id)
: null;
return result is not null;
}

#endregion
}

public record RepeatingPocoElementNode(IReadOnlyList<Base> Pocos, SinglePocoElementNode? Parent, string Name) : PocoElementNode2(Parent, Name)
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved
{
public SinglePocoElementNode this[int index] => new(Pocos[index], Parent, index, Name);

public IEnumerable<SinglePocoElementNode> Where<T>(Func<T, bool> predicate) where T : Base =>
Pocos.OfType<T>().Where(predicate).Select((poco, index) => new SinglePocoElementNode(poco, Parent, index, Name));

public SinglePocoElementNode? FirstOrDefault<T>(Func<T, bool> predicate) where T : Base
{
for (int index = 0; index < Pocos.Count; index++)
{
if (Pocos[index] is T item && predicate(item))
return new SinglePocoElementNode(item, Parent, index, Name);
}

return null;
}

public override IEnumerator<SinglePocoElementNode> GetEnumerator() => Pocos.Select((poco, index) => new SinglePocoElementNode(poco, Parent, index, Name)).GetEnumerator();
}

public record SinglePrimitiveElementNode<T> : SinglePocoElementNode where T : PrimitiveType
{
public static SinglePrimitiveElementNode<T> FromSystemPrimitive<TTo>(object primitive, string? name = null) where TTo : T, new()
{
return new SinglePrimitiveElementNode<T>(new TTo { ObjectValue = primitive }, name);
}

public SinglePrimitiveElementNode(T primitive, string? name = null) : base(primitive, null, null, name ?? "value") { }
private T Primitive => (T)Poco;
public override object? Value => Primitive.ToITypedElementValue();
}

public record RepeatingPrimitiveElementNode<T> : RepeatingPocoElementNode where T : PrimitiveType
{
public RepeatingPrimitiveElementNode(IReadOnlyList<T> primitives, string? name = null) : base(primitives, null, name ?? "value") { }

public static RepeatingPrimitiveElementNode<T> FromSystemPrimitives<TTo>(IEnumerable<object> values, string? name = null) where TTo : T, new()
{
return new RepeatingPrimitiveElementNode<T>(values.Select(v => new TTo { ObjectValue = v }).ToList(), name);
}

public override IEnumerator<SinglePocoElementNode> GetEnumerator() =>
Primitives.Select((primitive, index) => new SinglePrimitiveElementNode<T>(primitive, Name) { Index = index }).GetEnumerator();

private IReadOnlyList<T> Primitives => (IReadOnlyList<T>)Pocos;
}

public static class PocoElementNodeExtensions
{
public static T? Child<T>(this SinglePocoElementNode? node, string name) where T : PocoElementNode2 => node?.Child(name) as T;
}
2 changes: 1 addition & 1 deletion src/Hl7.Fhir.Base/FhirPath/ElementNavFhirExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public static bool HtmlChecks(this IScopedNode focus)
if (r is null)
return null;

var fhirValue = r.Annotation<IFhirValueProvider>();
var fhirValue = r.Annotation<IFhirValueProvider>() ?? r as IFhirValueProvider;
if (fhirValue != null)
{
return fhirValue.FhirValue;
Expand Down
2 changes: 1 addition & 1 deletion src/Hl7.Fhir.Base/FhirPath/Expressions/Closure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static Closure Root(IScopedNode root, EvaluationContext ctx = null)

newClosure.SetThis(input);
newClosure.SetThat(input);
newClosure.SetIndex([new Integer(0)]);
newClosure.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(0));
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved
newClosure.SetOriginalContext(input);

if (newContext.Resource != null) newClosure.SetResource(new[] { newContext.Resource });
Expand Down
18 changes: 9 additions & 9 deletions src/Hl7.Fhir.Base/FhirPath/Expressions/SymbolTableInit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ IEnumerable<IScopedNode> runForeach()
IEnumerable<IScopedNode> newFocus = [element];
var newContext = ctx.Nest(newFocus);
newContext.SetThis(newFocus);
newContext.SetIndex([new Integer(index)]);
newContext.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(index));
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved
index++;

if (lambda(newContext, InvokeeFactory.EmptyArgs).BooleanEval() == true)
Expand All @@ -388,7 +388,7 @@ IEnumerable<IScopedNode> runForeach()
IEnumerable<IScopedNode> newFocus = [element];
var newContext = ctx.Nest(newFocus);
newContext.SetThis(newFocus);
newContext.SetIndex([new Integer(index)]);
newContext.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(index));
index++;

var result = lambda(newContext, InvokeeFactory.EmptyArgs);
Expand Down Expand Up @@ -417,7 +417,7 @@ private static IEnumerable<IScopedNode> runRepeat(Closure ctx, IEnumerable<Invok
IEnumerable<IScopedNode> newFocus = [element];
var newContext = ctx.Nest(newFocus);
newContext.SetThis(newFocus);
newContext.SetIndex([new Integer(index)]);
newContext.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(index));
index++;

var candidates = lambda(newContext, InvokeeFactory.EmptyArgs);
Expand All @@ -443,15 +443,15 @@ private static IEnumerable<IScopedNode> runAll(Closure ctx, IEnumerable<Invokee>
IEnumerable<IScopedNode> newFocus = [element];
var newContext = ctx.Nest(newFocus);
newContext.SetThis(newFocus);
newContext.SetIndex([new Integer(index)]);
newContext.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(index));
index++;

var result = lambda(newContext, InvokeeFactory.EmptyArgs).BooleanEval();
if (result == null) return [];
if (result == false) return [new FhirBoolean(false)];
if (result == false) return SinglePrimitiveElementNode<FhirBoolean>.FromSystemPrimitive<FhirBoolean>(false);
}

return [new FhirBoolean(true)];
return SinglePrimitiveElementNode<FhirBoolean>.FromSystemPrimitive<FhirBoolean>(true);
}

private static IEnumerable<IScopedNode> runAny(Closure ctx, IEnumerable<Invokee> arguments)
Expand All @@ -465,14 +465,14 @@ private static IEnumerable<IScopedNode> runAny(Closure ctx, IEnumerable<Invokee>
IEnumerable<IScopedNode> newFocus = [element];
var newContext = ctx.Nest(newFocus);
newContext.SetThis(newFocus);
newContext.SetIndex([new Integer(index)]);
newContext.SetIndex(SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(index));
index++;

var result = lambda(newContext, InvokeeFactory.EmptyArgs).BooleanEval();
if (result == true) return [new FhirBoolean(true)];
if (result == true) return SinglePrimitiveElementNode<FhirBoolean>.FromSystemPrimitive<FhirBoolean>(true);
}

return [new FhirBoolean(false)];
return SinglePrimitiveElementNode<FhirBoolean>.FromSystemPrimitive<FhirBoolean>(false);
}
}
}
20 changes: 11 additions & 9 deletions src/Hl7.Fhir.Base/FhirPath/Expressions/Typecasts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ private static Cast getImplicitCast(object f, Type to)
if (to == typeof(object)) return id;
if (from.CanBeTreatedAsType(to)) return id;

bool fromElemList = from.CanBeTreatedAsType(typeof(IEnumerable<IScopedNode>));
// this check seems weird, but PocoElementNode both implements IScopedNode and IEnumerable<IScopedNode> for the sake of backwards compatibility
bool fromElemList = from.CanBeTreatedAsType(typeof(IEnumerable<IScopedNode>)) && !from.CanBeTreatedAsType(typeof(IScopedNode));
if (to == typeof(P.Quantity) && from.CanBeTreatedAsType(typeof(IScopedNode))) return tryQuantity;
if (to == typeof(IScopedNode) && (!fromElemList)) return any2primitiveTypedElement;
if (to == typeof(IEnumerable<IScopedNode>)) return any2List;
Expand Down Expand Up @@ -111,7 +112,7 @@ private static Cast getImplicitCast(object f, Type to)
internal static object UnboxTo(object instance, Type to)
{
if (instance == null) return null;

if (instance is IEnumerable<IScopedNode> list)
{
var cachedEnum = CachedEnumerable.Create(list);
Expand All @@ -121,7 +122,7 @@ internal static object UnboxTo(object instance, Type to)
if (cachedEnum.Count() == 1)
instance = cachedEnum.Single();
}

if (instance is IScopedNode element)
{
if (to.CanBeTreatedAsType(typeof(IScopedNode))) return instance;
Expand All @@ -133,8 +134,8 @@ internal static object UnboxTo(object instance, Type to)
// to represent the object in Value.

var isPrimitive = element.Value != null ||
(element.InstanceType != null &&
Char.IsLower(element.InstanceType[0]) || element.InstanceType.StartsWith("System."));
(element.InstanceType != null &&
Char.IsLower(element.InstanceType[0]) || element.InstanceType.StartsWith("System."));
if (isPrimitive)
instance = element.Value;
}
Expand Down Expand Up @@ -213,17 +214,18 @@ public static bool IsNullable(this Type t)

public static string ReadableFhirPathName(object value)
{
if (value is IScopedNode te)
return te.InstanceType;

if (value is IEnumerable<IScopedNode> ete)
{
var values = ete.ToList();
var types = ete.Select(te => ReadableFhirPathName(te)).Distinct();

return values.Count > 1 ? "collection of " + String.Join("/", types) : types.Single();
}
else if (value is IScopedNode te)
return te.InstanceType;
else
return value.GetType().Name;

return value.GetType().Name;
}

public static string ReadableTypeName(Type t)
Expand Down
8 changes: 4 additions & 4 deletions src/Hl7.Fhir.Base/FhirPath/Functions/StringOperators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ public static string FpSubstring(this string me, long start, long? length)

public static IScopedNode FpIndexOf(this string me, string fragment)
{
return new Integer(me.IndexOf(fragment, StringComparison.Ordinal));
return SinglePrimitiveElementNode<Integer>.FromSystemPrimitive<Integer>(me.IndexOf(fragment, StringComparison.Ordinal));
}

public static IEnumerable<IScopedNode> ToChars(this string me) =>
me.Select(c => new FhirString(c.ToString()));
RepeatingPrimitiveElementNode<FhirString>.FromSystemPrimitives<FhirString>(me.Select(c => c.ToString()));
Comment thread
ewoutkramer marked this conversation as resolved.
Resolved

public static string FpReplace(this string me, string find, string replace)
{
Expand All @@ -56,8 +56,8 @@ public static string FpReplace(this string me, string find, string replace)

public static IEnumerable<IScopedNode> FpSplit(this string me, string seperator)
{
var results = me.Split(new[] { seperator }, StringSplitOptions.None);
return results.Select(s => new FhirString(s));
var results = me.Split(new[] { seperator }, StringSplitOptions.None).ToArray<object>();
return RepeatingPrimitiveElementNode<FhirString>.FromSystemPrimitives<FhirString>(results);
}

public static string FpEncode(this string me, string encoding)
Expand Down
Loading