rewrite.mx raw

   1  // Package mxsrc holds the byte-level source rewrites shared by the compiler
   2  // and the distillation tools. Moving them here is the first step of the package
   3  // layout refactor: there is one implementation of the make-literal lowering, not
   4  // one in the compiler and another in a rewriter.
   5  package mxsrc
   6  
   7  import (
   8  	"moxielang.dev/pkg/mxutil"
   9  )
  10  
  11  // JoinChunks concatenates byte slices in one allocation.
  12  func JoinChunks(chunks [][]byte) (r []byte) {
  13  	n := int32(0)
  14  	for _, c := range chunks {
  15  		n += len(c)
  16  	}
  17  	out := []byte{:n}
  18  	off := int32(0)
  19  	for _, c := range chunks {
  20  		for j := int32(0); j < len(c); j++ {
  21  			out[off+j] = c[j]
  22  		}
  23  		off += len(c)
  24  	}
  25  	return out
  26  }
  27  
  28  // LIndexByte returns the first index of c in b, or -1.
  29  func LIndexByte(b []byte, c byte) (n int32) {
  30  	for i := int32(0); i < int32(len(b)); i++ {
  31  		if b[i] == c {
  32  			return i
  33  		}
  34  	}
  35  	return -1
  36  }
  37  
  38  // LIndexFrom returns the first absolute index at or after `from` of sep in s,
  39  // or -1. A sub-slice is a COPY in Moxie, so the rewrite loops that called
  40  // `LIndex(src[i:], ...)` copied the whole remaining source on every iteration.
  41  // The scans themselves are linear, so this is an efficiency fix, not the pass's
  42  // quadratic term (measured: 1.847 GB -> 1.832 GB on the `runtime` package).
  43  func LIndexFrom(s []byte, from int32, sep []byte) (n int32) {
  44  	n = len(sep)
  45  	if n == 0 {
  46  		return from
  47  	}
  48  	if from < 0 {
  49  		from = 0
  50  	}
  51  	if from > int32(len(s)) || n > int32(len(s))-from {
  52  		return -1
  53  	}
  54  	c0 := sep[0]
  55  	for i := from; i <= int32(len(s))-n; i++ {
  56  		if s[i] != c0 {
  57  			continue
  58  		}
  59  		hit := true
  60  		for j := int32(1); j < n; j++ {
  61  			if s[i+j] != sep[j] {
  62  				hit = false
  63  				break
  64  			}
  65  		}
  66  		if hit {
  67  			return i
  68  		}
  69  	}
  70  	return -1
  71  }
  72  
  73  // LIndex returns the first index of sep in s, or -1.
  74  func LIndex(s, sep []byte) (n int32) {
  75  	n = len(sep)
  76  	if n == 0 {
  77  		return 0
  78  	}
  79  	if n > len(s) {
  80  		return -1
  81  	}
  82  	c0 := sep[0]
  83  	for i := int32(0); i <= int32(len(s))-int32(n); i++ {
  84  		if s[i] == c0 {
  85  			match := true
  86  			for j := int32(1); j < int32(n); j++ {
  87  				if s[i+j] != sep[j] {
  88  					match = false
  89  					break
  90  				}
  91  			}
  92  			if match {
  93  				return i
  94  			}
  95  		}
  96  	}
  97  	return -1
  98  }
  99  
 100  // LTrimSpace trims leading and trailing ASCII whitespace.
 101  func LTrimSpace(s []byte) (buf []byte) {
 102  	start := int32(0)
 103  	for start < int32(len(s)) && (s[start] == ' ' || s[start] == '\t' || s[start] == '\n' || s[start] == '\r') {
 104  		start++
 105  	}
 106  	stop := int32(len(s))
 107  	for stop > start && (s[stop-1] == ' ' || s[stop-1] == '\t' || s[stop-1] == '\n' || s[stop-1] == '\r') {
 108  		stop--
 109  	}
 110  	return s[start:stop]
 111  }
 112  
 113  // LIndexByteFrom returns the first index of c at or after `from`, or -1. The
 114  // caller otherwise has to sub-slice, and a sub-slice is a COPY in Moxie.
 115  func LIndexByteFrom(s []byte, from int32, c byte) (n int32) {
 116  	if from < 0 {
 117  		from = 0
 118  	}
 119  	for i := from; i < int32(len(s)); i++ {
 120  		if s[i] == c {
 121  			return i
 122  		}
 123  	}
 124  	return -1
 125  }
 126  
 127  // trimRange trims ASCII whitespace from src[from:to] and returns the bounds, so
 128  // trimming costs two indexes instead of a copied sub-slice.
 129  func trimRange(src []byte, from, to int32) (a, b int32) {
 130  	a = from
 131  	for a < to && (src[a] == ' ' || src[a] == '\t' || src[a] == '\n' || src[a] == '\r') {
 132  		a++
 133  	}
 134  	b = to
 135  	for b > a && (src[b-1] == ' ' || src[b-1] == '\t' || src[b-1] == '\n' || src[b-1] == '\r') {
 136  		b--
 137  	}
 138  	return a, b
 139  }
 140  
 141  // sliceLiteralScan resolves the `{:` at `start` to its match. ok is false when
 142  // the construct is not a slice literal, in which case the caller emits the two
 143  // bytes and continues.
 144  func sliceLiteralScan(src []byte, start int32) (lbrack, closeIdx, colonIdx int32, ok bool) {
 145  	lbrack = findSliceTypeStart(src, start)
 146  	if lbrack < 0 {
 147  		return -1, -1, -1, false
 148  	}
 149  	closeIdx = findMatchingBrace(src, start)
 150  	if closeIdx < 0 {
 151  		return -1, -1, -1, false
 152  	}
 153  	colonIdx = LIndexByteFrom(src, start+2, ':')
 154  	if colonIdx >= closeIdx {
 155  		colonIdx = -1
 156  	}
 157  	return lbrack, closeIdx, colonIdx, true
 158  }
 159  
 160  // putStr copies s into out at o and returns the next cursor position.
 161  func putStr(out []byte, o int32, s string) (n int32) {
 162  	for i := int32(0); i < int32(len(s)); i++ {
 163  		out[o] = s[i]
 164  		o++
 165  	}
 166  	return o
 167  }
 168  
 169  // putRange copies src[from:to] into out at o and returns the next cursor.
 170  func putRange(out []byte, o int32, src []byte, from, to int32) (n int32) {
 171  	for i := from; i < to; i++ {
 172  		out[o] = src[i]
 173  		o++
 174  	}
 175  	return o
 176  }
 177  
 178  // emitSliceLiteral writes one rewritten literal into out at o.
 179  func emitSliceLiteral(out []byte, o int32, src []byte, lbrack, start, closeIdx, colonIdx int32) (n int32) {
 180  	a, b := trimRange(src, start+2, closeIdx)
 181  	a2 := int32(0)
 182  	b2 := int32(0)
 183  	if colonIdx >= 0 {
 184  		a, b = trimRange(src, start+2, colonIdx)
 185  		a2, b2 = trimRange(src, colonIdx+1, closeIdx)
 186  	}
 187  	o = putStr(out, o, "__slicealloc(")
 188  	o = putRange(out, o, src, lbrack, start)
 189  	o = putStr(out, o, ", ")
 190  	o = putRange(out, o, src, a, b)
 191  	if colonIdx >= 0 {
 192  		o = putStr(out, o, ", ")
 193  		o = putRange(out, o, src, a2, b2)
 194  	}
 195  	return putStr(out, o, ")")
 196  }
 197  
 198  // trimmedLen is the length of src[from:to] with ASCII whitespace trimmed.
 199  func trimmedLen(src []byte, from, to int32) (n int32) {
 200  	a, b := trimRange(src, from, to)
 201  	return b - a
 202  }
 203  
 204  // sliceLiteralOutLen is the number of bytes emitSliceLiteral writes for the
 205  // same match, without writing them.
 206  func sliceLiteralOutLen(src []byte, lbrack, start, closeIdx, colonIdx int32) (n int32) {
 207  	n = (start - lbrack) + 16
 208  	if colonIdx < 0 {
 209  		return n + trimmedLen(src, start+2, closeIdx)
 210  	}
 211  	n += trimmedLen(src, start+2, colonIdx) + 2
 212  	return n + trimmedLen(src, colonIdx+1, closeIdx)
 213  }
 214  
 215  // RewriteSliceMakeLiterals lowers `[]T{:n}` and `[]T{:a:b}` to __slicealloc.
 216  //
 217  // It scans twice and writes once. The obvious shape - collect the segments in a
 218  // [][]byte and JoinChunks them - is quadratic here, and not because of the
 219  // scans: every `chunks = mxutil.Ensure(chunks, 1)` RETURNS a pointer-containing
 220  // slice across a function boundary, so the return protocol walks and copies
 221  // every segment accumulated so far, once per push. Measured on `runtime`
 222  // (519 KB of source): 32 MB -> 1.92 GB of arena inside this function, and
 223  // `io` (32 KB): 1.5 MB -> 35 MB.
 224  //
 225  // The output length is exactly computable from a scan that allocates nothing,
 226  // so pass one totals it, pass two writes through a cursor into one allocation.
 227  func RewriteSliceMakeLiterals(src []byte) (buf []byte) {
 228  	bc := []byte("{:")
 229  	n := int32(len(src))
 230  	outLen := n
 231  	matches := int32(0)
 232  	i := int32(0)
 233  	for i < n {
 234  		start := LIndexFrom(src, i, bc)
 235  		if start < 0 {
 236  			break
 237  		}
 238  		lbrack, closeIdx, colonIdx, ok := sliceLiteralScan(src, start)
 239  		if !ok {
 240  			i = start + 2
 241  			continue
 242  		}
 243  		outLen += sliceLiteralOutLen(src, lbrack, start, closeIdx, colonIdx) - (closeIdx + 1 - start)
 244  		matches++
 245  		i = closeIdx + 1
 246  	}
 247  	if matches == 0 {
 248  		return src
 249  	}
 250  	out := []byte{:outLen}
 251  	o := int32(0)
 252  	i = 0
 253  	for i < n {
 254  		start := LIndexFrom(src, i, bc)
 255  		if start < 0 {
 256  			o = putRange(out, o, src, i, n)
 257  			break
 258  		}
 259  		lbrack, closeIdx, colonIdx, ok := sliceLiteralScan(src, start)
 260  		if !ok {
 261  			o = putRange(out, o, src, i, start+2)
 262  			i = start + 2
 263  			continue
 264  		}
 265  		o = putRange(out, o, src, i, lbrack)
 266  		o = emitSliceLiteral(out, o, src, lbrack, start, closeIdx, colonIdx)
 267  		i = closeIdx + 1
 268  	}
 269  	// out[:o] rather than out: the estimate can only err LARGE (an underestimate
 270  	// faults at once in putRange), and an overestimate leaves unwritten NULs
 271  	// that the parser reports as "invalid NUL character" at end of file - a
 272  	// silent corruption that a miscount of __slicealloc( by one byte produced.
 273  	return out[:o]
 274  }
 275  
 276  func isIdentByteAt(src []byte, k int32) (r bool) {
 277  	if k < 0 {
 278  		return false
 279  	}
 280  	ch := src[k]
 281  	return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '.'
 282  }
 283  
 284  // followsConstruct reports whether the identifier at start is the result type
 285  // of a construct whose text continues leftward, in which case a space before it
 286  // is inside the type rather than a boundary: `func() int32` and `map[K]V` end in
 287  // `)` / `]`, while `chan int32` and friends end in a bare type keyword.
 288  func followsConstruct(src []byte, start int32) (r bool) {
 289  	k := start - 1
 290  	for k >= 0 && (src[k] == ' ' || src[k] == '\t') {
 291  		k--
 292  	}
 293  	if k < 0 {
 294  		return false
 295  	}
 296  	if src[k] == ')' || src[k] == ']' {
 297  		return true
 298  	}
 299  	for _, kw := range []string{"chan", "map", "func", "struct", "interface"} {
 300  		if wordEndsAt(src, k+1, kw) {
 301  			return true
 302  		}
 303  	}
 304  	return false
 305  }
 306  
 307  // wordEndsAt reports whether word occupies src[end-len(word):end] as a whole
 308  // word (not as the tail of a longer identifier).
 309  func wordEndsAt(src []byte, end int32, word string) (r bool) {
 310  	n := int32(len(word))
 311  	if end < n {
 312  		return false
 313  	}
 314  	for i := int32(0); i < n; i++ {
 315  		if src[end-n+i] != word[i] {
 316  			return false
 317  		}
 318  	}
 319  	return !isIdentByteAt(src, end-n-1)
 320  }
 321  
 322  func findSliceTypeStart(src []byte, braceIdx int32) (n int32) {
 323  	j := braceIdx - 1
 324  	for j >= 0 && (src[j] == ' ' || src[j] == '\t' || src[j] == '\n') {
 325  		j--
 326  	}
 327  	if j < 0 {
 328  		return -1
 329  	}
 330  	depth := 0
 331  	parenDepth := 0
 332  	// braceDepth tracks the TYPE's own braces: `[]struct{ n int32 }{:2}` must
 333  	// scan back over `struct{ n int32 }` as one unit. Without it the `}` of the
 334  	// struct was treated as a boundary and the type text came out as
 335  	// `int32 }`, which the parser then rejected with "unexpected :". inTag
 336  	// skips a backquoted struct tag, whose contents may hold braces or colons.
 337  	braceDepth := 0
 338  	inTag := false
 339  	candidate := -1
 340  	identStart := -1
 341  	for j >= 0 {
 342  		ch := src[j]
 343  		if ch == '`' {
 344  			inTag = !inTag
 345  			j--
 346  			continue
 347  		}
 348  		if inTag {
 349  			j--
 350  			continue
 351  		}
 352  		if ch == '}' {
 353  			braceDepth++
 354  			j--
 355  			continue
 356  		}
 357  		if ch == '{' {
 358  			if braceDepth > 0 {
 359  				braceDepth--
 360  			}
 361  			j--
 362  			continue
 363  		}
 364  		if braceDepth > 0 {
 365  			j--
 366  			continue
 367  		}
 368  		if ch == ')' {
 369  			parenDepth++
 370  		} else if ch == '(' {
 371  			if parenDepth > 0 {
 372  				parenDepth--
 373  			} else {
 374  				if candidate >= 0 {
 375  					return candidate
 376  				}
 377  				if identStart >= 0 {
 378  					return identStart
 379  				}
 380  				return -1
 381  			}
 382  		} else if parenDepth > 0 {
 383  			j--
 384  			continue
 385  		}
 386  		if ch == ']' {
 387  			depth++
 388  		} else if ch == '[' {
 389  			depth--
 390  			if depth == 0 && !isIdentByteAt(src, j-1) {
 391  				// A balanced pair starts the type only when nothing names it:
 392  				// the `[` of `map[K]V` or of a generic `List[T]` is preceded by
 393  				// an identifier and must not be mistaken for the slice's `[`.
 394  				candidate = j
 395  			}
 396  		} else if depth == 0 && parenDepth == 0 {
 397  			if candidate >= 0 {
 398  				return candidate
 399  			}
 400  			if ch == ' ' || ch == '\t' || ch == '\n' {
 401  				// A space after a type name ends the type: `return nat{:1}`
 402  				// must not scan back into the `return` keyword. Spaces
 403  				// before any type char (e.g. `[]byte {`) are skipped.
 404  				if identStart >= 0 && !followsConstruct(src, identStart) {
 405  					return identStart
 406  				}
 407  				j--
 408  				continue
 409  			}
 410  			if ch == '*' || ch == '(' || ch == ')' {
 411  				j--
 412  				continue
 413  			}
 414  			if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '.' {
 415  				// A bare type name (buffer{:0:64}) has no brackets to mark
 416  				// its start; record the leftmost identifier byte and return
 417  				// it when a real boundary follows.
 418  				identStart = j
 419  				j--
 420  				continue
 421  			}
 422  			if identStart >= 0 {
 423  				return identStart
 424  			}
 425  			return -1
 426  		}
 427  		j--
 428  	}
 429  	if candidate >= 0 {
 430  		return candidate
 431  	}
 432  	if identStart >= 0 {
 433  		return identStart
 434  	}
 435  	return -1
 436  }
 437  
 438  func findMatchingBrace(src []byte, openIdx int32) (n int32) {
 439  	depth := 1
 440  	for i := openIdx + 1; i < len(src); i++ {
 441  		if src[i] == '{' {
 442  			depth++
 443  		} else if src[i] == '}' {
 444  			depth--
 445  			if depth == 0 {
 446  				return i
 447  			}
 448  		}
 449  	}
 450  	return -1
 451  }
 452  
 453  
 454  func RewriteChanMakeLiterals(src []byte) (buf []byte) {
 455  	chanKw := []byte("chan ")
 456  	var chunks [][]byte
 457  	started := false
 458  	i := 0
 459  	for i < len(src) {
 460  		idx := LIndexFrom(src, i, chanKw)
 461  		if idx < 0 {
 462  			if started {
 463  				chunks = mxutil.Ensure(chunks, 1)
 464  				push(chunks, src[i:])
 465  			}
 466  			break
 467  		}
 468  		j := idx + 5
 469  		for j < len(src) && (src[j] == ' ' || src[j] == '\t') {
 470  			j++
 471  		}
 472  		if j >= len(src) {
 473  			if started {
 474  				chunks = mxutil.Ensure(chunks, 1)
 475  				push(chunks, src[i:])
 476  			}
 477  			break
 478  		}
 479  		if src[j] == '<' && j+1 < len(src) && src[j+1] == '-' {
 480  			if started {
 481  				chunks = mxutil.Ensure(chunks, 1)
 482  				push(chunks, src[i:j+2])
 483  			}
 484  			i = j + 2
 485  			continue
 486  		}
 487  		for j < len(src) && (src[j] != '{' && src[j] != '\n' && src[j] != ';' && src[j] != '(' && src[j] != ')') {
 488  			if src[j] == ' ' || src[j] == '\t' {
 489  				break
 490  			}
 491  			j++
 492  		}
 493  		if j >= len(src) || src[j] != '{' {
 494  			if !started {
 495  				i = idx + 4
 496  			} else {
 497  				chunks = mxutil.Ensure(chunks, 1)
 498  				push(chunks, src[i:idx+4])
 499  				i = idx + 4
 500  			}
 501  			continue
 502  		}
 503  		braceOpen := j
 504  		endsStruct := braceOpen >= 6 && string(src[braceOpen-6:braceOpen]) == "struct"
 505  		endsIface := braceOpen >= 9 && string(src[braceOpen-9:braceOpen]) == "interface"
 506  		if endsStruct || endsIface {
 507  			typeClose := findMatchingBrace(src, braceOpen)
 508  			if typeClose < 0 {
 509  				if !started {
 510  					i = idx + 4
 511  				} else {
 512  					chunks = mxutil.Ensure(chunks, 1)
 513  					push(chunks, src[i:idx+4])
 514  					i = idx + 4
 515  				}
 516  				continue
 517  			}
 518  			k := typeClose + 1
 519  			if k >= len(src) || src[k] != '{' {
 520  				if !started {
 521  					i = typeClose + 1
 522  				} else {
 523  					chunks = mxutil.Ensure(chunks, 1)
 524  					push(chunks, src[i:typeClose+1])
 525  					i = typeClose + 1
 526  				}
 527  				continue
 528  			}
 529  			braceOpen = k
 530  		}
 531  		closeIdx := findMatchingBrace(src, braceOpen)
 532  		if closeIdx < 0 {
 533  			if !started {
 534  				i = idx + 4
 535  			} else {
 536  				chunks = mxutil.Ensure(chunks, 1)
 537  				push(chunks, src[i:idx+4])
 538  				i = idx + 4
 539  			}
 540  			continue
 541  		}
 542  		inner := LTrimSpace(src[braceOpen+1 : closeIdx])
 543  		// chan T{:n} is the capacity-only form (a channel has no length
 544  		// separate from its capacity): the allocator takes the number.
 545  		if len(inner) > 0 && inner[0] == ':' {
 546  			inner = LTrimSpace(inner[1:])
 547  		}
 548  		chanType := src[idx : braceOpen]
 549  		for len(chanType) > 0 && (chanType[len(chanType)-1] == ' ' || chanType[len(chanType)-1] == '\t') {
 550  			chanType = resize(chanType, len(chanType)-1)
 551  		}
 552  		if !started {
 553  			chunks = mxutil.Ensure(chunks, 1)
 554  			push(chunks, src[:idx])
 555  			started = true
 556  		} else {
 557  			chunks = mxutil.Ensure(chunks, 1)
 558  			push(chunks, src[i:idx])
 559  		}
 560  		// chan T{depth, budget}: the second field is the PER-MESSAGE byte budget,
 561  		// which the ring is sized from. It is an ordinary expression,
 562  		// so relay policy read from config can set it at run time. A channel
 563  		// with no stated depth still gets one slot.
 564  		depth, budget := splitChanSpec(inner)
 565  		if len(depth) == 0 {
 566  			depth = []byte("1")
 567  		}
 568  		chunks = mxutil.Ensure(chunks, 1)
 569  		push(chunks, []byte("__slicealloc("))
 570  		chunks = mxutil.Ensure(chunks, 1)
 571  		push(chunks, chanType)
 572  		chunks = mxutil.Ensure(chunks, 1)
 573  		push(chunks, []byte(", "))
 574  		chunks = mxutil.Ensure(chunks, 1)
 575  		push(chunks, depth)
 576  		if len(budget) > 0 {
 577  			chunks = mxutil.Ensure(chunks, 1)
 578  			push(chunks, []byte(", "))
 579  			chunks = mxutil.Ensure(chunks, 1)
 580  			push(chunks, budget)
 581  		}
 582  		chunks = mxutil.Ensure(chunks, 1)
 583  		push(chunks, []byte(")"))
 584  		i = closeIdx + 1
 585  	}
 586  	if !started {
 587  		return src
 588  	}
 589  	return JoinChunks(chunks)
 590  }
 591  
 592  // splitChanSpec splits a channel literal's inner text into its element count
 593  // and its optional per-element byte budget at the first TOP-LEVEL colon, the
 594  // notation `chan T{:depth:bytes}`. A colon inside brackets is part of a slice
 595  // expression, not a field separator. An empty depth means the default (one
 596  // slot), which is how `chan T{::65536}` states a budget with no element count.
 597  func splitChanSpec(inner []byte) (depth, budget []byte) {
 598  	parens := int32(0)
 599  	brackets := int32(0)
 600  	braces := int32(0)
 601  	for i := int32(0); i < len(inner); i++ {
 602  		switch inner[i] {
 603  		case '(':
 604  			parens++
 605  		case ')':
 606  			parens--
 607  		case '[':
 608  			brackets++
 609  		case ']':
 610  			brackets--
 611  		case '{':
 612  			braces++
 613  		case '}':
 614  			braces--
 615  		case ':':
 616  			if parens == 0 && brackets == 0 && braces == 0 {
 617  				return LTrimSpace(inner[:i]), LTrimSpace(inner[i+1:])
 618  			}
 619  		}
 620  	}
 621  	return LTrimSpace(inner), nil
 622  }
 623  
 624  // RewriteEdgeDecls lowers the declared ownership pair
 625  //
 626  //	parent, child := edge[In, Out]{depth}
 627  //
 628  // into the form the compiler special-cases:
 629  //
 630  //	var parent Edge[In, Out]; var child Edge[In, Out]; __edgealloc(&parent, &child, Edge[In, Out]{}, depth)
 631  //
 632  // The declaration is the language surface (docs/memory-model.md D19); the
 633  // lowered form is the same machinery []T{:n} uses, where the first argument of
 634  // the internal builtin is a TYPE expression and the compiler lowers the call.
 635  // Newlines in the replaced range are re-emitted so diagnostics keep their
 636  // line numbers.
 637  func RewriteEdgeDecls(src []byte) (buf []byte) {
 638  	var chunks [][]byte
 639  	i := int32(0)
 640  	last := int32(0)
 641  	for i < len(src) {
 642  		k := LIndexFrom(src, i, []byte("edge["))
 643  		if k < 0 {
 644  			break
 645  		}
 646  		e0 := k
 647  		// Identifier boundary: not part of a longer identifier.
 648  		if e0 > 0 && isIdentByteAt(src, e0-1) {
 649  			i = e0 + 5
 650  			continue
 651  		}
 652  		open := e0 + 4
 653  		rb := edgeMatchDelim(src, open, '[', ']')
 654  		if rb < 0 {
 655  			i = e0 + 5
 656  			continue
 657  		}
 658  		j := rb + 1
 659  		for j < len(src) && edgeSpace(src[j]) {
 660  			j = j + 1
 661  		}
 662  		if j >= len(src) || src[j] != '{' {
 663  			i = e0 + 5
 664  			continue
 665  		}
 666  		rc := findMatchingBrace(src, j)
 667  		if rc < 0 {
 668  			i = e0 + 5
 669  			continue
 670  		}
 671  		// Backward: ident ',' ident ':=' before the keyword.
 672  		b := e0 - 1
 673  		for b >= 0 && edgeSpace(src[b]) {
 674  			b = b - 1
 675  		}
 676  		// Backward from the keyword the define token is `=:` read right-to-left.
 677  		if b < 1 || src[b] != '=' || src[b-1] != ':' {
 678  			i = e0 + 5
 679  			continue
 680  		}
 681  		b = b - 2
 682  		for b >= 0 && edgeSpace(src[b]) {
 683  			b = b - 1
 684  		}
 685  		cEnd := b + 1
 686  		for b >= 0 && edgeIdentBody(src[b]) {
 687  			b = b - 1
 688  		}
 689  		cStart := b + 1
 690  		if cStart >= cEnd {
 691  			i = e0 + 5
 692  			continue
 693  		}
 694  		for b >= 0 && edgeSpace(src[b]) {
 695  			b = b - 1
 696  		}
 697  		if b < 0 || src[b] != ',' {
 698  			i = e0 + 5
 699  			continue
 700  		}
 701  		b = b - 1
 702  		for b >= 0 && edgeSpace(src[b]) {
 703  			b = b - 1
 704  		}
 705  		pEnd := b + 1
 706  		for b >= 0 && edgeIdentBody(src[b]) {
 707  			b = b - 1
 708  		}
 709  		pStart := b + 1
 710  		if pStart >= pEnd {
 711  			i = e0 + 5
 712  			continue
 713  		}
 714  		// Statement position: start of input, or after ; { } or a line break.
 715  		if pStart > 0 {
 716  			pc := src[pStart-1]
 717  			if !(pc == ';' || pc == '{' || pc == '}' || pc == '\n' || pc == '\t' || pc == ' ') {
 718  				i = e0 + 5
 719  				continue
 720  			}
 721  		}
 722  		paren := src[pStart:pEnd]
 723  		cname := src[cStart:cEnd]
 724  		types := LTrimSpace(src[open+1 : rb])
 725  		depth := LTrimSpace(src[j+1 : rc])
 726  		if len(types) == 0 {
 727  			i = e0 + 5
 728  			continue
 729  		}
 730  		if len(depth) == 0 {
 731  			depth = []byte("1")
 732  		}
 733  		// The child is the COMPLEMENT: Edge[Out, In]. One type on both sides
 734  		// would type the child's Receive end for In while the parent sends Out.
 735  		inText, outText, okArgs := splitEdgeArgs(types)
 736  		if !okArgs {
 737  			i = e0 + 5
 738  			continue
 739  		}
 740  		childType := []byte("Edge[")
 741  		childType = push(childType, outText...)
 742  		childType = push(childType, []byte(", ")...)
 743  		childType = push(childType, inText...)
 744  		childType = push(childType, []byte("]")...)
 745  		push(chunks, src[last:pStart])
 746  		push(chunks, []byte("var "))
 747  		push(chunks, paren)
 748  		push(chunks, []byte(" Edge["))
 749  		push(chunks, types)
 750  		push(chunks, []byte("]; var "))
 751  		push(chunks, cname)
 752  		push(chunks, []byte(" ")) // childType already carries Edge[...]
 753  		push(chunks, childType)
 754  		push(chunks, []byte("; __edgealloc(&"))
 755  		push(chunks, paren)
 756  		push(chunks, []byte(", &"))
 757  		push(chunks, cname)
 758  		push(chunks, []byte(", Edge["))
 759  		push(chunks, types)
 760  		push(chunks, []byte("]{}"))
 761  		push(chunks, []byte(", "))
 762  		push(chunks, depth)
 763  		push(chunks, []byte(")"))
 764  		for nl := pStart; nl <= rc; nl++ {
 765  			if src[nl] == '\n' {
 766  				push(chunks, []byte("\n"))
 767  			}
 768  		}
 769  		last = rc + 1
 770  		i = rc + 1
 771  	}
 772  	if len(chunks) == 0 {
 773  		return src
 774  	}
 775  	push(chunks, src[last:])
 776  	return JoinChunks(chunks)
 777  }
 778  
 779  func edgeSpace(c byte) (ok bool) {
 780  	return c == ' ' || c == '\t' || c == '\n' || c == '\r'
 781  }
 782  
 783  func edgeIdentBody(c byte) (ok bool) {
 784  	return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
 785  }
 786  
 787  // edgeMatchDelim finds the delimiter that closes the one at open. Type
 788  // arguments nest brackets ([]byte) but cannot contain a string literal, so
 789  // counting is enough.
 790  func edgeMatchDelim(src []byte, open int32, oc, cc byte) (n int32) {
 791  	d := int32(0)
 792  	for i := open; i < len(src); i++ {
 793  		if src[i] == oc {
 794  			d = d + 1
 795  		} else if src[i] == cc {
 796  			d = d - 1
 797  			if d == 0 {
 798  				return i
 799  			}
 800  		}
 801  	}
 802  	return -1
 803  }
 804  
 805  // splitEdgeArgs splits an edge declaration's type arguments at the top-level
 806  // comma: edge[In, Out] names the parent's receive type first and its send type
 807  // second.
 808  func splitEdgeArgs(b []byte) (ins, outs []byte, ok bool) {
 809  	d := int32(0)
 810  	for i := int32(0); i < len(b); i++ {
 811  		switch b[i] {
 812  		case '[', '(', '{':
 813  			d = d + 1
 814  		case ']', ')', '}':
 815  			d = d - 1
 816  		case ',':
 817  			if d == 0 {
 818  				return LTrimSpace(b[:i]), LTrimSpace(b[i+1:]), true
 819  			}
 820  		}
 821  	}
 822  	return nil, nil, false
 823  }
 824