fhirpathpy 2.2.4__tar.gz → 3.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/PKG-INFO +2 -2
  2. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/__init__.py +19 -6
  3. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/__init__.py +7 -5
  4. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/evaluators/__init__.py +21 -21
  5. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/__init__.py +6 -5
  6. fhirpathpy-3.0.0/fhirpathpy/engine/invocations/aggregate.py +53 -0
  7. fhirpathpy-3.0.0/fhirpathpy/engine/invocations/datetime.py +22 -0
  8. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/equality.py +93 -59
  9. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/existence.py +20 -4
  10. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/filtering.py +5 -1
  11. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/math.py +9 -10
  12. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/misc.py +11 -13
  13. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/navigation.py +3 -0
  14. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/strings.py +6 -5
  15. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/nodes.py +217 -160
  16. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/util.py +20 -3
  17. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/pyproject.toml +1 -1
  18. fhirpathpy-2.2.4/fhirpathpy/engine/invocations/aggregate.py +0 -35
  19. fhirpathpy-2.2.4/fhirpathpy/engine/invocations/datetime.py +0 -28
  20. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/LICENSE.md +0 -0
  21. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/README.md +0 -0
  22. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/collections.py +0 -0
  23. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/combining.py +0 -0
  24. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/constants.py +0 -0
  25. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/logic.py +0 -0
  26. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/subsetting.py +0 -0
  27. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/engine/invocations/types.py +0 -0
  28. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/__init__.py +0 -0
  29. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/dstu2/choiceTypePaths.json +0 -0
  30. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/dstu2/path2Type.json +0 -0
  31. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/dstu2/pathsDefinedElsewhere.json +0 -0
  32. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/dstu2/type2Parent.json +0 -0
  33. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r4/choiceTypePaths.json +0 -0
  34. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r4/path2Type.json +0 -0
  35. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r4/pathsDefinedElsewhere.json +0 -0
  36. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r4/type2Parent.json +0 -0
  37. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r5/choiceTypePaths.json +0 -0
  38. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r5/path2Type.json +0 -0
  39. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r5/pathsDefinedElsewhere.json +0 -0
  40. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/r5/type2Parent.json +0 -0
  41. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/stu3/choiceTypePaths.json +0 -0
  42. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/stu3/path2Type.json +0 -0
  43. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/stu3/pathsDefinedElsewhere.json +0 -0
  44. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/models/stu3/type2Parent.json +0 -0
  45. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/ASTPathListener.py +0 -0
  46. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/FHIRPath.g4 +0 -0
  47. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/README.md +0 -0
  48. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/__init__.py +0 -0
  49. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPath.interp +0 -0
  50. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPath.tokens +0 -0
  51. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPathLexer.interp +0 -0
  52. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPathLexer.py +0 -0
  53. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPathLexer.tokens +0 -0
  54. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPathListener.py +0 -0
  55. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/FHIRPathParser.py +0 -0
  56. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/parser/generated/__init__.py +0 -0
  57. {fhirpathpy-2.2.4 → fhirpathpy-3.0.0}/fhirpathpy/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fhirpathpy
3
- Version: 2.2.4
3
+ Version: 3.0.0
4
4
  Summary: FHIRPath implementation in Python
5
5
  Keywords: fhir,fhirpath
6
6
  Author-email: "beda.software" <fhirpath@beda.software>
@@ -22,7 +22,7 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
22
  Classifier: Typing :: Typed
23
23
  License-File: LICENSE.md
24
24
  Requires-Dist: antlr4-python3-runtime~=4.10
25
- Requires-Dist: python-dateutil~=2.8
25
+ Requires-Dist: python-dateutil>=2.8,<5
26
26
  Requires-Dist: pytest==7.1.1 ; extra == "test"
27
27
  Requires-Dist: pyyaml==5.4 ; extra == "test"
28
28
  Requires-Dist: pydantic==2.13.1 ; extra == "test"
@@ -5,12 +5,18 @@ from typing import Any, Protocol, TypeVar, cast
5
5
 
6
6
  from fhirpathpy.engine import do_eval
7
7
  from fhirpathpy.engine.invocations.constants import constants
8
- from fhirpathpy.engine.nodes import FP_Type, ResourceNode
9
- from fhirpathpy.engine.util import arraify, get_data, process_user_invocation_table, set_paths
8
+ from fhirpathpy.engine.nodes import FP_Quantity, FP_Type, ResourceNode
9
+ from fhirpathpy.engine.util import (
10
+ arraify,
11
+ get_data,
12
+ get_text,
13
+ process_user_invocation_table,
14
+ set_paths,
15
+ )
10
16
  from fhirpathpy.parser import parse
11
17
 
12
18
  __title__ = "fhirpathpy"
13
- __version__ = "2.2.4"
19
+ __version__ = "3.0.0"
14
20
  __author__ = "beda.software"
15
21
  __license__ = "MIT"
16
22
  __copyright__ = "Copyright 2026 beda.software"
@@ -50,8 +56,8 @@ def apply_parsed_path(resource, parsedPath, context=None, model=None, options=No
50
56
 
51
57
  node = do_eval(ctx, dataRoot, parsedPath["children"][0])
52
58
 
53
- # Resolve any internal "ResourceNode" instances. Continue to let FP_Type
54
- # subclasses through.
59
+ # Unless returnRawData is set, unwrap ResourceNode values and return date/time and
60
+ # Quantity values as text.
55
61
 
56
62
  if options and options.get("returnRawData", False):
57
63
  if isinstance(node, list):
@@ -60,6 +66,8 @@ def apply_parsed_path(resource, parsedPath, context=None, model=None, options=No
60
66
  # even in this raw data mode (as they are not a part of the output)
61
67
  for item in node:
62
68
  if isinstance(item, ResourceNode):
69
+ if item.data is None and item._data is not None:
70
+ continue
63
71
  if isinstance(item.data, dict):
64
72
  keys = list(item.data.keys())
65
73
  if keys == ["extension"]:
@@ -75,6 +83,8 @@ def apply_parsed_path(resource, parsedPath, context=None, model=None, options=No
75
83
  res = []
76
84
  for item in data:
77
85
  # Filter out intenal representation of primitive extensions
86
+ if isinstance(item, ResourceNode) and item.data is None and item._data is not None:
87
+ continue
78
88
  i = visit(item)
79
89
  if isinstance(i, dict):
80
90
  keys = list(i.keys())
@@ -86,7 +96,10 @@ def apply_parsed_path(resource, parsedPath, context=None, model=None, options=No
86
96
  if isinstance(data, dict) and not isinstance(data, FP_Type):
87
97
  return {key: visit(value) for key, value in data.items()}
88
98
 
89
- return data
99
+ if isinstance(data, FP_Quantity):
100
+ return data.asStr
101
+
102
+ return get_text(data)
90
103
 
91
104
  return visit(node)
92
105
 
@@ -11,8 +11,8 @@ from fhirpathpy.engine.nodes import TypeInfo
11
11
 
12
12
  def check_integer_param(val):
13
13
  data = util.get_data(val)
14
- if int(data) != data:
15
- raise Exception("Expected integer, got: " + json.dumps(data))
14
+ if not isinstance(data, numbers.Number) or int(data) != data:
15
+ raise Exception("Expected integer, but got: " + util.format_error_value(data))
16
16
  return data
17
17
 
18
18
 
@@ -33,7 +33,7 @@ def check_boolean_param(val):
33
33
  def check_string_param(val):
34
34
  data = util.get_data(val)
35
35
  if not isinstance(data, str):
36
- raise Exception("Expected string, got: " + json.dumps(data))
36
+ raise Exception("Expected string, but got: " + util.format_error_value(data))
37
37
  return data
38
38
 
39
39
 
@@ -61,7 +61,9 @@ def doInvoke(ctx, fn_name, data, raw_params):
61
61
 
62
62
  invocation = invocation_registry[fn_name]
63
63
 
64
- if "nullable_input" in invocation and util.is_nullable(data):
64
+ if "nullable_input" in invocation and (
65
+ util.is_nullable(data) or len(data) == 1 and util.get_data(data[0]) is None
66
+ ):
65
67
  return []
66
68
 
67
69
  if "variadic" in invocation:
@@ -172,7 +174,7 @@ def make_param(ctx, parentData, node_type, param):
172
174
  "Unexpected collection" + json.dumps(res) + "; expected singleton of type " + node_type
173
175
  )
174
176
 
175
- if len(res) == 0:
177
+ if len(res) == 0 or util.get_data(res[0]) is None:
176
178
  return []
177
179
 
178
180
  if node_type not in param_check_table:
@@ -161,7 +161,7 @@ def quantity_literal(ctx, parentData, node):
161
161
 
162
162
  def date_time_literal(ctx, parentData, node):
163
163
  dateStr = node["text"][1:]
164
- return [nodes.FP_DateTime(dateStr)]
164
+ return [nodes.FP_Date(dateStr) or nodes.FP_DateTime(dateStr)]
165
165
 
166
166
 
167
167
  def time_literal(ctx, parentData, node):
@@ -205,6 +205,11 @@ def create_reduce_member_invocation(model, key):
205
205
  childPath = "Extension"
206
206
  elif key == "length":
207
207
  toAdd = len(res.data)
208
+ elif isinstance(res._data, abc.Mapping):
209
+ # A primitive keeps its id and extensions in the "_" sibling element
210
+ toAdd = res._data.get(key)
211
+ if key == "extension":
212
+ childPath = "Extension"
208
213
 
209
214
  childPath = (
210
215
  model["path2Type"].get(childPath, childPath)
@@ -212,28 +217,23 @@ def create_reduce_member_invocation(model, key):
212
217
  else childPath
213
218
  )
214
219
 
215
- if util.is_some(toAdd):
216
- if isinstance(toAdd, list):
217
- mapped = [
218
- nodes.ResourceNode.create_node(
219
- x, childPath, propName=f"{fullPath}[{i}]", index=i
220
- )
221
- for i, x in enumerate(toAdd)
222
- ]
223
- acc = acc + mapped
224
- else:
225
- acc.append(nodes.ResourceNode.create_node(toAdd, childPath, propName=fullPath))
226
- if util.is_some(toAdd_):
227
- if isinstance(toAdd_, list):
228
- mapped = [
220
+ if isinstance(toAdd, list) or isinstance(toAdd_, list):
221
+ # Pair each primitive value with its "_" element (same index), so a
222
+ # primitive that has extensions is still a single item
223
+ values = toAdd if isinstance(toAdd, list) else []
224
+ elements = toAdd_ if isinstance(toAdd_, list) else []
225
+ for i in range(max(len(values), len(elements))):
226
+ value = values[i] if i < len(values) else None
227
+ element = elements[i] if i < len(elements) else None
228
+ acc.append(
229
229
  nodes.ResourceNode.create_node(
230
- x, childPath, propName=f"{fullPath}[{i}]", index=i
230
+ value, childPath, _data=element, propName=f"{fullPath}[{i}]", index=i
231
231
  )
232
- for i, x in enumerate(toAdd_)
233
- ]
234
- acc = acc + mapped
235
- else:
236
- acc.append(nodes.ResourceNode.create_node(toAdd_, childPath, propName=fullPath))
232
+ )
233
+ elif util.is_some(toAdd) or util.is_some(toAdd_):
234
+ acc.append(
235
+ nodes.ResourceNode.create_node(toAdd, childPath, _data=toAdd_, propName=fullPath)
236
+ )
237
237
  return acc
238
238
 
239
239
  return func
@@ -16,12 +16,13 @@ from fhirpathpy.engine.invocations import (
16
16
  subsetting,
17
17
  types,
18
18
  )
19
- from fhirpathpy.engine.nodes import FP_DateTime, FP_Quantity, FP_Time
19
+ from fhirpathpy.engine.nodes import FP_Date, FP_DateTime, FP_Quantity, FP_Time
20
20
 
21
21
  invocation_registry = {
22
22
  "empty": {"fn": existence.empty_fn},
23
23
  "not": {"fn": existence.not_fn},
24
24
  "exists": {"fn": existence.exists_macro, "arity": {0: [], 1: ["Expr"]}},
25
+ "hasValue": {"fn": existence.has_value_fn},
25
26
  "all": {"fn": existence.all_macro, "arity": {1: ["Expr"]}},
26
27
  "union": {"fn": combining.union_op, "arity": {1: ["AnyAtRoot"]}},
27
28
  "exclude": {"fn": combining.exclude_fn, "arity": {1: ["AnyAtRoot"]}},
@@ -80,12 +81,12 @@ invocation_registry = {
80
81
  "nullable_input": True,
81
82
  },
82
83
  "length": {"fn": strings.length, "nullable_input": True},
83
- "toChars": {"fn": strings.toChars},
84
+ "toChars": {"fn": strings.toChars, "nullable_input": True},
84
85
  "join": {"fn": strings.join, "arity": {0: [], 1: ["String"]}},
85
86
  "split": {"fn": strings.split, "arity": {1: ["String"]}, "nullable_input": True},
86
87
  "trim": {"fn": strings.trim, "nullable_input": True},
87
- "encode": {"fn": strings.encode, "arity": {1: ["String"]}},
88
- "decode": {"fn": strings.decode, "arity": {1: ["String"]}},
88
+ "encode": {"fn": strings.encode, "arity": {1: ["String"]}, "nullable_input": True},
89
+ "decode": {"fn": strings.decode, "arity": {1: ["String"]}, "nullable_input": True},
89
90
  "abs": {"fn": math.abs},
90
91
  "ceiling": {"fn": math.ceiling},
91
92
  "exp": {"fn": math.exp},
@@ -134,7 +135,7 @@ invocation_registry = {
134
135
  "convertsToInteger": {"fn": misc.create_converts_to_fn(misc.to_integer, "int")},
135
136
  "convertsToDecimal": {"fn": misc.create_converts_to_fn(misc.to_decimal, Decimal)},
136
137
  "convertsToString": {"fn": misc.create_converts_to_fn(misc.to_string, "str")},
137
- "convertsToDate": {"fn": misc.create_converts_to_fn(misc.to_date, FP_DateTime)},
138
+ "convertsToDate": {"fn": misc.create_converts_to_fn(misc.to_date, FP_Date)},
138
139
  "convertsToDateTime": {"fn": misc.create_converts_to_fn(misc.to_date_time, FP_DateTime)},
139
140
  "convertsToTime": {"fn": misc.create_converts_to_fn(misc.to_time, FP_Time)},
140
141
  "convertsToQuantity": {"fn": misc.create_converts_to_fn(misc.to_quantity, FP_Quantity)},
@@ -0,0 +1,53 @@
1
+ from fhirpathpy.engine import util
2
+ from fhirpathpy.engine.invocations.math import div
3
+
4
+
5
+ def unwrap_values(x):
6
+ """
7
+ Returns the plain values of the input collection.
8
+
9
+ Items coming from a resource are ResourceNode instances, so they have to be
10
+ unwrapped (and converted, e.g. a FHIR Quantity to System.Quantity) before
11
+ they can be used in arithmetic or comparison.
12
+ """
13
+ return [util.get_data(util.val_data_converted(item)) for item in x]
14
+
15
+
16
+ def avg_fn(ctx, x):
17
+ values = unwrap_values(x)
18
+ if len(values) == 0 or None in values:
19
+ return []
20
+
21
+ return div(ctx, sum(values), len(values))
22
+
23
+
24
+ def sum_fn(ctx, x):
25
+ values = unwrap_values(x)
26
+ if None in values:
27
+ return []
28
+
29
+ return sum(values)
30
+
31
+
32
+ def min_fn(ctx, x):
33
+ values = unwrap_values(x)
34
+ if len(values) == 0 or None in values:
35
+ return []
36
+
37
+ return min(values)
38
+
39
+
40
+ def max_fn(ctx, x):
41
+ values = unwrap_values(x)
42
+ if len(values) == 0 or None in values:
43
+ return []
44
+
45
+ return max(values)
46
+
47
+
48
+ def aggregate_macro(ctx, data, expr, initial_value=None):
49
+ ctx["$total"] = initial_value
50
+ for i, x in enumerate(data):
51
+ ctx["$index"] = i
52
+ ctx["$total"] = expr(x)
53
+ return ctx["$total"]
@@ -0,0 +1,22 @@
1
+ from fhirpathpy.engine.invocations.constants import constants, systemtime
2
+ from fhirpathpy.engine.nodes import FP_Date, FP_DateTime, FP_Time
3
+
4
+
5
+ def now(ctx, data):
6
+ if not constants.now:
7
+ constants.now = FP_DateTime.build_in_local_timezone(systemtime.now(), 7)
8
+ return constants.now
9
+
10
+
11
+ def today(ctx, data):
12
+ if not constants.today:
13
+ now = systemtime.now()
14
+ constants.today = FP_Date(now.date().isoformat())
15
+ return constants.today
16
+
17
+
18
+ def timeOfDay(ctx, data):
19
+ if not constants.timeOfDay:
20
+ now = systemtime.now()
21
+ constants.timeOfDay = FP_Time(now.time().isoformat(timespec="milliseconds"))
22
+ return constants.timeOfDay
@@ -7,19 +7,34 @@ from fhirpathpy.engine import nodes, util
7
7
  """
8
8
  This file holds code to hande the FHIRPath Math functions.
9
9
  """
10
- DATETIME_NODES_LIST = (nodes.FP_DateTime, nodes.FP_Time)
10
+ DATETIME_NODES_LIST = (nodes.FP_DateTime, nodes.FP_Date, nodes.FP_Time)
11
11
 
12
12
 
13
13
  def equality(ctx, x, y):
14
14
  if util.is_empty(x) or util.is_empty(y):
15
15
  return False
16
16
 
17
- if type(x[0]) in DATETIME_NODES_LIST or type(y[0]) in DATETIME_NODES_LIST:
18
- return datetime_equality(ctx, x, y)
19
-
20
17
  if len(x) != len(y):
21
18
  return False
22
19
 
20
+ result = True
21
+ for a, b in zip(x, y, strict=True):
22
+ item_result = item_equality(ctx, [a], [b])
23
+ if item_result is None:
24
+ result = None
25
+ elif not item_result:
26
+ return False
27
+ return result
28
+
29
+
30
+ def item_equality(ctx, x, y):
31
+ if (
32
+ type(x[0]) in DATETIME_NODES_LIST
33
+ or type(y[0]) in DATETIME_NODES_LIST
34
+ or are_date_time_values(x[0], y[0])
35
+ ):
36
+ return datetime_equality(ctx, x, y)
37
+
23
38
  a = util.parse_value(x[0])
24
39
  b = util.parse_value(y[0])
25
40
 
@@ -33,6 +48,12 @@ def equality(ctx, x, y):
33
48
  return a == b
34
49
 
35
50
 
51
+ def are_date_time_values(x, y):
52
+ return isinstance(get_comparable_data(x), nodes.FP_TimeBase) and isinstance(
53
+ get_comparable_data(y), nodes.FP_TimeBase
54
+ )
55
+
56
+
36
57
  def normalize_string(s):
37
58
  return " ".join(s.lower().split())
38
59
 
@@ -63,15 +84,40 @@ def equivalence(ctx, x, y):
63
84
  if util.is_empty(x) or util.is_empty(y):
64
85
  return False
65
86
 
87
+ if len(x) != len(y):
88
+ return False
89
+
90
+ if len(x) == 1:
91
+ return item_equivalence(ctx, x, y)
92
+
93
+ unmatched = list(y)
94
+ for a in x:
95
+ for i, b in enumerate(unmatched):
96
+ if item_equivalence(ctx, [a], [b]):
97
+ del unmatched[i]
98
+ break
99
+ else:
100
+ return False
101
+ return True
102
+
103
+
104
+ def item_equivalence(ctx, x, y):
66
105
  a = util.get_data(x[0])
67
106
  b = util.get_data(y[0])
68
107
 
69
- if type(a) in DATETIME_NODES_LIST or type(b) in DATETIME_NODES_LIST:
108
+ if (
109
+ type(a) in DATETIME_NODES_LIST
110
+ or type(b) in DATETIME_NODES_LIST
111
+ or are_date_time_values(x[0], y[0])
112
+ ):
70
113
  return datetime_equality(ctx, x, y)
71
114
 
72
115
  if isinstance(a, str) and isinstance(b, str):
73
116
  return normalize_string(a) == normalize_string(b)
74
117
 
118
+ if a is None or b is None:
119
+ return a is None and b is None
120
+
75
121
  if isinstance(a, Decimal) or isinstance(b, Decimal):
76
122
  return is_equivalent(a, b)
77
123
 
@@ -83,6 +129,9 @@ def equivalence(ctx, x, y):
83
129
 
84
130
  if isinstance(a, abc.Mapping | list) and isinstance(b, abc.Mapping | list):
85
131
 
132
+ def sort_key(item):
133
+ return json.dumps(item, sort_keys=True, default=str)
134
+
86
135
  def deep_equal(a, b):
87
136
  if isinstance(a, abc.Mapping) and isinstance(b, abc.Mapping):
88
137
  if a.keys() != b.keys():
@@ -90,7 +139,8 @@ def equivalence(ctx, x, y):
90
139
  return all(deep_equal(a[key], b[key]) for key in a)
91
140
  elif isinstance(a, list) and isinstance(b, list):
92
141
  return len(a) == len(b) and all(
93
- deep_equal(x, y) for x, y in zip(sorted(a), sorted(b), strict=True)
142
+ deep_equal(x, y)
143
+ for x, y in zip(sorted(a, key=sort_key), sorted(b, key=sort_key), strict=True)
94
144
  )
95
145
  elif isinstance(a, str) and isinstance(b, str):
96
146
  return normalize_string(a) == normalize_string(b)
@@ -101,23 +151,28 @@ def equivalence(ctx, x, y):
101
151
 
102
152
  return deep_equal(a, b)
103
153
 
104
- return x == y
154
+ return a == b
105
155
 
106
156
 
107
157
  def datetime_equality(ctx, x, y):
108
- datetime_x = x[0]
109
- datetime_y = y[0]
110
- if datetime_x is None or datetime_y is None:
158
+ if len(x) != len(y):
159
+ return False
160
+ if x[0] is None or y[0] is None:
111
161
  return None
112
- if type(datetime_x) not in DATETIME_NODES_LIST:
113
- v_x = util.get_data(datetime_x)
114
- datetime_x = nodes.FP_DateTime(v_x) or nodes.FP_Time(v_x)
115
- if type(datetime_y) not in DATETIME_NODES_LIST:
116
- v_y = util.get_data(datetime_y)
117
- datetime_y = nodes.FP_DateTime(v_y) or nodes.FP_Time(v_y)
162
+ datetime_x = convert_to_date_time(x[0])
163
+ datetime_y = convert_to_date_time(y[0])
164
+ if datetime_x is None or datetime_y is None:
165
+ return False
118
166
  return datetime_x.equals(datetime_y)
119
167
 
120
168
 
169
+ def convert_to_date_time(value):
170
+ data = get_comparable_data(value)
171
+ if isinstance(data, nodes.FP_TimeBase):
172
+ return data
173
+ return nodes.FP_DateTime(data) or nodes.FP_Time(data)
174
+
175
+
121
176
  def equal(ctx, a, b):
122
177
  equality_result = equality(ctx, a, b)
123
178
  return util.arraify(equality_result)
@@ -144,21 +199,11 @@ def check_length(value):
144
199
  if len(value) > 1:
145
200
  raise Exception(
146
201
  "Was expecting no more than one element but got "
147
- + json.dumps(value)
202
+ + json.dumps(value, default=lambda item: str(util.get_data(item)))
148
203
  + ". Singleton was expected"
149
204
  )
150
205
 
151
206
 
152
- def remove_duplicate_extension(list):
153
- """
154
- This is a temporary solution for cases where the list contains 2 items with the same key,
155
- like birthDate and _birthDate. Needs to be fixed to a better solution.
156
- """
157
- if len(list) == 2 and isinstance(list[1], nodes.ResourceNode) and "extension" in list[1].data:
158
- return list[:1]
159
- return list
160
-
161
-
162
207
  def typecheck(a, b):
163
208
  """
164
209
  Checks that the types of a and b are suitable for comparison in an
@@ -173,28 +218,26 @@ def typecheck(a, b):
173
218
  """
174
219
  rtn = None
175
220
 
176
- a = remove_duplicate_extension(a)
177
- b = remove_duplicate_extension(b)
178
-
179
221
  check_length(a)
180
222
  check_length(b)
181
223
 
182
- a = util.get_data(a[0])
183
- b = util.get_data(b[0])
224
+ a = get_comparable_data(a[0])
225
+ b = get_comparable_data(b[0])
184
226
 
185
227
  lClass = a.__class__
186
228
  rClass = b.__class__
187
229
 
188
230
  areNumbers = util.is_number(a) and util.is_number(b)
231
+ areDateTimes = isinstance(a, nodes.FP_DateTime) and isinstance(b, nodes.FP_DateTime)
189
232
 
190
- if lClass != rClass and not areNumbers:
233
+ if lClass != rClass and not areNumbers and not areDateTimes:
191
234
  d = None
192
235
 
193
- if lClass is str and (rClass in (nodes.FP_DateTime, nodes.FP_Time)):
236
+ if lClass is str and (rClass in DATETIME_NODES_LIST):
194
237
  d = nodes.FP_DateTime(a) or nodes.FP_Time(a)
195
238
  if d is not None:
196
239
  rtn = [d, b]
197
- elif rClass is str and (lClass in (nodes.FP_DateTime, nodes.FP_Time)):
240
+ elif rClass is str and (lClass in DATETIME_NODES_LIST):
198
241
  d = nodes.FP_DateTime(b) or nodes.FP_Time(b)
199
242
  if d is not None:
200
243
  rtn = [a, d]
@@ -218,10 +261,17 @@ def typecheck(a, b):
218
261
  return [a, b]
219
262
 
220
263
 
264
+ def get_comparable_data(value):
265
+ """Return a resource date, dateTime, instant or time as a typed value, other values as data."""
266
+ if isinstance(value, nodes.ResourceNode) and value.date_time is not None:
267
+ return value.date_time
268
+ return util.get_data(value)
269
+
270
+
221
271
  def lt(ctx, a, b):
222
272
  if len(a) == 0 or len(b) == 0:
223
273
  return []
224
- if a[0] is None or b[0] is None:
274
+ if util.get_data(a[0]) is None or util.get_data(b[0]) is None:
225
275
  return []
226
276
 
227
277
  vals = typecheck(a, b)
@@ -229,11 +279,7 @@ def lt(ctx, a, b):
229
279
  b0 = vals[1]
230
280
 
231
281
  if isinstance(a0, nodes.FP_Type):
232
- if (
233
- isinstance(a0, nodes.FP_TimeBase)
234
- and a0.compare(b0) is None
235
- and a0._precision != b0._precision
236
- ):
282
+ if isinstance(a0, nodes.FP_TimeBase) and a0.compare(b0) is None:
237
283
  return None
238
284
  return a0.compare(b0) == -1
239
285
 
@@ -243,7 +289,7 @@ def lt(ctx, a, b):
243
289
  def gt(ctx, a, b):
244
290
  if len(a) == 0 or len(b) == 0:
245
291
  return []
246
- if a[0] is None or b[0] is None:
292
+ if util.get_data(a[0]) is None or util.get_data(b[0]) is None:
247
293
  return []
248
294
 
249
295
  vals = typecheck(a, b)
@@ -251,11 +297,7 @@ def gt(ctx, a, b):
251
297
  b0 = vals[1]
252
298
 
253
299
  if isinstance(a0, nodes.FP_Type):
254
- if (
255
- isinstance(a0, nodes.FP_TimeBase)
256
- and a0.compare(b0) is None
257
- and a0._precision != b0._precision
258
- ):
300
+ if isinstance(a0, nodes.FP_TimeBase) and a0.compare(b0) is None:
259
301
  return None
260
302
  return a0.compare(b0) == 1
261
303
 
@@ -265,7 +307,7 @@ def gt(ctx, a, b):
265
307
  def lte(ctx, a, b):
266
308
  if len(a) == 0 or len(b) == 0:
267
309
  return []
268
- if a[0] is None or b[0] is None:
310
+ if util.get_data(a[0]) is None or util.get_data(b[0]) is None:
269
311
  return []
270
312
 
271
313
  vals = typecheck(a, b)
@@ -273,11 +315,7 @@ def lte(ctx, a, b):
273
315
  b0 = vals[1]
274
316
 
275
317
  if isinstance(a0, nodes.FP_Type):
276
- if (
277
- isinstance(a0, nodes.FP_TimeBase)
278
- and a0.compare(b0) is None
279
- and a0._precision != b0._precision
280
- ):
318
+ if isinstance(a0, nodes.FP_TimeBase) and a0.compare(b0) is None:
281
319
  return None
282
320
  return a0.compare(b0) <= 0
283
321
 
@@ -287,7 +325,7 @@ def lte(ctx, a, b):
287
325
  def gte(ctx, a, b):
288
326
  if len(a) == 0 or len(b) == 0:
289
327
  return []
290
- if a[0] is None or b[0] is None:
328
+ if util.get_data(a[0]) is None or util.get_data(b[0]) is None:
291
329
  return []
292
330
 
293
331
  vals = typecheck(a, b)
@@ -295,11 +333,7 @@ def gte(ctx, a, b):
295
333
  b0 = vals[1]
296
334
 
297
335
  if isinstance(a0, nodes.FP_Type):
298
- if (
299
- isinstance(a0, nodes.FP_TimeBase)
300
- and a0.compare(b0) is None
301
- and a0._precision != b0._precision
302
- ):
336
+ if isinstance(a0, nodes.FP_TimeBase) and a0.compare(b0) is None:
303
337
  return None
304
338
  return a0.compare(b0) >= 0
305
339
 
@@ -1,3 +1,4 @@
1
+ from collections import abc
1
2
  from decimal import Decimal
2
3
 
3
4
  from fhirpathpy.engine import nodes, util
@@ -20,10 +21,10 @@ def count_fn(ctx, value):
20
21
 
21
22
 
22
23
  def not_fn(ctx, x):
23
- if len(x) != 1:
24
+ if len(x) == 1 and util.get_data(x[0]) is None:
24
25
  return []
25
26
 
26
- data = util.get_data(x[0])
27
+ # singleton() returns [] for an empty input and raises for more than one item
27
28
  data = misc.singleton(x, "Boolean")
28
29
 
29
30
  if isinstance(data, bool):
@@ -40,6 +41,19 @@ def exists_macro(ctx, coll, expr=None):
40
41
  return not util.is_empty(vec)
41
42
 
42
43
 
44
+ def has_value_fn(ctx, coll):
45
+ """
46
+ FHIR specific hasValue(), see https://hl7.org/fhir/fhirpath.html#functions
47
+ Returns true if the input is a single FHIR primitive that has a value
48
+ (as opposed to a primitive that only has extensions), otherwise false.
49
+ """
50
+ if len(coll) != 1:
51
+ return False
52
+
53
+ value = util.get_data(coll[0])
54
+ return value is not None and not isinstance(value, abc.Mapping | list | nodes.FP_Quantity)
55
+
56
+
43
57
  def all_macro(ctx, colls, expr):
44
58
  for i, coll in enumerate(colls):
45
59
  ctx["$index"] = i
@@ -73,7 +87,9 @@ def any_false_fn(ctx, items):
73
87
 
74
88
 
75
89
  def subset_of(ctx, coll1, coll2):
76
- return all(item in coll2 for item in coll1)
90
+ # Resource date/time values compare as written, not by instant, as in fhirpath.js.
91
+ data2 = [util.get_data(item) for item in coll2]
92
+ return all(util.get_data(item) in data2 for item in coll1)
77
93
 
78
94
 
79
95
  def subset_of_fn(ctx, coll1, coll2):
@@ -113,7 +129,7 @@ def distinct_fn(ctx, x):
113
129
  }
114
130
 
115
131
  if all(isinstance(v, nodes.ResourceNode) for v in x):
116
- data = [v.data for v in x]
132
+ data = [v if util.is_date_time(v) or v.data is None else v.data for v in x]
117
133
  unique = util.uniq(data)
118
134
  return [nodes.ResourceNode.create_node(item) for item in unique]
119
135
 
@@ -13,7 +13,8 @@ from fhirpathpy.engine import nodes, util
13
13
  def check_macro_expr(expr, x):
14
14
  result = expr(x)
15
15
  if len(result) > 0:
16
- return expr(x)[0]
16
+ value = util.get_data(result[0])
17
+ return value if isinstance(value, bool) else True
17
18
 
18
19
  return False
19
20
 
@@ -120,6 +121,9 @@ def extension(ctx, data, url):
120
121
  res = []
121
122
  for d in data:
122
123
  element = util.get_data(d)
124
+ if isinstance(d, nodes.ResourceNode) and not isinstance(element, abc.Mapping):
125
+ # Extensions of a primitive are stored in its "_" element
126
+ element = d._data
123
127
  if isinstance(element, abc.Mapping):
124
128
  exts = [e for e in element.get("extension", []) if e["url"] == url]
125
129
  if len(exts) > 0: