CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-scala-lang--scala3-library-sjs1-3

Scala.js-specific runtime library components for Scala 3, providing JavaScript-specific functionality and bridge components between Scala 3 and the Scala.js runtime environment

Pending
Overview
Eval results
Files

metaprogramming.mddocs/

Metaprogramming

Compile-time operations, quoted expressions, and macro support for powerful metaprogramming with type-safe code generation and compile-time computation.

Capabilities

Compile-Time Operations

Core compile-time functions for constant folding, implicit summoning, and compile-time errors.

/**
 * Get a value of singleton type T at compile time
 * T must be a constant type like 42 or "hello"
 */
inline def constValue[T]: T

/**
 * Safely get a constant value, returns None if not a constant type
 */
inline def constValueOpt[T]: Option[T]

/**
 * Extract all constant values from a tuple type
 */
inline def constValueTuple[T <: Tuple]: T

/**
 * Pattern match on types without values (erased matching)
 */
inline def erasedValue[T]: T

/**
 * Marker for uninitialized fields (use with caution)
 */
def uninitialized: Nothing

/**
 * Marker for deferred given instances
 */
def deferred: Nothing

/**
 * Emit compile-time error with custom message
 */
inline def error(msg: String): Nothing

/**
 * Get string representation of code expression
 */
inline def codeOf(arg: Any): String

/**
 * Require that expression is a compile-time constant
 */
inline def requireConst(x: Boolean | Byte | Short | Int | Long | Float | Double | Char | String): Unit

/**
 * Delayed implicit summoning - resolved at inline expansion
 */
inline def summonInline[T]: T

/**
 * Conditional implicit summoning with fallback handling
 */
inline def summonFrom[T](f: Nothing => T): T

/**
 * Summon all implicit instances for tuple of types
 */
inline def summonAll[T <: Tuple]: T

/**
 * Force by-name parameter evaluation (compile-time assertion)
 */
inline def byName[T](x: => T): T

Usage Examples:

import scala.compiletime.*

// Constant value extraction
type Three = 3
val three: 3 = constValue[Three]  // 3

type Message = "Hello, World!"
val msg: String = constValue[Message]  // "Hello, World!"

// Safe constant extraction
val maybeConst = constValueOpt[Int]  // None (Int is not a singleton type)
val definiteConst = constValueOpt[42]  // Some(42)

// Tuple constant extraction
type Point = (1, 2, 3)
val coords = constValueTuple[Point]  // (1, 2, 3)

// Type-based pattern matching
inline def sizeOf[T]: Int = inline erasedValue[T] match
  case _: Byte => 1
  case _: Short => 2  
  case _: Int => 4
  case _: Long => 8
  case _: Float => 4
  case _: Double => 8

// Compile-time errors
inline def assertPositive(x: Int): Int =
  inline if x <= 0 then error("Value must be positive")
  else x

// Code introspection
val code = codeOf(1 + 2 * 3)  // "1.+(2.*(3))"

// Conditional summoning
inline def optionalSummoning[T]: Option[T] = summonFrom {
  case given T => Some(summon[T])
  case _ => None
}

// By-name forcing
inline def debugTime[T](name: String)(expr: => T): T =
  println(s"Evaluating $name")
  byName(expr)

Type-Level Operations

Compile-time operations on types for type-level programming.

Any Type Operations

/**
 * Convert any type to its string representation
 */
type ToString[X] <: String

/**
 * Type equality test
 */
type =:=[X, Y] <: Boolean

Boolean Operations

/**
 * Boolean negation at type level
 */
type ![X <: Boolean] <: Boolean

/**
 * Boolean AND at type level
 */
type &&[X <: Boolean, Y <: Boolean] <: Boolean

/**
 * Boolean OR at type level
 */
type ||[X <: Boolean, Y <: Boolean] <: Boolean

Integer Operations

/**
 * Successor (add 1) at type level
 */
type S[X <: Int] <: Int

/**
 * Addition at type level
 */
type +[X <: Int, Y <: Int] <: Int

/**
 * Subtraction at type level
 */
type -[X <: Int, Y <: Int] <: Int

/**
 * Multiplication at type level
 */
type *[X <: Int, Y <: Int] <: Int

/**
 * Division at type level
 */
type /[X <: Int, Y <: Int] <: Int

/**
 * Modulo at type level
 */
type %[X <: Int, Y <: Int] <: Int

/**
 * Less than comparison at type level
 */
type <[X <: Int, Y <: Int] <: Boolean

/**
 * Less than or equal at type level
 */
type <=[X <: Int, Y <: Int] <: Boolean

/**
 * Greater than at type level
 */
type >[X <: Int, Y <: Int] <: Boolean

/**
 * Greater than or equal at type level
 */
type >=[X <: Int, Y <: Int] <: Boolean

/**
 * Absolute value at type level
 */
type Abs[X <: Int] <: Int

/**
 * Maximum of two integers at type level
 */
type Max[X <: Int, Y <: Int] <: Int

/**
 * Minimum of two integers at type level
 */
type Min[X <: Int, Y <: Int] <: Int

String Operations

/**
 * String concatenation at type level
 */
type +[X <: String, Y <: String] <: String

/**
 * String length at type level
 */
type Length[X <: String] <: Int

/**
 * Substring extraction at type level
 */
type Substring[S <: String, IBeg <: Int, IEnd <: Int] <: String

/**
 * Regular expression matching at type level
 */
type Matches[S <: String, Regex <: String] <: Boolean

Usage Examples:

import scala.compiletime.ops.*

// Type-level arithmetic
type Five = int.+[2, 3]      // 5
type Seven = int.*[Five, 1]  // 7  
type Two = int.-[Five, 3]    // 2

// Type-level boolean logic
type True = boolean.![false]  // true
type False = boolean.&&[true, false]  // false

// Type-level string operations
type Greeting = string.+["Hello", " World"]  // "Hello World"
type Len = string.Length[Greeting]  // 11
type Sub = string.Substring[Greeting, 0, 5]  // "Hello"

// Using in function signatures
def vectorOfSize[N <: Int](size: N): IArray[Int] = 
  IArray.fill(constValue[N])(0)

val vec5 = vectorOfSize[5]  // IArray of size 5

Quoted Expressions

Quotation system for representing and manipulating Scala expressions at compile time.

/**
 * Quoted expression representing Scala code of type T
 */
abstract class Expr[+T]:
  /** Show the expression as a string */
  def show(using Quotes): String
  /** Get the value if expression is a constant */
  def value(using Quotes): Option[T]
  /** Get the value, throwing if not constant */
  def valueOrAbort(using Quotes)(msg: String): T
  /** Apply beta reduction to inline definitions */
  def betaReduce(using Quotes): Expr[T]

object Expr:
  /** Lift a value to an expression */
  def apply[T](value: T)(using ToExpr[T], Quotes): Expr[T]
  /** Create block expression */
  def block[T](statements: List[Expr[Any]], expr: Expr[T])(using Quotes): Expr[T]
  /** Unapply to extract value from constant expression */
  def unapply[T](expr: Expr[T])(using Quotes): Option[T]
  /** Create expression from sequence */
  def ofSeq[T](elems: Seq[Expr[T]])(using Type[T], Quotes): Expr[Seq[T]]
  /** Create expression from list */
  def ofList[T](elems: List[Expr[T]])(using Type[T], Quotes): Expr[List[T]]
  /** Create tuple expression from sequence */
  def ofTupleFromSeq(elems: Seq[Expr[Any]])(using Quotes): Expr[Tuple]
  /** Summon implicit and create expression */
  def summon[T](using Type[T], Quotes): Expr[T]

/**
 * Type representation in quoted context
 */
trait Type[T]:
  /** Show the type as a string */
  def show(using Quotes): String

/**
 * Quotes context providing access to compiler information
 */
trait Quotes:
  /** Reflect API for advanced operations */
  val reflect: Reflect
  
/**
 * Convert values to expressions
 */  
trait ToExpr[T]:
  def apply(x: T)(using Quotes): Expr[T]

/**
 * Extract values from expressions
 */
trait FromExpr[T]:
  def apply(x: Expr[T])(using Quotes): Option[T]

/**
 * Variable argument expressions
 */
object Varargs:
  def apply[T](elems: Expr[T]*)(using Type[T], Quotes): Expr[Seq[T]]
  def unapply[T](expr: Expr[Seq[T]])(using Quotes): Option[Seq[Expr[T]]]

Usage Examples:

import scala.quoted.*

// Basic quotation (inside macro)
def exampleMacro(using Quotes): Expr[Int] =
  val two = Expr(2)
  val three = Expr(3)
  '{ $two + $three }  // Creates expression: 2 + 3

// Pattern matching on expressions
def analyzeExpr(expr: Expr[Int])(using Quotes): String = expr match
  case Expr(n) => s"Constant: $n"
  case '{ $x + $y } => s"Addition of ${x.show} and ${y.show}"
  case _ => "Complex expression"

// Creating block expressions
def blockMacro(using Quotes): Expr[String] =
  val printExpr = '{ println("Computing...") }
  val resultExpr = '{ "Hello, World!" }
  Expr.block(List(printExpr), resultExpr)

// Working with sequences
def listMacro(elems: Expr[Seq[Int]])(using Quotes): Expr[List[Int]] = elems match
  case Varargs(exprs) => 
    val listExprs = exprs.map(e => '{ $e }).toList
    Expr.ofList(listExprs)
  case _ => 
    '{ $elems.toList }

Compile-Time Testing

Utilities for testing compile-time behavior and error handling.

/**
 * Representation of a compile-time error
 */
case class Error(
  message: String,
  line: Int,
  column: Int,
  kind: ErrorKind
)

/**
 * Classification of compile errors
 */
enum ErrorKind:
  case Parser, Typer, Other

/**
 * Test if code compiles without errors
 */
def typeChecks(code: String): Boolean

/**
 * Get all compile errors for given code
 */
def typeCheckErrors(code: String): List[Error]

Usage Examples:

import scala.compiletime.testing.*

// Test compilation
val goodCode = "val x: Int = 42"
val badCode = "val x: String = 42"

assert(typeChecks(goodCode))   // true
assert(!typeChecks(badCode))   // false

// Analyze errors
val errors = typeCheckErrors("val x: String = 42")
errors.foreach { error =>
  println(s"Error at line ${error.line}: ${error.message}")
}

// Use in inline tests
inline def testInline(): Unit =
  inline if !typeChecks("val x: Int = \"hello\"") then
    println("Type error detected as expected")

Extension Methods for Metaprogramming

extension (inline x: Any)
  /** Cast value to Matchable for pattern matching */
  inline def asMatchable: Matchable

Usage Examples:

def processAny(x: Any): String =
  x.asMatchable match
    case s: String => s"String: $s"
    case i: Int => s"Int: $i"
    case _ => "Other"

Types

// Core metaprogramming types
abstract class Expr[+T]
trait Type[T] 
trait Quotes
trait ToExpr[T]
trait FromExpr[T]

// Type-level operation types
object ops:
  object any:
    type ToString[X] <: String
    type =:=[X, Y] <: Boolean
    
  object boolean:
    type ![X <: Boolean] <: Boolean
    type &&[X <: Boolean, Y <: Boolean] <: Boolean
    type ||[X <: Boolean, Y <: Boolean] <: Boolean
    
  object int:
    type S[X <: Int] <: Int
    type +[X <: Int, Y <: Int] <: Int
    type -[X <: Int, Y <: Int] <: Int
    type *[X <: Int, Y <: Int] <: Int
    type /[X <: Int, Y <: Int] <: Int
    type %[X <: Int, Y <: Int] <: Int
    type <[X <: Int, Y <: Int] <: Boolean
    type <=[X <: Int, Y <: Int] <: Boolean
    type >[X <: Int, Y <: Int] <: Boolean
    type >=[X <: Int, Y <: Int] <: Boolean
    type Abs[X <: Int] <: Int
    type Max[X <: Int, Y <: Int] <: Int
    type Min[X <: Int, Y <: Int] <: Int
    
  object long:
    // Similar operations for Long types
    
  object double:
    // Similar operations for Double types
    
  object float:
    // Similar operations for Float types
    
  object string:
    type +[X <: String, Y <: String] <: String
    type Length[X <: String] <: Int
    type Substring[S <: String, IBeg <: Int, IEnd <: Int] <: String
    type Matches[S <: String, Regex <: String] <: Boolean

// Testing types
case class Error(message: String, line: Int, column: Int, kind: ErrorKind)
enum ErrorKind

Install with Tessl CLI

npx tessl i tessl/maven-org-scala-lang--scala3-library-sjs1-3

docs

annotations.md

capabilities.md

collections.md

core-types.md

derivation.md

index.md

metaprogramming.md

runtime.md

utilities.md

tile.json