Files
cparse/packToken.cpp
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

214 lines
5.3 KiB
C++

#include <sstream>
#include <string>
#include <iostream>
#include "./shunting-yard.h"
#include "./packToken.h"
#include "./shunting-yard-exceptions.h"
const packToken packToken::None = packToken(TokenNone());
packToken& packToken::operator=(int t) {
delete base;
base = new Token<double>(t, NUM);
return *this;
}
packToken& packToken::operator=(double t) {
delete base;
base = new Token<double>(t, NUM);
return *this;
}
packToken& packToken::operator=(const char* t) {
delete base;
base = new Token<std::string>(t, STR);
return *this;
}
packToken& packToken::operator=(const std::string& t) {
delete base;
base = new Token<std::string>(t, STR);
return *this;
}
packToken& packToken::operator=(const packToken& t) {
delete base;
base = t.base->clone();
return *this;
}
// Used mainly for testing
bool packToken::operator==(const packToken& token) const {
if (token.base->type != base->type) {
return false;
} else {
// Compare strings to simplify code
return token.str().compare(str()) == 0;
}
}
TokenBase* packToken::operator->() const {
return base;
}
std::ostream& operator<<(std::ostream &os, const packToken& t) {
return os << t.str();
}
packToken& packToken::operator[](const std::string& key) {
if (base->type != MAP) {
throw bad_cast(
"The Token is not a map!");
}
return (*static_cast<Token<packMap>*>(base)->val)[key];
}
const packToken& packToken::operator[](const std::string& key) const {
if (base->type != MAP) {
throw bad_cast(
"The Token is not a map!");
}
return (*static_cast<Token<packMap>*>(base)->val)[key];
}
packToken& packToken::operator[](const char* key) {
if (base->type != MAP) {
throw bad_cast(
"The Token is not a map!");
}
return (*static_cast<Token<packMap>*>(base)->val)[key];
}
const packToken& packToken::operator[](const char* key) const {
if (base->type != MAP) {
throw bad_cast(
"The Token is not a map!");
}
return (*static_cast<Token<packMap>*>(base)->val)[key];
}
bool packToken::asBool() const {
switch (base->type) {
case NUM:
return static_cast<Token<double>*>(base)->val != 0;
case STR:
return static_cast<Token<std::string>*>(base)->val != std::string();
case MAP:
case FUNC:
return true;
case NONE:
return false;
case TUPLE:
return static_cast<Tuple*>(base)->tuple.size() != 0;
default:
throw bad_cast("Token type can not be cast to boolean!");
}
}
double packToken::asDouble() const {
if (base->type != NUM) {
throw bad_cast(
"The Token is not a number!");
}
return static_cast<Token<double>*>(base)->val;
}
std::string& packToken::asString() const {
if (base->type != STR && base->type != VAR && base->type != OP) {
throw bad_cast(
"The Token is not a string!");
}
return static_cast<Token<std::string>*>(base)->val;
}
packMap& packToken::asMap() const {
if (base->type != MAP) {
throw bad_cast(
"The Token is not a map!");
}
return static_cast<Token<packMap>*>(base)->val;
}
packList& packToken::asList() const {
if (base->type != LIST) {
throw bad_cast(
"The Token is not a list!");
}
return static_cast<Token<packList>*>(base)->val;
}
std::string packToken::str() const {
return packToken::str(base);
}
std::string packToken::str(const TokenBase* base) {
std::stringstream ss;
TokenMap::TokenMap_t* tmap;
TokenMap::TokenMap_t::iterator m_it;
TokenList::TokenList_t* tlist;
TokenList::TokenList_t::iterator l_it;
const Function* func;
bool first;
std::string name;
if (!base) return "undefined";
if (base->type & REF) {
base = static_cast<const RefToken*>(base)->value;
name = static_cast<const RefToken*>(base)->key.str();
}
switch (base->type) {
case NONE:
return "None";
case OP:
return static_cast<const Token<std::string>*>(base)->val;
case VAR:
return static_cast<const Token<std::string>*>(base)->val;
case NUM:
ss << static_cast<const Token<double>*>(base)->val;
return ss.str();
case STR:
return "\"" + static_cast<const Token<std::string>*>(base)->val + "\"";
case FUNC:
func = static_cast<const Function*>(base);
if (func->name.size()) return "[Function: " + func->name + "]";
if (name.size()) return "[Function: " + name + "]";
return "[Function]";
case TUPLE:
ss << "(";
first = true;
for (const TokenBase* token : static_cast<const Tuple*>(base)->tuple) {
if (!first) {
ss << ", ";
} else {
first = false;
}
ss << str(token);
}
ss << ")";
return ss.str();
case MAP:
tmap = &(static_cast<const Token<packMap>*>(base)->val->map);
if (tmap->size() == 0) return "{}";
ss << "{";
for (m_it = tmap->begin(); m_it != tmap->end(); ++m_it) {
ss << (m_it == tmap->begin() ? "" : ",");
ss << " \"" << m_it->first << "\": " << m_it->second.str();
}
ss << " }";
return ss.str();
case LIST:
tlist = &(static_cast<const Token<packList>*>(base)->val->list);
if (tlist->size() == 0) return "[]";
ss << "[";
for (l_it = tlist->begin(); l_it != tlist->end(); ++l_it) {
ss << (l_it == tlist->begin() ? "" : ",");
ss << " " << l_it->str();
}
ss << " ]";
return ss.str();
default:
return "unknown_type";
}
}