Extend the tester to compile sources

This commit is contained in:
Eugen Wissner 2024-02-25 15:16:19 +01:00
parent ad29dbdc14
commit 03a72fc583
Signed by: belka
GPG Key ID: A27FDC1E8EE902C0
40 changed files with 3473 additions and 104 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
.cache/
CMakeFiles/
CMakeCache.txt
dub.selections.json

View File

@ -3,8 +3,7 @@ project(Elna)
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
find_package(Boost COMPONENTS filesystem REQUIRED)
set(CMAKE_CXX_STANDARD 17)
add_executable(tester tests/runner.cpp include/elna/tester.hpp)
target_include_directories(tester PRIVATE include)
@ -13,9 +12,11 @@ add_executable(elnsh shell/main.cpp
shell/interactive.cpp include/elna/interactive.hpp
shell/history.cpp include/elna/history.hpp
shell/state.cpp include/elna/state.hpp
shell/lexer.cpp include/elna/lexer.hpp
shell/result.cpp include/elna/result.hpp)
target_include_directories(elnsh PRIVATE include)
target_link_libraries(elnsh PUBLIC
${Boost_FILESYSTEM_LIBRARY}
shell/result.cpp include/elna/result.hpp
)
target_include_directories(elnsh PRIVATE include)
add_library(elna
source/lexer.cpp include/elna/lexer.hpp
)
target_include_directories(elna PRIVATE include)

37
README Normal file
View File

@ -0,0 +1,37 @@
# Elna programming language
Elna compiles simple mathematical operations to machine code.
The compiled program returns the result of the operation.
## File extension
.elna
## Grammar PL/0
program = block "." ;
block = [ "const" ident "=" number {"," ident "=" number} ";"]
[ "var" ident {"," ident} ";"]
{ "procedure" ident ";" block ";" } statement ;
statement = [ ident ":=" expression | "call" ident
| "?" ident | "!" expression
| "begin" statement {";" statement } "end"
| "if" condition "then" statement
| "while" condition "do" statement ];
condition = "odd" expression |
expression ("="|"#"|"<"|"<="|">"|">=") expression ;
expression = [ "+"|"-"] term { ("+"|"-") term};
term = factor {("*"|"/") factor};
factor = ident | number | "(" expression ")";
## Operations
"!" - Write a line.
"?" - Read user input.
"odd" - The only function, returns whether a number is odd.

90
Rakefile Normal file
View File

@ -0,0 +1,90 @@
require 'pathname'
require 'rake/clean'
require 'open3'
DFLAGS = ['--warn-no-deprecated', '-L/usr/lib64/gcc-12']
BINARY = 'build/bin/elna'
TESTS = FileList['tests/*.eln'].flat_map do |test|
build = Pathname.new 'build'
test_basename = Pathname.new(test).basename('')
[build + 'riscv' + test_basename].map { |path| path.sub_ext('').to_path }
end
SOURCES = FileList['source/**/*.d']
directory 'build'
CLEAN.include 'build'
CLEAN.include '.dub'
rule(/build\/riscv\/[^\/\.]+$/ => ->(file) { test_for_out(file, '.o') }) do |t|
sh '/opt/riscv/bin/riscv32-unknown-elf-ld',
'-o', t.name,
'-L/opt/riscv/lib/gcc/riscv32-unknown-elf/13.2.0/',
'-L/opt/riscv/riscv32-unknown-elf/lib',
'/opt/riscv/riscv32-unknown-elf/lib/crt0.o',
'/opt/riscv/lib/gcc/riscv32-unknown-elf/13.2.0/crtbegin.o',
t.source,
'--start-group', '-lgcc', '-lc', '-lgloss', '--end-group',
'/opt/riscv/lib/gcc/riscv32-unknown-elf/13.2.0/crtend.o'
end
rule(/build\/riscv\/.+\.o$/ => ->(file) { test_for_object(file, '.eln') }) do |t|
Pathname.new(t.name).dirname.mkpath
sh BINARY, '-o', t.name, t.source
end
file BINARY => SOURCES do |t|
sh({ 'DFLAGS' => (DFLAGS * ' ') }, 'dub', 'build', '--compiler=gdc')
end
task default: BINARY
desc 'Run all tests and check the results'
task test: TESTS
task test: BINARY do
TESTS.each do |test|
expected = Pathname
.new(test)
.sub_ext('.txt')
.sub(/^build\/[[:alpha:]]+\//, 'tests/expectations/')
.to_path
puts "Running #{test}"
if test.include? '/riscv/'
spike = [
'/opt/riscv/bin/spike',
'--isa=RV32IMAC',
'/opt/riscv/riscv32-unknown-elf/bin/pk',
test
]
diff = ['diff', '-Nur', '--color', expected, '-']
tail = ['tail', '-n', '1']
last_stdout, wait_threads = Open3.pipeline_r spike, tail, diff
else
raise 'Unsupported test platform'
end
print last_stdout.read
last_stdout.close
fail unless wait_threads.last.value.exitstatus.zero?
end
end
def test_for_object(out_file, extension)
test_source = Pathname
.new(out_file)
.sub_ext(extension)
.sub(/^build\/[[:alpha:]]+\//, 'tests/')
.to_path
[test_source, BINARY]
end
def test_for_out(out_file, extension)
Pathname
.new(out_file)
.sub_ext(extension)
.to_path
end

30
TODO
View File

@ -1,15 +1,23 @@
- After inserting autocompletion move the cursor to the end of the insertion.
# Completion
- Configure fzf to show only the current directory files
- Support multiple selections for insertion in fzf.
- Vi mode.
- Don't hardcode fzf binary path.
- Persist the history.
- Send the word under the cursor to fzf as initial input.
- Replace hard coded ANSI codes with constants or functions.
- Show the hostname in the prompt.
- Crash if the cd directory doesn't exist.
- Home directory expansion.
- Paste pastes only the first character.
- When we read the key and an error occures how it should be handled?
- Kitty protocol works with UTF8 code points for escape sequences with modifiers.
They can be wider than an unsigned char.
- Add a bar with additional information under the prompt (edit_bar).
- Show files in the PATH if starting at the beginning of the prompt
# Appearance
- Add a bar with additional information under the prompt (edit_bar), like the hostname.
- Show current time in the prompt.
# Input
- DEL handling.
- Starting long running process and killing it with Ctrl-C kills the shell.
# Other
- Persist the history.
- Replace hard coded ANSI codes with constants or functions.

9
dub.json Normal file
View File

@ -0,0 +1,9 @@
{
"dependencies": {
"tanya": "~>0.19.0"
},
"name": "elna",
"targetType": "executable",
"targetPath": "build/bin",
"mainSourceFile": "source/main.d"
}

View File

@ -5,10 +5,11 @@
#include <string>
#include <optional>
#include "elna/lexer.hpp"
#include "elna/state.hpp"
#include "elna/history.hpp"
#define BOOST_PROCESS_USE_STD_FS
namespace elna
{
/**
@ -42,15 +43,14 @@ namespace elna
* \param line The command and arguments.
* \return Whether the input shoud continued (no exit requested).
*/
bool execute(const std::vector<token>& line);
bool execute(const std::string& line);
/**
* Runs the binary specified in its argument.
*
* \param program Program name in PATH.
* \param arguments Command arguments.
*/
void launch(const std::string& program, const std::vector<std::string>& arguments);
void launch(const std::string& program);
/**
* Enables the raw mode.
@ -74,7 +74,16 @@ namespace elna
/**
* Calls autocompletion.
*
* \param User input.
* \param Cursor position in the user input.
* \return Selected item.
*/
std::string complete();
std::string complete(const std::string& input, const std::size_t position);
/**
* Prints the message from the exception.
*
* \param exception The exception to print.
*/
void print_exception(const std::exception& exception);
}

View File

@ -14,9 +14,10 @@ namespace elna
class const_iterator
{
std::string::const_iterator m_buffer;
Position m_position;
source_position m_position;
const_iterator(std::string::const_iterator buffer, const Position& position);
const_iterator(std::string::const_iterator buffer,
const source_position position = source_position());
public:
using iterator_category = std::forward_iterator_tag;
@ -25,7 +26,7 @@ namespace elna
using pointer = const value_type *;
using reference = const value_type&;
const Position& position() const noexcept;
const source_position& position() const noexcept;
reference operator*() const noexcept;
pointer operator->() const noexcept;
@ -68,11 +69,11 @@ namespace elna
type of() const noexcept;
const value& identifier() const noexcept;
const Position& position() const noexcept;
const source_position& position() const noexcept;
private:
std::string m_value;
Position m_position;
source_position m_position;
type m_type;
};

View File

@ -8,7 +8,7 @@ namespace elna
/**
* Position in the source text.
*/
struct Position
struct source_position
{
/// Line.
std::size_t line = 1;
@ -20,21 +20,21 @@ namespace elna
/**
* A compilation error consists of an error message and position.
*/
struct CompileError
struct compile_error
{
private:
char const *message_;
Position position_;
char const *message;
source_position position;
public:
/**
* @param message Error text.
* @param position Error position in the source text.
*/
CompileError(char const *message, Position position) noexcept;
compile_error(char const *message, const source_position position) noexcept;
/// Error text.
char const *message() const noexcept;
const char *what() const noexcept;
/// Error line in the source text.
std::size_t line() const noexcept;
@ -44,5 +44,5 @@ namespace elna
};
template<typename T>
using result = boost::outcome_v2::result<T, CompileError>;
using result = boost::outcome_v2::result<T, compile_error>;
}

View File

@ -38,30 +38,28 @@ namespace elna
num_lock = 0b10000000, ///< 128
};
class key
struct key
{
std::variant<special_key, unsigned char> store;
std::uint8_t modifiers;
using char_t = std::uint32_t;
public:
key();
explicit key(const unsigned char c, const std::uint8_t modifiers = 0);
explicit key(const unsigned char c, const modifier modifiers);
explicit key(const char_t c, const std::uint8_t modifiers = 0);
explicit key(const char_t c, const modifier modifiers);
explicit key(const special_key control, const std::uint8_t modifiers = 0);
explicit key(const special_key control, const modifier modifiers);
bool operator==(const unsigned char c) const;
friend bool operator==(const unsigned char c, const key& that);
bool operator==(const char_t c) const;
friend bool operator==(const char_t c, const key& that);
bool operator==(const special_key control) const;
friend bool operator==(const special_key control, const key& that);
bool operator==(const key& that) const;
bool operator!=(const unsigned char c) const;
friend bool operator!=(const unsigned char c, const key& that);
bool operator!=(const char_t c) const;
friend bool operator!=(const char_t c, const key& that);
bool operator!=(const special_key control) const;
friend bool operator!=(const special_key control, const key& that);
bool operator!=(const key& that) const;
unsigned char character() const;
char_t character() const;
special_key control() const;
bool modified(const std::uint8_t modifiers) const noexcept;
bool modified(const modifier modifiers) const noexcept;
@ -69,6 +67,10 @@ namespace elna
bool is_character() const noexcept;
bool is_control() const noexcept;
bool empty() const noexcept;
private:
std::variant<special_key, char_t> store;
std::uint8_t modifiers;
};
/**
@ -143,12 +145,20 @@ namespace elna
*/
std::size_t absolute_position() const noexcept;
/**
* Cursor position relative to the start of the user input.
*
* \returns Cursor position.
*/
std::size_t relative_position() const noexcept;
/**
* Inserts text at cursor position.
*
* \param text Text to insert.
*/
void insert(const std::string& text);
void insert(const key::char_t text);
/**
* Replaces the user input with the given string.

View File

@ -9,8 +9,8 @@ namespace elna
void editor_history::push(const std::string& entry)
{
commands.push_front(entry);
current_pointer = commands.cbegin();
commands.push_back(entry);
current_pointer = commands.cend();
}
void editor_history::clear()
@ -46,4 +46,9 @@ namespace elna
{
return this->commands.cend();
}
editor_history::const_iterator editor_history::current() const noexcept
{
return this->current_pointer;
}
}

View File

@ -1,9 +1,10 @@
#include "elna/interactive.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/process.hpp>
#include <termios.h>
#include <filesystem>
#include "elna/interactive.hpp"
namespace elna
{
static termios original_termios;
@ -39,9 +40,8 @@ namespace elna
break;
}
history.push(line.value().command_line());
auto tokens = lex(line.value().command_line());
if (!execute(tokens.assume_value()))
if (!execute(line.value().command_line()))
{
break;
}
@ -53,6 +53,7 @@ namespace elna
{
editor_state state;
std::string buffer;
std::string saved;
state.draw(std::back_inserter(buffer));
write(STDOUT_FILENO, buffer.data(), buffer.size());
@ -81,7 +82,7 @@ namespace elna
break;
case action::complete:
write(STDOUT_FILENO, "\x1b[1E\x1b[2K", 8);
state.insert(complete());
state.insert(complete(state.command_line(), state.relative_position()));
write(STDOUT_FILENO, "\x1b[1A", 4);
state.draw(std::back_inserter(buffer));
write(STDOUT_FILENO, buffer.data(), buffer.size());
@ -104,18 +105,26 @@ namespace elna
if (pressed_key == key(special_key::arrow_up, modifier::ctrl))
{
history_iterator = history.next();
if (history.current() == history.cend())
{
saved = state.command_line();
}
history_iterator = history.prev();
}
else if (pressed_key == key(special_key::arrow_down, modifier::ctrl))
{
history_iterator = history.prev();
history_iterator = history.next();
if (history_iterator == history.cend())
{
state.load(saved);
}
}
if (history_iterator != history.cend())
{
state.load(*history_iterator);
state.draw(std::back_inserter(buffer));
write(STDOUT_FILENO, buffer.data(), buffer.size());
}
state.draw(std::back_inserter(buffer));
write(STDOUT_FILENO, buffer.data(), buffer.size());
break;
}
}
@ -137,7 +146,7 @@ namespace elna
{
return key();
}
auto [number, last_char] = read_number<unsigned char>();
auto [number, last_char] = read_number<key::char_t>();
std::uint8_t modifiers{ 0 };
if (last_char == ';')
@ -185,35 +194,51 @@ namespace elna
return key();
}
bool execute(const std::vector<token>& tokens)
void print_exception(const std::exception& exception)
{
if (tokens.empty())
std::string message{ exception.what() };
message += "\r\n";
write(STDERR_FILENO, message.data(), message.size());
}
bool execute(const std::string& line)
{
if (line.empty())
{
return true;
}
std::string program = tokens.front().identifier();
if (program == "exit")
if (line == "exit")
{
return false;
}
else if (program == "cd")
else if (boost::starts_with(line, "cd "))
{
std::filesystem::current_path(tokens[1].identifier());
try
{
std::filesystem::current_path(line.substr(strlen("cd ")));
}
catch (const std::filesystem::filesystem_error& exception)
{
print_exception(exception);
}
return true;
}
std::vector<std::string> arguments;
for (auto argument = tokens.cbegin() + 1; argument != std::cend(tokens); ++argument)
{
arguments.push_back(argument->identifier());
}
launch(program, arguments);
launch(line);
return true;
}
void launch(const std::string& program, const std::vector<std::string>& arguments)
void launch(const std::string& program)
{
boost::process::system(boost::process::search_path(program), arguments);
try
{
boost::process::system(program);
}
catch (const boost::process::process_error& exception)
{
print_exception(exception);
}
enable_raw_mode();
}
bool enable_raw_mode()
@ -240,10 +265,17 @@ namespace elna
tcsetattr(STDIN_FILENO, TCSAFLUSH, &original_termios);
}
std::string complete()
std::string complete(const std::string& input, const std::size_t position)
{
std::filesystem::path program = boost::process::search_path("fzf");
if (program.empty())
{
return "";
}
boost::process::ipstream output;
boost::process::system("/usr/bin/fzf", "--height=10", "--layout=reverse",
boost::process::system(program,
"--height=10", "--layout=reverse", "-1", "--no-multi",
boost::process::std_out > output);
std::string selections;

View File

@ -2,24 +2,24 @@
namespace elna
{
CompileError::CompileError(char const *message, Position position) noexcept
compile_error::compile_error(const char *message, const source_position position) noexcept
{
this->message_ = message;
this->position_ = position;
this->message = message;
this->position = position;
}
char const *CompileError::message() const noexcept
char const *compile_error::what() const noexcept
{
return this->message_;
return this->message;
}
std::size_t CompileError::line() const noexcept
std::size_t compile_error::line() const noexcept
{
return this->position_.line;
return this->position.line;
}
std::size_t CompileError::column() const noexcept
std::size_t compile_error::column() const noexcept
{
return this->position_.column;
return this->position.column;
}
}

View File

@ -1,3 +1,6 @@
#include <algorithm>
#include <boost/endian.hpp>
#include "elna/state.hpp"
namespace elna
@ -12,16 +15,16 @@ namespace elna
}
key::key()
: store(static_cast<unsigned char>(0x1b))
: store(0x1bu)
{
}
key::key(const unsigned char c, const std::uint8_t modifiers)
key::key(const char_t c, const std::uint8_t modifiers)
: store(c), modifiers(modifiers == 0 ? 0 : modifiers - 1)
{
}
key::key(const unsigned char c, const modifier modifiers)
key::key(const char_t c, const modifier modifiers)
: store(c), modifiers(static_cast<uint8_t>(modifiers))
{
}
@ -36,9 +39,9 @@ namespace elna
{
}
unsigned char key::character() const
key::char_t key::character() const
{
return std::get<unsigned char>(this->store);
return std::get<char_t>(this->store);
}
special_key key::control() const
@ -56,10 +59,10 @@ namespace elna
return this->modifiers == static_cast<std::uint8_t>(modifiers);
}
bool key::operator==(const unsigned char c) const
bool key::operator==(const char_t c) const
{
return std::holds_alternative<unsigned char>(this->store)
&& std::get<unsigned char>(this->store) == c;
return std::holds_alternative<char_t>(this->store)
&& std::get<char_t>(this->store) == c;
}
bool key::operator==(const special_key control) const
@ -73,7 +76,7 @@ namespace elna
return this->store == that.store;
}
bool key::operator!=(const unsigned char c) const
bool key::operator!=(const char_t c) const
{
return !(*this == c);
}
@ -90,7 +93,7 @@ namespace elna
bool key::is_character() const noexcept
{
return std::holds_alternative<unsigned char>(this->store);
return std::holds_alternative<char_t>(this->store);
}
bool key::is_control() const noexcept
@ -131,6 +134,7 @@ namespace elna
void editor_state::load(const std::string& text)
{
this->input = text;
this->position = this->input.size() + 1;
}
const std::string& editor_state::command_line() const noexcept
@ -143,9 +147,36 @@ namespace elna
return this->prompt.size() + this->position;
}
std::size_t editor_state::relative_position() const noexcept
{
return this->position;
}
void editor_state::insert(const std::string& text)
{
this->input.insert(std::end(this->input), std::cbegin(text), std::cend(text));
this->input.insert(this->position - 1, text);
this->position += text.size();
}
void editor_state::insert(const key::char_t text)
{
if (text == 0u)
{
this->input.insert(this->position - 1, '\0', 1);
++this->position;
return;
}
key::char_t buffer = boost::endian::native_to_big<key::char_t>(text);
const char *begin = reinterpret_cast<char *>(&buffer);
const char *end = begin + sizeof(key::char_t);
const char *significant = std::find_if(begin, end,
[](const char byte) {
return byte != 0;
});
this->input.insert(this->position - 1, significant, end - significant);
this->position += end - significant;
}
action editor_state::process_keypress(const key& press)
@ -202,12 +233,21 @@ namespace elna
this->input.erase(this->position - 1, 1);
}
return action::redraw;
case 9: // Tab.
return action::complete;
case '\r':
return action::finalize;
default:
++this->position;
this->input.push_back(press.character());
return action::write;
if (this->position - 1 < input.size())
{
insert(press.character());
return action::redraw;
}
else
{
insert(press.character());
return action::write;
}
}
}
}

154
source/elna/arguments.d Normal file
View File

@ -0,0 +1,154 @@
/**
* Argument parsing.
*/
module elna.arguments;
import std.algorithm;
import std.range;
import std.sumtype;
struct ArgumentError
{
enum Type
{
expectedOutputFile,
noInput,
superfluousArguments,
}
private Type type_;
private string argument_;
@property Type type() const @nogc nothrow pure @safe
{
return this.type_;
}
@property string argument() const @nogc nothrow pure @safe
{
return this.argument_;
}
void toString(OR)(OR range)
if (isOutputRage!OR)
{
final switch (Type)
{
case Type.expectedOutputFile:
put(range, "Expected an output filename after -o");
break;
case Type.noInput:
put(range, "No input files specified");
break;
}
}
}
/**
* Supported compiler arguments.
*/
struct Arguments
{
private bool assembler_;
private string output_;
private string inFile_;
@property string inFile() @nogc nothrow pure @safe
{
return this.inFile_;
}
/**
* Returns: Whether to generate assembly instead of an object file.
*/
@property bool assembler() const @nogc nothrow pure @safe
{
return this.assembler_;
}
/**
* Returns: Output file.
*/
@property string output() const @nogc nothrow pure @safe
{
return this.output_;
}
/**
* Parse command line arguments.
*
* The first argument is expected to be the program name (and it is
* ignored).
*
* Params:
* arguments = Command line arguments.
*
* Returns: Parsed arguments or an error.
*/
static SumType!(ArgumentError, Arguments) parse(string[] arguments)
@nogc nothrow pure @safe
{
if (!arguments.empty)
{
arguments.popFront;
}
alias ReturnType = typeof(return);
return parseArguments(arguments).match!(
(Arguments parsed) {
if (parsed.inFile is null)
{
return ReturnType(ArgumentError(ArgumentError.Type.noInput));
}
else if (!arguments.empty)
{
return ReturnType(ArgumentError(
ArgumentError.Type.superfluousArguments,
arguments.front
));
}
return ReturnType(parsed);
},
(ArgumentError argumentError) => ReturnType(argumentError)
);
}
private static SumType!(ArgumentError, Arguments) parseArguments(ref string[] arguments)
@nogc nothrow pure @safe
{
Arguments parsed;
while (!arguments.empty)
{
if (arguments.front == "-s")
{
parsed.assembler_ = true;
}
else if (arguments.front == "-o")
{
if (arguments.empty)
{
return typeof(return)(ArgumentError(
ArgumentError.Type.expectedOutputFile,
arguments.front
));
}
arguments.popFront;
parsed.output_ = arguments.front;
}
else if (arguments.front == "--")
{
arguments.popFront;
parsed.inFile_ = arguments.front;
arguments.popFront;
break;
}
else if (!arguments.front.startsWith("-"))
{
parsed.inFile_ = arguments.front;
}
arguments.popFront;
}
return typeof(return)(parsed);
}
}

105
source/elna/backend.d Normal file
View File

@ -0,0 +1,105 @@
module elna.backend;
import core.stdc.stdio;
import core.stdc.stdlib;
import elna.elf;
import elna.ir;
import elna.extended;
import elna.riscv;
import elna.lexer;
import elna.parser;
import elna.result;
import std.algorithm;
import std.sumtype;
import std.typecons;
import tanya.os.error;
import tanya.container.array;
import tanya.container.string;
import tanya.memory.allocator;
private Nullable!String readSource(string source) @nogc
{
enum size_t bufferSize = 255;
auto sourceFilename = String(source);
return readFile(sourceFilename).match!(
(ErrorCode errorCode) {
perror(sourceFilename.toStringz);
return Nullable!String();
},
(Array!ubyte contents) => nullable(String(cast(char[]) contents.get))
);
}
int generate(string inFile, ref String outputFilename) @nogc
{
auto sourceText = readSource(inFile);
if (sourceText.isNull)
{
return 3;
}
auto tokens = lex(sourceText.get.get);
if (!tokens.valid)
{
auto compileError = tokens.error.get;
printf("%lu:%lu: %s\n", compileError.line, compileError.column, compileError.message.ptr);
return 1;
}
auto ast = parse(tokens.result);
if (!ast.valid)
{
auto compileError = ast.error.get;
printf("%lu:%lu: %s\n", compileError.line, compileError.column, compileError.message.ptr);
return 2;
}
auto transformVisitor = cast(TransformVisitor) malloc(__traits(classInstanceSize, TransformVisitor));
(cast(void*) transformVisitor)[0 .. __traits(classInstanceSize, TransformVisitor)] = __traits(initSymbol, TransformVisitor)[];
auto ir = transformVisitor.visit(ast.result);
transformVisitor.__xdtor();
free(cast(void*) transformVisitor);
auto handle = File.open(outputFilename.toStringz, BitFlags!(File.Mode)(File.Mode.truncate));
if (!handle.valid)
{
return 1;
}
auto program = writeNext(ir);
auto elf = Elf!ELFCLASS32(move(handle));
auto readOnlyData = Array!ubyte(cast(const(ubyte)[]) "%d\n".ptr[0 .. 4]); // With \0.
elf.addReadOnlyData(String(".CL0"), readOnlyData);
elf.addCode(program.name, program.text);
elf.addExternSymbol(String("printf"));
foreach (ref reference; program.symbols)
{
elf.Rela relocationEntry = {
r_offset: cast(elf.Addr) reference.offset
};
elf.Rela relocationSub = {
r_offset: cast(elf.Addr) reference.offset,
r_info: R_RISCV_RELAX
};
final switch (reference.target)
{
case Reference.Target.text:
relocationEntry.r_info = R_RISCV_CALL;
break;
case Reference.Target.high20:
relocationEntry.r_info = R_RISCV_HI20;
break;
case Reference.Target.lower12i:
relocationEntry.r_info = R_RISCV_LO12_I;
break;
}
elf.relocate(reference.name, relocationEntry, relocationSub);
}
elf.finish();
return 0;
}

1060
source/elna/elf.d Normal file

File diff suppressed because it is too large Load Diff

335
source/elna/extended.d Normal file
View File

@ -0,0 +1,335 @@
/**
* File I/O that can be moved into more generic library when and if finished.
*/
module elna.extended;
import core.stdc.errno;
import core.stdc.stdio;
import std.sumtype;
import std.typecons;
import tanya.os.error;
import tanya.container.array;
import tanya.container.string;
/**
* File handle abstraction.
*/
struct File
{
/// Plattform dependent file type.
alias Handle = FILE*;
/// Uninitialized file handle value.
enum Handle invalid = null;
/**
* Relative position.
*/
enum Whence
{
/// Relative to the start of the file.
set = SEEK_SET,
/// Relative to the current cursor position.
currentt = SEEK_CUR,
/// Relative from the end of the file.
end = SEEK_END,
}
/**
* File open modes.
*/
enum Mode
{
/// Open the file for reading.
read = 1 << 0,
/// Open the file for writing. The stream is positioned at the beginning
/// of the file.
write = 1 << 1,
/// Open the file for writing and remove its contents.
truncate = 1 << 2,
/// Open the file for writing. The stream is positioned at the end of
/// the file.
append = 1 << 3,
}
private enum Status
{
invalid,
owned,
borrowed,
}
private union Storage
{
Handle handle;
ErrorCode errorCode;
}
private Storage storage;
private Status status = Status.invalid;
@disable this(scope return ref File f);
@disable this();
/**
* Closes the file.
*/
~this() @nogc nothrow
{
if (this.status == Status.owned)
{
fclose(this.storage.handle);
}
this.storage.handle = invalid;
this.status = Status.invalid;
}
/**
* Construct the object with the given system handle. The won't be claused
* in the descructor if this constructor is used.
*
* Params:
* handle = File handle to be wrapped by this structure.
*/
this(Handle handle) @nogc nothrow pure @safe
{
this.storage.handle = handle;
this.status = Status.borrowed;
}
/**
* Returns: Plattform dependent file handle.
*/
@property Handle handle() @nogc nothrow pure @trusted
{
return valid ? this.storage.handle : invalid;
}
/**
* Returns: An error code if an error has occurred.
*/
@property ErrorCode errorCode() @nogc nothrow pure @safe
{
return valid ? ErrorCode() : this.storage.errorCode;
}
/**
* Returns: Whether a valid, opened file is represented.
*/
@property bool valid() @nogc nothrow pure @safe
{
return this.status != Status.invalid;
}
/**
* Transfers the file into invalid state.
*
* Returns: The old file handle.
*/
Handle reset() @nogc nothrow pure @safe
{
if (!valid)
{
return invalid;
}
auto oldHandle = handle;
this.status = Status.invalid;
this.storage.errorCode = ErrorCode();
return oldHandle;
}
/**
* Sets stream position in the file.
*
* Params:
* offset = File offset.
* whence = File position to add the offset to.
*
* Returns: Error code if any.
*/
ErrorCode seek(size_t offset, Whence whence) @nogc nothrow
{
if (!valid)
{
return ErrorCode(ErrorCode.ErrorNo.badDescriptor);
}
if (fseek(this.storage.handle, offset, whence))
{
return ErrorCode(cast(ErrorCode.ErrorNo) errno);
}
return ErrorCode();
}
/**
* Returns: Current offset or an error.
*/
SumType!(ErrorCode, size_t) tell() @nogc nothrow
{
if (!valid)
{
return typeof(return)(ErrorCode(ErrorCode.ErrorNo.badDescriptor));
}
auto result = ftell(this.storage.handle);
if (result < 0)
{
return typeof(return)(ErrorCode(cast(ErrorCode.ErrorNo) errno));
}
return typeof(return)(cast(size_t) result);
}
/**
* Params:
* buffer = Destination buffer.
*
* Returns: Bytes read. $(D_PSYMBOL ErrorCode.ErrorNo.success) means that
* while reading the file an unknown error has occurred.
*/
SumType!(ErrorCode, size_t) read(ubyte[] buffer) @nogc nothrow
{
if (!valid)
{
return typeof(return)(ErrorCode(ErrorCode.ErrorNo.badDescriptor));
}
const bytesRead = fread(buffer.ptr, 1, buffer.length, this.storage.handle);
if (bytesRead == buffer.length || eof())
{
return typeof(return)(bytesRead);
}
return typeof(return)(ErrorCode());
}
/**
* Params:
* buffer = Source buffer.
*
* Returns: Bytes written. $(D_PSYMBOL ErrorCode.ErrorNo.success) means that
* while reading the file an unknown error has occurred.
*/
SumType!(ErrorCode, size_t) write(const(ubyte)[] buffer) @nogc nothrow
{
if (!valid)
{
return typeof(return)(ErrorCode(ErrorCode.ErrorNo.badDescriptor));
}
const bytesWritten = fwrite(buffer.ptr, 1, buffer.length, this.storage.handle);
if (bytesWritten == buffer.length)
{
return typeof(return)(buffer.length);
}
return typeof(return)(ErrorCode());
}
/**
* Returns: EOF status of the file.
*/
bool eof() @nogc nothrow
{
return valid && feof(this.storage.handle) != 0;
}
/**
* Constructs a file object that will be closed in the destructor.
*
* Params:
* filename = The file to open.
*
* Returns: Opened file or an error.
*/
static File open(const(char)* filename, BitFlags!Mode mode) @nogc nothrow
{
char[3] modeBuffer = "\0\0\0";
if (mode.truncate)
{
modeBuffer[0] = 'w';
if (mode.read)
{
modeBuffer[1] = '+';
}
}
else if (mode.append)
{
modeBuffer[0] = 'a';
if (mode.read)
{
modeBuffer[1] = '+';
}
}
else if (mode.read)
{
modeBuffer[0] = 'r';
if (mode.write)
{
modeBuffer[1] = '+';
}
}
auto newHandle = fopen(filename, modeBuffer.ptr);
auto newFile = File(newHandle);
if (newHandle is null)
{
newFile.status = Status.invalid;
newFile.storage.errorCode = ErrorCode(cast(ErrorCode.ErrorNo) errno);
}
else
{
if (mode == BitFlags!Mode(Mode.write))
{
rewind(newHandle);
}
newFile.status = Status.owned;
}
return newFile;
}
}
/**
* Reads the whole file and returns its contents.
*
* Params:
* sourceFilename = Source filename.
*
* Returns: File contents or an error.
*
* See_Also: $(D_PSYMBOL File.read)
*/
SumType!(ErrorCode, Array!ubyte) readFile(String sourceFilename) @nogc
{
enum size_t bufferSize = 255;
auto sourceFile = File.open(sourceFilename.toStringz, BitFlags!(File.Mode)(File.Mode.read));
if (!sourceFile.valid)
{
return typeof(return)(sourceFile.errorCode);
}
Array!ubyte sourceText;
size_t totalRead;
size_t bytesRead;
do
{
sourceText.length = sourceText.length + bufferSize;
const readStatus = sourceFile
.read(sourceText[totalRead .. $].get)
.match!(
(ErrorCode errorCode) => nullable(errorCode),
(size_t bytesRead_) {
bytesRead = bytesRead_;
return Nullable!ErrorCode();
}
);
if (!readStatus.isNull)
{
return typeof(return)(readStatus.get);
}
totalRead += bytesRead;
}
while (bytesRead == bufferSize);
sourceText.length = totalRead;
return typeof(return)(sourceText);