mirror of
https://github.com/allankoechke/cparse.git
synced 2026-11-30 17:11:31 +00:00
The builtin functions are defined in the file functions.cpp Each function receive a Scope* as argument and must return a packToken type. The Function class inherits from TokenBase and its constructor receive 3 arguments: - A function pointer with signature: packToken (*func)(Scope*) - The number of named arguments to expect. - A std::string* list with the arguments name. The number of named arguments must equal the length of the string list. The reason for the only argument be a Scope* is because a function should also be able to access global variables. This scope is created so that the arguments are inserted on its most local TokenMap_t. After the function execution this TokenMap_t is dellocated. Builtin functions are now automatically added in the global TokenMap_t of all scopes by the Scope constructor.
53 lines
1.3 KiB
C++
53 lines
1.3 KiB
C++
#include <cstdio>
|
|
#include <cmath>
|
|
#include "./shunting-yard.h"
|
|
|
|
TokenMap_t Function::default_functions = Function::initialize_functions();
|
|
|
|
std::string text_arg[] = {"text"};
|
|
packToken default_print(const Scope* args) {
|
|
// Get a single argument:
|
|
std::string text = args->find("text")->asString();
|
|
printf(text.c_str());
|
|
printf("\n");
|
|
|
|
return packToken::None;
|
|
}
|
|
|
|
std::string num_arg[] = {"number"};
|
|
packToken default_sqrt(const Scope* args) {
|
|
// Get a single argument:
|
|
double number = args->find("number")->asDouble();
|
|
|
|
return sqrt(number);
|
|
}
|
|
packToken default_sin(const Scope* args) {
|
|
// Get a single argument:
|
|
double number = args->find("number")->asDouble();
|
|
|
|
return sin(number);
|
|
}
|
|
packToken default_cos(const Scope* args) {
|
|
// Get a single argument:
|
|
double number = args->find("number")->asDouble();
|
|
|
|
return cos(number);
|
|
}
|
|
packToken default_tan(const Scope* args) {
|
|
// Get a single argument:
|
|
double number = args->find("number")->asDouble();
|
|
|
|
return tan(number);
|
|
}
|
|
|
|
TokenMap_t Function::initialize_functions() {
|
|
TokenMap_t funcs;
|
|
|
|
funcs["print"] = Function(&default_print, 1, text_arg);
|
|
funcs["sqrt"] = Function(&default_sqrt, 1, num_arg);
|
|
funcs["sin"] = Function(&default_sin, 1, num_arg);
|
|
funcs["cos"] = Function(&default_cos, 1, num_arg);
|
|
funcs["tan"] = Function(&default_tan, 1, num_arg);
|
|
return funcs;
|
|
}
|