Files
cparse/functions.cpp
Vinícius Garcia 6bafe9d9c1 Improve support to Map and Tuple (#28)
* Make Iterator class inherit from Iterable

* Add tests for str() representation of all Tokens

* Uninitialized calculators now return `None`

Before this commit evaluating an uninitialized calculator would
cause a segmentation fault. Now it will just return None.

* Add args variable to Makefile for passing args to tests

* Refactor Tuple class to inherit from TokenList

Now the Tuple class inherits from TokenList, this allows:

- To use less code to describe it
- To garbage collect it

* Add the Special Tuple operator `:`

This new Tuple operator differs from the operator `,` on 2 aspects:

1. It has greater operator priority.
2. The generate tuple has the type STUPLE (Special Tuple) so that
   these 2 kinds of tuple won't be merged together.

With these changes it is possible to define a tuple like this:
(1, 'b':2, 'c':3, 4)

This will be used to provide make the language easier to use:

- Allow list slicing: my_list[1:30:2]
- Allow setting key-value args for functions: map('attr1':10, 'attr2':20)

The Special Tuple name is currently STuple, which could mean:

- Special Tuple
- System Tuple
- Syntactic Tuple

Another possible name would be 'Nested Tuple', in any case, the
current name is not very good, so new names suggestions are welcome.

* Move extend() function test

* Add keyword arguments support, update map() constructor

Now it is possible to pass keyword values to functions, as a sample
the map() constructor was updated to work with it:

```
  m = map(
    'a': 1,
    'b': 2,
    'c': list(1,2,3)
  )
  print(m) // { "a": 1, "b": 2, "c": [ 1, 2, 3 ] }
```

It should also work in conjunction with positional arguments:

```
  func(1, 2, 3, 'optional_arg': 10)
```

But this was not tested yet for lack of a built-in function
to make use of it.

* Add map().pop('key') and map().len() built-in functions
2016-09-09 08:58:08 -04:00

375 lines
9.7 KiB
C++

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <stdexcept>
#include <cerrno>
#include <iostream>
#include <cctype> // For tolower() and toupper()
#include "./shunting-yard.h"
#include "./functions.h"
#include "./shunting-yard-exceptions.h"
/* * * * * class Function * * * * */
packToken Function::call(packToken _this, Function* func,
TokenList* args, TokenMap scope) {
// Build the local namespace:
TokenMap kwargs;
TokenMap local = scope.getChild();
argsList arg_names = func->args();
TokenList_t::iterator args_it = args->list().begin();
argsList::const_iterator names_it = arg_names.begin();
/* * * * * Parse named arguments: * * * * */
while (args_it != args->list().end() && names_it != arg_names.end()) {
// If the positional argument list is over:
if ((*args_it)->type == STUPLE) break;
// Else add it to the local namespace:
local[*names_it] = *args_it;
++args_it;
++names_it;
}
/* * * * * Parse extra positional arguments: * * * * */
TokenList arglist;
for (; args_it != args->list().end(); ++args_it) {
// If there is a keyword argument:
if ((*args_it)->type == STUPLE) break;
// Else add it to arglist:
arglist.list().push_back(*args_it);
}
/* * * * * Parse keyword arguments: * * * * */
for (; args_it != args->list().end(); ++args_it) {
packToken& arg = *args_it;
if (arg->type != STUPLE) {
throw syntax_error("Positional argument follows keyword argument");
}
STuple* st = static_cast<STuple*>(arg.token());
if (st->list().size() != 2) {
throw syntax_error("Keyword tuples must have exactly 2 items!");
}
if (st->list()[0]->type != STR) {
throw syntax_error("Keyword first argument should be of type string!");
}
// Save it:
std::string key = st->list()[0].asString();
packToken& value = st->list()[1];
kwargs[key] = value;
}
/* * * * * Set missing arguments to None: * * * * */
for (; names_it != arg_names.end(); ++names_it) {
// If not set by a keyword argument:
if (local.map().count(*names_it) == 0) {
local[*names_it] = packToken::None;
}
}
/* * * * * Set built-in variables: * * * * */
local["this"] = _this;
local["args"] = arglist;
local["kwargs"] = kwargs;
return func->exec(local);
}
/* * * * * Built-in Functions: * * * * */
packToken default_print(TokenMap scope) {
// Get the argument list:
TokenList list = scope.find("args")->asList();
bool first = true;
for (packToken item : list.list()) {
if (first) {
first = false;
} else {
std::cout << " ";
}
if (item->type == STR) {
std::cout << item.asString();
} else {
std::cout << item.str();
}
}
std::cout << std::endl;
return packToken::None;
}
packToken default_sum(TokenMap scope) {
// Get the arguments:
TokenList list = scope.find("args")->asList();
if (list.list().size() == 1 && list.list().front()->type == LIST) {
list = list.list().front().asList();
}
double sum = 0;
for (packToken num : list.list()) {
sum += num.asDouble();
}
return sum;
}
const char* value_arg[] = {"value"};
packToken default_eval(TokenMap scope) {
std::string code = scope.find("value")->asString();
// Evaluate it as a calculator expression:
return calculator::calculate(code.c_str(), scope);
}
packToken default_float(TokenMap scope) {
packToken* tok = scope.find("value");
if ((*tok)->type & NUM) return tok->asDouble();
// Convert it to double:
char* rest;
const std::string& str = tok->asString();
errno = 0;
double ret = strtod(str.c_str(), &rest);
if (str == rest) {
throw std::runtime_error("Could not convert \"" + str + "\" to float!");
} else if (errno) {
std::range_error("Value too big or too small to fit a Double!");
}
return ret;
}
packToken default_int(TokenMap scope) {
packToken* tok = scope.find("value");
if ((*tok)->type & NUM) return tok->asInt();
// Convert it to double:
char* rest;
const std::string& str = tok->asString();
errno = 0;
int64_t ret = strtol(str.c_str(), &rest, 10);
if (str == rest) {
throw std::runtime_error("Could not convert \"" + str + "\" to integer!");
} else if (errno) {
std::range_error("Value too big or too small to fit an Integer!");
}
return ret;
}
packToken default_str(TokenMap scope) {
// Return its string representation:
packToken* tok = scope.find("value");
if ((*tok)->type == STR) return *tok;
return tok->str();
}
packToken default_type(TokenMap scope) {
packToken* tok = scope.find("value");
switch ((*tok)->type) {
case NONE: return "none";
case VAR: return "variable";
case REAL: return "float";
case INT: return "integer";
case STR: return "string";
case FUNC: return "function";
case IT: return "iterable";
case TUPLE: return "tuple";
case STUPLE: return "argument tuple";
case LIST: return "list";
case MAP: return "map";
default: return "unknown_type";
}
}
packToken default_extend(TokenMap scope) {
packToken* tok = scope.find("value");
if ((*tok)->type == MAP) {
return tok->asMap().getChild();
} else {
throw std::runtime_error(tok->str() + " is not extensible!");
}
}
packToken default_instanceof(TokenMap scope) {
TokenMap _super = scope.find("value")->asMap();
TokenMap* _this = scope.find("this")->asMap().parent();
TokenMap* parent = _this;
while (parent) {
if ((*parent) == _super) {
return true;
}
parent = parent->parent();
}
return false;
}
const char* num_arg[] = {"number"};
packToken default_sqrt(TokenMap scope) {
// Get a single argument:
double number = scope.find("number")->asDouble();
return sqrt(number);
}
packToken default_sin(TokenMap scope) {
// Get a single argument:
double number = scope.find("number")->asDouble();
return sin(number);
}
packToken default_cos(TokenMap scope) {
// Get a single argument:
double number = scope.find("number")->asDouble();
return cos(number);
}
packToken default_tan(TokenMap scope) {
// Get a single argument:
double number = scope.find("number")->asDouble();
return tan(number);
}
packToken default_abs(TokenMap scope) {
// Get a single argument:
double number = scope.find("number")->asDouble();
return std::abs(number);
}
const char* pow_args[] = {"number", "exp"};
packToken default_pow(TokenMap scope) {
// Get two arguments:
double number = scope.find("number")->asDouble();
double exp = scope.find("exp")->asDouble();
return pow(number, exp);
}
/* * * * * Type-specific default functions * * * * */
packToken string_len(TokenMap scope) {
std::string str = scope.find("this")->asString();
return static_cast<int64_t>(str.size());
}
packToken string_lower(TokenMap scope) {
std::string str = scope.find("this")->asString();
std::string out;
for (char c : str) {
out.push_back(tolower(c));
}
return out;
}
packToken string_upper(TokenMap scope) {
std::string str = scope.find("this")->asString();
std::string out;
for (char c : str) {
out.push_back(toupper(c));
}
return out;
}
/* * * * * default constructor functions * * * * */
packToken default_list(TokenMap scope) {
// Get the arguments:
TokenList list = scope.find("args")->asList();
// If the only argument is iterable:
if (list.list().size() == 1 && list.list()[0]->type & IT) {
TokenList new_list;
Iterator* it = static_cast<Iterable*>(list.list()[0].token())->getIterator();
packToken* next = it->next();
while (next) {
new_list.list().push_back(*next);
next = it->next();
}
delete it;
return new_list;
} else {
return list;
}
}
packToken default_map(TokenMap scope) {
return scope["kwargs"];
}
/* * * * * class CppFunction * * * * */
CppFunction::CppFunction(packToken (*func)(TokenMap), unsigned int nargs,
const char** args, std::string name)
: func(func) {
this->name = name;
// Add all strings to args list:
for (uint32_t i = 0; i < nargs; ++i) {
this->_args.push_back(args[i]);
}
}
// Build a function with no named args:
CppFunction::CppFunction(packToken (*func)(TokenMap), std::string name)
: func(func) {
this->name = name;
}
/* * * * * CppFunction Initializer Constructor: * * * * */
struct CppFunction::Startup {
Startup() {
TokenMap& global = TokenMap::default_global();
global["print"] = CppFunction(&default_print, "print");
global["sum"] = CppFunction(&default_sum, "sum");
global["sqrt"] = CppFunction(&default_sqrt, 1, num_arg, "sqrt");
global["sin"] = CppFunction(&default_sin, 1, num_arg, "sin");
global["cos"] = CppFunction(&default_cos, 1, num_arg, "cos");
global["tan"] = CppFunction(&default_tan, 1, num_arg, "tan");
global["abs"] = CppFunction(&default_abs, 1, num_arg, "abs");
global["pow"] = CppFunction(&default_pow, 2, pow_args, "pow");
global["float"] = CppFunction(&default_float, 1, value_arg, "float");
global["str"] = CppFunction(&default_str, 1, value_arg, "str");
global["eval"] = CppFunction(&default_eval, 1, value_arg, "eval");
global["type"] = CppFunction(&default_type, 1, value_arg, "type");
global["extend"] = CppFunction(&default_extend, 1, value_arg, "extend");
// Default constructors:
global["list"] = CppFunction(&default_list, "list");
global["map"] = CppFunction(&default_map, "map");
TokenMap& base_map = TokenMap::base_map();
base_map["instanceof"] = CppFunction(&default_instanceof, 1,
value_arg, "instanceof");
typeMap_t& type_map = calculator::type_attribute_map();
type_map[STR]["len"] = CppFunction(&string_len, "len");
type_map[STR]["lower"] = CppFunction(&string_lower, "lower");
type_map[STR]["upper"] = CppFunction(&string_upper, "upper");
}
} CppFunction_startup;