33 Commits

Author SHA1 Message Date
Vinícius Garcia
2bb8ada027 Fix linter complaints 2021-04-26 19:10:22 -03:00
dimxy
a4ea8b5f8c cparse namespace added (#82) 2021-04-26 18:38:05 -03:00
Vinícius Garcia
42cb2944ba Fix linter complaints 2020-11-02 16:27:31 -03:00
Zipo Chen
73b1279969 Add cppfunction for lambda function (#73)
* Add cppfunction for lambda function

* Add default constructor for CppFunction

* Add polymorphic function
2020-07-03 12:18:25 -03:00
Vinícius Garcia
68a373e849 Fix kwargs feature: now it replaces positional args
Before this commit you could pass keyword arguments to a function
and it would be accessible inside a variable `kwargs` when the
function was executed.

However, if the keyword argument had the same name as a positional
argument it should instead replace the argument as in Python.

It is now fixed and it is possible to set positional arguments
by name as it was originally designed to be, e.g.:

```C++
// Passing arguments to pow by name:
packToken result = calculator::calculate("pow('exp': 3, 'number': 2)");
std::cout << result << std::endl; // 8

// Works independently from arguments order:
packToken result = calculator::calculate("pow('exp': 3, 'number': 2)");
std::cout << result << std::endl; // 8
```
2017-12-09 15:44:37 -02:00
Vinícius Garcia
c8a79020f9 Add support for custom right unary operators
Now it is possible to design unary operators to work on the
right side of an operand, e.g. `a~` instead of `~a`.

Note, however, that an operator such as `a++` is not yet possible
because it alters the value of the lvalue `a` and this value
is not yet available for access by custom operators.

This commit also adds bug fixes and new tests for left unary operators.
2017-11-15 23:12:00 -02:00
Vinícius Garcia
a077e73615 Add const qualifier to some functions
The `Function::call()` second argument is now qualified as `const`,
this makes the function usable even if the Function* is const.

The function `TokenMap::find()` now has a const version that
return a `const packToken*`.
2017-05-12 21:25:31 -03:00
Vinícius Garcia
3e781ad76c Refactor builtin-features.cpp into multiple files
Before this commit all built-in features were kept not very well
organized inside the `builtin-features.cpp` file.

Now 4 extra files have been created:

1. `builtin-features/functions.h`
2. `builtin-features/operations.h`
3. `builtin-features/reservedWords.h`
4. `builtin-features/typeSpecificFunctions.h`

The `builtin-features.cpp` file still exists but now it only
contains `#includes "..."` of the other 4 files.

This was done to make it easier to understand each file and
easier to find an specific function if required.
2017-03-10 02:06:00 -03:00
Vinícius Garcia
96704a4872 Add some small improvements (#49)
* Add string strip() and string split() functions

* Add list `join()` function.

* Make const version of packToken::token() function

* Add const modifier to Iterable::getIterator() function

* Fix static initialization order bug with packToken::None

Before this commit there was a hidden bug on packToken::None.

If it was called from a static initialized constructor it might
or might not cause a bug.

Now packToken::None is no longe a packToken, but instead a function
that returns a packToken when called.

To adapt old code to conform with this change you should replace
any occurency of `packToken::None` for `packToken::None()`.

* Group together: OppMap_t, rWordMap_t and opMap_t

Now these 3 containers were grouped into a a bigger one: Config_t

This change was done for all the 3 contained configuration data.
And this data had to be passed along on many functions.

Now only 1 argument is required to be passed.

An extra reason is for when a user wants to create his own calculator,
Before this he would need to overwrite 3 virtual functions, one
for each of those configuration containers, now 1 is enough.

The old static variables:

- calculator::default_opPrecedence
- calculator::default_opMap
- calculator::default_rWordMap

Were replaced by the Default static variable:

- Config_t calculator::Default

To access them now it is possible like this:

- calculator::Default().opPrecedence
- calculator::Default().opMap
- calculator::Default().rWordMap

* Small refactor + Add the concept of reserved character

rWordMap_t was replaced by the struct parserMap_t.

This was the small refactor. To add new reserved words the
syntax has changed a little:

```C++
parserMap_t& parser = calculator::Default().parserMap;

parser.add("op", &op_function);

// Before it was like this:
rWordMap_t& rmap = calculator::Default().rWordMap;

rmap["op"] = &op_function;
``

With this change we could add the concept of a reserved character.

To add a reserved character you can do in a very simillar way
to the way you do with reserved words, just make sure to use
simple quotes around the character:

```C++
parserMap_t& parser = calculator::Default().parserMap;

parser.add('=', &assignment);
```

Considerations:

1. Reserved characters work even if the current token contain
   more than one character such the token `=-` on the expression:

   - "a =-10"

   It will consider the minus sign a separated token like: "a = -10".

2. In situations where the current token have meaning such as:

   - "a == 10"

   The operator meaning will have precedence, and the character
   parser will not be called, thus allowing for the correct behavior.

   The same is valid if "==" were a reserved, it also takes precedence
   in relation to the reserved character.

This concept is complicated. However necessary. With this feature
it will be possible to remove the hardcoded operations:

- Assignment: `=`
- Subscripting: `.`
- Bracketing: `(`, `[` and `{`

And write them on `builtin-features.cpp`.

* Fix built-in type casts for `real` and `int`

* Update output of built-in function `type()`

Before this the output for the type REAL was `float`.

Now it will return the string `real` instead, making it more
coherent with the actual name of the type.

* Fix Travis Build
2017-03-09 22:36:39 -03:00
Vinícius Garcia
9182625ae1 Simplify operations (#38)
* Greatly simplify declaring new operations

Now declaring new operations looks much more like
declaring a new function. The most important difference
is that its arguments are `TokenBase*` instead of `packToken`s.

* Greatly simplify definition of new Operations

Before this commit defining a new Operation would
mean:

1. Extend a class
2. Overwrite a function
3. Manually build a mask
4. Add it to the correct map

Now the process to define a new operations is a lot simpler:

1. Define a function
2. Call the `add()` function to add it to the correct map

Beside this change there is one more simplification: the
signature of the function that describes the operation behavior
now receives `packToken`s as arguments instead of `TokenBase*`.

This means that our users won't have to learn about `TokenBase*`
and won't need to worry about memory management.

An example of the new syntax follows:

```C++
packToken my_operation(const packToken& left, const std::string& op, const packToken& right) {
  return left == right;
}

class myStartup {
  myStartup() {
    opMap_t opMap& = calculator::opMap();
    opMap.add({ANY_TYPE, "==", ANY_TYPE}, &my_operation);
  }
} myStartup;
```

* Simplify RefToken's constructor

This commit simplifies the RefToken's constructor
so that it can accept packTokens instead of TokenBase* as
the `value` argument.

This allows to remove all references of the TokenBase class from
the built-in operations. Making them good examples for our users
to use as template.

* Move all builtin logic to operations.cpp file

* Rename `operations.cpp` to `builtin-operations.cpp`

* Add `make release` as dependency of `make all`

* Fix Travis Build
2016-10-24 21:04:08 -02:00
Vinícius Garcia
9bdba2aa4c Decouple operations (#30)
* Replace all `scope->find(name)` calls for `scope[name]`

These calls were on the built-in functions declarations, and
were used to recover the function arguments.

This change was made because the find() function was not
the correct tool for the job; The find() function looks
on the entire prototype chain of the scope for the variable,
and this is not needed on this case since the function arguments
will always be on the most local scope of the function.

This refactor makes the code more readable and sightly more
efficient.

* Rename `argsList` to `args_t`

* Convert Function::name from a literal string to a getter function

* Simplify CppFunction constructor

This commit adds a new constructor to CppFunction that expects
a `const args_t` as argument.

This way it is possible to define a new function without having
to explicitly give how many arguments it receives, i.e.:

  CppFunction(&my_func, {"arg1", "arg2", "arg3"}, "my_func");

instead of:

  CppFunction(&my_func, 3, {"arg1", "arg2", "arg3"}, "my_func");

* Add new constructor to undefined_operation

* Major refactor: decouple operations from calculator class

Before this commit every new operation would be hard coded
inside the static calculator::calculate() function.

Now it is not required anymore. To add a new operation do as follow:

```C++
struct my_operation : public Operation {
  // This describes the operands expected by this operation:
  const opID_t getMask() { return build_mask(INT, REAL); }

  // This describes the operation behavior:
  TokenBase* exec(TokenBase* left, std::string op, TokenBase* right) {
    if (/* not satisfy condition */) {
      // Ignore this operation and keep looking for a match:
      return 0;
    }

    if (/* erro condition*/) {
      throw my_error("...");
    }

    // if its all ok:
    TokenBase* result = some_code(left, right);

    // Consume both Tokens:
    delete left;
    delete right;

    // Return:
    return result;
  }
// Don't forget to declare and static instance:
} my_operation;

struct my_Startup {
  my_Startup() {
    // Register the operation on the default opMap:
    opMap_t& opMap = calculator::default_opMap();
    opMap[","].push_back(&my_operation);
    opMap[ANY_OP].push_back(&my_other_operation);
  }
} my_Startup;
```

The default operations are on the operations.cpp file.
To declare your own default operations, just make sure
to not link your code to `operations.o`, and add your
own description of your operations wherever you want.

In future work:

* Make an optional Operation function that works with
  packTokens, so the final user will not need to worry about
  memory management.

* Make it possible to overwrite the default_opMap by extending
  the calculator class, creating any number of different
  calculators as required.

* Add `release` recipe to Makefile

The `make release` will output 2 `.o` files:

- core-shunting-yard.o
- operations.o

The `core` bin contain an working calculator with
no defined operations except for asignment and function call,
that are still hard-coded on the system.

The `operations` bin contain all the other default operations.

If a user wants to define adhoc operations, include only
the `core` binary.

* Add tests for declaring adhoc operations

* Simplify Operation definition

Now there are 2 Operation classes: `BaseOperation` which is the
old class with a new name and the `Operation` that inherits from
the former.

The `exec()` pure virtual function from BaseOperation has the following
signature: TokenBase* exec(TokenBase*, std::string, TokenBase*);

The `exec()` pure virtual function from Operation has the following
signature: packToken exec(packToken, std::string, packToken);

This makes the usage of the Operation class easier since
hiding from the user the required memory management.

Advanced users can declare new operations using the `BaseOperation`
class. Working with TokenBase* is more efficient since
it does not require to call the packToken constructor and
destructor several times.

* Make possible to define adhoc opPrecedence.

Now it is possible to define your own operator precedence map
the same way it is done for operations.

The definition of the operator precedence was now moved to the
file `operations.h` and is initialized just before the operations.

If the user want to define its own operations and precedence map,
he just need to compile his code without the file `operations.o`.
After that he can define his own adhoc behavior in a file on his
project.

It is also possible to overwrite opPrecedence on a child calculator
class. The user just need to overwrite the function "opPrecedence()".

* Update README with new features.
2016-10-04 13:37:35 -04:00
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
Vinícius Garcia
2821109b38 Minor updates (#27)
* Remove TokenMap::find() const in favor of non-const find()

* Add TokenMap::findMap()

It returns the map where the variable is located instead of the
variable it-self.

It will be useful in dealing with references to variables in
the local/global scope.

* Change assignment rules to protect global scope

TLDR; The global scope is special and should be protected.

The user should not be able to implicitly overwrite a variable if he
did not declare it.

It's not feasible to expect our users to remember all variables
that exist on the global scope and avoid using their names on
assignments. So now if a user try to assign a value to a built-in
function on global scope, it will instead assign it to the local scope.

The user is still capable of writting stuff on non-local variables,
as long as these variables scope is not the default global scope.

* Add error checks for `print())` and `map()['k']]`

Before this commit these expressions caused a segmentation fault.

* Add integer type (INT) to calculator class

Note that the operations are still the same, so any operation
envolving one or two integers will return a REAL.

This should be fixed in future, but does not affect the tests.

* Remove some unnecessary `operator=` from packToken

* Make list() constructor accept an Iterator as argument

Now if this constructor receives an iterator as its single argument
it will build a list with one item for each output of the iterator.

* Fix bug on list(<iterator>) constructor

* Add string index operator

* Make operators `==` and `!=` work with any type.

* Make empty Tuples str() display `(,)` instead of `()`

* Add string.upper() and string.lower() functions
2016-09-01 10:53:59 -04:00
Vinícius Garcia
87c480956d Simplify containers (#26)
* Add a new CppFunction constructor for funcs with 0 args

* Update `pack` class API

* Remove `packMap` type in favor of the `TokenMap` class

The `packMap` type was defined as a `pack<TokenMap>`, so it would
manage memory of all Maps used on the system.

TLDR; This is a better design choice than it was before.

The reason for this change is to solve this 2 problems:

1. It creates 2 maps that do almost the same thing: packMap and TokenMap
   and it might confuse a reader of the code.

2. It could not count all TokenMap references, since some of these
   maps were referenced from inside the TokenMap class, i.e. the
   parent TokenMap of each TokenMap.

For those reasons we modified the TokenMap class. Now it inherits
from the pack<> class and manage a reference to a struct called `MapData_t`

----

This commit also makes TokenMap inherit from TokenBase, as well as
the Iterable interface.

This way it will be possible to cast a TokenBase* to an Iterable*
if the token type is an iterator, i.e. if `IT & type != 0`.

* Remove `packList` type in favor of `TokenList` class

Now TokenList inherits from:
- pack<TokenList_t>
- TokenBase
- Iterable

The reasons for this commit are the same of the last commit.

* Change "arglist" function keyword to "args"

* Refactor: Iterable is now a public TokenBase

Now there is no need to make TokenMap and TokenList
inherit from TokenBase and Iterable.

Now the Iterable class means "an Iterable Token"

* Make Iterator inherit from TokenBase

* Fix Travis build
2016-09-01 09:50:41 -04:00
Vinícius Garcia
96e8b9b23d Prototype support (#25)
* Move Tuple class from functions.h to objects.h

* Add packToken::token() function to return the TokenBase*

* Fix bug on Tuple default constructor

* Fix bug on function calls with 0 args

* Add Python string format operator: '%'

Now it is possible to write: 'replace %s for text' % 'text'
and it works like it would in Python.

It also work with:
- Numbers: 'number %s' % 10 == 'number 10'
- Multiple items: '%s %s %s' % (1,2,3) == '1 2 3'
- Escapping %s:
  - 'escape \%s %s' % '' == 'escape %s '
  - 'ignore % and %% %s' % '' == 'ignore % and %% '
- It also throws if the number of formats and arguments diverge:
  - ' %s %s ' % 'one arg' // throws
  - ' %s ' % ('two', 'args') // throws

* Add tests for Iterators and improve MapIterator

* Add built-in `type()` function

* Move the function call procedure to `Function::call()`

* Greatly simplify the resolve_reference function

* Add tests for the prototypical inheritance feature

* Add function `packToken::asFunc()`

* Add built-in function `extend(obj)`

This function allow users to play with the prototipical
inheritance feature. The function will return a new object whose
parent (i.e. prototype) is `obj`.

* Move TokenMap function implementations to objects.cpp

* Add `map.instanceof(other_map)` function
2016-08-30 15:21:29 -04:00
Vinícius Garcia
a61a241241 Almost a complete programming language core (#24)
* Fix bug of treating characters `'` and `"` as operators

* Fix print() so it can print anything not only strings

* Remove `print()` tests so stdout is not polluted

* Make the expression `pow(2,+2) and pow(2,-2) work

* Add literals: None, True and False, with capital letters

* Replace `^` operator for `**`

* Improve the reference resolving mechanism

* Fix Travis build

* Major refactor: Add prototypical inheritance

This commit makes the default Map class compatible
with prototypical inheritance.

The old TokenMap_t was replaced by the class TokenMap.

Since all TokenMaps now work as a hierarchy of maps,
the Scope class was also replaced by the the TokenMap class.

The old Scope::default_global()
was replaced by TokenMap::default_global()

Since now all maps have a parent map, a static Map was created
to occupy the top of the hierarchy: TokenMap::base_map()

By default any map inherits from TokenMap::default_global().

If you want an empty TokenMap, use instead the Object class.

* Make it possible for evaluation to return a reference

Before this commit all references were resolved before
being returned, and there was no way to get to them.

Now the calculator::eval() function has an optional
argument: `keep_refs`, which is set by default to false.

If set to true this function will return the result
of its evaluation without resolving its reference.

It can be used to parse names like: a.b.c['d'],
and allow the library user to add or edit information
of this map.

* Fix Travis build

* Prepare to add more complex types

* Refactor RefToken to work with complex types

* Add `this` to functions local scope

* Add support to type specific functions, e.g.: 'str'.len()

Before this commit it was not possible to link functions
to objects other than MAPs, so it would not be possible
to add functions such as:

- `'str'.len()` for the STR type.
- or `(1,2,3).join(',')` for the TUPLE type.

Now it is possible. This feature is possible because of 2
new structures:

1. Now we have a static std::map<tokType, Object> that
   maps a Token type to an Object which is a packToken map.
2. The `this` attribute that was added on the last commit.

Now everytime the calculator::calculate function finds
any type of Token (except MAP) followed by a '.' operator
and a string `str`.
It will search on the tokType map to see if there is a
function named `str` for this type.

* Major commit: Add reference counting to Map instances

This commit add a reference counting system for automatically
deleting maps that are not used anymore. This will allow our
users to declare their own maps and use them with no risk
or memory leaking.

This commit adds the template pack<T> that wraps any type T.
The pack<TokenMap>() instance was typedef'd as packMap.

A packMap can me initialized with no arguments and it will
manage a pointer to a TokenMap*. If you copy a packMap
the reference counter is increase, if you delete a packMap
it is decreased. If it gets to 0, the original TokenMap* is
also deleted.

Secondary changes:

- The TokenMap constructor with no arguments now sets its parent
  attribute to TokenMap::base_map instead of TokenMap::default_global.

It means that a TokenMap() will no have access by default to variables
declared on TokenMap::default_global. But instead will be really empty.

- The Object class that inherited from TokenMap was changed:

  * Now it sets TokenMap::default_global as it parent by default.
  * Now it is named `class GlobalScope` which is a more consistent name.

So if you want to declare a Map with access to the global scope
now you should use the `GlobalScope class`, if you just want
an empty map you should use the `TokenMap class`.

If you want to insert a map into a TokenMap or GlobalScope,
you should declare it as a packMap(), e.g.:

  GlobalScope map;
  map["sub_map"] = packMap()

But it would also work if you did like this:

  GlobalScope map;
  TokenMap sub_map;
  map["sub_map"] = packMap(&sub_map);

* Make packToken::asMap and ::asString to return by reference

* Fix bug on assignment operation on maps

* Add support for `closures` just like JavaScript.

This change required that all the references to `TokenMap*` on
the calculator class were replaced by `packMap`.

This was an important change because now the local scope of any
function defined within a calculator expression will keep existing
for as long as there is a reference of it.

This allow this language to support de definition of `closures` by
our users, just like JavaScript does.

* Fix Travis Build

* Add the LIST type and the packList class

Now we finally have lists! They are objects like maps and
are passed by reference, implying they also need memory management.

To solve this the same template: `pack<T>` class is used to manage
memory with a reference counting system.

----

Please note that the reference counting system we use has a problem:
It does not get rid of cycles, e.g.: a[0] = b; b[0] = a;

We need to plan a way to check for existence of unreachable
memory from time to time.

(Note that this problem also exist with maps)

----

Lists also have 3 functions associated with them that are
tested and work:

- list.push(item)
  * add an item to the end of the list.
- list.pop() or list.pop(idx)
  * remove an item from the end of the list
  * or remove an item whose index is idx.
- list.len()
  * return the current length of the list.

They are all tested and work.

* Small refactor: Move TokenMap and TokenList to objects.{cpp,h}

* Fix Travis Build

* Add multiple arguments support for functions

Now every function will receive at least 2 arguments:

- "this", but thats old news
- "arglist" that contain all the extra args that did not
  match the normal required arguments of the function.

This is different from the "arguments" Tuple of Javascript in
that it won't contain all the arguments, but instead only
the one that were not named by the function argument names.

It is simillar to the *largs arguments of Python.

In future we might change this behavior to work even more like
Python, i.e. only pass this argument if the user require it
with an argument named "*largs" or something with an asterisk
on the beginning.

Also:

- Add the sum() built-in function to test this feature.
- Improve the print() built-in function with this feature.

* Fix bug with parentesis expressions: list.push((1,2))

* Add built-in map and list constructors

* Add the Iterator abstract class

This class requires the implementation of:

- packToken* next()
- void reset()

Thus allowing any subclass to be iterable.

It should also be used as return type for generator
functions in future.

Currently the TokenMap class and the TokenList class inherit from
the Iterator class.

The Tuple class should also inherit from it in future.

* Make packMap and packList inherit from Iterator class

* Revert "Make packMap and packList inherit from Iterator class"

Reverting this last commit since it made things
more complicated, less efficient and didn't really had
the effect I wanted.

This reverts commit 8a005fb4990c70c4909c543191d6282bacd01b7b.
2016-07-30 16:57:06 -04:00
Brandon Amos
c776455095 Merge. 2016-07-21 17:32:18 -04:00
Vinícius Garcia
465821fa33 Fix Travis build 2016-07-21 14:17:00 -03:00
Vinícius Garcia
7c2b42b13c Refactor Function class so it is possible to extend it
Now Function is an abstract class. The built-in function
are instances of CppFunction which inherits from Function.

Now it is possible to have a client code defining a new type of
function, e.g.: user defined function, generators, class constructors etc.
2016-07-21 13:44:41 -03:00
Vinícius Garcia
2cfdf11e32 Improve float built-in function 2016-07-20 23:31:24 -03:00
Vinícius Garcia
9c0097d102 Add built-in functions: str(), float() and eval() 2016-07-20 19:37:01 -03:00
Vinícius Garcia
d5870affdc Add optional name attribute to Function class 2016-07-19 22:29:40 -03:00
Vinícius Garcia
e4ebe719cd Some refactoring and bug fixing (#22)
* Remove redundant calculator::compile(const char*, OppMap_t)

* Add support for calculator to work as a slave parser

As a slave parser I mean it will parse until a specified delimiter
and report back the pointer of where it has stopped.

This way another class can the calculator constructor to parse
or evaluate a sequence of expressions.

* Add static calculator::str() implementation for help debug

* Add an arguments validation check at calculator::toRPN()

* Minor refactor: Move calculator::scope_empty to Scope::empty

* Set Function string argument to `const char*`

* Update files to satisfy Travis CI rules

* Move Function::default_functions to Scope::default_global

The TokenMap_t Function::default_functions was used as base
map for all Scope instances, and represented the global scope.

It is more coherent to keep it with the name default_global
and defined as a static member of Scope class.

Now any other class that needs to add something to the global
scope can just use Scope::default_global.

* Make packToken::str(TokenBase*) accept const argument

* Fix memory leak problem on Reference Token management

* Prevent bug called "static initialization order fiasco"

This bug is better explained here:

 - https://isocpp.org/wiki/faq/ctors#static-init-order

Short version:

It is caused when the compiler initializes static objects in
a random order. And one of these objects depend on the initialization
of another one.

In our project the singleton class Function::Startup depends
on the TokenMap_t Scope::default_global.

It might cause no bug if we are lucky with the init order the
compiler chooses. But might cause big problems otherwise.

This commit fix this problem so we don't need to depend on lucky.

* Optimize calculator::toRPN loop

* Update README.md features section

* Update quote escaping for string literals

Now the user can type \\n and it will be converted to \n.

It also works for \\t, but nothing happens with other characters
like: \\f or \\o

Also add more tests for the string section.

* Fix bug on string escaping

* Add RAII_TokenQueue_t class to facilitate rpn management

Since C++ does not allow a finally block it is hard to
be sure something will be dealloc'd even when exceptions are
thrown.

The function calculator::calculate(char* expr, ...)
needed to have a catch for each possible exception type thrown
by its internal function calls (where a single finally
block would have done the job)

The only alternative encouraged by C++ is the RAII idiom
so the RAII_TokenQueue_t was built.

This new class should be used with care, but it has reduced the
number of explicit calls to cleanRPN which is good.

* Add valgrind check (make check) to Makefile

* Fix () operator so m.a(arg) works

* Fix `print()` so that it will call `print(None)`

* Add string representations to types FUNC and TUPLE
2016-07-18 12:11:02 -04:00
Vinícius Garcia
92e2bd6221 Fix print() so that it will call print(None) 2016-07-18 11:15:11 -03:00
Vinícius Garcia
ab7be02878 Prevent bug called "static initialization order fiasco"
This bug is better explained here:

 - https://isocpp.org/wiki/faq/ctors#static-init-order

Short version:

It is caused when the compiler initializes static objects in
a random order. And one of these objects depend on the initialization
of another one.

In our project the singleton class Function::Startup depends
on the TokenMap_t Scope::default_global.

It might cause no bug if we are lucky with the init order the
compiler chooses. But might cause big problems otherwise.

This commit fix this problem so we don't need to depend on lucky.
2016-07-15 22:10:42 -03:00
Vinícius Garcia
3fb964195d Move Function::default_functions to Scope::default_global
The TokenMap_t Function::default_functions was used as base
map for all Scope instances, and represented the global scope.

It is more coherent to keep it with the name default_global
and defined as a static member of Scope class.

Now any other class that needs to add something to the global
scope can just use Scope::default_global.
2016-07-15 14:51:36 -03:00
Vinícius Garcia
61f00ecfb8 Update files to satisfy Travis CI rules 2016-07-15 01:28:15 -03:00
Vinícius Garcia
726182a8ec Set Function string argument to const char* 2016-07-15 01:04:36 -03:00
Brandon Amos
21eb0d7f99 Add abs to resolve #2. 2016-07-10 08:34:03 -04:00
Vinícius Garcia
f62d717479 Add <stdexcept> to functions.cpp 2016-07-10 01:56:29 -03:00
Vinícius Garcia
80f29955f5 Fix style to conform with Travis suggestions 2016-07-10 01:30:04 -03:00
Vinícius Garcia
9ea4e26f2c Add TUPLE type and functions with multiple arguments
The function implementation is not yet complete,
there are still some caveeats for example:

- Functions with no parameters will have an untested behavior.
- If a function receive a tuple as argument it will believe it
  has received a list of parameters.
- If there are more arguments than expected the extra ones
  can not be accessed.

One case that is already handled is the case when you have
less arguments than expected. In this case the remaining
arguments will be filled with packToken::None copies.
2016-07-09 17:45:18 -03:00
Vinícius Garcia
7b7e541d43 Add builtin function support
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.
2016-07-09 13:04:47 -03:00