Language reference · section 26

26. Streams

A @worker function whose body contains yield is a stream.

Feature: Streams

  Scenario: A worker function with yield is a stream
    Given a @worker function whose body contains yield expr
    Then the function returns an async iterable of items

  Scenario: yield is allowed only directly in a worker function body
    Given yield inside a plain function
    Then the compiler reports an error "yield is only allowed in a @worker function, directly in its body"

  Scenario: A stream cannot be async
    Given an async @worker function with yield
    Then the compiler reports an error "a streaming @worker function cannot be async"

  Scenario: The return annotation names the item type
    Given the code "fn count_up(n: int): int:"
    Then the stream yields int items

  Scenario: A stream ends with a return that has no value
    Given a stream with a bare return
    When the loop reaches it
    Then the loop ends

  Scenario: A stream cannot return a value
    Given a stream with return 5
    Then the compiler reports an error "a streaming @worker function ends with a plain `return`; it cannot return a value"

  Scenario: The worker runs only when the caller asks
    Given a stream that no code reads
    Then the worker does no work

  Scenario: A stream holds its worker until it ends
    Given a stream that is running
    When another call arrives
    Then the call does not run on the stream's worker

  Scenario: A failed stream stops the loop with the error
    Given a stream that fails on an item
    When the loop asks for that item
    Then the loop stops with the same error as a failed call

  Scenario: A crashed stream worker fails the next step only
    Given a stream whose worker crashes
    When the loop asks for the next item
    Then the step fails with a "worker crashed" error

  Scenario: break in a for await loop stops the generator
    Given a for await loop over a stream
    When the loop runs break
    Then the generator stops on its worker and its finally block runs
@worker
fn odds_up_to(limit: int): int:
  mut n = 1

  while n <= limit:
    if n % 2 is 1:
      yield n

    n = n + 1

for await odd in odds_up_to(9):
  console.log("odd:", odd)