From 215c005bde88752999978adce56b09d2a90a13b7 Mon Sep 17 00:00:00 2001 From: jsdelfino Date: Sun, 27 Sep 2009 20:04:28 +0000 Subject: Moved some sources up in the directory tree to attempt to simplify the directory structure a bit, and some minor refactoring. git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@819394 13f79535-47bb-0310-9956-ffa450edef68 --- cpp/sca/kernel/Makefile.am | 29 +++ cpp/sca/kernel/function.hpp | 232 +++++++++++++++++++++ cpp/sca/kernel/gc.hpp | 269 +++++++++++++++++++++++++ cpp/sca/kernel/kernel-test.cpp | 444 +++++++++++++++++++++++++++++++++++++++++ cpp/sca/kernel/list.hpp | 379 +++++++++++++++++++++++++++++++++++ cpp/sca/kernel/parallel.hpp | 283 ++++++++++++++++++++++++++ cpp/sca/kernel/value.hpp | 357 +++++++++++++++++++++++++++++++++ cpp/sca/kernel/xml-test.cpp | 107 ++++++++++ cpp/sca/kernel/xml.hpp | 385 +++++++++++++++++++++++++++++++++++ 9 files changed, 2485 insertions(+) create mode 100644 cpp/sca/kernel/Makefile.am create mode 100644 cpp/sca/kernel/function.hpp create mode 100644 cpp/sca/kernel/gc.hpp create mode 100644 cpp/sca/kernel/kernel-test.cpp create mode 100644 cpp/sca/kernel/list.hpp create mode 100644 cpp/sca/kernel/parallel.hpp create mode 100644 cpp/sca/kernel/value.hpp create mode 100644 cpp/sca/kernel/xml-test.cpp create mode 100644 cpp/sca/kernel/xml.hpp (limited to 'cpp/sca/kernel') 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 +#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 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 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)...); + } + + virtual const int size() const { + return sizeof(function); + } + + private: + const F function; + }; + +}; + +template class lambda; + +template class lambda { +public: + lambda() : callable(0) { + countLambdas++; + countELambdas++; + } + + template explicit lambda(const F f) : callable(0) { + typedef typename CallableType::template Proxy ProxyType; + + countLambdas++; + countFLambdas++; + callable = gc_counting_ptr(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)...); + } + + template friend std::ostream& operator<<(std::ostream&, const lambda&); + +private: + typedef Callable CallableType; + gc_counting_ptr callable; +}; + +template std::ostream& operator<<(std::ostream& out, const lambda& l) { + return out << "lambda::" << l.callable; +} + +/** + * Creates a lambda function from a pointer to a function. + */ +template lambda makeLambda(const R (* const f)(P...)) { + return lambda(f); +} + +/** + * Curry a lambda function. + */ +template class curried { +public: + curried(const lambda& f, const T& v): v(v), f(f) { + } + + const R operator()(P... p) const { + return f(v, std::forward

(p)...); + } + +private: + const T v; + const lambdaf; +}; + +template const lambda curry(const lambda& f, const T& t) { + return (lambda)curried(f, t); +} + +template const lambda curry(const lambda& f, const T& t, const U& u) { + return curry(curry(f, t), u); +} + +template const lambda curry(const lambda& 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 class unitReturn { +public: + explicit unitReturn(const T& v) : + v(v) { + } + const T operator()() const { + return v; + } +private: + const T v; +}; + +template const lambda unit(const T& v) { + return lambda (unitReturn (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 + +namespace tuscany +{ + +template 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 friend std::ostream& operator<<(std::ostream&, const gc_ptr&); + +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 std::ostream& operator<<(std::ostream& out, const gc_ptr& p) { + return out << p.countingRef->ptr; +} + +/** + * Garbage collected pointer to an array. + */ +template 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 friend std::ostream& operator<<(std::ostream&, const gc_aptr&); + +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 std::ostream& operator<<(std::ostream& out, const gc_aptr& p) { + return out << p.countingRef->ptr; +} + +/** + * Garbage collected pointer to a reference counting object. + */ +template 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 friend std::ostream& operator<<(std::ostream&, const gc_counting_ptr&); + +private: + T* ptr; + + void acquire(T* p) throw() { + if(p) + p->acquire(); + } + + void release() throw() { + if(ptr) { + if(ptr->release() == 0) { + delete ptr; + } + } + } +}; + +template std::ostream& operator<<(std::ostream& out, const gc_counting_ptr& 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 +#include +#include +#include +#include +#include +#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 sq(square); + assert(sq(2) == 4); + + const lambda 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 (); + assert(os1.str() == "()"); + + std::ostringstream os2; + os2 << makeList(1, 2, 3); + assert(os2.str() == "(1, (2, (3, ())))"); + return true; +} + +bool testEquals() { + assert(list() == list()); + assert(makeList(1, 2) == makeList(1, 2)); + assert(list() != 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())); + 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 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)square, list()))); + + const list m = map((lambda )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 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 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()))); + 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 s = seq(0.0, 1000.0); + assert(1001 == length(s)); + //printLambdaCounters(); + //printlistCounters(); + + assert(1001 == length(map(lambda(testSeqMap), s))); + + assert(801 == length(member(200.0, s))); + assert(201 == length(member(200.0, reverse(s)))); + + assert(1001 == reduce(lambda(testSeqReduce), 0.0, s)); + //printLambdaCounters(); + //printlistCounters(); + + return true; +} + +value valueSquare(list 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&)> 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 s = seq(0.0, 999.0); + list r = map((lambda )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 func = curry(lambda (mtsquare), 2); + assert(submit(w, func) == 4); + } + { + const int max = 10; + + list > r; + for(int i = 0; i < max; i++) { + const lambda func = curry(lambda (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 = +"\n" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"" +"\n"; + +const bool isName(const value& token) { + return isAttribute(token) && attributeName(token) == "name"; +} + +bool testReadXML() { + std::istringstream is(currencyXML); + const list currency = value(readXML(is)); + + const value composite = car(currency); + assert(isElement(composite)); + assert(elementName(composite) == "composite"); + assert(!elementHasText(composite)); + + assert(attributeText(car(filter(lambda(isName), elementChildren(composite)))) == "currency"); + return true; +} + +bool testWriteXML() { + std::istringstream is(currencyXML); + const list 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 +#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 class list { +public: + + list(const T car, const lambda ()>& 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& p) { + if(this == &p) + return *this; + nil = p.nil; + car = p.car; + cdr = p.cdr; + return *this; + } + + ~list() { + countlists--; + } + + const bool operator==(const list& 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& p) const { + return !this->operator==(p); + } + + template friend std::ostream& operator<<(std::ostream&, const list&); + + bool nil; + T car; + lambda ()> cdr; +}; + +/** + * Returns true if the given list is nil. + */ +template const bool isNil(const list& p) { + return p.nil; +} + +/** + * Write a list to an output stream. + */ +template std::ostream& operator<<(std::ostream& out, const list& l) { + if(l == list ()) + return out << "()"; + return out << "(" << car(l) << ", " << cdr(l) << ")"; +} + +/** + * Construct a (lazy) list from a value and a lambda function that returns the cdr. + */ +template const list cons(const T& car, const lambda ()>& cdr) { + return list (car, cdr); +} + +/** + * Construct a list from a value and a cdr list. + */ +template const list cons(const T& car, const list& cdr) { + return list (car, unit(cdr)); +} + +/** + * Construct a list of one value. + */ +template const list makeList(const T& car) { + return list (car, unit(list ())); +} + +/** + * Construct a list of two values. + */ +template const list makeList(const T& a, const T& b) { + return cons(a, makeList(b)); +} + +/** + * Construct a list of three values. + */ +template const list makeList(const T& a, const T& b, const T& c) { + return cons(a, cons(b, makeList(c))); +} + +/** + * Construct a list of four values. + */ +template const list 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 const T car(const list& p) { + return p.car; +} + +/** + * Returns the cdr of a list. + */ +template list const cdr(const list& p) { + return p.cdr(); +} + +/** + * Returns the car of the cdr of a list. + */ +template const T cadr(const list& p) { + return car(cdr(p)); +} + +/** + * Returns the car of the cdr of the cdr of a list. + */ +template const T caddr(const list& p) { + return car(cdr(cdr(p))); +} + +/** + * Returns the cdr of a cdr of a list. + */ +template const list cddr(const list& p) { + return cdr(cdr(p)); +} + +/** + * Returns the cdr of a cdr of the cdr of a list. + */ +template const list cdddr(const list& p) { + return cdr(cdr(cdr(p))); +} + +/** + * Returns the length of a list. + */ +template struct lengthRef { + const int operator()(const int c, const list& p) { + if(isNil(p)) + return c; + return (*this)(c + 1, cdr(p)); + } +}; + +template const int length(const list& p) { + return lengthRef ()(0, p); +} + +/** + * Appends a list and a lambda function returning a list. + */ +template struct appendCdr { + const list a; + const lambda ()> fb; + appendCdr(const list& a, const lambda ()>& fb) : + a(a), fb(fb) { + } + const list operator()() const { + return append(a, fb); + } +}; + +template const list append(const list&a, const lambda ()>& fb) { + if(isNil(a)) + return fb(); + + return cons(car(a), lambda ()> (appendCdr (cdr(a), fb))); +} + +/** + * Appends two lists. + */ +template const list append(const list&a, const list& b) { + return append(a, unit(b)); +} + +/** + * Map a lambda function on a list. + */ +template const list map(const lambda& f, const list& p) { + if(isNil(p)) + return list (); + return cons(f(car(p)), map(f, cdr(p))); +} + +/** + * Run a reduce lambda function on a list. + */ +template struct reduceAccumulate { + const lambda f; + explicit reduceAccumulate(const lambda& f) : + f(f) { + } + R operator()(const R& acc, const list& p) const { + if(isNil(p)) + return acc; + return (*this)(f(acc, car(p)), cdr(p)); + } +}; + +template const R reduce(const lambda& f, const R& initial, const list& p) { + return reduceAccumulate (f)(initial, p); +} + +/** + * Run a filter lambda function on a list. + */ +template const list filter(const lambda& f, const list& p) { + if(isNil(p)) + return list (); + if(f(car(p))) { + const lambda (lambda , list )> ff(filter ); + 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 const list member(const T& t, const list& p) { + if(isNil(p)) + return list (); + if(t == car(p)) + return p; + return member(t, cdr(p)); +} + +/** + * Reverse a list. + */ +template const list reverseIter(const list& acc, const list& p) { + if(isNil(p)) + return acc; + return reverseIter(cons(car(p), acc), cdr(p)); +} + +template const list reverse(const list& p) { + return reverseIter(list (), p); +} + +template const list seq(const T& start, const T& end); + +template struct seqGenerate { + const T start; + const T end; + seqGenerate(const T& start, const T&end) : + start(start), end(end) { + } + const list operator()() const { + return seq (start, end); + } +}; + +/** + * Returns a sequence of values between the given bounds. + */ +template const list seq(const T& start, const T& end) { + if(start == end) + return makeList(start); + if(start < end) + return cons(start, lambda ()> (seqGenerate (start + 1, end))); + return cons(start, lambda ()> (seqGenerate (start - 1, end))); +} + +/** + * Equivalent of the list assoc function. + */ +template const list assoc(const T& k, const list >& p) { + if(isNil(p)) + return list (); + if(k == car(car(p))) + return car(p); + return assoc(k, cdr(p)); +} + +/** + * Pretty print a list. + */ +template std::ostream& print(const list& l, std::ostream& os) { + os << "("; + if (!isNil(l)) { + list 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 +#include +#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 class future { + +private: + template 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 > fvalue; + + template friend const X get(const future& f); + template friend bool set(const future& f, const X& v); + +public: + future() : fvalue(new futureValue()) { + //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 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 values; + + template friend const int enqueue(queue& q, const X& v); + template friend const X dequeue(queue& q); +}; + +/** + * Adds an element to the tail of the queue. + */ +template const int enqueue(queue&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 const T dequeue(queue& 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 >* work = reinterpret_cast >*>(arg); + while(dequeue(*work)()) + ; + return NULL; +} + +/** + * Returns a list of worker threads. + */ +const list makeWorkerThreads(queue >& queue, const int count) { + if (count == 0) + return list(); + 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 >(max)), threads(makeWorkerThreads(work, max)) { + } + +private: + queue > work; + const list threads; + + template friend const future submit(worker& w, const lambda& func); + friend const bool shutdown(worker& w); +}; + +/** + * Function used to wrap work submitted to a worker. + */ +template bool submitFunc(const lambda& func, const future& fut) { + fut = func(); + return true; +} + +/** + * Submits work to a worker. + */ +template const future submit(worker& w, const lambda& func) { + const future fut; + const lambda f = curry(lambda, future)>(submitFunc), func, fut); + enqueue(w.work, f); + return fut; +} + +/** + * Enqueues shutdown requests. + */ +const bool shutdownEnqueue(const list& threads, queue >& work) { + if (threads == list()) + return true; + enqueue(work, unit(false)); + return shutdownEnqueue(cdr(threads), work); +} + +/** + * Waits for shut down threads to terminate. + */ +const bool shutdownJoin(const list& threads) { + if (threads == list()) + 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 +#include +#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&)>& 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& 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& 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() const { + return lst()(); + } + + operator const lambda&)>() const { + return func(); + } + + friend std::ostream& operator<<(std::ostream&, const value&); + + ValueType type; + lambda data; + +private: + template lambda& vdata() const { + return *reinterpret_cast *> (const_cast *> (&data)); + } + + template const lambda& vdata(const T& v) const { + return *reinterpret_cast *> (&v); + } + + lambda& num() const { + return vdata (); + } + + lambda& boo() const { + return vdata (); + } + + lambda& chr() const { + return vdata (); + } + + lambda& str() const { + return vdata (); + } + + lambda()>& lst() const { + return vdata()> (); + } + + lambda&)>& func() const { + return vdata&)> (); + } + +}; + +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 )exp) == tag; + return false; +} + +/** + * Pretty print a list of values. + */ +std::ostream& print(const list& l, std::ostream& os) { + os << "("; + if (!isNil(l)) { + list ml = l; + while(true) { + const value v = car(ml); + if (isList(v)) + print(list(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 +#include +#include +#include + +namespace tuscany { + +bool printNode(xmlTextReaderPtr reader) { + const xmlChar* name = xmlTextReaderConstName(reader); + if(name == NULL) + name = (xmlChar *)""; + 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 +#include +#include +#include +#include +#include +#include +#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 readList(const list& 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 read(XmlReader& reader) { + value nextToken = readToken(reader); + if (startElement == nextToken) + return makeList(value(readList(makeList(element), reader))); + return list(); +} + +/** + * Callback function called by libxml2 to read the XML input stream. + */ +int readCallback(void *context, char* buffer, int len) { + std::istream* is = static_cast(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 readXML(std::istream& is) { + xmlTextReaderPtr xml = xmlReaderForIO(readCallback, NULL, &is, NULL, NULL, XML_PARSE_NONET); + if (xml == NULL) + return list(); + 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(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(context); + fis->close(); + return 0; +} + +/** + * Read an XML document from a file input stream. + */ +const list readXML(std::ifstream& is) { + xmlTextReaderPtr xml = xmlReaderForIO(readFileCallback, readCloseFileCallback, &is, NULL, NULL, XML_PARSE_NONET); + if (xml == NULL) + return list(); + XmlReader reader(xml); + return read(reader); +} + +/** + * Returns true if a value is an XML attribute. + */ +const bool isAttribute(const list& l) { + return !isNil(l) && car(l) == attribute; +} + +/** + * Returns the name of an XML attribute. + */ +const std::string attributeName(const list& l) { + return cadr(l); +} + +/** + * Returns the text value of an XML attribute. + */ +const std::string attributeText(const list& l) { + return caddr(l); +} + +/** + * Returns true if a value is an XML element. + */ +const bool isElement(const list& l) { + return !isNil(l) && car(l) == element; +} + +/** + * Returns the name of an XML element. + */ +const std::string elementName(const list& l) { + return cadr(l); +} + +/** + * Returns true if an XML element contains text content. + */ +const bool elementHasText(const list& 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& l) { + return caddr(l); +} + +/** + * Returns the children of an XML element. + */ +const list elementChildren(const list& 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& l, const xmlTextWriterPtr xml) { + if (isNil(l)) + return true; + + // Write an attribute + const list 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& 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(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& 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(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(context); + fos->close(); + return 0; +} + +/** + * Write an XML document to a file output stream. + */ +const bool writeXML(const list& 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 */ -- cgit v1.2.3