example.mx raw

   1  package main
   2  
   3  import "moxie"
   4  
   5  // Example Moxie file exercising syntax highlighting.
   6  //
   7  // Moxie is a systems language for domain-isolated programs. Key differences from Go:
   8  //   - string and []byte are the same type
   9  //   - int32 and uint32 are always 32-bit (int/uint are illegal)
  10  //   - no goroutines; spawn() creates isolated domains over IPC
  11  //   - no new(), complex, uintptr; use &T{}, literal syntax, explicit pointers
  12  //   - text concat uses |, not +
  13  //   - push/pop/resize replace append
  14  //   - fallthrough and go are compile errors
  15  
  16  const MaxWorkers = int32(4)
  17  
  18  type Job struct {
  19  	id   int32
  20  	name string
  21  }
  22  
  23  func worker(j moxie.Int32, out chan moxie.Int32) {
  24  	out <- moxie.Int32(int32(j) * int32(j))
  25  }
  26  
  27  func main() {
  28  	// Slice size literals: []T{:len} and []T{:len:cap}.
  29  	buf := []byte{:1024}
  30  	queue := []int32{:0:100}
  31  
  32  	// Channel and map literals (no make).
  33  	results := chan moxie.Int32{}
  34  	config := map[string]int32{
  35  		"timeout":    30,
  36  		"maxRetries": 3,
  37  	}
  38  
  39  	// Text concatenation with |, not +.
  40  	greeting := "hello " | "moxie" | "!"
  41  
  42  	// Fan out: each spawn creates an isolated domain.
  43  	for i := int32(0); i < MaxWorkers; i++ {
  44  		spawn(worker, moxie.Int32(i), results)
  45  	}
  46  
  47  	// Event loop.
  48  	for n := int32(0); n < MaxWorkers; n++ {
  49  		select {
  50  		case r := <-results:
  51  			println(int32(r))
  52  		}
  53  	}
  54  
  55  	/*
  56  	   Range over text yields bytes, not runes.
  57  	   Use an encoding library for rune-level iteration.
  58  	*/
  59  	for i, b := range greeting {
  60  		if b == ' ' {
  61  			clear(buf[i:])
  62  			break
  63  		}
  64  	}
  65  
  66  	// push replaces append: explicit growth, store-back implicit.
  67  	push(queue, 1, 2, 3)
  68  	last := pop(queue)
  69  	resize(queue, 0)
  70  	_ = config
  71  	_ = last
  72  }
  73  
  74  // Multiple return values must be named.
  75  func divide(a, b float64) (result float64, err error) {
  76  	if b == 0 {
  77  		return 0, nil
  78  	}
  79  	return a / b, nil
  80  }
  81  
  82  // Generics with comparable constraint (no any/interface{}).
  83  func filter[T comparable](items []T, pred func(T) bool) (result []T) {
  84  	result = []T{:0:len(items)}
  85  	for _, item := range items {
  86  		if pred(item) {
  87  			push(result, item)
  88  		}
  89  	}
  90  	return
  91  }
  92