module scheme import encoding.utf8 import strings import sync.stdatomic const data_primitive_descriptors = [ PrimitiveDescriptor{'set-car!', Primitive.set_car} PrimitiveDescriptor{'set-cdr!', Primitive.set_cdr} PrimitiveDescriptor{'list-tail', Primitive.list_tail} PrimitiveDescriptor{'list-ref', Primitive.list_ref} PrimitiveDescriptor{'reverse', Primitive.reverse} PrimitiveDescriptor{'memq', Primitive.memq} PrimitiveDescriptor{'memv', Primitive.memv} PrimitiveDescriptor{'member', Primitive.member} PrimitiveDescriptor{'assq', Primitive.assq} PrimitiveDescriptor{'assv', Primitive.assv} PrimitiveDescriptor{'assoc', Primitive.assoc} PrimitiveDescriptor{'string', Primitive.string_chars} PrimitiveDescriptor{'make-string', Primitive.make_string} PrimitiveDescriptor{'string-ref', Primitive.string_ref} PrimitiveDescriptor{'string-set!', Primitive.string_set} PrimitiveDescriptor{'substring', Primitive.substring} PrimitiveDescriptor{'string-copy', Primitive.string_copy} PrimitiveDescriptor{'string-fill!', Primitive.string_fill} PrimitiveDescriptor{'string->list', Primitive.string_to_list} PrimitiveDescriptor{'list->string', Primitive.list_to_string} PrimitiveDescriptor{'string->symbol', Primitive.string_to_symbol} PrimitiveDescriptor{'vector-set!', Primitive.vector_set} PrimitiveDescriptor{'vector-fill!', Primitive.vector_fill} PrimitiveDescriptor{'vector->list', Primitive.vector_to_list} PrimitiveDescriptor{'list->vector', Primitive.list_to_vector} PrimitiveDescriptor{'char-alphabetic?', Primitive.char_alphabetic} PrimitiveDescriptor{'char-numeric?', Primitive.char_numeric} PrimitiveDescriptor{'char-whitespace?', Primitive.char_whitespace} PrimitiveDescriptor{'char-upper-case?', Primitive.char_upper} PrimitiveDescriptor{'char-lower-case?', Primitive.char_lower} PrimitiveDescriptor{'char->integer', Primitive.char_to_integer} PrimitiveDescriptor{'integer->char', Primitive.integer_to_char} PrimitiveDescriptor{'char-upcase', Primitive.char_upcase} PrimitiveDescriptor{'char-downcase', Primitive.char_downcase} PrimitiveDescriptor{'string=?', Primitive.string_eq} PrimitiveDescriptor{'string?', Primitive.string_greater} PrimitiveDescriptor{'string<=?', Primitive.string_le} PrimitiveDescriptor{'string>=?', Primitive.string_ge} PrimitiveDescriptor{'string-ci=?', Primitive.string_ci_eq} PrimitiveDescriptor{'string-ci?', Primitive.string_ci_greater} PrimitiveDescriptor{'string-ci<=?', Primitive.string_ci_le} PrimitiveDescriptor{'string-ci>=?', Primitive.string_ci_ge} PrimitiveDescriptor{'char=?', Primitive.char_eq} PrimitiveDescriptor{'char?', Primitive.char_greater} PrimitiveDescriptor{'char<=?', Primitive.char_le} PrimitiveDescriptor{'char>=?', Primitive.char_ge} PrimitiveDescriptor{'char-ci=?', Primitive.char_ci_eq} PrimitiveDescriptor{'char-ci?', Primitive.char_ci_greater} PrimitiveDescriptor{'char-ci<=?', Primitive.char_ci_le} PrimitiveDescriptor{'char-ci>=?', Primitive.char_ci_ge}, ]! fn (mut vm VM) install_data_primitives() { for index in 0 .. data_primitive_descriptors.len { entry := &data_primitive_descriptors[index] vm.bind_global(entry.name, procedure_value(&Procedure{ mode: if entry.primitive in [ .member, .assoc, ] { .search } else { .primitive } name: entry.name owner: vm.owner primitive: entry.primitive })) } // R5RS includes every composed car/cdr accessor of depths two through four. for depth in 2 .. 5 { for mask in 0 .. (1 << depth) { mut name := 'c' for bit in 0 .. depth { name += if mask & (1 << bit) == 0 { 'a' } else { 'd' } } name += 'r' vm.bind_global(name, procedure_value(&Procedure{ mode: .primitive, name: name, owner: vm.owner, primitive: .cxr })) } } vm.install_sequence_primitives() } struct ListBuilder { mut: head Value = nil_value() tail &Pair = unsafe { nil } } fn (mut builder ListBuilder) push(value Value) { node := &Pair{ car: value, cdr: nil_value() } link := payload_value(.pair, node) if isnil(builder.tail) { builder.head = link } else { builder.tail.cdr = link } builder.tail = node } fn (mut builder ListBuilder) finish(tail Value) Value { if isnil(builder.tail) { return tail } builder.tail.cdr = tail return builder.head } fn append_lists(args []Value) !Value { if args.len == 0 { return nil_value() } mut out := ListBuilder{} for i in 0 .. args.len - 1 { count := args[i].list_length()! mut current := args[i] for _ in 0 .. count { pair := current.pair_pointer() out.push(pair.car) current = pair.cdr } } return out.finish(args.last()) } fn data_call(p Primitive, args []Value, name string) !Value { if int(p) >= int(Primitive.make_list) { if int(p) >= int(Primitive.bytevectorp) { return bytevector_call(p, args, name) } return sequence_call(p, args, name) } minimum, maximum := match p { .string_chars { 0, -1 } .make_string { 1, 2 } .set_car, .set_cdr, .list_tail, .list_ref, .string_ref, .memq, .memv, .member, .assq, .assv, .assoc { 2, 2 } .string_set, .vector_set, .substring { 3, 3 } .string_copy, .string_to_list, .vector_to_list { 1, 3 } .string_fill, .vector_fill { 2, 4 } .string_eq, .string_less, .string_greater, .string_le, .string_ge, .string_ci_eq, .string_ci_less, .string_ci_greater, .string_ci_le, .string_ci_ge, .char_eq, .char_less, .char_greater, .char_le, .char_ge, .char_ci_eq, .char_ci_less, .char_ci_greater, .char_ci_le, .char_ci_ge { 2, -1 } else { 1, 1 } } check_arity(name, args.len, minimum, maximum)! // These enums are contiguous groups of five order predicates each. if int(p) >= int(Primitive.string_eq) && int(p) <= int(Primitive.string_ci_ge) { mode := int(p) - int(Primitive.string_eq) mut previous := string_data(args[0])! mut matches := true for i in 1 .. args.len { current := string_data(args[i])! if !order_matches(compare_text(previous, current, mode >= 5), mode % 5) { matches = false } previous = current } return boolean(matches) } if int(p) >= int(Primitive.char_eq) && int(p) <= int(Primitive.char_ci_ge) { mode := int(p) - int(Primitive.char_eq) mut previous := args[0].as_character()! if mode >= 5 { previous = unicode_simple_fold(previous) } mut matches := true for i in 1 .. args.len { mut current := args[i].as_character()! if mode >= 5 { current = unicode_simple_fold(current) } order := if previous < current { -1 } else if previous > current { 1 } else { 0 } if !order_matches(order, mode % 5) { matches = false } previous = current } return boolean(matches) } match p { .set_car, .set_cdr { args[0].require_mutable(.pair)! mut pair := args[0].pair_pointer() if p == .set_car { pair.car = args[1] } else { pair.cdr = args[1] } return unspecified() } .cxr { mut current := args[0] for i := name.len - 2; i >= 1; i-- { a, d := current.pair_parts()! current = if name[i] == `a` { a } else { d } } return current } .list_tail, .list_ref { index := args[1].as_integer()! if index < 0 { return failure('list index must be nonnegative') } mut current := args[0] for _ in i64(0) .. index { if current.tag != .pair { return failure('list index out of range') } current = current.pair_pointer().cdr } if p == .list_tail { return current } a, _ := current.pair_parts()! return a } .reverse { count := args[0].list_length()! mut current := args[0] mut result := nil_value() for _ in 0 .. count { pair := current.pair_pointer() result = cons(pair.car, result) current = pair.cdr } return result } .memq, .memv, .member, .assq, .assv, .assoc { mut current := args[1] mut slow := current mut steps := 0 association := p in [.assq, .assv, .assoc] structural := p in [.member, .assoc] for current.tag == .pair { pair := current.pair_pointer() candidate := if association { head, _ := pair.car.pair_parts()! head } else { pair.car } matches := if structural { equal(args[0], candidate) } else { eqv(args[0], candidate) } if matches { return if association { pair.car } else { current } } current = pair.cdr if !args[1].read_only || args[1].datum_graph { steps++ if steps % 2 == 0 { slow = slow.pair_pointer().cdr if current.tag == .pair && current.pointer() == slow.pointer() { return failure('expected a proper list, got a circular list') } } } } if current.tag != .nil { return failure('expected a proper list') } return boolean(false) } .string_chars { mut out := strings.new_buffer(args.len) for value in args { out.write_string(value.as_character()!.str()) } return owned_string(out.take_string(), args.len) } .make_string { ch := if args.len == 2 { args[1].as_character()! } else { rune(` `) } encoded := ch.str() count := allocation_count(args[0], encoded.len)! return owned_string(encoded.repeat(count), count) } .string_to_symbol { return text_value(.symbol, string_data(args[0])!.clone()) } .string_copy { return copy_string_range(args) } .string_ref { _ := string_data(args[0])! text := args[0].string_pointer() offset := text_offset(text, args[1].as_integer()!)! if offset == text.value.len { return failure('string index out of range') } ch, _ := utf8.decode_rune_at(text.value, offset) return character(ch) } .string_set { args[0].require_mutable(.string)! ch := args[2].as_character()! mut target := args[0].string_pointer() replace_character(mut target, args[1].as_integer()!, ch)! target.revision++ return unspecified() } .string_fill { return fill_string_range(args) } .substring { _ := string_data(args[0])! text := args[0].string_pointer() start, end := args[1].as_integer()!, args[2].as_integer()! if end < start { return failure('substring end precedes start') } first, last := text_offset(text, start)!, text_offset(text, end)! return owned_string(text_view(text.value, first, last).clone(), int(end - start)) } .string_to_list { text, first, last, _, _ := string_range(args, 0, 1)! mut out := ListBuilder{} for ch in text_view(text.value, first, last).runes_iterator() { out.push(character(ch)!) } return out.finish(nil_value()) } .list_to_string { count := args[0].list_length()! mut current := args[0] mut out := strings.new_buffer(count) for _ in 0 .. count { pair := current.pair_pointer() out.write_string(pair.car.as_character()!.str()) current = pair.cdr } return owned_string(out.take_string(), count) } .vector_set { args[0].require_mutable(.vector)! index := args[1].as_integer()! mut content := args[0].vector_pointer() if index < 0 || index >= content.items.len { return failure('vector index out of range') } container_store_validated(mut content.items, int(index), args[2]) return unspecified() } .vector_fill { args[0].require_mutable(.vector)! mut content := args[0].vector_pointer() start, end := sequence_range(args, 2, content.items.len)! for i in start .. end { container_store_validated(mut content.items, i, args[1]) } return unspecified() } .vector_to_list { if args[0].tag != .vector { return failure('expected a vector') } items := args[0].vector_pointer().items start, end := sequence_range(args, 1, items.len)! mut out := ListBuilder{} for i in start .. end { out.push(items[i]) } return out.finish(nil_value()) } .list_to_vector { return payload_value(.vector, &Vector{ items: args[0].list_items()! }) } .integer_to_char { value := args[0].as_integer()! if value < 0 || value > 0x10ffff { return failure('invalid Unicode character') } return character(rune(value)) } .char_to_integer { return integer(i64(args[0].as_character()!)) } .char_upcase { return character(unicode_simple_case(args[0].as_character()!, 0)) } .char_downcase { return character(unicode_simple_case(args[0].as_character()!, 1)) } .char_alphabetic, .char_numeric, .char_whitespace, .char_upper, .char_lower { ch := args[0].as_character()! return boolean(match p { .char_alphabetic { unicode_alphabetic(ch) } .char_numeric { unicode_decimal(ch) >= 0 } .char_whitespace { unicode_white_space(ch) } .char_upper { unicode_case_property(ch, true) } else { unicode_case_property(ch, false) } }) } else { return failure('unimplemented data primitive ${name}') } } } fn string_data(value Value) !string { if value.tag != .string { return failure('expected a string, got ${value.tag}') } return value.text() } fn allocation_count(value Value, width int) !int { count := value.as_integer()! if count < 0 || count > max_int / width { return failure('invalid allocation length') } return int(count) } fn text_offset(text &StringData, index i64) !int { if index < 0 || index > text.length { return failure('string index out of range') } if text.length == text.value.len { return int(index) } if index == text.length { return text.value.len } revision := text.revision position_revision := stdatomic.load_u64(&text.cursor_revision) position := stdatomic.load_u64(&text.cursor_position) mut start_index := i64(0) mut offset := 0 if position_revision == revision && i64(position >> 32) <= index { start_index = i64(position >> 32) offset = int(u32(position)) } for _ in start_index .. index { if offset >= text.value.len { return failure('string index out of range') } _, width := utf8.decode_rune_at(text.value, offset) offset += width } // Publish the position first: a reader seeing the new revision must also // see a position for that revision. String mutations already bump revision. stdatomic.store_u64(&text.cursor_position, (u64(index) << 32) | u64(offset)) stdatomic.store_u64(&text.cursor_revision, revision) return offset } fn compare_text(a string, b string, fold bool) int { if fold { return compare_folded_text(a, b) } mut left := a.runes_iterator() mut right := b.runes_iterator() for { x := left.next() or { _ := right.next() or { return 0 } return -1 } y := right.next() or { return 1 } lx := x ry := y if lx < ry { return -1 } if lx > ry { return 1 } } return 0 } fn order_matches(order int, mode int) bool { return match mode { 0 { order == 0 } 1 { order < 0 } 2 { order > 0 } 3 { order <= 0 } else { order >= 0 } } } fn replace_character(mut target StringData, index i64, ch rune) ! { old := target.value start := text_offset(target, index)! if start == old.len { return failure('string index out of range') } _, width := utf8.decode_rune_at(old, start) if ch < 0x80 && width == 1 { overwrite_owned_byte(target, start, u8(ch)) return } replacement := ch.str() if width == replacement.len { overwrite_owned_text(target, start, replacement) return } end := start + width // Keep the old buffer rooted until the builder copies both borrowed ranges. prefix := text_view(old, 0, start) suffix := text_view(old, end, old.len) mut out := strings.new_buffer(old.len - width + replacement.len) out.write_string(prefix) out.write_string(replacement) out.write_string(suffix) target.value = out.take_string() } fn overwrite_owned_text(target &StringData, start int, replacement string) { // Callers checked mutability, character bounds, and equal encoded widths. // Mutable Text buffers are owned allocations; exported strings are clones. unsafe { mut bytes := &u8(target.value.str) for i, byte in replacement { bytes[start + i] = byte } } } fn overwrite_owned_byte(target &StringData, index int, value u8) { // String mutability and character/byte bounds were checked by the caller. unsafe { mut bytes := &u8(target.value.str) bytes[index] = value } } fn text_view(source string, start int, end int) string { // Private caller validated the byte range and keeps source alive. The view // is consumed only by a length-aware buffer writer, then discarded. return unsafe { tos(source.str + start, end - start) } }