parseSymbol method

Component parseSymbol(
  1. Lexer lexer
)

Implementation

Component parseSymbol(Lexer lexer) {
  final Symbol symbol = Symbol();
  final String sym = lexer.token!;

  // Now, can we pick a prefix that leaves behind a metric unit?
  Prefix? selected;
  UcumUnit? unit;
  for (final Prefix prefix in model.prefixes) {
    // TODO(Dokotela): relook at this
    if (prefix.names.isNotEmpty && sym.startsWith(prefix.names.first)) {
      unit = model.getUnit(sym.substring(prefix.names.first.length));
      if (unit != null && (unit is BaseUnit || (unit.isMetric ?? false))) {
        selected = prefix;
      }
    }
    if (selected == prefix) {
      break;
    }
    if (sym.startsWith(prefix.code)) {
      unit = model.getUnit(sym.substring(prefix.code.length));
      if (unit != null && (unit is BaseUnit || (unit.isMetric ?? false))) {
        selected = prefix;
        break;
      }
    }
  }

  if (selected != null) {
    symbol.prefix = selected;
    symbol.unit = unit;
  } else {
    unit = model.getUnit(sym);
    if (unit != null) {
      symbol.unit = unit;
    } else if (sym != '1') {
      throw UcumException("Error processing unit: '${lexer.source}' The unit "
          "'$sym' is unknown at position ${lexer.start}");
    }
  }

  lexer.consume();
  if (lexer.type == TokenType.number) {
    symbol.exponent = lexer.getTokenAsInt();
    lexer.consume();
  } else {
    symbol.exponent = 1;
  }

  return symbol;
}