Skip to content

Commit

Permalink
Changed c_bindings module to std::clib
Browse files Browse the repository at this point in the history
  • Loading branch information
mauro-balades committed Jan 25, 2024
1 parent 7a3d251 commit 4dd4f43
Show file tree
Hide file tree
Showing 13 changed files with 70 additions and 67 deletions.
3 changes: 3 additions & 0 deletions src/visitors/transform/utils/createModuleAliases.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ void Transformer::createModuleAliases(std::shared_ptr<ir::Module> mod, Statement
auto moduleIndex = N<Expression::Index>(baseIdentifier, aliasIdentifier, true);
moduleIndex->setDBGInfo(import->getDBGInfo());
auto item = std::make_shared<transform::Item>(moduleIndex);
if (ctx->getItem(identifier).second) {
E<VARIABLE_ERROR>(import, "Variable with name '" + identifier + "' already exists");
}
ctx->addItem(identifier, item);
}
}
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions stdlib/env.sn
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std::c_bindings;
import std::clib;
import std::ptr;
import std::map::{Map};
import std::opt::{Option};
Expand All @@ -13,7 +13,7 @@ import std::asserts;
*/
public func posix_get_error_msg(code: i32) String {
unsafe {
let err = c_bindings::strerror(code);
let err = clib::strerror(code);
return String::from_cstr(err);
}
}
Expand Down
26 changes: 13 additions & 13 deletions stdlib/fs/file.sn
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std::fs::path;
import std::c_bindings;
import std::clib;
import std::env;
import std::ptr;

Expand Down Expand Up @@ -76,9 +76,9 @@ public class File implements ToString, Debug {
}
// safety: we are using the C bindings, so we need to be careful.
unsafe {
let cfile = c_bindings::files::fopen(self.path.to_string().c_str(), mode.c_str());
let cfile = clib::files::fopen(self.path.to_string().c_str(), mode.c_str());
if cfile.is_null() {
throw new FileOpenError("Failed to open or create file (" + self.path.to_string() + "): " + env::posix_get_error_msg(c_bindings::errno()));
throw new FileOpenError("Failed to open or create file (" + self.path.to_string() + "): " + env::posix_get_error_msg(clib::errno()));
}
self.open = true;
self.file = cfile;
Expand All @@ -96,9 +96,9 @@ public class File implements ToString, Debug {
}
// safety: we are using the C bindings, so we need to be careful.
unsafe {
let result = c_bindings::files::fclose(self.file);
let result = clib::files::fclose(self.file);
if result != 0 {
throw new FileOpenError("Failed to close file (" + self.path.to_string() + "): " + env::posix_get_error_msg(c_bindings::errno()));
throw new FileOpenError("Failed to close file (" + self.path.to_string() + "): " + env::posix_get_error_msg(clib::errno()));
}
self.open = false;
self.file = zero_initialized!(:*const void);
Expand All @@ -113,14 +113,14 @@ public class File implements ToString, Debug {
self.assert_open();
// safety: we are using the C bindings, so we need to be careful.
unsafe {
c_bindings::files::fseek(self.file, 0, /*SEEK_END*/2);
let size = c_bindings::files::ftell(self.file);
c_bindings::files::fseek(self.file, 0, /*SEEK_SET*/0);
clib::files::fseek(self.file, 0, /*SEEK_END*/2);
let size = clib::files::ftell(self.file);
clib::files::fseek(self.file, 0, /*SEEK_SET*/0);
unsafe {
let data = c_bindings::malloc(16*size);
let result = c_bindings::files::fread(data, 1, size, self.file);
let data = clib::malloc(16*size);
let result = clib::files::fread(data, 1, size, self.file);
if result != size {
throw new FileOpenError("Failed to read from file (" + self.path.to_string() + "): " + env::posix_get_error_msg(c_bindings::errno()));
throw new FileOpenError("Failed to read from file (" + self.path.to_string() + "): " + env::posix_get_error_msg(clib::errno()));
}
let str = String::from(data, result);
//ptr::Allocator<?u8>::free(data);
Expand All @@ -137,9 +137,9 @@ public class File implements ToString, Debug {
self.assert_open();
// safety: we are using the C bindings, so we need to be careful.
unsafe {
let result = c_bindings::files::fwrite(data.c_str(), 1, data.size(), self.file);
let result = clib::files::fwrite(data.c_str(), 1, data.size(), self.file);
if result != data.size() {
throw new FileOpenError("Failed to write to file (" + self.path.to_string() + "): " + env::posix_get_error_msg(c_bindings::errno()));
throw new FileOpenError("Failed to write to file (" + self.path.to_string() + "): " + env::posix_get_error_msg(clib::errno()));
}
}
return true;
Expand Down
8 changes: 4 additions & 4 deletions stdlib/fs/path.sn
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std::env;
import std::c_bindings;
import std::clib;

@cfg(target_os="windows")
@export
Expand Down Expand Up @@ -167,9 +167,9 @@ public class Path implements ToString, Iterable<String> {
}
let path = (#PATH_SEPARATOR).join(copy);
unsafe {
let err = c_bindings::files::remove(path.c_str());
let err = clib::files::remove(path.c_str());
if err != 0 {
throw new PathError("Coudn't remove path (" + path + "): " + env::posix_get_error_msg(c_bindings::errno()));
throw new PathError("Coudn't remove path (" + path + "): " + env::posix_get_error_msg(clib::errno()));
}
}
return true;
Expand Down Expand Up @@ -197,7 +197,7 @@ public class Path implements ToString, Iterable<String> {
}
let path = (#PATH_SEPARATOR).join(copy);
unsafe {
let err = c_bindings::files::access(path.c_str(), 0);
let err = clib::files::access(path.c_str(), 0);
return err == 0;
}
}
Expand Down
8 changes: 4 additions & 4 deletions stdlib/io.sn
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std::c_bindings;
import std::clib;

/**
* @brief Causes the program to terminate with the specified exit code.
Expand All @@ -8,7 +8,7 @@ import std::c_bindings;
*/
public static func exit(exitCode: i32 = 0) {
// TODO: make it diverge
unsafe { c_bindings::exit(exitCode); }
unsafe { clib::exit(exitCode); }
}
/**
* @brief Prints `msg` to standard output.
Expand All @@ -20,7 +20,7 @@ public static func exit(exitCode: i32 = 0) {
public static func print<T: ToString>(msg: T, end: String = "") i32 {
let m = String::from(msg);
for i in 0..m.size() {
unsafe {c_bindings::putchar(m[i]);}
unsafe {clib::putchar(m[i]);}
}
if end.size() > 0 { return print(end); }
return 0;
Expand All @@ -45,6 +45,6 @@ public static func println<T: ToString>(msg: T) i32 {
* If you need to print additional characters or a string, use the `println(...)` function instead.
*/
@inline
public static func println() { unsafe { c_bindings::putchar('\n'); } }
public static func println() { unsafe { clib::putchar('\n'); } }


2 changes: 1 addition & 1 deletion stdlib/math.sn
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std::c_bindings;
import std::clib;
import std::ptr;
/**
* @brief It performs the square root of a given floating-point number.
Expand Down
10 changes: 5 additions & 5 deletions stdlib/ptr.sn
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import std::c_bindings;
import std::clib;
import std::intrinsics;

/**
Expand Down Expand Up @@ -73,7 +73,7 @@ public class Allocator<T: Sized> {
@inline
static func alloc(size: i32) NonNull<T> {
unsafe {
return new NonNull<T>(c_bindings::malloc(Self::size_of<?T>(size)));
return new NonNull<T>(clib::malloc(Self::size_of<?T>(size)));
}
}
/**
Expand All @@ -84,7 +84,7 @@ public class Allocator<T: Sized> {
@inline
static func alloc_zeroed(size: i32) NonNull<T> {
unsafe {
return new NonNull<T>(c_bindings::calloc(Self::size_of<?T>(size), 0));
return new NonNull<T>(clib::calloc(Self::size_of<?T>(size), 0));
}
}
/**
Expand All @@ -96,7 +96,7 @@ public class Allocator<T: Sized> {
@inline
static func realloc(ptr: NonNull<T>, size: i32) NonNull<T> {
unsafe {
return new NonNull<T>(c_bindings::realloc(ptr.ptr(), Self::size_of<?T>(size)));
return new NonNull<T>(clib::realloc(ptr.ptr(), Self::size_of<?T>(size)));
}
}
/**
Expand All @@ -105,7 +105,7 @@ public class Allocator<T: Sized> {
*/
@inline
static func free(ptr: NonNull<T>) {
unsafe { c_bindings::free(ptr.ptr()); }
unsafe { clib::free(ptr.ptr()); }
}
/**
* @brief It calculates the size of a memory block.
Expand Down
4 changes: 2 additions & 2 deletions stdlib/rand.sn
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

import std::ptr;
import std::c_bindings;
import std::time::{clock};

/**
* @brief A class representing a generic random number generator.
Expand Down Expand Up @@ -43,7 +43,7 @@ public: DefaultRNG() : super() {}
// We use the linear congruential generator (LCG) algorithm.
if self.seed == 0 {
unsafe {
self.seed = c_bindings::time(ptr::null_ptr<?i32>()) as u64;
self.seed = clock();
}
}
// LCG algorithm for generating random unsigned 64-bit integers.
Expand Down
42 changes: 21 additions & 21 deletions stdlib/std.sn
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import std::internal::preload;
import std::c_bindings;
import std::clib;
import std::ptr;
import std::intrinsics;

Expand Down Expand Up @@ -931,7 +931,7 @@ public class StringView<Char: Sized = u8> implements ToString, Clone<Self> {
if buffer.is_null() {
return "";
}
return new Self(buffer, c_bindings::c_string::strlen(buffer));
return new Self(buffer, clib::c_string::strlen(buffer));
}

// Internal exports
Expand All @@ -949,7 +949,7 @@ public class StringView<Char: Sized = u8> implements ToString, Clone<Self> {
// safety: we make sure the buffer is not null.
unsafe {
let sum = len1 + len2;
let buffer = c_bindings::malloc(sum) as StringType;
let buffer = clib::malloc(sum) as StringType;
intrinsics::memcpy(buffer, str1, len1);
intrinsics::memcpy(buffer + len1, str2, len2);
return buffer;
Expand All @@ -968,7 +968,7 @@ public class StringView<Char: Sized = u8> implements ToString, Clone<Self> {
}
// safety: we make sure the buffer is not null.
unsafe {
self.buffer = c_bindings::malloc(length) as StringType;
self.buffer = clib::malloc(length) as StringType;
ptr::copy_nonoverlapping(buffer, self.buffer, length);
}
}
Expand Down Expand Up @@ -1019,7 +1019,7 @@ static unsafe func execute_tests(
// note: This depends on the total number of tests, so we make sure we don't overflow.
let indexStr = index.to_string().rjust(total.to_string().size(), '0').c_str();
// safety: we use printf here, so we make sure the name is null-terminated.
c_bindings::printf(b" Testing \e[1m%-44s\e[0m [(%s\e[0;30m/%i\e[0m) %s]\t... ", name, indexStr, total, expectStr);
clib::printf(b" Testing \e[1m%-44s\e[0m [(%s\e[0;30m/%i\e[0m) %s]\t... ", name, indexStr, total, expectStr);
if !skip {
try {
// note: The compiler makes sure the function is not null and that it follows the correct signature.
Expand All @@ -1029,16 +1029,16 @@ static unsafe func execute_tests(
// We check if the result is equal to the expected result.
if result == expect {
// If the result is equal to the expected result, we print "nice!".
c_bindings::printf(b"\e[1;32mnice!\e[0m\n");
clib::printf(b"\e[1;32mnice!\e[0m\n");
} else {
// If the result is not equal to the expected result, we print "error".
// we also print the expected result and the actual result. Again, we use
// printf, so we make sure the expected result is null-terminated.
// There hasn't been a case where the expected result is not null-terminated,
// but we make sure just in case.
c_bindings::printf(b"\e[1;31merror \n");
c_bindings::printf(b"\n\tExpected result\e[0m: \e[1;32m%i\e[1;31m\n", expect);
c_bindings::printf(b"\tActual result\e[0m: \e[1;31m%i\e[0m\n\n", result);
clib::printf(b"\e[1;31merror \n");
clib::printf(b"\n\tExpected result\e[0m: \e[1;32m%i\e[1;31m\n", expect);
clib::printf(b"\tActual result\e[0m: \e[1;31m%i\e[0m\n\n", result);
// We return 0 to indicate that the test failed. We don't return 1 because
// that's just not how the compiler will handle it. The compiler will return
// 1 if the test succeeds, and 0 if it fails. So we return 0 if the test fails.
Expand All @@ -1047,14 +1047,14 @@ static unsafe func execute_tests(
} catch (e: Exception) {
// We catch any exceptions thrown by the test and print "error".
// We also print the exception message.
c_bindings::printf(b"\e[1;31merror \n");
c_bindings::printf(b"\n ------- %s failure -------\n", name);
c_bindings::printf(b"\n Failed with: \e[1m%s\e[0m\n", e.what().c_str());
c_bindings::printf(b"\e[0m\n");
clib::printf(b"\e[1;31merror \n");
clib::printf(b"\n ------- %s failure -------\n", name);
clib::printf(b"\n Failed with: \e[1m%s\e[0m\n", e.what().c_str());
clib::printf(b"\e[0m\n");
return false;
}
} else {
c_bindings::printf(b"\e[1;33mwip\e[0m\n");
clib::printf(b"\e[1;33mwip\e[0m\n");
}
// We return 1 to indicate that the test succeeded.
return true;
Expand All @@ -1073,9 +1073,9 @@ func snowball_bench(
for i in 0..size {
unsafe {
let fn = functions[i] as *const void as func () => i32;
let start = c_bindings::time(ptr::null_ptr<?i32>());
let start = clib::time(ptr::null_ptr<?i32>());
fn();
let end = c_bindings::time(ptr::null_ptr<?i32>());
let end = clib::time(ptr::null_ptr<?i32>());
// unix time to ms
let result = (end - start) * 1000;
results.push(result);
Expand Down Expand Up @@ -1112,7 +1112,7 @@ func snowball_bench(
divider = 1000;
}
unsafe {
c_bindings::printf(b" \e[1m%s\e[0m: %s%i%s\e[0m\n", name, color.c_str(), result / divider, unit.c_str());
clib::printf(b" \e[1m%s\e[0m: %s%i%s\e[0m\n", name, color.c_str(), result / divider, unit.c_str());
}
}
Expand All @@ -1121,26 +1121,26 @@ func snowball_bench(
let mut divider = 1;
unsafe {
c_bindings::printf(b"\n\e[1mBenchmark results:\e[0m\n");
clib::printf(b"\n\e[1mBenchmark results:\e[0m\n");
if min >= 1000 {
unit = "s";
divider = 1000;
min = min / divider;
}
c_bindings::printf(b" \e[1;32mmin\e[0m: \e[1m%d%s\e[0m\n", min, unit.c_str());
clib::printf(b" \e[1;32mmin\e[0m: \e[1m%d%s\e[0m\n", min, unit.c_str());
if max >= 1000 {
unit = "s";
divider = 1000;
max = max / divider;
} else unit = "ms";
c_bindings::printf(b" \e[1;31mmax\e[0m: \e[1m%d%s\e[0m\n", max, unit.c_str());
clib::printf(b" \e[1;31mmax\e[0m: \e[1m%d%s\e[0m\n", max, unit.c_str());
if avg >= 1000.0 {
unit = "s";
divider = 1000;
avg = avg;
} else unit = "ms";
// TODO:
// c_bindings::printf(b" \e[1mavg\e[0m: \e[1m%d%s\e[0m\n", avg, unit.c_str());
// clib::printf(b" \e[1mavg\e[0m: \e[1m%d%s\e[0m\n", avg, unit.c_str());
}
}
Expand Down
6 changes: 3 additions & 3 deletions stdlib/time.sn
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@

import std::ptr;
import std::c_bindings;
import std::clib;

/**
* @brief It returns the current time of the system as the number of seconds
* since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
* @return The current time of the system as the number of seconds since the
*/
@inline
public func time() i64 {
public func clock() u64 {
unsafe {
return c_bindings::time(ptr::null_ptr<?i32>()) as i64;
return clib::time(ptr::null_ptr<?i32>()) as u64;
}
}
Loading

0 comments on commit 4dd4f43

Please sign in to comment.