walkFhirPath function Null safety

List walkFhirPath(
  1. Map<String, dynamic>? resource,
  2. String pathExpression,
  3. [Map<String, dynamic>? passed,
  4. FhirVersion version = FhirVersion.r4]
)

Start here! This is where the fun begins. It first checks to be sure there is a resource to be evaluated, and an AST (abstract syntax tree) which admittedly in this case is a bit of a misnomer, because the AST is actually placed as a list into the value field of a ParserList It then checks if the first node in the AST is the same as the ResourceType of the Resource, if so, it is removed.

Implementation

List<dynamic> walkFhirPath(
  Map<String, dynamic>? resource,
  String pathExpression, [
  Map<String, dynamic>? passed,
  FhirVersion version = FhirVersion.r4,
]) {
  final passedValue = passed ?? {};
  passedValue['%resource'] = resource ?? [];
  passedValue['version'] = version;

  try {
    final FhirPathParser ast = lexer().parse(pathExpression).value;
    if (ast is ParserList) {
      if (ast.isEmpty) {
        return [];
      } else {
        // Check for combination of IdentifierParser followed by ParenthesisParser
        // This indicates invalid function name
        if (ast.value.length > 1) {
          for (int i = 0; i < ast.value.length - 1; i++) {
            if ((ast.value[i] is IdentifierParser) &&
                (ast.value[i + 1] is ParenthesesParser)) {
              final String functionName =
                  (ast.value[i] as IdentifierParser).value;
              throw FhirPathInvalidExpressionException(
                  'Unknown function: $functionName',
                  pathExpression: pathExpression);
            }
          }
        }

        return ast.execute([resource], passedValue);
      }
    } else {
      throw FhirPathInvalidExpressionException(
          'Parsing did not result in ParserList',
          pathExpression: pathExpression);
    }
  } catch (error) {
    if (error is FhirPathException) {
      throw error;
    } else if (error is ParserException) {
      throw FhirPathInvalidExpressionException(
        'Expression could not be parsed: ${error.message}',
        pathExpression: pathExpression,
        offset: error.offset,
        cause: error,
      );
    } else {
      throw FhirPathException(
        'Unable to execute FHIRPath expression',
        pathExpression: pathExpression,
        cause: error,
        resource: resource,
        variables: passedValue,
      );
    }
  }
}