Giter Club home page Giter Club logo

chaiscript's Introduction

Master Status: Linux Build Status Windows Build status codecov.io

Develop Status: Linux Build Status Windows Build status codecov.io

ChaiScript

http://www.chaiscript.com

(c) 2009-2012 Jonathan Turner (c) 2009-2017 Jason Turner

Release under the BSD license, see "license.txt" for details.

Introduction

Gitter

ChaiScript is one of the only embedded scripting language designed from the ground up to directly target C++ and take advantage of modern C++ development techniques, working with the developer how they would expect it to work. Being a native C++ application, it has some advantages over existing embedded scripting languages:

  1. It uses a header-only approach, which makes it easy to integrate with existing projects.
  2. It maintains type safety between your C++ application and the user scripts.
  3. It supports a variety of C++ techniques including callbacks, overloaded functions, class methods, and stl containers.

Requirements

ChaiScript requires a C++17 compiler to build with support for variadic templates. It has been tested with gcc 7 and clang 6 (with libcxx).

Installation using vcpkg

You can download and install ChaiScript using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install chaiscript

The ChaiScript port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Usage

  • Add the ChaiScript include directory to your project's header search path
  • Add #include <chaiscript/chaiscript.hpp> to your source file
  • Instantiate the ChaiScript engine in your application. For example, create a new engine with the name chai like so: chaiscript::ChaiScript chai
  • The default behavior is to load the ChaiScript standard library from a loadable module. A second option is to compile the library into your code, see below for an example.

Once instantiated, the engine is ready to start running ChaiScript source. You have two main options for processing ChaiScript source: a line at a time using chai.eval(string) and a file at a time using chai.eval_file(fname)

To make functions in your C++ code visible to scripts, they must be registered with the scripting engine. To do so, call add:

chai.add(chaiscript::fun(&my_function), "my_function_name");

Once registered the function will be visible to scripts as "my_function_name"

Examples

ChaiScript is similar to ECMAScript (aka JavaScript(tm)), but with some modifications to make it easier to use. For usage examples see the "samples" directory, and for more in-depth look at the language, the unit tests in the "unittests" directory cover the most ground.

For examples of how to register parts of your C++ application, see "example.cpp" in the "samples" directory. Example.cpp is verbose and shows every possible way of working with the library. For further documentation generate the doxygen documentation in the build folder or see the website http://www.chaiscript.com.

The shortest complete example possible follows:

/// main.cpp

#include <chaiscript/chaiscript.hpp>

double function(int i, double j)
{
  return i * j;
}

int main()
{
  chaiscript::ChaiScript chai;
  chai.add(chaiscript::fun(&function), "function");

  double d = chai.eval<double>("function(3, 4.75);");
}

chaiscript's People

Contributors

alekmosingiewicz avatar arbmind avatar arcorocks avatar axelstudios avatar berndamend avatar christiankaeser avatar clanmills avatar draghan avatar elynx avatar ftk avatar guoyunhe avatar iohannrabeson avatar ktm avatar lefticus avatar mlamby avatar mlang avatar nixman avatar njlr avatar raptorfactor avatar robloach avatar rollbear avatar sirnate0 avatar sophiajt avatar stephenberry avatar svenstaro avatar totalgee avatar tw1ddle avatar vrennert avatar windoze avatar zemasoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chaiscript's Issues

Switch branch <-> Cx

Master needs to becoming the Cx branch, while the current master needs to be the pre-C++11 work.

Update any weblinks

Make sure links between documentation / github / chaiscript.com are correct and make sense.

Save and restore Stack on state swapping

The Stack is not saved and restored when the state of a chaiscript instance is changed.

This way different chaiscripts share the same variables, which IMHO should not be the case.

Update Cx readme.txt

The readme.txt for Cx uses an example that's out of date for the Cx branch. Needs to be updated to include using the stdlib.

ChaiScript not working cleanly with msvc x64

I've been trying to use ChaiScript when compiling for x64 with Windows SDK 7.1

I have been getting numinous warning such as:

1> d:\users\cameron garnham\documents\dev\open-transactions\include\chaiscript\dispatchkit/boxed_number.hpp(185) : see reference to function template instantiation 'chaiscript::Boxed_Value chaiscript::Boxed_Number::const_binary::go<LHS,RHS>(chaiscript::Operators::Opers,const T &,const U &,const chaiscript::Boxed_Value &)' being compiled
1> with
1> [
1> LHS=uint64_t,
1> RHS=char,
1> T=uint64_t,
1> U=char
1> ]
1> d:\users\cameron garnham\documents\dev\open-transactions\include\chaiscript\dispatchkit/boxed_number.hpp(174) : while compiling class template member function 'chaiscript::Boxed_Value chaiscript::Boxed_Number::Go<LHS,RHS,Float>::go(chaiscript::Operators::Opers,const chaiscript::Boxed_Value &,const chaiscript::Boxed_Value &)'
1> with
1> [
1> LHS=uint64_t,
1> RHS=char,
1> Float=false
1> ]
1> d:\users\cameron garnham\documents\dev\open-transactions\include\chaiscript\dispatchkit/boxed_number.hpp(228) : see reference to class template instantiation 'chaiscript::Boxed_Number::Go<LHS,RHS,Float>' being compiled
1> with
1> [
1> LHS=uint64_t,
1> RHS=char,
1> Float=false
1> ]

Can I please have some help with this error.

Different dynamic objects with same attribute name fails.

problem

In case there is two different objects with same attribute name the engine ignore the second one.

diagnosis:

It seems like there is bug in Attr_Decl_AST_Node.
Attr_Decl_AST_Node add the attribute as Proxy_Function_Impl so it looks like the operator == return true(ignore the object type name).

in the function bool add_function(const Proxy_Function &t_f, const std::string &t_name) under dispatchkit
((_t_f) == *(_itr2)) return true without

Hope my diagnosis is correct.

example:

//obj1
attr obj1::Height;
def obj1::obj1() {
this.reset();
}
def obj1::reset() {
this.Height = 0;
}

//obj2
attr obj2::Height;
def obj2::reset() {
this.Height = 0;
}
def obj2::obj2() {
this.reset();
}
var c6 := obj1();
var c7 := obj2();

Use std::move where applicable

std::move could be used to move Boxed_Value objects around and prevent copies in some places. Also, it could be used for moving the vector of arguments for function calls.

Variable/function redefinition issues

No errors are thrown when redefining a variable. It simply acts (as far as I can tell) as a normal assignment. I would expect an error here:

eval> auto y = 10;
10
eval> y
10
eval> auto y = 20;
20
eval> y
20

Interestingly, function definitions have a similar problem. No error is thrown, but instead of acting as a new definition, it's silently ignored:

eval> def foo(x) { return x + 1; }
eval> foo(4)
5
eval> def foo(x) { return x + 2; }
eval> foo(4)
5

Document reflection

Currently I can't find any resources on how to use reflection in Chaiscript. Could you please write up some?

Support switch statements

Allow the following:

switch (myvalue)
{
   case 1:
     // do something
     break;
   case 2:
     // do something else
    break;
};

To be consistent with C++, this would require support for labels and break statements. The labels can be emulated, but the break statements and fall through would have to actually be supported.

Allow casting to container types

Support this:

std::vector<int> vec = m_chai<std::vector<int> >("[1,2,3,4]");

It will require tests in boxed_cast, but should be possible. Might be doable by using ranges somehow.

Build Failure on Mageia Linux

After I do "cmake .." and "make" I am getting:

shlomif@telaviv1:~/Download/unpack/prog/chai-script/ChaiScript/build$ make 
Scanning dependencies of target boxed_cast_test
[  5%] Building CXX object CMakeFiles/boxed_cast_test.dir/unittests/boxed_cast_test.cpp.o
Linking CXX executable boxed_cast_test
[  5%] Built target boxed_cast_test
Scanning dependencies of target chai
[ 11%] Building CXX object CMakeFiles/chai.dir/src/main.cpp.o
Linking CXX executable chai
/usr/bin/ld: CMakeFiles/chai.dir/src/main.cpp.o: undefined reference to symbol 'pthread_mutexattr_settype@@GLIBC_2.2.5'
/usr/bin/ld: note: 'pthread_mutexattr_settype@@GLIBC_2.2.5' is defined in DSO /lib64/libpthread.so.0 so try adding it to the linker command line
/lib64/libpthread.so.0: could not read symbols: Invalid operation
collect2: ld returned 1 exit status
make[2]: *** [chai] Error 1
make[1]: *** [CMakeFiles/chai.dir/all] Error 2
make: *** [all] Error 2

The "make VERBOSE=1" command line is:

/usr/bin/c++       CMakeFiles/chai.dir/src/main.cpp.o  -o chai -rdynamic -ldl -lboost_thread-mt -lreadline 

This is on the trunk in commit d2aba2e .

I am on Mageia Linux Cauldron (what will become Mageia Linux 3).

Regards,

-- Shlomi Fish

Explore def-use analysis for easy optimization of lookups

We should be able to speed up variable lookup dramatically in some cases by caching the def of identifiers we know statically at parse time. It may be as simple as a double-pointer to the currently definition of the variable (def's of variables aren't unique based on AST location, as in the case of var decls inside of loops).

Better exception catching

provide way to specify types of exceptions to catch and unwrap during eval, to shorten exception handling code in the C++ side.

Handling errors inside of eval with try/catch

try {
 eval("2 + \"bob\"");
}
catch (e) {
  print("got an exception!");
}

Currently, this prints out:

Error: "Can not find appropriate '+'" during evaluation at (EVAL 1, 1)
from break.chai (2, 3)
from break.chai (2, 3)

Despite the eyesore of the location being printed twice, it's clear we don't have enough control to grab the exception and handle it from inside ChaiScript itself.

Allow hashbang in first line

The chai interpreter should allow the first line of a passed script file to be a Hashbang. An example such line:

#!/usr/bin/env chai

This works without modification for many languages, since the octothorpe is a common character to indicate comments. This could be supported by ChaiScript in a number of ways:

  1. Allow comments to start with # in addition to // (this is probably not desired, given the goals of the language)
  2. Modify either load_file or do_eval in chaiscript_engine.hpp to check the first two characters in the file for #! and replace them with // .
  3. Modify main.cpp to do the same string modification as in 2, loading its own file and using chai.eval() instead of chai.eval_file().

Solution 3 here is the only solution that keeps the change entirely within the command-line interpreter, which might be desired.

Create any new ChaiScript examples needed

Make sure there are example scripts for common use cases. Unit tests count as well, but it might make sense to add new examples.

Make sure examples run during "make test" probably utilizing the same mechanism as the existing unit tests, in the CMakeLists.txt

Doesn't compile with -pedantic

Some constructs used in the library break standards conventions but could be worked around. For instance, the dlsym problem could be worked around by using reinterpret_cast(reinterpret_cast<intptr_t>(dlsym(...))).

Create more efficient Numeric + Numeric handler

This can reduce the number of methods for POD Numeric types to only 1 per operator and can be used as a shortcut handler to bypass dispatch on common operators. Should provide a large performance and compile time boost.

Note: this has to be done in such a way that it is both a shortcircuiting of dispatch, and available for dispatch so that - type operations are not broken.

Use constexpr where applicable

Initial thoughts are that at least the user_type<>() function could make use of constexpr to inform the compiler the value will always be the same and can be compiled.

Fix poor error handling with deep function calls

An error in OpenTransactions fails to report a proper error.

The gist of it is ChaiScript Function->ChaiScript Function->ChaiScript Method->ChaiScript Method->C++ Function call failure.

This error failed to report the c++ function and stopped at the method call.

Comparison of two short(uint16_t) numbers returns an incorrect result.

Problem :

Comparison of two short(uint16_t) numbers returns an incorrect result.

diagnosis:

It seems like it copy/paste issue.
file : chaiscript\include\chaiscript\dispatchkit\boxed_number.hpp
function: static Boxed_Value oper(Operators::Opers t_oper, const Boxed_Value &t_lhs, const Boxed_Value &t_rhs)
...
} else if (inp_ == typeid(boost::int16_t)) {
return oper_rhs<boost::int32_t, false>(t_oper, t_lhs, t_rhs);
.....

Should be changed to : oper_rhs<boost::int16_t, false>(t_oper, t_lhs, t_rhs);

sample:

#include <chaiscript/utility/utility.hpp>

class Test {
 public:
  Test() : value_(5) {}

  short get_value() { return value_; }

  short value_;
};

int main()
{

  chaiscript::ChaiScript chai;
  chai.add(chaiscript::user_type<Test>(), "Test");
  chai.add(chaiscript::constructor<Test()>(), "Test");

  chai.add(chaiscript::fun(&Test::get_value), "get_value");

  chai.eval("var t := Test();");
  chai.eval("if(t.get_value() == 5 ) { print(\"TRUE\"); } else { print(\"FALSE\"); } ");
}

Thanks Rafi

Can't add C functions?

pScript->chai.add(fun(&OT_API_CreateNym), "OT_API_CreateNym");
    pScript->chai.add(fun(&OT_API_AddServerContract), "OT_API_AddServerContract");
    pScript->chai.add(fun(&OT_API_AddAssetContract), "OT_API_AddAssetContract");

While trying to add functions declared as extern "C", I get this linker error:

Undefined symbols for architecture x86_64:
"_OT_API_CreateNym", referenced from:
RegisterAPIWithScript(OTScript&) in xmlrpcxx_client.o
"_OT_API_AddServerContract", referenced from:
RegisterAPIWithScript(OTScript&) in xmlrpcxx_client.o
"_OT_API_AddAssetContract", referenced from:
RegisterAPIWithScript(OTScript&) in xmlrpcxx_client.o

The problem doesn't occur with normal C++ functions, only C functions.

Fill eval_error with relevant information

Hi,

right now if one uses eval_file to execute a chai script and an eval_error occurs,
the variables filename, start_position and end_position are always empty.
Although it would be extremely helpful to know in which file and line the error occurred.

Is this planned in the future or did I miss some existing functionality?

Cheers
Markus

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.