unicode

Branch: main

Switch branches or tags

Branch: main
Go to file t

413 files indexed

History
Code

tools/emitter/enum.mbt
1///|2/// One value of an enumerated property: the enum constructor standing for it3/// and the comment written next to that constructor.4pub(all) struct EnumValue {5  name : String6  comment : String7}89///|10/// Write the enum of an enumerated property with `Debug` and `Eq`, a `Show`11/// implementation printing the constructor names, and the function12/// `converter` turning a table ordinal into the enum.13///14/// The ordinal of a value is its index in `values`, which is how moonc15/// represents a constructor without arguments on every backend, so the16/// converter is `%identity`. Its callers must pass only ordinals below17/// `values.length()`: no other value is a constructor.18pub fn Emitter::write_enum(19  self : Emitter,20  type_name~ : String,21  doc~ : Array[String],22  converter~ : String,23  values~ : Array[EnumValue],24) -> Unit raise {25  guard !values.is_empty() else { fail("\{type_name} has no constructors") }26  self.write("///|\n")27  for line in doc {28    self.write_line("/// \{line}")29  }30  self.write_line("#derive(Debug, Eq)")31  self.write_line("pub(all) enum \{type_name} {")32  for value in values {33    self.write_line("  \{value.name} // \{value.comment}")34  }35  self.write(36    (37      $|}38      $|39      $|///|40      $|#deprecated("Use `Debug::to_repr` instead", skip_current_package=true)41      $|#doc(hidden)42      $|pub extend \{type_name} with Debug::{to_repr}43      $|44      $|///|45      $|pub extend \{type_name} with Eq::{not_equal, equal}46      $|47      $|///|48      $|pub extend \{type_name} with Show::{to_string, output}49      $|50      $|///|51      $|pub impl Show for \{type_name} with fn output(self, logger) {52      $|  logger.write_string(53      $|    match self {54      $|55    ),56  )57  for value in values {58    self.write_line("      \{value.name} => \"\{value.name}\"")59  }60  self.write(61    (62      $|    },63      $|  )64      $|}65      $|66      $|///|67      $|/// Convert a \{type_name} ordinal, below \{values.length()}, to the enum value.68      $|///69      $|/// A constructor without arguments is its ordinal on every backend. A70      $|/// `match` or a table would cost a jump table or a load on wasm, wasm-gc71      $|/// and JS, slower there than the trie lookup itself.72      $|fn \{converter}(ordinal : Int) -> \{type_name} = "%identity"73      $|74      $|75    ),76  )77}78