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

Setup library #1

Merged
merged 10 commits into from
Oct 6, 2023
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
29 changes: 29 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: ci
on: [push]
jobs:
build-linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: init
run: sudo apt update -yqq && sudo apt install -yqq ninja-build g++-13 clang-15
- name: configure gcc
run: cmake -S . --preset=default -B build -DCMAKE_CXX_COMPILER=g++-13
- name: configure clang
run: cmake -S . --preset=ninja-clang -B clang -DKALCY_BUILD_TESTS=OFF -DKALCY_BUILD_EXAMPLES=OFF -DCMAKE_CXX_COMPILER=clang++-15
- name: build gcc
run: cmake --build build --config=Release
- name: build clang
run: cmake --build clang --config=Release
- name: test
run: cd build && ctest -C Release
build-windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: configure
run: cmake -S . --preset=vs22 -B build
- name: build
run: cmake --build build --config=Release
- name: test
run: cd build && ctest -C Release
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.24)

project(kalcy)
project(kalcy VERSION 0.1)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
Expand Down Expand Up @@ -33,7 +33,7 @@ endif()
add_subdirectory(kalcy)

if(KALCY_BUILD_EXAMPLES)
# add_subdirectory(examples)
add_subdirectory(examples)
endif()

if(KALCY_BUILD_TESTS)
Expand Down
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_subdirectory(quickstart)
12 changes: 12 additions & 0 deletions examples/quickstart/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
project(kalcy-quickstart)

add_executable(${PROJECT_NAME})

target_link_libraries(${PROJECT_NAME} PRIVATE
kalcy::kalcy
kalcy::kalcy-compile-options
)

target_sources(${PROJECT_NAME} PRIVATE
quickstart.cpp
)
53 changes: 53 additions & 0 deletions examples/quickstart/quickstart.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <kalcy/kalcy.hpp>
#include <cassert>
#include <format>
#include <iomanip>
#include <iostream>
#include <span>

namespace {
auto run(std::string_view const text, bool verbose) -> bool {
try {
// parse text into an expression
auto expr = kalcy::Parser{text}.parse();
assert(expr != nullptr);
// evaluate parsed expression
// a custom Env can be used and passed, if desired
std::cout << kalcy::evaluate(*expr) << "\n";
// print AST if verbose
if (verbose) { std::cout << std::format("expression\t: {}\nAST\t\t: {}\n", text, kalcy::to_string(*expr)); }
return true;
} catch (kalcy::Error const& err) {
// print error
std::cerr << err.what() << "\n";
// highlight error location under text
std::cerr << " | " << text << "\n | " << err.build_highlight() << "\n";
return false;
}
}
} // namespace

auto main(int argc, char** argv) -> int {
// obtain arguments, skip exe name
auto args = std::span{argv, static_cast<std::size_t>(argc)}.subspan(1);

bool verbose{};
// check if verbose
if (args.front() == std::string_view{"-v"}) {
verbose = true;
// advance args by 1
args = args.subspan(1);
}

if (args.empty()) {
// print usage
std::cout << std::format("usage: {} [-v] \"<expression>\"\n", *argv);
return EXIT_SUCCESS;
}

// run kalcy on input expression
if (!run(args.front(), verbose)) { return EXIT_FAILURE; }

// print epilogue
std::cout << std::format("\n^^ kalcy v{}\n", kalcy::version_v);
}
4 changes: 3 additions & 1 deletion kalcy/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ target_link_libraries(${PROJECT_NAME} PRIVATE

target_include_directories(${PROJECT_NAME} PUBLIC
include
"${CMAKE_CURRENT_BINARY_DIR}/include"
)

target_compile_features(${PROJECT_NAME} PUBLIC
cxx_std_20
)

configure_file(src/build_version.hpp.in "${CMAKE_CURRENT_BINARY_DIR}/include/kalcy/build_version.hpp" @ONLY)

target_sources(${PROJECT_NAME} PUBLIC FILE_SET HEADERS BASE_DIRS include FILES
include/kalcy/error.hpp
include/kalcy/enum_array.hpp
Expand All @@ -30,7 +33,6 @@ target_sources(${PROJECT_NAME} PRIVATE
src/error.cpp
src/eval.cpp
src/expr.cpp
src/kalcy.cpp
src/parser.cpp
src/scanner.cpp
)
15 changes: 12 additions & 3 deletions kalcy/include/kalcy/env.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,18 @@ class Env {
///
/// \brief Funcs can throw an instance of this.
///
struct Mismatch {
std::size_t argument_count{};
};
struct Mismatch {};

///
/// \brief Get a default instance (singleton).
/// \returns const reference to a static default instance.
///
static auto get_default() -> Env const&;

///
/// \brief Populate environment with builtins.
///
explicit Env();

///
/// \brief Define a function.
Expand Down
2 changes: 2 additions & 0 deletions kalcy/include/kalcy/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ struct Error : std::runtime_error {
Token token{};

explicit Error(Token const token, std::string const& message) : std::runtime_error(message), token(token) {}

[[nodiscard]] auto build_highlight(char higlight = '^') const -> std::string;
};

///
Expand Down
2 changes: 2 additions & 0 deletions kalcy/include/kalcy/eval.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@ struct Eval {
///
[[nodiscard]] auto operator()(Expr const& expr) const noexcept(false) -> double;
};

inline auto evaluate(Expr const& expr, Env const& env = Env::get_default()) { return Eval{env}(expr); }
} // namespace kalcy
5 changes: 5 additions & 0 deletions kalcy/include/kalcy/kalcy.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#pragma once
#include <kalcy/build_version.hpp>
#include <kalcy/error.hpp>
#include <kalcy/eval.hpp>
#include <kalcy/parser.hpp>
9 changes: 9 additions & 0 deletions kalcy/src/build_version.hpp.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#pragma once
#include <string_view>

namespace kalcy {
///
/// \brief kalcy build version.
///
inline constexpr std::string_view version_v{"@PROJECT_VERSION@"};
} // namespace kalcy
15 changes: 15 additions & 0 deletions kalcy/src/env.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
#include <kalcy/env.hpp>
#include <kalcy/error.hpp>
#include <cassert>
#include <cmath>
#include <numbers>

namespace kalcy {
auto Env::get_default() -> Env const& {
static auto const ret{Env{}};
return ret;
}

Env::Env() {
define("pi", std::numbers::pi_v<double>);
define("sqrt", [](std::span<double const> args) {
if (args.size() != 1) { throw Mismatch{}; }
return std::sqrt(args.front());
});
}

void Env::define(std::string_view name, Func func) {
if (name.empty() || !func) { return; }
m_table.insert_or_assign(name, std::move(func));
Expand Down
11 changes: 10 additions & 1 deletion kalcy/src/error.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
#include <kalcy/error.hpp>
#include <format>
#include <iomanip>
#include <sstream>

namespace kalcy {
auto Error::build_highlight(char const higlight) const -> std::string {
auto ret = std::ostringstream{};
if (token.location > 0) { ret << std::setw(static_cast<int>(token.location)) << ' '; }
ret << std::setfill(higlight) << std::setw(static_cast<int>(token.lexeme.size())) << higlight;
return ret.str();
}

ParseError::ParseError(Token const token) : Error(token, "parse error") {}

ParseError::ParseError(Token const token, Token::Type const expected)
Expand All @@ -10,7 +19,7 @@ ParseError::ParseError(Token const token, Token::Type const expected)
UndefinedSymbol::UndefinedSymbol(Token const token) : Error(token, std::format("undefined symbol: '{}'", token.lexeme)) {}

ArgsMismatch::ArgsMismatch(Token const token, std::size_t argument_count)
: Error(token, std::format("{} does not take {} arguments", token.lexeme, argument_count)), argument_count(argument_count) {}
: Error(token, std::format("{} does not take {} argument(s)", token.lexeme, argument_count)), argument_count(argument_count) {}

InvalidOperaor::InvalidOperaor(Token const token) : Error(token, std::format("invalid operator: '{}'", token.lexeme)) {}
} // namespace kalcy
2 changes: 1 addition & 1 deletion kalcy/src/eval.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ struct Evaluator {
for (auto const& in : call.arguments) { args.push_back(Evaluator{env}.evaluate(*in)); }
try {
return env.invoke(call.callee, args);
} catch (Env::Mismatch const& mismatched_args) { throw ArgsMismatch{call.callee, mismatched_args.argument_count}; }
} catch (Env::Mismatch) { throw ArgsMismatch{call.callee, args.size()}; }
}

auto operator()(expr::Group const& group) const -> double { return Evaluator{env}.evaluate(*group.expr); }
Expand Down
Empty file removed kalcy/src/kalcy.cpp
Empty file.
2 changes: 1 addition & 1 deletion tests/tests/test_eval.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ ADD_TEST(Evaluate) {
ADD_TEST(Call) {
auto env = Env{};
env.define("sqrt", [](std::span<double const> args) {
if (args.size() != 1) { throw Env::Mismatch{args.size()}; }
if (args.size() != 1) { throw Env::Mismatch{}; }
return std::sqrt(args.front());
});
auto expr = make_expr("sqrt(4)");
Expand Down
Loading