Compare commits
334 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
18d4984258 | ||
![]() |
845eb394ac | ||
![]() |
66b2adba5c | ||
![]() |
02db23e9e2 | ||
![]() |
fbef83ecb7 | ||
![]() |
88fbf41091 | ||
![]() |
897385953c | ||
![]() |
319f9e4de9 | ||
![]() |
2786156086 | ||
![]() |
e5f9dbb93b | ||
![]() |
61b8481514 | ||
![]() |
8a0ef143c9 | ||
![]() |
f1918f147d | ||
![]() |
0d238b1617 | ||
![]() |
d22a77503c | ||
![]() |
8dec35ba19 | ||
![]() |
a91c66d286 | ||
![]() |
8ecd3a084b | ||
![]() |
79e8af4f6e | ||
![]() |
de5822873b | ||
![]() |
d6b8e32373 | ||
![]() |
bbe89e61bc | ||
![]() |
87c29ebc91 | ||
![]() |
92c836c58a | ||
![]() |
58e5df0a9a | ||
![]() |
854737ea25 | ||
![]() |
8bd512a0af | ||
![]() |
deb4cb036f | ||
![]() |
cd8bead54a | ||
![]() |
637164e457 | ||
![]() |
9dd9ffec46 | ||
![]() |
ac0688a8d7 | ||
![]() |
e3feb05e05 | ||
![]() |
2ce55d81b3 | ||
![]() |
4e06478fb8 | ||
![]() |
46a669dab1 | ||
![]() |
d9a92a5148 | ||
![]() |
f6b6936348 | ||
![]() |
0b97fcb4df | ||
![]() |
eee5c19b6e | ||
![]() |
5cc4a758ab | ||
![]() |
7c2550ba74 | ||
![]() |
41d7842963 | ||
![]() |
13b35f2f47 | ||
![]() |
18c6ed71f0 | ||
![]() |
7ac22c7072 | ||
![]() |
c9c4f1add7 | ||
![]() |
65d054b36e | ||
![]() |
894063261e | ||
![]() |
80f576a2f3 | ||
![]() |
0a2b5d7a40 | ||
![]() |
660e978da3 | ||
![]() |
e90d49bb9d | ||
![]() |
13f53839c9 | ||
![]() |
65edf30ef0 | ||
![]() |
7ef1b81504 | ||
![]() |
3aee589274 | ||
![]() |
97081b1f33 | ||
![]() |
a758c86ba5 | ||
![]() |
5f661fad20 | ||
![]() |
811764e048 | ||
![]() |
0f9b1aaf92 | ||
![]() |
912379d58c | ||
![]() |
91c05f0e73 | ||
![]() |
906140ec78 | ||
![]() |
e75a354a04 | ||
![]() |
36173d277d | ||
![]() |
e1e48d732f | ||
![]() |
6e18aa3dcd | ||
![]() |
6a18862c79 | ||
![]() |
b3dafa385e | ||
![]() |
70cc1111f3 | ||
![]() |
2d353cb189 | ||
![]() |
67bad374a9 | ||
![]() |
bff5b8bce0 | ||
![]() |
2cdfac4e47 | ||
![]() |
0caa782437 | ||
![]() |
caa67e811c | ||
![]() |
c1318eb8b4 | ||
![]() |
3f87210dc5 | ||
![]() |
c3da778103 | ||
![]() |
5a92146d28 | ||
![]() |
3ab91356e5 | ||
![]() |
fa2a7045a7 | ||
![]() |
512d6b342d | ||
![]() |
4ab29013ec | ||
![]() |
3ae748c026 | ||
![]() |
d8c979b204 | ||
![]() |
74e719c053 | ||
![]() |
43dbd8ac78 | ||
![]() |
7b77af3736 | ||
![]() |
8b35434e6f | ||
![]() |
1e867f5760 | ||
![]() |
670eb0692b | ||
![]() |
4b9d2d130f | ||
![]() |
30affb8855 | ||
![]() |
22c2be835a | ||
![]() |
a39d70dbca | ||
![]() |
10986c159f | ||
![]() |
cfa42158af | ||
![]() |
054179ead3 | ||
![]() |
8a6a46d0d3 | ||
![]() |
efae821996 | ||
![]() |
31feab6053 | ||
![]() |
7ef12f634d | ||
![]() |
c6452c4bd6 | ||
![]() |
71de169e09 | ||
![]() |
329244759f | ||
![]() |
c5f20ea158 | ||
![]() |
58c62f6333 | ||
![]() |
7f037b26d4 | ||
![]() |
b1e357423f | ||
![]() |
3a904d9f74 | ||
![]() |
d838f7a6d4 | ||
![]() |
556e7ad916 | ||
![]() |
21253043d1 | ||
![]() |
f215cae866 | ||
![]() |
ea93903884 | ||
![]() |
f03189c168 | ||
![]() |
a122403c20 | ||
![]() |
e1fbf54e40 | ||
![]() |
2b80ca8cc5 | ||
![]() |
f4e4f92dae | ||
![]() |
4358564065 | ||
![]() |
a463ee5ff2 | ||
![]() |
cd015a8437 | ||
![]() |
8be4aa08db | ||
![]() |
edee892cad | ||
![]() |
b971ee44ad | ||
![]() |
b9ae4cd528 | ||
![]() |
4ec21ff552 | ||
![]() |
f5f99961c1 | ||
![]() |
f7086c10ec | ||
![]() |
3d19138c95 | ||
![]() |
35ac7342b6 | ||
![]() |
3f9b5081c6 | ||
![]() |
799b3ef388 | ||
![]() |
fe6694297f | ||
![]() |
e77ec4b16a | ||
![]() |
f070575205 | ||
![]() |
43d0d6199a | ||
![]() |
65c5178549 | ||
![]() |
c928e2992b | ||
![]() |
7fef086cab | ||
![]() |
791fd242e7 | ||
![]() |
e81b71ccc7 | ||
![]() |
ef7a785214 | ||
![]() |
f431d479fc | ||
![]() |
e11eca406d | ||
![]() |
7efb65a5c2 | ||
![]() |
39339d769a | ||
![]() |
7ac9ea7249 | ||
![]() |
7080f5d681 | ||
![]() |
22d994009e | ||
![]() |
567f911093 | ||
![]() |
5c98a5d6e7 | ||
![]() |
856b682e72 | ||
![]() |
faaa964565 | ||
![]() |
d8213a4206 | ||
![]() |
3a4421a57c | ||
![]() |
31fec2202c | ||
![]() |
13178e55e1 | ||
![]() |
968da650b2 | ||
![]() |
fb5ba0be26 | ||
![]() |
39a2c39d90 | ||
![]() |
70047424f9 | ||
![]() |
2805af1ed2 | ||
![]() |
e5a29ede5f | ||
![]() |
0c0df2c982 | ||
![]() |
4457df9ff5 | ||
![]() |
e601de9d18 | ||
![]() |
37b2ac2056 | ||
![]() |
645cdddd70 | ||
![]() |
ac8462fb67 | ||
![]() |
636c55493c | ||
![]() |
e2a2c14c0d | ||
![]() |
c418644a5b | ||
![]() |
fbf8f53e04 | ||
![]() |
a0c6366479 | ||
![]() |
15ffbd200a | ||
![]() |
1c6b2725b3 | ||
![]() |
95c124ca35 | ||
![]() |
1bd73884b2 | ||
![]() |
d3e4af433e | ||
![]() |
9f65303370 | ||
![]() |
391eaa9e11 | ||
![]() |
ed11f48847 | ||
![]() |
9dddb49850 | ||
![]() |
cca477dae6 | ||
![]() |
07352a16a3 | ||
![]() |
e14931f389 | ||
![]() |
f4a680a582 | ||
![]() |
e6c6223c5b | ||
![]() |
cbc61d898c | ||
![]() |
3a37ceedb7 | ||
![]() |
1bc968e788 | ||
![]() |
fe5a935abd | ||
![]() |
4e5c972e66 | ||
![]() |
d946cb7e9d | ||
![]() |
18bfead387 | ||
![]() |
4c015d7e44 | ||
![]() |
1122f2c818 | ||
![]() |
d2d752ecd4 | ||
![]() |
a18c701866 | ||
![]() |
9871604a48 | ||
![]() |
b1d12fdc91 | ||
![]() |
24e717d532 | ||
![]() |
1568fedebd | ||
![]() |
c88578d537 | ||
![]() |
9827345213 | ||
![]() |
c51d14fb13 | ||
![]() |
480761c1f7 | ||
![]() |
12e909d9aa | ||
![]() |
b1e892487f | ||
![]() |
720eabcb16 | ||
![]() |
1fde71f3f4 | ||
![]() |
90f8b77171 | ||
![]() |
315d7521a7 | ||
![]() |
ff177b5eaf | ||
![]() |
46fd7e9a58 | ||
![]() |
edd274ccce | ||
![]() |
a5b2ec3006 | ||
![]() |
cd3c0d4fd7 | ||
![]() |
3bdd79a3fd | ||
![]() |
b04e01cda7 | ||
![]() |
bad5384c96 | ||
![]() |
443902f787 | ||
![]() |
d3cdd6959d | ||
![]() |
9762e15460 | ||
![]() |
33897e2c0f | ||
![]() |
9528e44b88 | ||
![]() |
03746e7606 | ||
![]() |
50eace16da | ||
![]() |
8241e46680 | ||
![]() |
160f64e9c2 | ||
![]() |
593c6c68ee | ||
![]() |
991753a492 | ||
![]() |
7cdd772f2b | ||
![]() |
c5f837fd19 | ||
![]() |
7c244d25b5 | ||
![]() |
18fc4d419f | ||
![]() |
813fa055a3 | ||
![]() |
6a47846b84 | ||
![]() |
b0041217b0 | ||
![]() |
fedcd28ecc | ||
![]() |
b17c6b9748 | ||
![]() |
204d379176 | ||
![]() |
a754ce9eb6 | ||
![]() |
99b5f46a9e | ||
![]() |
394d8c3bf6 | ||
![]() |
4bdbcf30ff | ||
![]() |
63de0fd33c | ||
![]() |
0fbb7c44bd | ||
![]() |
5092713876 | ||
![]() |
f369afed77 | ||
![]() |
f23f0edc70 | ||
![]() |
daee00da95 | ||
![]() |
e2cdac0406 | ||
![]() |
cc44ec99ba | ||
![]() |
1bf3b1ed37 | ||
![]() |
f7b530ebae | ||
![]() |
b185e2e792 | ||
![]() |
73ec2abd43 | ||
![]() |
cfee4c6bc1 | ||
![]() |
2d4b9c0d93 | ||
![]() |
f522d3697c | ||
![]() |
48e96b2f3b | ||
![]() |
798908f127 | ||
![]() |
7e3127549f | ||
![]() |
4713325877 | ||
![]() |
7cc6a3cab9 | ||
![]() |
cba5731576 | ||
![]() |
b3656c95f5 | ||
![]() |
e9539dfee2 | ||
![]() |
4b40812e26 | ||
![]() |
ef8cd1f591 | ||
![]() |
46cdb89921 | ||
![]() |
3094ff6e3b | ||
![]() |
4d42d6ff33 | ||
![]() |
a427d2c1a9 | ||
![]() |
efb7a8d453 | ||
![]() |
6c4872eae9 | ||
![]() |
ff639a267d | ||
![]() |
94e4b671f3 | ||
![]() |
096c8aab50 | ||
![]() |
89186a86c8 | ||
![]() |
c8c1c65e8c | ||
![]() |
c5e1d5fa20 | ||
![]() |
91011695f0 | ||
![]() |
3a951cea99 | ||
![]() |
8620f4eaf9 | ||
![]() |
59ecf32f9b | ||
![]() |
541e453098 | ||
![]() |
0b780593a6 | ||
![]() |
2e7c5f413e | ||
![]() |
7e5b7cbd7a | ||
![]() |
c539e0b458 | ||
![]() |
1f011f3d5b | ||
![]() |
a136236179 | ||
![]() |
8840f06053 | ||
![]() |
00e4de774f | ||
![]() |
bc3a17b3b7 | ||
![]() |
4a57efde25 | ||
![]() |
cf94817869 | ||
![]() |
6775863415 | ||
![]() |
a3d4b6698a | ||
![]() |
0ff107a818 | ||
![]() |
ba6b392174 | ||
![]() |
5b424be4ed | ||
![]() |
669d6e9495 | ||
![]() |
9f614bba33 | ||
![]() |
0b789004e9 | ||
![]() |
0d3c90a245 | ||
![]() |
2f591a25a6 | ||
![]() |
4127a6ed41 | ||
![]() |
4e412c0f6a | ||
![]() |
370121a9ff | ||
![]() |
00ac8113c0 | ||
![]() |
72b6647718 | ||
![]() |
daacbaa9e0 | ||
![]() |
a5a1e3ee1b | ||
![]() |
5a5b2929b0 | ||
![]() |
82bd46bb1a | ||
![]() |
4d4c26bf73 | ||
![]() |
ac817ff33a | ||
![]() |
689143aba5 | ||
![]() |
9b733b2621 | ||
![]() |
727dc7b0d6 | ||
![]() |
3fc5f8e8e1 | ||
![]() |
aed493322b | ||
![]() |
8dbb43f45f | ||
![]() |
ec2f81c674 | ||
![]() |
724ffdcb20 | ||
![]() |
7c7e437b10 |
219
CMakeLists.txt
219
CMakeLists.txt
@@ -1,23 +1,212 @@
|
||||
cmake_minimum_required(VERSION 2.6)
|
||||
cmake_minimum_required(VERSION 2.8)
|
||||
|
||||
project(chaiscript)
|
||||
|
||||
SET (CMAKE_BUILD_TYPE gdb)
|
||||
SET (CMAKE_C_FLAGS_GDB " -Wall -ggdb")
|
||||
SET (CMAKE_CXX_FLAGS_GDB " -Wall -ggdb")
|
||||
option(MULTITHREAD_SUPPORT_ENABLED "Multithreaded Support Enabled" TRUE)
|
||||
option(BUILD_MODULES "Build Extra Modules (stl, reflection)" TRUE)
|
||||
option(BUILD_SAMPLES "Build Samples Folder" FALSE)
|
||||
|
||||
#SET (CMAKE_BUILD_TYPE rel)
|
||||
#SET (CMAKE_C_FLAGS_REL " -Wall -O3")
|
||||
#SET (CMAKE_CXX_FLAGS_REL " -Wall -O3")
|
||||
list(APPEND CPACK_SOURCE_IGNORE_FILES "${CMAKE_CURRENT_BINARY_DIR}")
|
||||
list(APPEND CPACK_SOURCE_IGNORE_FILES "\\\\.svn")
|
||||
list(APPEND CPACK_SOURCE_IGNORE_FILES "\\\\.git")
|
||||
list(APPEND CPACK_SOURCE_IGNORE_FILES ".swp")
|
||||
list(APPEND CPACK_SOURCE_IGNORE_FILES ".*~")
|
||||
|
||||
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/license.txt")
|
||||
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/readme.txt")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/description.txt")
|
||||
|
||||
set(CPACK_PACKAGE_VERSION_MAJOR 3)
|
||||
set(CPACK_PACKAGE_VERSION_MINOR 0)
|
||||
set(CPACK_PACKAGE_VERSION_PATCH 0)
|
||||
set(CPACK_PACKAGE_EXECUTABLES "chai;ChaiScript Eval")
|
||||
set(CPACK_PACKAGE_VENDOR "ChaiScript.com")
|
||||
set(CPACK_PACKAGE_CONTACT "contact@chaiscript.com")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "An embedded scripting language for C++")
|
||||
|
||||
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libboost-dev (>=1.36.0)")
|
||||
set(CPACK_DEBIAN_PACKAGE_SECTION "devel")
|
||||
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
|
||||
|
||||
set(CPACK_RPM_PACKAGE_LICENSE "BSD")
|
||||
set(CPACK_RPM_PACKAGE_GROUP "Programming")
|
||||
set(CPACK_RPM_PACKAGE_REQUIRES "boost-devel >= 1.36.0, boost-thread >= 1.36.0")
|
||||
|
||||
set(CHAI_VERSION ${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH})
|
||||
|
||||
configure_file(Doxyfile.in ${CMAKE_BINARY_DIR}/Doxyfile)
|
||||
|
||||
include(CTest)
|
||||
include(CPack)
|
||||
|
||||
FIND_LIBRARY(READLINE_LIBRARY NAMES readline PATH /usr/lib /usr/local/lib /opt/local/lib)
|
||||
|
||||
enable_testing()
|
||||
|
||||
|
||||
MESSAGE(STATUS "Detecting readline support")
|
||||
if (READLINE_LIBRARY)
|
||||
MESSAGE(STATUS "Found: ${READLINE_LIBRARY}")
|
||||
SET (READLINE_LIB readline)
|
||||
ADD_DEFINITIONS(/DREADLINE_AVAILABLE)
|
||||
else(READLINE_LIBRARY)
|
||||
MESSAGE(STATUS "Not Found")
|
||||
SET (READLINE_LIB )
|
||||
SET (READLINE_FLAG )
|
||||
endif(READLINE_LIBRARY)
|
||||
|
||||
IF(MSVC)
|
||||
ADD_DEFINITIONS(/W4)
|
||||
IF(CMAKE_CL_64)
|
||||
ADD_DEFINITIONS(/bigobj)
|
||||
ENDIF()
|
||||
ELSE()
|
||||
# -Wno-missing-field-initializers is for boost on macos
|
||||
ADD_DEFINITIONS(-Wall -Wextra -Wno-missing-field-initializers -Wshadow)
|
||||
ENDIF()
|
||||
|
||||
include_directories(include)
|
||||
|
||||
find_package(Boost 1.36.0)
|
||||
if (Boost_FOUND)
|
||||
include_directories(${Boost_INCLUDE_DIRS})
|
||||
add_executable(chaiscript_eval src/main.cpp)
|
||||
#add_executable(dispatchkit_test contrib/test/dispatchkit_test.cpp)
|
||||
target_link_libraries(chaiscript_eval ${Boost_LIBRARIES})
|
||||
install(TARGETS chaiscript_eval DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/bin)
|
||||
endif(Boost_FOUND)
|
||||
SET(Boost_ADDITIONAL_VERSIONS "1.44" "1.44.0" "1.43" "1.43.0" "1.42" "1.42.0" "1.41")
|
||||
SET(Boost_USE_MULTITHREADED ON)
|
||||
|
||||
if (MULTITHREAD_SUPPORT_ENABLED)
|
||||
find_package(Boost 1.36.0 COMPONENTS thread)
|
||||
|
||||
if (Boost_FOUND)
|
||||
link_directories( ${Boost_LIBRARY_DIRS} )
|
||||
else()
|
||||
message(FATAL_ERROR "Can not find Boost")
|
||||
endif(Boost_FOUND)
|
||||
else()
|
||||
ADD_DEFINITIONS(-DCHAISCRIPT_NO_THREADS)
|
||||
endif()
|
||||
|
||||
if (CMAKE_HOST_UNIX)
|
||||
SET(DYNAMIC_LOADER "dl")
|
||||
endif(CMAKE_HOST_UNIX)
|
||||
|
||||
if (MSVC)
|
||||
# Boost on MSVC does automatic linking
|
||||
SET(LIBS ${DYNAMIC_LOADER} ${READLINE_LIB})
|
||||
else()
|
||||
SET(LIBS ${DYNAMIC_LOADER} ${Boost_LIBRARIES} ${READLINE_LIB})
|
||||
endif()
|
||||
|
||||
if (CMAKE_COMPILER_2005)
|
||||
# vs2005 is a bit too loud about possible loss of data warnings
|
||||
# ADD_DEFINITIONS(/wd4244)
|
||||
endif()
|
||||
|
||||
include_directories(${Boost_INCLUDE_DIRS})
|
||||
include_directories(${Boost_INCLUDE_DIR})
|
||||
add_executable(chai src/main.cpp)
|
||||
target_link_libraries(chai ${LIBS})
|
||||
|
||||
if (BUILD_SAMPLES)
|
||||
add_executable(example samples/example.cpp)
|
||||
target_link_libraries(example ${LIBS})
|
||||
add_executable(memory_leak_test samples/memory_leak_test.cpp)
|
||||
target_link_libraries(memory_leak_test ${LIBS})
|
||||
endif()
|
||||
|
||||
|
||||
if (BUILD_MODULES)
|
||||
add_library(stl_extra MODULE src/stl_extra.cpp)
|
||||
target_link_libraries(stl_extra ${LIBS})
|
||||
|
||||
add_library(reflection MODULE src/reflection.cpp)
|
||||
target_link_libraries(reflection ${LIBS})
|
||||
set(MODULES stl_extra reflection)
|
||||
endif()
|
||||
|
||||
file(GLOB UNIT_TESTS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/unittests/ ${CMAKE_CURRENT_SOURCE_DIR}/unittests/*.chai)
|
||||
|
||||
list(SORT UNIT_TESTS)
|
||||
|
||||
IF(BUILD_TESTING)
|
||||
option(UNIT_TEST_LIGHT "Unit tests light (expect module loading failures)" FALSE)
|
||||
|
||||
foreach(filename ${UNIT_TESTS})
|
||||
message(STATUS "Adding test ${filename}")
|
||||
add_test(${filename} chai ${CMAKE_CURRENT_SOURCE_DIR}/unittests/unit_test.inc ${CMAKE_CURRENT_SOURCE_DIR}/unittests/${filename})
|
||||
endforeach(filename)
|
||||
|
||||
SET_PROPERTY(TEST ${UNIT_TESTS}
|
||||
PROPERTY ENVIRONMENT
|
||||
"CHAI_USE_PATH=${CMAKE_CURRENT_SOURCE_DIR}/unittests/"
|
||||
"CHAI_MODULE_PATH=${CMAKE_CURRENT_BINARY_DIR}/"
|
||||
)
|
||||
|
||||
IF (NOT UNIT_TEST_LIGHT)
|
||||
add_executable(utility_test unittests/utility_test.cpp)
|
||||
target_link_libraries(utility_test ${LIBS})
|
||||
add_test(NAME Utility_Test COMMAND utility_test)
|
||||
|
||||
add_executable(dynamic_object_test unittests/dynamic_object_test.cpp)
|
||||
target_link_libraries(dynamic_object_test ${LIBS})
|
||||
add_test(NAME Dynamic_Object_Test COMMAND dynamic_object_test)
|
||||
|
||||
add_executable(functor_creation_test unittests/functor_creation_test.cpp)
|
||||
target_link_libraries(functor_creation_test ${LIBS})
|
||||
add_test(NAME Functor_Creation_Test COMMAND functor_creation_test)
|
||||
|
||||
add_executable(functor_cast_test unittests/functor_cast_test.cpp)
|
||||
target_link_libraries(functor_cast_test ${LIBS})
|
||||
add_test(NAME Functor_Cast_Test COMMAND functor_cast_test)
|
||||
|
||||
add_executable(boxed_cast_test unittests/boxed_cast_test.cpp)
|
||||
target_link_libraries(boxed_cast_test ${LIBS})
|
||||
add_test(NAME Boxed_Cast_Test COMMAND boxed_cast_test)
|
||||
|
||||
add_executable(object_lifetime_test unittests/object_lifetime_test.cpp)
|
||||
target_link_libraries(object_lifetime_test ${LIBS})
|
||||
add_test(NAME Object_Lifetime_Test COMMAND object_lifetime_test)
|
||||
|
||||
add_executable(function_ordering_test unittests/function_ordering_test.cpp)
|
||||
target_link_libraries(function_ordering_test ${LIBS})
|
||||
add_test(NAME Function_Ordering_Test COMMAND function_ordering_test)
|
||||
|
||||
add_executable(type_info_test unittests/type_info_test.cpp)
|
||||
target_link_libraries(type_info_test ${LIBS})
|
||||
add_test(NAME Type_Info_Test COMMAND type_info_test)
|
||||
|
||||
add_executable(eval_catch_exception_test unittests/eval_catch_exception_test.cpp)
|
||||
target_link_libraries(eval_catch_exception_test ${LIBS})
|
||||
add_test(NAME Eval_Catch_Exception_Test COMMAND eval_catch_exception_test)
|
||||
|
||||
add_executable(multifile_test unittests/multifile_test_main.cpp unittests/multifile_test_chai.cpp
|
||||
unittests/multifile_test_module.cpp)
|
||||
target_link_libraries(multifile_test ${LIBS})
|
||||
add_test(NAME MultiFile_Test COMMAND multifile_test)
|
||||
|
||||
add_library(test_module MODULE src/test_module.cpp)
|
||||
target_link_libraries(test_module ${LIBS})
|
||||
|
||||
install(TARGETS test_module RUNTIME DESTINATION bin LIBRARY DESTINATION lib/chaiscript)
|
||||
ENDIF()
|
||||
ENDIF(BUILD_TESTING)
|
||||
|
||||
install(TARGETS chai ${MODULES} RUNTIME DESTINATION bin LIBRARY DESTINATION lib/chaiscript )
|
||||
install(DIRECTORY include/chaiscript DESTINATION include
|
||||
PATTERN "*.hpp"
|
||||
PATTERN "*/.svn*" EXCLUDE
|
||||
PATTERN "*/.git*" EXCLUDE
|
||||
PATTERN "*~" EXCLUDE)
|
||||
install(DIRECTORY unittests DESTINATION share/chaiscript
|
||||
PATTERN "*.chai"
|
||||
PATTERN "*.inc"
|
||||
PATTERN "*/.svn*" EXCLUDE
|
||||
PATTERN "*/.git*" EXCLUDE
|
||||
PATTERN "*~" EXCLUDE)
|
||||
install(DIRECTORY samples DESTINATION share/chaiscript
|
||||
PATTERN "*.chai"
|
||||
PATTERN "*/.svn*" EXCLUDE
|
||||
PATTERN "*/.git*" EXCLUDE
|
||||
PATTERN "*~" EXCLUDE)
|
||||
|
||||
|
||||
configure_file(contrib/pkgconfig/chaiscript.pc.in lib/pkgconfig/chaiscript.pc @ONLY)
|
||||
install(FILES "${chaiscript_BINARY_DIR}/lib/pkgconfig/chaiscript.pc"
|
||||
DESTINATION lib/pkgconfig)
|
||||
|
||||
|
1661
Doxyfile.in
Normal file
1661
Doxyfile.in
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
This is a placeholder
|
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .
|
||||
make install
|
||||
|
||||
INCLUDED_FILES="include/chaiscript/*.hpp include/chaiscript/dispatchkit/*.hpp include/chaiscript/language/*.hpp bin/chaiscript_eval"
|
||||
|
||||
zip -r chaiscript-1.0.zip $INCLUDED_FILES
|
43
contrib/codeanalysis/analyzedata.sh
Executable file
43
contrib/codeanalysis/analyzedata.sh
Executable file
@@ -0,0 +1,43 @@
|
||||
|
||||
function analyze_data
|
||||
{
|
||||
echo -n "$1," >> $2
|
||||
awk 'END {printf "%s,", $1}' r$1-codesize.out >> $2
|
||||
awk '{printf "%s,", $1}' r$1-numunittests.out >> $2
|
||||
awk 'END {printf "%s,", $1}' r$1-unittestsoutput.out >> $2
|
||||
|
||||
awk '{printf "%s,", $1}' r$1-debugbinarysize.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-debugbuildtime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-debugprofiletime.out >> $2
|
||||
|
||||
awk '{printf "%s,", $1}' r$1-releasebinarysize.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-releasebuildtime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-releasemodulesbuildtime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-releaseprofiletime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-releaseunittestruntime.out >> $2
|
||||
|
||||
if [ -x r$1-threadfreebinarysize.out ]
|
||||
then
|
||||
awk '{printf "%s,", $1}' r$1-threadfreebinarysize.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-threadfreeprofiletime.out >> $2
|
||||
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-1threadruntime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-2threadruntime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-4threadruntime.out >> $2
|
||||
awk 'NR>1{exit} 1 {printf "%s,", $2}' r$1-8threadruntime.out >> $2
|
||||
else
|
||||
echo -n ",,,,,," >> $2
|
||||
fi
|
||||
|
||||
awk -F "\n" 'NR>1{exit} 1 {printf "\"%s\"\n", $1}' r$1-revisionlog.out >> $2
|
||||
}
|
||||
|
||||
|
||||
filename=output-$1-$2.csv
|
||||
|
||||
echo "Revision, LOC, Num Unit Tests, Successful Unit Tests, Debug Binary Size, Debug Build Time, Debug Profile Time, Release Binary Size, Release Core Build Time, Release Modules Build Time, Release Profile Time, Release Unit Tests Time, Threadless Binary Size, Threadless Profile Time, 1 Thread Profile Time, 2 Threads Profile Time, 4 Threads Profile Time, 8 Threads Profile Time, Revision Log" > $filename
|
||||
|
||||
for i in `seq $1 $2`
|
||||
do
|
||||
analyze_data $i $filename
|
||||
done
|
81
contrib/codeanalysis/codeanalysis.sh
Executable file
81
contrib/codeanalysis/codeanalysis.sh
Executable file
@@ -0,0 +1,81 @@
|
||||
|
||||
function run_test
|
||||
{
|
||||
echo "****Getting r$1 from SVN"
|
||||
svn export --quiet -r$1 http://chaiscript.googlecode.com/svn/trunk chaiscript-r$1
|
||||
|
||||
pushd chaiscript-r$1
|
||||
|
||||
echo "****Getting svn revision log"
|
||||
svn propget svn:log --revprop -r$1 http://chaiscript.googlecode.com/svn/trunk > ../r$1-revisionlog.out
|
||||
|
||||
echo "****Editing CMakeLists.txt to allow for build type switching"
|
||||
# Clean up CMakeLists.txt so that we can set the build type at configure time
|
||||
sed -i -e "s/SET (CMAKE_BUILD_TYPE.*//" CMakeLists.txt
|
||||
|
||||
echo "****Compiling Debug Build"
|
||||
cmake -D CMAKE_BUILD_TYPE=Debug CMakeLists.txt
|
||||
/usr/bin/time -p make chaiscript_eval 2> ../r$1-debugbuildtime.out
|
||||
|
||||
echo "****Analyzing Debug Build"
|
||||
/usr/bin/time -p ./chaiscript_eval ../profile.chai 2>../r$1-debugprofiletime.out
|
||||
ls -s --block-size=1 ./chaiscript_eval > ../r$1-debugbinarysize.out
|
||||
|
||||
make clean
|
||||
|
||||
echo "****Compiling Release Build"
|
||||
cmake -D CMAKE_BUILD_TYPE=Release CMakeLists.txt
|
||||
/usr/bin/time -p make chaiscript_eval 2> ../r$1-releasebuildtime.out
|
||||
|
||||
echo "****Analyzing Release Build"
|
||||
/usr/bin/time -p ./chaiscript_eval ../profile.chai 2>../r$1-releaseprofiletime.out
|
||||
ls -s --block-size=1 ./chaiscript_eval > ../r$1-releasebinarysize.out
|
||||
|
||||
echo "****Analyzing Code Size"
|
||||
find ./include -name "*.hpp" | xargs wc > ../r$1-codesize.out
|
||||
|
||||
echo "****Building Remaining Modules"
|
||||
/usr/bin/time -p make 2> ../r$1-releasemodulesbuildtime.out
|
||||
|
||||
echo "****Running unit tests"
|
||||
/usr/bin/time -p ./run_unit_tests.sh 2> ../r$1-releaseunittestruntime.out > ../r$1-unittestsoutput.out
|
||||
|
||||
echo "****Counting number of unit tests"
|
||||
find unittests/ -name "*.chai" | wc | awk '{print $1}' > ../r$1-numunittests.out
|
||||
|
||||
|
||||
echo "****Running multithreaded tests"
|
||||
if [ -e src/multithreaded.cpp ]
|
||||
then
|
||||
# Run multithreaded tests
|
||||
echo "****Building multithreaded test"
|
||||
pushd src
|
||||
g++ multithreaded.cpp -lboost_thread-mt -ldl -omultithreaded -I../include -O3
|
||||
echo "****Testing 1 thread runtime"
|
||||
/usr/bin/time -p ./multithreaded 1 2> ../../r$1-1threadruntime.out
|
||||
echo "****Testing 2 thread runtime"
|
||||
/usr/bin/time -p ./multithreaded 1 1 2> ../../r$1-2threadruntime.out
|
||||
echo "****Testing 4 thread runtime"
|
||||
/usr/bin/time -p ./multithreaded 1 1 1 1 2> ../../r$1-4threadruntime.out
|
||||
echo "****Testing 8 thread runtime"
|
||||
/usr/bin/time -p ./multithreaded 1 1 1 1 1 1 1 1 2> ../../r$1-8threadruntime.out
|
||||
|
||||
|
||||
echo "****Compiling thread-free version"
|
||||
g++ main.cpp -ldl -othreadfree -I../include -O3 -DCHAISCRIPT_NO_THREADS
|
||||
echo "****Analyzing thread-free version"
|
||||
/usr/bin/time -p ./threadfree ../../profile.chai 2>../../r$1-threadfreeprofiletime.out
|
||||
ls -s --block-size=1 ./threadfree > ../../r$1-threadfreebinarysize.out
|
||||
|
||||
popd
|
||||
else
|
||||
echo "Multithreaded test non-existent"
|
||||
fi
|
||||
|
||||
popd
|
||||
}
|
||||
|
||||
for i in `seq $1 $2`
|
||||
do
|
||||
run_test $i
|
||||
done
|
15
contrib/codeanalysis/profile.chai
Normal file
15
contrib/codeanalysis/profile.chai
Normal file
@@ -0,0 +1,15 @@
|
||||
var total = 0
|
||||
|
||||
for (var i = 0.0; i < 10000.0; i += 0.1) {
|
||||
total += int(double(i) + int(10));
|
||||
if (i < 9000.0)
|
||||
{
|
||||
total += double(11);
|
||||
if (i > double(4000.0))
|
||||
{
|
||||
total += double(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print(total)
|
136
contrib/geshi/chaiscript.php
Normal file
136
contrib/geshi/chaiscript.php
Normal file
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
/*************************************************************************************
|
||||
* chaiscript.php
|
||||
* --------------
|
||||
* Author: Jason Turner & Jonathan Turner (based on JavaScript by Ben Keen (ben.keen@gmail.com))
|
||||
* Copyright: (c) 2010 Jason Turner (jason@emptycrate.com) (c) 2009 Jonathan Turner
|
||||
* (c) 2004 Ben Keen (ben.keen@gmail.com), Nigel McNie (http://qbnz.com/highlighter)
|
||||
* Release Version: 1.0
|
||||
* Date Started: 2009/07/03
|
||||
*
|
||||
* ChaiScript language file for GeSHi.
|
||||
*
|
||||
* CHANGES
|
||||
* -------
|
||||
* 2009/07/03 (1.0.0)
|
||||
* - First Release
|
||||
* 2010/03/30 (1.1.0)
|
||||
* - Updated to include more language features and remove left over pieces from JavaScript
|
||||
*
|
||||
*************************************************************************************
|
||||
*
|
||||
* This file is part of GeSHi.
|
||||
*
|
||||
* GeSHi is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* GeSHi is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with GeSHi; if not, write to the Free Software
|
||||
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
*
|
||||
************************************************************************************/
|
||||
|
||||
$language_data = array (
|
||||
'LANG_NAME' => 'Chaiscript',
|
||||
'COMMENT_SINGLE' => array(1 => '//'),
|
||||
'COMMENT_MULTI' => array('/*' => '*/'),
|
||||
//Regular Expressions
|
||||
'COMMENT_REGEXP' => array(2 => "/(?<=[\\s^])s\\/(?:\\\\.|(?!\n)[^\\/\\\\])+\\/(?:\\\\.|(?!\n)[^\\/\\\\])+\\/[gimsu]*(?=[\\s$\\.\\;])|(?<=[\\s^(=])m?\\/(?:\\\\.|(?!\n)[^\\/\\\\])+\\/[gimsu]*(?=[\\s$\\.\\,\\;\\)])/iU"),
|
||||
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
|
||||
'QUOTEMARKS' => array("'", '"'),
|
||||
'ESCAPE_CHAR' => '\\',
|
||||
'KEYWORDS' => array(
|
||||
1 => array(
|
||||
'break', 'else', 'else if', 'eval', 'for', 'if', 'return', 'while', 'try', 'catch', 'finally',
|
||||
),
|
||||
2 => array(
|
||||
'def', 'false', 'fun', 'true', 'var', 'attr',
|
||||
),
|
||||
3 => array(
|
||||
// built in functions
|
||||
'throw',
|
||||
)
|
||||
),
|
||||
'SYMBOLS' => array(
|
||||
'(', ')', '[', ']', '{', '}',
|
||||
'+', '-', '*', '/', '%',
|
||||
'!', '@', '&', '|', '^',
|
||||
'<', '>', '=',
|
||||
',', ';', '?', ':'
|
||||
),
|
||||
'CASE_SENSITIVE' => array(
|
||||
GESHI_COMMENTS => false,
|
||||
1 => false,
|
||||
2 => false,
|
||||
3 => false
|
||||
),
|
||||
'STYLES' => array(
|
||||
'KEYWORDS' => array(
|
||||
1 => 'color: #000066; font-weight: bold;',
|
||||
2 => 'color: #003366; font-weight: bold;',
|
||||
3 => 'color: #000066;'
|
||||
),
|
||||
'COMMENTS' => array(
|
||||
1 => 'color: #006600; font-style: italic;',
|
||||
2 => 'color: #009966; font-style: italic;',
|
||||
'MULTI' => 'color: #006600; font-style: italic;'
|
||||
),
|
||||
'ESCAPE_CHAR' => array(
|
||||
0 => 'color: #000099; font-weight: bold;'
|
||||
),
|
||||
'BRACKETS' => array(
|
||||
0 => 'color: #009900;'
|
||||
),
|
||||
'STRINGS' => array(
|
||||
0 => 'color: #3366CC;'
|
||||
),
|
||||
'NUMBERS' => array(
|
||||
0 => 'color: #CC0000;'
|
||||
),
|
||||
'METHODS' => array(
|
||||
1 => 'color: #660066;'
|
||||
),
|
||||
'SYMBOLS' => array(
|
||||
0 => 'color: #339933;'
|
||||
),
|
||||
'REGEXPS' => array(
|
||||
),
|
||||
'SCRIPT' => array(
|
||||
0 => '',
|
||||
1 => '',
|
||||
2 => '',
|
||||
3 => ''
|
||||
)
|
||||
),
|
||||
'URLS' => array(
|
||||
1 => '',
|
||||
2 => '',
|
||||
3 => ''
|
||||
),
|
||||
'OOLANG' => true,
|
||||
'OBJECT_SPLITTERS' => array(
|
||||
1 => '.'
|
||||
),
|
||||
'REGEXPS' => array(
|
||||
),
|
||||
'STRICT_MODE_APPLIES' => GESHI_MAYBE,
|
||||
'SCRIPT_DELIMITERS' => array(
|
||||
0 => array(
|
||||
),
|
||||
1 => array(
|
||||
)
|
||||
),
|
||||
'HIGHLIGHT_STRICT_BLOCK' => array(
|
||||
0 => true,
|
||||
1 => true
|
||||
)
|
||||
);
|
||||
|
||||
?>
|
12
contrib/pkgconfig/chaiscript.pc.in
Normal file
12
contrib/pkgconfig/chaiscript.pc.in
Normal file
@@ -0,0 +1,12 @@
|
||||
prefix=@CMAKE_INSTALL_PREFIX@
|
||||
exec_prefix=${prefix}
|
||||
libdir=${exec_prefix}/lib
|
||||
includedir=${prefix}/include
|
||||
|
||||
Name: chaiscript
|
||||
Description: ChaiScript is a scripting language that easily embeds into your existing C++ applications. It's built to be flexible and dynamic, yet still maintain the type-safety you expect as a C++ user. It can natively use classes, methods, and attributes, even if the class inherits functionality from a parent class.
|
||||
Version: @CPACK_PACKAGE_VERSION_MAJOR@.@CPACK_PACKAGE_VERSION_MINOR@.@CPACK_PACKAGE_VERSION_PATCH@
|
||||
Requires:
|
||||
Conflicts:
|
||||
Libs:
|
||||
Cflags: -I${includedir}
|
@@ -1,69 +0,0 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "function_call.hpp"
|
||||
#include "chaiscript.hpp"
|
||||
#include <boost/function.hpp>
|
||||
|
||||
struct Callback_Handler
|
||||
{
|
||||
typedef std::vector<std::pair<boost::function<std::string ()>,
|
||||
boost::function<double (int)> > > Callbacks;
|
||||
|
||||
Callbacks m_callbacks;
|
||||
|
||||
void add_callbacks(boost::shared_ptr<dispatchkit::Proxy_Function> t_name,
|
||||
boost::shared_ptr<dispatchkit::Proxy_Function> t_value)
|
||||
{
|
||||
m_callbacks.push_back(
|
||||
std::make_pair(dispatchkit::build_function_caller<std::string ()>(t_name),
|
||||
dispatchkit::build_function_caller<double (int)>(t_value)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
void do_callbacks()
|
||||
{
|
||||
int i=1;
|
||||
for (Callbacks::iterator itr = m_callbacks.begin();
|
||||
itr != m_callbacks.end();
|
||||
++itr)
|
||||
{
|
||||
std::cout << "Name: " << itr->first() << " = " << itr->second(i) << std::endl;
|
||||
++i;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
chaiscript::ChaiScript_Engine chai;
|
||||
|
||||
Callback_Handler cb_handler;
|
||||
chai.get_eval_engine().add_object("cb_handler", boost::ref(cb_handler));
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &Callback_Handler::add_callbacks, "add_callbacks");
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
try {
|
||||
dispatchkit::Boxed_Value val = chai.evaluate_file(argv[i]);
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cerr << "Could not open: " << argv[i] << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
cb_handler.do_callbacks();
|
||||
|
||||
boost::function<std::string (const std::string&, const std::string &)> f =
|
||||
dispatchkit::build_functor<std::string (const std::string &, const std::string &)>
|
||||
(chai, "function(x, y) { return x + y }");
|
||||
|
||||
std::cout << "Functor call: " << f("Hello", " World") << std::endl;
|
||||
}
|
||||
|
@@ -1,212 +0,0 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/function.hpp>
|
||||
|
||||
#include <chaiscript/dispatchkit/dispatchkit.hpp>
|
||||
#include <chaiscript/dispatchkit/bootstrap.hpp>
|
||||
#include <chaiscript/dispatchkit/bootstrap_stl.hpp>
|
||||
#include <chaiscript/dispatchkit/function_call.hpp>
|
||||
|
||||
using namespace dispatchkit;
|
||||
|
||||
struct Test
|
||||
{
|
||||
Test(const std::string &s)
|
||||
: number(-25), message(s)
|
||||
{
|
||||
std::cout << "Test class constructed with value: " << s << std::endl;
|
||||
}
|
||||
|
||||
void show_message()
|
||||
{
|
||||
std::cout << "Constructed Message: " << message << std::endl;
|
||||
}
|
||||
|
||||
std::string &get_message()
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
int number;
|
||||
|
||||
std::string message;
|
||||
};
|
||||
|
||||
|
||||
|
||||
Boxed_Value named_func_call(Dispatch_Engine &ss,
|
||||
const std::string &nametocall, const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
if (params.size() == 2)
|
||||
{
|
||||
return dispatch(ss.get_function(nametocall), params);
|
||||
} else {
|
||||
throw std::runtime_error("Invalid num params");
|
||||
}
|
||||
}
|
||||
|
||||
// A function that takes a dynamic list of params
|
||||
// and calls a bunch of conversion functions on them and
|
||||
// returns the result as a boxed_value
|
||||
Boxed_Value dynamic_function(Dispatch_Engine &ss, const std::string &name,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
if (name == "concat_string")
|
||||
{
|
||||
Boxed_Value result;
|
||||
|
||||
//Return a void if there is nothing in the array
|
||||
if (params.size() == 0)
|
||||
{
|
||||
return result;
|
||||
} else {
|
||||
//else, prepopulate the result with a string conversion of the first
|
||||
//param
|
||||
result =
|
||||
dispatch(ss.get_function("to_string"), Param_List_Builder() << params[0]);
|
||||
}
|
||||
|
||||
//Then, loop over all remaining params, converting them to strings and adding
|
||||
//them to the result. This example maybe bette served with a string += operator
|
||||
//implementation, but it works.
|
||||
for (size_t i = 1; i < params.size(); ++i)
|
||||
{
|
||||
result =
|
||||
dispatch(ss.get_function("+"), Param_List_Builder() << result <<
|
||||
dispatch(ss.get_function("to_string"), Param_List_Builder() << params[i]));
|
||||
}
|
||||
|
||||
return result;
|
||||
} else {
|
||||
throw std::runtime_error("Unknown function call");
|
||||
}
|
||||
}
|
||||
|
||||
void test(const std::string &p)
|
||||
{
|
||||
std::cout << "Test: " << p << std::endl;
|
||||
}
|
||||
|
||||
//Test main
|
||||
int main()
|
||||
{
|
||||
Dispatch_Engine ss;
|
||||
Bootstrap::bootstrap(ss);
|
||||
bootstrap_vector<std::vector<int> >(ss, "VectorInt");
|
||||
dump_system(ss);
|
||||
|
||||
//Calling a function by name and allowing the built in dispatch mechanism to
|
||||
//choose the most appropriate version of the function
|
||||
Boxed_Value addresult = dispatch(ss.get_function("+"), Param_List_Builder() << double(5.1) << double(10.3));
|
||||
|
||||
//Using the cast to unbox the resultant value and output it
|
||||
std::cout << boxed_cast<double>(addresult) << std::endl;
|
||||
|
||||
//Using the Boxed_Value as input to another function, again with automatic dispatch.
|
||||
//This time we will not bother saving the result and will instead send it straight out
|
||||
std::cout << boxed_cast<double>(
|
||||
dispatch(ss.get_function("*"), Param_List_Builder() << 2 << addresult)
|
||||
) << std::endl;
|
||||
|
||||
//Register a new function, this one with typing for us, so we don't have to ubox anything
|
||||
//right here
|
||||
|
||||
//Now we have a print method, let's try to print out the earlier example:
|
||||
//so, we dispatch the to_string and pass its result as a param to "print"
|
||||
//In this example we don't bother with temporaries and we don't have to know
|
||||
//anything about types
|
||||
dispatch(ss.get_function("print_string"),
|
||||
Param_List_Builder() << dispatch(ss.get_function("to_string"), Param_List_Builder() << addresult));
|
||||
|
||||
// Now we are going to register a new dynamic function,
|
||||
// when this function is called the objects are not unboxed, but passed
|
||||
// in in their boxed state
|
||||
ss.register_function(boost::shared_ptr<Proxy_Function>(new Dynamic_Proxy_Function(boost::bind(&dynamic_function, boost::ref(ss), "concat_string", _1))), "concat_string");
|
||||
|
||||
|
||||
// Call our newly defined dynamic function with 10 parameters, then send
|
||||
// its output to the "print" function
|
||||
dispatch(ss.get_function("print_string"),
|
||||
Param_List_Builder() << dispatch(ss.get_function("concat_string"),
|
||||
Param_List_Builder() << std::string("\n\t") << std::string("The Value Was: ")
|
||||
<< double(42.5) << std::string(".")
|
||||
<< '\n'
|
||||
<< '\t' << std::string("The old value was: ")
|
||||
<< addresult << '.' << '\n' ));
|
||||
|
||||
|
||||
|
||||
|
||||
//Register some local methods of the "Test" class
|
||||
ss.register_function(build_constructor<Test, const std::string &>(), "Test");
|
||||
|
||||
register_function(ss, &Test::get_message, "get_message");
|
||||
register_function(ss, &Test::show_message, "show_message");
|
||||
register_member(ss, &Test::number, "number");
|
||||
|
||||
//Create a new object using the "Test" constructor, passing the param "Yo".
|
||||
//Then, add the new object to the system with the name "testobj2"
|
||||
ss.add_object("testobj2",
|
||||
dispatch(ss.get_function("Test"), Param_List_Builder() << std::string("Yo")));
|
||||
|
||||
// Look up and store a reference to our new object
|
||||
std::vector<Boxed_Value> sos;
|
||||
sos.push_back(ss.get_object("testobj2"));
|
||||
|
||||
//Build a bound function proxy for calling the script handled function
|
||||
boost::function<void (Test &)> show_message =
|
||||
build_function_caller<void (Test &)>(ss.get_function("show_message"));
|
||||
|
||||
Test &t = boxed_cast<Test &>(ss.get_object("testobj2"));
|
||||
|
||||
//Print the message the object was created with
|
||||
show_message(t);
|
||||
|
||||
//Now, get a reference to the object's stored message
|
||||
Boxed_Value stringref = dispatch(ss.get_function("get_message"), sos);
|
||||
|
||||
//Unbox it using boxed_cast
|
||||
std::string &sr = boxed_cast<std::string &>(stringref);
|
||||
|
||||
//Update the value of the reference
|
||||
sr = "Bob Updated The message";
|
||||
|
||||
//Now, get a reference to the object's stored number
|
||||
Boxed_Value numberref= dispatch(ss.get_function("number"), sos);
|
||||
|
||||
//Unbox it using boxed_cast
|
||||
int &ir = boxed_cast<int &>(numberref);
|
||||
|
||||
std::cout << "Number: " << ir << std::endl;
|
||||
|
||||
//Now, prove that the reference was successfully acquired
|
||||
//and we are able to peek into the boxed types
|
||||
show_message(t);
|
||||
|
||||
|
||||
// Finally, we are going to register some named function aliases, for
|
||||
// the fun of it
|
||||
ss.register_function(boost::shared_ptr<Proxy_Function>(
|
||||
new Dynamic_Proxy_Function(boost::bind(&named_func_call, boost::ref(ss), "+", _1))), "add");
|
||||
|
||||
//Call our newly named "add" function (which in turn dispatches +)
|
||||
|
||||
std::cout << "Result of add function: " <<
|
||||
boxed_cast<int>(dispatch(ss.get_function("add"), Param_List_Builder() << 5 << 2))
|
||||
<< std::endl;
|
||||
|
||||
|
||||
ss.set_object("myfunc", boost::shared_ptr<Proxy_Function>(new Proxy_Function_Impl<boost::function<void (const std::string &)> >(&test)));
|
||||
|
||||
dispatch(ss.get_function("myfunc"), Param_List_Builder() << std::string("hello function variable"));
|
||||
|
||||
}
|
||||
|
@@ -1,23 +0,0 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include "dispatchkit.hpp"
|
||||
#include "bootstrap.hpp"
|
||||
|
||||
#define BOOST_TEST_DYN_LINK
|
||||
#define BOOST_TEST_MODULE boxedcpp_unittests
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
BOOST_AUTO_TEST_CASE( add_operators )
|
||||
{
|
||||
using namespace dispatchkit;
|
||||
|
||||
Dispatch_Engine ss;
|
||||
Bootstrap::bootstrap(ss);
|
||||
dump_system(ss);
|
||||
|
||||
BOOST_CHECK_EQUAL(boxed_cast<int>(dispatch(ss.get_function("+"), Param_List_Builder() << double(5.1) << double(10.3))), 15.4);
|
||||
}
|
@@ -1,148 +0,0 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "chaiscript.hpp"
|
||||
#include "function_call.hpp"
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/regex.hpp>
|
||||
|
||||
|
||||
std::string load_text_file(const std::string &filename)
|
||||
{
|
||||
std::ifstream infile(filename.c_str());
|
||||
|
||||
std::string str;
|
||||
|
||||
std::string result;
|
||||
|
||||
while (std::getline(infile, str))
|
||||
{
|
||||
result += str + "\n";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<dispatchkit::Boxed_Value> regex_search(const std::string &str, const std::string ®ex)
|
||||
{
|
||||
boost::smatch matches;
|
||||
boost::regex_search(str, matches, boost::regex(regex));
|
||||
|
||||
std::vector<dispatchkit::Boxed_Value> results;
|
||||
|
||||
for (unsigned int i = 0; i < matches.size(); ++i)
|
||||
{
|
||||
results.push_back(dispatchkit::Boxed_Value(std::string(matches.str(i))));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
struct Sensor_Manager
|
||||
{
|
||||
struct Sensor
|
||||
{
|
||||
int milliseconds;
|
||||
dispatchkit::Boxed_Value state_object;
|
||||
boost::function<double (dispatchkit::Boxed_Value)> sensor;
|
||||
boost::posix_time::ptime next_run;
|
||||
|
||||
Sensor(int t_milliseconds, dispatchkit::Boxed_Value t_state_object,
|
||||
boost::function<double (dispatchkit::Boxed_Value)> t_sensor)
|
||||
: milliseconds(t_milliseconds), state_object(t_state_object), sensor(t_sensor),
|
||||
next_run(boost::posix_time::microsec_clock::universal_time()
|
||||
+ boost::posix_time::milliseconds(milliseconds))
|
||||
{
|
||||
}
|
||||
|
||||
std::pair<boost::posix_time::ptime, double> get_value()
|
||||
{
|
||||
next_run = boost::posix_time::microsec_clock::universal_time()
|
||||
+ boost::posix_time::milliseconds(milliseconds);
|
||||
|
||||
return std::make_pair(boost::posix_time::microsec_clock::universal_time(),
|
||||
sensor(state_object));
|
||||
}
|
||||
};
|
||||
|
||||
std::map<std::string, Sensor> m_sensors;
|
||||
|
||||
//sensor_manager.add_sensor("CPU", 1000, global_state, function(state) { update_state(state); state["CPU"]; } )
|
||||
void add_sensor(const std::string &t_name, int t_milliseconds, dispatchkit::Boxed_Value t_state_object,
|
||||
boost::shared_ptr<dispatchkit::Proxy_Function> t_func)
|
||||
{
|
||||
m_sensors.insert(
|
||||
std::make_pair(t_name,
|
||||
Sensor(t_milliseconds, t_state_object,
|
||||
dispatchkit::build_function_caller<double (dispatchkit::Boxed_Value)>(t_func)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
std::vector<std::pair<std::string, double> > run_sensors()
|
||||
{
|
||||
std::vector<std::pair<std::string, double> > results;
|
||||
|
||||
boost::posix_time::ptime t(boost::posix_time::microsec_clock::universal_time());
|
||||
|
||||
for (std::map<std::string, Sensor>::iterator itr = m_sensors.begin();
|
||||
itr != m_sensors.end();
|
||||
++itr)
|
||||
{
|
||||
if (itr->second.next_run <= t)
|
||||
{
|
||||
results.push_back(std::make_pair(itr->first, itr->second.get_value().second));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
chaiscript::ChaiScript_Engine chai;
|
||||
|
||||
Sensor_Manager sensor_manager;
|
||||
chai.get_eval_engine().add_object("sensor_manager", boost::ref(sensor_manager));
|
||||
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &Sensor_Manager::add_sensor, "add_sensor");
|
||||
dispatchkit::register_function(chai.get_eval_engine(), ®ex_search, "regex_search");
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &load_text_file, "load_text_file");
|
||||
|
||||
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
try {
|
||||
chai.evaluate_file(argv[i]);
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cerr << "Could not open: " << argv[i] << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
while (true)
|
||||
{
|
||||
usleep(1000);
|
||||
std::vector<std::pair<std::string, double> > sensor_data = sensor_manager.run_sensors();
|
||||
|
||||
for (std::vector<std::pair<std::string, double> >::iterator itr = sensor_data.begin();
|
||||
itr != sensor_data.end();
|
||||
++itr)
|
||||
{
|
||||
std::cout << "Sensor: " << itr->first << " value: " << itr->second << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
7
contrib/vim/README.txt
Normal file
7
contrib/vim/README.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
Install ftdetect, indent and syntax subdirectories to:
|
||||
|
||||
~/.vim/
|
||||
|
||||
See the vim documentation on this:
|
||||
|
||||
http://vimdoc.sourceforge.net/htmldoc/syntax.html#mysyntaxfile
|
2
contrib/vim/ftdetect/chaiscript.vim
Normal file
2
contrib/vim/ftdetect/chaiscript.vim
Normal file
@@ -0,0 +1,2 @@
|
||||
au BufRead,BufNewFile *.chai set filetype=chaiscript
|
||||
|
50
contrib/vim/indent/chaiscript.vim
Normal file
50
contrib/vim/indent/chaiscript.vim
Normal file
@@ -0,0 +1,50 @@
|
||||
" Vim indent file
|
||||
" Language: ChaiScript
|
||||
" Maintainer: Jason Turner <lefticus 'at' gmail com>
|
||||
|
||||
" Only load this indent file when no other was loaded.
|
||||
if exists("b:did_indent")
|
||||
finish
|
||||
endif
|
||||
let b:did_indent = 1
|
||||
|
||||
setlocal indentexpr=GetChaiScriptIndent()
|
||||
setlocal autoindent
|
||||
|
||||
" Only define the function once.
|
||||
if exists("*GetChaiScriptIndent")
|
||||
finish
|
||||
endif
|
||||
|
||||
function! GetChaiScriptIndent()
|
||||
" Find a non-blank line above the current line.
|
||||
let lnum = prevnonblank(v:lnum - 1)
|
||||
|
||||
" Hit the start of the file, use zero indent.
|
||||
if lnum == 0
|
||||
return 0
|
||||
endif
|
||||
|
||||
" Add a 'shiftwidth' after lines that start a block:
|
||||
" lines containing a {
|
||||
let ind = indent(lnum)
|
||||
let flag = 0
|
||||
let prevline = getline(lnum)
|
||||
if prevline =~ '^.*{.*'
|
||||
let ind = ind + &shiftwidth
|
||||
let flag = 1
|
||||
endif
|
||||
|
||||
" Subtract a 'shiftwidth' after lines containing a { followed by a }
|
||||
" to keep it balanced
|
||||
if flag == 1 && prevline =~ '.*{.*}.*'
|
||||
let ind = ind - &shiftwidth
|
||||
endif
|
||||
|
||||
" Subtract a 'shiftwidth' on lines ending with }
|
||||
if getline(v:lnum) =~ '^\s*\%(}\)'
|
||||
let ind = ind - &shiftwidth
|
||||
endif
|
||||
|
||||
return ind
|
||||
endfunction
|
94
contrib/vim/syntax/chaiscript.vim
Normal file
94
contrib/vim/syntax/chaiscript.vim
Normal file
@@ -0,0 +1,94 @@
|
||||
" Vim syntax file
|
||||
" Language: ChaiScript
|
||||
" Maintainer: Jason Turner <lefticus 'at' gmail com>
|
||||
|
||||
" Quit when a (custom) syntax file was already loaded
|
||||
if exists("b:current_syntax")
|
||||
finish
|
||||
end
|
||||
|
||||
syn case match
|
||||
|
||||
" syncing method
|
||||
syn sync fromstart
|
||||
|
||||
" Strings
|
||||
syn region chaiscriptString start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=chaiscriptSpecial,chaiscriptEval,@Spell
|
||||
|
||||
" Escape characters
|
||||
syn match chaiscriptSpecial contained "\\[\\abfnrtv\'\"]\|\\\d\{,3}"
|
||||
|
||||
" String evals
|
||||
syn region chaiscriptEval contained start="${" end="}"
|
||||
|
||||
" integer number
|
||||
syn match chaiscriptNumber "\<\d\+\>"
|
||||
|
||||
" floating point number, with dot, optional exponent
|
||||
syn match chaiscriptFloat "\<\d\+\.\d*\%(e[-+]\=\d\+\)\=\>"
|
||||
|
||||
" floating point number, starting with a dot, optional exponent
|
||||
syn match chaiscriptFloat "\.\d\+\%(e[-+]\=\d\+\)\=\>"
|
||||
|
||||
" floating point number, without dot, with exponent
|
||||
syn match chaiscriptFloat "\<\d\+e[-+]\=\d\+\>"
|
||||
|
||||
" Hex strings
|
||||
syn match chaiscriptNumber "\<0x\x\+\>"
|
||||
|
||||
" Binary strings
|
||||
syn match chaiscriptNumber "\<0b[01]\+\>"
|
||||
|
||||
" Various language features
|
||||
syn keyword chaiscriptCond if else
|
||||
syn keyword chaiscriptRepeat while for do
|
||||
syn keyword chaiscriptStatement break continue return
|
||||
syn keyword chaiscriptExceptions try catch throw
|
||||
|
||||
"Keyword
|
||||
syn keyword chaiscriptKeyword def true false attr
|
||||
|
||||
"Built in types
|
||||
syn keyword chaiscriptType fun var
|
||||
|
||||
"Built in funcs, keep it simple
|
||||
syn keyword chaiscriptFunc eval throw
|
||||
|
||||
"Let's treat all backtick operator function lookups as built in too
|
||||
syn region chaiscriptFunc matchgroup=chaiscriptFunc start="`" end="`"
|
||||
|
||||
" Account for the "[1..10]" syntax, treating it as an operator
|
||||
" Intentionally leaving out all of the normal, well known operators
|
||||
syn match chaiscriptOperator "\.\."
|
||||
|
||||
" Guard seperator as an operator
|
||||
syn match chaiscriptOperator ":"
|
||||
|
||||
" Comments
|
||||
syn match chaiscriptComment "//.*$" contains=@Spell
|
||||
syn region chaiscriptComment matchgroup=chaiscriptComment start="/\*" end="\*/" contains=@Spell
|
||||
|
||||
|
||||
|
||||
hi def link chaiscriptExceptions Exception
|
||||
hi def link chaiscriptKeyword Keyword
|
||||
hi def link chaiscriptStatement Statement
|
||||
hi def link chaiscriptRepeat Repeat
|
||||
hi def link chaiscriptString String
|
||||
hi def link chaiscriptNumber Number
|
||||
hi def link chaiscriptFloat Float
|
||||
hi def link chaiscriptOperator Operator
|
||||
hi def link chaiscriptConstant Constant
|
||||
hi def link chaiscriptCond Conditional
|
||||
hi def link chaiscriptFunction Function
|
||||
hi def link chaiscriptComment Comment
|
||||
hi def link chaiscriptTodo Todo
|
||||
hi def link chaiscriptError Error
|
||||
hi def link chaiscriptSpecial SpecialChar
|
||||
hi def link chaiscriptFunc Identifier
|
||||
hi def link chaiscriptType Type
|
||||
hi def link chaiscriptEval Special
|
||||
|
||||
let b:current_syntax = "chaiscript"
|
||||
|
||||
" vim: nowrap sw=2 sts=2 ts=8 noet
|
1
description.txt
Normal file
1
description.txt
Normal file
@@ -0,0 +1 @@
|
||||
ChaiScript is a header-only C++ embedded scripting language loosely based on ECMA script. It is designed for ease of use and tight integration with C++. See http://www.chaiscript.com for more details.
|
@@ -1,145 +1,575 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_HPP_
|
||||
#define CHAISCRIPT_HPP_
|
||||
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/function.hpp>
|
||||
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <fstream>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
|
||||
/// \mainpage
|
||||
/// <a href="http://www.chaiscript.com">ChaiScript</a> is a scripting language designed specifically for integration with C++. It provides
|
||||
/// seamless integration with C++ on all levels, including shared_ptr objects, functors and exceptions.
|
||||
///
|
||||
/// The parts of the ChaiScript API that the average user will be concerned with are contained in the
|
||||
/// chaiscript namespace and the chaiscript::ChaiScript class.
|
||||
///
|
||||
/// The end user parts of the API are extremely simple both in size and ease of use.
|
||||
///
|
||||
/// Currently, all source control and project management aspects of ChaiScript occur on <a href="http://www.github.com/ChaiScript/ChaiScript">github</a>.
|
||||
///
|
||||
/// <hr>
|
||||
///
|
||||
/// \sa chaiscript
|
||||
/// \sa chaiscript::ChaiScript
|
||||
/// \sa \ref LangKeywordRef
|
||||
/// \sa \ref LangInPlaceRef
|
||||
/// \sa \ref LangObjectSystemRef
|
||||
/// \sa http://www.chaiscript.com
|
||||
/// \sa http://www.github.com/ChaiScript/ChaiScript
|
||||
///
|
||||
/// <hr>
|
||||
///
|
||||
/// \section gettingstarted Getting Started
|
||||
///
|
||||
/// \li \ref basics
|
||||
/// \li \ref eval
|
||||
/// \li \ref addingitems
|
||||
/// \li \ref helpermacro
|
||||
/// \li \ref pointerconversions
|
||||
/// \li \ref baseclasses
|
||||
/// \li \ref functionobjects
|
||||
/// \li \ref threading
|
||||
/// \li \ref exceptions
|
||||
///
|
||||
///
|
||||
/// \subsection basics Basics
|
||||
///
|
||||
/// Basic simple example:
|
||||
///
|
||||
/// \code
|
||||
/// #include <chaiscript/chaiscript.hpp>
|
||||
///
|
||||
/// double function(int i, double j)
|
||||
/// {
|
||||
/// return i * j;
|
||||
/// }
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(&function, "function");
|
||||
///
|
||||
/// double d = chai.eval<double>("function(3, 4.75);");
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// <hr>
|
||||
/// \subsection eval Evaluating Scripts
|
||||
///
|
||||
/// Scripts can be evaluated with the () operator, eval method or eval_file method.
|
||||
///
|
||||
/// \subsubsection parenoperator () Operator
|
||||
///
|
||||
/// operator() can be used as a handy shortcut for evaluating ChaiScript snippets.
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai("print(\"hello world\")");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa chaiscript::ChaiScript::operator()(const std::string &)
|
||||
///
|
||||
/// \subsubsection evalmethod Method 'eval'
|
||||
///
|
||||
/// The eval method is somewhat more verbose and can be used to get typesafely return values
|
||||
/// from the script.
|
||||
///
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.eval("callsomefunc()");
|
||||
/// int result = chai.eval<int>("1 + 3");
|
||||
/// // result now equals 4
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa chaiscript::ChaiScript::eval
|
||||
///
|
||||
/// \subsubsection evalfilemethod Method 'eval_file'
|
||||
///
|
||||
/// The 'eval_file' method loads a file from disk and executes the script in it
|
||||
///
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.eval_file("myfile.chai");
|
||||
/// std::string result = chai.eval_file<std::string>("myfile.chai") // extract the last value returned from the file
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa chaiscript::ChaiScript::eval_file
|
||||
///
|
||||
/// <hr>
|
||||
/// \subsection addingitems Adding Items to ChaiScript
|
||||
///
|
||||
/// ChaiScript supports 4 basic things that can be added: objects, functions, type infos and Modules
|
||||
///
|
||||
/// \subsubsection addingobjects Adding Objects
|
||||
///
|
||||
/// Named objects can be created with the #var function.
|
||||
///
|
||||
/// \code
|
||||
/// using namespace chaiscript;
|
||||
/// ChaiScript chai;
|
||||
/// int i = 5;
|
||||
/// chai.add(var(i), "i");
|
||||
/// chai("print(i)");
|
||||
/// \endcode
|
||||
///
|
||||
/// Immutable objects can be created with the chaiscript::const_var function.
|
||||
///
|
||||
/// \code
|
||||
/// chai.add(const_var(i), "i");
|
||||
/// chai("i = 5"); // exception throw, cannot assign const var
|
||||
/// \endcode
|
||||
///
|
||||
/// Named variables can only be accessed from the context they are created in.
|
||||
/// If you want a global variable, it must be const, and created with the
|
||||
/// chaiscript::ChaiScript::add_global_const function.
|
||||
///
|
||||
/// \code
|
||||
/// chai.add_global_const(const_var(i), "i");
|
||||
/// chai("def somefun() { print(i); }; sumfun();");
|
||||
/// \endcode
|
||||
///
|
||||
/// \subsubsection addingfunctions Adding Functions
|
||||
///
|
||||
/// Functions, methods and members are all added using the same function: chaiscript::fun.
|
||||
///
|
||||
/// \code
|
||||
/// using namespace chaiscript;
|
||||
///
|
||||
/// class MyClass {
|
||||
/// public:
|
||||
/// int memberdata;
|
||||
/// void method();
|
||||
/// void method2(int);
|
||||
/// static void staticmethod();
|
||||
/// void overloadedmethod();
|
||||
/// void overloadedmethod(const std::string &);
|
||||
/// };
|
||||
///
|
||||
/// ChaiScript chai;
|
||||
/// chai.add(fun(&MyClass::memberdata), "memberdata");
|
||||
/// chai.add(fun(&MyClass::method), "method");
|
||||
/// chai.add(fun(&MyClass::staticmethod), "staticmethod");
|
||||
/// \endcode
|
||||
///
|
||||
/// Overloaded methods will need some help, to hint the compiler as to which overload you want:
|
||||
///
|
||||
/// \code
|
||||
/// chai.add(fun<void (MyClass::*)()>(&MyClass::overloadedmethod), "overloadedmethod"));
|
||||
/// chai.add(fun<void (MyClass::*)(const std::string &)>(&MyClass::overloadedmethod, "overloadedmethod"));
|
||||
/// \endcode
|
||||
///
|
||||
/// There are also shortcuts built into chaiscript::fun for binding up to the first two parameters of the function.
|
||||
///
|
||||
/// \code
|
||||
/// MyClass obj;
|
||||
/// chai.add(fun(&MyClass::method, &obj), "method");
|
||||
/// chai("method()"); // equiv to obj.method()
|
||||
/// chai.add(fun(&MyClass::method2, &obj, 3), "method2");
|
||||
/// chai("method2()"); // equiv to obj.method2(3)
|
||||
/// \endcode
|
||||
///
|
||||
/// \subsubsection addingtypeinfo Adding Type Info
|
||||
///
|
||||
/// ChaiScript will automatically support any type implicitly provided to it in the form
|
||||
/// of objects and function parameters / return types. However, it can be nice to let ChaiScript
|
||||
/// know more details about the types you are giving it. For instance, the "clone" functionality
|
||||
/// cannot work unless there is a copy constructor registered and the name of the type is known
|
||||
/// (so that ChaiScript can look up the copy constructor).
|
||||
///
|
||||
/// Continuing with the example "MyClass" from above:
|
||||
///
|
||||
/// \code
|
||||
/// chai.add(user_type<MyClass>(), "MyClass");
|
||||
/// \endcode
|
||||
///
|
||||
/// \subsubsection addingmodules Adding Modules
|
||||
///
|
||||
/// Modules are holders for collections of ChaiScript registrations.
|
||||
///
|
||||
/// \code
|
||||
/// ModulePtr module = get_sum_module();
|
||||
/// chai.add(module);
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa chaiscript::Module
|
||||
///
|
||||
/// <hr>
|
||||
/// \subsection helpermacro Class Helper Macro
|
||||
///
|
||||
/// Much of the work of adding new classes to ChaiScript can be reduced with the help
|
||||
/// of the CHAISCRIPT_CLASS helper macro.
|
||||
///
|
||||
/// \code
|
||||
/// class Test
|
||||
/// {
|
||||
/// public:
|
||||
/// void function() {}
|
||||
/// std::string function2() { return "Function2"; }
|
||||
/// void function3() {}
|
||||
/// std::string functionOverload(double) { return "double"; }
|
||||
/// std::string functionOverload(int) { return "int"; }
|
||||
/// };
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
///
|
||||
/// chaiscript::ModulePtr m = chaiscript::ModulePtr(new chaiscript::Module());
|
||||
///
|
||||
/// CHAISCRIPT_CLASS( m,
|
||||
/// Test,
|
||||
/// (Test ())
|
||||
/// (Test (const Test &)),
|
||||
/// ((function))
|
||||
/// ((function2))
|
||||
/// ((function3))
|
||||
/// ((functionOverload)(std::string (Test::*)(double)))
|
||||
/// ((functionOverload)(std::string (Test::*)(int)))
|
||||
/// ((operator=))
|
||||
/// );
|
||||
///
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(m);
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingmodules
|
||||
///
|
||||
/// <hr>
|
||||
/// \subsection pointerconversions Pointer / Object Conversions
|
||||
///
|
||||
/// As much as possible, ChaiScript attempts to convert between &, *, const &, const *, boost::shared_ptr<T>,
|
||||
/// boost::shared_ptr<const T>, boost::reference_wrapper<T>, boost::reference_wrapper<const T> and value types automatically.
|
||||
///
|
||||
/// If a var object was created in C++ from a pointer, it cannot be convered to a shared_ptr (this would add invalid reference counting).
|
||||
/// Const may be added, but never removed.
|
||||
///
|
||||
/// The take away is that you can pretty much expect function calls to Just Work when you need them to.
|
||||
///
|
||||
/// \code
|
||||
/// void fun1(const int *);
|
||||
/// void fun2(int *);
|
||||
/// void fun3(int);
|
||||
/// void fun4(int &);
|
||||
/// void fun5(const int &);
|
||||
/// void fun5(boost::shared_ptr<int>);
|
||||
/// void fun6(boost::shared_ptr<const int>);
|
||||
/// void fun7(const boost::shared_ptr<int> &);
|
||||
/// void fun8(const boost::shared_ptr<const int> &);
|
||||
/// void fun9(boost::reference_wrapper<int>);
|
||||
/// void fun10(boost::reference_wrapper<const int>);
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
/// using namespace chaiscript
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(fun(fun1), "fun1");
|
||||
/// chai.add(fun(fun2), "fun2");
|
||||
/// chai.add(fun(fun3), "fun3");
|
||||
/// chai.add(fun(fun4), "fun4");
|
||||
/// chai.add(fun(fun5), "fun5");
|
||||
/// chai.add(fun(fun6), "fun6");
|
||||
/// chai.add(fun(fun7), "fun7");
|
||||
/// chai.add(fun(fun8), "fun8");
|
||||
/// chai.add(fun(fun9), "fun9");
|
||||
/// chai.add(fun(fun10), "fun10");
|
||||
///
|
||||
/// chai("var i = 10;");
|
||||
/// chai("fun1(i)");
|
||||
/// chai("fun2(i)");
|
||||
/// chai("fun3(i)");
|
||||
/// chai("fun4(i)");
|
||||
/// chai("fun5(i)");
|
||||
/// chai("fun6(i)");
|
||||
/// chai("fun7(i)");
|
||||
/// chai("fun8(i)");
|
||||
/// chai("fun9(i)");
|
||||
/// chai("fun10(i)");
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// See the unit test unittests/boxed_cast_test.cpp for a complete breakdown of the automatic casts that
|
||||
/// available and tested.
|
||||
///
|
||||
/// <hr>
|
||||
/// \subsection baseclasses Base Classes
|
||||
///
|
||||
/// ChaiScript supports handling of passing a derived class object to a function expecting a base class object.
|
||||
/// For the process to work, the base/derived relationship must be registered with the engine.
|
||||
///
|
||||
/// \code
|
||||
/// class Base {};
|
||||
/// class Derived : public Base {};
|
||||
/// void myfunction(Base *b);
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::base_class<Base, Derived>());
|
||||
/// Derived d;
|
||||
/// chai.add(chaiscript::var(&d), "d");
|
||||
/// chai.add(chaiscript::fun(&myfunction), "myfunction");
|
||||
/// chai("myfunction(d)");
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// <hr>
|
||||
///
|
||||
/// \subsection functionobjects Function Objects
|
||||
///
|
||||
/// Functions are first class objects in Chaiscript and ChaiScript supports automatic conversion
|
||||
/// between ChaiScript functions and boost::function objects.
|
||||
///
|
||||
/// \code
|
||||
/// void callafunc(const boost::function<void (const std::string &)> &t_func)
|
||||
/// {
|
||||
/// t_func("bob");
|
||||
/// }
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::fun(&callafunc), "callafunc");
|
||||
/// chai("callafunc(fun(x) { print(x); })"); // pass a lambda function to the registered function
|
||||
/// // which expects a typed boost::function
|
||||
///
|
||||
/// boost::function<void ()> f = chai.eval<boost::function<void ()> >("dump_system");
|
||||
/// f(); // call the ChaiScript function dump_system, from C++
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// <hr>
|
||||
///
|
||||
/// \subsection threading Threading
|
||||
///
|
||||
/// Thread safety is automatically handled within the ChaiScript system. Objects can be added
|
||||
/// and scripts executed from multiple threads. For each thread that executes scripts, a new
|
||||
/// context is created and managed by the engine.
|
||||
///
|
||||
/// Thread safety can be disabled by defining CHAISCRIPT_NO_THREADS when using the library.
|
||||
///
|
||||
/// Disabling thread safety increases performance and removes the requirement for boost_threads.
|
||||
///
|
||||
/// <hr>
|
||||
///
|
||||
/// \subsection exceptions Exception Handling
|
||||
///
|
||||
/// Exceptions can be thrown in ChaiScript and caught in C++ or thrown in C++ and caught in
|
||||
/// ChaiScript.
|
||||
///
|
||||
/// \code
|
||||
/// void throwexception()
|
||||
/// {
|
||||
/// throw std::runtime_error("err");
|
||||
/// }
|
||||
///
|
||||
/// int main()
|
||||
/// {
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::fun(&throwexception), "throwexception");
|
||||
/// chai("try { throwexception(); } catch (e) { print(e.what()); }"); // prints "err"
|
||||
///
|
||||
/// try {
|
||||
/// chai("throw(1)");
|
||||
/// } catch (chaiscript::Boxed_Value bv) {
|
||||
/// int i = chaiscript::boxed_cast<int>(bv);
|
||||
/// // i == 1
|
||||
/// }
|
||||
/// }
|
||||
/// \endcode
|
||||
|
||||
/// \page LangObjectSystemRef ChaiScript Language Object Model Reference
|
||||
///
|
||||
///
|
||||
/// ChaiScript has an object system built in, for types defined within the ChaiScript system.
|
||||
///
|
||||
/// \code
|
||||
/// attr Rectangle::height
|
||||
/// attr Rectangle::width
|
||||
/// def Rectangle::Rectangle() { this.height = 10; this.width = 20 }
|
||||
/// def Rectangle::area() { this.height * this.width }
|
||||
///
|
||||
/// var rect = Rectangle()
|
||||
/// rect.height = 30
|
||||
/// print(rect.area())
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keywordattr
|
||||
/// \sa \ref keyworddef
|
||||
|
||||
/// \page LangInPlaceRef ChaiScript Language In-Place Creation Reference
|
||||
/// \section inplacevector Vector
|
||||
///
|
||||
/// \code
|
||||
/// In-place Vector ::= "[" [expression ("," expression)*] "]"
|
||||
/// \endcode
|
||||
///
|
||||
/// \section inplacerangedvector Ranged Vector
|
||||
///
|
||||
/// \code
|
||||
/// In-place Ranged Vector ::= "[" value ".." value "]"
|
||||
/// \endcode
|
||||
///
|
||||
/// Creates a vector over a range (eg. 1..10)
|
||||
///
|
||||
/// \section inplacemap Map
|
||||
///
|
||||
/// \code
|
||||
/// In-place Map ::= "[" (string ":" expression)+ "]"
|
||||
/// \endcode
|
||||
|
||||
/// \page LangKeywordRef ChaiScript Language Keyword Reference
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordattr attr
|
||||
/// Defines a ChaiScript object attribute
|
||||
///
|
||||
/// \code
|
||||
/// Attribute Definition ::= "attr" class_name "::" attribute_name
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref LangObjectSystemRef
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordbreak break
|
||||
/// Stops execution of a looping block.
|
||||
///
|
||||
/// \code
|
||||
/// Break Statement ::= "break"
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keywordfor
|
||||
/// \sa \ref keywordwhile
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keyworddef def
|
||||
/// Begins a function or method definition
|
||||
///
|
||||
/// \code
|
||||
/// Function Definition ::= [annotation + CR/LF] "def" identifier "(" [arg ("," arg)*] ")" [":" guard] block
|
||||
/// Method Definition ::= [annotation + CR/LF] "def" class_name "::" method_name "(" [arg ("," arg)*] ")" [":" guard] block
|
||||
/// \endcode
|
||||
///
|
||||
/// annotation: meta-annotation on function, currently used as documentation. Optional.
|
||||
/// identifier: name of function. Required.
|
||||
/// args: comma-delimited list of parameter names. Optional.
|
||||
/// guards: guarding statement that act as a prerequisite for the function. Optional.
|
||||
/// { }: scoped block as function body. Required.
|
||||
///
|
||||
/// Functions return values in one of two ways:
|
||||
///
|
||||
/// By using an explicit return call, optionally passing the value to be returned.
|
||||
/// By implicitly returning the value of the last expression (if it is not a while or for loop).
|
||||
///
|
||||
/// Method definitions for known types extend those types with new methods. This includes C++ and ChaiScript defined types.
|
||||
/// Method definitions for unknown types implicitly define the named type.
|
||||
///
|
||||
/// \sa \ref LangObjectSystemRef
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordelse else
|
||||
/// \sa \ref keywordif
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordfor for
|
||||
/// \code
|
||||
/// For Block ::= "for" "(" [initial] ";" stop_condition ";" loop_expression ")" block
|
||||
/// \endcode
|
||||
/// This loop can be broken using the \ref keywordbreak command.
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordfun fun
|
||||
/// Begins an anonymous function declaration (sometimes called a lambda).
|
||||
///
|
||||
/// \code
|
||||
/// Lambda ::= "fun" "(" [variable] ("," variable)* ")" block
|
||||
/// \endcode
|
||||
///
|
||||
/// \b Examples:
|
||||
///
|
||||
/// \code
|
||||
/// // Generate an anonymous function object that adds 2 to its parameter
|
||||
/// var f = fun(x) { x + 2; }
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keyworddef for more details on ChaiScript functions
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordif if
|
||||
/// Begins a conditional block of code that only executes if the condition evaluates as true.
|
||||
/// \code
|
||||
/// If Block ::= "if" "(" condition ")" block
|
||||
/// Else If Block ::= "else if" "(" condition ")" block
|
||||
/// Else Block ::= "else" block
|
||||
/// \endcode
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// if (true) {
|
||||
/// // do something
|
||||
/// } else if (false) {
|
||||
/// // do something else
|
||||
/// } else {
|
||||
/// // otherwise do this
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordtry try
|
||||
/// \code
|
||||
/// Try Block ::= "try" block
|
||||
/// ("catch" ["(" variable ")"] [":" guards] block)+
|
||||
/// ["finally" block]
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa ChaiScript_Language::throw
|
||||
///
|
||||
/// <hr>
|
||||
/// \section keywordwhile while
|
||||
///
|
||||
/// Begins a conditional block of code that loops 0 or more times, as long as the condition is true
|
||||
///
|
||||
/// \code
|
||||
/// While Block ::= "while" "(" condition ")" block
|
||||
/// \endcode
|
||||
/// This loop can be broken using the \ref keywordbreak command.
|
||||
|
||||
|
||||
/// \namespace chaiscript
|
||||
/// \brief Namespace chaiscript contains every API call that the average user will be concerned with.
|
||||
|
||||
/// \namespace chaiscript::detail
|
||||
/// \brief Classes and functions reserved for internal use. Items in this namespace are not supported.
|
||||
|
||||
#include "dispatchkit/dispatchkit.hpp"
|
||||
#include "dispatchkit/bootstrap.hpp"
|
||||
#include "dispatchkit/bootstrap_stl.hpp"
|
||||
#include "dispatchkit/function_call.hpp"
|
||||
#include "dispatchkit/dynamic_object.hpp"
|
||||
#include "dispatchkit/boxed_pod_value.hpp"
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* Types of AST nodes available to the parser and eval
|
||||
*/
|
||||
class Token_Type { public: enum Type { Error, Int, Float, Id, Char, Str, Eol, Fun_Call, Arg_List, Variable, Equation, Var_Decl,
|
||||
Expression, Comparison, Additive, Multiplicative, Negate, Not, Array_Call, Dot_Access, Quoted_String, Single_Quoted_String,
|
||||
Lambda, Block, Def, While, If, For, Inline_Array, Inline_Map, Return, File, Prefix, Break, Map_Pair, Value_Range,
|
||||
Inline_Range, Annotation }; };
|
||||
|
||||
/**
|
||||
* Helper lookup to get the name of each node type
|
||||
*/
|
||||
const char *token_type_to_string(int tokentype) {
|
||||
const char *token_types[] = { "Internal Parser Error", "Int", "Float", "Id", "Char", "Str", "Eol", "Fun_Call", "Arg_List", "Variable", "Equation", "Var_Decl",
|
||||
"Expression", "Comparison", "Additive", "Multiplicative", "Negate", "Not", "Array_Call", "Dot_Access", "Quoted_String", "Single_Quoted_String",
|
||||
"Lambda", "Block", "Def", "While", "If", "For", "Inline_Array", "Inline_Map", "Return", "File", "Prefix", "Break", "Map_Pair", "Value_Range",
|
||||
"Inline_Range", "Annotation"};
|
||||
|
||||
return token_types[tokentype];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience type for file positions
|
||||
*/
|
||||
struct File_Position {
|
||||
int line;
|
||||
int column;
|
||||
|
||||
File_Position(int file_line, int file_column)
|
||||
: line(file_line), column(file_column) { }
|
||||
|
||||
File_Position() : line(0), column(0) { }
|
||||
};
|
||||
|
||||
typedef boost::shared_ptr<struct Token> TokenPtr;
|
||||
|
||||
/**
|
||||
* The struct that doubles as both a parser token and an AST node
|
||||
*/
|
||||
struct Token {
|
||||
std::string text;
|
||||
int identifier;
|
||||
const char *filename;
|
||||
File_Position start, end;
|
||||
|
||||
std::vector<TokenPtr> children;
|
||||
TokenPtr annotation;
|
||||
|
||||
Token(const std::string &token_text, int id, const char *fname) : text(token_text), identifier(id), filename(fname) { }
|
||||
|
||||
Token(const std::string &token_text, int id, const char *fname, int start_line, int start_col, int end_line, int end_col) :
|
||||
text(token_text), identifier(id), filename(fname) {
|
||||
|
||||
start.line = start_line;
|
||||
start.column = start_col;
|
||||
end.line = end_line;
|
||||
end.column = end_col;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Errors generated inside the parser
|
||||
*/
|
||||
struct Parse_Error : public std::runtime_error {
|
||||
std::string reason;
|
||||
File_Position position;
|
||||
const char *filename;
|
||||
|
||||
Parse_Error(const std::string &why, const File_Position &where, const char *fname) :
|
||||
std::runtime_error("Parse error: \"" + why + "\" in '"
|
||||
+ std::string(fname) + "' at: (" + boost::lexical_cast<std::string>(where.line+1) + ", " +
|
||||
boost::lexical_cast<std::string>(where.column) + ")"),
|
||||
reason(why), position(where), filename(fname)
|
||||
{ }
|
||||
|
||||
Parse_Error(const std::string &why, const TokenPtr &where)
|
||||
: std::runtime_error("Parse error: \"" + why + "\" in '"
|
||||
+ where->filename + "' line: " + boost::lexical_cast<std::string>(where->start.line+1)),
|
||||
reason(why), position(where->start), filename(where->filename) {
|
||||
}
|
||||
|
||||
virtual ~Parse_Error() throw() {}
|
||||
};
|
||||
|
||||
/**
|
||||
* Errors generated inside the evaluator
|
||||
*/
|
||||
struct Eval_Error : public std::runtime_error {
|
||||
std::string reason;
|
||||
TokenPtr location;
|
||||
|
||||
Eval_Error(const std::string &why, const TokenPtr where)
|
||||
: std::runtime_error("Eval error: \"" + why + "\" in '"
|
||||
+ where->filename + "' line: " + boost::lexical_cast<std::string>(where->start.line+1)),
|
||||
reason(why), location(where) { }
|
||||
|
||||
virtual ~Eval_Error() throw() {}
|
||||
};
|
||||
|
||||
/**
|
||||
* Special type for returned values
|
||||
*/
|
||||
struct Return_Value {
|
||||
dispatchkit::Boxed_Value retval;
|
||||
TokenPtr location;
|
||||
|
||||
Return_Value(const dispatchkit::Boxed_Value &return_value, const TokenPtr where) : retval(return_value), location(where) { }
|
||||
};
|
||||
|
||||
/**
|
||||
* Special type indicating a call to 'break'
|
||||
*/
|
||||
struct Break_Loop {
|
||||
TokenPtr location;
|
||||
|
||||
Break_Loop(const TokenPtr where) : location(where) { }
|
||||
};
|
||||
}
|
||||
#ifdef BOOST_HAS_DECLSPEC
|
||||
#define CHAISCRIPT_MODULE_EXPORT extern "C" __declspec(dllexport)
|
||||
#else
|
||||
#define CHAISCRIPT_MODULE_EXPORT extern "C"
|
||||
#endif
|
||||
|
||||
#include "language/chaiscript_eval.hpp"
|
||||
#include "language/chaiscript_engine.hpp"
|
||||
|
126
include/chaiscript/chaiscript_threading.hpp
Normal file
126
include/chaiscript/chaiscript_threading.hpp
Normal file
@@ -0,0 +1,126 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_THREADING_HPP_
|
||||
#define CHAISCRIPT_THREADING_HPP_
|
||||
|
||||
#ifndef CHAISCRIPT_NO_THREADS
|
||||
#include <boost/thread.hpp>
|
||||
#else
|
||||
#pragma message ("ChaiScript is compiling without thread safety.")
|
||||
#endif
|
||||
|
||||
/// \file
|
||||
///
|
||||
/// This file contains code necessary for thread support in ChaiScript.
|
||||
/// If the compiler definition CHAISCRIPT_NO_THREADS is defined then thread safety
|
||||
/// is disabled in ChaiScript. This has the result that some code is faster, because mutex locks are not required.
|
||||
/// It also has the side effect that the chaiscript::ChaiScript object may not be accessed from more than
|
||||
/// one thread simultaneously.
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/// If threading is enabled, then this namespace contains boost::thread classes.
|
||||
/// If threading is not enabled, then stubbed in wrappers that do nothing are provided.
|
||||
/// This allows us to avoid \#ifdef code in the sections that need thread safety.
|
||||
namespace threading
|
||||
{
|
||||
|
||||
#ifndef CHAISCRIPT_NO_THREADS
|
||||
using boost::unique_lock;
|
||||
using boost::shared_lock;
|
||||
using boost::lock_guard;
|
||||
using boost::shared_mutex;
|
||||
using boost::recursive_mutex;
|
||||
|
||||
|
||||
/// Typesafe thread specific storage. If threading is enabled, this class uses boost::thread_specific_ptr<T>. If
|
||||
/// threading is not enabled, the class always returns the same data, regardless of which thread it is called from.
|
||||
template<typename T>
|
||||
class Thread_Storage
|
||||
{
|
||||
public:
|
||||
~Thread_Storage()
|
||||
{
|
||||
m_thread_storage.reset();
|
||||
}
|
||||
|
||||
inline T *operator->() const
|
||||
{
|
||||
if (!m_thread_storage.get())
|
||||
{
|
||||
m_thread_storage.reset(new T());
|
||||
}
|
||||
|
||||
return m_thread_storage.get();
|
||||
}
|
||||
|
||||
inline T &operator*() const
|
||||
{
|
||||
return *(this->operator->());
|
||||
}
|
||||
|
||||
private:
|
||||
mutable boost::thread_specific_ptr<T> m_thread_storage;
|
||||
};
|
||||
|
||||
#else
|
||||
template<typename T>
|
||||
class unique_lock
|
||||
{
|
||||
public:
|
||||
unique_lock(T &) {}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class shared_lock
|
||||
{
|
||||
public:
|
||||
shared_lock(T &) {}
|
||||
void unlock() {}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class lock_guard
|
||||
{
|
||||
public:
|
||||
lock_guard(T &) {}
|
||||
};
|
||||
|
||||
class shared_mutex { };
|
||||
|
||||
class recursive_mutex {};
|
||||
|
||||
|
||||
template<typename T>
|
||||
class Thread_Storage
|
||||
{
|
||||
public:
|
||||
inline T *operator->() const
|
||||
{
|
||||
return &obj;
|
||||
}
|
||||
|
||||
inline T &operator*() const
|
||||
{
|
||||
return obj;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable T obj;
|
||||
};
|
||||
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
60
include/chaiscript/dispatchkit/bad_boxed_cast.hpp
Normal file
60
include/chaiscript/dispatchkit/bad_boxed_cast.hpp
Normal file
@@ -0,0 +1,60 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_BAD_BOXED_CAST_HPP_
|
||||
#define CHAISCRIPT_BAD_BOXED_CAST_HPP_
|
||||
|
||||
#include "type_info.hpp"
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace exception
|
||||
{
|
||||
/// \brief Thrown in the event that a Boxed_Value cannot be cast to the desired type
|
||||
///
|
||||
/// It is used internally during function dispatch and may be used by the end user.
|
||||
///
|
||||
/// \sa chaiscript::boxed_cast
|
||||
class bad_boxed_cast : public std::bad_cast
|
||||
{
|
||||
public:
|
||||
bad_boxed_cast(const Type_Info &t_from, const std::type_info &t_to,
|
||||
const std::string &t_what) throw()
|
||||
: from(t_from), to(&t_to), m_what(t_what)
|
||||
{
|
||||
}
|
||||
|
||||
bad_boxed_cast(const Type_Info &t_from, const std::type_info &t_to) throw()
|
||||
: from(t_from), to(&t_to), m_what("Cannot perform boxed_cast")
|
||||
{
|
||||
}
|
||||
|
||||
bad_boxed_cast(const std::string &t_what) throw()
|
||||
: m_what(t_what)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~bad_boxed_cast() throw() {}
|
||||
|
||||
/// \brief Description of what error occured
|
||||
virtual const char * what() const throw()
|
||||
{
|
||||
return m_what.c_str();
|
||||
}
|
||||
|
||||
Type_Info from; ///< Type_Info contained in the Boxed_Value
|
||||
const std::type_info *to; ///< std::type_info of the desired (but failed) result type
|
||||
|
||||
private:
|
||||
std::string m_what;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
93
include/chaiscript/dispatchkit/bind_first.hpp
Normal file
93
include/chaiscript/dispatchkit/bind_first.hpp
Normal file
@@ -0,0 +1,93 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
#include <boost/preprocessor/arithmetic/inc.hpp>
|
||||
|
||||
#define param(z,n,text) BOOST_PP_CAT(text, BOOST_PP_INC(n))
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef CHAISCRIPT_BIND_FIRST_HPP_
|
||||
#define CHAISCRIPT_BIND_FIRST_HPP_
|
||||
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/ref.hpp>
|
||||
|
||||
#define BOOST_PP_ITERATION_LIMITS ( 0, 8 )
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/bind_first.hpp>
|
||||
|
||||
#include BOOST_PP_ITERATE()
|
||||
|
||||
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
# define m BOOST_PP_INC(n)
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/// \brief Helper function for binding the first parameter of a class method pointer. Used in chaiscript::fun overloads
|
||||
/// that take 1 or 2 parameters to pre-bind to the function.
|
||||
///
|
||||
/// \param[in] f method pointer to bind
|
||||
/// \param[in] o object to bind as first parameter
|
||||
/// \returns a new boost::function object with one fewer parameters than the function passed in.
|
||||
template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
|
||||
bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const O &o)
|
||||
{
|
||||
return boost::bind(boost::mem_fn(f), o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, _));
|
||||
}
|
||||
|
||||
/// \brief Helper function for binding the first parameter of a const class method pointer. Used in chaiscript::fun overloads
|
||||
/// that take 1 or 2 parameters to pre-bind to the function.
|
||||
///
|
||||
/// \param[in] f method pointer to bind
|
||||
/// \param[in] o object to bind as first parameter
|
||||
/// \returns a new boost::function object with one fewer parameters than the function passed in.
|
||||
template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
|
||||
bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)) const, const O &o)
|
||||
{
|
||||
return boost::bind(boost::mem_fn(f), o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, _));
|
||||
}
|
||||
|
||||
/// \brief Helper function for binding the first parameter of a function pointer. Used in chaiscript::fun overloads
|
||||
/// that take 1 or 2 parameters to pre-bind to the function.
|
||||
///
|
||||
/// \param[in] f method pointer to bind
|
||||
/// \param[in] o object to bind as first parameter
|
||||
/// \returns a new boost::function object with one fewer parameters than the function passed in.
|
||||
template<typename Ret,typename O BOOST_PP_COMMA_IF(m) BOOST_PP_ENUM_PARAMS(m, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM(n, param, Param))>
|
||||
bind_first(Ret (*f)(BOOST_PP_ENUM_PARAMS(m, Param)), const O &o)
|
||||
{
|
||||
return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, _));
|
||||
}
|
||||
|
||||
/// \brief Helper function for binding the first parameter of a boost::function object. Used in chaiscript::fun overloads
|
||||
/// that take 1 or 2 parameters to pre-bind to the function.
|
||||
///
|
||||
/// \param[in] f method pointer to bind
|
||||
/// \param[in] o object to bind as first parameter
|
||||
/// \returns a new boost::function object with one fewer parameters than the function passed in.
|
||||
template<typename Ret,typename O BOOST_PP_COMMA_IF(m) BOOST_PP_ENUM_PARAMS(m, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM(n, param, Param))>
|
||||
bind_first(const boost::function<Ret (BOOST_PP_ENUM_PARAMS(m, Param))> &f, const O &o)
|
||||
{
|
||||
return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, _));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#undef n
|
||||
#undef m
|
||||
|
||||
#endif
|
File diff suppressed because it is too large
Load Diff
@@ -1,383 +1,536 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
/**
|
||||
* \file
|
||||
* This file contains utility functions for registration of STL container
|
||||
* classes. The methodology used is based on the SGI STL concepts.
|
||||
* http://www.sgi.com/tech/stl/table_of_contents.html
|
||||
*/
|
||||
|
||||
#ifndef __bootstrap_stl_hpp
|
||||
#define __bootstrap_stl_hpp__
|
||||
|
||||
|
||||
#ifndef CHAISCRIPT_BOOTSTRAP_STL_HPP_
|
||||
#define CHAISCRIPT_BOOTSTRAP_STL_HPP_
|
||||
|
||||
#include "dispatchkit.hpp"
|
||||
#include "register_function.hpp"
|
||||
|
||||
|
||||
namespace dispatchkit
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* Input_Range, based on the D concept of ranges.
|
||||
* \todo Update the Range code to base its capabilities on
|
||||
* the type_traits of the iterator passed in
|
||||
*/
|
||||
template<typename Container>
|
||||
struct Input_Range
|
||||
namespace bootstrap
|
||||
{
|
||||
namespace standard_library
|
||||
{
|
||||
Input_Range(Container &c)
|
||||
: m_begin(c.begin()), m_end(c.end())
|
||||
{
|
||||
}
|
||||
|
||||
Input_Range(typename Container::iterator itr)
|
||||
: m_begin(itr), m_end(itr)
|
||||
{
|
||||
}
|
||||
|
||||
Input_Range(const std::pair<typename Container::iterator, typename Container::iterator> &t_p)
|
||||
: m_begin(t_p.first), m_end(t_p.second)
|
||||
{
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return m_begin == m_end;
|
||||
}
|
||||
|
||||
void pop_front()
|
||||
{
|
||||
if (empty())
|
||||
/**
|
||||
* Bidir_Range, based on the D concept of ranges.
|
||||
* \todo Update the Range code to base its capabilities on
|
||||
* the user_typetraits of the iterator passed in
|
||||
*/
|
||||
template<typename Container>
|
||||
struct Bidir_Range
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
++m_begin;
|
||||
}
|
||||
typedef Container container_type;
|
||||
typedef typename std::iterator_traits<typename Container::iterator>::reference reference_type;
|
||||
|
||||
typename std::iterator_traits<typename Container::iterator>::reference front() const
|
||||
{
|
||||
if (empty())
|
||||
Bidir_Range(Container &c)
|
||||
: m_begin(c.begin()), m_end(c.end())
|
||||
{
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return m_begin == m_end;
|
||||
}
|
||||
|
||||
void pop_front()
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
++m_begin;
|
||||
}
|
||||
|
||||
void pop_back()
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
--m_end;
|
||||
}
|
||||
|
||||
reference_type front() const
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
return *m_begin;
|
||||
}
|
||||
|
||||
reference_type back() const
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
typename Container::iterator pos = m_end;
|
||||
--pos;
|
||||
return *(pos);
|
||||
}
|
||||
|
||||
typename Container::iterator m_begin;
|
||||
typename Container::iterator m_end;
|
||||
};
|
||||
|
||||
template<typename Container>
|
||||
struct Const_Bidir_Range
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
typedef const Container container_type;
|
||||
typedef typename std::iterator_traits<typename Container::const_iterator>::reference const_reference_type;
|
||||
|
||||
Const_Bidir_Range(const Container &c)
|
||||
: m_begin(c.begin()), m_end(c.end())
|
||||
{
|
||||
}
|
||||
|
||||
bool empty() const
|
||||
{
|
||||
return m_begin == m_end;
|
||||
}
|
||||
|
||||
void pop_front()
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
++m_begin;
|
||||
}
|
||||
|
||||
void pop_back()
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
--m_end;
|
||||
}
|
||||
|
||||
const_reference_type front() const
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
return *m_begin;
|
||||
}
|
||||
|
||||
const_reference_type back() const
|
||||
{
|
||||
if (empty())
|
||||
{
|
||||
throw std::range_error("Range empty");
|
||||
}
|
||||
typename Container::const_iterator pos = m_end;
|
||||
--pos;
|
||||
return *(pos);
|
||||
}
|
||||
|
||||
typename Container::const_iterator m_begin;
|
||||
typename Container::const_iterator m_end;
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
/**
|
||||
* Add Bidir_Range support for the given ContainerType
|
||||
*/
|
||||
template<typename Bidir_Type>
|
||||
ModulePtr input_range_type_impl(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<Bidir_Type>(), type + "_Range");
|
||||
|
||||
copy_constructor<Bidir_Type>(type + "_Range", m);
|
||||
|
||||
m->add(constructor<Bidir_Type (typename Bidir_Type::container_type &)>(), "range");
|
||||
|
||||
m->add(fun(&Bidir_Type::empty), "empty");
|
||||
m->add(fun(&Bidir_Type::pop_front), "pop_front");
|
||||
m->add(fun(&Bidir_Type::front), "front");
|
||||
m->add(fun(&Bidir_Type::pop_back), "pop_back");
|
||||
m->add(fun(&Bidir_Type::back), "back");
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Algorithm for inserting at a specific position into a container
|
||||
*/
|
||||
template<typename Type>
|
||||
void insert_at(Type &container, int pos, const typename Type::value_type &v)
|
||||
{
|
||||
typename Type::iterator itr = container.begin();
|
||||
typename Type::iterator end = container.end();
|
||||
|
||||
if (pos < 0 || std::distance(itr, end) < pos)
|
||||
{
|
||||
throw std::range_error("Cannot insert past end of range");
|
||||
}
|
||||
|
||||
std::advance(itr, pos);
|
||||
container.insert(itr, v);
|
||||
}
|
||||
|
||||
/**
|
||||
* Algorithm for erasing a specific position from a container
|
||||
*/
|
||||
template<typename Type>
|
||||
void erase_at(Type &container, int pos)
|
||||
{
|
||||
typename Type::iterator itr = container.begin();
|
||||
typename Type::iterator end = container.end();
|
||||
|
||||
if (pos < 0 || std::distance(itr, end) < (pos-1))
|
||||
{
|
||||
throw std::range_error("Cannot erase past end of range");
|
||||
}
|
||||
|
||||
std::advance(itr, pos);
|
||||
container.erase(itr);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
template<typename ContainerType>
|
||||
ModulePtr input_range_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
detail::input_range_type_impl<Bidir_Range<ContainerType> >(type,m);
|
||||
detail::input_range_type_impl<Const_Bidir_Range<ContainerType> >("Const_" + type, m);
|
||||
return m;
|
||||
}
|
||||
return *m_begin;
|
||||
}
|
||||
|
||||
typename Container::iterator m_begin;
|
||||
typename Container::iterator m_end;
|
||||
};
|
||||
/**
|
||||
* Add random_access_container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/RandomAccessContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr random_access_container_type(const std::string &/*type*/, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
typedef typename ContainerType::reference(ContainerType::*indexoper)(size_t);
|
||||
typedef typename ContainerType::const_reference(ContainerType::*constindexoper)(size_t) const;
|
||||
|
||||
|
||||
/**
|
||||
* Add Input_Range support for the given ContainerType
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_input_range(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_type<Input_Range<ContainerType> >(type+"_Range");
|
||||
system.register_type<typename ContainerType::iterator>(type+"_Iterator");
|
||||
//In the interest of runtime safety for the m, we prefer the at() method for [] access,
|
||||
//to throw an exception in an out of bounds condition.
|
||||
m->add(
|
||||
fun(boost::function<typename ContainerType::reference (ContainerType *, int)>
|
||||
(boost::mem_fn(static_cast<indexoper>(&ContainerType::at)))), "[]");
|
||||
m->add(
|
||||
fun(boost::function<typename ContainerType::const_reference (const ContainerType *, int)>
|
||||
(boost::mem_fn(static_cast<constindexoper>(&ContainerType::at)))), "[]");
|
||||
|
||||
system.register_function(build_constructor<Input_Range<ContainerType>, ContainerType &>(), "range");
|
||||
system.register_function(build_constructor<Input_Range<ContainerType>,
|
||||
typename ContainerType::iterator>(), "range");
|
||||
return m;
|
||||
}
|
||||
|
||||
typedef std::pair<typename ContainerType::iterator, typename ContainerType::iterator> ItrPair;
|
||||
/**
|
||||
* Add assignable concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Assignable.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr assignable_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
basic_constructors<ContainerType>(type, m);
|
||||
operators::assign<ContainerType>(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
system.register_function(build_constructor<Input_Range<ContainerType>,
|
||||
const ItrPair &>(), "range");
|
||||
system.register_type<ItrPair>(type+"_Iterator_Pair");
|
||||
/**
|
||||
* Add container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Container.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr container_type(const std::string &/*type*/, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(boost::function<int (const ContainerType *)>(boost::mem_fn(&ContainerType::size))), "size");
|
||||
m->add(fun<bool (ContainerType::*)() const>(&ContainerType::empty), "empty");
|
||||
m->add(fun<void (ContainerType::*)()>(&ContainerType::clear), "clear");
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add default constructable concept to the given Type
|
||||
* http://www.sgi.com/tech/stl/DefaultConstructible.html
|
||||
*/
|
||||
template<typename Type>
|
||||
ModulePtr default_constructible_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(constructor<Type ()>(), type);
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
register_function(system, &Input_Range<ContainerType>::empty, "empty");
|
||||
register_function(system, &Input_Range<ContainerType>::pop_front, "pop_front");
|
||||
register_function(system, &Input_Range<ContainerType>::front, "front");
|
||||
system.register_function(build_constructor<Input_Range<ContainerType>, const Input_Range<ContainerType> &>(), "clone");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add reversible_container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/ReversibleContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_reversible_container(Dispatch_Engine &/*system*/, const std::string &/*type*/)
|
||||
{
|
||||
|
||||
/**
|
||||
* Add sequence concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Sequence.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr sequence_type(const std::string &/*type*/, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
std::string insert_name;
|
||||
if (typeid(typename ContainerType::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
insert_name = "insert_ref_at";
|
||||
} else {
|
||||
insert_name = "insert_at";
|
||||
}
|
||||
|
||||
m->add(fun(&detail::insert_at<ContainerType>), insert_name);
|
||||
m->add(fun(&detail::erase_at<ContainerType>), "erase_at");
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add back insertion sequence concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/BackInsertionSequence.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr back_insertion_sequence_type(const std::string &/*type*/, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
typedef typename ContainerType::reference (ContainerType::*backptr)();
|
||||
|
||||
m->add(fun(static_cast<backptr>(&ContainerType::back)), "back");
|
||||
|
||||
std::string push_back_name;
|
||||
if (typeid(typename ContainerType::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
push_back_name = "push_back_ref";
|
||||
} else {
|
||||
push_back_name = "push_back";
|
||||
}
|
||||
|
||||
typedef void (ContainerType::*pushback)(const typename ContainerType::value_type &);
|
||||
m->add(fun(static_cast<pushback>(&ContainerType::push_back)), push_back_name);
|
||||
m->add(fun(&ContainerType::pop_back), "pop_back");
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*Front insertion sequence
|
||||
*http://www.sgi.com/tech/stl/FrontInsertionSequence.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr front_insertion_sequence_type(const std::string &, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
typedef typename ContainerType::reference (ContainerType::*frontptr)();
|
||||
typedef void (ContainerType::*pushptr)(typename ContainerType::const_reference);
|
||||
typedef void (ContainerType::*popptr)();
|
||||
|
||||
m->add(fun(static_cast<frontptr>(&ContainerType::front)), "front");
|
||||
|
||||
std::string push_front_name;
|
||||
if (typeid(typename ContainerType::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
push_front_name = "push_front_ref";
|
||||
} else {
|
||||
push_front_name = "push_front";
|
||||
}
|
||||
|
||||
m->add(fun(static_cast<pushptr>(&ContainerType::push_front)), push_front_name);
|
||||
m->add(fun(static_cast<popptr>(&ContainerType::pop_front)), "pop_front");
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* bootstrap a given PairType
|
||||
* http://www.sgi.com/tech/stl/pair.html
|
||||
*/
|
||||
template<typename PairType>
|
||||
ModulePtr pair_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<PairType>(), type);
|
||||
|
||||
|
||||
typename PairType::first_type PairType::* f = &PairType::first;
|
||||
typename PairType::second_type PairType::* s = &PairType::second;
|
||||
|
||||
m->add(fun(f), "first");
|
||||
m->add(fun(s), "second");
|
||||
|
||||
basic_constructors<PairType>(type, m);
|
||||
m->add(constructor<PairType (const typename PairType::first_type &, const typename PairType::second_type &)>(), type);
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add pair associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/PairAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr pair_associative_container_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
pair_type<typename ContainerType::value_type>(type + "_Pair", m);
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add unique associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/UniqueAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
ModulePtr unique_associative_container_type(const std::string &/*type*/, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(boost::function<int (const ContainerType *, const typename ContainerType::key_type &)>(boost::mem_fn(&ContainerType::count))), "count");
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a MapType container
|
||||
* http://www.sgi.com/tech/stl/Map.html
|
||||
*/
|
||||
template<typename MapType>
|
||||
ModulePtr map_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<MapType>(), type);
|
||||
|
||||
typedef typename MapType::mapped_type &(MapType::*elemaccess)(const typename MapType::key_type &);
|
||||
|
||||
m->add(fun(static_cast<elemaccess>(&MapType::operator[])), "[]");
|
||||
|
||||
container_type<MapType>(type, m);
|
||||
assignable_type<MapType>(type, m);
|
||||
unique_associative_container_type<MapType>(type, m);
|
||||
pair_associative_container_type<MapType>(type, m);
|
||||
input_range_type<MapType>(type, m);
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* hopefully working List type
|
||||
* http://www.sgi.com/tech/stl/List.html
|
||||
*/
|
||||
template<typename ListType>
|
||||
ModulePtr list_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<ListType>(), type);
|
||||
|
||||
front_insertion_sequence_type<ListType>(type, m);
|
||||
back_insertion_sequence_type<ListType>(type, m);
|
||||
sequence_type<ListType>(type, m);
|
||||
container_type<ListType>(type, m);
|
||||
default_constructible_type<ListType>(type, m);
|
||||
assignable_type<ListType>(type, m);
|
||||
input_range_type<ListType>(type, m);
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a vector type with associated concepts
|
||||
* http://www.sgi.com/tech/stl/Vector.html
|
||||
*/
|
||||
template<typename VectorType>
|
||||
ModulePtr vector_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<VectorType>(), type);
|
||||
|
||||
typedef typename VectorType::reference (VectorType::*frontptr)();
|
||||
m->add(fun(static_cast<frontptr>(&VectorType::front)), "front");
|
||||
|
||||
|
||||
back_insertion_sequence_type<VectorType>(type, m);
|
||||
sequence_type<VectorType>(type, m);
|
||||
random_access_container_type<VectorType>(type, m);
|
||||
container_type<VectorType>(type, m);
|
||||
default_constructible_type<VectorType>(type, m);
|
||||
assignable_type<VectorType>(type, m);
|
||||
input_range_type<VectorType>(type, m);
|
||||
|
||||
if (typeid(VectorType) == typeid(std::vector<Boxed_Value>))
|
||||
{
|
||||
m->eval("def Vector::`==`(rhs) : type_match(rhs, this) { \
|
||||
if ( rhs.size() != this.size() ) { \
|
||||
return false; \
|
||||
} else { \
|
||||
var r1 = range(this); \
|
||||
var r2 = range(rhs); \
|
||||
while (!r1.empty()) \
|
||||
{ \
|
||||
if (!eq(r1.front(), r2.front())) \
|
||||
{ \
|
||||
return false; \
|
||||
} \
|
||||
r1.pop_front(); \
|
||||
r2.pop_front(); \
|
||||
} \
|
||||
return true; \
|
||||
} \
|
||||
}");
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a String container
|
||||
* http://www.sgi.com/tech/stl/basic_string.html
|
||||
*/
|
||||
template<typename String>
|
||||
ModulePtr string_type(const std::string &type, ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(user_type<String>(), type);
|
||||
operators::addition<String>(m);
|
||||
operators::assign_sum<String>(m);
|
||||
opers_comparison<String>(m);
|
||||
random_access_container_type<String>(type, m);
|
||||
sequence_type<String>(type, m);
|
||||
default_constructible_type<String>(type, m);
|
||||
container_type<String>(type, m);
|
||||
assignable_type<String>(type, m);
|
||||
input_range_type<String>(type, m);
|
||||
|
||||
//Special case: add push_back to string (which doesn't support other back_insertion operations
|
||||
std::string push_back_name;
|
||||
if (typeid(typename String::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
push_back_name = "push_back_ref";
|
||||
} else {
|
||||
push_back_name = "push_back";
|
||||
}
|
||||
m->add(fun(&String::push_back), push_back_name);
|
||||
|
||||
typedef typename String::size_type (String::*find_func_ptr)(const String &, typename String::size_type) const;
|
||||
|
||||
typedef boost::function<int (const String *, const String &, int)> find_func;
|
||||
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::find)))), "find");
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::rfind)))), "rfind");
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::find_first_of)))), "find_first_of");
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::find_last_of)))), "find_last_of");
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::find_first_not_of)))), "find_first_not_of");
|
||||
m->add(fun(find_func(boost::mem_fn(static_cast<find_func_ptr>(&String::find_last_not_of)))), "find_last_not_of");
|
||||
|
||||
m->add(fun(&String::c_str), "c_str");
|
||||
m->add(fun(&String::data), "data");
|
||||
|
||||
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add random_access_container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/RandomAccessContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_random_access_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_reversible_container<ContainerType>(system, type);
|
||||
typedef typename ContainerType::reference(ContainerType::*indexoper)(size_t);
|
||||
|
||||
//In the interest of runtime safety for the system, we prefer the at() method for [] access,
|
||||
//to throw an exception in an out of bounds condition.
|
||||
system.register_function(
|
||||
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::at)), "[]");
|
||||
system.register_function(
|
||||
boost::function<typename ContainerType::reference (ContainerType *, int)>(indexoper(&ContainerType::operator[])), "at");
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Add assignable concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Assignable.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_assignable(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
add_basic_constructors<ContainerType>(system, type);
|
||||
add_oper_assign<ContainerType>(system);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Container.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_assignable<ContainerType>(system, type);
|
||||
|
||||
register_function(system, &ContainerType::size, "size");
|
||||
register_function(system, &ContainerType::max_size, "max_size");
|
||||
register_function(system, &ContainerType::empty, "empty");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add forward container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/ForwardContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_forward_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_input_range<ContainerType>(system, type);
|
||||
bootstrap_container<ContainerType>(system, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add default constructable concept to the given Type
|
||||
* http://www.sgi.com/tech/stl/DefaultConstructible.html
|
||||
*/
|
||||
template<typename Type>
|
||||
void bootstrap_default_constructible(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_function(build_constructor<Type>(), type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Algorithm for inserting at a specific position into a container
|
||||
*/
|
||||
template<typename Type>
|
||||
void insert_at(Type &container, int pos, const typename Type::value_type &v)
|
||||
{
|
||||
typename Type::iterator itr = container.begin();
|
||||
typename Type::iterator end = container.end();
|
||||
|
||||
if (pos < 0 || std::distance(itr, end) < pos)
|
||||
{
|
||||
throw std::range_error("Cannot insert past end of range");
|
||||
}
|
||||
|
||||
std::advance(itr, pos);
|
||||
container.insert(itr, v);
|
||||
}
|
||||
|
||||
/**
|
||||
* Algorithm for erasing a specific position from a container
|
||||
*/
|
||||
template<typename Type>
|
||||
void erase_at(Type &container, int pos)
|
||||
{
|
||||
typename Type::iterator itr = container.begin();
|
||||
typename Type::iterator end = container.end();
|
||||
|
||||
if (pos < 0 || std::distance(itr, end) < (pos-1))
|
||||
{
|
||||
throw std::range_error("Cannot erase past end of range");
|
||||
}
|
||||
|
||||
std::advance(itr, pos);
|
||||
container.erase(itr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add sequence concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/Sequence.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_sequence(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_forward_container<ContainerType>(system, type);
|
||||
bootstrap_default_constructible<ContainerType>(system, type);
|
||||
|
||||
std::string insert_name;
|
||||
if (typeid(typename ContainerType::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
insert_name = "insert_ref_at";
|
||||
} else {
|
||||
insert_name = "insert_at";
|
||||
}
|
||||
|
||||
register_function(system, &insert_at<ContainerType>, insert_name);
|
||||
register_function(system, &erase_at<ContainerType>, "erase_at");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add back insertion sequence concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/BackInsertionSequence.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_back_insertion_sequence(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_sequence<ContainerType>(system, type);
|
||||
|
||||
|
||||
typedef typename ContainerType::reference (ContainerType::*backptr)();
|
||||
|
||||
register_function(system, (backptr(&ContainerType::back)), "back");
|
||||
|
||||
std::string push_back_name;
|
||||
if (typeid(typename ContainerType::value_type) == typeid(Boxed_Value))
|
||||
{
|
||||
push_back_name = "push_back_ref";
|
||||
} else {
|
||||
push_back_name = "push_back";
|
||||
}
|
||||
|
||||
register_function(system, &ContainerType::push_back, push_back_name);
|
||||
register_function(system, &ContainerType::pop_back, "pop_back");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a vector type with associated concepts
|
||||
* http://www.sgi.com/tech/stl/Vector.html
|
||||
*/
|
||||
template<typename VectorType>
|
||||
void bootstrap_vector(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_type<VectorType>(type);
|
||||
bootstrap_random_access_container<VectorType>(system, type);
|
||||
bootstrap_back_insertion_sequence<VectorType>(system, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a vector type with associated concepts
|
||||
* http://www.sgi.com/tech/stl/Vector.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_associative_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_forward_container<ContainerType>(system, type);
|
||||
bootstrap_default_constructible<ContainerType>(system, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* bootstrap a given PairType
|
||||
* http://www.sgi.com/tech/stl/pair.html
|
||||
*/
|
||||
template<typename PairType>
|
||||
void bootstrap_pair(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_type<PairType>(type);
|
||||
|
||||
register_member(system, &PairType::first, "first");
|
||||
register_member(system, &PairType::second, "second");
|
||||
|
||||
system.register_function(build_constructor<PairType >(), type);
|
||||
system.register_function(build_constructor<PairType, const PairType &>(), type);
|
||||
system.register_function(build_constructor<PairType, const PairType &>(), "clone");
|
||||
system.register_function(build_constructor<PairType, const typename PairType::first_type &, const typename PairType::second_type &>(), type);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add pair associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/PairAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_pair_associative_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_associative_container<ContainerType>(system, type);
|
||||
bootstrap_pair<typename ContainerType::value_type>(system, type + "_Pair");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add unique associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/UniqueAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_unique_associative_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_associative_container<ContainerType>(system, type);
|
||||
register_function(system, &ContainerType::count, "count");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add sorted associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/SortedAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
typedef std::pair<typename ContainerType::iterator, typename ContainerType::iterator>
|
||||
(ContainerType::*eq_range)(const typename ContainerType::key_type &);
|
||||
|
||||
bootstrap_reversible_container<ContainerType>(system, type);
|
||||
bootstrap_associative_container<ContainerType>(system, type);
|
||||
register_function(system, eq_range(&ContainerType::equal_range), "equal_range");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add unique sorted associative container concept to the given ContainerType
|
||||
* http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html
|
||||
*/
|
||||
template<typename ContainerType>
|
||||
void bootstrap_unique_sorted_associative_container(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
bootstrap_sorted_associative_container<ContainerType>(system, type);
|
||||
bootstrap_unique_associative_container<ContainerType>(system, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a MapType container
|
||||
* http://www.sgi.com/tech/stl/Map.html
|
||||
*/
|
||||
template<typename MapType>
|
||||
void bootstrap_map(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_type<MapType>(type);
|
||||
register_function(system, &MapType::operator[], "[]");
|
||||
bootstrap_unique_sorted_associative_container<MapType>(system, type);
|
||||
bootstrap_pair_associative_container<MapType>(system, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a String container
|
||||
* http://www.sgi.com/tech/stl/basic_string.html
|
||||
*/
|
||||
template<typename String>
|
||||
void bootstrap_string(Dispatch_Engine &system, const std::string &type)
|
||||
{
|
||||
system.register_type<String>(type);
|
||||
add_oper_add<String>(system);
|
||||
add_oper_add_equals<String>(system);
|
||||
add_opers_comparison<String>(system);
|
||||
bootstrap_random_access_container<String>(system, type);
|
||||
bootstrap_sequence<String>(system, type);
|
||||
typedef typename String::size_type (String::*find_func)(const String &, typename String::size_type) const;
|
||||
register_function(system, find_func(&String::find), "find");
|
||||
register_function(system, find_func(&String::rfind), "rfind");
|
||||
register_function(system, find_func(&String::find_first_of), "find_first_of");
|
||||
register_function(system, find_func(&String::find_last_of), "find_last_of");
|
||||
register_function(system, find_func(&String::find_first_not_of), "find_first_not_of");
|
||||
register_function(system, find_func(&String::find_last_not_of), "find_last_not_of");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
112
include/chaiscript/dispatchkit/boxed_cast.hpp
Normal file
112
include/chaiscript/dispatchkit/boxed_cast.hpp
Normal file
@@ -0,0 +1,112 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef __boxed_cast_hpp__
|
||||
#define __boxed_cast_hpp__
|
||||
|
||||
#include "type_info.hpp"
|
||||
#include "boxed_value.hpp"
|
||||
#include "boxed_cast_helper.hpp"
|
||||
#include "dynamic_cast_conversion.hpp"
|
||||
|
||||
#include "../chaiscript_threading.hpp"
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/any.hpp>
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/ref.hpp>
|
||||
#include <boost/cstdint.hpp>
|
||||
#include <boost/type_traits/add_const.hpp>
|
||||
#include <boost/type_traits/is_polymorphic.hpp>
|
||||
#include <boost/integer_traits.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
|
||||
/// \brief Function for extracting a value stored in a Boxed_Value object
|
||||
/// \tparam Type The type to extract from the Boxed_Value
|
||||
/// \param[in] bv The Boxed_Value to extract a typed value from
|
||||
/// \returns Type equivalent to the requested type
|
||||
/// \throws exception::bad_boxed_cast If the requested conversion is not possible
|
||||
///
|
||||
/// boxed_cast will attempt to make conversions between value, &, *, boost::shared_ptr, boost::reference_wrapper,
|
||||
/// and boost::function (const and non-const) where possible. boxed_cast is used internally during function
|
||||
/// dispatch. This means that all of these conversions will be attempted automatically for you during
|
||||
/// ChaiScript function calls.
|
||||
///
|
||||
/// \li non-const values can be extracted as const or non-const
|
||||
/// \li const values can be extracted only as const
|
||||
/// \li Boxed_Value constructed from pointer or boost::reference_wrapper can be extracted as reference,
|
||||
/// pointer or value types
|
||||
/// \li Boxed_Value constructed from boost::shared_ptr or value types can be extracted as reference,
|
||||
/// pointer, value, or boost::shared_ptr types
|
||||
///
|
||||
/// Conversions to boost::function objects are attempted as well
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// // All of the following should succeed
|
||||
/// chaiscript::Boxed_Value bv(1);
|
||||
/// boost::shared_ptr<int> spi = chaiscript::boxed_cast<boost::shared_ptr<int> >(bv);
|
||||
/// int i = chaiscript::boxed_cast<int>(bv);
|
||||
/// int *ip = chaiscript::boxed_cast<int *>(bv);
|
||||
/// int &ir = chaiscript::boxed_cast<int &>(bv);
|
||||
/// boost::shared_ptr<const int> cspi = chaiscript::boxed_cast<boost::shared_ptr<const int> >(bv);
|
||||
/// const int ci = chaiscript::boxed_cast<const int>(bv);
|
||||
/// const int *cip = chaiscript::boxed_cast<const int *>(bv);
|
||||
/// const int &cir = chaiscript::boxed_cast<const int &>(bv);
|
||||
/// \endcode
|
||||
///
|
||||
/// boost::function conversion example
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// Boxed_Value bv = chai.eval("`+`"); // Get the functor for the + operator which is built in
|
||||
/// boost::function<int (int, int)> f = chaiscript::boxed_cast<boost::function<int (int, int)> >(bv);
|
||||
/// int i = f(2,3);
|
||||
/// assert(i == 5);
|
||||
/// \endcode
|
||||
template<typename Type>
|
||||
typename detail::Cast_Helper<Type>::Result_Type boxed_cast(const Boxed_Value &bv)
|
||||
{
|
||||
try {
|
||||
return detail::Cast_Helper<Type>::cast(bv);
|
||||
} catch (const boost::bad_any_cast &) {
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
//Thank you MSVC, yes we know that a constant value is being used in the if
|
||||
// statment in THIS VERSION of the template instantiation
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4127)
|
||||
#endif
|
||||
|
||||
if (boost::is_polymorphic<typename detail::Stripped_Type<Type>::type>::value)
|
||||
{
|
||||
try {
|
||||
// We will not catch any bad_boxed_dynamic_cast that is thrown, let the user get it
|
||||
// either way, we are not responsible if it doesn't work
|
||||
return detail::Cast_Helper<Type>::cast(detail::boxed_dynamic_cast<Type>(bv));
|
||||
} catch (const boost::bad_any_cast &) {
|
||||
throw exception::bad_boxed_cast(bv.get_type_info(), typeid(Type));
|
||||
}
|
||||
} else {
|
||||
// If it's not polymorphic, just throw the error, don't waste the time on the
|
||||
// attempted dynamic_cast
|
||||
throw exception::bad_boxed_cast(bv.get_type_info(), typeid(Type));
|
||||
}
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
273
include/chaiscript/dispatchkit/boxed_cast_helper.hpp
Normal file
273
include/chaiscript/dispatchkit/boxed_cast_helper.hpp
Normal file
@@ -0,0 +1,273 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_BOXED_CAST_HELPER_HPP_
|
||||
#define CHAISCRIPT_BOXED_CAST_HELPER_HPP_
|
||||
|
||||
#include "type_info.hpp"
|
||||
#include "boxed_value.hpp"
|
||||
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/any.hpp>
|
||||
#include <boost/ref.hpp>
|
||||
#include <boost/type_traits/add_const.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
// Cast_Helper_Inner helper classes
|
||||
|
||||
/**
|
||||
* Generic Cast_Helper_Inner, for casting to any type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner
|
||||
{
|
||||
typedef typename boost::reference_wrapper<typename boost::add_const<Result>::type > Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
if (!ob.get_type_info().is_const())
|
||||
{
|
||||
return boost::cref((boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get());
|
||||
} else {
|
||||
return boost::any_cast<boost::reference_wrapper<const Result> >(ob.get());
|
||||
}
|
||||
} else {
|
||||
if (!ob.get_type_info().is_const())
|
||||
{
|
||||
return boost::cref(*(boost::any_cast<boost::shared_ptr<Result> >(ob.get())));
|
||||
} else {
|
||||
return boost::cref(*(boost::any_cast<boost::shared_ptr<const Result> >(ob.get())));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const Result> : Cast_Helper_Inner<Result>
|
||||
{
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a const & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const Result &> : Cast_Helper_Inner<Result>
|
||||
{
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a const * type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const Result *>
|
||||
{
|
||||
typedef const Result * Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
if (!ob.get_type_info().is_const())
|
||||
{
|
||||
return (boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get_pointer();
|
||||
} else {
|
||||
return (boost::any_cast<boost::reference_wrapper<const Result> >(ob.get())).get_pointer();
|
||||
}
|
||||
} else {
|
||||
if (!ob.get_type_info().is_const())
|
||||
{
|
||||
return (boost::any_cast<boost::shared_ptr<Result> >(ob.get())).get();
|
||||
} else {
|
||||
return (boost::any_cast<boost::shared_ptr<const Result> >(ob.get())).get();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a * type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<Result *>
|
||||
{
|
||||
typedef Result * Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return (boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get_pointer();
|
||||
} else {
|
||||
return (boost::any_cast<boost::shared_ptr<Result> >(ob.get())).get();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<Result &>
|
||||
{
|
||||
typedef typename boost::reference_wrapper<Result> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return boost::any_cast<boost::reference_wrapper<Result> >(ob.get());
|
||||
} else {
|
||||
return boost::ref(*(boost::any_cast<boost::shared_ptr<Result> >(ob.get())));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a boost::shared_ptr<> type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<typename boost::shared_ptr<Result> >
|
||||
{
|
||||
typedef typename boost::shared_ptr<Result> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return boost::any_cast<boost::shared_ptr<Result> >(ob.get());
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a boost::shared_ptr<const> type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<typename boost::shared_ptr<const Result> >
|
||||
{
|
||||
typedef typename boost::shared_ptr<const Result> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (!ob.get_type_info().is_const())
|
||||
{
|
||||
return boost::const_pointer_cast<const Result>(boost::any_cast<boost::shared_ptr<Result> >(ob.get()));
|
||||
} else {
|
||||
return boost::any_cast<boost::shared_ptr<const Result> >(ob.get());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a const boost::shared_ptr<> & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::shared_ptr<Result> > : Cast_Helper_Inner<boost::shared_ptr<Result> >
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::shared_ptr<Result> &> : Cast_Helper_Inner<boost::shared_ptr<Result> >
|
||||
{
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a const boost::shared_ptr<const> & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::shared_ptr<const Result> > : Cast_Helper_Inner<boost::shared_ptr<const Result> >
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::shared_ptr<const Result> &> : Cast_Helper_Inner<boost::shared_ptr<const Result> >
|
||||
{
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a Boxed_Value type
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper_Inner<Boxed_Value>
|
||||
{
|
||||
typedef const Boxed_Value & Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return ob;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a const Boxed_Value & type
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper_Inner<const Boxed_Value> : Cast_Helper_Inner<Boxed_Value>
|
||||
{
|
||||
};
|
||||
|
||||
template<>
|
||||
struct Cast_Helper_Inner<const Boxed_Value &> : Cast_Helper_Inner<Boxed_Value>
|
||||
{
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Cast_Helper_Inner for casting to a boost::reference_wrapper type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<boost::reference_wrapper<Result> > : Cast_Helper_Inner<Result &>
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::reference_wrapper<Result> > : Cast_Helper_Inner<Result &>
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::reference_wrapper<Result> &> : Cast_Helper_Inner<Result &>
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<boost::reference_wrapper<const Result> > : Cast_Helper_Inner<const Result &>
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::reference_wrapper<const Result> > : Cast_Helper_Inner<const Result &>
|
||||
{
|
||||
};
|
||||
|
||||
template<typename Result>
|
||||
struct Cast_Helper_Inner<const boost::reference_wrapper<const Result> & > : Cast_Helper_Inner<const Result &>
|
||||
{
|
||||
};
|
||||
|
||||
/**
|
||||
* The exposed Cast_Helper object that by default just calls the Cast_Helper_Inner
|
||||
*/
|
||||
template<typename T>
|
||||
struct Cast_Helper
|
||||
{
|
||||
typedef typename Cast_Helper_Inner<T>::Result_Type Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return Cast_Helper_Inner<T>::cast(ob);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
260
include/chaiscript/dispatchkit/boxed_pod_value.hpp
Normal file
260
include/chaiscript/dispatchkit/boxed_pod_value.hpp
Normal file
@@ -0,0 +1,260 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_BOXED_POD_VALUE_HPP_
|
||||
#define CHAISCRIPT_BOXED_POD_VALUE_HPP_
|
||||
|
||||
#include "type_info.hpp"
|
||||
#include "boxed_value.hpp"
|
||||
#include "boxed_cast_helper.hpp"
|
||||
#include <boost/any.hpp>
|
||||
#include <boost/cstdint.hpp>
|
||||
#include <boost/integer_traits.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
|
||||
/// \brief Represents any numeric type, generically. Used internally for generic operations between POD values
|
||||
class Boxed_POD_Value
|
||||
{
|
||||
public:
|
||||
Boxed_POD_Value(const Boxed_Value &v)
|
||||
: d(0), i(0), isfloat(false)
|
||||
{
|
||||
if (v.get_type_info().is_undef())
|
||||
{
|
||||
throw boost::bad_any_cast();
|
||||
}
|
||||
|
||||
const Type_Info &inp_ = v.get_type_info();
|
||||
|
||||
if (inp_ == typeid(double))
|
||||
{
|
||||
d = boxed_cast<double>(v);
|
||||
isfloat = true;
|
||||
} else if (inp_ == typeid(float)) {
|
||||
d = boxed_cast<float>(v);
|
||||
isfloat = true;
|
||||
} else if (inp_ == typeid(bool)) {
|
||||
i = boxed_cast<bool>(v);
|
||||
} else if (inp_ == typeid(char)) {
|
||||
i = boxed_cast<char>(v);
|
||||
} else if (inp_ == typeid(int)) {
|
||||
i = boxed_cast<int>(v);
|
||||
} else if (inp_ == typeid(unsigned int)) {
|
||||
i = boxed_cast<unsigned int>(v);
|
||||
} else if (inp_ == typeid(long)) {
|
||||
i = boxed_cast<long>(v);
|
||||
} else if (inp_ == typeid(unsigned long)) {
|
||||
i = boxed_cast<unsigned long>(v);
|
||||
} else if (inp_ == typeid(boost::int8_t)) {
|
||||
i = boxed_cast<boost::int8_t>(v);
|
||||
} else if (inp_ == typeid(boost::int16_t)) {
|
||||
i = boxed_cast<boost::int16_t>(v);
|
||||
} else if (inp_ == typeid(boost::int32_t)) {
|
||||
i = boxed_cast<boost::int32_t>(v);
|
||||
} else if (inp_ == typeid(boost::int64_t)) {
|
||||
i = boxed_cast<boost::int64_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint8_t)) {
|
||||
i = boxed_cast<boost::uint8_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint16_t)) {
|
||||
i = boxed_cast<boost::uint16_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint32_t)) {
|
||||
i = boxed_cast<boost::uint32_t>(v);
|
||||
} else {
|
||||
throw boost::bad_any_cast();
|
||||
}
|
||||
}
|
||||
|
||||
bool operator==(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) == ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator<(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) < ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator>(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) > ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator>=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) >= ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator<=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) <= ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator!=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((isfloat)?d:i) != ((r.isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
Boxed_Value operator+(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i + r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((isfloat)?d:i) + ((r.isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator-(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i - r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((isfloat)?d:i) - ((r.isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator&(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return Boxed_Value(i & r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast("& only valid for integer types");
|
||||
}
|
||||
|
||||
Boxed_Value operator^(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return Boxed_Value(i ^ r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast("^ only valid for integer types");
|
||||
}
|
||||
|
||||
Boxed_Value operator|(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return Boxed_Value(i | r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast("| only valid for integer types");
|
||||
}
|
||||
|
||||
Boxed_Value operator/(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i / r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((isfloat)?d:i) / ((r.isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator<<(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i << r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast("<< only valid for integer types");
|
||||
}
|
||||
|
||||
|
||||
Boxed_Value operator*(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i * r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((isfloat)?d:i) * ((r.isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
|
||||
Boxed_Value operator%(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i % r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast("% only valid for integer types");
|
||||
}
|
||||
|
||||
Boxed_Value operator>>(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!isfloat && !r.isfloat)
|
||||
{
|
||||
return smart_size(i >> r.i);
|
||||
}
|
||||
|
||||
throw exception::bad_boxed_cast(">> only valid for integer types");
|
||||
}
|
||||
|
||||
Boxed_Value smart_size(boost::int64_t t_i) const
|
||||
{
|
||||
if (t_i < boost::integer_traits<int>::const_min
|
||||
|| t_i > boost::integer_traits<int>::const_max)
|
||||
{
|
||||
return Boxed_Value(t_i);
|
||||
} else {
|
||||
return Boxed_Value(static_cast<int>(t_i));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
double d;
|
||||
boost::int64_t i;
|
||||
|
||||
bool isfloat;
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* Cast_Helper for converting from Boxed_Value to Boxed_POD_Value
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<Boxed_POD_Value>
|
||||
{
|
||||
typedef Boxed_POD_Value Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return Boxed_POD_Value(ob);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for converting from Boxed_Value to Boxed_POD_Value
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<const Boxed_POD_Value &> : Cast_Helper<Boxed_POD_Value>
|
||||
{
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for converting from Boxed_Value to Boxed_POD_Value
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<const Boxed_POD_Value> : Cast_Helper<Boxed_POD_Value>
|
||||
{
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
@@ -1,13 +1,16 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef __boxed_value_hpp__
|
||||
#define __boxed_value_hpp__
|
||||
#ifndef CHAISCRIPT_BOXED_VALUE_HPP_
|
||||
#define CHAISCRIPT_BOXED_VALUE_HPP_
|
||||
|
||||
#include "type_info.hpp"
|
||||
|
||||
#include "../chaiscript_threading.hpp"
|
||||
|
||||
#include <map>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/any.hpp>
|
||||
@@ -16,15 +19,12 @@
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/cstdint.hpp>
|
||||
#include <boost/type_traits/add_const.hpp>
|
||||
#include <boost/integer_traits.hpp>
|
||||
|
||||
namespace dispatchkit
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* Boxed_Value is the main tool of the dispatchkit. It allows
|
||||
* for boxed / untyped containment of any C++ object. It uses
|
||||
* boost::any internally but also provides user access the underlying
|
||||
* stored type information
|
||||
*/
|
||||
/// \brief A wrapper for holding any valid C++ type. All types in ChaiScript are Boxed_Value objects
|
||||
/// \sa chaiscript::boxed_cast
|
||||
class Boxed_Value
|
||||
{
|
||||
public:
|
||||
@@ -41,49 +41,19 @@ namespace dispatchkit
|
||||
*/
|
||||
struct Data
|
||||
{
|
||||
/**
|
||||
* used to provide type-erased access to the internal boost::shared_ptr
|
||||
* reference count information
|
||||
*/
|
||||
struct Shared_Ptr_Proxy
|
||||
{
|
||||
virtual ~Shared_Ptr_Proxy()
|
||||
{
|
||||
}
|
||||
|
||||
virtual bool unique(boost::any *) = 0;
|
||||
virtual long use_count(boost::any *) = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Typed implementation of the Shared_Ptr_Proxy
|
||||
*/
|
||||
template<typename T>
|
||||
struct Shared_Ptr_Proxy_Impl : Shared_Ptr_Proxy
|
||||
{
|
||||
virtual ~Shared_Ptr_Proxy_Impl()
|
||||
{
|
||||
}
|
||||
|
||||
virtual bool unique(boost::any *a)
|
||||
static bool is_null(boost::any *a)
|
||||
{
|
||||
boost::shared_ptr<T> *ptr = boost::any_cast<boost::shared_ptr<T> >(a);
|
||||
return ptr->unique();
|
||||
return ptr->get() == 0;
|
||||
}
|
||||
|
||||
virtual long use_count(boost::any *a)
|
||||
{
|
||||
boost::shared_ptr<T> *ptr = boost::any_cast<boost::shared_ptr<T> >(a);
|
||||
return ptr->use_count();
|
||||
}
|
||||
};
|
||||
|
||||
Data(const Type_Info &ti,
|
||||
const boost::any &to,
|
||||
bool tr,
|
||||
const boost::shared_ptr<Shared_Ptr_Proxy> &t_proxy = boost::shared_ptr<Shared_Ptr_Proxy>())
|
||||
const boost::function<bool (boost::any*)> &t_is_null = boost::function<bool (boost::any*)>())
|
||||
: m_type_info(ti), m_obj(to),
|
||||
m_is_ref(tr), m_ptr_proxy(t_proxy)
|
||||
m_is_ref(tr), m_is_null(t_is_null)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -92,99 +62,78 @@ namespace dispatchkit
|
||||
m_type_info = rhs.m_type_info;
|
||||
m_obj = rhs.m_obj;
|
||||
m_is_ref = rhs.m_is_ref;
|
||||
m_ptr_proxy = rhs.m_ptr_proxy;
|
||||
m_is_null = rhs.m_is_null;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
static bool get_false()
|
||||
~Data()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Type_Info m_type_info;
|
||||
boost::any m_obj;
|
||||
bool m_is_ref;
|
||||
boost::shared_ptr<Shared_Ptr_Proxy> m_ptr_proxy;
|
||||
boost::function<bool (boost::any*)> m_is_null;
|
||||
std::vector<boost::shared_ptr<Data> > m_dependencies;
|
||||
};
|
||||
|
||||
/**
|
||||
* Cache of all created objects in the dispatch kit. Used to return the
|
||||
* same shared_ptr if the same object is created more than once.
|
||||
* Also used for acquiring a shared_ptr of a reference object, if the
|
||||
* value of the shared_ptr is known
|
||||
*/
|
||||
struct Object_Cache
|
||||
struct Object_Data
|
||||
{
|
||||
boost::shared_ptr<Data> get(Boxed_Value::Void_Type)
|
||||
static boost::shared_ptr<Data> get(Boxed_Value::Void_Type)
|
||||
{
|
||||
return boost::shared_ptr<Data> (new Data(
|
||||
Get_Type_Info<void>::get(),
|
||||
detail::Get_Type_Info<void>::get(),
|
||||
boost::any(),
|
||||
false)
|
||||
);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
boost::shared_ptr<Data> get(boost::shared_ptr<T> obj)
|
||||
static boost::shared_ptr<Data> get(const boost::shared_ptr<T> *obj)
|
||||
{
|
||||
boost::shared_ptr<Data> data(new Data(
|
||||
Get_Type_Info<T>::get(),
|
||||
boost::any(obj),
|
||||
false,
|
||||
boost::shared_ptr<Data::Shared_Ptr_Proxy>(new Data::Shared_Ptr_Proxy_Impl<T>()))
|
||||
);
|
||||
|
||||
std::map<void *, Data >::iterator itr
|
||||
= m_ptrs.find(obj.get());
|
||||
|
||||
if (itr != m_ptrs.end())
|
||||
{
|
||||
(*data) = (itr->second);
|
||||
} else {
|
||||
m_ptrs.insert(std::make_pair(obj.get(), *data));
|
||||
}
|
||||
|
||||
return data;
|
||||
return get(*obj);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
boost::shared_ptr<Data> get(boost::reference_wrapper<T> obj)
|
||||
static boost::shared_ptr<Data> get(const boost::shared_ptr<T> &obj)
|
||||
{
|
||||
boost::shared_ptr<Data> data(new Data(
|
||||
Get_Type_Info<T>::get(),
|
||||
return boost::shared_ptr<Data>(new Data(
|
||||
detail::Get_Type_Info<T>::get(),
|
||||
boost::any(obj),
|
||||
false,
|
||||
boost::function<bool (boost::any *)>(&Data::is_null<T>))
|
||||
);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static boost::shared_ptr<Data> get(T *t)
|
||||
{
|
||||
return get(boost::ref(*t));
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static boost::shared_ptr<Data> get(boost::reference_wrapper<T> obj)
|
||||
{
|
||||
return boost::shared_ptr<Data>(new Data(
|
||||
detail::Get_Type_Info<T>::get(),
|
||||
boost::any(obj),
|
||||
true)
|
||||
);
|
||||
|
||||
std::map<void *, Data >::iterator itr
|
||||
= m_ptrs.find(obj.get_pointer());
|
||||
|
||||
if (itr != m_ptrs.end())
|
||||
{
|
||||
(*data) = (itr->second);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
boost::shared_ptr<Data> get(const T& t)
|
||||
static boost::shared_ptr<Data> get(const T& t)
|
||||
{
|
||||
boost::shared_ptr<Data> data(new Data(
|
||||
Get_Type_Info<T>::get(),
|
||||
return boost::shared_ptr<Data>(new Data(
|
||||
detail::Get_Type_Info<T>::get(),
|
||||
boost::any(boost::shared_ptr<T>(new T(t))),
|
||||
false,
|
||||
boost::shared_ptr<Data::Shared_Ptr_Proxy>(new Data::Shared_Ptr_Proxy_Impl<T>()))
|
||||
boost::function<bool (boost::any *)>(&Data::is_null<T>))
|
||||
);
|
||||
|
||||
boost::shared_ptr<T> *ptr = boost::any_cast<boost::shared_ptr<T> >(&data->m_obj);
|
||||
|
||||
m_ptrs.insert(std::make_pair(ptr->get(), *data));
|
||||
return data;
|
||||
}
|
||||
|
||||
boost::shared_ptr<Data> get()
|
||||
static boost::shared_ptr<Data> get()
|
||||
{
|
||||
return boost::shared_ptr<Data> (new Data(
|
||||
Type_Info(),
|
||||
@@ -193,28 +142,6 @@ namespace dispatchkit
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop objects from the cache where there is only one (ie, our)
|
||||
* reference to it, so it may be destructed
|
||||
*/
|
||||
void cull()
|
||||
{
|
||||
std::map<void *, Data >::iterator itr = m_ptrs.begin();
|
||||
|
||||
while (itr != m_ptrs.end())
|
||||
{
|
||||
if (itr->second.m_ptr_proxy->unique(&itr->second.m_obj) == 1)
|
||||
{
|
||||
std::map<void *, Data >::iterator todel = itr;
|
||||
++itr;
|
||||
m_ptrs.erase(todel);
|
||||
} else {
|
||||
++itr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::map<void *, Data > m_ptrs;
|
||||
};
|
||||
|
||||
public:
|
||||
@@ -223,9 +150,8 @@ namespace dispatchkit
|
||||
*/
|
||||
template<typename T>
|
||||
explicit Boxed_Value(T t)
|
||||
: m_data(get_object_cache().get(t))
|
||||
: m_data(Object_Data::get(t))
|
||||
{
|
||||
get_object_cache().cull();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -240,7 +166,7 @@ namespace dispatchkit
|
||||
* Unknown-type constructor
|
||||
*/
|
||||
Boxed_Value()
|
||||
: m_data(get_object_cache().get())
|
||||
: m_data(Object_Data::get())
|
||||
{
|
||||
}
|
||||
|
||||
@@ -248,14 +174,10 @@ namespace dispatchkit
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a reference to the static global Object_Cache
|
||||
*/
|
||||
Object_Cache &get_object_cache()
|
||||
void swap(Boxed_Value &rhs)
|
||||
{
|
||||
static Object_Cache oc;
|
||||
return oc;
|
||||
}
|
||||
std::swap(m_data, rhs.m_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* copy the values stored in rhs.m_data to m_data
|
||||
@@ -272,7 +194,8 @@ namespace dispatchkit
|
||||
*/
|
||||
Boxed_Value &operator=(const Boxed_Value &rhs)
|
||||
{
|
||||
m_data = rhs.m_data;
|
||||
Boxed_Value temp(rhs);
|
||||
swap(temp);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -284,12 +207,32 @@ namespace dispatchkit
|
||||
/**
|
||||
* return true if the object is uninitialized
|
||||
*/
|
||||
bool is_unknown() const
|
||||
bool is_undef() const
|
||||
{
|
||||
return m_data->m_type_info.m_is_unknown;
|
||||
return m_data->m_type_info.is_undef();
|
||||
}
|
||||
|
||||
boost::any get() const
|
||||
bool is_const() const
|
||||
{
|
||||
return m_data->m_type_info.is_const();
|
||||
}
|
||||
|
||||
bool is_type(const Type_Info &ti) const
|
||||
{
|
||||
return m_data->m_type_info.bare_equal(ti);
|
||||
}
|
||||
|
||||
bool is_null() const
|
||||
{
|
||||
if (m_data->m_is_null)
|
||||
{
|
||||
return m_data->m_is_null(&m_data->m_obj);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const boost::any & get() const
|
||||
{
|
||||
return m_data->m_obj;
|
||||
}
|
||||
@@ -299,339 +242,133 @@ namespace dispatchkit
|
||||
return m_data->m_is_ref;
|
||||
}
|
||||
|
||||
bool is_pointer() const
|
||||
{
|
||||
return !is_ref();
|
||||
}
|
||||
|
||||
void clear_dependencies()
|
||||
{
|
||||
m_data->m_dependencies.clear();
|
||||
}
|
||||
|
||||
template<typename InItr>
|
||||
void add_dependencies(InItr begin, const InItr &end)
|
||||
{
|
||||
while (begin != end)
|
||||
{
|
||||
if (begin->m_data != m_data)
|
||||
{
|
||||
m_data->m_dependencies.push_back(begin->m_data);
|
||||
}
|
||||
++begin;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
boost::shared_ptr<Data> m_data;
|
||||
};
|
||||
|
||||
|
||||
// Cast_Helper helper classes
|
||||
|
||||
/**
|
||||
* Generic Cast_Helper, for casting to any type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper
|
||||
/// \brief Creates a Boxed_Value. If the object passed in is a value type, it is copied. If it is a pointer, boost::shared_ptr, or boost::reference_type
|
||||
/// a copy is not made.
|
||||
/// \param t The value to box
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// int i;
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::var(i), "i");
|
||||
/// chai.add(chaiscript::var(&i), "ip");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingobjects
|
||||
template<typename T>
|
||||
Boxed_Value var(T t)
|
||||
{
|
||||
typedef typename boost::reference_wrapper<typename boost::add_const<Result>::type > Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return boost::cref((boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get());
|
||||
} else {
|
||||
return boost::cref(*(boost::any_cast<boost::shared_ptr<Result> >(ob.get())));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a const & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper<const Result &>
|
||||
{
|
||||
typedef typename boost::reference_wrapper<typename boost::add_const<Result>::type > Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return boost::cref((boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get());
|
||||
} else {
|
||||
return boost::cref(*(boost::any_cast<boost::shared_ptr<Result> >(ob.get())));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a const * type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper<const Result *>
|
||||
{
|
||||
typedef const Result * Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return (boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get_pointer();
|
||||
} else {
|
||||
return (boost::any_cast<boost::shared_ptr<Result> >(ob.get())).get();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a * type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper<Result *>
|
||||
{
|
||||
typedef Result * Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return (boost::any_cast<boost::reference_wrapper<Result> >(ob.get())).get_pointer();
|
||||
} else {
|
||||
return (boost::any_cast<boost::shared_ptr<Result> >(ob.get())).get();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a & type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper<Result &>
|
||||
{
|
||||
typedef typename boost::reference_wrapper<Result> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.is_ref())
|
||||
{
|
||||
return boost::any_cast<boost::reference_wrapper<Result> >(ob.get());
|
||||
} else {
|
||||
return boost::ref(*(boost::any_cast<boost::shared_ptr<Result> >(ob.get())));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a boost::shared_ptr<> type
|
||||
*/
|
||||
template<typename Result>
|
||||
struct Cast_Helper<typename boost::shared_ptr<Result> >
|
||||
{
|
||||
typedef typename boost::shared_ptr<Result> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return boost::any_cast<boost::shared_ptr<Result> >(ob.get());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a Boxed_Value type
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<Boxed_Value>
|
||||
{
|
||||
typedef Boxed_Value Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return ob;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for casting to a const Boxed_Value & type
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<const Boxed_Value &>
|
||||
{
|
||||
typedef Boxed_Value Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return ob;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* class that is thrown in the event of a bad_boxed_cast. That is,
|
||||
* in the case that a Boxed_Value cannot be cast to the desired type
|
||||
*/
|
||||
class bad_boxed_cast : public std::bad_cast
|
||||
{
|
||||
public:
|
||||
bad_boxed_cast(const Type_Info &t_from, const std::type_info &t_to) throw()
|
||||
: from(t_from.m_type_info), to(&t_to), m_what("Cannot perform boxed_cast")
|
||||
{
|
||||
}
|
||||
|
||||
bad_boxed_cast(const std::string &w) throw()
|
||||
: m_what(w)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~bad_boxed_cast() throw() {}
|
||||
|
||||
virtual const char * what () throw()
|
||||
{
|
||||
return m_what.c_str();
|
||||
}
|
||||
const std::type_info *from;
|
||||
const std::type_info *to;
|
||||
|
||||
private:
|
||||
std::string m_what;
|
||||
};
|
||||
|
||||
/**
|
||||
* boxed_cast function for casting a Boxed_Value into a given type
|
||||
* example:
|
||||
* int &i = boxed_cast<int &>(boxedvalue);
|
||||
*/
|
||||
template<typename Type>
|
||||
typename Cast_Helper<Type>::Result_Type boxed_cast(const Boxed_Value &bv)
|
||||
{
|
||||
try {
|
||||
return Cast_Helper<Type>::cast(bv);
|
||||
} catch (const boost::bad_any_cast &) {
|
||||
throw bad_boxed_cast(bv.get_type_info(), typeid(Type));
|
||||
return Boxed_Value(t);
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
/// \brief Takes a value, copies it and returns a Boxed_Value object that is immutable
|
||||
/// \param[in] t Value to copy and make const
|
||||
/// \returns Immutable Boxed_Value
|
||||
/// \sa Boxed_Value::is_const
|
||||
template<typename T>
|
||||
Boxed_Value const_var_impl(const T &t)
|
||||
{
|
||||
return Boxed_Value(boost::shared_ptr<typename boost::add_const<T>::type >(new T(t)));
|
||||
}
|
||||
|
||||
/// \brief Takes a pointer to a value, adds const to the pointed to type and returns an immutable Boxed_Value.
|
||||
/// Does not copy the pointed to value.
|
||||
/// \param[in] t Pointer to make immutable
|
||||
/// \returns Immutable Boxed_Value
|
||||
/// \sa Boxed_Value::is_const
|
||||
template<typename T>
|
||||
Boxed_Value const_var_impl(T *t)
|
||||
{
|
||||
return Boxed_Value( const_cast<typename boost::add_const<T>::type *>(t) );
|
||||
}
|
||||
|
||||
/// \brief Takes a boost::shared_ptr to a value, adds const to the pointed to type and returns an immutable Boxed_Value.
|
||||
/// Does not copy the pointed to value.
|
||||
/// \param[in] t Pointer to make immutable
|
||||
/// \returns Immutable Boxed_Value
|
||||
/// \sa Boxed_Value::is_const
|
||||
template<typename T>
|
||||
Boxed_Value const_var_impl(const boost::shared_ptr<T> &t)
|
||||
{
|
||||
return Boxed_Value( boost::const_pointer_cast<typename boost::add_const<T>::type>(t) );
|
||||
}
|
||||
|
||||
/// \brief Takes a boost::reference_wrapper value, adds const to the referenced type and returns an immutable Boxed_Value.
|
||||
/// Does not copy the referenced value.
|
||||
/// \param[in] t Reference object to make immutable
|
||||
/// \returns Immutable Boxed_Value
|
||||
/// \sa Boxed_Value::is_const
|
||||
template<typename T>
|
||||
Boxed_Value const_var_impl(const boost::reference_wrapper<T> &t)
|
||||
{
|
||||
return Boxed_Value( boost::cref(t.get()) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Object which attempts to convert a Boxed_Value into a generic
|
||||
* POD type and provide generic POD type operations
|
||||
*/
|
||||
struct Boxed_POD_Value
|
||||
/// \brief Takes an object and returns an immutable Boxed_Value. If the object is a boost::reference or pointer type
|
||||
/// the value is not copied. If it is an object type, it is copied.
|
||||
/// \param[in] t Object to make immutable
|
||||
/// \returns Immutable Boxed_Value
|
||||
/// \sa chaiscript::Boxed_Value::is_const
|
||||
/// \sa chaiscript::var
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// enum Colors
|
||||
/// {
|
||||
/// Blue,
|
||||
/// Green,
|
||||
/// Red
|
||||
/// };
|
||||
/// chaiscript::ChaiScript chai
|
||||
/// chai.add(chaiscript::const_var(Blue), "Blue"); // add immutable constant
|
||||
/// chai.add(chaiscript::const_var(Red), "Red");
|
||||
/// chai.add(chaiscript::const_var(Green), "Green");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingobjects
|
||||
template<typename T>
|
||||
Boxed_Value const_var(const T &t)
|
||||
{
|
||||
return detail::const_var_impl(t);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// \returns true if the two Boxed_Values share the same internal type
|
||||
static bool type_match(Boxed_Value l, Boxed_Value r)
|
||||
{
|
||||
Boxed_POD_Value(const Boxed_Value &v)
|
||||
: d(0), i(0), m_isfloat(false)
|
||||
{
|
||||
if (!v.get_type_info().m_type_info)
|
||||
{
|
||||
throw boost::bad_any_cast();
|
||||
}
|
||||
|
||||
const std::type_info &inp_ = *v.get_type_info().m_type_info;
|
||||
|
||||
if (inp_ == typeid(double))
|
||||
{
|
||||
d = boxed_cast<double>(v);
|
||||
m_isfloat = true;
|
||||
} else if (inp_ == typeid(float)) {
|
||||
d = boxed_cast<float>(v);
|
||||
m_isfloat = true;
|
||||
} else if (inp_ == typeid(bool)) {
|
||||
i = boxed_cast<bool>(v);
|
||||
} else if (inp_ == typeid(char)) {
|
||||
i = boxed_cast<char>(v);
|
||||
} else if (inp_ == typeid(int)) {
|
||||
i = boxed_cast<int>(v);
|
||||
} else if (inp_ == typeid(unsigned int)) {
|
||||
i = boxed_cast<unsigned int>(v);
|
||||
} else if (inp_ == typeid(long)) {
|
||||
i = boxed_cast<long>(v);
|
||||
} else if (inp_ == typeid(unsigned long)) {
|
||||
i = boxed_cast<unsigned long>(v);
|
||||
} else if (inp_ == typeid(boost::int8_t)) {
|
||||
i = boxed_cast<boost::int8_t>(v);
|
||||
} else if (inp_ == typeid(boost::int16_t)) {
|
||||
i = boxed_cast<boost::int16_t>(v);
|
||||
} else if (inp_ == typeid(boost::int32_t)) {
|
||||
i = boxed_cast<boost::int32_t>(v);
|
||||
} else if (inp_ == typeid(boost::int64_t)) {
|
||||
i = boxed_cast<boost::int64_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint8_t)) {
|
||||
i = boxed_cast<boost::uint8_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint16_t)) {
|
||||
i = boxed_cast<boost::uint16_t>(v);
|
||||
} else if (inp_ == typeid(boost::uint32_t)) {
|
||||
i = boxed_cast<boost::uint32_t>(v);
|
||||
} else {
|
||||
throw boost::bad_any_cast();
|
||||
}
|
||||
}
|
||||
|
||||
bool operator==(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) == ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator<(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) < ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator>(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) > ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator>=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) >= ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator<=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) <= ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
bool operator!=(const Boxed_POD_Value &r) const
|
||||
{
|
||||
return ((m_isfloat)?d:i) != ((r.m_isfloat)?r.d:r.i);
|
||||
}
|
||||
|
||||
Boxed_Value operator+(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!m_isfloat && !r.m_isfloat)
|
||||
{
|
||||
return Boxed_Value(i + r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((m_isfloat)?d:i) + ((r.m_isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator*(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!m_isfloat && !r.m_isfloat)
|
||||
{
|
||||
return Boxed_Value(i * r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((m_isfloat)?d:i) * ((r.m_isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator/(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!m_isfloat && !r.m_isfloat)
|
||||
{
|
||||
return Boxed_Value(i / r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((m_isfloat)?d:i) / ((r.m_isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
Boxed_Value operator-(const Boxed_POD_Value &r) const
|
||||
{
|
||||
if (!m_isfloat && !r.m_isfloat)
|
||||
{
|
||||
return Boxed_Value(i - r.i);
|
||||
}
|
||||
|
||||
return Boxed_Value(((m_isfloat)?d:i) - ((r.m_isfloat)?r.d:r.i));
|
||||
}
|
||||
|
||||
double d;
|
||||
boost::int64_t i;
|
||||
|
||||
bool m_isfloat;
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast_Helper for converting from Boxed_Value to Boxed_POD_Value
|
||||
*/
|
||||
template<>
|
||||
struct Cast_Helper<Boxed_POD_Value>
|
||||
{
|
||||
typedef Boxed_POD_Value Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
return Boxed_POD_Value(ob);
|
||||
}
|
||||
};
|
||||
return l.get_type_info() == r.get_type_info();
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
File diff suppressed because it is too large
Load Diff
287
include/chaiscript/dispatchkit/dynamic_cast_conversion.hpp
Normal file
287
include/chaiscript/dispatchkit/dynamic_cast_conversion.hpp
Normal file
@@ -0,0 +1,287 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_DYNAMIC_CAST_CONVERSION_HPP_
|
||||
#define CHAISCRIPT_DYNAMIC_CAST_CONVERSION_HPP_
|
||||
|
||||
#include "type_info.hpp"
|
||||
#include "boxed_value.hpp"
|
||||
#include "boxed_cast_helper.hpp"
|
||||
#include "bad_boxed_cast.hpp"
|
||||
#include <boost/static_assert.hpp>
|
||||
#include <boost/type_traits/is_polymorphic.hpp>
|
||||
#include <boost/type_traits/is_base_of.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace exception
|
||||
{
|
||||
class bad_boxed_dynamic_cast : public bad_boxed_cast
|
||||
{
|
||||
public:
|
||||
bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to,
|
||||
const std::string &t_what) throw()
|
||||
: bad_boxed_cast(t_from, t_to, t_what)
|
||||
{
|
||||
}
|
||||
|
||||
bad_boxed_dynamic_cast(const Type_Info &t_from, const std::type_info &t_to) throw()
|
||||
: bad_boxed_cast(t_from, t_to)
|
||||
{
|
||||
}
|
||||
|
||||
bad_boxed_dynamic_cast(const std::string &w) throw()
|
||||
: bad_boxed_cast(w)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~bad_boxed_dynamic_cast() throw() {}
|
||||
};
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
class Dynamic_Conversion
|
||||
{
|
||||
public:
|
||||
virtual Boxed_Value convert(const Boxed_Value &derived) = 0;
|
||||
const Type_Info &base()
|
||||
{
|
||||
return m_base;
|
||||
}
|
||||
const Type_Info &derived()
|
||||
{
|
||||
return m_derived;
|
||||
}
|
||||
|
||||
protected:
|
||||
Dynamic_Conversion(const Type_Info &t_base, const Type_Info &t_derived)
|
||||
: m_base(t_base), m_derived(t_derived)
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
Type_Info m_base;
|
||||
Type_Info m_derived;
|
||||
|
||||
};
|
||||
|
||||
template<typename Base, typename Derived>
|
||||
class Dynamic_Conversion_Impl : public Dynamic_Conversion
|
||||
{
|
||||
public:
|
||||
Dynamic_Conversion_Impl()
|
||||
: Dynamic_Conversion(user_type<Base>(), user_type<Derived>())
|
||||
{
|
||||
}
|
||||
|
||||
virtual Boxed_Value convert(const Boxed_Value &t_derived)
|
||||
{
|
||||
if (t_derived.get_type_info().bare_equal(user_type<Derived>()))
|
||||
{
|
||||
if (t_derived.is_pointer())
|
||||
{
|
||||
// Dynamic cast out the contained boxed value, which we know is the type we want
|
||||
if (t_derived.is_const())
|
||||
{
|
||||
boost::shared_ptr<const Base> data
|
||||
= boost::dynamic_pointer_cast<const Base>(detail::Cast_Helper<boost::shared_ptr<const Derived> >::cast(t_derived));
|
||||
if (!data)
|
||||
{
|
||||
throw std::bad_cast();
|
||||
}
|
||||
|
||||
return Boxed_Value(data);
|
||||
} else {
|
||||
boost::shared_ptr<Base> data
|
||||
= boost::dynamic_pointer_cast<Base>(detail::Cast_Helper<boost::shared_ptr<Derived> >::cast(t_derived));
|
||||
|
||||
if (!data)
|
||||
{
|
||||
throw std::bad_cast();
|
||||
}
|
||||
|
||||
return Boxed_Value(data);
|
||||
}
|
||||
} else {
|
||||
// Pull the reference out of the contained boxed value, which we know is the type we want
|
||||
if (t_derived.is_const())
|
||||
{
|
||||
const Derived &d = detail::Cast_Helper<const Derived &>::cast(t_derived);
|
||||
const Base &data = dynamic_cast<const Base &>(d);
|
||||
return Boxed_Value(boost::cref(data));
|
||||
} else {
|
||||
Derived &d = detail::Cast_Helper<Derived &>::cast(t_derived);
|
||||
Base &data = dynamic_cast<Base &>(d);
|
||||
return Boxed_Value(boost::ref(data));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw exception::bad_boxed_dynamic_cast(t_derived.get_type_info(), typeid(Base), "Unknown dynamic_cast_conversion");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class Dynamic_Conversions
|
||||
{
|
||||
public:
|
||||
static inline Dynamic_Conversions &get()
|
||||
{
|
||||
static Dynamic_Conversions obj;
|
||||
return obj;
|
||||
}
|
||||
|
||||
template<typename Base, typename Derived>
|
||||
static boost::shared_ptr<Dynamic_Conversion> create()
|
||||
{
|
||||
boost::shared_ptr<Dynamic_Conversion> conversion(new Dynamic_Conversion_Impl<Base, Derived>());
|
||||
|
||||
/// \todo this is a hack and a kludge. The idea is to make sure that
|
||||
/// the conversion is registered both in the module's notion of the static conversion object
|
||||
/// and in the global notion of the static conversion object
|
||||
/// someday this will almost certainly have to change. Maybe it is time for ChaiScript
|
||||
/// to become a library?
|
||||
Dynamic_Conversions::get().add_conversion(conversion);
|
||||
return conversion;
|
||||
}
|
||||
|
||||
template<typename InItr>
|
||||
void cleanup(InItr begin, const InItr &end)
|
||||
{
|
||||
chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex);
|
||||
|
||||
while (begin != end)
|
||||
{
|
||||
if (begin->unique())
|
||||
{
|
||||
m_conversions.erase(begin->get());
|
||||
}
|
||||
|
||||
++begin;
|
||||
}
|
||||
}
|
||||
|
||||
void add_conversion(const boost::shared_ptr<Dynamic_Conversion> &conversion)
|
||||
{
|
||||
chaiscript::detail::threading::unique_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex);
|
||||
|
||||
m_conversions.insert(conversion.get());
|
||||
}
|
||||
|
||||
bool has_conversion(const Type_Info &base, const Type_Info &derived) const
|
||||
{
|
||||
chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex);
|
||||
|
||||
return find(base, derived) != m_conversions.end();
|
||||
}
|
||||
|
||||
|
||||
Dynamic_Conversion *get_conversion(const Type_Info &base, const Type_Info &derived) const
|
||||
{
|
||||
chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l(m_mutex);
|
||||
|
||||
std::set<Dynamic_Conversion *>::const_iterator itr =
|
||||
find(base, derived);
|
||||
|
||||
if (itr != m_conversions.end())
|
||||
{
|
||||
return *itr;
|
||||
} else {
|
||||
throw std::out_of_range("No such conversion exists from " + derived.bare_name() + " to " + base.bare_name());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Dynamic_Conversions() {}
|
||||
|
||||
std::set<Dynamic_Conversion *>::const_iterator find(
|
||||
const Type_Info &base, const Type_Info &derived) const
|
||||
{
|
||||
for (std::set<Dynamic_Conversion *>::const_iterator itr = m_conversions.begin();
|
||||
itr != m_conversions.end();
|
||||
++itr)
|
||||
{
|
||||
if ((*itr)->base().bare_equal(base) && (*itr)->derived().bare_equal(derived))
|
||||
{
|
||||
return itr;
|
||||
}
|
||||
}
|
||||
|
||||
return m_conversions.end();
|
||||
}
|
||||
|
||||
mutable chaiscript::detail::threading::shared_mutex m_mutex;
|
||||
std::set<Dynamic_Conversion *> m_conversions;
|
||||
};
|
||||
}
|
||||
|
||||
typedef boost::shared_ptr<chaiscript::detail::Dynamic_Conversion> Dynamic_Cast_Conversion;
|
||||
|
||||
/// \brief Used to register a base / parent class relationship with ChaiScript. Necessary if you
|
||||
/// want automatic conversions up your inheritance hierarchy.
|
||||
///
|
||||
/// Create a new base class registration for applying to a module or to the chaiscript engine
|
||||
/// Currently, due to limitations in module loading on Windows, and for the sake of portability,
|
||||
/// if you have a type that is introduced in a loadable module and is used by multiple modules
|
||||
/// (through a tertiary dll that is shared between the modules, static linking the new type
|
||||
/// into both loadable modules would not be portable), you need to register the base type
|
||||
/// relationship in all modules that use the newly added type in a polymorphic way.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// class Base
|
||||
/// {};
|
||||
/// class Derived : public Base
|
||||
/// {};
|
||||
///
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::base_class<Base, Derived>());
|
||||
/// \endcode
|
||||
///
|
||||
/// \todo Move share static type registration code into a mechanism that allows it to be properly
|
||||
/// shared by all modules
|
||||
template<typename Base, typename Derived>
|
||||
Dynamic_Cast_Conversion base_class()
|
||||
{
|
||||
//Can only be used with related polymorphic types
|
||||
//may be expanded some day to support conversions other than child -> parent
|
||||
BOOST_STATIC_ASSERT((boost::is_base_of<Base,Derived>::value));
|
||||
BOOST_STATIC_ASSERT(boost::is_polymorphic<Base>::value);
|
||||
BOOST_STATIC_ASSERT(boost::is_polymorphic<Derived>::value);
|
||||
|
||||
return detail::Dynamic_Conversions::create<Base, Derived>();
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
template<typename Base, typename Derived>
|
||||
bool dynamic_cast_converts()
|
||||
{
|
||||
return dynamic_cast_converts(user_type<Base>(), user_type<Derived>());
|
||||
}
|
||||
|
||||
static bool dynamic_cast_converts(const Type_Info &base, const Type_Info &derived)
|
||||
{
|
||||
return detail::Dynamic_Conversions::get().has_conversion(base, derived);
|
||||
}
|
||||
|
||||
template<typename Base>
|
||||
Boxed_Value boxed_dynamic_cast(const Boxed_Value &derived)
|
||||
{
|
||||
try {
|
||||
return detail::Dynamic_Conversions::get().get_conversion(user_type<Base>(), derived.get_type_info())->convert(derived);
|
||||
} catch (const std::out_of_range &) {
|
||||
throw exception::bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), "No known conversion");
|
||||
} catch (const std::bad_cast &) {
|
||||
throw exception::bad_boxed_dynamic_cast(derived.get_type_info(), typeid(Base), "Unable to perform dynamic_cast operation");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
284
include/chaiscript/dispatchkit/dynamic_object.hpp
Normal file
284
include/chaiscript/dispatchkit/dynamic_object.hpp
Normal file
@@ -0,0 +1,284 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_DYNAMIC_OBJECT_HPP_
|
||||
#define CHAISCRIPT_DYNAMIC_OBJECT_HPP_
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
class Dynamic_Object
|
||||
{
|
||||
public:
|
||||
Dynamic_Object(const std::string &t_type_name)
|
||||
: m_type_name(t_type_name)
|
||||
{
|
||||
}
|
||||
|
||||
std::string get_type_name() const
|
||||
{
|
||||
return m_type_name;
|
||||
}
|
||||
|
||||
Boxed_Value get_attr(const std::string &t_attr_name)
|
||||
{
|
||||
return m_attrs[t_attr_name];
|
||||
}
|
||||
|
||||
std::map<std::string, Boxed_Value> get_attrs()
|
||||
{
|
||||
return m_attrs;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string m_type_name;
|
||||
|
||||
std::map<std::string, Boxed_Value> m_attrs;
|
||||
};
|
||||
|
||||
namespace detail
|
||||
{
|
||||
struct Dynamic_Object_Attribute
|
||||
{
|
||||
static Boxed_Value func(const std::string &t_type_name, const std::string &t_attr_name,
|
||||
Dynamic_Object &t_do)
|
||||
{
|
||||
if (t_do.get_type_name() != t_type_name)
|
||||
{
|
||||
throw exception::bad_boxed_cast("Dynamic object type mismatch");
|
||||
}
|
||||
|
||||
return t_do.get_attr(t_attr_name);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A Proxy_Function implementation designed for calling a function
|
||||
* that is automatically guarded based on the first param based on the
|
||||
* param's type name
|
||||
*/
|
||||
class Dynamic_Object_Function : public Proxy_Function_Base
|
||||
{
|
||||
public:
|
||||
Dynamic_Object_Function(
|
||||
const std::string &t_type_name,
|
||||
const Proxy_Function &t_func,
|
||||
const boost::optional<Type_Info> &t_ti = boost::optional<Type_Info>())
|
||||
: Proxy_Function_Base(build_param_types(t_func->get_param_types(), t_ti)),
|
||||
m_type_name(t_type_name), m_func(t_func), m_ti(t_ti)
|
||||
{
|
||||
assert( (t_func->get_arity() > 0 || t_func->get_arity() < 0)
|
||||
&& "Programming error, Dynamic_Object_Function must have at least one parameter (this)");
|
||||
}
|
||||
|
||||
virtual ~Dynamic_Object_Function() {}
|
||||
|
||||
virtual bool operator==(const Proxy_Function_Base &f) const
|
||||
{
|
||||
const Dynamic_Object_Function *df = dynamic_cast<const Dynamic_Object_Function *>(&f);
|
||||
if (df)
|
||||
{
|
||||
return df->m_type_name == m_type_name && (*df->m_func) == (*m_func);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
virtual bool call_match(const std::vector<Boxed_Value> &vals) const
|
||||
{
|
||||
if (dynamic_object_typename_match(vals, m_type_name, m_ti))
|
||||
{
|
||||
return m_func->call_match(vals);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
virtual std::vector<Const_Proxy_Function> get_contained_functions() const
|
||||
{
|
||||
std::vector<Const_Proxy_Function> fs;
|
||||
fs.push_back(m_func);
|
||||
return fs;
|
||||
}
|
||||
|
||||
|
||||
virtual int get_arity() const
|
||||
{
|
||||
return m_func->get_arity();
|
||||
}
|
||||
|
||||
virtual std::string annotation() const
|
||||
{
|
||||
return m_func->annotation();
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
virtual Boxed_Value do_call(const std::vector<Boxed_Value> ¶ms) const
|
||||
{
|
||||
if (dynamic_object_typename_match(params, m_type_name, m_ti))
|
||||
{
|
||||
return (*m_func)(params);
|
||||
} else {
|
||||
throw exception::guard_error();
|
||||
}
|
||||
}
|
||||
|
||||
virtual bool compare_first_type(const Boxed_Value &bv) const
|
||||
{
|
||||
return dynamic_object_typename_match(bv, m_type_name, m_ti);
|
||||
}
|
||||
|
||||
private:
|
||||
static std::vector<Type_Info> build_param_types(
|
||||
const std::vector<Type_Info> &t_inner_types, boost::optional<Type_Info> t_objectti)
|
||||
{
|
||||
if (t_objectti)
|
||||
{
|
||||
std::vector<Type_Info> types(t_inner_types);
|
||||
|
||||
assert(types.size() > 1);
|
||||
assert(types[1].bare_equal(user_type<Boxed_Value>()));
|
||||
types[1] = *t_objectti;
|
||||
return types;
|
||||
} else {
|
||||
return t_inner_types;
|
||||
}
|
||||
}
|
||||
|
||||
static bool dynamic_object_typename_match(const Boxed_Value &bv, const std::string &name,
|
||||
const boost::optional<Type_Info> &ti)
|
||||
{
|
||||
static Type_Info doti = user_type<Dynamic_Object>();
|
||||
if (bv.get_type_info().bare_equal(doti))
|
||||
{
|
||||
try {
|
||||
const Dynamic_Object &d = boxed_cast<const Dynamic_Object &>(bv);
|
||||
return name == "Dynamic_Object" || d.get_type_name() == name;
|
||||
} catch (const std::bad_cast &) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (ti)
|
||||
{
|
||||
return bv.get_type_info().bare_equal(*ti);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static bool dynamic_object_typename_match(const std::vector<Boxed_Value> &bvs, const std::string &name,
|
||||
const boost::optional<Type_Info> &ti)
|
||||
{
|
||||
if (bvs.size() > 0)
|
||||
{
|
||||
return dynamic_object_typename_match(bvs[0], name, ti);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string m_type_name;
|
||||
Proxy_Function m_func;
|
||||
boost::optional<Type_Info> m_ti;
|
||||
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A Proxy_Function implementation designed for creating a new
|
||||
* Dynamic_Object
|
||||
* that is automatically guarded based on the first param based on the
|
||||
* param's type name
|
||||
*/
|
||||
class Dynamic_Object_Constructor : public Proxy_Function_Base
|
||||
{
|
||||
public:
|
||||
Dynamic_Object_Constructor(
|
||||
const std::string &t_type_name,
|
||||
const Proxy_Function &t_func)
|
||||
: Proxy_Function_Base(build_type_list(t_func->get_param_types())),
|
||||
m_type_name(t_type_name), m_func(t_func)
|
||||
{
|
||||
assert( (t_func->get_arity() > 0 || t_func->get_arity() < 0)
|
||||
&& "Programming error, Dynamic_Object_Function must have at least one parameter (this)");
|
||||
}
|
||||
|
||||
static std::vector<Type_Info> build_type_list(const std::vector<Type_Info> &tl)
|
||||
{
|
||||
std::vector<Type_Info>::const_iterator begin = tl.begin();
|
||||
std::vector<Type_Info>::const_iterator end = tl.end();
|
||||
|
||||
if (begin != end)
|
||||
{
|
||||
++begin;
|
||||
}
|
||||
|
||||
return std::vector<Type_Info>(begin, end);
|
||||
}
|
||||
|
||||
virtual ~Dynamic_Object_Constructor() {}
|
||||
|
||||
virtual bool operator==(const Proxy_Function_Base &f) const
|
||||
{
|
||||
const Dynamic_Object_Constructor *dc = dynamic_cast<const Dynamic_Object_Constructor*>(&f);
|
||||
if (dc)
|
||||
{
|
||||
return dc->m_type_name == m_type_name && (*dc->m_func) == (*m_func);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
virtual bool call_match(const std::vector<Boxed_Value> &vals) const
|
||||
{
|
||||
std::vector<Boxed_Value> new_vals;
|
||||
new_vals.push_back(Boxed_Value(Dynamic_Object(m_type_name)));
|
||||
new_vals.insert(new_vals.end(), vals.begin(), vals.end());
|
||||
|
||||
return m_func->call_match(new_vals);
|
||||
}
|
||||
|
||||
|
||||
virtual int get_arity() const
|
||||
{
|
||||
// "this" is not considered part of the arity
|
||||
return m_func->get_arity() - 1;
|
||||
}
|
||||
|
||||
virtual std::string annotation() const
|
||||
{
|
||||
return m_func->annotation();
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual Boxed_Value do_call(const std::vector<Boxed_Value> ¶ms) const
|
||||
{
|
||||
std::vector<Boxed_Value> new_params;
|
||||
chaiscript::Boxed_Value bv = var(Dynamic_Object(m_type_name));
|
||||
new_params.push_back(bv);
|
||||
new_params.insert(new_params.end(), params.begin(), params.end());
|
||||
|
||||
(*m_func)(new_params);
|
||||
|
||||
return bv;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string m_type_name;
|
||||
Proxy_Function m_func;
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
@@ -1,18 +1,11 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
|
||||
#define addparam(z,n,text) params.push_back(Boxed_Value(BOOST_PP_CAT(p, n) ));
|
||||
#define curry(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n))
|
||||
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef __function_call_hpp__
|
||||
#define __function_call_hpp__
|
||||
#ifndef CHAISCRIPT_FUNCTION_CALL_HPP_
|
||||
#define CHAISCRIPT_FUNCTION_CALL_HPP_
|
||||
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
@@ -20,149 +13,123 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "proxy_functions.hpp"
|
||||
#include "function_call_detail.hpp"
|
||||
|
||||
namespace dispatchkit
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* Internal helper class for handling the return
|
||||
* value of a build_function_caller
|
||||
*/
|
||||
template<typename Ret>
|
||||
class Function_Caller_Ret
|
||||
{
|
||||
public:
|
||||
Function_Caller_Ret()
|
||||
{
|
||||
}
|
||||
|
||||
Ret call(const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &t_funcs,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
return boxed_cast<Ret>(dispatch(t_funcs, params));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Specialization for void return types
|
||||
*/
|
||||
template<>
|
||||
class Function_Caller_Ret<void>
|
||||
{
|
||||
public:
|
||||
Function_Caller_Ret()
|
||||
{
|
||||
}
|
||||
|
||||
void call(const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &t_funcs,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
dispatch(t_funcs, params);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#define BOOST_PP_ITERATION_LIMITS ( 0, 9 )
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/function_call.hpp>
|
||||
#include BOOST_PP_ITERATE()
|
||||
|
||||
namespace dispatchkit
|
||||
{
|
||||
/**
|
||||
* Build a function caller that knows how to dispatch on a set of functions
|
||||
* example:
|
||||
* boost::function<void (int)> f =
|
||||
* build_function_caller(dispatchkit.get_function("print"));
|
||||
* \returns A boost::function object for dispatching
|
||||
* \param[in] funcs the set of functions to dispatch on.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
build_function_caller(const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &funcs)
|
||||
namespace dispatch
|
||||
{
|
||||
/**
|
||||
* Build a function caller that knows how to dispatch on a set of functions
|
||||
* example:
|
||||
* boost::function<void (int)> f =
|
||||
* build_function_caller(dispatchkit.get_function("print"));
|
||||
* \returns A boost::function object for dispatching
|
||||
* \param[in] funcs the set of functions to dispatch on.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
functor(const std::vector<Const_Proxy_Function> &funcs)
|
||||
{
|
||||
FunctionType *p;
|
||||
return build_function_caller_helper(p, funcs);
|
||||
FunctionType *p=0;
|
||||
return detail::build_function_caller_helper(p, funcs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a function caller for a particular Proxy_Function object
|
||||
* useful in the case that a function is being pass out from scripting back
|
||||
* into code
|
||||
* example:
|
||||
* void my_function(boost::shared_ptr<Proxy_Function> f)
|
||||
* {
|
||||
* boost::function<void (int)> local_f =
|
||||
* build_function_caller(f);
|
||||
* }
|
||||
* \returns A boost::function object for dispatching
|
||||
* \param[in] func A function to execute.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
build_function_caller(boost::shared_ptr<Proxy_Function> func)
|
||||
/**
|
||||
* Build a function caller for a particular Proxy_Function object
|
||||
* useful in the case that a function is being pass out from scripting back
|
||||
* into code
|
||||
* example:
|
||||
* void my_function(Proxy_Function f)
|
||||
* {
|
||||
* boost::function<void (int)> local_f =
|
||||
* build_function_caller(f);
|
||||
* }
|
||||
* \returns A boost::function object for dispatching
|
||||
* \param[in] func A function to execute.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
functor(Const_Proxy_Function func)
|
||||
{
|
||||
std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > funcs;
|
||||
funcs.push_back(std::make_pair(std::string(), func));
|
||||
return build_function_caller<FunctionType>(funcs);
|
||||
std::vector<Const_Proxy_Function> funcs;
|
||||
funcs.push_back(func);
|
||||
return functor<FunctionType>(funcs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for automatically unboxing a Boxed_Value that contains a function object
|
||||
* and creating a typesafe C++ function caller from it.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
build_function_caller(const Boxed_Value &bv)
|
||||
/**
|
||||
* Helper for automatically unboxing a Boxed_Value that contains a function object
|
||||
* and creating a typesafe C++ function caller from it.
|
||||
*/
|
||||
template<typename FunctionType>
|
||||
boost::function<FunctionType>
|
||||
functor(const Boxed_Value &bv)
|
||||
{
|
||||
return build_function_caller<FunctionType>(boxed_cast<boost::shared_ptr<Proxy_Function> >(bv));
|
||||
return functor<FunctionType>(boxed_cast<Const_Proxy_Function >(bv));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for calling script code as if it were native C++ code
|
||||
* example:
|
||||
* boost::function<int (int, int)> f = build_functor(chai, "func(x, y){x+y}");
|
||||
* \return a boost::function representing the passed in script
|
||||
* \param[in] e ScriptEngine to build the script execution from
|
||||
* \param[in] script Script code to build a function from
|
||||
*/
|
||||
template<typename FunctionType, typename ScriptEngine>
|
||||
boost::function<FunctionType> build_functor(ScriptEngine &e, const std::string &script)
|
||||
{
|
||||
return build_function_caller<FunctionType>(e.evaluate_string(script));
|
||||
}
|
||||
}
|
||||
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace dispatchkit
|
||||
{
|
||||
/**
|
||||
* used internally for unwrapping a function call's types
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
Ret function_caller(const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &funcs
|
||||
BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_BINARY_PARAMS(n, Param, p) )
|
||||
{
|
||||
std::vector<Boxed_Value> params;
|
||||
|
||||
BOOST_PP_REPEAT(n, addparam, ~)
|
||||
|
||||
return Function_Caller_Ret<Ret>().call(funcs, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* used internally for unwrapping a function call's types
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param)) >
|
||||
build_function_caller_helper(Ret (BOOST_PP_ENUM_PARAMS(n, Param)), const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &funcs)
|
||||
namespace detail{
|
||||
/**
|
||||
* Cast helper to handle automatic casting to const boost::function &
|
||||
*/
|
||||
template<typename Signature>
|
||||
struct Cast_Helper<const boost::function<Signature> &>
|
||||
{
|
||||
return boost::bind(&function_caller<Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param)>, funcs
|
||||
BOOST_PP_ENUM_TRAILING(n, curry, ~));
|
||||
}
|
||||
typedef boost::function<Signature> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.get_type_info().bare_equal(user_type<Const_Proxy_Function>()))
|
||||
{
|
||||
return dispatch::functor<Signature>(ob);
|
||||
} else {
|
||||
return Cast_Helper_Inner<const boost::function<Signature> &>::cast(ob);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast helper to handle automatic casting to boost::function
|
||||
*/
|
||||
template<typename Signature>
|
||||
struct Cast_Helper<boost::function<Signature> >
|
||||
{
|
||||
typedef boost::function<Signature> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.get_type_info().bare_equal(user_type<Const_Proxy_Function>()))
|
||||
{
|
||||
return dispatch::functor<Signature>(ob);
|
||||
} else {
|
||||
return Cast_Helper_Inner<boost::function<Signature> >::cast(ob);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast helper to handle automatic casting to const boost::function
|
||||
*/
|
||||
template<typename Signature>
|
||||
struct Cast_Helper<const boost::function<Signature> >
|
||||
{
|
||||
typedef boost::function<Signature> Result_Type;
|
||||
|
||||
static Result_Type cast(const Boxed_Value &ob)
|
||||
{
|
||||
if (ob.get_type_info().bare_equal(user_type<Const_Proxy_Function>()))
|
||||
{
|
||||
return dispatch::functor<Signature>(ob);
|
||||
} else {
|
||||
return Cast_Helper_Inner<const boost::function<Signature> >::cast(ob);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
119
include/chaiscript/dispatchkit/function_call_detail.hpp
Normal file
119
include/chaiscript/dispatchkit/function_call_detail.hpp
Normal file
@@ -0,0 +1,119 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
|
||||
#define addparam(z,n,text) params.push_back((boost::is_reference<Param ## n>::value&&!(boost::is_same<chaiscript::Boxed_Value, typename boost::remove_const<typename boost::remove_reference<Param ## n>::type>::type>::value))?Boxed_Value(boost::ref(BOOST_PP_CAT(p, n))):Boxed_Value(BOOST_PP_CAT(p, n) ));
|
||||
#define curry(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n))
|
||||
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef CHAISCRIPT_FUNCTION_CALL_DETAIL_HPP_
|
||||
#define CHAISCRIPT_FUNCTION_CALL_DETAIL_HPP_
|
||||
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/function.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "proxy_functions.hpp"
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
|
||||
/**
|
||||
* Internal helper class for handling the return
|
||||
* value of a build_function_caller
|
||||
*/
|
||||
template<typename Ret>
|
||||
struct Function_Caller_Ret
|
||||
{
|
||||
static Ret call(const std::vector<Const_Proxy_Function> &t_funcs,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
return boxed_cast<Ret>(dispatch::dispatch(t_funcs, params));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Specialization for void return types
|
||||
*/
|
||||
template<>
|
||||
struct Function_Caller_Ret<void>
|
||||
{
|
||||
static void call(const std::vector<Const_Proxy_Function> &t_funcs,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
dispatch::dispatch(t_funcs, params);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#define BOOST_PP_ITERATION_LIMITS ( 0, 9 )
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/function_call_detail.hpp>
|
||||
#include BOOST_PP_ITERATE()
|
||||
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* used internally for unwrapping a function call's types
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
Ret function_caller(const std::vector<Const_Proxy_Function> &funcs
|
||||
BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_BINARY_PARAMS(n, Param, p) )
|
||||
{
|
||||
std::vector<Boxed_Value> params;
|
||||
|
||||
BOOST_PP_REPEAT(n, addparam, ~)
|
||||
|
||||
return Function_Caller_Ret<Ret>::call(funcs, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* used internally for unwrapping a function call's types
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param)) >
|
||||
build_function_caller_helper(Ret (BOOST_PP_ENUM_PARAMS(n, Param)), const std::vector<Const_Proxy_Function> &funcs)
|
||||
{
|
||||
if (funcs.size() == 1)
|
||||
{
|
||||
boost::shared_ptr<const Proxy_Function_Impl<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> > pfi =
|
||||
boost::dynamic_pointer_cast<const Proxy_Function_Impl<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> >
|
||||
(funcs[0]);
|
||||
|
||||
if (pfi)
|
||||
{
|
||||
return pfi->internal_function();
|
||||
}
|
||||
// looks like this either wasn't a Proxy_Function_Impl or the types didn't match
|
||||
// we cannot make any other guesses or assumptions really, so continuing
|
||||
}
|
||||
|
||||
return boost::bind(&function_caller<Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param)>, funcs
|
||||
BOOST_PP_ENUM_TRAILING(n, curry, ~));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#undef n
|
||||
|
||||
#endif
|
||||
|
154
include/chaiscript/dispatchkit/handle_return.hpp
Normal file
154
include/chaiscript/dispatchkit/handle_return.hpp
Normal file
@@ -0,0 +1,154 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_HANDLE_RETURN_HPP_
|
||||
#define CHAISCRIPT_HANDLE_RETURN_HPP_
|
||||
|
||||
#include "boxed_value.hpp"
|
||||
#include "type_info.hpp"
|
||||
#include <string>
|
||||
#include <boost/function.hpp>
|
||||
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<typename Ret>
|
||||
struct Handle_Return
|
||||
{
|
||||
static Boxed_Value handle(const Ret &r)
|
||||
{
|
||||
return const_var(r);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Ret>
|
||||
struct Handle_Return<boost::shared_ptr<Ret> &>
|
||||
{
|
||||
static Boxed_Value handle(const boost::shared_ptr<Ret> &r)
|
||||
{
|
||||
return Boxed_Value(r);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Ret>
|
||||
struct Handle_Return<boost::shared_ptr<Ret> >
|
||||
{
|
||||
static Boxed_Value handle(const boost::shared_ptr<Ret> &r)
|
||||
{
|
||||
return Boxed_Value(r);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Ret>
|
||||
struct Handle_Return<const boost::shared_ptr<Ret> &>
|
||||
{
|
||||
static Boxed_Value handle(const boost::shared_ptr<Ret> &r)
|
||||
{
|
||||
return Boxed_Value(r);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Ret>
|
||||
struct Handle_Return<const Ret &>
|
||||
{
|
||||
static Boxed_Value handle(const Ret &r)
|
||||
{
|
||||
return Boxed_Value(boost::cref(r));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<typename Ret>
|
||||
struct Handle_Return<Ret &>
|
||||
{
|
||||
static Boxed_Value handle(Ret &r)
|
||||
{
|
||||
return Boxed_Value(boost::ref(r));
|
||||
}
|
||||
|
||||
static Boxed_Value handle(const Ret &r)
|
||||
{
|
||||
return Boxed_Value(boost::cref(r));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<>
|
||||
struct Handle_Return<Boxed_Value>
|
||||
{
|
||||
static Boxed_Value handle(const Boxed_Value &r)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<>
|
||||
struct Handle_Return<const Boxed_Value>
|
||||
{
|
||||
static Boxed_Value handle(const Boxed_Value &r)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<>
|
||||
struct Handle_Return<Boxed_Value &>
|
||||
{
|
||||
static Boxed_Value handle(const Boxed_Value &r)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<>
|
||||
struct Handle_Return<const Boxed_Value &>
|
||||
{
|
||||
static Boxed_Value handle(const Boxed_Value &r)
|
||||
{
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Used internally for handling a return value from a Proxy_Function call
|
||||
*/
|
||||
template<>
|
||||
struct Handle_Return<void>
|
||||
{
|
||||
static Boxed_Value handle()
|
||||
{
|
||||
return Boxed_Value(Boxed_Value::Void_Type());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
458
include/chaiscript/dispatchkit/operators.hpp
Normal file
458
include/chaiscript/dispatchkit/operators.hpp
Normal file
@@ -0,0 +1,458 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_OPERATORS_HPP_
|
||||
#define CHAISCRIPT_OPERATORS_HPP_
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace bootstrap
|
||||
{
|
||||
namespace operators
|
||||
{
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign(L l, R r)
|
||||
{
|
||||
return (l = r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_bitwise_and(L l, R r)
|
||||
{
|
||||
return (l &= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_xor(L l, R r)
|
||||
{
|
||||
return (l ^= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_bitwise_or(L l, R r)
|
||||
{
|
||||
return (l |= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_difference(L l, R r)
|
||||
{
|
||||
return (l -= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_left_shift(L l, R r)
|
||||
{
|
||||
return (l <<= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_product(L l, R r)
|
||||
{
|
||||
return (l *= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_quotient(L l, R r)
|
||||
{
|
||||
return (l /= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_remainder(L l, R r)
|
||||
{
|
||||
return (l %= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_right_shift(L l, R r)
|
||||
{
|
||||
return (l >>= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret assign_sum(L l, R r)
|
||||
{
|
||||
return (l += r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret prefix_decrement(L l)
|
||||
{
|
||||
return (--l);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret prefix_increment(L l)
|
||||
{
|
||||
return (++l);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret equal(L l, R r)
|
||||
{
|
||||
return (l == r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret greater_than(L l, R r)
|
||||
{
|
||||
return (l > r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret greater_than_equal(L l, R r)
|
||||
{
|
||||
return (l >= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret less_than(L l, R r)
|
||||
{
|
||||
return (l < r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret less_than_equal(L l, R r)
|
||||
{
|
||||
return (l <= r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret logical_compliment(L l)
|
||||
{
|
||||
return (!l);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret not_equal(L l, R r)
|
||||
{
|
||||
return (l != r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret addition(L l, R r)
|
||||
{
|
||||
return (l + r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret unary_plus(L l)
|
||||
{
|
||||
return (+l);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret subtraction(L l, R r)
|
||||
{
|
||||
return (l - r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret unary_minus(L l)
|
||||
{
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4146)
|
||||
return (-l);
|
||||
#pragma warning(pop)
|
||||
#else
|
||||
return (-l);
|
||||
#endif
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret bitwise_and(L l, R r)
|
||||
{
|
||||
return (l & r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L>
|
||||
Ret bitwise_compliment(L l)
|
||||
{
|
||||
return (~l);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret bitwise_xor(L l, R r)
|
||||
{
|
||||
return (l ^ r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret bitwise_or(L l, R r)
|
||||
{
|
||||
return (l | r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret division(L l, R r)
|
||||
{
|
||||
return (l / r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret left_shift(L l, R r)
|
||||
{
|
||||
return l << r;
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret multiplication(L l, R r)
|
||||
{
|
||||
return l * r;
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret remainder(L l, R r)
|
||||
{
|
||||
return (l % r);
|
||||
}
|
||||
|
||||
template<typename Ret, typename L, typename R>
|
||||
Ret right_shift(L l, R r)
|
||||
{
|
||||
return (l >> r);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign<T &, T &, const T&>), "=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_bitwise_and(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_bitwise_and<T &, T &, const T&>), "&=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_xor(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_xor<T &, T &, const T&>), "^=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_bitwise_or(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_bitwise_or<T &, T &, const T&>), "|=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_difference(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_difference<T &, T &, const T&>), "-=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_left_shift(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_left_shift<T &, T &, const T&>), "<<=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_product(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_product<T &, T &, const T&>), "*=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_quotient(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_quotient<T &, T &, const T&>), "/=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_remainder(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_remainder<T &, T &, const T&>), "%=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_right_shift(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_right_shift<T &, T &, const T&>), ">>=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr assign_sum(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&assign_sum<T &, T &, const T&>), "+=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr prefix_decrement(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&prefix_decrement<T &, T &>), "--");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr prefix_increment(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&prefix_increment<T &, T &>), "++");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr equal(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&equal<bool, const T&, const T&>), "==");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr greater_than(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&greater_than<bool, const T&, const T&>), ">");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr greater_than_equal(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&greater_than_equal<bool, const T&, const T&>), ">=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr less_than(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&less_than<bool, const T&, const T&>), "<");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr less_than_equal(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&less_than_equal<bool, const T&, const T&>), "<=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr logical_compliment(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&logical_compliment<bool, const T &>), "!");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr not_equal(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(¬_equal<bool, const T &, const T &>), "!=");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr addition(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&addition<T, const T &, const T &>), "+");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr unary_plus(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&unary_plus<T, const T &>), "+");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr subtraction(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&subtraction<T, const T &, const T &>), "-");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr unary_minus(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&unary_minus<T, const T &>), "-");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr bitwise_and(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&bitwise_and<T, const T &, const T &>), "&");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr bitwise_compliment(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&bitwise_compliment<T, const T &>), "~");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr bitwise_xor(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&bitwise_xor<T, const T &, const T &>), "^");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr bitwise_or(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&bitwise_or<T, const T &, const T &>), "|");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr division(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&division<T, const T &, const T &>), "/");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr left_shift(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&left_shift<T, const T &, const T &>), "<<");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr multiplication(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&multiplication<T, const T &, const T &>), "*");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr remainder(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&remainder<T, const T &, const T &>), "%");
|
||||
return m;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
ModulePtr right_shift(ModulePtr m = ModulePtr(new Module()))
|
||||
{
|
||||
m->add(fun(&right_shift<T, const T &, const T &>), ">>");
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@@ -1,14 +1,14 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef __proxy_constructors_hpp__
|
||||
#define __proxy_constructors_hpp__
|
||||
#ifndef CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
|
||||
#define CHAISCRIPT_PROXY_CONSTRUCTORS_HPP_
|
||||
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
@@ -19,34 +19,63 @@
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/proxy_constructors.hpp>
|
||||
#include BOOST_PP_ITERATE()
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace dispatchkit
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* A constructor function, used for creating a new object
|
||||
* of a given type with a given set of params
|
||||
*/
|
||||
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::shared_ptr<Class> constructor( BOOST_PP_ENUM_BINARY_PARAMS(n, Param, p) )
|
||||
/// \brief Generates a constructor function for use with ChaiScript
|
||||
///
|
||||
/// \tparam T The signature of the constructor to generate. In the form of: ClassType (ParamType1, ParamType2, ...)
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// // Create a new function that creates a MyClass object using the (int, float) constructor
|
||||
/// // and call that function "MyClass" so that it appears as a normal constructor to the user.
|
||||
/// chai.add(constructor<MyClass (int, float)>(), "MyClass");
|
||||
/// \endcode
|
||||
template<typename T>
|
||||
Proxy_Function constructor()
|
||||
{
|
||||
return boost::shared_ptr<Class>(new Class( BOOST_PP_ENUM_PARAMS(n, p) ));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for build a constructor function
|
||||
* example:
|
||||
* dispatchengine.register_function(build_constructor<MyClass, int, const std::string&>, "MyClass");
|
||||
* \todo See if it is possible to make this not be a variadic function
|
||||
*/
|
||||
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::function<boost::shared_ptr<Class> (BOOST_PP_ENUM_PARAMS(n, Param))> build_constructor()
|
||||
{
|
||||
typedef boost::shared_ptr<Class> (*func)(BOOST_PP_ENUM_PARAMS(n, Param));
|
||||
return boost::function<boost::shared_ptr<Class> (BOOST_PP_ENUM_PARAMS(n, Param))>(func(&(constructor<Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param)>)));
|
||||
T *f = 0;
|
||||
return (dispatch::detail::build_constructor_(f));
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* A constructor function, used for creating a new object
|
||||
* of a given type with a given set of params
|
||||
*/
|
||||
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
boost::shared_ptr<Class> constructor_( BOOST_PP_ENUM_BINARY_PARAMS(n, Param, p) )
|
||||
{
|
||||
return boost::shared_ptr<Class>(new Class( BOOST_PP_ENUM_PARAMS(n, p) ));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for build a constructor function
|
||||
* example:
|
||||
* dispatchengine.register_function(build_constructor<MyClass, int, const std::string&>, "MyClass");
|
||||
* \todo See if it is possible to make this not be a variadic function
|
||||
*/
|
||||
template<typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
Proxy_Function build_constructor_(Class (*)(BOOST_PP_ENUM_PARAMS(n, Param)))
|
||||
{
|
||||
typedef boost::shared_ptr<Class> (sig)(BOOST_PP_ENUM_PARAMS(n, Param));
|
||||
return Proxy_Function(new Proxy_Function_Impl<sig>(boost::function<sig>(&(constructor_<Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param)>))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#undef n
|
||||
|
||||
#endif
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
160
include/chaiscript/dispatchkit/proxy_functions_detail.hpp
Normal file
160
include/chaiscript/dispatchkit/proxy_functions_detail.hpp
Normal file
@@ -0,0 +1,160 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
|
||||
#define gettypeinfo(z,n,text) ti.push_back(chaiscript::detail::Get_Type_Info<Param ## n>::get());
|
||||
#define casthelper(z,n,text) BOOST_PP_COMMA_IF(n) chaiscript::boxed_cast< Param ## n >(params[n])
|
||||
#define trycast(z,n,text) chaiscript::boxed_cast<Param ## n>(params[n]);
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef CHAISCRIPT_PROXY_FUNCTIONS_DETAIL_HPP_
|
||||
#define CHAISCRIPT_PROXY_FUNCTIONS_DETAIL_HPP_
|
||||
|
||||
#include "boxed_value.hpp"
|
||||
#include "boxed_cast.hpp"
|
||||
#include "type_info.hpp"
|
||||
#include "handle_return.hpp"
|
||||
#include <string>
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace exception
|
||||
{
|
||||
/**
|
||||
* Exception thrown when there is a mismatch in number of
|
||||
* parameters during Proxy_Function execution
|
||||
*/
|
||||
struct arity_error : std::range_error
|
||||
{
|
||||
arity_error(int t_got, int t_expected)
|
||||
: std::range_error("Function dispatch arity mismatch"),
|
||||
got(t_got), expected(t_expected)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~arity_error() throw() {}
|
||||
|
||||
int got;
|
||||
int expected;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#define BOOST_PP_ITERATION_LIMITS ( 0, 10 )
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/proxy_functions_detail.hpp>
|
||||
#include BOOST_PP_ITERATE()
|
||||
|
||||
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* Used by Proxy_Function_Impl to return a list of all param types
|
||||
* it contains.
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
|
||||
std::vector<Type_Info> build_param_type_list(Ret (*)(BOOST_PP_ENUM_PARAMS(n, Param)))
|
||||
{
|
||||
std::vector<Type_Info> ti;
|
||||
ti.push_back(chaiscript::detail::Get_Type_Info<Ret>::get());
|
||||
|
||||
BOOST_PP_REPEAT(n, gettypeinfo, ~)
|
||||
|
||||
return ti;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used by Proxy_Function_Impl to perform typesafe execution of a function.
|
||||
* The function attempts to unbox each paramter to the expected type.
|
||||
* if any unboxing fails the execution of the function fails and
|
||||
* the bad_boxed_cast is passed up to the caller.
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param)>
|
||||
Ret call_func(const boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> &f,
|
||||
const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
if (params.size() != n)
|
||||
{
|
||||
throw exception::arity_error(static_cast<int>(params.size()), n);
|
||||
} else {
|
||||
return f(BOOST_PP_REPEAT(n, casthelper, ~));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Used by Proxy_Function_Impl to determine if it is equivalent to another
|
||||
* Proxy_Function_Impl object. This function is primarly used to prevent
|
||||
* registration of two functions with the exact same signatures
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param)>
|
||||
bool compare_types_cast(Ret (*)(BOOST_PP_ENUM_PARAMS(n, Param)),
|
||||
const std::vector<Boxed_Value> & BOOST_PP_IF(n, params, ))
|
||||
{
|
||||
try {
|
||||
BOOST_PP_REPEAT(n, trycast, ~);
|
||||
} catch (const exception::bad_boxed_cast &) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#undef n
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
template<typename Ret>
|
||||
struct Do_Call
|
||||
{
|
||||
template<typename Fun>
|
||||
static Boxed_Value go(const boost::function<Fun> &fun, const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
return Handle_Return<Ret>::handle(call_func(fun, params));
|
||||
}
|
||||
};
|
||||
|
||||
template<>
|
||||
struct Do_Call<void>
|
||||
{
|
||||
template<typename Fun>
|
||||
static Boxed_Value go(const boost::function<Fun> &fun, const std::vector<Boxed_Value> ¶ms)
|
||||
{
|
||||
call_func(fun, params);
|
||||
return Handle_Return<void>::handle();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@@ -1,79 +1,165 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <boost/preprocessor.hpp>
|
||||
|
||||
#ifndef BOOST_PP_IS_ITERATING
|
||||
#ifndef __register_function_hpp__
|
||||
#define __register_function_hpp__
|
||||
#ifndef CHAISCRIPT_REGISTER_FUNCTION_HPP_
|
||||
#define CHAISCRIPT_REGISTER_FUNCTION_HPP_
|
||||
|
||||
#include "dispatchkit.hpp"
|
||||
#include "bind_first.hpp"
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/bind.hpp>
|
||||
#include <boost/function_types/components.hpp>
|
||||
#include <boost/function_types/function_type.hpp>
|
||||
#include <boost/function_types/is_member_object_pointer.hpp>
|
||||
#include <boost/function_types/is_member_function_pointer.hpp>
|
||||
|
||||
namespace dispatchkit
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* Helper function for register_member function
|
||||
*/
|
||||
template<typename T, typename Class>
|
||||
T &get_member(T Class::* m, Class *obj)
|
||||
namespace dispatch
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
return obj->*m;
|
||||
template<bool Object, bool MemFn>
|
||||
struct Fun_Helper
|
||||
{
|
||||
template<typename T>
|
||||
static Proxy_Function go(T t)
|
||||
{
|
||||
return Proxy_Function(
|
||||
new Proxy_Function_Impl<
|
||||
typename boost::function_types::function_type<boost::function_types::components<T> >::type> (
|
||||
boost::function<
|
||||
typename boost::function_types::function_type<boost::function_types::components<T> >::type
|
||||
>(t)));
|
||||
}
|
||||
};
|
||||
|
||||
template<>
|
||||
struct Fun_Helper<false, true>
|
||||
{
|
||||
template<typename T>
|
||||
static Proxy_Function go(T t)
|
||||
{
|
||||
return Proxy_Function(
|
||||
new Proxy_Function_Impl<
|
||||
typename boost::function_types::function_type<boost::function_types::components<T> >::type> (
|
||||
boost::function<
|
||||
typename boost::function_types::function_type<boost::function_types::components<T> >::type
|
||||
>(boost::mem_fn(t))));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
template<>
|
||||
struct Fun_Helper<true, false>
|
||||
{
|
||||
template<typename T, typename Class>
|
||||
static Proxy_Function go(T Class::* m)
|
||||
{
|
||||
return Proxy_Function(new Attribute_Access<T, Class>(m));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// \brief Creates a new Proxy_Function object from a boost::function object
|
||||
/// \param[in] f boost::function to expose to ChaiScript
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// boost::function<int (char, float, std::string)> f = get_some_function();
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(fun(f), "some_function");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingfunctions
|
||||
template<typename T>
|
||||
Proxy_Function fun(const boost::function<T> &f)
|
||||
{
|
||||
return Proxy_Function(new dispatch::Proxy_Function_Impl<T>(f));
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically create a get_member helper function for an object
|
||||
* to allow for runtime dispatched access to public data members
|
||||
* for example, the case of std::pair<>::first and std::pair<>::second
|
||||
*/
|
||||
template<typename T, typename Class>
|
||||
void register_member(Dispatch_Engine &s, T Class::* m, const std::string &name)
|
||||
/// \brief Creates a new Proxy_Function object from a free function, member function or data member
|
||||
/// \param[in] t Function / member to expose
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// int myfunction(const std::string &);
|
||||
/// class MyClass
|
||||
/// {
|
||||
/// public:
|
||||
/// void memberfunction();
|
||||
/// int memberdata;
|
||||
/// };
|
||||
///
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(fun(&myfunction), "myfunction");
|
||||
/// chai.add(fun(&MyClass::memberfunction), "memberfunction");
|
||||
/// chai.add(fun(&MyClass::memberdata), "memberdata");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingfunctions
|
||||
template<typename T>
|
||||
Proxy_Function fun(T t)
|
||||
{
|
||||
s.register_function(boost::function<T (Class *)>(boost::bind(&get_member<T, Class>, m, _1)), name);
|
||||
return dispatch::detail::Fun_Helper<boost::function_types::is_member_object_pointer<T>::value, boost::function_types::is_member_function_pointer<T>::value>::go(t);
|
||||
}
|
||||
|
||||
/// \brief Creates a new Proxy_Function object from a free function, member function or data member and binds the first parameter of it
|
||||
/// \param[in] t Function / member to expose
|
||||
/// \param[in] q Value to bind to first parameter
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// struct MyClass
|
||||
/// {
|
||||
/// void memberfunction(int);
|
||||
/// };
|
||||
///
|
||||
/// MyClass obj;
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// // Add function taking only one argument, an int, and permanently bound to "obj"
|
||||
/// chai.add(fun(&MyClass::memberfunction, boost::ref(obj)), "memberfunction");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingfunctions
|
||||
template<typename T, typename Q>
|
||||
Proxy_Function fun(T t, const Q &q)
|
||||
{
|
||||
return fun(detail::bind_first(t, q));
|
||||
}
|
||||
|
||||
/// \brief Creates a new Proxy_Function object from a free function or member function and binds the first and second parameters of it
|
||||
/// \param[in] t Function / member to expose
|
||||
/// \param[in] q Value to bind to first parameter
|
||||
/// \param[in] r Value to bind to second parameter
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// struct MyClass
|
||||
/// {
|
||||
/// void memberfunction(int);
|
||||
/// };
|
||||
///
|
||||
/// MyClass obj;
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// // Add function taking only no arguments, and permanently bound to "obj" and "1"
|
||||
/// // memberfunction() will be equivalent to obj.memberfunction(1)
|
||||
/// chai.add(fun(&MyClass::memberfunction, boost::ref(obj), 1), "memberfunction");
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingfunctions
|
||||
template<typename T, typename Q, typename R>
|
||||
Proxy_Function fun(T t, const Q &q, const R &r)
|
||||
{
|
||||
return fun(detail::bind_first(detail::bind_first(t, q), r));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#define BOOST_PP_ITERATION_LIMITS ( 0, 10 )
|
||||
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/register_function.hpp>
|
||||
#include BOOST_PP_ITERATE()
|
||||
|
||||
# endif
|
||||
#else
|
||||
# define n BOOST_PP_ITERATION()
|
||||
|
||||
namespace dispatchkit
|
||||
{
|
||||
/**
|
||||
* Register a global function of n parameters with name
|
||||
*/
|
||||
template<typename Ret BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param)>
|
||||
void register_function(Dispatch_Engine &s, Ret (*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const std::string &name)
|
||||
{
|
||||
s.register_function(boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>(f), name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a class method of n parameters with name
|
||||
*/
|
||||
template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param)>
|
||||
void register_function(Dispatch_Engine &s, Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const std::string &name)
|
||||
{
|
||||
s.register_function(boost::function<Ret (Class* BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param))>(f), name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a const class method of n parameters with name
|
||||
*/
|
||||
template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param)>
|
||||
void register_function(Dispatch_Engine &s, Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, const std::string &name)
|
||||
{
|
||||
s.register_function(boost::function<Ret (const Class* BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, Param))>(f), name);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
@@ -1,12 +1,15 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef __type_info_hpp__
|
||||
#define __type_info_hpp__
|
||||
#ifndef CHAISCRIPT_TYPE_INFO_HPP_
|
||||
#define CHAISCRIPT_TYPE_INFO_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <boost/shared_ptr.hpp>
|
||||
#include <boost/type_traits/is_const.hpp>
|
||||
#include <boost/type_traits/is_void.hpp>
|
||||
#include <boost/type_traits/is_reference.hpp>
|
||||
@@ -16,105 +19,229 @@
|
||||
#include <boost/type_traits/remove_pointer.hpp>
|
||||
#include <boost/ref.hpp>
|
||||
|
||||
namespace dispatchkit
|
||||
namespace chaiscript
|
||||
{
|
||||
/**
|
||||
* compile time deduced information about a type
|
||||
*/
|
||||
struct Type_Info
|
||||
|
||||
namespace detail
|
||||
{
|
||||
Type_Info(bool t_is_const, bool t_is_reference, bool t_is_pointer, bool t_is_void,
|
||||
const std::type_info *t_ti, const std::type_info *t_bareti)
|
||||
: m_is_const(t_is_const), m_is_reference(t_is_reference), m_is_pointer(t_is_pointer),
|
||||
template<typename T>
|
||||
struct Bare_Type
|
||||
{
|
||||
typedef typename boost::remove_const<typename boost::remove_pointer<typename boost::remove_reference<T>::type>::type>::type type;
|
||||
};
|
||||
}
|
||||
|
||||
/// \brief Compile time deduced information about a type
|
||||
class Type_Info
|
||||
{
|
||||
public:
|
||||
Type_Info(bool t_is_const, bool t_is_reference, bool t_is_pointer, bool t_is_void,
|
||||
const std::type_info *t_ti, const std::type_info *t_bareti)
|
||||
: m_is_const(t_is_const), m_is_reference(t_is_reference), m_is_pointer(t_is_pointer),
|
||||
m_is_void(t_is_void),
|
||||
m_type_info(t_ti), m_bare_type_info(t_bareti),
|
||||
m_is_unknown(false)
|
||||
{
|
||||
}
|
||||
m_type_info(t_ti), m_bare_type_info(t_bareti),
|
||||
m_is_undef(false)
|
||||
{
|
||||
}
|
||||
|
||||
Type_Info()
|
||||
: m_is_const(false), m_is_reference(false), m_is_pointer(false),
|
||||
m_is_void(false), m_type_info(0), m_bare_type_info(0),
|
||||
m_is_unknown(true)
|
||||
{
|
||||
}
|
||||
Type_Info()
|
||||
: m_is_const(false), m_is_reference(false), m_is_pointer(false),
|
||||
m_is_void(false), m_type_info(0), m_bare_type_info(0),
|
||||
m_is_undef(true)
|
||||
{
|
||||
}
|
||||
|
||||
Type_Info(const Type_Info &ti)
|
||||
: m_is_const(ti.m_is_const), m_is_reference(ti.m_is_reference),
|
||||
m_is_pointer(ti.m_is_pointer),
|
||||
m_is_void(ti.m_is_void), m_type_info(ti.m_type_info),
|
||||
m_bare_type_info(ti.m_bare_type_info),
|
||||
m_is_unknown(ti.m_is_unknown)
|
||||
{
|
||||
}
|
||||
Type_Info &operator=(const Type_Info &ti)
|
||||
{
|
||||
m_is_const = ti.m_is_const;
|
||||
m_is_reference = ti.m_is_reference;
|
||||
m_is_pointer = ti.m_is_pointer;
|
||||
m_is_void = ti.m_is_void;
|
||||
m_type_info = ti.m_type_info;
|
||||
m_bare_type_info = ti.m_bare_type_info;
|
||||
m_is_unknown = ti.m_is_unknown;
|
||||
return *this;
|
||||
}
|
||||
bool operator<(const Type_Info &ti) const
|
||||
{
|
||||
return m_type_info < ti.m_type_info;
|
||||
}
|
||||
Type_Info(const Type_Info &ti)
|
||||
: m_is_const(ti.m_is_const), m_is_reference(ti.m_is_reference),
|
||||
m_is_pointer(ti.m_is_pointer),
|
||||
m_is_void(ti.m_is_void), m_type_info(ti.m_type_info),
|
||||
m_bare_type_info(ti.m_bare_type_info),
|
||||
m_is_undef(ti.m_is_undef)
|
||||
{
|
||||
}
|
||||
|
||||
bool operator==(const Type_Info &ti) const
|
||||
{
|
||||
return ti.m_type_info == m_type_info;
|
||||
}
|
||||
Type_Info &operator=(const Type_Info &ti)
|
||||
{
|
||||
m_is_const = ti.m_is_const;
|
||||
m_is_reference = ti.m_is_reference;
|
||||
m_is_pointer = ti.m_is_pointer;
|
||||
m_is_void = ti.m_is_void;
|
||||
m_type_info = ti.m_type_info;
|
||||
m_bare_type_info = ti.m_bare_type_info;
|
||||
m_is_undef = ti.m_is_undef;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool m_is_const;
|
||||
bool m_is_reference;
|
||||
bool m_is_pointer;
|
||||
bool m_is_void;
|
||||
const std::type_info *m_type_info;
|
||||
const std::type_info *m_bare_type_info;
|
||||
bool m_is_unknown;
|
||||
bool operator<(const Type_Info &ti) const
|
||||
{
|
||||
return m_type_info < ti.m_type_info;
|
||||
}
|
||||
|
||||
bool operator==(const Type_Info &ti) const
|
||||
{
|
||||
return ti.m_type_info == m_type_info
|
||||
|| (ti.m_type_info && m_type_info && *ti.m_type_info == *m_type_info);
|
||||
}
|
||||
|
||||
bool operator==(const std::type_info &ti) const
|
||||
{
|
||||
return m_type_info != 0 && (*m_type_info) == ti;
|
||||
}
|
||||
|
||||
bool bare_equal(const Type_Info &ti) const
|
||||
{
|
||||
return ti.m_bare_type_info == m_bare_type_info
|
||||
|| (ti.m_bare_type_info && m_bare_type_info && *ti.m_bare_type_info == *m_bare_type_info);
|
||||
}
|
||||
|
||||
bool is_const() const { return m_is_const; }
|
||||
bool is_reference() const { return m_is_reference; }
|
||||
bool is_void() const { return m_is_void; }
|
||||
bool is_undef() const { return m_is_undef || m_bare_type_info == 0; }
|
||||
bool is_pointer() const { return m_is_pointer; }
|
||||
|
||||
std::string name() const
|
||||
{
|
||||
if (m_type_info)
|
||||
{
|
||||
return m_type_info->name();
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
std::string bare_name() const
|
||||
{
|
||||
if (m_bare_type_info)
|
||||
{
|
||||
return m_bare_type_info->name();
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
bool m_is_const;
|
||||
bool m_is_reference;
|
||||
bool m_is_pointer;
|
||||
bool m_is_void;
|
||||
const std::type_info *m_type_info;
|
||||
const std::type_info *m_bare_type_info;
|
||||
bool m_is_undef;
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper used to create a Type_Info object
|
||||
*/
|
||||
template<typename T>
|
||||
struct Get_Type_Info
|
||||
{
|
||||
static Type_Info get()
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* Helper used to create a Type_Info object
|
||||
*/
|
||||
template<typename T>
|
||||
struct Get_Type_Info
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(T),
|
||||
&typeid(typename boost::remove_const<typename boost::remove_pointer<typename boost::remove_reference<T>::type>::type>::type));
|
||||
}
|
||||
};
|
||||
typedef T type;
|
||||
|
||||
template<typename T>
|
||||
struct Get_Type_Info<boost::shared_ptr<T> >
|
||||
{
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(boost::shared_ptr<T> ),
|
||||
&typeid(typename boost::remove_const<typename boost::remove_pointer<typename boost::remove_reference<T>::type>::type>::type));
|
||||
}
|
||||
};
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<typename boost::remove_pointer<typename boost::remove_reference<T>::type>::type>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(T),
|
||||
&typeid(typename Bare_Type<T>::type));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Get_Type_Info<boost::reference_wrapper<T> >
|
||||
{
|
||||
static Type_Info get()
|
||||
template<typename T>
|
||||
struct Get_Type_Info<boost::shared_ptr<T> >
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(boost::reference_wrapper<T> ),
|
||||
&typeid(typename boost::remove_const<typename boost::remove_pointer<typename boost::remove_reference<T>::type>::type>::type));
|
||||
}
|
||||
};
|
||||
typedef T type;
|
||||
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(boost::shared_ptr<T> ),
|
||||
&typeid(typename Bare_Type<T>::type));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Get_Type_Info<const boost::shared_ptr<T> &>
|
||||
{
|
||||
typedef T type;
|
||||
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(const boost::shared_ptr<T> &),
|
||||
&typeid(typename Bare_Type<T>::type));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Get_Type_Info<boost::reference_wrapper<T> >
|
||||
{
|
||||
typedef T type;
|
||||
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(boost::reference_wrapper<T> ),
|
||||
&typeid(typename Bare_Type<T>::type));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Get_Type_Info<const boost::reference_wrapper<T> &>
|
||||
{
|
||||
typedef T type;
|
||||
|
||||
static Type_Info get()
|
||||
{
|
||||
return Type_Info(boost::is_const<T>::value, boost::is_reference<T>::value, boost::is_pointer<T>::value,
|
||||
boost::is_void<T>::value,
|
||||
&typeid(const boost::reference_wrapper<T> &),
|
||||
&typeid(typename Bare_Type<T>::type));
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Stripped_Type
|
||||
{
|
||||
typedef typename Bare_Type<typename detail::Get_Type_Info<T>::type>::type type;
|
||||
};
|
||||
}
|
||||
|
||||
/// \brief Creates a Type_Info object representing the type passed in
|
||||
/// \tparam T Type of object to get a Type_Info for, derived from the passed in parameter
|
||||
/// \return Type_Info for T
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// int i;
|
||||
/// chaiscript::Type_Info ti = chaiscript::user_type(i);
|
||||
/// \endcode
|
||||
template<typename T>
|
||||
Type_Info user_type(const T &/*t*/)
|
||||
{
|
||||
return detail::Get_Type_Info<T>::get();
|
||||
}
|
||||
|
||||
|
||||
/// \brief Creates a Type_Info object representing the templated type
|
||||
/// \tparam T Type of object to get a Type_Info for
|
||||
/// \return Type_Info for T
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// chaiscript::Type_Info ti = chaiscript::user_type<int>();
|
||||
/// \endcode
|
||||
template<typename T>
|
||||
Type_Info user_type()
|
||||
{
|
||||
return detail::Get_Type_Info<T>::get();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
|
220
include/chaiscript/language/chaiscript_common.hpp
Normal file
220
include/chaiscript/language/chaiscript_common.hpp
Normal file
@@ -0,0 +1,220 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_COMMON_HPP_
|
||||
#define CHAISCRIPT_COMMON_HPP_
|
||||
|
||||
#include <chaiscript/dispatchkit/dispatchkit.hpp>
|
||||
#include <boost/enable_shared_from_this.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
/// Signature of module entry point that all binary loadable modules must implement.
|
||||
typedef ModulePtr (*Create_Module_Func)();
|
||||
|
||||
/// Types of AST nodes available to the parser and eval
|
||||
class AST_Node_Type {
|
||||
public:
|
||||
enum Type { Error, Int, Float, Id, Char, Str, Eol, Fun_Call, Inplace_Fun_Call, Arg_List, Variable, Equation, Var_Decl,
|
||||
Comparison, Additive, Multiplicative, Array_Call, Dot_Access, Quoted_String, Single_Quoted_String,
|
||||
Lambda, Block, Def, While, If, For, Inline_Array, Inline_Map, Return, File, Prefix, Break, Map_Pair, Value_Range,
|
||||
Inline_Range, Annotation, Try, Catch, Finally, Method, Attr_Decl, Shift, Equality, Bitwise_And, Bitwise_Xor, Bitwise_Or,
|
||||
Logical_And, Logical_Or
|
||||
};
|
||||
};
|
||||
|
||||
namespace
|
||||
{
|
||||
/**
|
||||
* Helper lookup to get the name of each node type
|
||||
*/
|
||||
const char *ast_node_type_to_string(int ast_node_type) {
|
||||
const char *ast_node_types[] = { "Internal Parser Error", "Int", "Float", "Id", "Char", "Str", "Eol", "Fun_Call", "Inplace_Fun_Call", "Arg_List", "Variable", "Equation", "Var_Decl",
|
||||
"Comparison", "Additive", "Multiplicative", "Array_Call", "Dot_Access", "Quoted_String", "Single_Quoted_String",
|
||||
"Lambda", "Block", "Def", "While", "If", "For", "Inline_Array", "Inline_Map", "Return", "File", "Prefix", "Break", "Map_Pair", "Value_Range",
|
||||
"Inline_Range", "Annotation", "Try", "Catch", "Finally", "Method", "Attr_Decl", "Shift", "Equality", "Bitwise_And", "Bitwise_Xor", "Bitwise_Or",
|
||||
"Logical_And", "Logical_Or"};
|
||||
|
||||
return ast_node_types[ast_node_type];
|
||||
}
|
||||
}
|
||||
|
||||
/// \brief Convenience type for file positions
|
||||
struct File_Position {
|
||||
int line;
|
||||
int column;
|
||||
|
||||
File_Position(int t_file_line, int t_file_column)
|
||||
: line(t_file_line), column(t_file_column) { }
|
||||
|
||||
File_Position() : line(0), column(0) { }
|
||||
};
|
||||
|
||||
/// \brief Typedef for pointers to AST_Node objects. Used in building of the AST_Node tree
|
||||
typedef boost::shared_ptr<struct AST_Node> AST_NodePtr;
|
||||
|
||||
|
||||
/// \brief Classes which may be thrown during error cases when ChaiScript is executing.
|
||||
namespace exception
|
||||
{
|
||||
/**
|
||||
* Errors generated during parsing or evaluation
|
||||
*/
|
||||
struct eval_error : public std::runtime_error {
|
||||
std::string reason;
|
||||
File_Position start_position;
|
||||
File_Position end_position;
|
||||
std::string filename;
|
||||
std::vector<AST_NodePtr> call_stack;
|
||||
|
||||
eval_error(const std::string &t_why, const File_Position &t_where, const std::string &t_fname) throw() :
|
||||
std::runtime_error("Error: \"" + t_why + "\" " +
|
||||
(t_fname != "__EVAL__" ? ("in '" + t_fname + "' ") : "during evaluation ") +
|
||||
+ "at (" + boost::lexical_cast<std::string>(t_where.line) + ", " +
|
||||
boost::lexical_cast<std::string>(t_where.column) + ")"),
|
||||
reason(t_why), start_position(t_where), end_position(t_where), filename(t_fname)
|
||||
{ }
|
||||
|
||||
eval_error(const std::string &t_why) throw()
|
||||
: std::runtime_error("Error: \"" + t_why + "\" "),
|
||||
reason(t_why)
|
||||
{}
|
||||
|
||||
virtual ~eval_error() throw() {}
|
||||
};
|
||||
|
||||
/**
|
||||
* Errors generated when loading a file
|
||||
*/
|
||||
struct file_not_found_error : public std::runtime_error {
|
||||
file_not_found_error(const std::string &t_filename) throw()
|
||||
: std::runtime_error("File Not Found: " + t_filename)
|
||||
{ }
|
||||
|
||||
virtual ~file_not_found_error() throw() {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// \brief Struct that doubles as both a parser ast_node and an AST node.
|
||||
struct AST_Node : boost::enable_shared_from_this<AST_Node> {
|
||||
public:
|
||||
const std::string text;
|
||||
const int identifier;
|
||||
boost::shared_ptr<const std::string> filename;
|
||||
File_Position start, end;
|
||||
std::vector<AST_NodePtr> children;
|
||||
AST_NodePtr annotation;
|
||||
|
||||
/**
|
||||
* Prints the contents of an AST node, including its children, recursively
|
||||
*/
|
||||
std::string to_string(std::string t_prepend = "") {
|
||||
std::ostringstream oss;
|
||||
|
||||
oss << t_prepend << "(" << ast_node_type_to_string(this->identifier) << ") "
|
||||
<< this->text << " : " << this->start.line << ", " << this->start.column << std::endl;
|
||||
|
||||
for (unsigned int j = 0; j < this->children.size(); ++j) {
|
||||
oss << this->children[j]->to_string(t_prepend + " ");
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
std::string internal_to_string() {
|
||||
return to_string();
|
||||
}
|
||||
|
||||
Boxed_Value eval(chaiscript::detail::Dispatch_Engine &t_e)
|
||||
{
|
||||
try {
|
||||
return eval_internal(t_e);
|
||||
} catch (exception::eval_error &ee) {
|
||||
ee.call_stack.push_back(shared_from_this());
|
||||
throw ee;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void replace_child(const AST_NodePtr &t_child, const AST_NodePtr &t_new_child)
|
||||
{
|
||||
std::replace(children.begin(), children.end(), t_child, t_new_child);
|
||||
}
|
||||
|
||||
protected:
|
||||
AST_Node(const std::string &t_ast_node_text, int t_id, const boost::shared_ptr<std::string> &t_fname,
|
||||
int t_start_line, int t_start_col, int t_end_line, int t_end_col) :
|
||||
text(t_ast_node_text), identifier(t_id), filename(t_fname),
|
||||
start(t_start_line, t_start_col), end(t_end_line, t_end_col)
|
||||
{
|
||||
}
|
||||
|
||||
AST_Node(const std::string &t_ast_node_text, int t_id, const boost::shared_ptr<std::string> &t_fname) :
|
||||
text(t_ast_node_text), identifier(t_id), filename(t_fname) {}
|
||||
|
||||
virtual ~AST_Node() {}
|
||||
|
||||
virtual Boxed_Value eval_internal(chaiscript::detail::Dispatch_Engine &)
|
||||
{
|
||||
throw std::runtime_error("Undispatched ast_node (internal error)");
|
||||
}
|
||||
|
||||
private:
|
||||
// Copy and assignment explicitly unimplemented
|
||||
AST_Node(const AST_Node &);
|
||||
AST_Node& operator=(const AST_Node &);
|
||||
};
|
||||
|
||||
|
||||
namespace eval
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
/**
|
||||
* Special type for returned values
|
||||
*/
|
||||
struct Return_Value {
|
||||
Boxed_Value retval;
|
||||
|
||||
Return_Value(const Boxed_Value &t_return_value) : retval(t_return_value) { }
|
||||
};
|
||||
|
||||
/**
|
||||
* Special type indicating a call to 'break'
|
||||
*/
|
||||
struct Break_Loop {
|
||||
Break_Loop() { }
|
||||
};
|
||||
|
||||
/// Creates a new scope then pops it on destruction
|
||||
struct Scope_Push_Pop
|
||||
{
|
||||
Scope_Push_Pop(chaiscript::detail::Dispatch_Engine &t_de)
|
||||
: m_de(t_de)
|
||||
{
|
||||
m_de.new_scope();
|
||||
}
|
||||
|
||||
~Scope_Push_Pop()
|
||||
{
|
||||
m_de.pop_scope();
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
// explicitly unimplemented copy and assignment
|
||||
Scope_Push_Pop(const Scope_Push_Pop &);
|
||||
Scope_Push_Pop& operator=(const Scope_Push_Pop &);
|
||||
|
||||
chaiscript::detail::Dispatch_Engine &m_de;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif /* _CHAISCRIPT_COMMON_HPP */
|
||||
|
@@ -1,7 +1,7 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_ENGINE_HPP_
|
||||
@@ -10,117 +10,652 @@
|
||||
#include <exception>
|
||||
#include <fstream>
|
||||
|
||||
#include <chaiscript/language/chaiscript_common.hpp>
|
||||
|
||||
#include "chaiscript_prelude.hpp"
|
||||
#include "chaiscript_parser.hpp"
|
||||
#ifdef _POSIX_VERSION
|
||||
#include <dlfcn.h>
|
||||
#else
|
||||
#ifdef BOOST_WINDOWS
|
||||
#define VC_EXTRA_LEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <Windows.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
#include <chaiscript/language/chaiscript_prelude.hpp>
|
||||
#include <chaiscript/language/chaiscript_parser.hpp>
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
template <typename Eval_Engine>
|
||||
class ChaiScript_System {
|
||||
Eval_Engine engine;
|
||||
ChaiScript_Parser parser;
|
||||
namespace exception
|
||||
{
|
||||
/// \brief Thrown if an error occurs while attempting to load a binary module
|
||||
struct load_module_error : std::runtime_error
|
||||
{
|
||||
load_module_error(const std::string &t_reason) throw()
|
||||
: std::runtime_error(t_reason)
|
||||
{
|
||||
}
|
||||
|
||||
public:
|
||||
ChaiScript_System() {
|
||||
build_eval_system();
|
||||
virtual ~load_module_error() throw()
|
||||
{
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
#ifdef _POSIX_VERSION
|
||||
struct Loadable_Module
|
||||
{
|
||||
struct DLModule
|
||||
{
|
||||
DLModule(const std::string &t_filename)
|
||||
: m_data(dlopen(t_filename.c_str(), RTLD_NOW))
|
||||
{
|
||||
if (!m_data)
|
||||
{
|
||||
throw exception::load_module_error(dlerror());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current evaluation engine
|
||||
*/
|
||||
Eval_Engine &get_eval_engine() {
|
||||
return engine;
|
||||
DLModule(const DLModule &); // Explicitly unimplemented copy constructor
|
||||
DLModule &operator=(const DLModule &); // Explicitly unimplemented assignment operator
|
||||
|
||||
~DLModule()
|
||||
{
|
||||
dlclose(m_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the contents of an AST node, including its children, recursively
|
||||
*/
|
||||
void debug_print(TokenPtr t, std::string prepend = "") {
|
||||
std::cout << prepend << "(" << token_type_to_string(t->identifier) << ") " << t->text << " : " << t->start.line << ", " << t->start.column << std::endl;
|
||||
for (unsigned int j = 0; j < t->children.size(); ++j) {
|
||||
debug_print(t->children[j], prepend + " ");
|
||||
void *m_data;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct DLSym
|
||||
{
|
||||
DLSym(DLModule &t_mod, const std::string &t_symbol)
|
||||
: m_symbol(reinterpret_cast<T>(dlsym(t_mod.m_data, t_symbol.c_str())))
|
||||
{
|
||||
if (!m_symbol)
|
||||
{
|
||||
throw exception::load_module_error(dlerror());
|
||||
}
|
||||
}
|
||||
|
||||
T m_symbol;
|
||||
};
|
||||
|
||||
Loadable_Module(const std::string &t_module_name, const std::string &t_filename)
|
||||
: m_dlmodule(t_filename), m_func(m_dlmodule, "create_chaiscript_module_" + t_module_name),
|
||||
m_moduleptr(m_func.m_symbol())
|
||||
{
|
||||
}
|
||||
|
||||
DLModule m_dlmodule;
|
||||
DLSym<Create_Module_Func> m_func;
|
||||
ModulePtr m_moduleptr;
|
||||
};
|
||||
#else
|
||||
|
||||
#ifdef WIN32
|
||||
|
||||
|
||||
struct Loadable_Module
|
||||
{
|
||||
template<typename T>
|
||||
static std::wstring towstring(const T &t_str)
|
||||
{
|
||||
return std::wstring(t_str.begin(), t_str.end());
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the given boxed string, used during eval() inside of a script
|
||||
*/
|
||||
const dispatchkit::Boxed_Value eval(const std::vector<dispatchkit::Boxed_Value> &vals) {
|
||||
std::string val;
|
||||
val = dispatchkit::boxed_cast<std::string &>(vals[0]);
|
||||
|
||||
return evaluate_string(val);
|
||||
template<typename T>
|
||||
static std::string tostring(const T &t_str)
|
||||
{
|
||||
return std::string(t_str.begin(), t_str.end());
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for loading a file
|
||||
*/
|
||||
std::string load_file(const char *filename) {
|
||||
std::ifstream infile (filename, std::ios::in | std::ios::ate);
|
||||
#ifdef _UNICODE
|
||||
template<typename T>
|
||||
static std::wstring toproperstring(const T &t_str)
|
||||
{
|
||||
return towstring(t_str);
|
||||
}
|
||||
#else
|
||||
template<typename T>
|
||||
static std::string toproperstring(const T &t_str)
|
||||
{
|
||||
return tostring(t_str);
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!infile.is_open()) {
|
||||
std::string fname = filename;
|
||||
throw std::runtime_error("Can not open: " + fname);
|
||||
static std::string GetErrorMessage(DWORD t_err)
|
||||
{
|
||||
#ifdef _UNICODE
|
||||
typedef LPWSTR StringType;
|
||||
std::wstring retval = L"Unknown Error";
|
||||
#else
|
||||
typedef LPSTR StringType;
|
||||
std::string retval = "Unknown Error";
|
||||
#endif
|
||||
StringType lpMsgBuf = 0;
|
||||
|
||||
FormatMessage(
|
||||
FORMAT_MESSAGE_ALLOCATE_BUFFER |
|
||||
FORMAT_MESSAGE_FROM_SYSTEM |
|
||||
FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
NULL,
|
||||
t_err,
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
(StringType)&lpMsgBuf,
|
||||
0, NULL );
|
||||
|
||||
if (lpMsgBuf)
|
||||
{
|
||||
retval = lpMsgBuf;
|
||||
}
|
||||
|
||||
LocalFree(lpMsgBuf);
|
||||
return tostring(retval);
|
||||
}
|
||||
|
||||
struct DLModule
|
||||
{
|
||||
DLModule(const std::string &t_filename)
|
||||
: m_data(LoadLibrary(toproperstring(t_filename).c_str()))
|
||||
{
|
||||
if (!m_data)
|
||||
{
|
||||
throw exception::load_module_error(GetErrorMessage(GetLastError()));
|
||||
}
|
||||
}
|
||||
|
||||
~DLModule()
|
||||
{
|
||||
FreeLibrary(m_data);
|
||||
}
|
||||
|
||||
HMODULE m_data;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct DLSym
|
||||
{
|
||||
DLSym(DLModule &t_mod, const std::string &t_symbol)
|
||||
: m_symbol(reinterpret_cast<T>(GetProcAddress(t_mod.m_data, t_symbol.c_str())))
|
||||
{
|
||||
if (!m_symbol)
|
||||
{
|
||||
throw exception::load_module_error(GetErrorMessage(GetLastError()));
|
||||
}
|
||||
}
|
||||
|
||||
std::streampos size = infile.tellg();
|
||||
infile.seekg(0, std::ios::beg);
|
||||
T m_symbol;
|
||||
};
|
||||
|
||||
std::vector<char> v(size);
|
||||
infile.read(&v[0], size);
|
||||
Loadable_Module(const std::string &t_module_name, const std::string &t_filename)
|
||||
: m_dlmodule(t_filename), m_func(m_dlmodule, "create_chaiscript_module_" + t_module_name),
|
||||
m_moduleptr(m_func.m_symbol())
|
||||
{
|
||||
}
|
||||
|
||||
std::string ret_val (v.empty() ? std::string() : std::string (v.begin(), v.end()).c_str());
|
||||
|
||||
return ret_val;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds all the requirements for ChaiScript, including its evaluator and a run of its prelude.
|
||||
*/
|
||||
void build_eval_system() {
|
||||
dispatchkit::Bootstrap::bootstrap(engine);
|
||||
dispatchkit::bootstrap_vector<std::vector<dispatchkit::Boxed_Value> >(engine, "Vector");
|
||||
dispatchkit::bootstrap_string<std::string>(engine, "string");
|
||||
dispatchkit::bootstrap_map<std::map<std::string, dispatchkit::Boxed_Value> >(engine, "Map");
|
||||
dispatchkit::bootstrap_pair<std::pair<dispatchkit::Boxed_Value, dispatchkit::Boxed_Value > >(engine, "Pair");
|
||||
|
||||
engine.register_function(boost::shared_ptr<dispatchkit::Proxy_Function>(
|
||||
new dispatchkit::Dynamic_Proxy_Function(boost::bind(&ChaiScript_System<Eval_Engine>::eval, boost::ref(*this), _1), 1)), "eval");
|
||||
|
||||
evaluate_string(chaiscript_prelude);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the given string in by parsing it and running the results through the evaluator
|
||||
*/
|
||||
dispatchkit::Boxed_Value evaluate_string(const std::string &input, const char *filename = "__EVAL__") {
|
||||
//debug_print(tokens);
|
||||
dispatchkit::Boxed_Value value;
|
||||
parser.clear_match_stack();
|
||||
|
||||
try {
|
||||
if (parser.parse(input, filename)) {
|
||||
//parser.show_match_stack();
|
||||
value = eval_token<Eval_Engine>(engine, parser.ast());
|
||||
}
|
||||
}
|
||||
catch (const Return_Value &rv) {
|
||||
value = rv.retval;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the file specified by filename, evaluates it, and returns the result
|
||||
*/
|
||||
dispatchkit::Boxed_Value evaluate_file(const char *filename) {
|
||||
return evaluate_string(load_file(filename), filename);
|
||||
}
|
||||
DLModule m_dlmodule;
|
||||
DLSym<Create_Module_Func> m_func;
|
||||
ModulePtr m_moduleptr;
|
||||
};
|
||||
|
||||
typedef ChaiScript_System<dispatchkit::Dispatch_Engine> ChaiScript_Engine;
|
||||
#else
|
||||
struct Loadable_Module
|
||||
{
|
||||
Loadable_Module(const std::string &, const std::string &)
|
||||
{
|
||||
throw exception::load_module_error("Loadable module support not available for your platform");
|
||||
}
|
||||
|
||||
ModulePtr m_moduleptr;
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
typedef boost::shared_ptr<Loadable_Module> Loadable_Module_Ptr;
|
||||
}
|
||||
|
||||
|
||||
/// \brief The main object that the ChaiScript user will use.
|
||||
class ChaiScript {
|
||||
|
||||
mutable chaiscript::detail::threading::shared_mutex m_mutex;
|
||||
mutable chaiscript::detail::threading::recursive_mutex m_use_mutex;
|
||||
|
||||
std::set<std::string> m_used_files;
|
||||
std::map<std::string, detail::Loadable_Module_Ptr> m_loaded_modules;
|
||||
std::set<std::string> m_active_loaded_modules;
|
||||
|
||||
std::vector<std::string> m_modulepaths;
|
||||
std::vector<std::string> m_usepaths;
|
||||
|
||||
chaiscript::detail::Dispatch_Engine m_engine;
|
||||
|
||||
|
||||
/**
|
||||
* Evaluates the given string in by parsing it and running the results through the evaluator
|
||||
*/
|
||||
Boxed_Value do_eval(const std::string &t_input, const std::string &t_filename = "__EVAL__", bool /* t_internal*/ = false)
|
||||
{
|
||||
try {
|
||||
parser::ChaiScript_Parser parser;
|
||||
if (parser.parse(t_input, t_filename)) {
|
||||
//parser.show_match_stack();
|
||||
return parser.ast()->eval(m_engine);
|
||||
} else {
|
||||
return Boxed_Value();
|
||||
}
|
||||
}
|
||||
catch (const chaiscript::eval::detail::Return_Value &rv) {
|
||||
return rv.retval;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
const Boxed_Value internal_eval_ast(const AST_NodePtr &t_ast)
|
||||
{
|
||||
return t_ast->eval(m_engine);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Evaluates the given string, used during eval() inside of a script
|
||||
*/
|
||||
const Boxed_Value internal_eval(const std::string &t_e) {
|
||||
return do_eval(t_e, "__EVAL__", true);
|
||||
}
|
||||
|
||||
void use(const std::string &t_filename)
|
||||
{
|
||||
for (size_t i = 0; i < m_usepaths.size(); ++i)
|
||||
{
|
||||
|
||||
try {
|
||||
const std::string appendedpath = m_usepaths[i] + t_filename;
|
||||
|
||||
chaiscript::detail::threading::lock_guard<chaiscript::detail::threading::recursive_mutex> l(m_use_mutex);
|
||||
chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l2(m_mutex);
|
||||
|
||||
if (m_used_files.count(appendedpath) == 0)
|
||||
{
|
||||
m_used_files.insert(appendedpath);
|
||||
l2.unlock();
|
||||
eval_file(appendedpath);
|
||||
}
|
||||
} catch (const exception::file_not_found_error &) {
|
||||
if (i == m_usepaths.size() - 1)
|
||||
{
|
||||
throw exception::file_not_found_error(t_filename);
|
||||
}
|
||||
|
||||
// failed to load, try the next path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current evaluation m_engine
|
||||
*/
|
||||
chaiscript::detail::Dispatch_Engine &get_eval_engine() {
|
||||
return m_engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds all the requirements for ChaiScript, including its evaluator and a run of its prelude.
|
||||
*/
|
||||
void build_eval_system() {
|
||||
using namespace bootstrap;
|
||||
m_engine.add_reserved_word("def");
|
||||
m_engine.add_reserved_word("fun");
|
||||
m_engine.add_reserved_word("while");
|
||||
m_engine.add_reserved_word("for");
|
||||
m_engine.add_reserved_word("if");
|
||||
m_engine.add_reserved_word("else");
|
||||
m_engine.add_reserved_word("&&");
|
||||
m_engine.add_reserved_word("||");
|
||||
m_engine.add_reserved_word(",");
|
||||
m_engine.add_reserved_word(":=");
|
||||
m_engine.add_reserved_word("var");
|
||||
m_engine.add_reserved_word("return");
|
||||
m_engine.add_reserved_word("break");
|
||||
m_engine.add_reserved_word("true");
|
||||
m_engine.add_reserved_word("false");
|
||||
m_engine.add_reserved_word("_");
|
||||
|
||||
add(Bootstrap::bootstrap());
|
||||
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::dump_system, boost::ref(m_engine)), "dump_system");
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::dump_object, boost::ref(m_engine)), "dump_object");
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::is_type, boost::ref(m_engine)), "is_type");
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::type_name, boost::ref(m_engine)), "type_name");
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::function_exists, boost::ref(m_engine)), "function_exists");
|
||||
|
||||
m_engine.add(fun(&chaiscript::detail::Dispatch_Engine::get_type_name, boost::ref(m_engine)), "name");
|
||||
|
||||
|
||||
typedef void (ChaiScript::*load_mod_1)(const std::string&);
|
||||
typedef void (ChaiScript::*load_mod_2)(const std::string&, const std::string&);
|
||||
|
||||
m_engine.add(fun(static_cast<load_mod_1>(&ChaiScript::load_module), this), "load_module");
|
||||
m_engine.add(fun(static_cast<load_mod_2>(&ChaiScript::load_module), this), "load_module");
|
||||
|
||||
add(standard_library::vector_type<std::vector<Boxed_Value> >("Vector"));
|
||||
add(standard_library::string_type<std::string>("string"));
|
||||
add(standard_library::map_type<std::map<std::string, Boxed_Value> >("Map"));
|
||||
add(standard_library::pair_type<std::pair<Boxed_Value, Boxed_Value > >("Pair"));
|
||||
|
||||
m_engine.add(fun(&ChaiScript::use, this), "use");
|
||||
m_engine.add(fun(&ChaiScript::internal_eval, this), "eval");
|
||||
m_engine.add(fun(&ChaiScript::internal_eval_ast, this), "eval");
|
||||
|
||||
do_eval(chaiscript_prelude, "standard prelude");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function for loading a file
|
||||
*/
|
||||
std::string load_file(const std::string &t_filename) {
|
||||
std::ifstream infile(t_filename.c_str(), std::ios::in | std::ios::ate | std::ios::binary );
|
||||
|
||||
if (!infile.is_open()) {
|
||||
throw exception::file_not_found_error(t_filename);
|
||||
}
|
||||
|
||||
std::streampos size = infile.tellg();
|
||||
infile.seekg(0, std::ios::beg);
|
||||
|
||||
assert(size >= 0);
|
||||
|
||||
if (size == std::streampos(0))
|
||||
{
|
||||
return std::string();
|
||||
} else {
|
||||
std::vector<char> v(static_cast<unsigned int>(size));
|
||||
infile.read(&v[0], size);
|
||||
return std::string(v.begin(), v.end());
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
/// \brief Constructor for ChaiScript
|
||||
/// \param[in] t_modulepaths Vector of paths to search when attempting to load a binary module
|
||||
/// \param[in] t_usepaths Vector of paths to search when attempting to "use" an included ChaiScript file
|
||||
ChaiScript(const std::vector<std::string> &t_modulepaths = std::vector<std::string>(),
|
||||
const std::vector<std::string> &t_usepaths = std::vector<std::string>())
|
||||
: m_modulepaths(t_modulepaths), m_usepaths(t_usepaths)
|
||||
{
|
||||
if (m_modulepaths.empty())
|
||||
{
|
||||
m_modulepaths.push_back("");
|
||||
}
|
||||
|
||||
if (m_usepaths.empty())
|
||||
{
|
||||
m_usepaths.push_back("");
|
||||
}
|
||||
|
||||
build_eval_system();
|
||||
}
|
||||
|
||||
/// \brief Adds a constant object that is available in all contexts and to all threads
|
||||
/// \param[in] t_bv Boxed_Value to add as a global
|
||||
/// \param[in] t_name Name of the value to add
|
||||
/// \throw exception::global_non_const If t_bv is not a constant object
|
||||
/// \sa Boxed_Value::is_const
|
||||
ChaiScript &add_global_const(const Boxed_Value &t_bv, const std::string &t_name)
|
||||
{
|
||||
m_engine.add_global_const(t_bv, t_name);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Represents the current state of the ChaiScript system. State and be saved and restored
|
||||
/// \sa ChaiScript::get_state
|
||||
/// \sa ChaiScript::set_state
|
||||
struct State
|
||||
{
|
||||
std::set<std::string> used_files;
|
||||
chaiscript::detail::Dispatch_Engine::State engine_state;
|
||||
std::set<std::string> active_loaded_modules;
|
||||
};
|
||||
|
||||
/// \brief Returns a state object that represents the current state of the system
|
||||
/// \return Current state of the system
|
||||
///
|
||||
/// \b Example:
|
||||
///
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chaiscript::ChaiScript::State s = chai.get_state(); // represents bootstrapped initial state
|
||||
/// \endcode
|
||||
State get_state()
|
||||
{
|
||||
chaiscript::detail::threading::lock_guard<chaiscript::detail::threading::recursive_mutex> l(m_use_mutex);
|
||||
chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l2(m_mutex);
|
||||
|
||||
State s;
|
||||
s.used_files = m_used_files;
|
||||
s.engine_state = m_engine.get_state();
|
||||
s.active_loaded_modules = m_active_loaded_modules;
|
||||
return s;
|
||||
}
|
||||
|
||||
/// \brief Sets the state of the system
|
||||
/// \param[in] t_state New state to set
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chaiscript::ChaiScript::State s = chai.get_state(); // get initial state
|
||||
/// chai.add(chaiscript::fun(&somefunction), "somefunction");
|
||||
/// chai.set_state(s); // restore initial state, which does not have the recently added "somefunction"
|
||||
/// \endcode
|
||||
void set_state(const State &t_state)
|
||||
{
|
||||
chaiscript::detail::threading::lock_guard<chaiscript::detail::threading::recursive_mutex> l(m_use_mutex);
|
||||
chaiscript::detail::threading::shared_lock<chaiscript::detail::threading::shared_mutex> l2(m_mutex);
|
||||
|
||||
m_used_files = t_state.used_files;
|
||||
m_active_loaded_modules = t_state.active_loaded_modules;
|
||||
m_engine.set_state(t_state.engine_state);
|
||||
}
|
||||
|
||||
/// \brief Adds a type, function or object to ChaiScript
|
||||
/// \param[in] t_t Item to add
|
||||
/// \param[in] t_name Name of item to add
|
||||
/// \returns Reference to current ChaiScript object
|
||||
///
|
||||
/// \b Examples:
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::user_type<MyClass>(), "MyClass"); // Add explicit type info (not strictly necessary)
|
||||
/// chai.add(chaiscript::fun(&MyClass::function), "function"); // Add a class method
|
||||
/// MyClass obj;
|
||||
/// chai.add(chaiscript::var(&obj), "obj"); // Add a pointer to a locally defined object
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref addingitems
|
||||
template<typename T>
|
||||
ChaiScript &add(const T &t_t, const std::string &t_name)
|
||||
{
|
||||
m_engine.add(t_t, t_name);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Add a new conversion for upcasting to a base class
|
||||
/// \sa chaiscript::base_class
|
||||
/// \param[in] d Base class / parent class
|
||||
///
|
||||
/// \b Example:
|
||||
/// \code
|
||||
/// chaiscript::ChaiScript chai;
|
||||
/// chai.add(chaiscript::base_class<std::runtime_error, chaiscript::dispatch_error>());
|
||||
/// \endcode
|
||||
ChaiScript &add(const Dynamic_Cast_Conversion &d)
|
||||
{
|
||||
m_engine.add(d);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Adds all elements of a module to ChaiScript runtime
|
||||
/// \param[in] t_p The module to add.
|
||||
/// \sa chaiscript::Module
|
||||
ChaiScript &add(const ModulePtr &t_p)
|
||||
{
|
||||
t_p->apply(*this, this->get_eval_engine());
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// \brief Load a binary module from a dynamic library. Works on platforms that support
|
||||
/// dynamic libraries.
|
||||
/// \param[in] t_module_name Name of the module to load
|
||||
///
|
||||
/// The module is searched for in the registered module path folders (chaiscript::ChaiScript::ChaiScript)
|
||||
/// and with standard prefixes and postfixes: ("lib"|"")\<t_module_name\>(".dll"|".so"|"").
|
||||
///
|
||||
/// Once the file is located, the system looks for the symbol "create_chaiscript_module_\<t_module_name\>".
|
||||
/// If no file can be found matching the search criteria and containing the appropriate entry point
|
||||
/// (the symbol mentioned above), an exception is thrown.
|
||||
///
|
||||
/// \throw exception::load_module_error In the event that no matching module can be found.
|
||||
void load_module(const std::string &t_module_name)
|
||||
{
|
||||
std::vector<exception::load_module_error> errors;
|
||||
|
||||
std::vector<std::string> prefixes;
|
||||
prefixes.push_back("lib");
|
||||
prefixes.push_back("");
|
||||
|
||||
std::vector<std::string> postfixes;
|
||||
postfixes.push_back(".dll");
|
||||
postfixes.push_back(".so");
|
||||
postfixes.push_back("");
|
||||
|
||||
for (size_t i = 0; i < m_modulepaths.size(); ++i)
|
||||
{
|
||||
for (size_t j = 0; j < prefixes.size(); ++j)
|
||||
{
|
||||
for (size_t k = 0; k < postfixes.size(); ++k)
|
||||
{
|
||||
try {
|
||||
std::string name = m_modulepaths[i] + prefixes[j] + t_module_name + postfixes[k];
|
||||
load_module(t_module_name, name);
|
||||
return;
|
||||
} catch (const exception::load_module_error &e) {
|
||||
errors.push_back(e);
|
||||
// Try next set
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string errstring;
|
||||
|
||||
for (std::vector<exception::load_module_error>::const_iterator itr = errors.begin();
|
||||
itr != errors.end();
|
||||
++itr)
|
||||
{
|
||||
if (!errstring.empty())
|
||||
{
|
||||
errstring += "; ";
|
||||
}
|
||||
|
||||
errstring += itr->what();
|
||||
}
|
||||
|
||||
throw exception::load_module_error("Unable to find module: " + t_module_name + " Errors: " + errstring);
|
||||
}
|
||||
|
||||
/// \brief Load a binary module from a dynamic library. Works on platforms that support
|
||||
/// dynamic libraries.
|
||||
///
|
||||
/// \param[in] t_module_name Module name to load
|
||||
/// \param[in] t_filename Ignore normal filename search process and use specific filename
|
||||
///
|
||||
/// \sa ChaiScript::load_module(const std::string &t_module_name)
|
||||
void load_module(const std::string &t_module_name, const std::string &t_filename)
|
||||
{
|
||||
chaiscript::detail::threading::lock_guard<chaiscript::detail::threading::recursive_mutex> l(m_use_mutex);
|
||||
|
||||
if (m_loaded_modules.count(t_module_name) == 0)
|
||||
{
|
||||
detail::Loadable_Module_Ptr lm(new detail::Loadable_Module(t_module_name, t_filename));
|
||||
m_loaded_modules[t_module_name] = lm;
|
||||
m_active_loaded_modules.insert(t_module_name);
|
||||
add(lm->m_moduleptr);
|
||||
} else if (m_active_loaded_modules.count(t_module_name) == 0) {
|
||||
m_active_loaded_modules.insert(t_module_name);
|
||||
add(m_loaded_modules[t_module_name]->m_moduleptr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// \brief Evaluates a string. Equivalent to ChaiScript::eval.
|
||||
///
|
||||
/// \param[in] t_script Script to execute
|
||||
///
|
||||
/// \return result of the script execution
|
||||
///
|
||||
/// \throw exception::eval_error In the case that evaluation fails.
|
||||
Boxed_Value operator()(const std::string &t_script)
|
||||
{
|
||||
return do_eval(t_script);
|
||||
}
|
||||
|
||||
/// \brief Evaluates a string and returns a typesafe result.
|
||||
///
|
||||
/// \tparam T Type to extract from the result value of the script execution
|
||||
/// \param[in] t_input Script to execute
|
||||
///
|
||||
/// \return result of the script execution
|
||||
///
|
||||
/// \throw exception::eval_error In the case that evaluation fails.
|
||||
/// \throw exception::bad_boxed_cast In the case that evaluation succeeds but the result value cannot be converted
|
||||
/// to the requested type.
|
||||
template<typename T>
|
||||
T eval(const std::string &t_input)
|
||||
{
|
||||
return boxed_cast<T>(do_eval(t_input));
|
||||
}
|
||||
|
||||
/// \brief Evaluates a string.
|
||||
///
|
||||
/// \param[in] t_input Script to execute
|
||||
///
|
||||
/// \return result of the script execution
|
||||
///
|
||||
/// \throw exception::eval_error In the case that evaluation fails.
|
||||
Boxed_Value eval(const std::string &t_input)
|
||||
{
|
||||
return do_eval(t_input);
|
||||
}
|
||||
|
||||
/// \brief Loads the file specified by filename, evaluates it, and returns the result.
|
||||
/// \param[in] t_filename File to load and parse.
|
||||
/// \return result of the script execution
|
||||
/// \throw exception::eval_error In the case that evaluation fails.
|
||||
Boxed_Value eval_file(const std::string &t_filename) {
|
||||
return do_eval(load_file(t_filename), t_filename);
|
||||
}
|
||||
|
||||
/// \brief Loads the file specified by filename, evaluates it, and returns the typesafe result.
|
||||
/// \tparam T Type to extract from the result value of the script execution
|
||||
/// \param[in] t_filename File to load and parse.
|
||||
/// \return result of the script execution
|
||||
/// \throw exception::eval_error In the case that evaluation fails.
|
||||
/// \throw exception::bad_boxed_cast In the case that evaluation succeeds but the result value cannot be converted
|
||||
/// to the requested type.
|
||||
template<typename T>
|
||||
T eval_file(const std::string &t_filename) {
|
||||
return boxed_cast<T>(do_eval(load_file(t_filename), t_filename));
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
#endif /* CHAISCRIPT_ENGINE_HPP_ */
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_PRELUDE_HPP_
|
||||
@@ -9,257 +9,321 @@
|
||||
|
||||
//Note, the expression "[x,y]" in "collate" is parsed as two separate expressions
|
||||
//by C++, so CODE_STRING, takes two expressions and adds in the missing comma
|
||||
#define CODE_STRING(x, y) #x ", " #y
|
||||
#define CODE_STRING(x, y) #x ", " #y
|
||||
|
||||
#define chaiscript_prelude CODE_STRING(\
|
||||
def lt(l, r) { if (call_exists(`<`, l, r)) { l < r } else { type_name(l) < type_name(r) } } \n\
|
||||
def gt(l, r) { if (call_exists(`>`, l, r)) { l > r } else { type_name(l) > type_name(r) } } \n\
|
||||
def eq(l, r) { if (call_exists(`==`, l, r)) { l == r } else { false } } \n\
|
||||
def new(x) { eval(type_name(x))(); } \n\
|
||||
def clone(x) : function_exists(type_name(x)) && call_exists(eval(type_name(x)), x) { eval(type_name(x))(x); } \n\
|
||||
# to_string for Pair()\n\
|
||||
def to_string(x) : call_exists(first, x) && call_exists(second, x) { \
|
||||
"<" + x.first.to_string() + ", " + x.second.to_string() + ">"; \
|
||||
}\
|
||||
def to_string(x) : call_exists(first, x) && call_exists(second, x) { \n\
|
||||
"<" + x.first.to_string() + ", " + x.second.to_string() + ">"; \n\
|
||||
}\n\
|
||||
# to_string for containers\n\
|
||||
def to_string(x) : call_exists(range, x) && !x.is_type("string"){ \
|
||||
"[" + x.join(", ") + "]"; \
|
||||
}\
|
||||
def to_string(x) : call_exists(range, x) && !x.is_type("string"){ \n\
|
||||
"[" + x.join(", ") + "]"; \n\
|
||||
}\n\
|
||||
# Basic to_string function\n\
|
||||
def to_string(x) { \
|
||||
return internal_to_string(x); \
|
||||
}\
|
||||
def to_string(x) { \n\
|
||||
internal_to_string(x); \n\
|
||||
}\n\
|
||||
# Prints to console with no carriage return\n\
|
||||
def puts(x) { \
|
||||
print_string(x.to_string()); \
|
||||
} \
|
||||
def puts(x) { \n\
|
||||
print_string(x.to_string()); \n\
|
||||
} \n\
|
||||
# Prints to console with carriage return\n\
|
||||
def print(x) { \
|
||||
println_string(x.to_string()); \
|
||||
} \
|
||||
def print(x) { \n\
|
||||
println_string(x.to_string()); \n\
|
||||
} \n\
|
||||
# Returns the maximum value of two numbers\n\
|
||||
def max(a, b) { if (a>b) { a } else { b } } \
|
||||
def max(a, b) { if (a>b) { a } else { b } } \n\
|
||||
# Returns the minimum value of two numbers\n\
|
||||
def min(a, b) { if (a<b) { a } else { b } } \
|
||||
def min(a, b) { if (a<b) { a } else { b } } \n\
|
||||
# Returns true if the value is odd\n\
|
||||
def odd(x) { if (x % 2 == 1) { true } else { false } } \
|
||||
def odd(x) { if (x % 2 == 1) { true } else { false } } \n\
|
||||
# Returns true if the value is even\n\
|
||||
def even(x) { if (x % 2 == 0) { true } else { false } } \
|
||||
def even(x) { if (x % 2 == 0) { true } else { false } } \n\
|
||||
# Pushes the second value onto the container first value while making a clone of the value\n\
|
||||
def push_back(container, x) { container.push_back_ref(clone(x)) } \n\
|
||||
def push_back(container, x) : call_exists(push_back_ref, container, x) { container.push_back_ref(clone(x)) } \n\
|
||||
# Pushes the second value onto the front of the container first value while making a clone of the value\n\
|
||||
def push_front(container, x) : call_exists(push_front_ref, container, x) { container.push_front_ref(clone(x)) } \n\
|
||||
# Inserts the third value at the position of the second value into the container of the first\n\
|
||||
# while making a clone. \n\
|
||||
def insert_at(container, pos, x) { container.insert_ref_at(pos, clone(x)); } \n\
|
||||
# Returns the reverse of the given container\n\
|
||||
def reverse(container) {\n\
|
||||
var retval = new(container); \n\
|
||||
var r = range(container); \n\
|
||||
while (!r.empty()) { \n\
|
||||
retval.push_back(r.back()); \n\
|
||||
r.pop_back(); \n\
|
||||
} \n\
|
||||
retval; \n\
|
||||
} \n\
|
||||
# Return a range from a range \n\
|
||||
def range(r) : call_exists(empty, r) && call_exists(pop_front, r) && call_exists(pop_back, r) && call_exists(back, r) && call_exists(front, r) { return clone(r); }\n\
|
||||
# The retro attribute that contains the underlying range \n\
|
||||
attr retro::m_range; \n\
|
||||
# Creates a retro from a retro by returning the original range\n\
|
||||
def retro(r) : call_exists(get_type_name, r) && get_type_name(r) == "retro" { clone(r.m_range) }\n\
|
||||
# Creates a retro range from a range\n\
|
||||
def retro::retro(r) : call_exists(empty, r) && call_exists(pop_front, r) && call_exists(pop_back, r) && call_exists(back, r) && call_exists(front, r) { this.m_range = r; }\n\
|
||||
# Returns the first value of a retro\n\
|
||||
def retro::front() { back(this.m_range) }\n\
|
||||
# Returns the last value of a retro\n\
|
||||
def retro::back() { front(this.m_range) }\n\
|
||||
# Moves the back iterator of a retro towards the front by one \n\
|
||||
def retro::pop_back() { pop_front(this.m_range) }\n\
|
||||
# Moves the front iterator of a retro towards the back by one \n\
|
||||
def retro::pop_front() { pop_back(this.m_range) } \n\
|
||||
# returns true if the retro is out of elements \n\
|
||||
def retro::empty() { empty(this.m_range); } \n\
|
||||
# Performs the second value function over the container first value\n\
|
||||
def for_each(container, func) : call_exists(range, container) { \
|
||||
var range = range(container); \
|
||||
while (!range.empty()) { \
|
||||
func(range.front()); \
|
||||
range.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
def back_inserter(container) { \
|
||||
return bind(push_back, container, _); \
|
||||
}\
|
||||
\
|
||||
def map(container, func, inserter) : call_exists(range, container) { \
|
||||
var range = range(container); \
|
||||
while (!range.empty()) { \
|
||||
inserter(func(range.front())); \
|
||||
range.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
# Performs the second value function over the container first value. Creates a new Vector with the results\n\
|
||||
def map(container, func) { \
|
||||
var retval = Vector();\
|
||||
map(container, func, back_inserter(retval));\
|
||||
return retval;\
|
||||
}\
|
||||
def for_each(container, func) : call_exists(range, container) { \n\
|
||||
var t_range = range(container); \n\
|
||||
while (!t_range.empty()) { \n\
|
||||
func(t_range.front()); \n\
|
||||
t_range.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
def back_inserter(container) { \n\
|
||||
bind(push_back, container, _); \n\
|
||||
}\n\
|
||||
\n\
|
||||
def contains(container, item, compare_func) : call_exists(range, container) { \n\
|
||||
var t_range = range(container); \n\
|
||||
while (!t_range.empty()) { \n\
|
||||
if ( compare_func(t_range.front(), item) ) { return true; } \n\
|
||||
t_range.pop_front(); \n\
|
||||
} \n\
|
||||
return false; \n\
|
||||
} \n\
|
||||
def contains(container, item) { return contains(container, item, eq) } \n\
|
||||
def map(container, func, inserter) : call_exists(range, container) { \n\
|
||||
var range = range(container); \n\
|
||||
while (!range.empty()) { \n\
|
||||
inserter(func(range.front())); \n\
|
||||
range.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Performs the second value function over the container first value. Creates a new container with the results\n\
|
||||
def map(container, func) { \n\
|
||||
var retval = new(container); \n\
|
||||
map(container, func, back_inserter(retval));\n\
|
||||
retval;\n\
|
||||
}\n\
|
||||
# Performs the second value function over the container first value. Starts with initial and continues with each element.\n\
|
||||
def foldl(container, func, initial) : call_exists(range, container){ \
|
||||
var retval = initial; \
|
||||
var range = range(container); \
|
||||
while (!range.empty()) { \
|
||||
retval = (func(range.front(), retval)); \
|
||||
range.pop_front(); \
|
||||
} \
|
||||
retval; \
|
||||
} \
|
||||
def foldl(container, func, initial) : call_exists(range, container){ \n\
|
||||
var retval = initial; \n\
|
||||
var range = range(container); \n\
|
||||
while (!range.empty()) { \n\
|
||||
retval = (func(range.front(), retval)); \n\
|
||||
range.pop_front(); \n\
|
||||
} \n\
|
||||
retval; \n\
|
||||
} \n\
|
||||
# Returns the sum of the elements of the given value\n\
|
||||
def sum(container) { foldl(container, `+`, 0.0) } \
|
||||
def sum(container) { foldl(container, `+`, 0.0) } \n\
|
||||
# Returns the product of the elements of the given value\n\
|
||||
def product(container) { foldl(container, `*`, 1.0) } \
|
||||
# Returns a new Vector with the elements of the first value concatenated with the elements of the second value\n\
|
||||
def concat(x, y) : call_exists(clone, x) { \
|
||||
var retval = x; \
|
||||
var len = y.size(); \
|
||||
var i = 0; \
|
||||
while (i < len) { \
|
||||
retval.push_back(y[i]); \
|
||||
++i; \
|
||||
} \
|
||||
retval; \
|
||||
} \
|
||||
def take(container, num, inserter) : call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
var i = num; \
|
||||
while ((i > 0) && (!r.empty())) { \
|
||||
inserter(r.front()); \
|
||||
r.pop_front(); \
|
||||
--i; \
|
||||
} \
|
||||
} \
|
||||
# Returns a new Vector with the given number of elements taken from the container\n\
|
||||
def take(container, num) {\
|
||||
var retval = Vector(); \
|
||||
take(container, num, back_inserter(retval)); \
|
||||
return retval; \
|
||||
}\
|
||||
def take_while(container, f, inserter) : call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
while ((!r.empty()) && f(r.front())) { \
|
||||
inserter(r.front()); \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
# Returns a new Vector with the given elements match the second value function\n\
|
||||
def take_while(container, f) {\
|
||||
var retval = Vector(); \
|
||||
take_while(container, f, back_inserter(retval)); \
|
||||
return retval;\
|
||||
}\
|
||||
def drop(container, num, inserter) : call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
var i = num; \
|
||||
while ((i > 0) && (!r.empty())) { \
|
||||
r.pop_front(); \
|
||||
--i; \
|
||||
} \
|
||||
while (!r.empty()) { \
|
||||
inserter(r.front()); \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
# Returns a new Vector with the given number of elements dropped from the given container \n\
|
||||
def drop(container, num) {\
|
||||
var retval = Vector(); \
|
||||
drop(container, num, back_inserter(retval)); \
|
||||
return retval; \
|
||||
}\
|
||||
def drop_while(container, f, inserter) : call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
while ((!r.empty())&& f(r.front())) { \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
while (!r.empty()) { \
|
||||
inserter(r.front()); \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
# Returns a new Vector with the given elements dropped that match the second value function\n\
|
||||
def drop_while(container, f) {\
|
||||
var retval = Vector(); \
|
||||
drop_while(container, f, back_inserter(retval)); \
|
||||
return retval; \
|
||||
}\
|
||||
def product(container) { foldl(container, `*`, 1.0) } \n\
|
||||
# Returns a new container with the elements of the first value concatenated with the elements of the second value\n\
|
||||
def concat(x, y) : call_exists(clone, x) { \n\
|
||||
var retval = x; \n\
|
||||
var inserter = back_inserter(retval); \n\
|
||||
var range = range(y); \n\
|
||||
while (!range.empty()) { \n\
|
||||
inserter(range.front()); \n\
|
||||
range.pop_front(); \n\
|
||||
} \n\
|
||||
retval; \n\
|
||||
} \n\
|
||||
def take(container, num, inserter) : call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
var i = num; \n\
|
||||
while ((i > 0) && (!r.empty())) { \n\
|
||||
inserter(r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
--i; \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new container with the given number of elements taken from the container\n\
|
||||
def take(container, num) {\n\
|
||||
var retval = new(container); \n\
|
||||
take(container, num, back_inserter(retval)); \n\
|
||||
retval; \n\
|
||||
}\n\
|
||||
def take_while(container, f, inserter) : call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
while ((!r.empty()) && f(r.front())) { \n\
|
||||
inserter(r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new container with the given elements match the second value function\n\
|
||||
def take_while(container, f) {\n\
|
||||
var retval = new(container); \n\
|
||||
take_while(container, f, back_inserter(retval)); \n\
|
||||
retval;\n\
|
||||
}\n\
|
||||
def drop(container, num, inserter) : call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
var i = num; \n\
|
||||
while ((i > 0) && (!r.empty())) { \n\
|
||||
r.pop_front(); \n\
|
||||
--i; \n\
|
||||
} \n\
|
||||
while (!r.empty()) { \n\
|
||||
inserter(r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new container with the given number of elements dropped from the given container \n\
|
||||
def drop(container, num) {\n\
|
||||
var retval = new(container); \n\
|
||||
drop(container, num, back_inserter(retval)); \n\
|
||||
retval; \n\
|
||||
}\n\
|
||||
def drop_while(container, f, inserter) : call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
while ((!r.empty())&& f(r.front())) { \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
while (!r.empty()) { \n\
|
||||
inserter(r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new container with the given elements dropped that match the second value function\n\
|
||||
def drop_while(container, f) {\n\
|
||||
var retval = new(container); \n\
|
||||
drop_while(container, f, back_inserter(retval)); \n\
|
||||
retval; \n\
|
||||
}\n\
|
||||
# Applies the second value function to the container. Starts with the first two elements. Expects at least 2 elements.\n\
|
||||
def reduce(container, func) : container.size() >= 2 && call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
var retval = r.front(); \
|
||||
r.pop_front(); \
|
||||
retval = func(retval, r.front()); \
|
||||
r.pop_front(); \
|
||||
while (!r.empty()) { \
|
||||
retval = func(retval, r.front()); \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
retval; \
|
||||
} \
|
||||
def reduce(container, func) : container.size() >= 2 && call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
var retval = r.front(); \n\
|
||||
r.pop_front(); \n\
|
||||
retval = func(retval, r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
while (!r.empty()) { \n\
|
||||
retval = func(retval, r.front()); \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
retval; \n\
|
||||
} \n\
|
||||
# Returns a string of the elements in container delimited by the second value string\n\
|
||||
def join(container, delim) { \
|
||||
var retval = ""; \
|
||||
var range = range(container); \
|
||||
if (!range.empty()) { \
|
||||
retval += to_string(range.front()); \
|
||||
range.pop_front(); \
|
||||
while (!range.empty()) { \
|
||||
retval += delim; \
|
||||
retval += to_string(range.front()); \
|
||||
range.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
retval; \
|
||||
} \
|
||||
def filter(container, f, inserter) : call_exists(range, container) { \
|
||||
var r = range(container); \
|
||||
while (!r.empty()) { \
|
||||
if (f(r.front())) { \
|
||||
inserter(r.front()); \
|
||||
} \
|
||||
r.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
def join(container, delim) { \n\
|
||||
var retval = ""; \n\
|
||||
var range = range(container); \n\
|
||||
if (!range.empty()) { \n\
|
||||
retval += to_string(range.front()); \n\
|
||||
range.pop_front(); \n\
|
||||
while (!range.empty()) { \n\
|
||||
retval += delim; \n\
|
||||
retval += to_string(range.front()); \n\
|
||||
range.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
retval; \n\
|
||||
} \n\
|
||||
def filter(container, f, inserter) : call_exists(range, container) { \n\
|
||||
var r = range(container); \n\
|
||||
while (!r.empty()) { \n\
|
||||
if (f(r.front())) { \n\
|
||||
inserter(r.front()); \n\
|
||||
} \n\
|
||||
r.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new Vector which match the second value function\n\
|
||||
def filter(container, f) { \
|
||||
var retval = Vector(); \
|
||||
filter(container, f, back_inserter(retval));\
|
||||
return retval;\
|
||||
}\
|
||||
def generate_range(x, y, inserter) { \
|
||||
var i = x; \
|
||||
while (i <= y) { \
|
||||
inserter(i); \
|
||||
++i; \
|
||||
} \
|
||||
} \
|
||||
def filter(container, f) { \n\
|
||||
var retval = new(container); \n\
|
||||
filter(container, f, back_inserter(retval));\n\
|
||||
retval;\n\
|
||||
}\n\
|
||||
def generate_range(x, y, inserter) { \n\
|
||||
var i = x; \n\
|
||||
while (i <= y) { \n\
|
||||
inserter(i); \n\
|
||||
++i; \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new Vector which represents the range from the first value to the second value\n\
|
||||
def generate_range(x, y) { \
|
||||
var retval = Vector(); \
|
||||
generate_range(x,y,back_inserter(retval)); \
|
||||
return retval; \
|
||||
}\
|
||||
def generate_range(x, y) { \n\
|
||||
var retval = Vector(); \n\
|
||||
generate_range(x,y,back_inserter(retval)); \n\
|
||||
retval; \n\
|
||||
}\n\
|
||||
# Returns a new Vector with the first value to the second value as its elements\n\
|
||||
def collate(x, y) { \
|
||||
[x, y]; \
|
||||
} \
|
||||
def zip_with(f, x, y, inserter) : call_exists(range, x) && call_exists(range, y) { \
|
||||
var r_x = range(x); \
|
||||
var r_y = range(y); \
|
||||
while (!r_x.empty() && !r_y.empty()) { \
|
||||
inserter(f(r_x.front(), r_y.front())); \
|
||||
r_x.pop_front(); \
|
||||
r_y.pop_front(); \
|
||||
} \
|
||||
} \
|
||||
def collate(x, y) { \n\
|
||||
[x, y]; \n\
|
||||
} \n\
|
||||
def zip_with(f, x, y, inserter) : call_exists(range, x) && call_exists(range, y) { \n\
|
||||
var r_x = range(x); \n\
|
||||
var r_y = range(y); \n\
|
||||
while (!r_x.empty() && !r_y.empty()) { \n\
|
||||
inserter(f(r_x.front(), r_y.front())); \n\
|
||||
r_x.pop_front(); \n\
|
||||
r_y.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
# Returns a new Vector which joins matching elements of the second and third value with the first value function\n\
|
||||
def zip_with(f, x, y) { \
|
||||
var retval = Vector(); \
|
||||
zip_with(f,x,y,back_inserter(retval)); \
|
||||
return retval;\
|
||||
}\
|
||||
def zip_with(f, x, y) { \n\
|
||||
var retval = Vector(); \n\
|
||||
zip_with(f,x,y,back_inserter(retval)); \n\
|
||||
retval;\n\
|
||||
}\n\
|
||||
# Returns a new Vector which joins matching elements of the first and second\n\
|
||||
def zip(x, y) { \
|
||||
zip_with(collate, x, y); \
|
||||
}\
|
||||
def zip(x, y) { \n\
|
||||
zip_with(collate, x, y); \n\
|
||||
}\n\
|
||||
# Returns the position of the second value string in the first value string\n\
|
||||
def find(str, substr) { \
|
||||
return int(find(str, substr, size_t(0))); \
|
||||
} \
|
||||
def string::find(substr) : is_type(substr, "string") { \n\
|
||||
int(find(this, substr, 0)); \n\
|
||||
} \n\
|
||||
# Returns the position of last match of the second value string in the first value string\n\
|
||||
def rfind(str, substr) { \
|
||||
return int(rfind(str, substr, size_t(-1))); \
|
||||
} \
|
||||
def string::rfind(substr) : is_type(substr, "string") { \n\
|
||||
int(rfind(this, substr, -1)); \n\
|
||||
} \n\
|
||||
# Returns the position of the first match of elements in the second value string in the first value string\n\
|
||||
def find_first_of(str, list) { \
|
||||
return int(find_first_of(str, list, size_t(0))); \
|
||||
} \
|
||||
def string::find_first_of(list) : is_type(list, "string") { \n\
|
||||
int(find_first_of(this, list, 0)); \n\
|
||||
} \n\
|
||||
# Returns the position of the last match of elements in the second value string in the first value string\n\
|
||||
def find_last_of(str, list) { \
|
||||
return int(find_last_of(str, list, size_t(-1))); \
|
||||
} \
|
||||
def string::find_last_of(list) : is_type(list, "string") { \n\
|
||||
int(find_last_of(this, list, -1)); \n\
|
||||
} \n\
|
||||
# Returns the position of the first non-matching element in the second value string in the first value string\n\
|
||||
def find_first_not_of(str, list) { \
|
||||
return int(find_first_not_of(str, list, size_t(0))); \
|
||||
} \
|
||||
def string::find_first_not_of(list) : is_type(list, "string") { \n\
|
||||
int(find_first_not_of(this, list, 0)); \n\
|
||||
} \n\
|
||||
# Returns the position of the last non-matching element in the second value string in the first value string\n\
|
||||
def find_last_not_of(str, list) { \
|
||||
return int(find_last_not_of(str, list, size_t(-1))); \
|
||||
} \
|
||||
def string::find_last_not_of(list) : is_type(list, "string") { \n\
|
||||
int(find_last_not_of(this, list, -1)); \n\
|
||||
} \n\
|
||||
def string::ltrim() { \n\
|
||||
drop_while(this, fun(x) { x == ' ' || x == '\t' || x == '\r' || x == '\n'}); \n\
|
||||
} \n\
|
||||
def string::rtrim() { \n\
|
||||
reverse(drop_while(reverse(this), fun(x) { x == ' ' || x == '\t' || x == '\r' || x == '\n'})); \n\
|
||||
} \n\
|
||||
def string::trim() { \n\
|
||||
ltrim(rtrim(this)); \n\
|
||||
} \n\
|
||||
def find(container, value, compare_func) : call_exists(range, container) && is_type(compare_func, "Function") { \n\
|
||||
var range = range(container); \n\
|
||||
while (!range.empty()) { \n\
|
||||
if (compare_func(range.front(), value)) { \n\
|
||||
return range; \n\
|
||||
} else { \n\
|
||||
range.pop_front(); \n\
|
||||
} \n\
|
||||
} \n\
|
||||
return range; \n\
|
||||
} \n\
|
||||
def find(container, value) { return find(container, value, eq) } \
|
||||
)
|
||||
|
||||
#endif /* CHAISCRIPT_PRELUDE_HPP_ */
|
||||
|
830
include/chaiscript/language/chaiscript_prelude_docs.hpp
Normal file
830
include/chaiscript/language/chaiscript_prelude_docs.hpp
Normal file
@@ -0,0 +1,830 @@
|
||||
/// This file is not technically part of the ChaiScript API. It is used solely for generating Doxygen docs
|
||||
/// regarding the ChaiScript standard runtime library.
|
||||
|
||||
/// \brief Items in this namespace exist in the ChaiScript language runtime. They are not part of the C++ API
|
||||
namespace ChaiScript_Language
|
||||
{
|
||||
|
||||
/// \page LangStandardLibraryRef ChaiScript Language Standard Libary Reference
|
||||
///
|
||||
/// ChaiScript, at its core, has some very functional programming-inspired habits. Few places show this off as clearly
|
||||
/// as the prelude, itself a name taken as a nod to the popular functional language Haskell. This prelude is available
|
||||
/// to all standard ChaiScript applications, and provides a simple foundation for using numbers, strings, and ranges
|
||||
/// (the general category of Range cs and their iteration).
|
||||
///
|
||||
|
||||
|
||||
/// \brief Generic concept of a value in ChaiScript.
|
||||
///
|
||||
/// The Object type exists merely as a concept. All objects in ChaiScript support this concept
|
||||
/// and have the following methods available to them. All objects are stored internally as chaiscript::Boxed_Value types.
|
||||
///
|
||||
/// \sa chaiscript::Boxed_Value
|
||||
class Object
|
||||
{
|
||||
public:
|
||||
/// \brief Returns the Type_Info value for this Object
|
||||
Type_Info get_type_info() const;
|
||||
|
||||
/// \brief Returns true if the Object is of the named type
|
||||
bool is_type(string) const;
|
||||
|
||||
/// \brief Returns true if the Object is of the Type_Info passed in
|
||||
bool is_type(Type_Info) const;
|
||||
|
||||
/// \brief Returns true if the Object is immutable
|
||||
bool is_var_const() const;
|
||||
|
||||
/// \brief Returns true if the Object is a pointer and the pointer is null
|
||||
bool is_var_null() const;
|
||||
|
||||
/// \brief Returns true if the Object is stored as a pointer
|
||||
bool is_var_pointer() const;
|
||||
|
||||
/// \brief Returns true if the Object is stored as a reference
|
||||
bool is_var_reference() const;
|
||||
|
||||
/// \brief Returns true if the Object does not contain a value is is undefined.
|
||||
bool is_var_undef() const;
|
||||
|
||||
/// \brief Returns the registered name of the type of the object.
|
||||
///
|
||||
/// \sa Type_Info::name();
|
||||
string type_name() const;
|
||||
};
|
||||
|
||||
/// \brief Item returned from a Range object from a Map
|
||||
class Map_Pair
|
||||
{
|
||||
public:
|
||||
/// \brief Returns the key of the Map entry
|
||||
const string first();
|
||||
|
||||
/// \brief Returns the value Object of the Map entry
|
||||
Object second();
|
||||
};
|
||||
|
||||
|
||||
/// \brief Maps strings to Objects
|
||||
///
|
||||
/// ChaiScript has a built in shortcut for generating Map objects:
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> var m = ["a":1, "b":2];
|
||||
/// [<a,1>, <b,2>]
|
||||
/// eval> m.count("a");
|
||||
/// 1
|
||||
/// eval> m.count("c");
|
||||
/// 0
|
||||
/// eval> m.size();
|
||||
/// 2
|
||||
/// \endcode
|
||||
///
|
||||
/// Implemented as std::map<Boxed_Value>
|
||||
///
|
||||
/// \sa Map_Pair
|
||||
/// \sa chaiscript::bootstrap::standard_library::map_type
|
||||
class Map
|
||||
{
|
||||
public:
|
||||
/// \brief Returns an object that implements the Range concept for the Map_Pair's in this Map
|
||||
Range range();
|
||||
|
||||
/// \brief Returns an object that implements the Const_Range concept for the Map_Pair's in this Map
|
||||
Const_Range range() const;
|
||||
|
||||
/// \brief Returns the number of elements in the Map
|
||||
int size() const;
|
||||
|
||||
/// \brief Returns the item at the given key, creating an undefined Object if the key does not yet exist in the map
|
||||
Object operator[](string);
|
||||
|
||||
/// \brief Clears the map of all items
|
||||
void clear();
|
||||
|
||||
/// \brief Returns the number of items in the Map with the given key. Returns 0 or 1 since this is not an std::multimap.
|
||||
int count(string) const;
|
||||
|
||||
/// \brief Returns true if the map contains no items
|
||||
bool empty() const;
|
||||
|
||||
};
|
||||
|
||||
|
||||
/// \brief A concept implemented by string, Vector and Map. It is convertable to Range, default constructable and back_insertable
|
||||
class Container
|
||||
{
|
||||
public:
|
||||
void push_back(Object);
|
||||
Range range();
|
||||
Const_Range range() const;
|
||||
};
|
||||
|
||||
|
||||
/// \brief Converts o into a string.
|
||||
///
|
||||
/// \code
|
||||
/// eval> to_string(3).is_type("string") <br>
|
||||
/// true<br>
|
||||
/// \endcode
|
||||
string to_string(Object o);
|
||||
|
||||
|
||||
/// \brief Prints o to the terminal, without a trailing carriage return. Applies conversions to string automatically.
|
||||
/// \code
|
||||
/// eval> puts("hi, "); puts("there")
|
||||
/// hi, thereeval>
|
||||
/// \endcode
|
||||
/// \sa to_string
|
||||
/// \sa print
|
||||
void puts(Object o);
|
||||
|
||||
|
||||
/// \brief Prints o to the terminal, with a trailing carriage return. Applies conversions to string automatically
|
||||
/// \code
|
||||
/// eval> print("hello")
|
||||
/// hello
|
||||
/// eval>
|
||||
/// \endcode
|
||||
/// \sa to_string
|
||||
/// \sa puts
|
||||
void print(Object o);
|
||||
|
||||
/// \brief ChaiScript representation of std::string. It is an std::string but only some member are exposed to ChaiScript.
|
||||
///
|
||||
/// Because the ChaiScript string object is an std::string, it is directly convertable to and from std::string
|
||||
/// using the chaiscript::boxed_cast and chaiscript::var functions.
|
||||
///
|
||||
/// With the exception of string::trim, string::rtrim, string::ltrim, all members are direct passthroughs to the
|
||||
/// std::string of the same name.
|
||||
///
|
||||
/// \note Object and function notations are equivalent in ChaiScript. This means that
|
||||
/// \c "bob".find("b") and \c find("bob", "b") are exactly the same. Most examples below follow the
|
||||
/// second formation of the function calls.
|
||||
/// \sa \ref keyworddef for extending existing C++ classes in ChaiScript
|
||||
/// \sa chaiscript::bootstrap::standard_library::string_type
|
||||
class string
|
||||
{
|
||||
public:
|
||||
/// \brief Finds the first instance of substr.
|
||||
/// \code
|
||||
/// eval> find("abab", "ab")
|
||||
/// 0
|
||||
/// \endcode
|
||||
int find(string s) const;
|
||||
|
||||
|
||||
/// \brief Finds the last instance of substr.
|
||||
/// \code
|
||||
/// eval> rfind("abab", "ab")
|
||||
/// 2
|
||||
/// \endcode
|
||||
int rfind(string s) const;
|
||||
|
||||
/// \brief Finds the first of characters in list in the string.
|
||||
///
|
||||
/// \code
|
||||
/// eval> find_first_of("abab", "bec")
|
||||
/// 1
|
||||
/// \endcode
|
||||
int find_first_of(string list) const;
|
||||
|
||||
/// \brief Finds the last of characters in list in the string.
|
||||
///
|
||||
/// \code
|
||||
/// eval> find_last_of("abab", "bec")
|
||||
/// 3
|
||||
/// \endcode
|
||||
int find_last_of(string list) const;
|
||||
|
||||
/// \brief Finds the first non-matching character to list in the str string.
|
||||
///
|
||||
/// \code
|
||||
/// eval> find_first_not_of("abcd", "fec")
|
||||
/// 0
|
||||
/// \endcode
|
||||
int find_first_not_of(string list) const;
|
||||
|
||||
/// \brief Finds the last non-matching character to list in the list string.
|
||||
///
|
||||
/// \code
|
||||
/// eval> find_last_not_of("abcd", "fec")
|
||||
/// 3
|
||||
/// \endcode
|
||||
int find_last_not_of(string list) const;
|
||||
|
||||
/// \brief Removes whitespace from the front of the string, returning a new string
|
||||
///
|
||||
/// \note This function is implemented as a ChaiScript function using the def member function notation.
|
||||
///
|
||||
/// \code
|
||||
/// eval> ltrim(" bob")
|
||||
/// bob
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keyworddef
|
||||
string lstrim() const;
|
||||
|
||||
/// \brief Removes whitespace from the back of the string, returning a new string
|
||||
///
|
||||
/// \note This function is implemented as a ChaiScript function using the def member function notation.
|
||||
///
|
||||
/// \code
|
||||
/// eval> rtrim("bob ") + "|"
|
||||
/// bob|
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keyworddef
|
||||
string rtrim() const;
|
||||
|
||||
/// \brief Removes whitespace from the front and back of the string, returning a new string
|
||||
///
|
||||
/// \note This function is implemented as a ChaiScript function using the def member function notation.
|
||||
///
|
||||
/// \code
|
||||
/// eval> trim(" bob ") + "|"
|
||||
/// bob|
|
||||
/// \endcode
|
||||
///
|
||||
/// Equivalent to rtrim(ltrim(" bob "));
|
||||
///
|
||||
/// \sa \ref keyworddef
|
||||
string trim() const;
|
||||
|
||||
/// \brief Returns the character at the given index in the string, const version
|
||||
const char &operator[](int t_index) const;
|
||||
|
||||
/// \brief Returns the character at the given index in the string
|
||||
char &operator[](int t_index);
|
||||
|
||||
/// \brief Returns underlying const char * for C api compatibility
|
||||
const char *c_str() const;
|
||||
|
||||
/// \brief Returns a pointer to the raw data in the string
|
||||
const char *data() const;
|
||||
|
||||
/// \brief Resets the string to empty
|
||||
void clear();
|
||||
|
||||
/// \brief Returns true if the string is empty
|
||||
bool empty() const;
|
||||
|
||||
/// \brief Returns the size of the string in bytes.
|
||||
///
|
||||
/// This function normally returns size_t in C++. In ChaiScript the return value is cast to int
|
||||
/// for ease of use.
|
||||
int size() const;
|
||||
|
||||
/// \brief Returns an object that implements the Range concept for the characters of this string
|
||||
Range range();
|
||||
|
||||
/// \brief Returns an object that implements the Const_Range concept for the characters of this string
|
||||
Const_Range range() const;
|
||||
};
|
||||
|
||||
/// \brief A concept in ChaiScript that is implemented by \ref string, Vector and Map. It provides
|
||||
/// easy iteration over the elements in a container.
|
||||
///
|
||||
/// Implemented by the template chaiscript::bootstrap::standard_library::Bidir_Range
|
||||
///
|
||||
/// \sa Const_Range
|
||||
class Range
|
||||
{
|
||||
public:
|
||||
/// \brief Returns the last item of the range
|
||||
Object back();
|
||||
|
||||
/// \brief Returns true if the front and back pointers have passed each other, if no items
|
||||
/// are left in the Range
|
||||
bool empty() const;
|
||||
|
||||
/// \brief Returns the first item of the range
|
||||
Object front();
|
||||
|
||||
/// \brief Moves the back pointer back one.
|
||||
///
|
||||
/// \post back() returns the element at back() - 1;
|
||||
void pop_back();
|
||||
|
||||
/// \brief Moves the front pointer forward one
|
||||
///
|
||||
/// \post front() returne the element at front() + 1;
|
||||
void pop_front();
|
||||
|
||||
};
|
||||
|
||||
/// \brief A concept in ChaiScript that is implemented by \ref string, Vector and Map. It provides
|
||||
/// easy iteration over the elements in a container. Contained values are const.
|
||||
///
|
||||
/// Implemented by the template chaiscript::bootstrap::standard_library::Const_Bidir_Range
|
||||
///
|
||||
/// \sa Range
|
||||
class Const_Range
|
||||
{
|
||||
public:
|
||||
/// \brief Returns the last item of the range
|
||||
const Object back();
|
||||
|
||||
/// \brief Returns true if the front and back pointers have passed each other, if no items
|
||||
/// are left in the Range
|
||||
bool empty() const;
|
||||
|
||||
/// \brief Returns the first item of the range
|
||||
const Object front();
|
||||
|
||||
/// \brief Moves the back pointer back one.
|
||||
///
|
||||
/// \post back() returns the element at back() - 1;
|
||||
void pop_back();
|
||||
|
||||
/// \brief Moves the front pointer forward one
|
||||
///
|
||||
/// \post front() returne the element at front() + 1;
|
||||
void pop_front();
|
||||
|
||||
};
|
||||
|
||||
/// \brief A vector of Objects
|
||||
///
|
||||
/// ChaiScript includes a shortcut for creating a Vector of Objects
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> var v = [1,2,3,4]
|
||||
/// [1, 2, 3, 4]
|
||||
/// eval> v[0];
|
||||
/// 1
|
||||
/// eval> v.size();
|
||||
/// 4
|
||||
/// \endcode
|
||||
///
|
||||
/// Implemented with std::vector<chaiscript::Boxed_Value>
|
||||
///
|
||||
/// \sa chaiscript::bootstrap::standard_library::vector_type
|
||||
class Vector
|
||||
{
|
||||
public:
|
||||
/// \brief returns the Object at the given index. Throws an exception if the index does not exist
|
||||
Object operator[](int t_index);
|
||||
|
||||
/// \brief returns a const Object at the given index. Throws an exception if the index does not exist.
|
||||
const Object operator[](int t_index) const;
|
||||
|
||||
/// \brief returns the last item in the Vector
|
||||
Object back();
|
||||
|
||||
/// \brief Clears the Vector of all items
|
||||
void clear();
|
||||
|
||||
/// \brief Returns true if the Vector is contains 0 items
|
||||
bool empty();
|
||||
|
||||
/// \brief Erases the element at the given index
|
||||
void erase_at(int t_index);
|
||||
|
||||
/// \brief Returns the first item in the Vector
|
||||
Object front();
|
||||
|
||||
/// \brief Inserts a new item in the Vector at the given index. The item is not cloned on insert
|
||||
///
|
||||
/// \sa insert_ref
|
||||
void insert_ref_at(int, Object);
|
||||
|
||||
/// \brief Inserts a new item in the Vector at the given index. The item is cloned on insert
|
||||
///
|
||||
/// \sa insert_ref
|
||||
void insert_at(int, Object);
|
||||
|
||||
/// \brief Removes the last item from the Vector
|
||||
void pop_back();
|
||||
|
||||
/// \brief Adds an item to the end of the Vector. The item is not cloned.
|
||||
///
|
||||
/// \sa push_back
|
||||
void push_back_ref(Object);
|
||||
|
||||
/// \brief Adds an item to the end of the Vector. The item is cloned.
|
||||
///
|
||||
/// \sa push_back_ref
|
||||
void push_back(Object);
|
||||
|
||||
/// \brief Returns a Range object for the entire vector
|
||||
Range range();
|
||||
|
||||
/// \brief Returns a Const_Range object for the entire vector
|
||||
Const_Range range() const;
|
||||
|
||||
/// \brief Returns the number of elements in the Vector
|
||||
int size() const;
|
||||
|
||||
};
|
||||
|
||||
class Type_Info
|
||||
{
|
||||
public:
|
||||
/// \brief Compares this Type_Info object with another one and returns true if the two types are the same
|
||||
/// after const, pointer, reference are removed.
|
||||
bool bare_equal(Type_Info t_ti) const;
|
||||
|
||||
/// \brief Returns the mangled C++ name for the type given by the compiler after const, pointer, reference is removed.
|
||||
string cpp_bare_name() const;
|
||||
|
||||
/// \brief Returns the mangled C++ name for the type given by the compiler.
|
||||
string cpp_name() const;
|
||||
|
||||
/// \brief Returns true if the type is const
|
||||
bool is_type_const() const;
|
||||
|
||||
/// \brief Returns true if the type is a pointer
|
||||
bool is_type_pointer() const;
|
||||
|
||||
/// \brief Returns true if the type is a reference
|
||||
bool is_type_reference() const;
|
||||
|
||||
/// \brief Returns true if the type is undefined
|
||||
bool is_type_undef() const;
|
||||
|
||||
/// \brief Returns true if the type is "void"
|
||||
bool is_type_void() const;
|
||||
|
||||
/// \brief Returns the ChaiScript registered name for the type if one exists.
|
||||
string name() const;
|
||||
|
||||
};
|
||||
|
||||
|
||||
/// \brief Represents a function object in ChaiScript
|
||||
///
|
||||
/// A function object may be one function, such as:
|
||||
/// \code
|
||||
/// var f = fun(x) { return x; }
|
||||
/// \endcode
|
||||
///
|
||||
/// Or it may represent multiple functions
|
||||
/// \code
|
||||
/// var f2 = `-`; // represents the unary - as well as the set of binary - operators
|
||||
/// \endcode
|
||||
///
|
||||
/// Guarded function example
|
||||
/// \code
|
||||
/// def f3(x) : x > 2 {
|
||||
/// return x;
|
||||
/// }
|
||||
/// \endcode
|
||||
///
|
||||
/// Examples in the function definitions below will reference these examples
|
||||
class Function
|
||||
{
|
||||
public:
|
||||
/// \brief Returns the annotation description of the function
|
||||
string get_annotation() const;
|
||||
|
||||
/// \brief Returns the arity of the function, -1 if the function takes a variable number of parameters
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> f.get_arity()
|
||||
/// 1
|
||||
/// eval> f2.get_arity()
|
||||
/// -1
|
||||
/// \endcode
|
||||
int get_arity() const;
|
||||
|
||||
/// \brief Returns a vector of the contained functions
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> f.get_contained_functions().size()
|
||||
/// 0
|
||||
/// eval> f2.get_contained_functions().size()
|
||||
/// 11
|
||||
/// eval> var v = f2.get_contained_functions();
|
||||
/// v[0].get_arity()
|
||||
/// 2
|
||||
/// \endcode
|
||||
Vector get_contained_functions() const;
|
||||
|
||||
/// \brief Returns a vector of the contained functions
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> f.get_guard() // Throws exception
|
||||
/// Function does not have a guard
|
||||
/// eval> f3.get_guard().get_arity()
|
||||
/// 1
|
||||
/// \endcode
|
||||
Function get_guard() const;
|
||||
|
||||
/// \brief Returns a vector of Type_Info objects that represent the param types for this function.
|
||||
/// The first value in the list is the return type.
|
||||
///
|
||||
/// If this function is a conglomeration of several functions (get_contained_values().size() > 0)
|
||||
/// then the function returns as many Type_Info objects as it can. If the functions contained all have
|
||||
/// the same arity, then it represents the arity. If they have different arities, it returns only
|
||||
/// one value - the return type.
|
||||
///
|
||||
/// For each parameter that is the same type, the type is returned. If the types are different
|
||||
/// then a Type_Info for Object is returned.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> f2.get_param_types().size(); // Returns a Type_Info for Object for the return type
|
||||
/// 1
|
||||
/// \endcode
|
||||
Vector get_param_types() const;
|
||||
|
||||
/// \brief Returns true if the function has a guard to it. Always returns falls for a conglomerate function
|
||||
bool has_guard() const;
|
||||
|
||||
/// \brief Calls the function with the given set of parameters and returns the value;
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> `-`.call([2,1]);
|
||||
/// 1
|
||||
/// \endcode
|
||||
Object call(Vector t_params) const;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// \brief Returns the max of a or b. Requires that operator>(a, b) exists
|
||||
/// Equivalent to
|
||||
/// \code
|
||||
/// return a>b?a:b;
|
||||
/// \endcode
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> max(4, 10)
|
||||
/// 10
|
||||
/// \endcode
|
||||
Object max(Object a, Object b);
|
||||
|
||||
/// \brief Returns the min of a or b. Requires that operator<(a, b) exists
|
||||
///
|
||||
/// Equivalent to
|
||||
/// \code
|
||||
/// return a<b?a:b;
|
||||
/// \endcode
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> min(4, 10)
|
||||
/// 4
|
||||
/// \endcode
|
||||
Object min(Object a, Object b);
|
||||
|
||||
/// \brief Returns true if x is an even integer.
|
||||
///
|
||||
/// Will also work on any non-integer type for which an operator%(x, int) exists
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> even(4)
|
||||
/// true
|
||||
/// \endcode
|
||||
bool even(Object x);
|
||||
|
||||
/// \brief Returns true if x is an odd integer.
|
||||
///
|
||||
/// Will also work on any non-integer type for which an operator%(x, int) exists
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> odd(4)
|
||||
/// false
|
||||
/// \endcode
|
||||
bool even(Object x);
|
||||
|
||||
|
||||
/// \brief Applies the function f over each element in the Range c.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> for_each([1, 2, 3], print)
|
||||
/// 1
|
||||
/// 2
|
||||
/// 3
|
||||
/// \endcode
|
||||
void for_each(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Applies f over each element in the Range c, joining all the results.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> map([1, 2, 3], odd)
|
||||
/// [true, false, true]
|
||||
/// \endcode
|
||||
Object map(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Starts with the initial value and applies the function f to it and the first element of the Range c.
|
||||
/// The result is then applied to the second element, and so on until the elements are exhausted.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> foldl([1, 2, 3, 4], `+`, 0)
|
||||
/// 10
|
||||
/// \endcode
|
||||
Object foldl(Range c, Function f, Object initial);
|
||||
|
||||
|
||||
/// \brief Returns the sum total of the values in the Range c.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> sum([1, 2, 3, 4])
|
||||
/// 10
|
||||
/// \endcode
|
||||
///
|
||||
/// Equivalent to:
|
||||
/// \code
|
||||
/// foldl(c, `+`, 0.0);
|
||||
/// \endcode
|
||||
Numeric sum(Range c);
|
||||
|
||||
|
||||
/// \brief Returns the product of the value in the Range c.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> product([1, 2, 3, 4])
|
||||
/// 24
|
||||
/// \endcode
|
||||
///
|
||||
/// Equivalent to:
|
||||
/// \code
|
||||
/// foldl(c, `*`, 1.0);
|
||||
/// \endcode
|
||||
Numeric product(Range c);
|
||||
|
||||
|
||||
/// \brief Takes num elements from the Range c, returning them.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> take([1, 2, 3, 4], 2)
|
||||
/// [1, 2]
|
||||
/// \endcode
|
||||
///
|
||||
/// \returns A container of the same type that was passed in
|
||||
Object take(Range c, int num);
|
||||
|
||||
|
||||
/// \brief Takes elements from the Range c that match function f, stopping at the first non-match, returning them as a new Vector.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> take_while([1, 2, 3], odd)
|
||||
/// [1]
|
||||
/// \endcode
|
||||
///
|
||||
/// \returns A container of the same type that was passed in
|
||||
Object take_while(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Drops num elements from the Range c, returning the remainder.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> drop([1, 2, 3, 4], 2)
|
||||
/// [3, 4]
|
||||
/// \endcode
|
||||
///
|
||||
/// \returns A container of the same type that was passed in
|
||||
Object drop(Range c, int num);
|
||||
|
||||
|
||||
/// \brief Drops elements from the Range c that match f, stopping at the first non-match, returning the remainder.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> drop_while([1, 2, 3], odd)
|
||||
/// [2, 3]
|
||||
/// \endcode
|
||||
Object drop_while(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Similar to foldl, this takes the first two elements as its starting values for f. This assumes Range c has at least 2 elements.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> reduce([1, 2, 3, 4], `+`)
|
||||
/// 10
|
||||
/// \endcode
|
||||
Object reduce(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Takes elements from Range c that match function f, return them.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> filter([1, 2, 3, 4], odd)
|
||||
/// [1, 3]
|
||||
/// \endcode
|
||||
Object filter(Range c, Function f);
|
||||
|
||||
|
||||
/// \brief Joins the elements of the Range c into a string, delimiting each with the delim string.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> join([1, 2, 3], "*")
|
||||
/// 1*2*3
|
||||
/// \endcode
|
||||
string join(Range c, string delim);
|
||||
|
||||
|
||||
/// \brief Returns the contents of the Container c in reversed order.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> reverse([1, 2, 3, 4, 5, 6, 7])
|
||||
/// [7, 6, 5, 4, 3, 2, 1]
|
||||
/// \endcode
|
||||
Container reverse(Container c);
|
||||
|
||||
|
||||
/// \brief Generates a new Vector filled with values starting at x and ending with y.
|
||||
///
|
||||
/// Works on types supporting operator<=(x, y) and operator++(x)
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> generate_range(1, 10)
|
||||
/// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
/// \endcode
|
||||
Vector generate_range(Object x, Object y);
|
||||
|
||||
|
||||
/// \brief Returns a new Range with x and y concatenated.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> concat([1, 2, 3], [4, 5, 6])
|
||||
/// [1, 2, 3, 4, 5, 6]
|
||||
/// \endcode
|
||||
Object concat(Range x, Range y);
|
||||
|
||||
|
||||
/// \brief Returns a new Vector with x and y as its values.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> collate(1, 2)
|
||||
/// [1, 2]
|
||||
/// \endcode
|
||||
Vector collate(Object x, Object y);
|
||||
|
||||
|
||||
/// \brief Applies f to elements of x and y, returning a new Vector with the result of each application.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> zip_with(`+`, [1, 2, 3], [4, 5, 6])
|
||||
/// [5, 7, 9]
|
||||
/// \endcode
|
||||
Vector zip_with(Function f, Range x, Range y);
|
||||
|
||||
|
||||
/// \brief Collates elements of x and y, returning a new Vector with the result.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> zip([1, 2, 3], [4, 5, 6])
|
||||
/// [[1, 4], [2, 5], [3, 6]]
|
||||
/// \endcode
|
||||
Vector zip(Range x, Range y);
|
||||
|
||||
|
||||
/// \brief returns true if there exists a call to the Function f that takes the given parameters
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> call_exists(`+`, 1, 2)
|
||||
/// true
|
||||
/// \endcode
|
||||
bool call_exists(Function f, ...);
|
||||
|
||||
/// \brief Reverses a Range object so that the elements are accessed in reverse
|
||||
Range retro(Range);
|
||||
|
||||
/// \brief Reverses a Const_Range object so that the elements are accessed in reverse
|
||||
Const_Range retro(Const_Range);
|
||||
|
||||
|
||||
/// \brief Raises the given object as an exception. Any type of object can be thrown.
|
||||
///
|
||||
/// Example:
|
||||
/// \code
|
||||
/// eval> try { throw(1); } catch (e) { print("Exception caught: " + to_string(e)); }
|
||||
/// Exception caught: 1
|
||||
/// \endcode
|
||||
///
|
||||
/// \sa \ref keywordtry
|
||||
void throw(Object);
|
||||
}
|
||||
|
89
include/chaiscript/utility/utility.hpp
Normal file
89
include/chaiscript/utility/utility.hpp
Normal file
@@ -0,0 +1,89 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2011, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#ifndef CHAISCRIPT_UTILITY_UTILITY_HPP_
|
||||
#define CHAISCRIPT_UTILITY_UTILITY_HPP_
|
||||
|
||||
#include "../chaiscript.hpp"
|
||||
#include <boost/preprocessor.hpp>
|
||||
#include <string>
|
||||
|
||||
#define CHAISCRIPT_MODULE(_info) BOOST_PP_SEQ_ELEM(0, _info)
|
||||
|
||||
#define CHAISCRIPT_CLASS_ELEM(_info) BOOST_PP_SEQ_ELEM(1, _info)
|
||||
|
||||
#define CHAISCRIPT_METHOD(_info, _method) & CHAISCRIPT_CLASS_ELEM(_info) :: BOOST_PP_SEQ_ELEM(0, _method)
|
||||
|
||||
#define CHAISCRIPT_METHOD_NAME(_info, _method) \
|
||||
BOOST_PP_SEQ_ELEM(3, _info) (BOOST_PP_STRINGIZE(BOOST_PP_SEQ_ELEM(0, _method ) ) )
|
||||
|
||||
#define CHAISCRIPT_CLASS_NAME(_info) \
|
||||
BOOST_PP_SEQ_ELEM(2, _info) (BOOST_PP_STRINGIZE(CHAISCRIPT_CLASS_ELEM(_info) ) )
|
||||
|
||||
#define CHAISCRIPT_METHOD_SIGNATURE_PART(_r, _info, _i, _method_part) \
|
||||
BOOST_PP_EXPR_IF(BOOST_PP_EQUAL(_i, 1), < _method_part > )
|
||||
|
||||
#define CHAISCRIPT_METHOD_SIGNATURE(_info, _method) \
|
||||
BOOST_PP_SEQ_FOR_EACH_I(CHAISCRIPT_METHOD_SIGNATURE_PART, _info, _method)
|
||||
|
||||
#define CHAISCRIPT_CLASS_CONSTRUCTOR(_r, _info, _constructor) \
|
||||
CHAISCRIPT_MODULE(_info) ->add BOOST_PP_LPAREN() chaiscript::constructor<_constructor>() BOOST_PP_COMMA() CHAISCRIPT_CLASS_NAME(_info) BOOST_PP_RPAREN() ;
|
||||
|
||||
#define CHAISCRIPT_CLASS_METHOD(_r, _info, _method) \
|
||||
CHAISCRIPT_MODULE(_info) ->add BOOST_PP_LPAREN() chaiscript::fun CHAISCRIPT_METHOD_SIGNATURE(_info, _method) \
|
||||
BOOST_PP_LPAREN() CHAISCRIPT_METHOD(_info, _method) BOOST_PP_RPAREN() BOOST_PP_COMMA() CHAISCRIPT_METHOD_NAME(_info, _method)BOOST_PP_RPAREN() ;
|
||||
|
||||
#define CHAISCRIPT_CLASS_CONSTRUCTORS(_info, _constructors) \
|
||||
BOOST_PP_SEQ_FOR_EACH(CHAISCRIPT_CLASS_CONSTRUCTOR, _info, _constructors)
|
||||
|
||||
#define CHAISCRIPT_CLASS_METHODS(_info, _methods) \
|
||||
BOOST_PP_SEQ_FOR_EACH(CHAISCRIPT_CLASS_METHOD, _info, _methods)
|
||||
|
||||
#define CHAISCRIPT_CLASS_EX(_module, _class_name, _class_name_translator, _method_name_translator, _constructors, _methods) \
|
||||
{ \
|
||||
_module->add(chaiscript::user_type<_class_name>(), _class_name_translator (BOOST_PP_STRINGIZE(_class_name))); \
|
||||
CHAISCRIPT_CLASS_CONSTRUCTORS((_module)(_class_name)(_class_name_translator), _constructors) \
|
||||
CHAISCRIPT_CLASS_METHODS((_module)(_class_name)(_class_name_translator)(_method_name_translator), _methods) \
|
||||
}
|
||||
|
||||
#define CHAISCRIPT_CLASS(_module, _class_name, _constructors, _methods) \
|
||||
CHAISCRIPT_CLASS_EX(_module, _class_name, chaiscript::utility::class_name_translator, \
|
||||
chaiscript::utility::method_name_translator, _constructors, _methods)
|
||||
|
||||
namespace chaiscript
|
||||
{
|
||||
/// \brief Classes and functions which provide general utility to the end user.
|
||||
namespace utility
|
||||
{
|
||||
inline std::string class_name_translator(const std::string &t_name)
|
||||
{
|
||||
size_t colon = t_name.rfind("::");
|
||||
if (colon != std::string::npos)
|
||||
{
|
||||
return t_name.substr(colon+2, std::string::npos);
|
||||
} else {
|
||||
return t_name;
|
||||
}
|
||||
}
|
||||
|
||||
inline std::string method_name_translator(const std::string &t_name)
|
||||
{
|
||||
size_t namestart = t_name.rfind("operator");
|
||||
namestart = (namestart == std::string::npos)?0:namestart+strlen("operator");
|
||||
|
||||
if (namestart == 0)
|
||||
{
|
||||
namestart = t_name.rfind("::");
|
||||
namestart = (namestart == std::string::npos)?0:namestart+strlen("::");
|
||||
}
|
||||
|
||||
return t_name.substr(namestart, std::string::npos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
@@ -1,4 +1,4 @@
|
||||
Copyright 2009 Jason and Jonathan Turner. All Rights Reserved.
|
||||
Copyright 2009-2010 Jason Turner and Jonathan Turner. All Rights Reserved.
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
@@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="Windows-1252"?>
|
||||
<VisualStudioPropertySheet
|
||||
ProjectType="Visual C++"
|
||||
Version="8.00"
|
||||
Name="Boost"
|
||||
>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
AdditionalIncludeDirectories=""C:\Programming\Boost\include\boost-1_38""
|
||||
/>
|
||||
</VisualStudioPropertySheet>
|
@@ -1,20 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 10.00
|
||||
# Visual C++ Express 2008
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "chaiscript", "chaiscript.vcproj", "{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
Release|Win32 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}.Release|Win32.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
@@ -1,258 +0,0 @@
|
||||
<?xml version="1.0" encoding="Windows-1252"?>
|
||||
<VisualStudioProject
|
||||
ProjectType="Visual C++"
|
||||
Version="9.00"
|
||||
Name="chaiscript"
|
||||
ProjectGUID="{46FD9DC7-2DA9-4C17-ADE4-E3A18C46E87B}"
|
||||
RootNamespace="chaiscript"
|
||||
Keyword="Win32Proj"
|
||||
TargetFrameworkVersion="196613"
|
||||
>
|
||||
<Platforms>
|
||||
<Platform
|
||||
Name="Win32"
|
||||
/>
|
||||
</Platforms>
|
||||
<ToolFiles>
|
||||
</ToolFiles>
|
||||
<Configurations>
|
||||
<Configuration
|
||||
Name="Debug|Win32"
|
||||
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
|
||||
IntermediateDirectory="$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
InheritedPropertySheets=".\Boost.vsprops"
|
||||
UseOfMFC="2"
|
||||
CharacterSet="0"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
UseUnicodeResponseFiles="false"
|
||||
Optimization="0"
|
||||
AdditionalIncludeDirectories=""$(ProjectDir)\..\..\include""
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
|
||||
MinimalRebuild="true"
|
||||
BasicRuntimeChecks="3"
|
||||
RuntimeLibrary="3"
|
||||
DisableLanguageExtensions="true"
|
||||
TreatWChar_tAsBuiltInType="false"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="4"
|
||||
DebugInformationFormat="4"
|
||||
CompileAs="2"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="2"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="1"
|
||||
TargetMachine="1"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Release|Win32"
|
||||
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
|
||||
IntermediateDirectory="$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
InheritedPropertySheets=".\Boost.vsprops"
|
||||
CharacterSet="0"
|
||||
WholeProgramOptimization="1"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="3"
|
||||
EnableIntrinsicFunctions="true"
|
||||
AdditionalIncludeDirectories=""$(ProjectDir)\..\..\dispatchkit";"$(ProjectDir)\..\..\chaiscript""
|
||||
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
|
||||
RuntimeLibrary="2"
|
||||
EnableFunctionLevelLinking="true"
|
||||
UsePrecompiledHeader="0"
|
||||
WarningLevel="4"
|
||||
DebugInformationFormat="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="1"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="1"
|
||||
OptimizeReferences="2"
|
||||
EnableCOMDATFolding="2"
|
||||
TargetMachine="1"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
</Configurations>
|
||||
<References>
|
||||
</References>
|
||||
<Files>
|
||||
<Filter
|
||||
Name="Source Files"
|
||||
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
|
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
|
||||
>
|
||||
<File
|
||||
RelativePath="..\..\src\main.cpp"
|
||||
>
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Header Files"
|
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd"
|
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
|
||||
>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\bootstrap.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\bootstrap_stl.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\boxed_value.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\chaiscript.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\language\chaiscript_engine.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\language\chaiscript_eval.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\language\chaiscript_parser.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\language\chaiscript_prelude.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\dispatchkit.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\function_call.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\proxy_constructors.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\proxy_functions.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\register_function.hpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath="..\..\include\chaiscript\dispatchkit\type_info.hpp"
|
||||
>
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Resource Files"
|
||||
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
|
||||
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
|
||||
>
|
||||
</Filter>
|
||||
</Files>
|
||||
<Globals>
|
||||
</Globals>
|
||||
</VisualStudioProject>
|
33
readme.txt
33
readme.txt
@@ -1,11 +1,11 @@
|
||||
ChaiScript v1.0
|
||||
ChaiScript v2.3.3
|
||||
http://www.chaiscript.com
|
||||
(c) 2009 Jason Turner and Jonathan Turner
|
||||
(c) 2009-2010 Jason Turner and Jonathan Turner
|
||||
Release under the BSD license, see "license.txt" for details.
|
||||
|
||||
[Introduction]
|
||||
|
||||
ChaiScript is one of the first (and perhaps only) embedded scripting language designed from the ground up to directly target C++. Being a native C++ application, it has some advantages over existing embedded scripting languages:
|
||||
ChaiScript is 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 like he expects 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.
|
||||
@@ -19,13 +19,13 @@ ChaiScript requires a recent version of Boost (http://www.boost.org) to build.
|
||||
|
||||
* 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_Engine chai"
|
||||
* Instantiate the ChaiScript engine in your application. For example, create a new engine with the name 'chai' like so: "chaiscript::ChaiScript chai"
|
||||
|
||||
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.evaluate_string(string)" and a file at a time using "chai.evaluate_file(fname)"
|
||||
|
||||
To make functions in your C++ code visible to scripts, they must be registered with the scripting engine. To do so, call register_function:
|
||||
To make functions in your C++ code visible to scripts, they must be registered with the scripting engine. To do so, call add:
|
||||
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &my_function, "my_function_name");
|
||||
chai.add(&my_function, "my_function_name");
|
||||
|
||||
Once registered the function will be visible to scripts as "my_function_name"
|
||||
|
||||
@@ -33,4 +33,23 @@ Once registered the function will be visible to scripts as "my_function_name"
|
||||
|
||||
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 example of how to register parts of your C++ application, see "example.cpp" in the "src" directory.
|
||||
For examples of how to register parts of your C++ application, see "example.cpp" in the "src" 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(&function, "function");
|
||||
|
||||
double d = chai.eval<double>("function(3, 4.75);");
|
||||
}
|
||||
|
26
releasenotes.txt
Normal file
26
releasenotes.txt
Normal file
@@ -0,0 +1,26 @@
|
||||
Changes since 2.3.3
|
||||
|
||||
* Code simplifications
|
||||
* Fully integrate documentation with source code in doxygen style comments
|
||||
* Unit tests increased from 114 to 137
|
||||
* Automatic conversion between boost::function objects and ChaiScript functions
|
||||
* Many bug fixes
|
||||
* Minor performance improvements
|
||||
* Namespace reorganization to make end user code more accessible
|
||||
* clang support
|
||||
* VisualStudio 2010 Support
|
||||
* Support for C++ base classes and automatic upcasting
|
||||
* Remove __ reserved identifiers
|
||||
* Better code organization to reduce #ifdefs
|
||||
* clanmills: command line options for chai eval
|
||||
* clanmills: parser cleanups and code reduction
|
||||
* Function introspection and reflection
|
||||
* Correct function dispatch order to account for base classes and provide a defined order of dispatch
|
||||
* Predictable object lifetime that emulates C++ stack lifetime
|
||||
* emarcotte: pkgconfig support
|
||||
* standardize on method/member naming and indentation
|
||||
* 64bit Visual Studio support
|
||||
* Better support for const objects
|
||||
* Drastic reduction of runtime exceptions - making debug builds orders of magnitude faster
|
||||
* Support for platforms with no loadable module support
|
||||
* Add helper macro for registering class
|
@@ -1,25 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
successes=0
|
||||
failures=0
|
||||
|
||||
echo -n "Running unit tests"
|
||||
for file in unittests/*.chai
|
||||
do
|
||||
tstname=${file%.*}
|
||||
tst="$tstname.txt"
|
||||
./chaiscript_eval $file > /tmp/tstout.txt
|
||||
diff $tst /tmp/tstout.txt
|
||||
if [ "$?" -eq "0" ]
|
||||
then
|
||||
echo -n "."
|
||||
successes=$((successes+1))
|
||||
else
|
||||
echo "[from failed test $file]"
|
||||
failures=$((failures+1))
|
||||
fi
|
||||
done
|
||||
echo ""
|
||||
|
||||
total=$((successes+failures))
|
||||
echo "$successes out of $total succeeded"
|
@@ -1,22 +0,0 @@
|
||||
|
||||
def add(x, y)
|
||||
{
|
||||
return x + y;
|
||||
}
|
||||
|
||||
var b = bind(add, 2, _);
|
||||
var c = bind(b, 3);
|
||||
|
||||
print(b(4));
|
||||
print(c());
|
||||
|
||||
|
||||
def concat(a,b,c,d)
|
||||
{
|
||||
return to_string(a) + to_string(b) + to_string(c) + to_string(d);
|
||||
}
|
||||
|
||||
var d = bind(concat, _, " Hello ", _, " World ");
|
||||
print(d(1, 3));
|
||||
//This checks to make sure arity is handled correctly:
|
||||
//print(d(1, 3, 4));
|
@@ -1,3 +1,2 @@
|
||||
var i = 1
|
||||
var j = eval("5 + 4")
|
||||
print(j)
|
||||
|
175
samples/example.cpp
Normal file
175
samples/example.cpp
Normal file
@@ -0,0 +1,175 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <chaiscript/dispatchkit/function_call.hpp>
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/regex.hpp>
|
||||
|
||||
void log(const std::string &msg)
|
||||
{
|
||||
std::cout << "[" << boost::posix_time::microsec_clock::local_time() << "] " << msg << std::endl;
|
||||
}
|
||||
|
||||
void log(const std::string &module, const std::string &msg)
|
||||
{
|
||||
std::cout << "[" << boost::posix_time::microsec_clock::local_time() << "] <" << module << "> " << msg << std::endl;
|
||||
}
|
||||
|
||||
void bound_log(const std::string &msg)
|
||||
{
|
||||
log(msg);
|
||||
}
|
||||
|
||||
void hello_world(const chaiscript::Boxed_Value & /*o*/)
|
||||
{
|
||||
std::cout << "Hello World" << std::endl;
|
||||
}
|
||||
|
||||
void hello_constructor(const chaiscript::Boxed_Value & /*o*/)
|
||||
{
|
||||
std::cout << "Hello Constructor" << std::endl;
|
||||
}
|
||||
|
||||
|
||||
struct System
|
||||
{
|
||||
std::map<std::string, boost::function<std::string (const std::string &) > > m_callbacks;
|
||||
|
||||
void add_callback(const std::string &t_name,
|
||||
const chaiscript::Proxy_Function &t_func)
|
||||
{
|
||||
m_callbacks[t_name] = chaiscript::dispatch::functor<std::string (const std::string &)>(t_func);
|
||||
}
|
||||
|
||||
|
||||
void do_callbacks(const std::string &inp)
|
||||
{
|
||||
log("Running Callbacks: " + inp);
|
||||
for (std::map<std::string, boost::function<std::string (const std::string &)> >::iterator itr = m_callbacks.begin();
|
||||
itr != m_callbacks.end();
|
||||
++itr)
|
||||
{
|
||||
log("Callback: " + itr->first, itr->second(inp));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void take_shared_ptr(const boost::shared_ptr<const std::string> &p)
|
||||
{
|
||||
std::cout << *p << std::endl;
|
||||
}
|
||||
|
||||
int main(int /*argc*/, char * /*argv*/[]) {
|
||||
using namespace chaiscript;
|
||||
|
||||
ChaiScript chai;
|
||||
|
||||
//Create a new system object and share it with the chaiscript engine
|
||||
System system;
|
||||
chai.add(var(&system), "system");
|
||||
|
||||
//Add a bound callback method
|
||||
chai.add(fun(&System::add_callback, system), "add_callback_bound");
|
||||
|
||||
//Register the two methods of the System structure.
|
||||
chai.add(fun(&System::add_callback), "add_callback");
|
||||
chai.add(fun(&System::do_callbacks), "do_callbacks");
|
||||
|
||||
chai.add(fun(&take_shared_ptr), "take_shared_ptr");
|
||||
|
||||
// Let's use chaiscript to add a new lambda callback to our system.
|
||||
// The function "{ 'Callback1' + x }" is created in chaiscript and passed into our C++ application
|
||||
// in the "add_callback" function of struct System the chaiscript function is converted into a
|
||||
// boost::function, so it can be handled and called easily and type-safely
|
||||
chai.eval("system.add_callback(\"#1\", fun(x) { \"Callback1 \" + x });");
|
||||
|
||||
// Because we are sharing the "system" object with the chaiscript engine we have equal
|
||||
// access to it both from within chaiscript and from C++ code
|
||||
system.do_callbacks("TestString");
|
||||
chai.eval("system.do_callbacks(\"TestString\");");
|
||||
|
||||
// The log function is overloaded, therefore we have to give the C++ compiler a hint as to which
|
||||
// version we want to register. One way to do this is to create a typedef of the function pointer
|
||||
// then cast your function to that typedef.
|
||||
typedef void (*PlainLog)(const std::string &);
|
||||
typedef void (*ModuleLog)(const std::string &, const std::string &);
|
||||
chai.add(fun(PlainLog(&log)), "log");
|
||||
chai.add(fun(ModuleLog(&log)), "log");
|
||||
|
||||
chai.eval("log(\"Test Message\")");
|
||||
|
||||
// A shortcut to using eval is just to use the chai operator()
|
||||
chai("log(\"Test Module\", \"Test Message\");");
|
||||
|
||||
//Finally, it is possible to register any boost::function as a system function, in this
|
||||
//way, we can, for instance add a bound member function to the system
|
||||
chai.add(fun(&System::do_callbacks, boost::ref(system), std::string("Bound Test")), "do_callbacks");
|
||||
|
||||
//Call bound version of do_callbacks
|
||||
chai("do_callbacks()");
|
||||
|
||||
boost::function<void ()> caller = chai.eval<boost::function<void ()> >("fun() { system.do_callbacks(\"From Functor\"); }");
|
||||
caller();
|
||||
|
||||
|
||||
//If we would like a type-safe return value from all call, we can use
|
||||
//the templated version of eval:
|
||||
int i = chai.eval<int>("5+5");
|
||||
|
||||
std::cout << "5+5: " << i << std::endl;
|
||||
|
||||
//Add a new variable
|
||||
chai("var scripti = 15");
|
||||
|
||||
//We can even get a handle to the variables in the system
|
||||
int &scripti = chai.eval<int &>("scripti");
|
||||
|
||||
std::cout << "scripti: " << scripti << std::endl;
|
||||
scripti *= 2;
|
||||
std::cout << "scripti (updated): " << scripti << std::endl;
|
||||
chai("print(\"Scripti from chai: \" + to_string(scripti))");
|
||||
|
||||
//To do: Add examples of handling Boxed_Values directly when needed
|
||||
|
||||
//Creating a functor on the stack and using it immediatly
|
||||
int x = chai.eval<boost::function<int (int, int)> >("fun (x, y) { return x + y; }")(5, 6);
|
||||
|
||||
log("Functor test output", boost::lexical_cast<std::string>(x));
|
||||
|
||||
chai.add(var(boost::shared_ptr<int>()), "nullvar");
|
||||
chai("print(\"This should be true.\"); print(nullvar.is_var_null())");
|
||||
|
||||
// test the global const action
|
||||
chai.add_global_const(const_var(1), "constvar");
|
||||
chai("def getvar() { return constvar; }");
|
||||
chai("print( getvar() )");
|
||||
|
||||
|
||||
//Ability to create our own container types when needed. std::vector and std::map are
|
||||
//mostly supported currently
|
||||
chai.add(bootstrap::standard_library::vector_type<std::vector<int> >("IntVector"));
|
||||
|
||||
|
||||
// Test ability to register a function that excepts a shared_ptr version of a type
|
||||
chai("take_shared_ptr(\"Hello World as a shared_ptr\");");
|
||||
|
||||
chai.add(fun(&bound_log, std::string("Msg")), "BoundFun");
|
||||
|
||||
//Dynamic objects test
|
||||
chai.add(chaiscript::Proxy_Function(new dispatch::detail::Dynamic_Object_Function("TestType", fun(&hello_world))), "hello_world");
|
||||
chai.add(chaiscript::Proxy_Function(new dispatch::detail::Dynamic_Object_Constructor("TestType", fun(&hello_constructor))), "TestType");
|
||||
chai.add(fun(boost::function<Boxed_Value (dispatch::Dynamic_Object &)>(boost::bind(&dispatch::detail::Dynamic_Object_Attribute::func, "TestType", "attr", _1))), "attr");
|
||||
|
||||
chai.eval("var x = TestType()");
|
||||
// chai.eval("x.attr = \"hi\"");
|
||||
// chai.eval("print(x.attr)");
|
||||
chai.eval("x.hello_world()");
|
||||
}
|
||||
|
@@ -2,11 +2,11 @@ for (var i = 0; i < 10; ++i) {
|
||||
print(i)
|
||||
}
|
||||
|
||||
for (i = 10; i >= 0; i -= 2) {
|
||||
for (var i = 10; i >= 0; i -= 2) {
|
||||
print(i)
|
||||
}
|
||||
|
||||
i = 0
|
||||
var i = 0
|
||||
|
||||
for (; i < 5; ++i) {
|
||||
print(i)
|
||||
|
@@ -2,7 +2,7 @@ var i = 0
|
||||
if (i == 0) {
|
||||
print("i is 0")
|
||||
}
|
||||
elseif (i == 1) {
|
||||
else if (i == 1) {
|
||||
print("i is 1")
|
||||
}
|
||||
else {
|
||||
|
88
samples/memory_leak_test.cpp
Normal file
88
samples/memory_leak_test.cpp
Normal file
@@ -0,0 +1,88 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "chaiscript/chaiscript.hpp"
|
||||
#ifdef READLINE_AVAILABLE
|
||||
#include <readline/readline.h>
|
||||
#include <readline/history.h>
|
||||
#endif
|
||||
|
||||
|
||||
using namespace chaiscript;
|
||||
|
||||
std::string get_next_command() {
|
||||
#ifdef READLINE_AVAILABLE
|
||||
char *input_raw;
|
||||
input_raw = readline("eval> ");
|
||||
add_history(input_raw);
|
||||
return std::string(input_raw);
|
||||
#else
|
||||
std::string retval;
|
||||
std::cout << "eval> ";
|
||||
std::getline(std::cin, retval);
|
||||
return retval;
|
||||
#endif
|
||||
}
|
||||
|
||||
void fuction(void)
|
||||
{
|
||||
// do nothing
|
||||
}
|
||||
|
||||
class test
|
||||
{
|
||||
ChaiScript chai;
|
||||
ChaiScript::State backupState;
|
||||
public:
|
||||
test()
|
||||
{
|
||||
backupState = chai.get_state();
|
||||
}
|
||||
~test(){}
|
||||
|
||||
void ResetState()
|
||||
{
|
||||
chai.set_state(backupState);
|
||||
chai.add(fun(&fuction),"Whatever()");
|
||||
}
|
||||
|
||||
void RunFile(std::string sFile)
|
||||
{
|
||||
try {
|
||||
chaiscript::Boxed_Value val = chai.eval_file(sFile);
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cout << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
int main(int /*argc*/, char * /*argv*/[]) {
|
||||
|
||||
test myChai;
|
||||
|
||||
|
||||
std::string command = "";
|
||||
|
||||
//
|
||||
// this loop increases memoryusage, if RunFile is not called (just hittin enter)
|
||||
// as soon RunFile gets called, memory will be freed.
|
||||
//
|
||||
// scenario1 - RunFile gets called every Loop: memoryusage does not change
|
||||
// scenario2 - RunFile gets never called (just hitting enter): memoryusage increases every loop
|
||||
// scenario3 - RunFile gets in changing intervals: memoryusage goes up and down, but never as
|
||||
// low as in case 1 scenario3 :
|
||||
|
||||
while(command != "quit")
|
||||
{
|
||||
for(int i = 1; i < 200; i++)
|
||||
myChai.ResetState();
|
||||
|
||||
if(command == "runfile")
|
||||
myChai.RunFile("Test.chai");
|
||||
|
||||
command = get_next_command();
|
||||
}
|
||||
}
|
@@ -1,70 +0,0 @@
|
||||
|
||||
|
||||
def initialize_cpu_sensor(state, cpuname, sensor_manager)
|
||||
{
|
||||
state[cpuname] = 0.0;
|
||||
state[cpuname + ".user"] = 0.0;
|
||||
state[cpuname + ".nice"] = 0.0;
|
||||
state[cpuname + ".system"] = 0.0;
|
||||
state[cpuname + ".idle"] = 0.0;
|
||||
state[cpuname + ".iowait"] = 0.0;
|
||||
state[cpuname + ".irq"] = 0.0;
|
||||
state[cpuname + ".softirq"] = 0.0;
|
||||
}
|
||||
|
||||
def update_cpu_state(state, statfile, cpuname)
|
||||
{
|
||||
var regex = cpuname + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)";
|
||||
var strs = regex_search(statfile, regex);
|
||||
|
||||
var user = to_double(strs[1]);
|
||||
var nice = to_double(strs[2]);
|
||||
var system = to_double(strs[3]);
|
||||
var idle = to_double(strs[4]);
|
||||
var iowait = to_double(strs[5]);
|
||||
var irq = to_double(strs[6]);
|
||||
var softirq = to_double(strs[7]);
|
||||
|
||||
var userd = user - state[cpuname + ".user"];
|
||||
var niced = nice - state[cpuname + ".nice"];
|
||||
var systemd = system - state[cpuname + ".system"];
|
||||
var idled = idle - state[cpuname + ".idle"];
|
||||
var iowaitd = iowait - state[cpuname + ".iowait"];
|
||||
var irqd = irq - state[cpuname + ".irq"];
|
||||
var softirqd = softirq - state[cpuname + ".softirq"];
|
||||
|
||||
var totalticks = userd + niced + systemd + idled + iowaitd + irqd + softirqd;
|
||||
|
||||
state[cpuname] = (totalticks - idled) / totalticks
|
||||
|
||||
state[cpuname + ".user"] = user;
|
||||
state[cpuname + ".nice"] = nice;
|
||||
state[cpuname + ".system"] = system;
|
||||
state[cpuname + ".idle"] = idle;
|
||||
state[cpuname + ".iowait"] = iowait;
|
||||
state[cpuname + ".irq"] = irq;
|
||||
state[cpuname + ".softirq"] = softirq;
|
||||
}
|
||||
|
||||
# annotation
|
||||
def update_state(state)
|
||||
{
|
||||
var file = load_text_file("/proc/stat");
|
||||
|
||||
update_cpu_state(state, file, "cpu");
|
||||
update_cpu_state(state, file, "cpu0");
|
||||
update_cpu_state(state, file, "cpu1");
|
||||
}
|
||||
|
||||
//dump_system()
|
||||
|
||||
var global_state = Map()
|
||||
|
||||
initialize_cpu_sensor(global_state, "cpu", sensor_manager);
|
||||
initialize_cpu_sensor(global_state, "cpu0", sensor_manager);
|
||||
initialize_cpu_sensor(global_state, "cpu1", sensor_manager);
|
||||
|
||||
sensor_manager.add_sensor("cpu", 500, global_state, fun(state) { update_state(state); state["cpu"]; } )
|
||||
sensor_manager.add_sensor("cpu0", 500, global_state, fun(state) { state["cpu0"]; } )
|
||||
sensor_manager.add_sensor("cpu1", 500, global_state, fun(state) { state["cpu1"]; } )
|
||||
|
@@ -1,92 +0,0 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <chaiscript/dispatchkit/function_call.hpp>
|
||||
#include <boost/function.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/regex.hpp>
|
||||
|
||||
void log(const std::string &msg)
|
||||
{
|
||||
std::cout << "[" << boost::posix_time::microsec_clock::local_time() << "] " << msg << std::endl;
|
||||
}
|
||||
|
||||
void log(const std::string &module, const std::string &msg)
|
||||
{
|
||||
std::cout << "[" << boost::posix_time::microsec_clock::local_time() << "] <" << module << "> " << msg << std::endl;
|
||||
}
|
||||
|
||||
struct System
|
||||
{
|
||||
std::map<std::string, boost::function<std::string (const std::string &) > > m_callbacks;
|
||||
|
||||
void add_callback(const std::string &t_name,
|
||||
boost::shared_ptr<dispatchkit::Proxy_Function> t_func)
|
||||
{
|
||||
m_callbacks[t_name] = dispatchkit::build_function_caller<std::string (const std::string &)>(t_func);
|
||||
}
|
||||
|
||||
|
||||
void do_callbacks(const std::string &inp)
|
||||
{
|
||||
log("Running Callbacks: " + inp);
|
||||
for (std::map<std::string, boost::function<std::string (const std::string &)> >::iterator itr = m_callbacks.begin();
|
||||
itr != m_callbacks.end();
|
||||
++itr)
|
||||
{
|
||||
log("Callback: " + itr->first, itr->second(inp));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
|
||||
chaiscript::ChaiScript_Engine chai;
|
||||
|
||||
//Create a new system object and share it with the chaiscript engine
|
||||
System system;
|
||||
chai.get_eval_engine().add_object("system", boost::ref(system));
|
||||
|
||||
//Register the two methods of the System structure.
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &System::add_callback, "add_callback");
|
||||
dispatchkit::register_function(chai.get_eval_engine(), &System::do_callbacks, "do_callbacks");
|
||||
|
||||
// Let's use chaiscript to add a new lambda callback to our system.
|
||||
// The function "{ 'Callback1' + x }" is created in chaiscript and passed into our C++ application
|
||||
// in the "add_callback" function of struct System the chaiscript function is converted into a
|
||||
// boost::function, so it can be handled and called easily and type-safely
|
||||
chai.evaluate_string("system.add_callback('#1', fun(x) { 'Callback1 ' + x });");
|
||||
|
||||
// Because we are sharing the "system" object with the chaiscript engine we have equal
|
||||
// access to it both from within chaiscript and from C++ code
|
||||
system.do_callbacks("TestString");
|
||||
chai.evaluate_string("system.do_callbacks(\"TestString\");");
|
||||
|
||||
// The log function is overloaded, therefore we have to give the C++ compiler a hint as to which
|
||||
// version we want to register. One way to do this is to create a typedef of the function pointer
|
||||
// then cast your function to that typedef.
|
||||
typedef void (*PlainLog)(const std::string &);
|
||||
typedef void (*ModuleLog)(const std::string &, const std::string &);
|
||||
dispatchkit::register_function(chai.get_eval_engine(), PlainLog(&log), "log");
|
||||
dispatchkit::register_function(chai.get_eval_engine(), ModuleLog(&log), "log");
|
||||
|
||||
chai.evaluate_string("log('Test Message')");
|
||||
chai.evaluate_string("log('Test Module', 'Test Message');");
|
||||
|
||||
//Finally, it is possible to register any boost::function as a system function, in this
|
||||
//way, we can, for instance add a bound member function to the system
|
||||
chai.get_eval_engine().register_function(boost::function<void ()>(boost::bind(&System::do_callbacks, boost::ref(system), "Bound Test")), "do_callbacks");
|
||||
|
||||
//Call bound version of do_callbacks
|
||||
chai.evaluate_string("do_callbacks()");
|
||||
|
||||
}
|
||||
|
303
src/main.cpp
303
src/main.cpp
@@ -1,90 +1,243 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
|
||||
// and Jason Turner (lefticus@gmail.com)
|
||||
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <boost/algorithm/string/trim.hpp>
|
||||
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
|
||||
void print_help() {
|
||||
std::cout << "ChaiScript evaluator. To evaluate and expression, type it and press <enter>." << std::endl;
|
||||
#ifdef READLINE_AVAILABLE
|
||||
#include <readline/readline.h>
|
||||
#include <readline/history.h>
|
||||
#else
|
||||
char* readline(const char* p)
|
||||
{
|
||||
std::string retval;
|
||||
std::cout << p ;
|
||||
std::getline(std::cin, retval);
|
||||
#ifdef BOOST_MSVC
|
||||
return std::cin.eof() ? NULL : _strdup(retval.c_str());
|
||||
#else
|
||||
return std::cin.eof() ? NULL : strdup(retval.c_str());
|
||||
#endif
|
||||
}
|
||||
void add_history(const char*){}
|
||||
void using_history(){}
|
||||
#endif
|
||||
|
||||
void help(int n) {
|
||||
if ( n >= 0 ) {
|
||||
std::cout << "ChaiScript evaluator. To evaluate an expression, type it and press <enter>." << std::endl;
|
||||
std::cout << "Additionally, you can inspect the runtime system using:" << std::endl;
|
||||
std::cout << " dump_system() - outputs all functions registered to the system" << std::endl;
|
||||
std::cout << " dump_object(x) - dumps information about the given symbol" << std::endl;
|
||||
} else {
|
||||
std::cout << "usage : chai [option]+" << std::endl;
|
||||
std::cout << "option:" << std::endl;
|
||||
std::cout << " -h | --help" << std::endl;
|
||||
std::cout << " -i | --interactive" << std::endl;
|
||||
std::cout << " -c | --command cmd" << std::endl;
|
||||
std::cout << " -v | --version" << std::endl;
|
||||
std::cout << " - --stdin" << std::endl;
|
||||
std::cout << " filepath" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
std::string input;
|
||||
chaiscript::ChaiScript_Engine chai;
|
||||
|
||||
if (argc < 2) {
|
||||
std::cout << "eval> ";
|
||||
std::getline(std::cin, input);
|
||||
while (input != "quit") {
|
||||
|
||||
dispatchkit::Boxed_Value val;
|
||||
|
||||
if (input == "help") {
|
||||
print_help();
|
||||
}
|
||||
else {
|
||||
try {
|
||||
//First, we evaluate it
|
||||
val = chai.evaluate_string(input);
|
||||
|
||||
//Then, we try to print the result of the evaluation to the user
|
||||
if (val.get_type_info().m_bare_type_info && *(val.get_type_info().m_bare_type_info) != typeid(void)) {
|
||||
try {
|
||||
dispatchkit::dispatch(chai.get_eval_engine().get_function("print"), dispatchkit::Param_List_Builder() << val);
|
||||
}
|
||||
catch (...) {
|
||||
//If we can't, do nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (chaiscript::Parse_Error &pe) {
|
||||
std::cout << pe.reason << " in " << pe.filename << " at " << pe.position.line << ", " << pe.position.column << std::endl;
|
||||
}
|
||||
catch (chaiscript::Eval_Error &ee) {
|
||||
std::cout << ee.reason << std::endl;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cout << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
std::cout << "eval> ";
|
||||
std::getline(std::cin, input);
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string filename(argv[i]);
|
||||
try {
|
||||
dispatchkit::Boxed_Value val = chai.evaluate_file(argv[i]);
|
||||
}
|
||||
catch (chaiscript::Parse_Error &pe) {
|
||||
if (filename != std::string("__EVAL__")) {
|
||||
std::cout << pe.reason << " in " << pe.filename << " at " << pe.position.line << ", " << pe.position.column << std::endl;
|
||||
}
|
||||
else {
|
||||
std::cout << pe.reason << std::endl;
|
||||
}
|
||||
}
|
||||
catch (chaiscript::Eval_Error &ee) {
|
||||
if (filename != std::string("__EVAL__")) {
|
||||
std::cout << ee.reason << " in '" << ee.location->filename << "' at " << ee.location->start.line << ", " << ee.location->start.column << std::endl;
|
||||
}
|
||||
else {
|
||||
std::cout << ee.reason << std::endl;
|
||||
}
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cout << e.what() << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
void version(int){
|
||||
std::cout << "chai: compiled " << __TIME__ << " " << __DATE__ << std::endl;
|
||||
}
|
||||
|
||||
bool throws_exception(const boost::function<void ()> &f)
|
||||
{
|
||||
try {
|
||||
f();
|
||||
} catch (...) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
chaiscript::exception::eval_error get_eval_error(const boost::function<void ()> &f)
|
||||
{
|
||||
try {
|
||||
f();
|
||||
} catch (const chaiscript::exception::eval_error &e) {
|
||||
return e;
|
||||
}
|
||||
|
||||
throw std::runtime_error("no exception throw");
|
||||
}
|
||||
|
||||
std::string get_next_command() {
|
||||
std::string retval("quit");
|
||||
if ( ! std::cin.eof() ) {
|
||||
char *input_raw = readline("eval> ");
|
||||
if ( input_raw ) {
|
||||
add_history(input_raw);
|
||||
retval = boost::trim_copy_if(std::string(input_raw),boost::is_any_of(" \t"));
|
||||
::free(input_raw);
|
||||
}
|
||||
}
|
||||
if( retval == "quit"
|
||||
|| retval == "exit"
|
||||
|| retval == "help"
|
||||
|| retval == "version")
|
||||
{
|
||||
retval += "(0)";
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
// We have to wrap exit with our own because Clang has a hard time with
|
||||
// function pointers to functions with special attributes (system exit being marked NORETURN)
|
||||
void myexit(int return_val) {
|
||||
exit(return_val);
|
||||
}
|
||||
|
||||
void interactive(chaiscript::ChaiScript& chai)
|
||||
{
|
||||
using_history();
|
||||
|
||||
for (;;) {
|
||||
std::string input = get_next_command();
|
||||
try {
|
||||
// evaluate input
|
||||
chaiscript::Boxed_Value val = chai.eval(input);
|
||||
|
||||
//Then, we try to print the result of the evaluation to the user
|
||||
if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) {
|
||||
try {
|
||||
std::cout << chai.eval<boost::function<std::string (const chaiscript::Boxed_Value &bv)> >("to_string")(val) << std::endl;
|
||||
}
|
||||
catch (...) {} //If we can't, do nothing
|
||||
}
|
||||
}
|
||||
catch (const chaiscript::exception::eval_error &ee) {
|
||||
std::cout << ee.what();
|
||||
if (ee.call_stack.size() > 0) {
|
||||
std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
catch (const std::exception &e) {
|
||||
std::cout << e.what();
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
std::vector<std::string> usepaths;
|
||||
std::vector<std::string> modulepaths;
|
||||
|
||||
// Disable deprecation warning for getenv call.
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4996)
|
||||
#endif
|
||||
|
||||
const char *usepath = getenv("CHAI_USE_PATH");
|
||||
const char *modulepath = getenv("CHAI_MODULE_PATH");
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
|
||||
usepaths.push_back("");
|
||||
if (usepath)
|
||||
{
|
||||
usepaths.push_back(usepath);
|
||||
}
|
||||
|
||||
modulepaths.push_back("");
|
||||
if (modulepath)
|
||||
{
|
||||
modulepaths.push_back(modulepath);
|
||||
}
|
||||
|
||||
chaiscript::ChaiScript chai(modulepaths,usepaths);
|
||||
|
||||
chai.add(chaiscript::fun(&myexit), "exit");
|
||||
chai.add(chaiscript::fun(&myexit), "quit");
|
||||
chai.add(chaiscript::fun(&help), "help");
|
||||
chai.add(chaiscript::fun(&version), "version");
|
||||
chai.add(chaiscript::fun(&throws_exception), "throws_exception");
|
||||
chai.add(chaiscript::fun(&get_eval_error), "get_eval_error");
|
||||
|
||||
for (int i = 0; i < argc; ++i) {
|
||||
if ( i == 0 && argc > 1 ) {
|
||||
++i;
|
||||
}
|
||||
|
||||
std::string arg( i ? argv[i] : "--interactive" );
|
||||
|
||||
enum { eInteractive
|
||||
, eCommand
|
||||
, eFile
|
||||
} mode = eCommand ;
|
||||
|
||||
if ( arg == "-c" || arg == "--command" ) {
|
||||
if ( (i+1) >= argc ) {
|
||||
std::cout << "insufficient input following " << arg << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
} else {
|
||||
arg = argv[++i];
|
||||
}
|
||||
} else if ( arg == "-" || arg == "--stdin" ) {
|
||||
arg = "" ;
|
||||
std::string line;
|
||||
while ( std::getline(std::cin, line) ) {
|
||||
arg += line + '\n' ;
|
||||
}
|
||||
} else if ( arg == "-v" || arg == "--version" ) {
|
||||
arg = "version(0)" ;
|
||||
} else if ( arg == "-h" || arg == "--help" ) {
|
||||
arg = "help(-1)";
|
||||
} else if ( arg == "-i" || arg == "--interactive" ) {
|
||||
mode = eInteractive ;
|
||||
} else if ( arg.find('-') == 0 ) {
|
||||
std::cout << "unrecognised argument " << arg << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
} else {
|
||||
mode = eFile;
|
||||
}
|
||||
|
||||
chaiscript::Boxed_Value val ;
|
||||
try {
|
||||
switch ( mode ) {
|
||||
case eInteractive : interactive(chai); break;
|
||||
case eCommand : val = chai.eval(arg); break;
|
||||
case eFile : val = chai.eval_file(arg); break;
|
||||
}
|
||||
}
|
||||
catch (const chaiscript::exception::eval_error &ee) {
|
||||
std::cout << ee.what();
|
||||
if (ee.call_stack.size() > 0) {
|
||||
std::cout << "during evaluation at (" << *(ee.call_stack[0]->filename) << " " << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
|
||||
for (size_t j = 1; j < ee.call_stack.size(); ++j) {
|
||||
if (ee.call_stack[j]->identifier != chaiscript::AST_Node_Type::Block
|
||||
&& ee.call_stack[j]->identifier != chaiscript::AST_Node_Type::File)
|
||||
{
|
||||
std::cout << std::endl;
|
||||
std::cout << " from " << *(ee.call_stack[j]->filename) << " (" << ee.call_stack[j]->start.line << ", " << ee.call_stack[j]->start.column << ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
std::cout << e.what() << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
40
src/multithreaded.cpp
Normal file
40
src/multithreaded.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
// This file is distributed under the BSD License.
|
||||
// See "license.txt" for details.
|
||||
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
|
||||
// and Jason Turner (jason@emptycrate.com)
|
||||
// http://www.chaiscript.com
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include <list>
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <boost/thread.hpp>
|
||||
|
||||
void do_work(chaiscript::ChaiScript &c)
|
||||
{
|
||||
// c("use(\"work.chai\"); do_chai_work(num_iterations);");
|
||||
std::string name = "MyVar" + boost::lexical_cast<std::string>(rand());
|
||||
c.add(chaiscript::var(5), name);
|
||||
c("use(\"work.chai\"); do_chai_work(10000);");
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
std::string input;
|
||||
chaiscript::ChaiScript chai;
|
||||
|
||||
//chai.add_shared_object(chaiscript::Boxed_Value(10000), "num_iterations");
|
||||
|
||||
std::vector<boost::shared_ptr<boost::thread> > threads;
|
||||
|
||||
for (int i = 0; i < argc - 1; ++i)
|
||||
{
|
||||
threads.push_back(boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(do_work, boost::ref(chai)))));
|
||||
}
|
||||
|
||||
for (int i = 0; i < argc - 1; ++i)
|
||||
{
|
||||
threads[i]->join();
|
||||
}
|
||||
}
|
||||
|
97
src/reflection.cpp
Normal file
97
src/reflection.cpp
Normal file
@@ -0,0 +1,97 @@
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <chaiscript/utility/utility.hpp>
|
||||
#include <string>
|
||||
|
||||
|
||||
// MSVC doesn't like that we are using C++ return types from our C declared module
|
||||
// but this is the best way to do it for cross platform compatibility
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4190)
|
||||
#endif
|
||||
|
||||
|
||||
bool has_parse_tree(const chaiscript::Const_Proxy_Function &t_pf)
|
||||
{
|
||||
boost::shared_ptr<const chaiscript::dispatch::Dynamic_Proxy_Function> pf
|
||||
= boost::dynamic_pointer_cast<const chaiscript::dispatch::Dynamic_Proxy_Function>(t_pf);
|
||||
if (pf)
|
||||
{
|
||||
return pf->get_parse_tree();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
chaiscript::AST_NodePtr get_parse_tree(const chaiscript::Const_Proxy_Function &t_pf)
|
||||
{
|
||||
boost::shared_ptr<const chaiscript::dispatch::Dynamic_Proxy_Function> pf
|
||||
= boost::dynamic_pointer_cast<const chaiscript::dispatch::Dynamic_Proxy_Function>(t_pf);
|
||||
if (pf)
|
||||
{
|
||||
if (pf->get_parse_tree())
|
||||
{
|
||||
return pf->get_parse_tree();
|
||||
} else {
|
||||
throw std::runtime_error("Function does not have a parse tree");
|
||||
}
|
||||
} else {
|
||||
throw std::runtime_error("Function does not have a parse tree");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_reflection()
|
||||
{
|
||||
chaiscript::ModulePtr m(new chaiscript::Module());
|
||||
|
||||
m->add(chaiscript::fun(&has_parse_tree), "has_parse_tree");
|
||||
m->add(chaiscript::fun(&get_parse_tree), "get_parse_tree");
|
||||
|
||||
|
||||
chaiscript::bootstrap::standard_library::vector_type<std::vector<boost::shared_ptr<chaiscript::AST_Node> > >("AST_NodeVector", m);
|
||||
|
||||
CHAISCRIPT_CLASS( m,
|
||||
chaiscript::exception::eval_error,
|
||||
,
|
||||
((reason))
|
||||
((call_stack))
|
||||
);
|
||||
|
||||
CHAISCRIPT_CLASS( m,
|
||||
chaiscript::File_Position,
|
||||
(chaiscript::File_Position())
|
||||
(chaiscript::File_Position(int,int)),
|
||||
((line))
|
||||
((column))
|
||||
);
|
||||
|
||||
CHAISCRIPT_CLASS( m,
|
||||
chaiscript::AST_Node,
|
||||
,
|
||||
((text))
|
||||
((identifier))
|
||||
((filename))
|
||||
((start))
|
||||
((end))
|
||||
((internal_to_string))
|
||||
((children))
|
||||
((replace_child))
|
||||
);
|
||||
|
||||
CHAISCRIPT_CLASS( m,
|
||||
chaiscript::parser::ChaiScript_Parser,
|
||||
(chaiscript::parser::ChaiScript_Parser ()),
|
||||
((parse))
|
||||
((ast))
|
||||
);
|
||||
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(pop)
|
||||
#endif
|
21
src/stl_extra.cpp
Normal file
21
src/stl_extra.cpp
Normal file
@@ -0,0 +1,21 @@
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <list>
|
||||
#include <string>
|
||||
|
||||
// MSVC doesn't like that we are using C++ return types from our C declared module
|
||||
// but this is the best way to do it for cross platform compatibility
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4190)
|
||||
#endif
|
||||
|
||||
CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_stl_extra()
|
||||
{
|
||||
return chaiscript::bootstrap::standard_library::list_type<std::list<chaiscript::Boxed_Value> >("List");
|
||||
}
|
||||
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(pop)
|
||||
#endif
|
61
src/test_module.cpp
Normal file
61
src/test_module.cpp
Normal file
@@ -0,0 +1,61 @@
|
||||
|
||||
#include <chaiscript/chaiscript.hpp>
|
||||
#include <string>
|
||||
|
||||
class TestBaseType
|
||||
{
|
||||
public:
|
||||
TestBaseType() {}
|
||||
TestBaseType(int) {}
|
||||
virtual ~TestBaseType() {}
|
||||
virtual int func() { return 0; }
|
||||
|
||||
};
|
||||
|
||||
class TestDerivedType : public TestBaseType
|
||||
{
|
||||
public:
|
||||
virtual ~TestDerivedType() {}
|
||||
virtual int func() { return 1; }
|
||||
};
|
||||
|
||||
std::string hello_world()
|
||||
{
|
||||
return "Hello World";
|
||||
}
|
||||
|
||||
// MSVC doesn't like that we are using C++ return types from our C declared module
|
||||
// but this is the best way to do it for cross platform compatibility
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(push)
|
||||
#pragma warning(disable : 4190)
|
||||
#endif
|
||||
|
||||
|
||||
CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_test_module()
|
||||
{
|
||||
chaiscript::ModulePtr m(new chaiscript::Module());
|
||||
|
||||
m->add(chaiscript::fun(hello_world), "hello_world");
|
||||
|
||||
m->add(chaiscript::user_type<TestBaseType>(), "TestBaseType");
|
||||
m->add(chaiscript::user_type<TestDerivedType>(), "TestDerivedType");
|
||||
|
||||
m->add(chaiscript::constructor<TestBaseType ()>(), "TestBaseType");
|
||||
// m->add(chaiscript::constructor<TestBaseType (int)>(), "TestBaseType");
|
||||
m->add(chaiscript::constructor<TestBaseType (const TestBaseType &)>(), "TestBaseType");
|
||||
|
||||
m->add(chaiscript::constructor<TestDerivedType ()>(), "TestDerivedType");
|
||||
m->add(chaiscript::constructor<TestDerivedType (const TestDerivedType &)>(), "TestDerivedType");
|
||||
|
||||
m->add(chaiscript::base_class<TestBaseType, TestDerivedType>());
|
||||
|
||||
m->add(chaiscript::fun(&TestBaseType::func), "func");
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
#ifdef BOOST_MSVC
|
||||
#pragma warning(pop)
|
||||
#endif
|
10
src/work.chai
Normal file
10
src/work.chai
Normal file
@@ -0,0 +1,10 @@
|
||||
def do_chai_work(num_iters)
|
||||
{
|
||||
var i = 0;
|
||||
for (var k = 0; k<num_iters * 10; ++k)
|
||||
{
|
||||
i += k;
|
||||
}
|
||||
|
||||
print(i);
|
||||
}
|
2
unittests/assign_const.chai
Normal file
2
unittests/assign_const.chai
Normal file
@@ -0,0 +1,2 @@
|
||||
assert_throws("Mismatched types in equation, lhs is const.", fun() { 1 = 2 } );
|
||||
assert_throws("Mismatched types in equation, lhs is const.", fun() { 1 + 2 = 2 } );
|
@@ -1,2 +1,2 @@
|
||||
var prod = bind(foldl, _, `*`, 1.0)
|
||||
print(prod([3, 4, 5]))
|
||||
assert_equal(60, prod([3, 4, 5]))
|
||||
|
@@ -1 +0,0 @@
|
||||
60
|
34
unittests/bind2.chai
Normal file
34
unittests/bind2.chai
Normal file
@@ -0,0 +1,34 @@
|
||||
|
||||
def add(x, y)
|
||||
{
|
||||
return x + y;
|
||||
}
|
||||
|
||||
assert_equal(2, add.get_arity());
|
||||
|
||||
var b = bind(add, 2, _);
|
||||
|
||||
assert_equal(1, b.get_arity());
|
||||
|
||||
var c = bind(b, 3);
|
||||
|
||||
assert_equal(0, c.get_arity());
|
||||
|
||||
assert_equal(6, b(4));
|
||||
assert_equal(5, c());
|
||||
|
||||
def concat2(a,b,c,d)
|
||||
{
|
||||
return to_string(a) + to_string(b) + to_string(c) + to_string(d);
|
||||
}
|
||||
|
||||
var d = bind(concat2, _, " Hello ", _, " World");
|
||||
assert_equal(2, d.get_arity());
|
||||
|
||||
assert_equal("1 Hello 3 World", d(1,3));
|
||||
|
||||
var e = bind(`<`, _, 5);
|
||||
var types = e.get_param_types();
|
||||
assert_equal(2, types.size());
|
||||
assert_equal(true, types[0].bare_equal(bool_type));
|
||||
|
1
unittests/block_start.chai
Normal file
1
unittests/block_start.chai
Normal file
@@ -0,0 +1 @@
|
||||
{print("hello")}
|
@@ -1 +1 @@
|
||||
print(!true)
|
||||
assert_equal(false, !true)
|
||||
|
@@ -1 +0,0 @@
|
||||
false
|
317
unittests/boxed_cast_test.cpp
Normal file
317
unittests/boxed_cast_test.cpp
Normal file
@@ -0,0 +1,317 @@
|
||||
#include <chaiscript/utility/utility.hpp>
|
||||
|
||||
|
||||
using namespace chaiscript;
|
||||
|
||||
|
||||
template<typename T>
|
||||
void use(T){}
|
||||
|
||||
template<typename To>
|
||||
bool run_test_type_conversion(const Boxed_Value &bv, bool expectedpass)
|
||||
{
|
||||
try {
|
||||
To ret = chaiscript::boxed_cast<To>(bv);
|
||||
use(ret);
|
||||
} catch (const chaiscript::exception::bad_boxed_cast &/*e*/) {
|
||||
if (expectedpass) {
|
||||
// std::cerr << "Failure in run_test_type_conversion: " << e.what() << std::endl;
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << "Unexpected standard exception when attempting cast_conversion: " << e.what() << std::endl;
|
||||
return false;
|
||||
} catch (...) {
|
||||
std::cerr << "Unexpected unknown exception when attempting cast_conversion." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (expectedpass)
|
||||
{
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename To>
|
||||
bool test_type_conversion(const Boxed_Value &bv, bool expectedpass)
|
||||
{
|
||||
bool ret = run_test_type_conversion<To>(bv, expectedpass);
|
||||
|
||||
if (!ret)
|
||||
{
|
||||
std::cerr << "Error with type conversion test. From: "
|
||||
<< (bv.is_const()?(std::string("const ")):(std::string())) << bv.get_type_info().name()
|
||||
<< " To: "
|
||||
<< (boost::is_const<To>::value?(std::string("const ")):(std::string())) << typeid(To).name()
|
||||
<< " test was expected to " << ((expectedpass)?(std::string("succeed")):(std::string("fail"))) << " but did not" << std::endl;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<typename Type>
|
||||
bool do_test(const Boxed_Value &bv, bool T, bool ConstT, bool TRef, bool ConstTRef, bool TPtr, bool ConstTPtr, bool TPtrConst,
|
||||
bool ConstTPtrConst, bool SharedPtrT, bool SharedConstPtrT,
|
||||
bool ConstSharedPtrT, bool ConstSharedConstPtrT, bool ConstSharedPtrTRef, bool ConstSharedPtrTConstRef,
|
||||
bool BoostRef, bool BoostConstRef, bool ConstBoostRef, bool ConstBoostConstRef,
|
||||
bool ConstBoostRefRef, bool ConstBoostConstRefRef, bool PODValue,
|
||||
bool ConstPODValue, bool ConstPODValueRef, bool TPtrConstRef, bool ConstTPtrConstRef)
|
||||
{
|
||||
bool passed = true;
|
||||
passed &= test_type_conversion<Type>(bv, T);
|
||||
passed &= test_type_conversion<const Type>(bv, ConstT);
|
||||
passed &= test_type_conversion<Type &>(bv, TRef);
|
||||
passed &= test_type_conversion<const Type &>(bv, ConstTRef);
|
||||
passed &= test_type_conversion<Type *>(bv, TPtr);
|
||||
passed &= test_type_conversion<const Type *>(bv, ConstTPtr);
|
||||
passed &= test_type_conversion<Type * const>(bv, TPtrConst);
|
||||
passed &= test_type_conversion<const Type * const>(bv, ConstTPtrConst);
|
||||
passed &= test_type_conversion<boost::shared_ptr<Type> >(bv, SharedPtrT);
|
||||
passed &= test_type_conversion<boost::shared_ptr<const Type> >(bv, SharedConstPtrT);
|
||||
passed &= test_type_conversion<boost::shared_ptr<Type> &>(bv, false);
|
||||
passed &= test_type_conversion<boost::shared_ptr<const Type> &>(bv, false);
|
||||
passed &= test_type_conversion<const boost::shared_ptr<Type> >(bv, ConstSharedPtrT);
|
||||
passed &= test_type_conversion<const boost::shared_ptr<const Type> >(bv, ConstSharedConstPtrT);
|
||||
passed &= test_type_conversion<const boost::shared_ptr<Type> &>(bv, ConstSharedPtrTRef);
|
||||
passed &= test_type_conversion<const boost::shared_ptr<const Type> &>(bv, ConstSharedPtrTConstRef);
|
||||
passed &= test_type_conversion<boost::reference_wrapper<Type> >(bv, BoostRef);
|
||||
passed &= test_type_conversion<boost::reference_wrapper<const Type> >(bv, BoostConstRef);
|
||||
passed &= test_type_conversion<boost::reference_wrapper<Type> &>(bv, false);
|
||||
passed &= test_type_conversion<boost::reference_wrapper<const Type> &>(bv, false);
|
||||
passed &= test_type_conversion<const boost::reference_wrapper<Type> >(bv, ConstBoostRef);
|
||||
passed &= test_type_conversion<const boost::reference_wrapper<const Type> >(bv, ConstBoostConstRef);
|
||||
passed &= test_type_conversion<const boost::reference_wrapper<Type> &>(bv, ConstBoostRefRef);
|
||||
passed &= test_type_conversion<const boost::reference_wrapper<const Type> &>(bv, ConstBoostConstRefRef);
|
||||
passed &= test_type_conversion<Boxed_POD_Value>(bv, PODValue);
|
||||
passed &= test_type_conversion<const Boxed_POD_Value>(bv, ConstPODValue);
|
||||
passed &= test_type_conversion<Boxed_POD_Value &>(bv, false);
|
||||
passed &= test_type_conversion<const Boxed_POD_Value &>(bv, ConstPODValueRef);
|
||||
passed &= test_type_conversion<Boxed_POD_Value *>(bv, false);
|
||||
passed &= test_type_conversion<const Boxed_POD_Value *>(bv, false);
|
||||
passed &= test_type_conversion<Boxed_POD_Value * const>(bv, false);
|
||||
passed &= test_type_conversion<const Boxed_POD_Value *const>(bv, false);
|
||||
passed &= test_type_conversion<Type *&>(bv, false);
|
||||
passed &= test_type_conversion<const Type *&>(bv, false);
|
||||
passed &= test_type_conversion<Type * const&>(bv, TPtrConstRef);
|
||||
passed &= test_type_conversion<const Type * const&>(bv, ConstTPtrConstRef);
|
||||
passed &= test_type_conversion<Boxed_Value>(bv, true);
|
||||
passed &= test_type_conversion<const Boxed_Value>(bv, true);
|
||||
passed &= test_type_conversion<const Boxed_Value &>(bv, true);
|
||||
|
||||
return passed;
|
||||
}
|
||||
|
||||
/** Tests intended for built int types **/
|
||||
template<typename T>
|
||||
bool built_in_type_test(const T &initial, bool ispod)
|
||||
{
|
||||
bool passed = true;
|
||||
|
||||
/** value tests **/
|
||||
T i = T(initial);
|
||||
passed &= do_test<T>(var(i), true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
ispod && true, ispod && true, ispod && true, true, true);
|
||||
|
||||
passed &= do_test<T>(const_var(i), true, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
false, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
passed &= do_test<T>(var(&i), true, true, true, true, true,
|
||||
true, true, true, false, false,
|
||||
false, false, false, false, true,
|
||||
true, true, true, true, true,
|
||||
ispod && true, ispod && true, ispod && true, true, true);
|
||||
|
||||
passed &= do_test<T>(const_var(&i), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, ispod && false, true);
|
||||
|
||||
passed &= do_test<T>(var(boost::ref(i)), true, true, true, true, true,
|
||||
true, true, true, false, false,
|
||||
false, false, false, false, true,
|
||||
true, true, true, true, true,
|
||||
ispod && true, ispod && true, ispod && true, true, true);
|
||||
|
||||
passed &= do_test<T>(var(boost::cref(i)), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
/** Const Reference Variable tests */
|
||||
|
||||
// This reference will be copied on input, which is expected
|
||||
const T &ir = i;
|
||||
|
||||
passed &= do_test<T>(var(i), true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
ispod && true, ispod && true, ispod && true, true, true);
|
||||
|
||||
// But a pointer or reference to it should be necessarily const
|
||||
passed &= do_test<T>(var(&ir), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
passed &= do_test<T>(var(boost::ref(ir)), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
// Make sure const of const works too
|
||||
passed &= do_test<T>(const_var(&ir), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
passed &= do_test<T>(const_var(boost::ref(ir)), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
/** Const Reference Variable tests */
|
||||
|
||||
// This will always be seen as a const
|
||||
const T*cip = &i;
|
||||
passed &= do_test<T>(var(cip), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
// make sure const of const works
|
||||
passed &= do_test<T>(const_var(cip), true, true, false, true, false,
|
||||
true, false, true, false, false,
|
||||
false, false, false, false, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
/** shared_ptr tests **/
|
||||
|
||||
boost::shared_ptr<T> ip(new T(initial));
|
||||
|
||||
passed &= do_test<T>(var(ip), true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
true, true, true, true, true,
|
||||
ispod && true, ispod && true, ispod && true, true, true);
|
||||
|
||||
passed &= do_test<T>(const_var(ip), true, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
false, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
/** const shared_ptr tests **/
|
||||
boost::shared_ptr<const T> ipc(new T(initial));
|
||||
|
||||
passed &= do_test<T>(var(ipc), true, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
false, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
// const of this should be the same, making sure it compiles
|
||||
passed &= do_test<T>(const_var(ipc), true, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
false, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
|
||||
|
||||
/** Double ptr tests **/
|
||||
|
||||
/*
|
||||
T **doublep;
|
||||
|
||||
passed &= do_test<T*>(var(doublep), true, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
false, true, false, true, false,
|
||||
true, false, true, false, true,
|
||||
ispod && true, ispod && true, ispod && true, false, true);
|
||||
*/
|
||||
|
||||
return passed;
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
bool pointer_test(const T& default_value, const T& new_value)
|
||||
{
|
||||
T *p = new T(default_value);
|
||||
|
||||
// we store a pointer to a pointer, so we can get a pointer to a pointer
|
||||
try {
|
||||
T **result = boxed_cast<T **>(var(&p));
|
||||
*(*result) = new_value;
|
||||
|
||||
|
||||
if (p != (*result) ) {
|
||||
std::cerr << "Pointer passed in different than one returned" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (*p != *(*result) ) {
|
||||
std::cerr << "Somehow dereferenced pointer values are not the same?" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (const exception::bad_boxed_cast &) {
|
||||
std::cerr << "Bad boxed cast performing ** to ** test" << std::endl;
|
||||
return false;
|
||||
} catch (...) {
|
||||
std::cerr << "Unknown exception performing ** to ** test" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
bool passed = true;
|
||||
|
||||
/*
|
||||
bool T, bool ConstT, bool TRef, bool ConstTRef, bool TPtr,
|
||||
bool ConstTPtr, bool TPtrConst, bool ConstTPtrConst, bool SharedPtrT, bool SharedConstPtrT,
|
||||
bool ConstSharedPtrT, bool ConstSharedConstPtrT, bool ConstSharedPtrTRef, bool ConstSharedPtrTConstRef, bool BoostRef,
|
||||
bool BoostConstRef, bool ConstBoostRef, bool ConstBoostConstRef, bool ConstBoostRefRef, bool ConstBoostConstRefRef,
|
||||
bool PODValue, bool ConstPODValue, bool ConstPODValueRef
|
||||
*/
|
||||
|
||||
passed &= built_in_type_test<int>(5, true);
|
||||
passed &= built_in_type_test<double>(1.1, true);
|
||||
passed &= built_in_type_test<char>('a', true);
|
||||
passed &= built_in_type_test<bool>(false, true);
|
||||
passed &= built_in_type_test<std::string>("Hello World", false);
|
||||
|
||||
// storing a pointer
|
||||
passed &= pointer_test<int>(1, 0);
|
||||
|
||||
if (passed)
|
||||
{
|
||||
return EXIT_SUCCESS;
|
||||
} else {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
}
|
@@ -4,4 +4,4 @@ while (i < 10) {
|
||||
break
|
||||
}
|
||||
}
|
||||
print(i)
|
||||
assert_equal(5, i);
|
||||
|
@@ -1 +0,0 @@
|
||||
5
|
@@ -1 +1 @@
|
||||
print('b')
|
||||
assert_equal("b", to_string('b'))
|
||||
|
@@ -1 +0,0 @@
|
||||
b
|
7
unittests/classification.chai
Normal file
7
unittests/classification.chai
Normal file
@@ -0,0 +1,7 @@
|
||||
assert_equal(true, 1.is_var_const());
|
||||
assert_equal(false, 1.is_var_reference());
|
||||
assert_equal(true, 1.is_var_pointer());
|
||||
assert_equal(false, 1.is_var_null());
|
||||
assert_equal(false, 1.is_var_undef());
|
||||
var i;
|
||||
assert_equal(true, i.is_var_undef());
|
@@ -1 +1,3 @@
|
||||
print(collate(1, 2))
|
||||
var v = collate(1, 2)
|
||||
assert_equal(1, v[0])
|
||||
assert_equal(2, v[1])
|
||||
|
@@ -1 +0,0 @@
|
||||
[1, 2]
|
@@ -1 +1 @@
|
||||
print(1 > 2)
|
||||
assert_equal(false, 1 > 2);
|
||||
|
@@ -1 +0,0 @@
|
||||
false
|
@@ -1 +1 @@
|
||||
print(1 < 2)
|
||||
assert_equal(true, 1 < 2)
|
||||
|
@@ -1 +0,0 @@
|
||||
true
|
@@ -1 +1,5 @@
|
||||
print(concat([1, 2], [3, 4]))
|
||||
var v = concat([1, 2], [3, 4]);
|
||||
|
||||
assert_equal(4, v.size());
|
||||
assert_equal(1, v[0]);
|
||||
assert_equal(4, v[3]);
|
||||
|
@@ -1 +0,0 @@
|
||||
[1, 2, 3, 4]
|
4
unittests/const_range_test.chai
Normal file
4
unittests/const_range_test.chai
Normal file
@@ -0,0 +1,4 @@
|
||||
//If the following succeeds, the test passes
|
||||
|
||||
|
||||
"Hello World".for_each(fun(x) { print(x) } )
|
@@ -1 +1 @@
|
||||
print(3.5.to_string() + "bob")
|
||||
assert_equal("3.5bob", 3.5.to_string() + "bob");
|
||||
|
@@ -1 +0,0 @@
|
||||
3.5bob
|
@@ -1 +1 @@
|
||||
print(3.to_string + "bob")
|
||||
assert_equal("3bob", 3.to_string + "bob")
|
||||
|
@@ -1 +0,0 @@
|
||||
3bob
|
@@ -1 +1 @@
|
||||
print("3.5".to_double() + 3.3)
|
||||
assert_equal(6.8, "3.5".to_double() + 3.3)
|
||||
|
@@ -1 +0,0 @@
|
||||
6.7999999999999998
|
@@ -1 +1 @@
|
||||
print("4".to_int() + 4)
|
||||
assert_equal(8, "4".to_int() + 4)
|
||||
|
@@ -1 +0,0 @@
|
||||
8
|
11
unittests/deep_array_lookup.chai
Normal file
11
unittests/deep_array_lookup.chai
Normal file
@@ -0,0 +1,11 @@
|
||||
var a = [1,2,3, [4,5,6] ]
|
||||
|
||||
assert_equal(a[3][0], 4)
|
||||
|
||||
|
||||
def Test::Test() { this.a = [1,2,3]; }
|
||||
attr Test::a;
|
||||
|
||||
var t = Test();
|
||||
|
||||
assert_equal(t.a[0], 1)
|
11
unittests/dispatch_functions.chai
Normal file
11
unittests/dispatch_functions.chai
Normal file
@@ -0,0 +1,11 @@
|
||||
assert_equal(`==`, `==`);
|
||||
assert_not_equal(`==`, `<`);
|
||||
assert_equal(`<`.get_arity(), 2);
|
||||
assert_equal(`+`.get_annotation(), "Multiple method dispatch function wrapper.");
|
||||
assert_equal(get_arity.get_contained_functions().size(), 0);
|
||||
assert_equal(get_arity.get_arity(), 1);
|
||||
assert_equal(get_arity.get_param_types().size(), 2);
|
||||
|
||||
var paramtypes = get_arity.get_param_types();
|
||||
|
||||
assert_equal(true, paramtypes[1].bare_equal(Function_type));
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user