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
c5b64fb5b0 Add template packToken::as<T>() to allow custom type casts
This new template allow users to define custom type casts for
their own types, e.g.:

In `my_type.h`:

```C++
class myType { ... };

template<> myType& packToken::as<myType>() const;
```

In `my_type.cpp`:

```C++
template <>
myType& packToken::as<myType>() const {
  if (base->type != MY_TYPE_CODE) {
    throw bad_cast(
        "The Token is not a myType!");
  }
  return *static_cast<myType*>(base);
}
```
2018-03-02 00:01:34 -03:00
Vinícius Garcia
f1ddc86004 Remove packToken::operator TokenBase*() for safety
This operator caused implicit conversions to TokenBase* on
unexpected situations.

A specially problematic one was when comparing a packToken with
a boolean. Old compilers instead of converting the boolean to
packToken would also consider converting the packToken and the
boolean to `TokenBase*`, which was crazy but anyway.

This bug was problematic because it was easy to occur and would
pop up only when using an old gcc versions (tested on gcc 4.8).
2017-06-28 00:31:21 +00:00
Vinícius Garcia
5bccca9a43 Expose an API for customizing packToken::str()
Now it is possible to set `packToken::str_custom()`
to a function pointer with a compatible signature:

```C++
std::string (*strFunc_t)(const TokenBase* base, uint32_t nest);
```

This function may have 2 types of return values:

- Empty string: Give up and allow the normal `packToken::str()`
  to finish buiding the string.

- Any other string will be used as the
  string representation for that Token.

To illustrate this an example was added to:

- `builtin-features/functions.h`

That checks for an "__str__" attribute on every TokenMap
and if it exists and is a function it uses that function
to build the string.
2017-05-14 01:55:06 -03:00
Vinícius Garcia
be451335d5 Fix packToken::str() function for cyclic structures #31 2017-05-09 08:53:25 -03:00
Vinícius Garcia
985fe62019 Add type BOOL and related operations
- Add a bool constructor to the packToken
- Add a BOOL case to:
  + packToken::str()
  + packToken::asReal()
  + packToken::asInt()
  + built-in function `type()`
- Add packToken::asBool() function.
- Add tests to check the changes
2017-05-09 08:30:41 -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
1336553282 A lot of refactors, some optimizations and {} and [] JSON constructors (#44)
* Simplify `handle_op()` and `handle_unary()` functions

Now both receive an rpnBuilder as argument, instead of receiving
several different variables.

`handle_unary()` now writes to `data->lastTokenWasUnary()` instead
of returning a true/false argument to be written on it outside
the function as it was before. The new return type of the
function is void.

* Join the functions `handle_unary` and `handle_op`

Since they were always called together and did almost the same
thing there was no reason to keep them separated.

* Minor refactor - Move `opPrecedence` into `rpnData`

Now the function `handle_op` requires only 2 arguments:

- const char* expr
- rpnBuilder* data

* Expose `handle_op` to API

`handle_op()` function was exposed to API so that it could be used
on custom reserved word parsers defined by our users.

* Add the builtin map constructor operator: '{}'

Now it is possible to create maps just by writing:

```C++
  calculator::calculate("M = { 'my':'map' }");
```

* Copy `map` and `list` constructors to `objects.*`

These constructors were defined as CppFunctions on
`builtin-features.cpp`, now that we are defining
the implicit constructors for map: `{}` and list: `[]` it
was necessary to define it on someplace the user could not change.

The original code on `builtin-features.cpp` is unchanged. The user
can still overwrite his own definition of the builtin `map` and `list`
functions, as he wish.

* Add list implicit constructor `[1,2,3]`

Now you can declare a new list as you would in JavaScript:

```C++
  calculator::calculate("L = [1,2,3]");
```

* Add logo to repository

* Add move constructor to packToken class

* Move some functions into the rpnBuilder class

The functions:

- `handle_op()`
- `handle_unary()`
- `cleanRPN()`

were moved inside the rpnBuilder class, allowing now to
use `data.handle_op("+")` instead of `handle_op("+", &data)`.

More functions and functionalities should be moved into this class
in future, since we can use it to decouple the rpn building process
from the calculator class.

* Minor refactor: Move open/close bracket code to functions

* Minor refactor - move 2 functions in `builtin-features.cpp`

* Make public the static functions: toRPN and calculate

These 2 functions are useful to be used on the user defined
reserved word parsers, as such they are now available
to be called outside the calculator class.

* Refactor: Decouple internal variables of calculate()

Now the internal variables of the calculate function are
joined together on a struct called "evaluationData".

It can then be exposed for the user to access it in future commits.

* Refactor: Expose calculator variables to Operation::exec()

Now the `Operation::exec` function's signature is:

```C++
  packToken exec(const packToken& left, const packToken& right,
                 const evaluationData* data);
```

The std::string op (that was before this commit the second argument
of the exec() function) is now available inside the evaluationData type.

This struct also contains several other internal variables used
by the calculator::calculate() function. This commit thus allows
more power and flexibility to user Operations.
2016-11-23 15:54:19 -02: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
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
Vinícius Garcia
465821fa33 Fix Travis build 2016-07-21 14:17:00 -03:00
Vinícius Garcia
b07f4232ac Make packToken(TokenBase*) public
It was set as private because it should be used with care,
since an unaware user might forget that the TokenBase* memory
will be deleted once the packToken is destroied.

But since this is a necessary feature of the API it is better
to stay public and with the `explicit` modifier on it.
2016-07-21 13:56:53 -03:00
Vinícius Garcia
c3bb8a1141 Simplify class packToken and make it more robust 2016-07-20 19:21:48 -03:00
Vinícius Garcia
098770677f Make packToken::str(TokenBase*) accept const argument 2016-07-15 17:46:58 -03:00
Vinícius Garcia
ad5f28c5ce Fix style 2016-07-10 01:44:23 -03:00
Vinícius Garcia
80f29955f5 Fix style to conform with Travis suggestions 2016-07-10 01:30:04 -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
Vinícius Garcia
1ee61ce997 Add asign function to Scope 2016-07-08 22:16:55 -03:00
Brandon Amos
9d84f72b04 Use Google code style. Add cpplint and cppcheck to Travis. 2016-06-27 15:01:44 -04:00
Vinícius Garcia
9ea1e5d3c8 Improve some comments 2016-06-26 10:05:54 -03:00
Vinícius Garcia
4b40f1b6cb Make packToken(TokenBase*) less error prone
packToken(TokenBase*) not only builds a packToken but also
gets responsible for dellocating it, and this is not a normal
class behavior, since it could lead to a error prone code like this:

int main() {
  TokenBase* b = new Token<double>(10, NUM);
  packToken p = b;

    ... some code here ...

  delete b;

    ... some more code ...

  return 0; // Seg fault.
}

This commit makes this function private and explicit,
and only accessible from inside the class calculator which is
now friend of class packToken.

It was done to guarantee that only main developers have need
to fully comprehend this constructor behavior avoiding headaches.
2016-06-26 04:52:29 -03:00
Vinícius Garcia
21565f44cb Add static str() function to packToken 2016-06-05 12:50:54 -03:00
Vinícius Garcia
8bc48c01e0 Add 2 utility functions to packToken
The functions are:
- bool packToken::asBool()
- packToken::operator TokenBase*()
2016-06-02 12:57:28 -03:00
Vinícius Garcia
4605387411 Add subscript operator to packToken to simplify MAP access 2016-04-25 12:24:54 -03:00
Vinícius Garcia
36866d0af6 Adapt packToken to work with the MAP type 2016-04-25 11:50:49 -03:00
Vinícius Garcia
03b4e17adc Update packToken to fit strings 2016-04-20 14:28:35 -03:00
Vinícius Garcia
976ef66292 Add copy assignment operator to packToken 2016-04-18 15:36:17 -03:00
Vinícius Garcia
0bb17555b7 Replace the token map value class for the packToken type
This change allow to the user of the `TokenMap_t` to:
- Implicit instantiate a BaseToken* from a double.
- Explicit (and safely) convert a BaseToken* to a double.
- Make use of `cout << map["var"]`
- Make use of a serialization function `str()`

The packToken class is not intended to be used on the internals
of the calculate and compile functions, because it would add
some unnecessary function calls everytime a Token is accessed,
but it is useful to simplify the Token access for the API user.
2016-04-18 15:03:41 -03:00
Vinícius Garcia
e88858c1b9 Add first version of the TokenBase* facade: packToken 2016-04-18 05:24:26 -03:00