getVar method

Value? getVar(
  1. String identifier, {
  2. LocalOnlyMode localOnly = LocalOnlyMode.off,
})

Get the value of a variable available in this context (including locals, globals, and intrinsics). Raise an exception if no such identifier can be found.

Implementation

Value? getVar(
  String identifier, {
  LocalOnlyMode localOnly = LocalOnlyMode.off,
}) {
  // check for special built-in identifiers 'locals', 'globals', etc.
  switch (identifier.length) {
    case 4:
      if (identifier == "self") return self;
      break;
    case 5:
      if (identifier == "outer") {
        // return module variables, if we have them; else globals
        if (outerVars != null) return outerVars;
        root.variables ??= ValMap();
        return root.variables;
      }
      break;
    case 6:
      if (identifier == "locals") {
        variables ??= ValMap();
        return variables!;
      }
      break;
    case 7:
      if (identifier == "globals") {
        root.variables ??= ValMap();
        return root.variables;
      }
      break;
  }

  // check for a local variable
  ValuePointer<Value> resultPointer = ValuePointer();
  if (variables != null &&
      variables!.tryGetValueWithIdentifier(
        identifier,
        resultPointer,
      )) {
    return resultPointer.value;
  }

  if (localOnly != LocalOnlyMode.off) {
    if (localOnly == LocalOnlyMode.strict) {
      throw UndefinedLocalException(identifier);
    } else {
      vm?.standardOutput(
        "Warning: assignment of unqualified local '$identifier' based on nonlocal is deprecated ${code[lineNum].location}",
        true,
      );
    }
  }

  // check for a module variable
  if (outerVars != null &&
      outerVars!.tryGetValueWithIdentifier(identifier, resultPointer)) {
    return resultPointer.value;
  }

  // OK, we don't have a local or module variable with that name.
  // Check the global scope (if that's not us already).
  if (parent != null) {
    Context globals = root;
    if (globals.variables != null &&
        globals.variables!.tryGetValueWithIdentifier(
          identifier,
          resultPointer,
        )) {
      return resultPointer.value;
    }
  }

  // Finally, check intrinsics.
  final intrinsic = Intrinsic.getByName(identifier);
  if (intrinsic != null) return intrinsic.getFunc();

  // No luck there either?  Undefined identifier.
  throw UndefinedIdentifierException(identifier);
}