Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new BF implementation in Swift and compile the matmul.swift #378

Merged
merged 2 commits into from
Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions brainfuck/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ executables := \
target/bin_d_gdc \
target/bin_d_ldc \
target/bin_rs \
target/bin_swift \
target/bin_nim_clang \
target/bin_nim_gcc \
target/bin_cr \
Expand Down Expand Up @@ -71,6 +72,9 @@ target/bin_rs: bf.rs | $(rs_fmt)
$(RUST_CLIPPY)
$(RUSTC_BUILD)

target/bin_swift: bf.swift | target
$(SWIFTC_BUILD)

target/bf_scala.jar: bf.scala | target
$(SCALAC_BUILD)

Expand Down
192 changes: 192 additions & 0 deletions brainfuck/bf.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Written by Ricardo Silva Veloso; distributed under the MIT license

import Foundation
import Glibc

enum Op {
case dec
case inc
case prev
case next
case print
case loop([Op])
}

struct Tape {
var pos = 0
var tape: ContiguousArray<Int32> = [0]
var currentCell: Int32 {
get { tape[pos] }
set { tape[pos] = newValue }
}

mutating func dec() {
currentCell -= 1
}

mutating func inc() {
currentCell += 1
}

mutating func prev() {
pos -= 1
}

mutating func next() {
pos += 1
if pos >= tape.count {
tape.append(contentsOf: repeatElement(0, count: tape.capacity * 2))
}
}
}

class Printer {
var sum1: Int32 = 0
var sum2: Int32 = 0
var quiet: Bool = false
var checksum: Int32 {
get { (sum2 << 8) | sum1 }
}

init(quiet: Bool) {
self.quiet = quiet
}

func print(_ n: Int32) {
if quiet {
sum1 = (sum1 + n) % 255
sum2 = (sum2 + sum1) % 255
} else {
putc(n, stdout)
}
}
}

@main
class Program {
let ops: [Op]
let p: Printer

init(code: String, p: Printer) {
var it = code.makeIterator()
self.ops = Program.parse(&it)
self.p = p
}

static func main() throws {
verify()
if CommandLine.argc < 2 {
exit(EXIT_FAILURE)
}
let text = try String(contentsOfFile: CommandLine.arguments[1])
let process = ProcessInfo.processInfo
let p = Printer(quiet: process.environment["QUIET"] != nil)
setbuf(stdout, nil)

notify("Swift\t\(process.processIdentifier)")
Program(code: text, p: p).run()
notify("stop")

if p.quiet {
print("Output checksum: \(p.checksum)")
}
}

static func verify() {
let s = """
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>\
---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
"""
let p_left = Printer(quiet: true)
Program(code: s, p: p_left).run()
let left = p_left.checksum

let p_right = Printer(quiet: true)
for c in "Hello World!\n" {
p_right.print(Int32(c.asciiValue!))
}
let right = p_right.checksum

if left != right {
fputs("\(left) != \(right)", stderr)
exit(EXIT_FAILURE)
}
}

private static func parse<I>(_ it: inout I) -> [Op]
where
I: IteratorProtocol,
I.Element == Character
{
var buf: [Op] = []
loop: while let c = it.next() {
switch c {
case "-":
buf.append(.dec)
case "+":
buf.append(.inc)
case "<":
buf.append(.prev)
case ">":
buf.append(.next)
case ".":
buf.append(.print)
case "[":
buf.append(.loop(parse(&it)))
case "]":
break loop
default:
continue
}
}
return buf
}

func run() {
var tape = Tape()
_run(ops, &tape)
}

private func _run(_ program: [Op], _ tape: inout Tape) {
for op in program {
switch op {
case .dec:
tape.dec()
case .inc:
tape.inc()
case .prev:
tape.prev()
case .next:
tape.next()
case .print:
p.print(tape.currentCell)
case let .loop(program):
while tape.currentCell > 0 {
_run(program, &tape)
}
}
}
}
}

func notify(_ msg: String) {
let sock = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
var serv_addr = (
sa_family_t(AF_INET),
in_port_t(htons(9001)),
in_addr(s_addr: 0),
(0,0,0,0,0,0,0,0))
inet_pton(AF_INET, "127.0.0.1", &serv_addr.2)
let len = MemoryLayout.stride(ofValue: serv_addr)
let rc = withUnsafePointer(to: &serv_addr) { ptr -> Int32 in
return ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
bptr in return connect(sock, bptr, socklen_t(len))
}
}
if rc == 0 {
msg.withCString { (cstr: UnsafePointer<Int8>) -> Void in
send(sock, cstr, Int(strlen(cstr)), 0)
close(sock)
}
}
}
2 changes: 1 addition & 1 deletion common/commands.mk
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ NIM_CLANG_BUILD = nim c -o:$@ --cc:clang $(NIM_FLAGS) $^
NIM_GCC_BUILD = nim c -o:$@ --cc:gcc $(NIM_FLAGS) $^
RUSTC_BUILD = rustc $(RUSTC_FLAGS) -C lto -C codegen-units=1 -o $@ $^
RUST_CLIPPY = clippy-driver -o [email protected] $^
SWIFTC_BUILD = swiftc -parse-as-library -Ounchecked -cross-module-optimization -o $@ $^
SCALAC_BUILD = scalac -d $@ $^
VALAC_CLANG_BUILD = valac $^ --cc=clang -D CLANG_TEST $(VALAC_FLAGS) -o $@
VALAC_GCC_BUILD = valac $^ --cc=gcc -D GCC_TEST $(VALAC_FLAGS) -o $@
Expand Down Expand Up @@ -67,7 +68,6 @@ RACKET_RUN = PLT_CS_COMPILE_LIMIT=100000 $(XTIME) racket $^
RUBY_JIT_RUN = $(XTIME) ruby --jit $^
RUBY_RUN = $(XTIME) ruby $^
SCALA_RUN = $(XTIME) scala -J-Xss100m -cp $^
SWIFT_RUN = $(XTIME) swift -O $^
TCLSH_RUN = $(XTIME) tclsh $^
TRUBY_JVM_RUN = $(XTIME) truffleruby --jvm $^
TRUBY_NATIVE_RUN = $(XTIME) truffleruby $^
Expand Down
8 changes: 4 additions & 4 deletions matmul/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ executables := \
target/matmul_go_gccgo \
target/matmul_c \
target/matmul_rs \
target/matmul_swift \
target/matmul_d \
target/matmul_d_gdc \
target/matmul_d_ldc \
Expand Down Expand Up @@ -43,7 +44,6 @@ all_runners := $(patsubst %,run[%], $(artifacts)) \
run[matmul-numpy.py] \
run[matmul.pl] \
run[matmul.tcl] \
run[matmul.swift] \
run[matmul.rb] \
run[jit][matmul.rb] \
run[truby-jvm][matmul.rb] \
Expand All @@ -68,6 +68,9 @@ target/matmul_rs: matmul.rs | $(rs_fmt)
$(RUST_CLIPPY)
$(RUSTC_BUILD)

target/matmul_swift: matmul.swift | target
$(SWIFTC_BUILD)

target/matmul_d: matmul.d | $(dfmt)
$(DMD_BUILD)

Expand Down Expand Up @@ -198,9 +201,6 @@ run[matmul.pl]:: run[%]: %
run[matmul.tcl]:: run[%]: %
$(TCLSH_RUN) $(MSIZE)

run[matmul.swift]:: run[%]: %
$(SWIFT_RUN) $(MSIZE)

run[matmul.rb]:: run[%]: % | $(rubocop)
$(RUBY_RUN) $(MSIZE)

Expand Down
34 changes: 20 additions & 14 deletions matmul/matmul.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Written by Kajal Sinha; distributed under the MIT license

import Glibc

func matgen(_ n: Int, _ seed: Double) -> [[Double]] {
Expand All @@ -19,7 +20,9 @@ func matmul(_ a : [[Double]], b : [[Double]]) ->[[Double]] {
let p = b[0].count
var x = Array(repeating: Array<Double>(repeating: 0, count: p), count: m)
var c = Array(repeating: Array<Double>(repeating: 0, count: n), count: p)
for i in 0..<n {// transpose

// Transpose
for i in 0..<n {
for j in 0..<p {
c[j][i] = b[i][j];
}
Expand Down Expand Up @@ -67,19 +70,22 @@ func calc(_ n: Int) -> Double {
return x[size / 2][size / 2]
}

let _ = { () -> () in
let n = CommandLine.argc > 1 ? Int(CommandLine.arguments[1])! : 100
@main
struct Matmul {
static func main() {
let n = CommandLine.argc > 1 ? Int(CommandLine.arguments[1])! : 100

let left = calc(101)
let right = -18.67
if abs(left - right) > 0.1 {
fputs("\(left) != \(right)\n", stderr)
exit(1)
}
let left = calc(101)
let right = -18.67
if abs(left - right) > 0.1 {
fputs("\(left) != \(right)\n", stderr)
exit(EXIT_FAILURE)
}

notify("Swift\t\(getpid())")
let results = calc(n)
notify("stop")
notify("Swift\t\(getpid())")
let results = calc(n)
notify("stop")

print(results)
} ()
print(results)
}
}