29 Commits

Author SHA1 Message Date
Vinícius Garcia
50eda83e37 Add cpplink to make lint recipe 2025-06-09 10:07:55 -03:00
Enno Rehling
2702455fd1 add warning for signed/unsigned comparison.
fix broken negative indexing flagged by tests.
2022-11-13 16:50:16 +01:00
Vinícius Garcia
e223a129e1 Make ld -O1 option conditional to Linux builds (#87)
This was changed because this options is not recognized on macOS
and possibly Windows too.
2021-12-04 11:46:43 -03:00
Vinícius Garcia
46dc2995b0 Update Makefile default action to release instead of all 2018-10-29 00:22:35 -03:00
Vinícius Garcia
a098d40a46 Add some extra warning flags on makefile compilation recipe 2018-06-03 10:15:50 -03:00
Vinícius Garcia
baabeb6daf Simplify the release recipe of the Makefile
When creating the release version of `builtin-features.o` the
Makefile was including several files that were not needed, which
probably were slowing down the compilation process.

Now they were removed and the compilation should run a little faster.
2018-04-10 11:54:56 -03:00
Vinícius Garcia
d847917123 Fix changes on Makefile a problem on Makefile 2017-12-10 10:07:18 -02:00
Vinícius Garcia
7807dc6aed Update Makefile to watch changes in builtin-features/
Before this commit changin a `.h` file inside the
`builtin-features` directory would not cause the file
`builtin-features.cpp` to be recompiled.

Now making changes on that file will cause it to recompile as it
should be.
2017-12-09 22:53:18 -02:00
Vinícius Garcia
aa27a208ca Improve Makefile for allowing gdb to accept arguments 2017-11-14 18:47:24 -02:00
Vinícius Garcia
5201775e88 Rename objecs.h/cpp to containers.h/cpp
This change is just to make the file name self explanatory and
also because all structs inside these files are now subclasses
of the `Container` class, so the change makes sense.
2017-09-27 23:28:14 -03:00
Vinícius Garcia
f465747740 Add a simul recipe do Makefile that start cgdb
This is meant to be used for testing.
2017-05-27 00:00:16 -03:00
Vinícius Garcia
a412190cbe Rename builtin-operations.cpp to builtin-features.cpp (#43)
The reason for this change is just because the name `features`
fits a lot better the meaning of this file.

Also this change should be done now, as early as possible
while we still have few users.
2016-11-08 11:57:59 -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
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
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
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
Brandon Amos
32eee30029 Re-add delagated constructor and C++11. Bump Travis to gcc 4.8. 2016-07-10 14:16:25 -04:00
Brandon Amos
4594e3be7d Remove C++11 feature because Travis doesn't support it. 2016-07-10 13:53:48 -04:00
Brandon Amos
cb8865efb2 Bump to C++11. Add default functions to Scope() constructor. 2016-07-10 13:31:12 -04: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
b47ec33d95 Move catch main to separated file so tests compile a lot faster 2016-07-08 20:41:37 -03:00
Vinícius Garcia
e88858c1b9 Add first version of the TokenBase* facade: packToken 2016-04-18 05:24:26 -03:00
Vinícius Garcia
bfd60ff166 Force Makefile to recompile all *.o on any .h change 2016-03-08 00:37:21 -03:00
Brandon Amos
d905c2f172 Makefile: run->test 2016-02-26 17:56:04 -05:00
Vinícius Garcia
1d0cfc0d60 Improve Makefile with a make run command 2016-02-26 01:26:25 -03:00
Brandon Amos
a272eaeaeb Replace RPNExpression with std::queue. 2013-06-21 10:41:07 -07:00
Brandon Amos
1d7e56285d Small-scale code refactors, improvements, and comments. 2013-06-21 10:30:40 -07:00
Brandon Amos
c048bb8108 Add test cases and Makefile. 2013-06-11 06:25:37 -07:00