1
1
Fork 0
mirror of https://github.com/azur1s/bobbylisp.git synced 2024-10-16 02:37:40 -05:00

read and write file

This commit is contained in:
Natapat Samutpong 2022-03-13 07:17:12 +07:00
parent 5754ecf641
commit d211a05fd0
4 changed files with 41 additions and 2 deletions

View file

@ -64,7 +64,9 @@ impl Codegen {
IRKind::Intrinsic { name, args } => {
match name.as_str() {
"write" => { format!("hazure_write({}){}\n", self.gen_ir(&args[0], false), semicolon!()) },
"read" => { format!("hazure_read(){}\n", semicolon!()) },
"read" => { format!("hazure_read(){}\n", semicolon!()) },
"write_file" => { format!("hazure_write({}){}\n", self.gen_ir(&args[0], false), semicolon!()) },
"read_file" => { format!("hazure_read_file({}){}\n", self.gen_ir(&args[0], false), semicolon!()) },
"time" => { format!("hazure_get_time(){}\n", semicolon!()) },
_ => unreachable!(format!("Unknown intrinsic: {}", name)) // Shoul be handled by lowering
}

View file

@ -1,9 +1,11 @@
use std::ops::Range;
use parser::Expr;
const INTRINSICS: [&str; 3] = [
const INTRINSICS: [&str; 5] = [
"write",
"read",
"write_file",
"read_file",
"time",
];

4
example/quine.hz Normal file
View file

@ -0,0 +1,4 @@
fun main: int = do
@read_file("./example/quine.hz") -- Run this from root folder
|> @write();
end;

View file

@ -1,5 +1,7 @@
#pragma once
#include <iostream>
#include <fstream>
#include <string>
template<typename T>
/**
@ -19,4 +21,33 @@ template<typename T>
*/
void hazure_write(T x) {
std::cout << x;
}
/*
* @brief Read the value from the file and return it.
*
* @param file_name The name of the file to read from.
* @return std::string The value read from the file.
*/
std::string hazure_read_file(std::string filename) {
std::ifstream file(filename);
std::string content((std::istreambuf_iterator<char>(file)),
(std::istreambuf_iterator<char>()));
return content;
}
/*
* @brief Write string to file.
*
* @param filename The file name to write to.
* @param content The content to write.
*/
void hazure_write_file(std::string filename, std::string content) {
std::ofstream file(filename);
if (file.is_open()) {
file << content;
file.close();
} else {
std::cerr << "Unable to open " << filename << std::endl;
}
}