summaryrefslogtreecommitdiffstats
path: root/cpp/sca/kernel
diff options
context:
space:
mode:
Diffstat (limited to 'cpp/sca/kernel')
-rw-r--r--cpp/sca/kernel/Makefile.am29
-rw-r--r--cpp/sca/kernel/function.hpp232
-rw-r--r--cpp/sca/kernel/gc.hpp269
-rw-r--r--cpp/sca/kernel/kernel-test.cpp444
-rw-r--r--cpp/sca/kernel/list.hpp379
-rw-r--r--cpp/sca/kernel/parallel.hpp283
-rw-r--r--cpp/sca/kernel/value.hpp357
-rw-r--r--cpp/sca/kernel/xml-test.cpp107
-rw-r--r--cpp/sca/kernel/xml.hpp385
9 files changed, 2485 insertions, 0 deletions
diff --git a/cpp/sca/kernel/Makefile.am b/cpp/sca/kernel/Makefile.am
new file mode 100644
index 0000000000..0055ae687f
--- /dev/null
+++ b/cpp/sca/kernel/Makefile.am
@@ -0,0 +1,29 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+noinst_PROGRAMS = kernel-test xml-test
+
+nobase_include_HEADERS = *.hpp
+
+INCLUDES = -I. -I$(top_builddir)/kernel -I${LIBXML2_INCLUDE}
+
+kernel_test_SOURCES = kernel-test.cpp
+kernel_test_LDADD = -lpthread -L${LIBXML2_LIB} -lxml2
+
+xml_test_SOURCES = xml-test.cpp
+xml_test_LDADD = -lpthread -L${LIBXML2_LIB} -lxml2
+
diff --git a/cpp/sca/kernel/function.hpp b/cpp/sca/kernel/function.hpp
new file mode 100644
index 0000000000..caba5211b9
--- /dev/null
+++ b/cpp/sca/kernel/function.hpp
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_function_hpp
+#define tuscany_function_hpp
+
+/**
+ * Lambda function type.
+ */
+
+#include <iostream>
+#include "gc.hpp"
+
+namespace tuscany {
+
+/**
+ * Debug counters.
+ */
+long int countProxies;
+long int countFProxies = 0;
+long int countCProxies = 0;
+long int countLambdas = 0;
+long int countELambdas = 0;
+long int countCLambdas = 0;
+long int countFLambdas = 0;
+
+bool resetLambdaCounters() {
+ countLambdas = countELambdas = countCLambdas = countFLambdas = countProxies = countFProxies = countCProxies = 0;
+ return true;
+}
+
+bool printLambdaCounters() {
+ std::cout << "countLambdas " << countLambdas << std::endl;
+ std::cout << "countELambdas " << countELambdas << std::endl;
+ std::cout << "countFLambdas " << countFLambdas << std::endl;
+ std::cout << "countCLambdas " << countCLambdas << std::endl;
+ std::cout << "countProxies " << countProxies << std::endl;
+ std::cout << "countFProxies " << countFProxies << std::endl;
+ std::cout << "countCProxies " << countCProxies << std::endl;
+ return true;
+}
+
+/**
+ * Lambda function type.
+ */
+
+template<typename R, typename... P> class Callable {
+public:
+ unsigned int refCount;
+
+ Callable() : refCount(0) {
+ }
+
+ virtual const int size() const = 0;
+
+ virtual const R operator()(P... p) const = 0;
+
+ virtual ~Callable() {
+ }
+
+ unsigned int acquire() {
+ return __sync_add_and_fetch(&refCount, 1);
+ }
+
+ unsigned int release() {
+ return __sync_sub_and_fetch(&refCount, 1);
+ }
+
+ template<typename F> class Proxy: public Callable {
+ public:
+ explicit Proxy(const F& f) : function(f) {
+ countProxies++;
+ countFProxies ++;
+ }
+
+ explicit Proxy(const Proxy& p) : function(p.function) {
+ countProxies++;
+ countCProxies ++;
+ }
+
+ ~Proxy() {
+ countProxies--;
+ }
+
+ virtual const R operator() (P... p) const {
+ return function(std::forward<P>(p)...);
+ }
+
+ virtual const int size() const {
+ return sizeof(function);
+ }
+
+ private:
+ const F function;
+ };
+
+};
+
+template<typename S> class lambda;
+
+template<typename R, typename... P> class lambda<R(P...)> {
+public:
+ lambda() : callable(0) {
+ countLambdas++;
+ countELambdas++;
+ }
+
+ template<typename F> explicit lambda(const F f) : callable(0) {
+ typedef typename CallableType::template Proxy<F> ProxyType;
+
+ countLambdas++;
+ countFLambdas++;
+ callable = gc_counting_ptr<CallableType>(new ProxyType(f));
+ }
+
+ lambda(const lambda& l) {
+ countLambdas++;
+ countCLambdas++;
+ callable = l.callable;
+ }
+
+ const lambda& operator=(const lambda& l) {
+ if (this == &l)
+ return *this;
+ callable = l.callable;
+ return *this;
+ }
+
+ ~lambda() {
+ countLambdas--;
+ }
+
+ const bool operator==(const lambda& l) const {
+ if (this == &l)
+ return true;
+ return callable == l.callable;
+ }
+
+ const bool operator!=(const lambda& l) const {
+ return !this->operator==(l);
+ }
+
+ const R operator()(P... p) const {
+ return (*callable)(std::forward<P>(p)...);
+ }
+
+ template<typename S> friend std::ostream& operator<<(std::ostream&, const lambda<S>&);
+
+private:
+ typedef Callable<R,P...> CallableType;
+ gc_counting_ptr<CallableType> callable;
+};
+
+template<typename S> std::ostream& operator<<(std::ostream& out, const lambda<S>& l) {
+ return out << "lambda::" << l.callable;
+}
+
+/**
+ * Creates a lambda function from a pointer to a function.
+ */
+template<typename R, typename... P> lambda<R(P...)> makeLambda(const R (* const f)(P...)) {
+ return lambda<R(P...)>(f);
+}
+
+/**
+ * Curry a lambda function.
+ */
+template<typename R, typename T, typename... P> class curried {
+public:
+ curried(const lambda<R(T, P...)>& f, const T& v): v(v), f(f) {
+ }
+
+ const R operator()(P... p) const {
+ return f(v, std::forward<P>(p)...);
+ }
+
+private:
+ const T v;
+ const lambda<R(T, P...)>f;
+};
+
+template<typename R, typename T, typename... P> const lambda<R(P...)> curry(const lambda<R(T, P...)>& f, const T& t) {
+ return (lambda<R(P...)>)curried<R, T, P...>(f, t);
+}
+
+template<typename R, typename T, typename U, typename... P> const lambda<R(P...)> curry(const lambda<R(T, U, P...)>& f, const T& t, const U& u) {
+ return curry(curry(f, t), u);
+}
+
+template<typename R, typename T, typename U, typename V, typename... P> const lambda<R(P...)> curry(const lambda<R(T, U, P...)>& f, const T& t, const U& u, const V& v) {
+ return curry(curry(curry(f, t), u), v);
+}
+
+/**
+ * A lambda function that returns the given value.
+ */
+template<typename T> class unitReturn {
+public:
+ explicit unitReturn(const T& v) :
+ v(v) {
+ }
+ const T operator()() const {
+ return v;
+ }
+private:
+ const T v;
+};
+
+template<typename T> const lambda<T()> unit(const T& v) {
+ return lambda<T()> (unitReturn<T> (v));
+}
+
+}
+#endif /* tuscany_function_hpp */
diff --git a/cpp/sca/kernel/gc.hpp b/cpp/sca/kernel/gc.hpp
new file mode 100644
index 0000000000..b0ed42a474
--- /dev/null
+++ b/cpp/sca/kernel/gc.hpp
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_gc_hpp
+#define tuscany_gc_hpp
+
+/**
+ * Garbage collected pointer.
+ */
+
+#include <iostream>
+
+namespace tuscany
+{
+
+template<typename T> class gc_ptr {
+public:
+ explicit gc_ptr(T* p = 0) throw() : countingRef(p == 0? 0 : new CountingRef(p)) {
+ }
+
+ ~gc_ptr() throw() {
+ release();
+ }
+
+ gc_ptr(const gc_ptr& r) throw() : countingRef(r.countingRef) {
+ acquire(r.countingRef);
+ }
+
+ gc_ptr& operator=(const gc_ptr& r) throw() {
+ if(this == &r)
+ return *this;
+ acquire(r.countingRef);
+ release();
+ countingRef = r.countingRef;
+ return *this;
+ }
+
+ const bool operator==(const gc_ptr& r) const throw() {
+ if (this == &r)
+ return true;
+ if (countingRef == NULL)
+ return r.countingRef == NULL;
+ if (r.countingRef == NULL)
+ return false;
+ return countingRef-> ptr == r.countingRef->ptr;
+ }
+
+ const bool operator!=(const gc_ptr& r) const throw() {
+ return !this->operator ==(r);
+ }
+
+ T& operator*() const throw() {
+ return *countingRef->ptr;
+ }
+
+ T* operator->() const throw() {
+ return countingRef->ptr;
+ }
+
+ operator T*() const throw() {
+ return countingRef->ptr;
+ }
+
+ template<typename X> friend std::ostream& operator<<(std::ostream&, const gc_ptr<X>&);
+
+private:
+ struct CountingRef {
+ T* ptr;
+ unsigned count;
+
+ CountingRef(T* p) throw() :
+ ptr(p), count(1) {
+ }
+ }* countingRef;
+
+ void acquire(CountingRef* ref) throw() {
+ if(ref)
+ __sync_add_and_fetch(&ref->count, 1);
+ }
+
+ void release() throw() {
+ if(countingRef) {
+ unsigned rc = __sync_sub_and_fetch(&countingRef->count, 1);
+ if(rc == 0) {
+ delete countingRef->ptr;
+ delete countingRef;
+ }
+ }
+ }
+};
+
+template<typename T> std::ostream& operator<<(std::ostream& out, const gc_ptr<T>& p) {
+ return out << p.countingRef->ptr;
+}
+
+/**
+ * Garbage collected pointer to an array.
+ */
+template<typename T> class gc_aptr {
+public:
+ explicit gc_aptr(T* p = 0) throw() : countingRef(p == 0? 0 : new CountingRef(p)) {
+ }
+
+ ~gc_aptr() throw() {
+ release();
+ }
+
+ gc_aptr(const gc_aptr& r) throw() : countingRef(r.countingRef) {
+ acquire(r.countingRef);
+ }
+
+ gc_aptr& operator=(const gc_aptr& r) throw() {
+ if(this == &r)
+ return *this;
+ acquire(r.countingRef);
+ release();
+ countingRef = r.countingRef;
+ return *this;
+ }
+
+ const bool operator==(const gc_aptr& r) const throw() {
+ if (this == &r)
+ return true;
+ if (countingRef == NULL)
+ return r.countingRef == NULL;
+ if (r.countingRef == NULL)
+ return false;
+ return countingRef-> ptr == r.countingRef->ptr;
+ }
+
+ const bool operator!=(const gc_aptr& r) const throw() {
+ return !this->operator ==(r);
+ }
+
+ T& operator*() const throw() {
+ return *countingRef->ptr;
+ }
+
+ T* operator->() const throw() {
+ return countingRef->ptr;
+ }
+
+ operator T*() const throw() {
+ return countingRef->ptr;
+ }
+
+ template<typename X> friend std::ostream& operator<<(std::ostream&, const gc_aptr<X>&);
+
+private:
+ struct CountingRef {
+ T* ptr;
+ unsigned count;
+
+ CountingRef(T* p) throw() :
+ ptr(p), count(1) {
+ }
+ }* countingRef;
+
+ void acquire(CountingRef* ref) throw() {
+ if(ref)
+ __sync_add_and_fetch(&ref->count, 1);
+ }
+
+ void release() throw() {
+ if(countingRef) {
+ unsigned rc = __sync_sub_and_fetch(&countingRef->count, 1);
+ if(rc == 0) {
+ delete[] countingRef->ptr;
+ delete countingRef;
+ }
+ }
+ }
+};
+
+template<typename T> std::ostream& operator<<(std::ostream& out, const gc_aptr<T>& p) {
+ return out << p.countingRef->ptr;
+}
+
+/**
+ * Garbage collected pointer to a reference counting object.
+ */
+template<typename T> class gc_counting_ptr {
+public:
+ explicit gc_counting_ptr(T* p = 0) throw() : ptr(p) {
+ acquire(p);
+ }
+
+ ~gc_counting_ptr() throw() {
+ release();
+ }
+
+ gc_counting_ptr(const gc_counting_ptr& r) throw() : ptr(r.ptr) {
+ acquire(ptr);
+ }
+
+ gc_counting_ptr& operator=(const gc_counting_ptr& r) throw() {
+ if(this == &r)
+ return *this;
+ acquire(r.ptr);
+ release();
+ ptr = r.ptr;
+ return *this;
+ }
+
+ const bool operator==(const gc_counting_ptr& r) const throw() {
+ if (this == &r)
+ return true;
+ return ptr == r.ptr;
+ }
+
+ const bool operator!=(const gc_counting_ptr& r) const throw() {
+ return !this->operator ==(r);
+ }
+
+ T& operator*() const throw() {
+ return *ptr;
+ }
+
+ T* operator->() const throw() {
+ return ptr;
+ }
+
+ operator T*() const throw() {
+ return ptr;
+ }
+
+ template<typename X> friend std::ostream& operator<<(std::ostream&, const gc_counting_ptr<X>&);
+
+private:
+ T* ptr;
+
+ void acquire(T* p) throw() {
+ if(p)
+ p->acquire();
+ }
+
+ void release() throw() {
+ if(ptr) {
+ if(ptr->release() == 0) {
+ delete ptr;
+ }
+ }
+ }
+};
+
+template<typename T> std::ostream& operator<<(std::ostream& out, const gc_counting_ptr<T>& p) {
+ return out << p.ptr;
+}
+
+}
+#endif /* tuscany_gc_hpp */
diff --git a/cpp/sca/kernel/kernel-test.cpp b/cpp/sca/kernel/kernel-test.cpp
new file mode 100644
index 0000000000..3e2793f070
--- /dev/null
+++ b/cpp/sca/kernel/kernel-test.cpp
@@ -0,0 +1,444 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+/**
+ * Test core utils.
+ */
+
+#include <assert.h>
+#include <sys/time.h>
+#include <time.h>
+#include <iostream>
+#include <string>
+#include <sstream>
+#include "function.hpp"
+#include "list.hpp"
+#include "parallel.hpp"
+#include "value.hpp"
+#include "xml.hpp"
+
+namespace tuscany {
+
+struct inc {
+ int i;
+ inc(int i) :
+ i(i) {
+ }
+ const int operator()(const int x) const {
+ return x + i;
+ }
+};
+
+const int square(const int x) {
+ return x * x;
+}
+
+bool testFunction() {
+ const lambda<int(int)> sq(square);
+ assert(sq(2) == 4);
+
+ const lambda<int(int i)> incf(inc(10));
+ assert(incf(1) == 11);
+ return true;
+}
+
+bool testFunctionGC() {
+ resetLambdaCounters();
+ testFunction();
+ assert(countLambdas == 0);
+ return true;
+}
+
+int countElements = 0;
+
+struct Element {
+ int i;
+
+ Element() :
+ i(0) {
+ countElements++;
+ }
+
+ Element(int i) :
+ i(i) {
+ countElements++;
+ }
+
+ Element(const Element& o) :
+ i(o.i) {
+ countElements++;
+ }
+
+ ~Element() {
+ countElements--;
+ }
+
+ const bool operator==(const Element& o) const {
+ return o.i == i;
+ }
+};
+
+bool testCons() {
+ assert(car(cons(2, makeList(3))) == 2);
+ assert(car(cdr(cons(2, makeList(3)))) == 3);
+ assert(isNil(cdr(cdr(cons(2, makeList(3))))));
+
+ assert(cons(Element(1), makeList(Element(2))) == makeList(Element(1), Element(2)));
+ return true;
+}
+
+bool testlistGC() {
+ resetLambdaCounters();
+ resetlistCounters();
+ countElements = 0;
+ testCons();
+ assert(countLambdas == 0);
+ assert(countlists == 0);
+ assert(countElements == 0);
+ return true;
+}
+
+bool testOut() {
+ std::ostringstream os1;
+ os1 << list<int> ();
+ assert(os1.str() == "()");
+
+ std::ostringstream os2;
+ os2 << makeList(1, 2, 3);
+ assert(os2.str() == "(1, (2, (3, ())))");
+ return true;
+}
+
+bool testEquals() {
+ assert(list<int>() == list<int>());
+ assert(makeList(1, 2) == makeList(1, 2));
+ assert(list<int>() != makeList(1, 2));
+ assert(makeList(1, 2, 3) == makeList(1, 2, 3));
+ assert(makeList(1, 2) != makeList(1, 2, 3));
+ return true;
+}
+
+bool testLength() {
+ assert(0 == length(list<int>()));
+ assert(1 == length(makeList(1)));
+ assert(2 == length(cons(1, makeList(2))));
+ return true;
+}
+
+bool testAppend() {
+ assert(car(append(makeList(1), makeList(2))) == 1);
+ assert(car(cdr(append(makeList(1), makeList(2)))) == 2);
+ assert(car(cdr(cdr(append(makeList(1), makeList(2, 3))))) == 3);
+ assert(isNil(cdr(cdr(cdr(append(makeList(1), makeList(2, 3)))))));
+ return true;
+}
+
+struct Complex {
+ int x;
+ int y;
+ Complex() {
+ }
+ Complex(int x, int y) :
+ x(x), y(y) {
+ }
+};
+
+bool testComplex() {
+ const list<Complex> p = makeList(Complex(1, 2), Complex(3, 4));
+ assert(car(p).x == 1);
+ assert(car(cdr(p)).x == 3);
+ assert(isNil(cdr(cdr(p))));
+ return true;
+}
+
+bool testMap() {
+ assert(isNil(map((lambda<int(int)>)square, list<int>())));
+
+ const list<int> m = map((lambda<int(int)> )square, makeList(2, 3));
+ assert(car(m) == 4);
+ assert(car(cdr(m)) == 9);
+
+ return true;
+}
+
+const int add(const int x, const int y) {
+ return x + y;
+}
+
+bool testReduce() {
+ const lambda<int(int, int)> r(add);
+ assert(reduce(r, 0, makeList(1, 2, 3)) == 6);
+ return true;
+}
+
+bool isPositive(int x) {
+ if(x >= 0)
+ return true;
+ else
+ return false;
+}
+
+bool testFilter() {
+ lambda<bool(int)> f(isPositive);
+ assert(car(filter(f, makeList(1, -1, 2, -2))) == 1);
+ assert(cadr(filter(f, makeList(1, -1, 2, -2))) == 2);
+ return true;
+}
+
+bool testMember() {
+ assert(isNil(member(4, makeList(1, 2, 3))));
+ assert(car(member(1, makeList(1, 2, 3))) == 1);
+ assert(car(member(2, makeList(1, 2, 3))) == 2);
+ assert(car(member(3, makeList(1, 2, 3))) == 3);
+ return true;
+}
+
+bool testReverse() {
+ assert(isNil(reverse(list<int>())));
+ assert(car(reverse(makeList(1, 2, 3))) == 3);
+ assert(cadr(reverse(makeList(1, 2, 3))) == 2);
+ return true;
+}
+
+double testSeqMap(double x) {
+ return x;
+}
+
+double testSeqReduce(double v, double accum) {
+ return accum + 1.0;
+}
+
+bool testSeq() {
+ //resetLambdaCounters();
+ //resetlistCounters();
+
+ list<double> s = seq(0.0, 1000.0);
+ assert(1001 == length(s));
+ //printLambdaCounters();
+ //printlistCounters();
+
+ assert(1001 == length(map(lambda<double(double)>(testSeqMap), s)));
+
+ assert(801 == length(member(200.0, s)));
+ assert(201 == length(member(200.0, reverse(s))));
+
+ assert(1001 == reduce(lambda<double(double, double)>(testSeqReduce), 0.0, s));
+ //printLambdaCounters();
+ //printlistCounters();
+
+ return true;
+}
+
+value valueSquare(list<value> x) {
+ return value((int)car(x) * (int)car(x));
+}
+
+bool testValue() {
+ assert(value(true) == value(true));
+ assert(value(1) == value(1));
+ assert(value("abcd") == value("abcd"));
+ lambda<value(list<value>&)> vl(valueSquare);
+ assert(value(vl) == value(vl));
+ assert(value(makeList(value(1), value(2))) == value(makeList(value(1), value(2))));
+ return true;
+}
+
+bool testValueGC() {
+ resetValueCounters();
+ resetLambdaCounters();
+ resetlistCounters();
+ testValue();
+ assert(countValues == 0);
+ assert(countLambdas == 0);
+ assert(countlists == 0);
+ return true;
+}
+
+double fib_aux(double n, double a, double b) {
+ if(n == 0.0)
+ return a;
+ return fib_aux(n - 1.0, b, a + b);
+}
+
+double fib(double n) {
+ return fib_aux(n, 0.0, 1.0);
+}
+
+bool testCppPerf() {
+ struct timeval start;
+ struct timeval end;
+ gettimeofday(&start, NULL);
+
+ list<double> s = seq(0.0, 999.0);
+ list<double> r = map((lambda<double(double)> )fib, s);
+ assert(1000 == length(r));
+
+ gettimeofday(&end, NULL);
+ long t = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000);
+ //std::cout << "Fib cpp perf test " << t << " ms" << std::endl;
+ return true;
+}
+
+bool testAtomicPerf() {
+ struct timeval start;
+ struct timeval end;
+ {
+ gettimeofday(&start, NULL);
+ for(int i = 0; i < 10000000;)
+ i = i + 1;
+ gettimeofday(&end, NULL);
+ long t = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000);
+ //std::cout << "Loop test " << t << " ms" << std::endl;
+ }
+ {
+ gettimeofday(&start, NULL);
+ for(int i = 0; i < 10000000;)
+ __sync_add_and_fetch(&i, 1);
+ gettimeofday(&end, NULL);
+ long t = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000);
+ //std::cout << "Loop atomic test " << t << " ms" << std::endl;
+ }
+ {
+ pthread_mutex_t mutex;
+ pthread_mutex_init(&mutex, NULL);
+ gettimeofday(&start, NULL);
+ for(int i = 0; i < 10000000;) {
+ pthread_mutex_lock(&mutex);
+ i = i + 1;
+ pthread_mutex_unlock(&mutex);
+ }
+ gettimeofday(&end, NULL);
+ pthread_mutex_destroy(&mutex);
+ long t = (end.tv_sec * 1000 + end.tv_usec / 1000) - (start.tv_sec * 1000 + start.tv_usec / 1000);
+ //std::cout << "Loop mutex test " << t << " ms" << std::endl;
+ }
+ return true;
+}
+
+const int mtsquare(const int x) {
+ //std::cout << "thread " << threadId() << " mtsquare(" << x << ")\n";
+ for(int i = 0; i < 10000000; i++)
+ ;
+ return x * x;
+}
+
+bool testWorker() {
+ worker w(10);
+ {
+ const lambda<int()> func = curry(lambda<int(int)> (mtsquare), 2);
+ assert(submit(w, func) == 4);
+ }
+ {
+ const int max = 10;
+
+ list<future<int> > r;
+ for(int i = 0; i < max; i++) {
+ const lambda<int()> func = curry(lambda<int(int)> (mtsquare), i);
+ r = cons(submit(w, func), r);
+ }
+ for(int i = max - 1; i >= 0; i--) {
+ assert(car(r) == i * i);
+ r = cdr(r);
+ }
+ }
+ shutdown(w);
+ return true;
+}
+
+const std::string currencyXML =
+"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+"<composite xmlns=\"http://docs.oasis-open.org/ns/opencsa/sca/200903\" "
+"xmlns:t=\"http://tuscany.apache.org/xmlns/sca/1.1\" "
+"targetNamespace=\"http://services\" "
+"name=\"currency\">"
+"<component name=\"CurrencyConverterWebService\">"
+"<implementation.java class=\"services.CurrencyConverterImpl\"/>"
+"<service name=\"CurrencyConverter\">"
+"<binding.ws/>"
+"</service>"
+"</component>"
+"<component name=\"CurrencyConverterWebService2\">"
+"<implementation.java class=\"services.CurrencyConverterImpl2\"/>"
+"<service name=\"CurrencyConverter2\">"
+"<binding.atom/>"
+"</service>"
+"</component>"
+"</composite>"
+"\n";
+
+const bool isName(const value& token) {
+ return isAttribute(token) && attributeName(token) == "name";
+}
+
+bool testReadXML() {
+ std::istringstream is(currencyXML);
+ const list<value> currency = value(readXML(is));
+
+ const value composite = car(currency);
+ assert(isElement(composite));
+ assert(elementName(composite) == "composite");
+ assert(!elementHasText(composite));
+
+ assert(attributeText(car(filter(lambda<bool(value)>(isName), elementChildren(composite)))) == "currency");
+ return true;
+}
+
+bool testWriteXML() {
+ std::istringstream is(currencyXML);
+ const list<value> currency = value(readXML(is));
+ std::ostringstream os;
+ writeXML(currency, os);
+ assert(os.str() == currencyXML);
+ return true;
+}
+
+}
+
+int main() {
+ std::cout << "Testing..." << std::endl;
+
+ tuscany::testFunction();
+ tuscany::testFunctionGC();
+ tuscany::testCons();
+ tuscany::testlistGC();
+ tuscany::testOut();
+ tuscany::testEquals();
+ tuscany::testLength();
+ tuscany::testAppend();
+ tuscany::testComplex();
+ tuscany::testMap();
+ tuscany::testReduce();
+ tuscany::testFilter();
+ tuscany::testMember();
+ tuscany::testReverse();
+ tuscany::testSeq();
+ tuscany::testValue();
+ tuscany::testValueGC();
+ tuscany::testCppPerf();
+ tuscany::testAtomicPerf();
+ tuscany::testWorker();
+ tuscany::testReadXML();
+ tuscany::testWriteXML();
+
+ std::cout << "OK" << std::endl;
+
+ return 0;
+}
diff --git a/cpp/sca/kernel/list.hpp b/cpp/sca/kernel/list.hpp
new file mode 100644
index 0000000000..ef493b19ca
--- /dev/null
+++ b/cpp/sca/kernel/list.hpp
@@ -0,0 +1,379 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_list_hpp
+#define tuscany_list_hpp
+
+/**
+ * Simple list functions.
+ */
+
+#include <iostream>
+#include "function.hpp"
+
+namespace tuscany {
+
+long countlists = 0;
+long countIlists = 0;
+long countClists = 0;
+long countElists = 0;
+
+bool resetlistCounters() {
+ countlists = countIlists = countClists = countElists = 0;
+ return true;
+}
+
+bool printlistCounters() {
+ std::cout << "countlists " << countlists << std::endl;
+ std::cout << "countElists " << countElists << std::endl;
+ std::cout << "countIlists " << countIlists << std::endl;
+ std::cout << "countClists " << countClists << std::endl;
+ return true;
+}
+
+/**
+ * A car/cdr lisp-like pair, base structure to construct lists.
+ */
+
+template<typename T> class list {
+public:
+
+ list(const T car, const lambda<list<T> ()>& cdr) :
+ nil(false), car(car), cdr(cdr) {
+ countlists++;
+ countIlists++;
+ }
+
+ list() :
+ nil(true) {
+ countlists++;
+ countElists++;
+ }
+
+ list(const list& p) :
+ nil(p.nil), car(p.car), cdr(p.cdr) {
+ countlists++;
+ countClists++;
+ }
+
+ const list& operator=(const list<T>& p) {
+ if(this == &p)
+ return *this;
+ nil = p.nil;
+ car = p.car;
+ cdr = p.cdr;
+ return *this;
+ }
+
+ ~list() {
+ countlists--;
+ }
+
+ const bool operator==(const list<T>& p) const {
+ if(this == &p)
+ return true;
+ if(nil)
+ return p.nil;
+ if(p.nil)
+ return false;
+ if(!(car == p.car))
+ return false;
+ if(cdr == p.cdr)
+ return true;
+ return cdr() == p.cdr();
+ }
+
+ const bool operator!=(const list<T>& p) const {
+ return !this->operator==(p);
+ }
+
+ template<typename X> friend std::ostream& operator<<(std::ostream&, const list<X>&);
+
+ bool nil;
+ T car;
+ lambda<list<T> ()> cdr;
+};
+
+/**
+ * Returns true if the given list is nil.
+ */
+template<typename T> const bool isNil(const list<T>& p) {
+ return p.nil;
+}
+
+/**
+ * Write a list to an output stream.
+ */
+template<typename X> std::ostream& operator<<(std::ostream& out, const list<X>& l) {
+ if(l == list<X> ())
+ return out << "()";
+ return out << "(" << car(l) << ", " << cdr(l) << ")";
+}
+
+/**
+ * Construct a (lazy) list from a value and a lambda function that returns the cdr.
+ */
+template<typename T> const list<T> cons(const T& car, const lambda<list<T> ()>& cdr) {
+ return list<T> (car, cdr);
+}
+
+/**
+ * Construct a list from a value and a cdr list.
+ */
+template<typename T> const list<T> cons(const T& car, const list<T>& cdr) {
+ return list<T> (car, unit(cdr));
+}
+
+/**
+ * Construct a list of one value.
+ */
+template<typename T> const list<T> makeList(const T& car) {
+ return list<T> (car, unit(list<T> ()));
+}
+
+/**
+ * Construct a list of two values.
+ */
+template<typename T> const list<T> makeList(const T& a, const T& b) {
+ return cons(a, makeList(b));
+}
+
+/**
+ * Construct a list of three values.
+ */
+template<typename T> const list<T> makeList(const T& a, const T& b, const T& c) {
+ return cons(a, cons(b, makeList(c)));
+}
+
+/**
+ * Construct a list of four values.
+ */
+template<typename T> const list<T> makeList(const T& a, const T& b, const T& c, const T& d) {
+ return cons(a, cons(b, cons(c, makeList(d))));
+}
+
+/**
+ * Returns the car of a list.
+ */
+template<typename T> const T car(const list<T>& p) {
+ return p.car;
+}
+
+/**
+ * Returns the cdr of a list.
+ */
+template<typename T> list<T> const cdr(const list<T>& p) {
+ return p.cdr();
+}
+
+/**
+ * Returns the car of the cdr of a list.
+ */
+template<typename T> const T cadr(const list<T>& p) {
+ return car(cdr(p));
+}
+
+/**
+ * Returns the car of the cdr of the cdr of a list.
+ */
+template<typename T> const T caddr(const list<T>& p) {
+ return car(cdr(cdr(p)));
+}
+
+/**
+ * Returns the cdr of a cdr of a list.
+ */
+template<typename T> const list<T> cddr(const list<T>& p) {
+ return cdr(cdr(p));
+}
+
+/**
+ * Returns the cdr of a cdr of the cdr of a list.
+ */
+template<typename T> const list<T> cdddr(const list<T>& p) {
+ return cdr(cdr(cdr(p)));
+}
+
+/**
+ * Returns the length of a list.
+ */
+template<typename T> struct lengthRef {
+ const int operator()(const int c, const list<T>& p) {
+ if(isNil(p))
+ return c;
+ return (*this)(c + 1, cdr(p));
+ }
+};
+
+template<typename T> const int length(const list<T>& p) {
+ return lengthRef<T> ()(0, p);
+}
+
+/**
+ * Appends a list and a lambda function returning a list.
+ */
+template<typename T> struct appendCdr {
+ const list<T> a;
+ const lambda<list<T> ()> fb;
+ appendCdr(const list<T>& a, const lambda<list<T> ()>& fb) :
+ a(a), fb(fb) {
+ }
+ const list<T> operator()() const {
+ return append(a, fb);
+ }
+};
+
+template<typename T> const list<T> append(const list<T>&a, const lambda<list<T> ()>& fb) {
+ if(isNil(a))
+ return fb();
+
+ return cons(car(a), lambda<list<T> ()> (appendCdr<T> (cdr(a), fb)));
+}
+
+/**
+ * Appends two lists.
+ */
+template<typename T> const list<T> append(const list<T>&a, const list<T>& b) {
+ return append(a, unit(b));
+}
+
+/**
+ * Map a lambda function on a list.
+ */
+template<typename T, typename R> const list<R> map(const lambda<R(T)>& f, const list<T>& p) {
+ if(isNil(p))
+ return list<R> ();
+ return cons(f(car(p)), map(f, cdr(p)));
+}
+
+/**
+ * Run a reduce lambda function on a list.
+ */
+template<typename T, typename R> struct reduceAccumulate {
+ const lambda<R(R, T)> f;
+ explicit reduceAccumulate(const lambda<R(R, T)>& f) :
+ f(f) {
+ }
+ R operator()(const R& acc, const list<T>& p) const {
+ if(isNil(p))
+ return acc;
+ return (*this)(f(acc, car(p)), cdr(p));
+ }
+};
+
+template<typename T, typename R> const R reduce(const lambda<R(R, T)>& f, const R& initial, const list<T>& p) {
+ return reduceAccumulate<T, R> (f)(initial, p);
+}
+
+/**
+ * Run a filter lambda function on a list.
+ */
+template<typename T> const list<T> filter(const lambda<bool(T)>& f, const list<T>& p) {
+ if(isNil(p))
+ return list<T> ();
+ if(f(car(p))) {
+ const lambda<list<T> (lambda<bool(T)> , list<T> )> ff(filter<T> );
+ return cons(car(p), curry(ff, f, cdr(p)));
+ }
+ return filter(f, cdr(p));
+}
+
+/**
+ * Returns a list pointing to a member of a list.
+ */
+template<typename T> const list<T> member(const T& t, const list<T>& p) {
+ if(isNil(p))
+ return list<T> ();
+ if(t == car(p))
+ return p;
+ return member(t, cdr(p));
+}
+
+/**
+ * Reverse a list.
+ */
+template<typename T> const list<T> reverseIter(const list<T>& acc, const list<T>& p) {
+ if(isNil(p))
+ return acc;
+ return reverseIter(cons(car(p), acc), cdr(p));
+}
+
+template<typename T> const list<T> reverse(const list<T>& p) {
+ return reverseIter(list<T> (), p);
+}
+
+template<typename T> const list<T> seq(const T& start, const T& end);
+
+template<typename T> struct seqGenerate {
+ const T start;
+ const T end;
+ seqGenerate(const T& start, const T&end) :
+ start(start), end(end) {
+ }
+ const list<T> operator()() const {
+ return seq<T> (start, end);
+ }
+};
+
+/**
+ * Returns a sequence of values between the given bounds.
+ */
+template<typename T> const list<T> seq(const T& start, const T& end) {
+ if(start == end)
+ return makeList(start);
+ if(start < end)
+ return cons(start, lambda<list<T> ()> (seqGenerate<T> (start + 1, end)));
+ return cons(start, lambda<list<T> ()> (seqGenerate<T> (start - 1, end)));
+}
+
+/**
+ * Equivalent of the list assoc function.
+ */
+template<typename T> const list<T> assoc(const T& k, const list<list<T> >& p) {
+ if(isNil(p))
+ return list<T> ();
+ if(k == car(car(p)))
+ return car(p);
+ return assoc(k, cdr(p));
+}
+
+/**
+ * Pretty print a list.
+ */
+template<typename T> std::ostream& print(const list<T>& l, std::ostream& os) {
+ os << "(";
+ if (!isNil(l)) {
+ list<T> ml = l;
+ while(true) {
+ os << car(ml);
+ ml = cdr(ml);
+ if (isNil(ml))
+ break;
+ os << ", ";
+ }
+ }
+ os << ")";
+ return os;
+}
+
+}
+
+#endif /* tuscany_list_hpp */
diff --git a/cpp/sca/kernel/parallel.hpp b/cpp/sca/kernel/parallel.hpp
new file mode 100644
index 0000000000..c0d578e281
--- /dev/null
+++ b/cpp/sca/kernel/parallel.hpp
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_parallel_hpp
+#define tuscany_parallel_hpp
+
+/**
+ * Simple parallel work execution functions.
+ */
+
+#include <pthread.h>
+#include <sys/syscall.h>
+#include "function.hpp"
+
+namespace tuscany {
+
+/**
+ * Returns the current thread id.
+ */
+unsigned int threadId() {
+ return syscall(__NR_gettid);
+}
+
+/**
+ * Represents a value which will be know in the future.
+ */
+template<typename T> class future {
+
+private:
+ template<typename X> class futureValue {
+ public:
+ futureValue() :
+ refCount(0), hasValue(false) {
+ pthread_mutex_init(&valueMutex, NULL);
+ pthread_cond_init(&valueCond, NULL);
+ }
+
+ ~futureValue() {
+ pthread_mutex_destroy(&valueMutex);
+ pthread_cond_destroy(&valueCond);
+ }
+
+ unsigned int acquire() {
+ return __sync_add_and_fetch(&refCount, 1);
+ }
+
+ unsigned int release() {
+ return __sync_sub_and_fetch(&refCount, 1);
+ }
+
+ bool set(const T& v) {
+ pthread_mutex_lock(&valueMutex);
+ if(hasValue) {
+ pthread_mutex_unlock(&valueMutex);
+ return false;
+ }
+ hasValue = true;
+ value = v;
+ pthread_mutex_unlock(&valueMutex);
+ pthread_cond_broadcast(&valueCond);
+ return true;
+ }
+
+ const T get() {
+ pthread_mutex_lock(&valueMutex);
+ while(!hasValue) {
+ pthread_cond_wait(&valueCond, &valueMutex);
+ }
+ const T& v = value;
+ pthread_mutex_unlock(&valueMutex);
+ return v;
+ }
+
+ private:
+ unsigned refCount;
+ pthread_mutex_t valueMutex;
+ pthread_cond_t valueCond;
+ bool hasValue;
+ X value;
+ };
+
+ gc_counting_ptr<futureValue<T> > fvalue;
+
+ template<typename X> friend const X get(const future<X>& f);
+ template<typename X> friend bool set(const future<X>& f, const X& v);
+
+public:
+ future() : fvalue(new futureValue<T>()) {
+ //std::cout << "future() threadId " << threadId() << "\n";
+ }
+
+ ~future() {
+ //std::cout << "~future() threadId " << threadId() << "\n";
+ }
+
+ future(const future& f) : fvalue(f.fvalue) {
+ //std::cout << "future(const future& f) threadId " << threadId() << "\n";
+ }
+
+ const future& operator=(const future& f) {
+ //std::cout << "future::operator=(const future& f) threadId " << threadId() << "\n";
+ if (&f == this)
+ return *this;
+ fvalue = f.fvalue;
+ return *this;
+ }
+
+ const future& operator=(const T& v) const {
+ fvalue->set(v);
+ return *this;
+ }
+
+ operator const T() const {
+ return fvalue->get();
+ }
+
+};
+
+/**
+ * A bounded thread safe queue.
+ */
+template<typename T> class queue {
+public:
+ explicit queue(int max) : max(max), size(0), tail(0), head(0), values(new T[max]) {
+ pthread_mutex_init(&mutex, NULL);
+ pthread_cond_init(&full, NULL);
+ pthread_cond_init(&empty, NULL);
+ }
+
+ ~queue() {
+ pthread_mutex_destroy(&mutex);
+ pthread_cond_destroy(&full);
+ pthread_cond_destroy(&empty);
+ }
+
+private:
+ const int max;
+ int size;
+ int tail;
+ int head;
+ pthread_mutex_t mutex;
+ pthread_cond_t full;
+ pthread_cond_t empty;
+ gc_aptr<T> values;
+
+ template<typename X> friend const int enqueue(queue<X>& q, const X& v);
+ template<typename X> friend const X dequeue(queue<X>& q);
+};
+
+/**
+ * Adds an element to the tail of the queue.
+ */
+template<typename T> const int enqueue(queue<T>&q, const T& v) {
+ pthread_mutex_lock(&q.mutex);
+ while(q.size == q.max)
+ pthread_cond_wait(&q.full, &q.mutex);
+ q.values[q.tail] = v;
+ q.tail = (q.tail + 1) % q.max;
+ q.size++;
+ pthread_mutex_unlock(&q.mutex);
+ pthread_cond_broadcast(&q.empty);
+ return q.size;
+}
+
+/**
+ * Returns the element at the head of the queue.
+ */
+template<typename T> const T dequeue(queue<T>& q) {
+ pthread_mutex_lock(&q.mutex);
+ while(q.size == 0)
+ pthread_cond_wait(&q.empty, &q.mutex);
+ const T v = q.values[q.head];
+ q.head = (q.head + 1) % q.max;
+ q.size--;
+ pthread_mutex_unlock(&q.mutex);
+ pthread_cond_broadcast(&q.full);
+ return v;
+}
+
+/**
+ * The worker thread function.
+ */
+void *workerThreadFunc(void *arg) {
+ queue<lambda<bool()> >* work = reinterpret_cast<queue<lambda<bool()> >*>(arg);
+ while(dequeue(*work)())
+ ;
+ return NULL;
+}
+
+/**
+ * Returns a list of worker threads.
+ */
+const list<pthread_t> makeWorkerThreads(queue<lambda<bool()> >& queue, const int count) {
+ if (count == 0)
+ return list<pthread_t>();
+ pthread_t thread;
+ pthread_create(&thread, NULL, workerThreadFunc, &queue);
+ return cons(thread, makeWorkerThreads(queue, count - 1));
+}
+
+/**
+ * A worker, implemented with a work queue and a pool of threads.
+ */
+class worker {
+public:
+ explicit worker(int max) : work(queue<lambda<bool()> >(max)), threads(makeWorkerThreads(work, max)) {
+ }
+
+private:
+ queue<lambda<bool()> > work;
+ const list<pthread_t> threads;
+
+ template<typename X> friend const future<X> submit(worker& w, const lambda<X()>& func);
+ friend const bool shutdown(worker& w);
+};
+
+/**
+ * Function used to wrap work submitted to a worker.
+ */
+template<typename R> bool submitFunc(const lambda<R()>& func, const future<R>& fut) {
+ fut = func();
+ return true;
+}
+
+/**
+ * Submits work to a worker.
+ */
+template<typename R> const future<R> submit(worker& w, const lambda<R()>& func) {
+ const future<R> fut;
+ const lambda<bool()> f = curry(lambda<bool(lambda<R()>, future<R>)>(submitFunc<R>), func, fut);
+ enqueue(w.work, f);
+ return fut;
+}
+
+/**
+ * Enqueues shutdown requests.
+ */
+const bool shutdownEnqueue(const list<pthread_t>& threads, queue<lambda<bool()> >& work) {
+ if (threads == list<pthread_t>())
+ return true;
+ enqueue(work, unit(false));
+ return shutdownEnqueue(cdr(threads), work);
+}
+
+/**
+ * Waits for shut down threads to terminate.
+ */
+const bool shutdownJoin(const list<pthread_t>& threads) {
+ if (threads == list<pthread_t>())
+ return true;
+ pthread_join(car(threads), NULL);
+ return shutdownJoin(cdr(threads));
+}
+
+/**
+ * Shutdown a worker.
+ */
+const bool shutdown(worker& w) {
+ shutdownEnqueue(w.threads, w.work);
+ shutdownJoin(w.threads);
+ return true;
+}
+
+}
+#endif /* tuscany_parallel_hpp */
diff --git a/cpp/sca/kernel/value.hpp b/cpp/sca/kernel/value.hpp
new file mode 100644
index 0000000000..ca4bd06ca6
--- /dev/null
+++ b/cpp/sca/kernel/value.hpp
@@ -0,0 +1,357 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_value_hpp
+#define tuscany_value_hpp
+
+/**
+ * Generic value type.
+ */
+
+#include <string>
+#include <iostream>
+#include "gc.hpp"
+#include "function.hpp"
+#include "list.hpp"
+
+namespace tuscany
+{
+
+long int countValues = 0;
+long int countEValues = 0;
+long int countCValues = 0;
+long int countVValues = 0;
+
+bool resetValueCounters() {
+ countValues = countEValues = countCValues = countVValues = 0;
+ return true;
+}
+
+bool printValueCounters() {
+ std::cout << "countValues " << countValues << std::endl;
+ std::cout << "countEValues " << countEValues << std::endl;
+ std::cout << "countCValues " << countCValues << std::endl;
+ std::cout << "countVValues " << countVValues << std::endl;
+ return true;
+}
+
+class value;
+
+class value {
+public:
+
+ enum ValueType {
+ Undefined, Symbol, String, List, Number, Boolean, Character, Lambda
+ };
+
+ value() :
+ type(value::Undefined) {
+ countValues++;
+ countEValues++;
+ }
+
+ value(const value& v) {
+ countValues++;
+ countCValues++;
+ type = v.type;
+ switch(type) {
+ case value::List:
+ lst() = v.lst();
+ case value::Lambda:
+ func() = v.func();
+ case value::Symbol:
+ str() = v.str();
+ case value::String:
+ str() = v.str();
+ case value::Number:
+ num() = v.num();
+ case value::Boolean:
+ boo() = v.boo();
+ case value::Character:
+ chr() = v.chr();
+ default:
+ break;
+ }
+ }
+
+ const value& operator=(const value& v) {
+ if(this == &v)
+ return *this;
+ type = v.type;
+ switch(type) {
+ case value::List:
+ lst() = v.lst();
+ case value::Lambda:
+ func() = v.func();
+ case value::Symbol:
+ str() = v.str();
+ case value::String:
+ str() = v.str();
+ case value::Number:
+ num() = v.num();
+ case value::Boolean:
+ boo() = v.boo();
+ case value::Character:
+ chr() = v.chr();
+ default:
+ break;
+ }
+ return *this;
+ }
+
+ virtual ~value() {
+ countValues--;
+ }
+
+ explicit value(const lambda<value(list<value>&)>& func) :
+ type(value::Lambda), data(vdata(func)) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const std::string& str) :
+ type(value::String), data(vdata(unit(str))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const char* str) :
+ type(value::Symbol), data(vdata(unit(std::string(str)))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const list<value>& lst) :
+ type(value::List), data(vdata(unit(lst))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const double num) :
+ type(value::Number), data(vdata(unit(num))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const int num) :
+ type(value::Number), data(vdata(unit((double)num))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const bool boo) :
+ type(value::Boolean), data(vdata(unit(boo))) {
+ countValues++;
+ countVValues++;
+ }
+
+ explicit value(const char chr) :
+ type(value::Character), data(vdata(unit(chr))) {
+ countValues++;
+ countVValues++;
+ }
+
+ const bool operator!=(const value& v) const {
+ return !this->operator==(v);
+ }
+
+ const bool operator==(const value& v) const {
+ if(this == &v)
+ return true;
+ if(type != v.type)
+ return false;
+ switch(type) {
+ case value::Undefined:
+ return true;
+ case value::List:
+ return lst()() == v.lst()();
+ case value::Lambda:
+ return func() == v.func();
+ case value::Symbol:
+ return str()() == v.str()();
+ case value::String:
+ return str()() == v.str()();
+ case value::Number:
+ return num()() == v.num()();
+ case value::Boolean:
+ return boo()() == v.boo()();
+ case value::Character:
+ return chr()() == v.chr()();
+ default:
+ return false;
+ }
+ }
+
+ const value operator()(list<value>& args) const {
+ return func()(args);
+ }
+
+ operator const std::string() const {
+ return str()();
+ }
+
+ operator const double() const {
+ return num()();
+ }
+
+ operator const int() const {
+ return num()();
+ }
+
+ operator const bool() const {
+ return boo()();
+ }
+
+ operator const char() const {
+ return chr()();
+ }
+
+ operator const list<value>() const {
+ return lst()();
+ }
+
+ operator const lambda<value(list<value>&)>() const {
+ return func();
+ }
+
+ friend std::ostream& operator<<(std::ostream&, const value&);
+
+ ValueType type;
+ lambda<char()> data;
+
+private:
+ template<typename T> lambda<T>& vdata() const {
+ return *reinterpret_cast<lambda<T> *> (const_cast<lambda<char()> *> (&data));
+ }
+
+ template<typename T> const lambda<char()>& vdata(const T& v) const {
+ return *reinterpret_cast<const lambda<char()> *> (&v);
+ }
+
+ lambda<double()>& num() const {
+ return vdata<double()> ();
+ }
+
+ lambda<bool()>& boo() const {
+ return vdata<bool()> ();
+ }
+
+ lambda<char()>& chr() const {
+ return vdata<char()> ();
+ }
+
+ lambda<std::string()>& str() const {
+ return vdata<std::string()> ();
+ }
+
+ lambda<list<value>()>& lst() const {
+ return vdata<list<value>()> ();
+ }
+
+ lambda<value(list<value>&)>& func() const {
+ return vdata<value(list<value>&)> ();
+ }
+
+};
+
+std::ostream& operator<<(std::ostream& out, const value& v) {
+ switch(v.type) {
+ case value::List:
+ return out << "List::" << v.lst()();
+ case value::Lambda:
+ return out << "Lambda::" << v.func();
+ case value::Symbol:
+ return out << "Symbol::" << v.str()();
+ case value::String:
+ return out << "String::" << '\'' << v.str()() << '\'';
+ case value::Number:
+ return out << "Number::" << v.num()();
+ case value::Boolean:
+ if(v.boo()())
+ return out << "Boolean::" << "true";
+ else
+ return out << "Boolean::" << "false";
+ case value::Character:
+ return out << "Character::" << v.chr()();
+ default:
+ return out << "Undefined";
+ }
+}
+
+const bool isNil(const value& value) {
+ return value.type == value::Undefined;
+}
+
+const bool isString(const value& value) {
+ return value.type == value::String;
+}
+
+const bool isSymbol(const value& value) {
+ return value.type == value::Symbol;
+}
+
+const bool isList(const value& value) {
+ return value.type == value::List;
+}
+
+const bool isNumber(const value& value) {
+ return value.type == value::Number;
+}
+
+const bool isBoolean(const value& value) {
+ return value.type == value::Boolean;
+}
+
+const bool isCharacter(const value& value) {
+ return value.type == value::Character;
+}
+
+const bool isTaggedList(const value& exp, value tag) {
+ if(isList(exp))
+ return car((list<value> )exp) == tag;
+ return false;
+}
+
+/**
+ * Pretty print a list of values.
+ */
+std::ostream& print(const list<value>& l, std::ostream& os) {
+ os << "(";
+ if (!isNil(l)) {
+ list<value> ml = l;
+ while(true) {
+ const value v = car(ml);
+ if (isList(v))
+ print(list<value>(v), os);
+ else
+ os << v;
+ ml = cdr(ml);
+ if (isNil(ml))
+ break;
+ os << ", ";
+ }
+ }
+ os << ")";
+ return os;
+}
+
+}
+#endif /* tuscany_value_hpp */
diff --git a/cpp/sca/kernel/xml-test.cpp b/cpp/sca/kernel/xml-test.cpp
new file mode 100644
index 0000000000..818c03ba68
--- /dev/null
+++ b/cpp/sca/kernel/xml-test.cpp
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+/**
+ * Test validation of a composite file against an SCDL schema.
+ */
+
+#include <iostream>
+#include <string>
+#include <libxml/xmlreader.h>
+#include <libxml/xmlschemas.h>
+
+namespace tuscany {
+
+bool printNode(xmlTextReaderPtr reader) {
+ const xmlChar* name = xmlTextReaderConstName(reader);
+ if(name == NULL)
+ name = (xmlChar *)"<unknown>";
+ const xmlChar* value = xmlTextReaderConstValue(reader);
+ std::cout << xmlTextReaderDepth(reader) << " " << xmlTextReaderNodeType(reader) << " " << name << " "
+ << xmlTextReaderIsEmptyElement(reader) << " " << xmlTextReaderHasValue(reader);
+ if(value == NULL)
+ std::cout << std::endl;
+ else
+ std::cout << value << std::endl;
+ return true;
+}
+
+int xmlRead(void *context, char* buffer, int len) {
+ return fread(buffer, 1, len, (FILE*)context);
+}
+
+int xmlClose(void *context) {
+ fclose((FILE*)context);
+ return 0;
+}
+
+bool readFile(const char*xsdfilename, const char *filename) {
+ std::cout << "Loading schemas...\n";
+ const xmlDocPtr xsddoc = xmlReadFile(xsdfilename, NULL, XML_PARSE_NONET);
+ const xmlSchemaParserCtxtPtr xsdctx = xmlSchemaNewDocParserCtxt(xsddoc);
+ const xmlSchemaPtr xsd = xmlSchemaParse(xsdctx);
+ const xmlSchemaValidCtxtPtr validctx = xmlSchemaNewValidCtxt(xsd);
+
+ std::cout << "Reading file...\n";
+ FILE* file = fopen(filename, "r");
+ if (file != NULL) {
+ const xmlTextReaderPtr reader = xmlReaderForIO(xmlRead, xmlClose, file, filename, NULL, XML_PARSE_NONET);
+ xmlTextReaderSetParserProp(reader, XML_PARSER_DEFAULTATTRS, 1);
+ xmlTextReaderSetParserProp(reader, XML_PARSER_SUBST_ENTITIES, 1);
+
+ if(reader != NULL) {
+ xmlTextReaderSchemaValidateCtxt(reader, validctx, 0);
+
+ int rc;
+ while((rc = xmlTextReaderRead(reader)) == 1) {
+ printNode(reader);
+ }
+ if(xmlTextReaderIsValid(reader) != 1)
+ std::cout << "Could not validate document" << std::endl;
+ xmlFreeTextReader(reader);
+ if(rc != 0)
+ std::cout << "Could not parse document" << std::endl;
+ } else
+ std::cout << "Could not create parser" << std::endl;
+ } else
+ std::cout << "Could not open document" << std::endl;
+
+ xmlSchemaFreeValidCtxt(validctx);
+ xmlSchemaFree(xsd);
+ xmlSchemaFreeParserCtxt(xsdctx);
+
+ return true;
+}
+
+}
+
+int main(int argc, char **argv) {
+ std::cout << "Testing..." << std::endl;
+ if(argc != 3)
+ return 1;
+
+ tuscany::readFile(argv[1], argv[2]);
+
+ xmlCleanupParser();
+
+ std::cout << "OK" << std::endl;
+ return 0;
+}
diff --git a/cpp/sca/kernel/xml.hpp b/cpp/sca/kernel/xml.hpp
new file mode 100644
index 0000000000..b4a3b87ad1
--- /dev/null
+++ b/cpp/sca/kernel/xml.hpp
@@ -0,0 +1,385 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/* $Rev$ $Date$ */
+
+#ifndef tuscany_xml_hpp
+#define tuscany_xml_hpp
+
+/**
+ * XML read/write functions.
+ */
+
+#include <libxml/xmlreader.h>
+#include <libxml/xmlwriter.h>
+#include <libxml/xmlschemas.h>
+#include <libxml/globals.h>
+#include <iostream>
+#include <fstream>
+#include <string>
+#include "list.hpp"
+
+namespace tuscany {
+
+/**
+ * Encapsulates a libxml2 xmlTextReader and its state.
+ */
+class XmlReader {
+public:
+ enum TokenType {
+ None = 0, Element = 1, Attribute = 2, EndElement = 15, Identifier = 100, Text = 101, End = 103
+ };
+
+ explicit XmlReader(xmlTextReaderPtr xml) : xml(xml), tokenType(None) {
+ xmlTextReaderSetParserProp(xml, XML_PARSER_DEFAULTATTRS, 1);
+ xmlTextReaderSetParserProp(xml, XML_PARSER_SUBST_ENTITIES, 1);
+ }
+
+ ~XmlReader() {
+ xmlFreeTextReader(xml);
+ }
+
+ /**
+ * Read the next token and return its type.
+ */
+ int read() {
+ if (tokenType == End)
+ return tokenType;
+ if (tokenType == Element) {
+ isEmptyElement = xmlTextReaderIsEmptyElement(xml);
+ hasValue = xmlTextReaderHasValue(xml);
+ hasAttributes = xmlTextReaderHasAttributes(xml);
+ return tokenType = Identifier;
+ }
+ if (hasValue && tokenType == Identifier)
+ return tokenType = Text;
+ if (hasAttributes && (tokenType == Identifier || tokenType == Text) && xmlTextReaderMoveToFirstAttribute(xml) == 1)
+ return tokenType = Attribute;
+ if (tokenType == Attribute && xmlTextReaderMoveToNextAttribute(xml) == 1)
+ return tokenType = Attribute;
+ if (isEmptyElement && (tokenType == Identifier || tokenType == Text || tokenType == Attribute))
+ return tokenType = EndElement;
+ if (!xmlTextReaderRead(xml))
+ return tokenType = End;
+ return tokenType = xmlTextReaderNodeType(xml);
+ }
+
+ operator xmlTextReaderPtr() const {
+ return xml;
+ }
+
+private:
+ const xmlTextReaderPtr xml;
+ int tokenType;
+ bool isEmptyElement;
+ bool hasValue;
+ bool hasAttributes;
+};
+
+/**
+ * Constants used to tag XML tokens.
+ */
+const value endElement("<");
+const value startElement(">");
+const value attribute("attribute");
+const value element("element");
+
+/**
+ * Read an XML identifier.
+ */
+const value readIdentifier(XmlReader& reader) {
+ const char* name = (const char*)xmlTextReaderConstName(reader);
+ return value(name);
+}
+
+/**
+ * Read XML text.
+ */
+const value readText(XmlReader& reader) {
+ const char *val = (const char*)xmlTextReaderConstValue(reader);
+ return value(std::string(val));
+}
+
+/**
+ * Read an XML attribute.
+ */
+const value readAttribute(XmlReader& reader) {
+ const char *name = (const char*)xmlTextReaderConstName(reader);
+ const char *val = (const char*)xmlTextReaderConstValue(reader);
+ return value(makeList(attribute, value(name), value(std::string(val))));
+}
+
+/**
+ * Read an XML token.
+ */
+const value readToken(XmlReader& reader) {
+ const int tokenType = reader.read();
+ if (tokenType == XmlReader::End)
+ return value();
+ if (tokenType == XmlReader::Element)
+ return startElement;
+ if (tokenType == XmlReader::Identifier)
+ return readIdentifier(reader);
+ if (tokenType == XmlReader::Attribute)
+ return readAttribute(reader);
+ if (tokenType == XmlReader::Text)
+ return readText(reader);
+ if (tokenType == XmlReader::EndElement)
+ return endElement;
+ return readToken(reader);
+}
+
+/**
+ * Read a list of XML tokens.
+ */
+const list<value> readList(const list<value>& listSoFar, XmlReader& reader) {
+ const value token = readToken(reader);
+ if(isNil(token) || endElement == token)
+ return reverse(listSoFar);
+ if(startElement == token)
+ return readList(cons(value(readList(makeList(element), reader)), listSoFar), reader);
+ return readList(cons(token, listSoFar), reader);
+}
+
+/**
+ * Read an XML document from a libxml2 XML reader.
+ */
+const list<value> read(XmlReader& reader) {
+ value nextToken = readToken(reader);
+ if (startElement == nextToken)
+ return makeList(value(readList(makeList(element), reader)));
+ return list<value>();
+}
+
+/**
+ * Callback function called by libxml2 to read the XML input stream.
+ */
+int readCallback(void *context, char* buffer, int len) {
+ std::istream* is = static_cast<std::istream*>(context);
+ is->read(buffer, len);
+ if (!is->eof() && (is->fail() || is->bad()))
+ return -1;
+ const int n = is->gcount();
+ return n;
+}
+
+/**
+ * Read an XML document from an input stream.
+ */
+const list<value> readXML(std::istream& is) {
+ xmlTextReaderPtr xml = xmlReaderForIO(readCallback, NULL, &is, NULL, NULL, XML_PARSE_NONET);
+ if (xml == NULL)
+ return list<value>();
+ XmlReader reader(xml);
+ return read(reader);
+}
+
+/**
+ * Callback function called by libxml2 to read the XML file input stream.
+ */
+int readFileCallback(void *context, char* buffer, int len) {
+ std::ifstream* is = static_cast<std::ifstream*>(context);
+ is->read(buffer, len);
+ if (is->fail() || is->bad())
+ return -1;
+ return is->gcount();
+}
+
+/**
+ * Callback function called by libxml2 to close the XML file input stream.
+ */
+int readCloseFileCallback(void *context) {
+ std::ifstream* fis = static_cast<std::ifstream*>(context);
+ fis->close();
+ return 0;
+}
+
+/**
+ * Read an XML document from a file input stream.
+ */
+const list<value> readXML(std::ifstream& is) {
+ xmlTextReaderPtr xml = xmlReaderForIO(readFileCallback, readCloseFileCallback, &is, NULL, NULL, XML_PARSE_NONET);
+ if (xml == NULL)
+ return list<value>();
+ XmlReader reader(xml);
+ return read(reader);
+}
+
+/**
+ * Returns true if a value is an XML attribute.
+ */
+const bool isAttribute(const list<value>& l) {
+ return !isNil(l) && car(l) == attribute;
+}
+
+/**
+ * Returns the name of an XML attribute.
+ */
+const std::string attributeName(const list<value>& l) {
+ return cadr(l);
+}
+
+/**
+ * Returns the text value of an XML attribute.
+ */
+const std::string attributeText(const list<value>& l) {
+ return caddr(l);
+}
+
+/**
+ * Returns true if a value is an XML element.
+ */
+const bool isElement(const list<value>& l) {
+ return !isNil(l) && car(l) == element;
+}
+
+/**
+ * Returns the name of an XML element.
+ */
+const std::string elementName(const list<value>& l) {
+ return cadr(l);
+}
+
+/**
+ * Returns true if an XML element contains text content.
+ */
+const bool elementHasText(const list<value>& l) {
+ if (isNil(cddr(l)))
+ return false;
+ return isString(caddr(l));
+}
+
+/**
+ * Returns the text content of an XML element.
+ */
+const std::string elementText(const list<value>& l) {
+ return caddr(l);
+}
+
+/**
+ * Returns the children of an XML element.
+ */
+const list<value> elementChildren(const list<value>& l) {
+ return cddr(l);
+}
+
+/**
+ * Default encoding used to write XML documents.
+ */
+const char* encoding = "UTF-8";
+
+/**
+ * Write a list of XML element or attribute tokens.
+ */
+const bool writeList(const list<value>& l, const xmlTextWriterPtr xml) {
+ if (isNil(l))
+ return true;
+
+ // Write an attribute
+ const list<value> token(car(l));
+ if (isAttribute(token)) {
+ if (xmlTextWriterWriteAttribute(xml, (const xmlChar*)attributeName(token).c_str(), (const xmlChar*)attributeText(token).c_str()) < 0)
+ return false;
+
+ } else if (isElement(token)) {
+
+ // Write an element
+ if (xmlTextWriterStartElement(xml, (const xmlChar*)elementName(token).c_str()) < 0)
+ return false;
+ if (elementHasText(token) && xmlTextWriterWriteString(xml, (const xmlChar*)elementText(token).c_str()) < 0)
+ return false;
+
+ // Write its children
+ writeList(elementChildren(token), xml);
+
+ if (xmlTextWriterEndElement(xml) < 0)
+ return false;
+ }
+
+ // Go on
+ return writeList(cdr(l), xml);
+}
+
+/**
+ * Write an XML document to a libxml2 XML writer.
+ */
+const bool write(const list<value>& l, const xmlTextWriterPtr xml) {
+ if (xmlTextWriterStartDocument(xml, NULL, encoding, NULL) < 0)
+ return false;
+ writeList(l, xml);
+ if (xmlTextWriterEndDocument(xml) < 0)
+ return false;
+ return true;
+}
+
+/**
+ * Callback function called by libxml2 to write to the XML output stream.
+ */
+int writeCallback(void *context, const char* buffer, int len) {
+ std::ostream* os = static_cast<std::ostream*>(context);
+ os->write(buffer, len);
+ if (os->fail() || os->bad())
+ return -1;
+ return len;
+}
+
+/**
+ * Write an XML document to an output stream.
+ */
+const bool writeXML(const list<value>& l, std::ostream& os) {
+ xmlOutputBufferPtr out = xmlOutputBufferCreateIO(writeCallback, NULL, &os, NULL);
+ xmlTextWriterPtr xml = xmlNewTextWriter(out);
+ if (xml == NULL)
+ return false;
+ return write(l, xml);
+}
+
+/**
+ * Callback function called by libxml2 to write to the XML file output stream.
+ */
+int writeFileCallback(void *context, const char* buffer, int len) {
+ std::ofstream* os = static_cast<std::ofstream*>(context);
+ os->write(buffer, len);
+ if (os->fail() || os->bad())
+ return -1;
+ return len;
+}
+
+/**
+ * Callback function called by libxml2 to close the XML file output stream.
+ */
+int writeCloseFileCallback(void *context) {
+ std::ofstream* fos = static_cast<std::ofstream*>(context);
+ fos->close();
+ return 0;
+}
+
+/**
+ * Write an XML document to a file output stream.
+ */
+const bool writeXML(const list<value>& l, std::ofstream& os) {
+ xmlOutputBufferPtr out = xmlOutputBufferCreateIO(writeFileCallback, writeCloseFileCallback, &os, NULL);
+ xmlTextWriterPtr xml = xmlNewTextWriter(out);
+ if (xml == NULL)
+ return false;
+ return write(l, xml);
+}
+
+}
+#endif /* tuscany_xml_hpp */