<commit_before>#include <iostream>
#include "Timer.h"
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
using namespace std;

int main(int argc, char* argv[]){
	bool all = false;
	bool fastest = false;
	if(argc < 3){
		cout << "cp: missing file operand" << endl;
        cout << "To copy using all methods use the -a flag" << endl;
		return 0;
	}
	if(argc ==  4){
		all = true;
	}
	else{
		fastest = true;
	}
	string path;
	string tmp;
	struct stat buf;
    int file1;
    int file2;
    if(all && argv[1][0] == '-'){
        if(argv[1][1] != 'a'){
            cerr << "Invalid flag" << endl;
            return 0;
        }
        file1 = 2;
        file2 = 3;
    }
    else if(all && argv[2][0] == '-'){
        if(argv[2][1] != 'a'){
            cerr << "Invalid lag" << endl;
            return 0;
        }
        file1 = 1;
        file2 = 3;
    }
    else if(all && argv[3][0] == '-'){
        if(argv[3][1] != 'a'){
            cerr << "Invalid flag" << endl;
            return 0;
        }
        file1 = 1;
        file2 = 2;
    }
    else{
        file1 = 1;
        file2 = 2;
    }
	if(argv[file1][0] != '.' && argv[file1][0] != '/' ){
		path = argv[file1];
		string tmp = "./";
		path = tmp + path;
		if(stat(path.c_str(), &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input parameter is dir" << endl;
			exit(0);
		}
	}
	else{
		if(stat(argv[file1], &buf)){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input files if dir" << endl;
			exit(0);
		}
	}
	if(ifstream(argv[file2])){
        if(-1 == stat(argv[2], &buf)){
            perror("stat");
            exit(0);
        }
        if(S_ISDIR(buf.st_mode)){
            cerr << "Output parameter is dir" << endl;
            exit(0);
        }
        else{
    		cerr << "Output file already exists" << endl;
	    	exit(0);
        }
	}
	else{
		ofstream tmp(argv[file2]);
		if(!tmp.good()){
			cerr << "Unable to open file" << endl;
			return 0;
		}
		tmp.close();
	}
	if(argv[file2][0] != '.' && argv[file2][0] != '/'){
		path = argv[file2];
		tmp = "./";
		path = tmp + path;
		if(stat(path.c_str(), &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Output file is dir" << endl;
			exit(0);
		}
	}
	else{
		if(stat(argv[file2], &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input file is dir" << endl;
			exit(0);
		}
	}

	if(all){
		Timer t;
		double eTime;
		t.start();
		ifstream in(argv[file1]);
		ofstream out(argv[file2]);
		if(!in.good() || !out.good()){
			cerr << "Unable to open file" << endl;
			return 0;
		}
		while(in.good()){
			char c = in.get();
			if(in.good()){
				out.put(c);
			}
		}
		cout << "Method 1: " << endl;
		t.elapsedUserTime(eTime);
		cout <<  "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
		in.close();
		out.close();
	}
	if(all){
		Timer t;
		double eTime;
		t.start();
		int infile = open(argv[file1], O_RDONLY);
		if(infile == -1){
			perror("open");
			exit(0);
		}
		int outfile = open(argv[file2], O_WRONLY);
		if(outfile == -1){
			perror("open");
			exit(0);
		}
		char buf[1];
		int n;
		while((n = read(infile, &buf, 1))){
			int w = write(outfile, &buf, 1);
			if(w == -1){
				perror("write");
				exit(0);
			}
		}
		if(n == -1){
			perror("read");
			exit(0);
		}
		cout << "Method 2: " << endl;
		t.elapsedUserTime(eTime);
		cout << "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
	}
	if(all || fastest){
		Timer t;
		double eTime;
		t.start();
		int infile = open(argv[file1], O_RDONLY);
		if(infile == -1){
			perror("open");
			exit(0);
		}
		int outfile = open(argv[file2], O_WRONLY);
		if(outfile == -1){
			perror("open");
			exit(0);
		}
		char buf[BUFSIZ];
		int n = read(infile, buf, BUFSIZ);
		if(n == -1){
			perror("read");
			exit(0);
		}
		int w = write(outfile, buf, BUFSIZ);
		if(w == -1){
			perror("write");
			exit(0);
		}
		cout << "Method 3: " << endl;
		t.elapsedUserTime(eTime);
		cout << "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
	}
	return 0;
}
<commit_msg>Update cp.cpp<commit_after>#include <iostream>
#include "Timer.h"
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
using namespace std;

int main(int argc, char* argv[]){
	bool all = false;
	bool fastest = false;
	if(argc < 3){
		cout << "cp: missing file operand" << endl;
        cout << "To copy using all methods use the -a flag, without flag copies using the fastest method" << endl;
		return 0;
	}
	if(argc ==  4){
		all = true;
	}
	else{
		fastest = true;
	}
	string path;
	string tmp;
	struct stat buf;
    int file1;
    int file2;
    if(all && argv[1][0] == '-'){
        if(argv[1][1] != 'a'){
            cerr << "Invalid flag" << endl;
            return 0;
        }
        file1 = 2;
        file2 = 3;
    }
    else if(all && argv[2][0] == '-'){
        if(argv[2][1] != 'a'){
            cerr << "Invalid lag" << endl;
            return 0;
        }
        file1 = 1;
        file2 = 3;
    }
    else if(all && argv[3][0] == '-'){
        if(argv[3][1] != 'a'){
            cerr << "Invalid flag" << endl;
            return 0;
        }
        file1 = 1;
        file2 = 2;
    }
    else{
        file1 = 1;
        file2 = 2;
    }
	if(argv[file1][0] != '.' && argv[file1][0] != '/' ){
		path = argv[file1];
		string tmp = "./";
		path = tmp + path;
		if(stat(path.c_str(), &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input parameter is dir" << endl;
			exit(0);
		}
	}
	else{
		if(stat(argv[file1], &buf)){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input files if dir" << endl;
			exit(0);
		}
	}
	if(ifstream(argv[file2])){
        if(-1 == stat(argv[2], &buf)){
            perror("stat");
            exit(0);
        }
        if(S_ISDIR(buf.st_mode)){
            cerr << "Output parameter is dir" << endl;
            exit(0);
        }
        else{
    		cerr << "Output file already exists" << endl;
	    	exit(0);
        }
	}
	else{
		ofstream tmp(argv[file2]);
		if(!tmp.good()){
			cerr << "Unable to open file" << endl;
			return 0;
		}
		tmp.close();
	}
	if(argv[file2][0] != '.' && argv[file2][0] != '/'){
		path = argv[file2];
		tmp = "./";
		path = tmp + path;
		if(stat(path.c_str(), &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Output file is dir" << endl;
			exit(0);
		}
	}
	else{
		if(stat(argv[file2], &buf) == -1){
			perror("stat");
			exit(0);
		}
		if(S_ISDIR(buf.st_mode)){
			cerr << "Input file is dir" << endl;
			exit(0);
		}
	}

	if(all){
		Timer t;
		double eTime;
		t.start();
		ifstream in(argv[file1]);
		ofstream out(argv[file2]);
		if(!in.good() || !out.good()){
			cerr << "Unable to open file" << endl;
			return 0;
		}
		while(in.good()){
			char c = in.get();
			if(in.good()){
				out.put(c);
			}
		}
		cout << "Method 1: " << endl;
		t.elapsedUserTime(eTime);
		cout <<  "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
		in.close();
		out.close();
	}
	if(all){
		Timer t;
		double eTime;
		t.start();
		int infile = open(argv[file1], O_RDONLY);
		if(infile == -1){
			perror("open");
			exit(0);
		}
		int outfile = open(argv[file2], O_WRONLY);
		if(outfile == -1){
			perror("open");
			exit(0);
		}
		char buf[1];
		int n;
		while((n = read(infile, &buf, 1))){
			int w = write(outfile, &buf, 1);
			if(w == -1){
				perror("write");
				exit(0);
			}
		}
		if(n == -1){
			perror("read");
			exit(0);
		}
		cout << "Method 2: " << endl;
		t.elapsedUserTime(eTime);
		cout << "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
	}
	if(all || fastest){
		Timer t;
		double eTime;
		t.start();
		int infile = open(argv[file1], O_RDONLY);
		if(infile == -1){
			perror("open");
			exit(0);
		}
		int outfile = open(argv[file2], O_WRONLY);
		if(outfile == -1){
			perror("open");
			exit(0);
		}
		char buf[BUFSIZ];
		int n = read(infile, buf, BUFSIZ);
		if(n == -1){
			perror("read");
			exit(0);
		}
		int w = write(outfile, buf, BUFSIZ);
		if(w == -1){
			perror("write");
			exit(0);
		}
		cout << "Method 3: " << endl;
		t.elapsedUserTime(eTime);
		cout << "User time: " << eTime << endl;
		t.elapsedWallclockTime(eTime);
		cout << "Wall clock time: " << eTime << endl;
		t.elapsedSystemTime(eTime);
		cout << "System time: " << eTime << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "unittest.hpp"
#include "rice/Module.hpp"
#include "rice/Exception.hpp"
#include "rice/Array.hpp"

using namespace Rice;

TESTSUITE(Module);

SETUP(Object)
{
  ruby_init();
}

TESTCASE(construct_from_value)
{
  Module m(rb_mEnumerable);
  ASSERT_EQUAL(rb_mEnumerable, m.value());
}

namespace
{

class Silly_Exception
  : public std::exception
{
};

void handle_silly_exception(Silly_Exception const & ex)
{
  throw Exception(rb_eRuntimeError, "SILLY");
}

void throw_silly_exception(Object self)
{
  throw Silly_Exception();
}

} // namespace

TESTCASE(add_handler)
{
  Module m(anonymous_module());
  m.add_handler<Silly_Exception>(handle_silly_exception);
  m.define_singleton_method("foo", throw_silly_exception);
  Object exc = m.instance_eval("begin; foo; rescue Exception; $!; end");
  ASSERT_EQUAL(rb_eRuntimeError, CLASS_OF(exc));
  Exception ex(exc);
  ASSERT_EQUAL(String("SILLY"), String(ex.message()));
}

namespace
{

bool define_method_simple_ok;

void define_method_simple_helper(Object o)
{
  define_method_simple_ok = true;
}

} // namespace

TESTCASE(define_method_simple)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  Object o = m.instance_eval("o = Object.new; o.extend(self); o.foo");
  ASSERT(define_method_simple_ok);
}

TESTCASE(define_singleton_method_simple)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  Object o = m.call("foo");
  ASSERT(define_method_simple_ok);
}

TESTCASE(define_module_function_simple)
{
  Module m(anonymous_module());
  m.define_module_function("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  m.instance_eval("o = Object.new; o.extend(self); o.instance_eval { foo }");
  ASSERT(define_method_simple_ok);
  define_method_simple_ok = false;
  m.call("foo");
  ASSERT(define_method_simple_ok);
}

namespace
{

int define_method_int_result;

void define_method_int_helper(Object o, int i)
{
  define_method_int_result = i;
}

} // namespace

TESTCASE(define_method_int)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_int_helper);
  define_method_int_result = 0;
  Object o = m.instance_eval("o = Object.new; o.extend(self); o.foo(42)");
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_singleton_method_int)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_int_helper);
  define_method_int_result = 0;
  Object o = m.call("foo", 42);
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_module_function_int)
{
  Module m(anonymous_module());
  m.define_module_function("foo", define_method_int_helper);
  define_method_int_result = 0;
  m.instance_eval("o = Object.new; o.extend(self); o.instance_eval { foo(42) }");
  ASSERT_EQUAL(42, define_method_int_result);
  define_method_int_result = 0;
  m.call("foo", 42);
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_method_int_passed_no_args)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_int_helper);
  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.instance_eval("o = Object.new; o.extend(self); o.foo"),
      ASSERT_EQUAL(
          Object(rb_eArgError),
          Object(CLASS_OF(ex.value()))
          )
      );
}

namespace
{

struct Foo
{
  int x;
};

int define_method_int_foo_result_i;
Foo * define_method_int_foo_result_x;

void define_method_int_foo_helper(Object o, int i, Foo * x)
{
  define_method_int_foo_result_i = i;
  define_method_int_foo_result_x = x;
}

} // namespace

template<>
Foo * from_ruby<Foo *>(Object x)
{
  Foo * retval;
  Data_Get_Struct(x.value(), Foo, retval);
  return retval;
}

TESTCASE(define_singleton_method_int_foo)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_int_foo_helper);
  define_method_int_result = 0;
  Foo * foo = new Foo;
  foo->x = 1024;
  VALUE f = Data_Wrap_Struct(rb_cObject, 0, Default_Allocation_Strategy<Foo>::free, foo);
  m.call("foo", 42, Object(f));
  ASSERT_EQUAL(42, define_method_int_foo_result_i);
  ASSERT_EQUAL(foo, define_method_int_foo_result_x);
}

// TODO: how to test define_iterator?

TESTCASE(include_module)
{
  Module m(anonymous_module());
  Module & m2(m.include_module(rb_mEnumerable));
  ASSERT_EQUAL(&m, &m2);
  Array ancestors(m.ancestors());
  Array expected_ancestors;
  expected_ancestors.push(m);
  expected_ancestors.push(Module(rb_mEnumerable));
  ASSERT_EQUAL(expected_ancestors, ancestors);
}

TESTCASE(const_set_get_by_id)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set(rb_intern("FOO"), v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get(rb_intern("FOO")));
}

TESTCASE(const_set_get_by_identifier)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set(Identifier("FOO"), v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get(Identifier("FOO")));
}

TESTCASE(const_set_get_by_string)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set("FOO", v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get("FOO"));
}

TESTCASE(remove_const)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  m.const_set("FOO", v);
  ASSERT_EQUAL(v, m.const_get("FOO"));
  m.remove_const("FOO");
  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.const_get("FOO"),
      ASSERT_EQUAL(
          Object(rb_eNameError),
          Object(CLASS_OF(ex.value()))
          )
      );
}

TESTCASE(mod_name_anonymous)
{
  Module m(anonymous_module());
  ASSERT_EQUAL(String(""), m.name());
}

<commit_msg>Test to show the API for default args<commit_after>#include "unittest.hpp"
#include "rice/Module.hpp"
#include "rice/Exception.hpp"
#include "rice/Array.hpp"
#include "rice/Arg.hpp"

using namespace Rice;

TESTSUITE(Module);

SETUP(Object)
{
  ruby_init();
}

TESTCASE(construct_from_value)
{
  Module m(rb_mEnumerable);
  ASSERT_EQUAL(rb_mEnumerable, m.value());
}

namespace
{

class Silly_Exception
  : public std::exception
{
};

void handle_silly_exception(Silly_Exception const & ex)
{
  throw Exception(rb_eRuntimeError, "SILLY");
}

void throw_silly_exception(Object self)
{
  throw Silly_Exception();
}

} // namespace

TESTCASE(add_handler)
{
  Module m(anonymous_module());
  m.add_handler<Silly_Exception>(handle_silly_exception);
  m.define_singleton_method("foo", throw_silly_exception);
  Object exc = m.instance_eval("begin; foo; rescue Exception; $!; end");
  ASSERT_EQUAL(rb_eRuntimeError, CLASS_OF(exc));
  Exception ex(exc);
  ASSERT_EQUAL(String("SILLY"), String(ex.message()));
}

namespace
{

bool define_method_simple_ok;

void define_method_simple_helper(Object o)
{
  define_method_simple_ok = true;
}

} // namespace

TESTCASE(define_method_simple)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  Object o = m.instance_eval("o = Object.new; o.extend(self); o.foo");
  ASSERT(define_method_simple_ok);
}

TESTCASE(define_singleton_method_simple)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  Object o = m.call("foo");
  ASSERT(define_method_simple_ok);
}

TESTCASE(define_module_function_simple)
{
  Module m(anonymous_module());
  m.define_module_function("foo", define_method_simple_helper);
  define_method_simple_ok = false;
  m.instance_eval("o = Object.new; o.extend(self); o.instance_eval { foo }");
  ASSERT(define_method_simple_ok);
  define_method_simple_ok = false;
  m.call("foo");
  ASSERT(define_method_simple_ok);
}

namespace
{

int define_method_int_result;

void define_method_int_helper(Object o, int i)
{
  define_method_int_result = i;
}

} // namespace

TESTCASE(define_method_int)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_int_helper);
  define_method_int_result = 0;
  Object o = m.instance_eval("o = Object.new; o.extend(self); o.foo(42)");
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_singleton_method_int)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_int_helper);
  define_method_int_result = 0;
  Object o = m.call("foo", 42);
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_module_function_int)
{
  Module m(anonymous_module());
  m.define_module_function("foo", define_method_int_helper);
  define_method_int_result = 0;
  m.instance_eval("o = Object.new; o.extend(self); o.instance_eval { foo(42) }");
  ASSERT_EQUAL(42, define_method_int_result);
  define_method_int_result = 0;
  m.call("foo", 42);
  ASSERT_EQUAL(42, define_method_int_result);
}

TESTCASE(define_method_int_passed_no_args)
{
  Module m(anonymous_module());
  m.define_method("foo", define_method_int_helper);
  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.instance_eval("o = Object.new; o.extend(self); o.foo"),
      ASSERT_EQUAL(
          Object(rb_eArgError),
          Object(CLASS_OF(ex.value()))
          )
      );
}

namespace
{

struct Foo
{
  int x;
};

int define_method_int_foo_result_i;
Foo * define_method_int_foo_result_x;

void define_method_int_foo_helper(Object o, int i, Foo * x)
{
  define_method_int_foo_result_i = i;
  define_method_int_foo_result_x = x;
}

} // namespace

template<>
Foo * from_ruby<Foo *>(Object x)
{
  Foo * retval;
  Data_Get_Struct(x.value(), Foo, retval);
  return retval;
}

TESTCASE(define_singleton_method_int_foo)
{
  Module m(anonymous_module());
  m.define_singleton_method("foo", define_method_int_foo_helper);
  define_method_int_result = 0;
  Foo * foo = new Foo;
  foo->x = 1024;
  VALUE f = Data_Wrap_Struct(rb_cObject, 0, Default_Allocation_Strategy<Foo>::free, foo);
  m.call("foo", 42, Object(f));
  ASSERT_EQUAL(42, define_method_int_foo_result_i);
  ASSERT_EQUAL(foo, define_method_int_foo_result_x);
}

// TODO: how to test define_iterator?

TESTCASE(include_module)
{
  Module m(anonymous_module());
  Module & m2(m.include_module(rb_mEnumerable));
  ASSERT_EQUAL(&m, &m2);
  Array ancestors(m.ancestors());
  Array expected_ancestors;
  expected_ancestors.push(m);
  expected_ancestors.push(Module(rb_mEnumerable));
  ASSERT_EQUAL(expected_ancestors, ancestors);
}

TESTCASE(const_set_get_by_id)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set(rb_intern("FOO"), v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get(rb_intern("FOO")));
}

TESTCASE(const_set_get_by_identifier)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set(Identifier("FOO"), v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get(Identifier("FOO")));
}

TESTCASE(const_set_get_by_string)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  Module & m2(m.const_set("FOO", v));
  ASSERT_EQUAL(&m, &m2);
  ASSERT_EQUAL(v, m.const_get("FOO"));
}

TESTCASE(remove_const)
{
  Module m(anonymous_module());
  Object v = to_ruby(42);
  m.const_set("FOO", v);
  ASSERT_EQUAL(v, m.const_get("FOO"));
  m.remove_const("FOO");
  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.const_get("FOO"),
      ASSERT_EQUAL(
          Object(rb_eNameError),
          Object(CLASS_OF(ex.value()))
          )
      );
}

TESTCASE(mod_name_anonymous)
{
  Module m(anonymous_module());
  ASSERT_EQUAL(String(""), m.name());
}

/**
 * Tests for default arguments
 */
namespace
{
  int defaults_method_one_arg1;
  int defaults_method_one_arg2;
  bool defaults_method_one_arg3 = false;

  void defaults_method_one(Object o, int arg1, int arg2 = 3, bool arg3 = true)
  {
    defaults_method_one_arg1 = arg1;
    defaults_method_one_arg2 = arg2;
    defaults_method_one_arg3 = arg3;
  }
}

TESTCASE(define_method_default_arguments)
{
  Module m(anonymous_module());
  m.define_method("foo", &defaults_method_one, (Arg("arg1"), Arg("arg2") = 3, Arg("arg3") = true));

  Object o = m.instance_eval("o = Object.new; o.extend(self); o.foo(2)");

  ASSERT_EQUAL(2, defaults_method_one_arg1);
  ASSERT_EQUAL(3, defaults_method_one_arg2);
  ASSERT(defaults_method_one_arg3);

  o = m.instance_eval("o = Object.new; o.extend(self); o.foo(11, 10)");

  ASSERT_EQUAL(11, defaults_method_one_arg1);
  ASSERT_EQUAL(10, defaults_method_one_arg2);
  ASSERT(defaults_method_one_arg3);

  o = m.instance_eval("o = Object.new; o.extend(self); o.foo(22, 33, false)");

  ASSERT_EQUAL(11, defaults_method_one_arg1);
  ASSERT_EQUAL(10, defaults_method_one_arg2);
  ASSERT(!defaults_method_one_arg3);
}

TESTCASE(default_arguments_still_throws_argument_error)
{
  Module m(anonymous_module());
  m.define_method("foo", &defaults_method_one, (Arg("arg1"), Arg("arg2") = 3, Arg("arg3") = true));

  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.instance_eval("o = Object.new; o.extend(self); o.foo()"),
      ASSERT_EQUAL(
          Object(rb_eArgError),
          Object(CLASS_OF(ex.value()))
          )
      );

  ASSERT_EXCEPTION_CHECK(
      Exception,
      m.instance_eval("o = Object.new; o.extend(self); o.foo(3, 4, false, 17)"),
      ASSERT_EQUAL(
          Object(rb_eArgError),
          Object(CLASS_OF(ex.value()))
          )
      );
}

TESTCASE(default_arguments_for_define_singleton_method)
{

}

TESTCASE(default_arguments_for_define_module_function)
{

}

TESTCASE(default_arguments_for_define_global_function)
<|endoftext|>


<commit_before>/*
 * observer.hpp
 *
 *  Created on: Jun 3, 2016
 *      Author: zmij
 */

#ifndef AFSM_DETAIL_OBSERVER_HPP_
#define AFSM_DETAIL_OBSERVER_HPP_

#include <afsm/fsm_fwd.hpp>
#include <afsm/detail/actions.hpp>
#include <afsm/detail/transitions.hpp>
#include <memory>

namespace afsm {
namespace detail {

struct null_observer {
    template < typename FSM, typename Event >
    void
    start_process_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM, typename State, typename Event >
    void
    state_entered(FSM const&, State const&, Event const&) const noexcept{}
    template < typename FSM, typename State, typename Event >
    void
    state_exited(FSM const&, State const&, Event const&) const noexcept{}
    template < typename FSM, typename State >
    void
    state_cleared(FSM const&, State const&) const noexcept{}

    template < typename FSM, typename SourceState, typename TargetState, typename Event>
    void
    state_changed(FSM const&, SourceState const&, TargetState const&, Event const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    processed_in_state(FSM const&, Event const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    enqueue_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM >
    void
    start_process_events_queue(FSM const&) const noexcept {}
    template < typename FSM >
    void
    end_process_events_queue(FSM const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    defer_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM >
    void
    start_process_deferred_queue(FSM const&, ::std::size_t size) const noexcept {}
    template < typename FSM >
    void
    end_process_deferred_queue(FSM const&, ::std::size_t remain) const noexcept {}

    template < typename FSM >
    void
    skip_processing_deferred_queue(FSM const&) const noexcept {}
    template < typename FSM >
    void
    postpone_deferred_events(FSM const&, ::std::size_t count) const noexcept {}
    template < typename FSM >
    void
    drop_deferred_event(FSM const&) const noexcept{};

    template < typename FSM, typename Event >
    void
    reject_event(FSM const&, Event const&) const noexcept {}
};

template < typename T >
class observer_wrapper {
public:
    using observer_ptr = ::std::shared_ptr<T>;
public:
    observer_wrapper()
        : observer_{} {}
    void
    set_observer(observer_ptr observer)
    {
        observer_ = observer;
    }

    template < typename ... Args >
    void
    make_observer(Args&& ... args)
    {
        observer_ = ::std::make_shared<T>(::std::forward<Args>(args)...);
    }
protected:
    template < typename FSM, typename FSM_DEF, typename Size >
    friend class transitions::state_transition_table;

    template < typename FSM, typename Event >
    void
    start_process_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->start_process_event(fsm, event);
    }

    template < typename FSM, typename State, typename Event >
    void
    state_entered(FSM const& fsm, State const& state, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_entered(fsm, state, event);
    }
    template < typename FSM, typename State, typename Event >
    void
    state_exited(FSM const& fsm, State const& state, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_exited(fsm, state, event);
    }
    template < typename FSM, typename State >
    void
    state_cleared(FSM const& fsm, State const& state) const noexcept
    {
        if (observer_)
            observer_->state_cleared(fsm, state);
    }
    template < typename FSM, typename SourceState, typename TargetState, typename Event>
    void
    state_changed(FSM const& fsm, SourceState const& source,
            TargetState const& target, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_changed(fsm, source, target, event);
    }

    template < typename FSM, typename Event >
    void
    processed_in_state(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->processed_in_state(fsm, event);
    }

    template < typename FSM, typename Event >
    void
    enqueue_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->enqueue_event(fsm, event);
    }

    template < typename FSM >
    void
    start_process_events_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->start_process_events_queue(fsm);
    }

    template < typename FSM >
    void
    end_process_events_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->end_process_events_queue(fsm);
    }

    template < typename FSM, typename Event >
    void
    defer_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->defer_event(fsm, event);
    }

    template < typename FSM >
    void
    start_process_deferred_queue(FSM const& fsm, ::std::size_t size) const noexcept
    {
        if (observer_)
            observer_->start_process_deferred_queue(fsm, size);
    }

    template < typename FSM >
    void
    end_process_deferred_queue(FSM const& fsm, ::std::size_t remain) const noexcept
    {
        if (observer_)
            observer_->end_process_deferred_queue(fsm, remain);
    }

    template < typename FSM >
    void
    skip_processing_deferred_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->skip_processing_deferred_queue(fsm);
    }
    template < typename FSM >
    void
    postpone_deferred_events(FSM const& fsm, ::std::size_t count) const noexcept
    {
        if (observer_)
            observer_->postpone_deferred_events(fsm, count);
    }
    template < typename FSM >
    void
    drop_deferred_event(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->drop_deferred_event(fsm);
    }

    template < typename FSM, typename Event >
    void
    reject_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->reject_event(fsm, event);
    }
private:
    observer_ptr    observer_;
};

template <>
struct observer_wrapper<none> : null_observer {
};

}  /* namespace detail */
}  /* namespace afsm */

#endif /* AFSM_DETAIL_OBSERVER_HPP_ */
<commit_msg>Satisfy extra pedantic flags<commit_after>/*
 * observer.hpp
 *
 *  Created on: Jun 3, 2016
 *      Author: zmij
 */

#ifndef AFSM_DETAIL_OBSERVER_HPP_
#define AFSM_DETAIL_OBSERVER_HPP_

#include <afsm/fsm_fwd.hpp>
#include <afsm/detail/actions.hpp>
#include <afsm/detail/transitions.hpp>
#include <memory>

namespace afsm {
namespace detail {

struct null_observer {
    template < typename FSM, typename Event >
    void
    start_process_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM, typename State, typename Event >
    void
    state_entered(FSM const&, State const&, Event const&) const noexcept{}
    template < typename FSM, typename State, typename Event >
    void
    state_exited(FSM const&, State const&, Event const&) const noexcept{}
    template < typename FSM, typename State >
    void
    state_cleared(FSM const&, State const&) const noexcept{}

    template < typename FSM, typename SourceState, typename TargetState, typename Event>
    void
    state_changed(FSM const&, SourceState const&, TargetState const&, Event const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    processed_in_state(FSM const&, Event const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    enqueue_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM >
    void
    start_process_events_queue(FSM const&) const noexcept {}
    template < typename FSM >
    void
    end_process_events_queue(FSM const&) const noexcept {}

    template < typename FSM, typename Event >
    void
    defer_event(FSM const&, Event const&) const noexcept {}

    template < typename FSM >
    void
    start_process_deferred_queue(FSM const&, ::std::size_t size) const noexcept {}
    template < typename FSM >
    void
    end_process_deferred_queue(FSM const&, ::std::size_t remain) const noexcept {}

    template < typename FSM >
    void
    skip_processing_deferred_queue(FSM const&) const noexcept {}
    template < typename FSM >
    void
    postpone_deferred_events(FSM const&, ::std::size_t count) const noexcept {}
    template < typename FSM >
    void
    drop_deferred_event(FSM const&) const noexcept{}

    template < typename FSM, typename Event >
    void
    reject_event(FSM const&, Event const&) const noexcept {}
};

template < typename T >
class observer_wrapper {
public:
    using observer_ptr = ::std::shared_ptr<T>;
public:
    observer_wrapper()
        : observer_{} {}
    void
    set_observer(observer_ptr observer)
    {
        observer_ = observer;
    }

    template < typename ... Args >
    void
    make_observer(Args&& ... args)
    {
        observer_ = ::std::make_shared<T>(::std::forward<Args>(args)...);
    }
protected:
    template < typename FSM, typename FSM_DEF, typename Size >
    friend class transitions::state_transition_table;

    template < typename FSM, typename Event >
    void
    start_process_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->start_process_event(fsm, event);
    }

    template < typename FSM, typename State, typename Event >
    void
    state_entered(FSM const& fsm, State const& state, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_entered(fsm, state, event);
    }
    template < typename FSM, typename State, typename Event >
    void
    state_exited(FSM const& fsm, State const& state, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_exited(fsm, state, event);
    }
    template < typename FSM, typename State >
    void
    state_cleared(FSM const& fsm, State const& state) const noexcept
    {
        if (observer_)
            observer_->state_cleared(fsm, state);
    }
    template < typename FSM, typename SourceState, typename TargetState, typename Event>
    void
    state_changed(FSM const& fsm, SourceState const& source,
            TargetState const& target, Event const& event) const noexcept
    {
        if (observer_)
            observer_->state_changed(fsm, source, target, event);
    }

    template < typename FSM, typename Event >
    void
    processed_in_state(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->processed_in_state(fsm, event);
    }

    template < typename FSM, typename Event >
    void
    enqueue_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->enqueue_event(fsm, event);
    }

    template < typename FSM >
    void
    start_process_events_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->start_process_events_queue(fsm);
    }

    template < typename FSM >
    void
    end_process_events_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->end_process_events_queue(fsm);
    }

    template < typename FSM, typename Event >
    void
    defer_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->defer_event(fsm, event);
    }

    template < typename FSM >
    void
    start_process_deferred_queue(FSM const& fsm, ::std::size_t size) const noexcept
    {
        if (observer_)
            observer_->start_process_deferred_queue(fsm, size);
    }

    template < typename FSM >
    void
    end_process_deferred_queue(FSM const& fsm, ::std::size_t remain) const noexcept
    {
        if (observer_)
            observer_->end_process_deferred_queue(fsm, remain);
    }

    template < typename FSM >
    void
    skip_processing_deferred_queue(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->skip_processing_deferred_queue(fsm);
    }
    template < typename FSM >
    void
    postpone_deferred_events(FSM const& fsm, ::std::size_t count) const noexcept
    {
        if (observer_)
            observer_->postpone_deferred_events(fsm, count);
    }
    template < typename FSM >
    void
    drop_deferred_event(FSM const& fsm) const noexcept
    {
        if (observer_)
            observer_->drop_deferred_event(fsm);
    }

    template < typename FSM, typename Event >
    void
    reject_event(FSM const& fsm, Event const& event) const noexcept
    {
        if (observer_)
            observer_->reject_event(fsm, event);
    }
private:
    observer_ptr    observer_;
};

template <>
struct observer_wrapper<none> : null_observer {
};

}  /* namespace detail */
}  /* namespace afsm */

#endif /* AFSM_DETAIL_OBSERVER_HPP_ */
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/Interpreter.h"
//#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"

namespace cling {
namespace internal {
void symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   Interpreter I(1, argv);
   //cling_PrintValue(0);
   LookupHelper h(0,0);
   h.findType("", LookupHelper::NoDiagnostics);
   h.findScope("", LookupHelper::NoDiagnostics);
   h.findFunctionProto(0, "", "", LookupHelper::NoDiagnostics);
   h.findFunctionArgs(0, "", "", LookupHelper::NoDiagnostics);
   runtime::internal::DynamicExprInfo DEI(0,0,false);
   DEI.getExpr();
}
}
}
<commit_msg>Force inclusion of throwNullDerefException(), CMake needs it.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Axel Naumann <axel@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/Interpreter.h"
//#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"

extern "C" void cling__runtime__internal__throwNullDerefException(void*, void*);

namespace cling {
namespace internal {
void symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   Interpreter I(1, argv);
   //cling_PrintValue(0);
   LookupHelper h(0,0);
   h.findType("", LookupHelper::NoDiagnostics);
   h.findScope("", LookupHelper::NoDiagnostics);
   h.findFunctionProto(0, "", "", LookupHelper::NoDiagnostics);
   h.findFunctionArgs(0, "", "", LookupHelper::NoDiagnostics);
   runtime::internal::DynamicExprInfo DEI(0,0,false);
   cling__runtime__internal__throwNullDerefException(0, 0);
   DEI.getExpr();
}
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/adopt_policy.hpp>
#include <luabind/detail/debug.hpp>
#include <luabind/error.hpp>
#include <luabind/operator.hpp>

#include <boost/lexical_cast.hpp>

#include <utility>

using namespace luabind;

int test_object_param(const object& table)
{
	LUABIND_CHECK_STACK(table.interpreter());

	object current_object;
	current_object = table;
	lua_State* L = table.interpreter();

	if (type(table) == LUA_TTABLE)
	{
		int sum1 = 0;
		for (iterator i(table), e; i != e; ++i)
		{
			assert(type(*i) == LUA_TNUMBER);
			sum1 += object_cast<int>(*i);
		}

		int sum2 = 0;
		for (raw_iterator i(table), e; i != e; ++i)
		{
			assert(type(*i) == LUA_TNUMBER);
			sum2 += object_cast<int>(*i);
		}

		// test iteration of empty table
		object empty_table = newtable(L);
		for (iterator i(empty_table), e; i != e; ++i)
		{}

		table["sum1"] = sum1;
		table["sum2"] = sum2;
		table["blurp"] = 5;
		table["sum3"] = table["sum1"];
		return 0;
	}
	else
	{
		if (type(table) != LUA_TNIL)
		{
			return 1;
		}
		else
		{
			return 2;
		}
	}
}

int test_fun()
{
	return 42;
}

struct test_param : counted_type<test_param>
{
	luabind::object obj;
	luabind::object obj2;

	bool operator==(test_param const& rhs) const
	{ return obj == rhs.obj && obj2 == rhs.obj2; }
};

COUNTER_GUARD(test_param);

int test_match(const luabind::object& o)
{
	return 0;
}

int test_match(int i)
{
	return 1;
}

void test_match_object(
	luabind::object p1
  , luabind::object p2
  , luabind::object p3)
{
	p1["ret"] = 1;
	p2["ret"] = 2;
	p3["ret"] = 3;
}

void test_main(lua_State* L)
{
	using namespace luabind;

	module(L)
	[
		def("test_object_param", &test_object_param),
		def("test_fun", &test_fun),
		def("test_match", (int(*)(const luabind::object&))&test_match),
		def("test_match", (int(*)(int))&test_match),
		def("test_match_object", &test_match_object),

		class_<test_param>("test_param")
			.def(constructor<>())
			.def_readwrite("obj", &test_param::obj)
			.def_readonly("obj2", &test_param::obj2)
			.def(const_self == const_self)
	];

	object uninitialized;
	TEST_CHECK(!uninitialized);
	TEST_CHECK(!uninitialized.is_valid());

	test_param temp_object;
	globals(L)["temp"] = temp_object;
	TEST_CHECK(object_cast<test_param>(globals(L)["temp"]) == temp_object);
	globals(L)["temp"] = &temp_object;
	TEST_CHECK(object_cast<test_param const*>(globals(L)["temp"]) == &temp_object);
	TEST_CHECK(globals(L)["temp"] == temp_object);

	// test the registry
	object reg = registry(L);
	reg["__a"] = "foobar";
	TEST_CHECK(object_cast<std::string>(registry(L)["__a"]) == "foobar");

	DOSTRING(L,
		"t = 2\n"
		"assert(test_object_param(t) == 1)");

	DOSTRING(L, "assert(test_object_param(nil) == 2)");
	DOSTRING(L, "t = { ['oh'] = 4, 3, 5, 7, 13 }");
	DOSTRING(L, "assert(test_object_param(t) == 0)");
	DOSTRING(L, "assert(t.sum1 == 4 + 3 + 5 + 7 + 13)");
	DOSTRING(L, "assert(t.sum2 == 4 + 3 + 5 + 7 + 13)");
	DOSTRING(L, "assert(t.blurp == 5)");

	object g = globals(L);
	object ret = g["test_fun"]();
	TEST_CHECK(object_cast<int>(ret) == 42);

	DOSTRING(L, "function test_param_policies(x, y) end");
	object test_param_policies = g["test_param_policies"];
	int a = type(test_param_policies);
	TEST_CHECK(a == LUA_TFUNCTION);

	luabind::object obj;
	obj = luabind::object();

	// call the function and tell lua to adopt the pointer passed as first argument
	test_param_policies(5, new test_param())[adopt(_2)];

	DOSTRING(L, "assert(test_match(7) == 1)");
	DOSTRING(L, "assert(test_match('oo') == 0)");

	DOSTRING(L,
		"t = test_param()\n"
		"t.obj = 'foo'\n"
		"assert(t.obj == 'foo')\n"
		"assert(t.obj2 == nil)");

	DOSTRING(L,
		"function test_object_policies(a) glob = a\n"
		"return 6\n"
		"end");
	object test_object_policies = g["test_object_policies"];
	object ret_val = test_object_policies("teststring")[detail::null_type()];
	TEST_CHECK(object_cast<int>(ret_val) == 6);
	TEST_CHECK(ret_val == 6);
	TEST_CHECK(6 == ret_val);
	g["temp_val"] = 6;
	TEST_CHECK(ret_val == g["temp_val"]);
	object temp_val = g["temp_val"];
	TEST_CHECK(ret_val == temp_val);

	g["temp"] = "test string";
	TEST_CHECK(boost::lexical_cast<std::string>(g["temp"]) == "test string");
	g["temp"] = 6;
	TEST_CHECK(boost::lexical_cast<std::string>(g["temp"]) == "6");

	TEST_CHECK(object_cast<std::string>(g["glob"]) == "teststring");
	TEST_CHECK(object_cast<std::string>(gettable(g, "glob")) == "teststring");
	TEST_CHECK(object_cast<std::string>(rawget(g, "glob")) == "teststring");

	object t = newtable(L);
	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";

	TEST_CHECK(object_cast<std::string>(t["foo"]) == "bar");
	TEST_CHECK(object_cast<std::string>(*iterator(t)) == "bar");
	TEST_CHECK(object_cast<std::string>(*raw_iterator(t)) == "bar");

	t["foo"] = nil; // luabind::nil_type

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";
	iterator it1(t);
	*it1 = nil;

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";
	raw_iterator it2(t);
	*it2 = nil;

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	DOSTRING(L,
		"p1 = {}\n"
		"p2 = {}\n"
		"p3 = {}\n"
		"test_match_object(p1, p2, p3)\n"
		"assert(p1.ret == 1)\n"
		"assert(p2.ret == 2)\n"
		"assert(p3.ret == 3)\n");

#ifndef LUABIND_NO_EXCEPTIONS

	try
	{
		object not_initialized;
		int i = object_cast<int>(not_initialized);
		(void)i;
		TEST_ERROR("invalid cast succeeded");
	}
	catch(luabind::cast_failed&) {}

#endif

    object not_initialized;
    TEST_CHECK(!object_cast_nothrow<int>(not_initialized));
	 TEST_CHECK(!not_initialized.is_valid());
	 TEST_CHECK(!not_initialized);

    DOSTRING(L, "t = { {1}, {2}, {3}, {4} }");

    int inner_sum = 0;

    for (iterator i(globals(L)["t"]), e; i != e; ++i)
    {
        inner_sum += object_cast<int>((*i)[1]);
    }

    TEST_CHECK(inner_sum == 1 + 2 + 3 + 4);

    DOSTRING(L, "t = { {1, 2}, {3, 4}, {5, 6}, {7, 8} }");

    inner_sum = 0;

    for (iterator i(globals(L)["t"]), e; i != e; ++i)
    {
        for (iterator j(*i), e; j != e; ++j)
        {
            inner_sum += object_cast<int>(*j);
        }
    }

    TEST_CHECK(inner_sum == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
	TEST_CHECK(object_cast<int>(globals(L)["t"][2][2]) == 4);
}
<commit_msg>Added test for `object::operator()` of different arities.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/adopt_policy.hpp>
#include <luabind/detail/debug.hpp>
#include <luabind/error.hpp>
#include <luabind/operator.hpp>

#include <boost/lexical_cast.hpp>

#include <utility>

using namespace luabind;

int test_object_param(const object& table)
{
	LUABIND_CHECK_STACK(table.interpreter());

	object current_object;
	current_object = table;
	lua_State* L = table.interpreter();

	if (type(table) == LUA_TTABLE)
	{
		int sum1 = 0;
		for (iterator i(table), e; i != e; ++i)
		{
			assert(type(*i) == LUA_TNUMBER);
			sum1 += object_cast<int>(*i);
		}

		int sum2 = 0;
		for (raw_iterator i(table), e; i != e; ++i)
		{
			assert(type(*i) == LUA_TNUMBER);
			sum2 += object_cast<int>(*i);
		}

		// test iteration of empty table
		object empty_table = newtable(L);
		for (iterator i(empty_table), e; i != e; ++i)
		{}

		table["sum1"] = sum1;
		table["sum2"] = sum2;
		table["blurp"] = 5;
		table["sum3"] = table["sum1"];
		return 0;
	}
	else
	{
		if (type(table) != LUA_TNIL)
		{
			return 1;
		}
		else
		{
			return 2;
		}
	}
}

int test_fun()
{
	return 42;
}

struct test_param : counted_type<test_param>
{
	luabind::object obj;
	luabind::object obj2;

	bool operator==(test_param const& rhs) const
	{ return obj == rhs.obj && obj2 == rhs.obj2; }
};

COUNTER_GUARD(test_param);

int test_match(const luabind::object& o)
{
	return 0;
}

int test_match(int i)
{
	return 1;
}

void test_match_object(
	luabind::object p1
  , luabind::object p2
  , luabind::object p3)
{
	p1["ret"] = 1;
	p2["ret"] = 2;
	p3["ret"] = 3;
}

void test_call(lua_State* L)
{
    DOSTRING(L,
        "function sum(...)\n"
        "    local result = 0\n"
        "    for _,x in pairs({...}) do\n"
        "        result = result + x\n"
        "    end\n"
        "    return result\n"
        "end\n"
    );

    object sum = globals(L)["sum"];

    TEST_CHECK(object_cast<int>(sum()) == 0);
    TEST_CHECK(object_cast<int>(sum(1)) == 1);
    TEST_CHECK(object_cast<int>(sum(1,2)) == 3);
    TEST_CHECK(object_cast<int>(sum(1,2,3)) == 6);
    TEST_CHECK(object_cast<int>(sum(1,2,3,4)) == 10);
    TEST_CHECK(object_cast<int>(sum(1,2,3,4,5)) == 15);
}

void test_main(lua_State* L)
{
	using namespace luabind;

	module(L)
	[
		def("test_object_param", &test_object_param),
		def("test_fun", &test_fun),
		def("test_match", (int(*)(const luabind::object&))&test_match),
		def("test_match", (int(*)(int))&test_match),
		def("test_match_object", &test_match_object),

		class_<test_param>("test_param")
			.def(constructor<>())
			.def_readwrite("obj", &test_param::obj)
			.def_readonly("obj2", &test_param::obj2)
			.def(const_self == const_self)
	];

	object uninitialized;
	TEST_CHECK(!uninitialized);
	TEST_CHECK(!uninitialized.is_valid());

	test_param temp_object;
	globals(L)["temp"] = temp_object;
	TEST_CHECK(object_cast<test_param>(globals(L)["temp"]) == temp_object);
	globals(L)["temp"] = &temp_object;
	TEST_CHECK(object_cast<test_param const*>(globals(L)["temp"]) == &temp_object);
	TEST_CHECK(globals(L)["temp"] == temp_object);

	// test the registry
	object reg = registry(L);
	reg["__a"] = "foobar";
	TEST_CHECK(object_cast<std::string>(registry(L)["__a"]) == "foobar");

	DOSTRING(L,
		"t = 2\n"
		"assert(test_object_param(t) == 1)");

	DOSTRING(L, "assert(test_object_param(nil) == 2)");
	DOSTRING(L, "t = { ['oh'] = 4, 3, 5, 7, 13 }");
	DOSTRING(L, "assert(test_object_param(t) == 0)");
	DOSTRING(L, "assert(t.sum1 == 4 + 3 + 5 + 7 + 13)");
	DOSTRING(L, "assert(t.sum2 == 4 + 3 + 5 + 7 + 13)");
	DOSTRING(L, "assert(t.blurp == 5)");

	object g = globals(L);
	object ret = g["test_fun"]();
	TEST_CHECK(object_cast<int>(ret) == 42);

	DOSTRING(L, "function test_param_policies(x, y) end");
	object test_param_policies = g["test_param_policies"];
	int a = type(test_param_policies);
	TEST_CHECK(a == LUA_TFUNCTION);

	luabind::object obj;
	obj = luabind::object();

	// call the function and tell lua to adopt the pointer passed as first argument
	test_param_policies(5, new test_param())[adopt(_2)];

	DOSTRING(L, "assert(test_match(7) == 1)");
	DOSTRING(L, "assert(test_match('oo') == 0)");

	DOSTRING(L,
		"t = test_param()\n"
		"t.obj = 'foo'\n"
		"assert(t.obj == 'foo')\n"
		"assert(t.obj2 == nil)");

	DOSTRING(L,
		"function test_object_policies(a) glob = a\n"
		"return 6\n"
		"end");
	object test_object_policies = g["test_object_policies"];
	object ret_val = test_object_policies("teststring")[detail::null_type()];
	TEST_CHECK(object_cast<int>(ret_val) == 6);
	TEST_CHECK(ret_val == 6);
	TEST_CHECK(6 == ret_val);
	g["temp_val"] = 6;
	TEST_CHECK(ret_val == g["temp_val"]);
	object temp_val = g["temp_val"];
	TEST_CHECK(ret_val == temp_val);

	g["temp"] = "test string";
	TEST_CHECK(boost::lexical_cast<std::string>(g["temp"]) == "test string");
	g["temp"] = 6;
	TEST_CHECK(boost::lexical_cast<std::string>(g["temp"]) == "6");

	TEST_CHECK(object_cast<std::string>(g["glob"]) == "teststring");
	TEST_CHECK(object_cast<std::string>(gettable(g, "glob")) == "teststring");
	TEST_CHECK(object_cast<std::string>(rawget(g, "glob")) == "teststring");

	object t = newtable(L);
	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";

	TEST_CHECK(object_cast<std::string>(t["foo"]) == "bar");
	TEST_CHECK(object_cast<std::string>(*iterator(t)) == "bar");
	TEST_CHECK(object_cast<std::string>(*raw_iterator(t)) == "bar");

	t["foo"] = nil; // luabind::nil_type

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";
	iterator it1(t);
	*it1 = nil;

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	t["foo"] = "bar";
	raw_iterator it2(t);
	*it2 = nil;

	TEST_CHECK(iterator(t) == iterator());
	TEST_CHECK(raw_iterator(t) == raw_iterator());

	DOSTRING(L,
		"p1 = {}\n"
		"p2 = {}\n"
		"p3 = {}\n"
		"test_match_object(p1, p2, p3)\n"
		"assert(p1.ret == 1)\n"
		"assert(p2.ret == 2)\n"
		"assert(p3.ret == 3)\n");

#ifndef LUABIND_NO_EXCEPTIONS

	try
	{
		object not_initialized;
		int i = object_cast<int>(not_initialized);
		(void)i;
		TEST_ERROR("invalid cast succeeded");
	}
	catch(luabind::cast_failed&) {}

#endif

    object not_initialized;
    TEST_CHECK(!object_cast_nothrow<int>(not_initialized));
	 TEST_CHECK(!not_initialized.is_valid());
	 TEST_CHECK(!not_initialized);

    DOSTRING(L, "t = { {1}, {2}, {3}, {4} }");

    int inner_sum = 0;

    for (iterator i(globals(L)["t"]), e; i != e; ++i)
    {
        inner_sum += object_cast<int>((*i)[1]);
    }

    TEST_CHECK(inner_sum == 1 + 2 + 3 + 4);

    DOSTRING(L, "t = { {1, 2}, {3, 4}, {5, 6}, {7, 8} }");

    inner_sum = 0;

    for (iterator i(globals(L)["t"]), e; i != e; ++i)
    {
        for (iterator j(*i), e; j != e; ++j)
        {
            inner_sum += object_cast<int>(*j);
        }
    }

    TEST_CHECK(inner_sum == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8);
    TEST_CHECK(object_cast<int>(globals(L)["t"][2][2]) == 4);

    test_call(L);
}

<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/object.hpp"
#include "flusspferd/create/object.hpp"
#include "flusspferd/create/array.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/value_io.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "test_environment.hpp"
#include <iostream> //FIXME

BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture )

BOOST_AUTO_TEST_CASE( null_object ) {
  flusspferd::object null_object;
  BOOST_CHECK(null_object.is_null());

  BOOST_CHECK_EQUAL(null_object, null_object);

  flusspferd::object object_copy(null_object);
  BOOST_CHECK(null_object.is_null());

  BOOST_CHECK_EQUAL(null_object, object_copy);
}

BOOST_AUTO_TEST_CASE( plain_object ) {
  flusspferd::object const &plain_object =
    flusspferd::create<flusspferd::object>();
  BOOST_CHECK(!plain_object.is_null());

  BOOST_CHECK_EQUAL(plain_object, plain_object);
  BOOST_CHECK_NE(plain_object, flusspferd::object());

  flusspferd::object object_copy(plain_object);
  BOOST_CHECK(!object_copy.is_null());

  BOOST_CHECK_EQUAL(plain_object, object_copy);

  flusspferd::object const &plain_object2 =
    flusspferd::create<flusspferd::object>();
  BOOST_CHECK_NE(plain_object, plain_object2);
}

BOOST_AUTO_TEST_CASE( object_property ) {
  flusspferd::object obj = flusspferd::create<flusspferd::object>();
  std::string const name = "foobar";
  flusspferd::value const v(409);
  obj.set_property(name, v);
  BOOST_CHECK(obj.has_property(name));
  BOOST_CHECK_EQUAL(obj.get_property(name), v);
  obj.delete_property(name);
  BOOST_CHECK(!obj.has_property(name));
  flusspferd::value const empty;
  BOOST_CHECK_EQUAL(obj.get_property(name), empty);
}

BOOST_AUTO_TEST_CASE( object_property_value ) {
  flusspferd::object obj = flusspferd::create<flusspferd::object>();
  flusspferd::value const name = flusspferd::string("foobar");
  flusspferd::value const v(409);
  obj.set_property(name, v);
  BOOST_CHECK(obj.has_property(name));
  BOOST_CHECK_EQUAL(obj.get_property(name), v);
  obj.delete_property(name);
  BOOST_CHECK(!obj.has_property(name));
  flusspferd::value const empty;
  BOOST_CHECK_EQUAL(obj.get_property(name), empty);
}

BOOST_AUTO_TEST_CASE( function_as_object ) {
  flusspferd::value v = flusspferd::evaluate("(function () {})");
  BOOST_CHECK(!v.is_undefined());
  BOOST_CHECK(v.is_object());
  BOOST_CHECK(!v.is_null());
}

BOOST_AUTO_TEST_CASE( call_on_invalid ) {
  flusspferd::object invalid_object;
  BOOST_REQUIRE(invalid_object.is_null());

  flusspferd::object &obj = invalid_object;

#define X(a) BOOST_CHECK_THROW((a), flusspferd::exception)

  X(obj.seal(true));
  X(obj.parent());
  X(obj.prototype());
  X(obj.set_parent(flusspferd::object()));
  X(obj.set_prototype(flusspferd::object()));
  X((obj.apply(flusspferd::global(), flusspferd::arguments())))
  X((obj.call("toString", flusspferd::arguments())));
  X((obj.call(flusspferd::global(), flusspferd::arguments())));
  X(obj.call(flusspferd::arguments()));
  X(obj.define_property("abc"));
  X(obj.define_property(flusspferd::string()));
  X(obj.define_property(std::string("abc")));
  X(obj.set_property("abc", flusspferd::value()));
  X(obj.set_property(flusspferd::value(3), flusspferd::value()));
  X(obj.set_property(std::string("abc"), flusspferd::value()));
  X(obj.get_property("abc"));
  X(obj.get_property(std::string("abc")));
  X(obj.get_property(flusspferd::value(3)));
  X(obj.has_property("abc"));
  X(obj.has_property(std::string("abc")));
  X(obj.has_property(flusspferd::value(3)));
  X(obj.has_own_property("abc"));
  X(obj.has_own_property(std::string("abc")));
  X(obj.has_own_property(flusspferd::value(3)));
  X(obj.delete_property("abc"));
  X(obj.delete_property(std::string("abc")));
  X(obj.delete_property(flusspferd::value(3)));
  X(obj.begin());
  X(obj.end());
  BOOST_CHECK_EQUAL(obj.is_array(), false);

  X(obj.get_property_attributes("abc"));
  X(obj.get_property_attributes(std::string("abc")));
  X(obj.get_property_attributes(flusspferd::string()));

  //TODO
#undef X
}

BOOST_AUTO_TEST_CASE( recursive_loop_on_set_property ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.set_property( flusspferd::string(), flusspferd::string() );
}

BOOST_AUTO_TEST_CASE( set_properties ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.set_properties(flusspferd::value(1),2)("3",4);

  BOOST_CHECK_EQUAL(object.get_property("1"), flusspferd::value(2));
  BOOST_CHECK_EQUAL(object.get_property(flusspferd::value(3)), flusspferd::value(4));
}

BOOST_AUTO_TEST_CASE( define_properties ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.define_properties(flusspferd::read_only_property)(flusspferd::value(1),2)("3",4)("5");
  object.set_property("1", 5); //no effect
  object.set_property("5", 5); //no effect

  BOOST_CHECK_EQUAL(object.get_property("1"), flusspferd::value(2));
  BOOST_CHECK_EQUAL(object.get_property(flusspferd::value(3)), flusspferd::value(4));
  BOOST_CHECK_EQUAL(object.get_property("5"), flusspferd::value());
}

BOOST_AUTO_TEST_CASE( instance_of ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::array>());

  flusspferd::root_value ctor_Object(
      flusspferd::global().get_property("Object"));
  flusspferd::root_value ctor_Array(
      flusspferd::global().get_property("Array"));
  flusspferd::root_value ctor_Date(
      flusspferd::global().get_property("Date"));
  flusspferd::root_string string_Date("Object");

  BOOST_CHECK(object.instance_of(ctor_Object));
  BOOST_CHECK(object.instance_of(ctor_Array));
  BOOST_CHECK(!object.instance_of(ctor_Date));

  BOOST_CHECK_THROW(
      object.instance_of(string_Date),
      flusspferd::exception);

  BOOST_CHECK_THROW(
      object.instance_of(flusspferd::value()),
      flusspferd::exception);
  BOOST_CHECK_THROW(
      object.instance_of(flusspferd::object()),
      flusspferd::exception);
}

BOOST_AUTO_TEST_CASE( constructor ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::array>());

  flusspferd::root_value ctor_Object(
      flusspferd::global().get_property("Object"));
  flusspferd::root_value ctor_Array(
      flusspferd::global().get_property("Array"));

  flusspferd::root_value ctor(object.constructor());

  BOOST_CHECK_NE(ctor, flusspferd::value());
  BOOST_CHECK_NE(ctor, flusspferd::object());

  BOOST_CHECK_NE(ctor, ctor_Object);
  BOOST_CHECK_EQUAL(ctor, ctor_Array);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test: fix non-operational bug in test_object<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/object.hpp"
#include "flusspferd/create/object.hpp"
#include "flusspferd/create/array.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/value_io.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "test_environment.hpp"
#include <iostream> //FIXME

BOOST_FIXTURE_TEST_SUITE( with_context, context_fixture )

BOOST_AUTO_TEST_CASE( null_object ) {
  flusspferd::object null_object;
  BOOST_CHECK(null_object.is_null());

  BOOST_CHECK_EQUAL(null_object, null_object);

  flusspferd::object object_copy(null_object);
  BOOST_CHECK(null_object.is_null());

  BOOST_CHECK_EQUAL(null_object, object_copy);
}

BOOST_AUTO_TEST_CASE( plain_object ) {
  flusspferd::object const &plain_object =
    flusspferd::create<flusspferd::object>();
  BOOST_CHECK(!plain_object.is_null());

  BOOST_CHECK_EQUAL(plain_object, plain_object);
  BOOST_CHECK_NE(plain_object, flusspferd::object());

  flusspferd::object object_copy(plain_object);
  BOOST_CHECK(!object_copy.is_null());

  BOOST_CHECK_EQUAL(plain_object, object_copy);

  flusspferd::object const &plain_object2 =
    flusspferd::create<flusspferd::object>();
  BOOST_CHECK_NE(plain_object, plain_object2);
}

BOOST_AUTO_TEST_CASE( object_property ) {
  flusspferd::object obj = flusspferd::create<flusspferd::object>();
  std::string const name = "foobar";
  flusspferd::value const v(409);
  obj.set_property(name, v);
  BOOST_CHECK(obj.has_property(name));
  BOOST_CHECK_EQUAL(obj.get_property(name), v);
  obj.delete_property(name);
  BOOST_CHECK(!obj.has_property(name));
  flusspferd::value const empty;
  BOOST_CHECK_EQUAL(obj.get_property(name), empty);
}

BOOST_AUTO_TEST_CASE( object_property_value ) {
  flusspferd::object obj = flusspferd::create<flusspferd::object>();
  flusspferd::value const name = flusspferd::string("foobar");
  flusspferd::value const v(409);
  obj.set_property(name, v);
  BOOST_CHECK(obj.has_property(name));
  BOOST_CHECK_EQUAL(obj.get_property(name), v);
  obj.delete_property(name);
  BOOST_CHECK(!obj.has_property(name));
  flusspferd::value const empty;
  BOOST_CHECK_EQUAL(obj.get_property(name), empty);
}

BOOST_AUTO_TEST_CASE( function_as_object ) {
  flusspferd::value v = flusspferd::evaluate("(function () {})");
  BOOST_CHECK(!v.is_undefined());
  BOOST_CHECK(v.is_object());
  BOOST_CHECK(!v.is_null());
}

BOOST_AUTO_TEST_CASE( call_on_invalid ) {
  flusspferd::object invalid_object;
  BOOST_REQUIRE(invalid_object.is_null());

  flusspferd::object &obj = invalid_object;

#define X(a) BOOST_CHECK_THROW((a), flusspferd::exception)

  X(obj.seal(true));
  X(obj.parent());
  X(obj.prototype());
  X(obj.set_parent(flusspferd::object()));
  X(obj.set_prototype(flusspferd::object()));
  X((obj.apply(flusspferd::global(), flusspferd::arguments())))
  X((obj.call("toString", flusspferd::arguments())));
  X((obj.call(flusspferd::global(), flusspferd::arguments())));
  X(obj.call(flusspferd::arguments()));
  X(obj.define_property("abc"));
  X(obj.define_property(flusspferd::string()));
  X(obj.define_property(std::string("abc")));
  X(obj.set_property("abc", flusspferd::value()));
  X(obj.set_property(flusspferd::value(3), flusspferd::value()));
  X(obj.set_property(std::string("abc"), flusspferd::value()));
  X(obj.get_property("abc"));
  X(obj.get_property(std::string("abc")));
  X(obj.get_property(flusspferd::value(3)));
  X(obj.has_property("abc"));
  X(obj.has_property(std::string("abc")));
  X(obj.has_property(flusspferd::value(3)));
  X(obj.has_own_property("abc"));
  X(obj.has_own_property(std::string("abc")));
  X(obj.has_own_property(flusspferd::value(3)));
  X(obj.delete_property("abc"));
  X(obj.delete_property(std::string("abc")));
  X(obj.delete_property(flusspferd::value(3)));
  X(obj.begin());
  X(obj.end());
  BOOST_CHECK_EQUAL(obj.is_array(), false);

  X(obj.get_property_attributes("abc"));
  X(obj.get_property_attributes(std::string("abc")));
  X(obj.get_property_attributes(flusspferd::string()));

  //TODO
#undef X
}

BOOST_AUTO_TEST_CASE( recursive_loop_on_set_property ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.set_property( flusspferd::string(), flusspferd::string() );
}

BOOST_AUTO_TEST_CASE( set_properties ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.set_properties(flusspferd::value(1),2)("3",4);

  BOOST_CHECK_EQUAL(object.get_property("1"), flusspferd::value(2));
  BOOST_CHECK_EQUAL(object.get_property(flusspferd::value(3)), flusspferd::value(4));
}

BOOST_AUTO_TEST_CASE( define_properties ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::object>());

  object.define_properties(flusspferd::read_only_property)(flusspferd::value(1),2)("3",4)("5");
  object.set_property("1", 5); //no effect
  object.set_property("5", 5); //no effect

  BOOST_CHECK_EQUAL(object.get_property("1"), flusspferd::value(2));
  BOOST_CHECK_EQUAL(object.get_property(flusspferd::value(3)), flusspferd::value(4));
  BOOST_CHECK_EQUAL(object.get_property("5"), flusspferd::value());
}

BOOST_AUTO_TEST_CASE( instance_of ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::array>());

  flusspferd::root_value ctor_Object(
      flusspferd::global().get_property("Object"));
  flusspferd::root_value ctor_Array(
      flusspferd::global().get_property("Array"));
  flusspferd::root_value ctor_Date(
      flusspferd::global().get_property("Date"));
  flusspferd::root_string string_Date("Date");

  BOOST_CHECK(object.instance_of(ctor_Object));
  BOOST_CHECK(object.instance_of(ctor_Array));
  BOOST_CHECK(!object.instance_of(ctor_Date));

  BOOST_CHECK_THROW(
      object.instance_of(string_Date),
      flusspferd::exception);

  BOOST_CHECK_THROW(
      object.instance_of(flusspferd::value()),
      flusspferd::exception);
  BOOST_CHECK_THROW(
      object.instance_of(flusspferd::object()),
      flusspferd::exception);
}

BOOST_AUTO_TEST_CASE( constructor ) {
  flusspferd::root_object object(flusspferd::create<flusspferd::array>());

  flusspferd::root_value ctor_Object(
      flusspferd::global().get_property("Object"));
  flusspferd::root_value ctor_Array(
      flusspferd::global().get_property("Array"));

  flusspferd::root_value ctor(object.constructor());

  BOOST_CHECK_NE(ctor, flusspferd::value());
  BOOST_CHECK_NE(ctor, flusspferd::object());

  BOOST_CHECK_NE(ctor, ctor_Object);
  BOOST_CHECK_EQUAL(ctor, ctor_Array);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include "PotentialRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>

using namespace ::com::sun::star;

namespace chart
{

PotentialRegressionCurveCalculator::PotentialRegressionCurveCalculator() :
        m_fSlope( 0.0 ),
        m_fIntercept( 0.0 )
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
}

PotentialRegressionCurveCalculator::~PotentialRegressionCurveCalculator()
{}

// ____ XRegressionCurveCalculator ____
void SAL_CALL PotentialRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException, std::exception)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndBothPositive()));
    m_fSign = 1.0;

    size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        aValues = RegressionCalculationHelper::cleanup(
                    aXValues, aYValues,
                    RegressionCalculationHelper::isValidAndXPositiveAndYNegative());
         nMax = aValues.first.size();
         if( nMax == 0 )
         {
            ::rtl::math::setNan( & m_fSlope );
            ::rtl::math::setNan( & m_fIntercept );
            ::rtl::math::setNan( & m_fCorrelationCoeffitient );
            return;
         }
         m_fSign = -1.0;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += log( aValues.first[i] );
        fAverageY += log( m_fSign * aValues.second[i] );
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = log( aValues.first[i] ) - fAverageX;
        double fDeltaY = log( m_fSign * aValues.second[i] ) - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );

    m_fIntercept = m_fSign * exp( m_fIntercept );
}

double SAL_CALL PotentialRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException, std::exception)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fIntercept * pow( x, m_fSlope );
    }

    return fResult;
}

uno::Sequence< geometry::RealPoint2D > SAL_CALL PotentialRegressionCurveCalculator::getCurveValues(
    double min, double max, ::sal_Int32 nPointCount,
    const uno::Reference< chart2::XScaling >& xScalingX,
    const uno::Reference< chart2::XScaling >& xScalingY,
    sal_Bool bMaySkipPointsInCalculation )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException, std::exception)
{
    if( bMaySkipPointsInCalculation &&
        isLogarithmicScaling( xScalingX ) &&
        isLogarithmicScaling( xScalingY ))
    {
        // optimize result
        uno::Sequence< geometry::RealPoint2D > aResult( 2 );
        aResult[0].X = min;
        aResult[0].Y = this->getCurveValue( min );
        aResult[1].X = max;
        aResult[1].Y = this->getCurveValue( max );

        return aResult;
    }
    return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation );
}

OUString PotentialRegressionCurveCalculator::ImplGetRepresentation(
    const uno::Reference< util::XNumberFormatter >& xNumFormatter,
    ::sal_Int32 nNumberFormatKey ) const
{
    OUStringBuffer aBuf( "f(x) = ");

    if( m_fIntercept == 0.0 )
    {
        aBuf.append( '0');
    }
    else if( m_fSlope == 0.0 )
    {
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
    }
    else
    {
        if( ! rtl::math::approxEqual( m_fIntercept, 1.0 ) )
        {
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
            aBuf.append( ' ');
        }
        if( m_fSlope != 0.0 )
        {
            aBuf.append( "x^" );
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope ));
        }
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1308146 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include "PotentialRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>

using namespace ::com::sun::star;

namespace chart
{

PotentialRegressionCurveCalculator::PotentialRegressionCurveCalculator()
    : m_fSlope(0.0)
    , m_fIntercept(0.0)
    , m_fSign(1.0)
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
}

PotentialRegressionCurveCalculator::~PotentialRegressionCurveCalculator()
{}

// ____ XRegressionCurveCalculator ____
void SAL_CALL PotentialRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException, std::exception)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndBothPositive()));
    m_fSign = 1.0;

    size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        aValues = RegressionCalculationHelper::cleanup(
                    aXValues, aYValues,
                    RegressionCalculationHelper::isValidAndXPositiveAndYNegative());
         nMax = aValues.first.size();
         if( nMax == 0 )
         {
            ::rtl::math::setNan( & m_fSlope );
            ::rtl::math::setNan( & m_fIntercept );
            ::rtl::math::setNan( & m_fCorrelationCoeffitient );
            return;
         }
         m_fSign = -1.0;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += log( aValues.first[i] );
        fAverageY += log( m_fSign * aValues.second[i] );
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = log( aValues.first[i] ) - fAverageX;
        double fDeltaY = log( m_fSign * aValues.second[i] ) - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );

    m_fIntercept = m_fSign * exp( m_fIntercept );
}

double SAL_CALL PotentialRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException, std::exception)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fIntercept * pow( x, m_fSlope );
    }

    return fResult;
}

uno::Sequence< geometry::RealPoint2D > SAL_CALL PotentialRegressionCurveCalculator::getCurveValues(
    double min, double max, ::sal_Int32 nPointCount,
    const uno::Reference< chart2::XScaling >& xScalingX,
    const uno::Reference< chart2::XScaling >& xScalingY,
    sal_Bool bMaySkipPointsInCalculation )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException, std::exception)
{
    if( bMaySkipPointsInCalculation &&
        isLogarithmicScaling( xScalingX ) &&
        isLogarithmicScaling( xScalingY ))
    {
        // optimize result
        uno::Sequence< geometry::RealPoint2D > aResult( 2 );
        aResult[0].X = min;
        aResult[0].Y = this->getCurveValue( min );
        aResult[1].X = max;
        aResult[1].Y = this->getCurveValue( max );

        return aResult;
    }
    return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation );
}

OUString PotentialRegressionCurveCalculator::ImplGetRepresentation(
    const uno::Reference< util::XNumberFormatter >& xNumFormatter,
    ::sal_Int32 nNumberFormatKey ) const
{
    OUStringBuffer aBuf( "f(x) = ");

    if( m_fIntercept == 0.0 )
    {
        aBuf.append( '0');
    }
    else if( m_fSlope == 0.0 )
    {
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
    }
    else
    {
        if( ! rtl::math::approxEqual( m_fIntercept, 1.0 ) )
        {
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
            aBuf.append( ' ');
        }
        if( m_fSlope != 0.0 )
        {
            aBuf.append( "x^" );
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope ));
        }
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed 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.
 *****************************************************************************/

/**
 * @file : piecewise_smoothing_spline_constraint.h
 * @brief: wrap up solver constraint interface with direct methods and preset
 *methods
 **/

#include "modules/planning/math/smoothing_spline/spline_1d_kernel.h"

#include <algorithm>

#include "cyber/common/log.h"
#include "modules/planning/math/smoothing_spline/spline_seg_kernel.h"

namespace apollo {
namespace planning {

Spline1dKernel::Spline1dKernel(const Spline1d& spline1d)
    : Spline1dKernel(spline1d.x_knots(), spline1d.spline_order()) {}

Spline1dKernel::Spline1dKernel(const std::vector<double>& x_knots,
                               const uint32_t spline_order)
    : x_knots_(x_knots), spline_order_(spline_order) {
  total_params_ =
      (x_knots.size() > 1 ? (x_knots.size() - 1) * (1 + spline_order_) : 0);
  kernel_matrix_ = Eigen::MatrixXd::Zero(total_params_, total_params_);
  offset_ = Eigen::MatrixXd::Zero(total_params_, 1);
}

void Spline1dKernel::AddRegularization(const double regularized_param) {
  Eigen::MatrixXd id_matrix =
      Eigen::MatrixXd::Identity(kernel_matrix_.rows(), kernel_matrix_.cols());
  kernel_matrix_ += 2.0 * id_matrix * regularized_param;
}

bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
                               const Eigen::MatrixXd& offset,
                               const double weight) {
  if (kernel.rows() != kernel.cols() ||
      kernel.rows() != kernel_matrix_.rows() || offset.cols() != 1 ||
      offset.rows() != offset_.rows()) {
    return false;
  }
  kernel_matrix_ += kernel * weight;
  offset_ += offset * weight;
  return true;
}

bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
                               const double weight) {
  Eigen::MatrixXd offset = Eigen::MatrixXd::Zero(kernel.rows(), 1);
  return AddKernel(kernel, offset, weight);
}

Eigen::MatrixXd* Spline1dKernel::mutable_kernel_matrix() {
  return &kernel_matrix_;
}

Eigen::MatrixXd* Spline1dKernel::mutable_offset() { return &offset_; }

const Eigen::MatrixXd& Spline1dKernel::kernel_matrix() const {
  return kernel_matrix_;
}

const Eigen::MatrixXd& Spline1dKernel::offset() const { return offset_; }

// build-in kernel methods
void Spline1dKernel::AddNthDerivativekernelMatrix(const uint32_t n,
                                                  const double weight) {
  const uint32_t num_params = spline_order_ + 1;
  for (uint32_t i = 0; i + 1 < x_knots_.size(); ++i) {
    Eigen::MatrixXd cur_kernel =
        2 *
        SplineSegKernel::Instance()->NthDerivativeKernel(
            n, num_params, x_knots_[i + 1] - x_knots_[i]) *
        weight;
    kernel_matrix_.block(i * num_params, i * num_params, num_params,
                         num_params) += cur_kernel;
  }
}

void Spline1dKernel::AddDerivativeKernelMatrix(const double weight) {
  AddNthDerivativekernelMatrix(1, weight);
}

void Spline1dKernel::AddSecondOrderDerivativeMatrix(const double weight) {
  AddNthDerivativekernelMatrix(2, weight);
}

void Spline1dKernel::AddThirdOrderDerivativeMatrix(const double weight) {
  AddNthDerivativekernelMatrix(3, weight);
}

void Spline1dKernel::AddNthDerivativekernelMatrixForSplineK(
    const uint32_t n, const uint32_t k, const double weight) {
  if (k + 1 >= x_knots_.size()) {
    AERROR << "Cannot add NthDerivativeKernel for spline K because k is out of "
              "range. k = "
           << k;
    return;
  }
  const uint32_t num_params = spline_order_ + 1;
  Eigen::MatrixXd cur_kernel =
      2 *
      SplineSegKernel::Instance()->NthDerivativeKernel(
          n, num_params, x_knots_[k + 1] - x_knots_[k]) *
      weight;
  kernel_matrix_.block(k * num_params, k * num_params, num_params,
                       num_params) += cur_kernel;
}

void Spline1dKernel::AddDerivativeKernelMatrixForSplineK(const uint32_t k,
                                                         const double weight) {
  AddNthDerivativekernelMatrixForSplineK(1, k, weight);
}

void Spline1dKernel::AddSecondOrderDerivativeMatrixForSplineK(
    const uint32_t k, const double weight) {
  AddNthDerivativekernelMatrixForSplineK(2, k, weight);
}

void Spline1dKernel::AddThirdOrderDerivativeMatrixForSplineK(
    const uint32_t k, const double weight) {
  AddNthDerivativekernelMatrixForSplineK(3, k, weight);
}

bool Spline1dKernel::AddReferenceLineKernelMatrix(
    const std::vector<double>& x_coord, const std::vector<double>& ref_x,
    const double weight) {
  if (ref_x.size() != x_coord.size()) {
    return false;
  }

  const uint32_t num_params = spline_order_ + 1;
  for (uint32_t i = 0; i < x_coord.size(); ++i) {
    double cur_index = FindIndex(x_coord[i]);
    double cur_rel_x = x_coord[i] - x_knots_[cur_index];
    // update offset
    double offset_coef = -2.0 * ref_x[i] * weight;
    for (uint32_t j = 0; j < num_params; ++j) {
      offset_(j + cur_index * num_params, 0) += offset_coef;
      offset_coef *= cur_rel_x;
    }
    // update kernel matrix
    Eigen::MatrixXd ref_kernel(num_params, num_params);

    double cur_x = 1.0;
    std::vector<double> power_x;
    for (uint32_t n = 0; n + 1 < 2 * num_params; ++n) {
      power_x.emplace_back(cur_x);
      cur_x *= cur_rel_x;
    }

    for (uint32_t r = 0; r < num_params; ++r) {
      for (uint32_t c = 0; c < num_params; ++c) {
        ref_kernel(r, c) = 2.0 * power_x[r + c];
      }
    }

    kernel_matrix_.block(cur_index * num_params, cur_index * num_params,
                         num_params, num_params) += weight * ref_kernel;
  }
  return true;
}

uint32_t Spline1dKernel::FindIndex(const double x) const {
  auto upper_bound = std::upper_bound(x_knots_.begin() + 1, x_knots_.end(), x);
  return std::min(static_cast<uint32_t>(x_knots_.size() - 1),
                  static_cast<uint32_t>(upper_bound - x_knots_.begin())) -
         1;
}

void Spline1dKernel::AddDistanceOffset(const double weight) {
  for (uint32_t i = 1; i < x_knots_.size(); ++i) {
    const double cur_x = x_knots_[i] - x_knots_[i - 1];
    double pw_x = 2.0 * weight;
    for (uint32_t j = 0; j < spline_order_ + 1; ++j) {
      offset_((i - 1) * (spline_order_ + 1) + j, 0) -= pw_x;
      pw_x *= cur_x;
    }
  }
}
}  // namespace planning
}  // namespace apollo
<commit_msg>planning: fix spline_1d_kernel compile warning.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed 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.
 *****************************************************************************/

/**
 * @file : piecewise_smoothing_spline_constraint.h
 * @brief: wrap up solver constraint interface with direct methods and preset
 *methods
 **/

#include "modules/planning/math/smoothing_spline/spline_1d_kernel.h"

#include <algorithm>

#include "cyber/common/log.h"
#include "modules/planning/math/smoothing_spline/spline_seg_kernel.h"

namespace apollo {
namespace planning {

Spline1dKernel::Spline1dKernel(const Spline1d& spline1d)
    : Spline1dKernel(spline1d.x_knots(), spline1d.spline_order()) {}

Spline1dKernel::Spline1dKernel(const std::vector<double>& x_knots,
                               const uint32_t spline_order)
    : x_knots_(x_knots), spline_order_(spline_order) {
  total_params_ =
      (static_cast<uint32_t>(x_knots.size()) > 1
           ? (static_cast<uint32_t>(x_knots.size()) - 1) * (1 + spline_order_)
           : 0);
  kernel_matrix_ = Eigen::MatrixXd::Zero(total_params_, total_params_);
  offset_ = Eigen::MatrixXd::Zero(total_params_, 1);
}

void Spline1dKernel::AddRegularization(const double regularized_param) {
  Eigen::MatrixXd id_matrix =
      Eigen::MatrixXd::Identity(kernel_matrix_.rows(), kernel_matrix_.cols());
  kernel_matrix_ += 2.0 * id_matrix * regularized_param;
}

bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
                               const Eigen::MatrixXd& offset,
                               const double weight) {
  if (kernel.rows() != kernel.cols() ||
      kernel.rows() != kernel_matrix_.rows() || offset.cols() != 1 ||
      offset.rows() != offset_.rows()) {
    return false;
  }
  kernel_matrix_ += kernel * weight;
  offset_ += offset * weight;
  return true;
}

bool Spline1dKernel::AddKernel(const Eigen::MatrixXd& kernel,
                               const double weight) {
  Eigen::MatrixXd offset = Eigen::MatrixXd::Zero(kernel.rows(), 1);
  return AddKernel(kernel, offset, weight);
}

Eigen::MatrixXd* Spline1dKernel::mutable_kernel_matrix() {
  return &kernel_matrix_;
}

Eigen::MatrixXd* Spline1dKernel::mutable_offset() { return &offset_; }

const Eigen::MatrixXd& Spline1dKernel::kernel_matrix() const {
  return kernel_matrix_;
}

const Eigen::MatrixXd& Spline1dKernel::offset() const { return offset_; }

// build-in kernel methods
void Spline1dKernel::AddNthDerivativekernelMatrix(const uint32_t n,
                                                  const double weight) {
  const uint32_t num_params = spline_order_ + 1;
  for (uint32_t i = 0; i + 1 < x_knots_.size(); ++i) {
    Eigen::MatrixXd cur_kernel =
        2 *
        SplineSegKernel::Instance()->NthDerivativeKernel(
            n, num_params, x_knots_[i + 1] - x_knots_[i]) *
        weight;
    kernel_matrix_.block(i * num_params, i * num_params, num_params,
                         num_params) += cur_kernel;
  }
}

void Spline1dKernel::AddDerivativeKernelMatrix(const double weight) {
  AddNthDerivativekernelMatrix(1, weight);
}

void Spline1dKernel::AddSecondOrderDerivativeMatrix(const double weight) {
  AddNthDerivativekernelMatrix(2, weight);
}

void Spline1dKernel::AddThirdOrderDerivativeMatrix(const double weight) {
  AddNthDerivativekernelMatrix(3, weight);
}

void Spline1dKernel::AddNthDerivativekernelMatrixForSplineK(
    const uint32_t n, const uint32_t k, const double weight) {
  if (k + 1 >= x_knots_.size()) {
    AERROR << "Cannot add NthDerivativeKernel for spline K because k is out of "
              "range. k = "
           << k;
    return;
  }
  const uint32_t num_params = spline_order_ + 1;
  Eigen::MatrixXd cur_kernel =
      2 *
      SplineSegKernel::Instance()->NthDerivativeKernel(
          n, num_params, x_knots_[k + 1] - x_knots_[k]) *
      weight;
  kernel_matrix_.block(k * num_params, k * num_params, num_params,
                       num_params) += cur_kernel;
}

void Spline1dKernel::AddDerivativeKernelMatrixForSplineK(const uint32_t k,
                                                         const double weight) {
  AddNthDerivativekernelMatrixForSplineK(1, k, weight);
}

void Spline1dKernel::AddSecondOrderDerivativeMatrixForSplineK(
    const uint32_t k, const double weight) {
  AddNthDerivativekernelMatrixForSplineK(2, k, weight);
}

void Spline1dKernel::AddThirdOrderDerivativeMatrixForSplineK(
    const uint32_t k, const double weight) {
  AddNthDerivativekernelMatrixForSplineK(3, k, weight);
}

bool Spline1dKernel::AddReferenceLineKernelMatrix(
    const std::vector<double>& x_coord, const std::vector<double>& ref_x,
    const double weight) {
  if (ref_x.size() != x_coord.size()) {
    return false;
  }

  const uint32_t num_params = spline_order_ + 1;
  for (size_t i = 0; i < x_coord.size(); ++i) {
    auto cur_index = FindIndex(x_coord[i]);
    double cur_rel_x = x_coord[i] - x_knots_[cur_index];
    // update offset
    double offset_coef = -2.0 * ref_x[i] * weight;
    for (size_t j = 0; j < num_params; ++j) {
      offset_(j + cur_index * num_params, 0) += offset_coef;
      offset_coef *= cur_rel_x;
    }
    // update kernel matrix
    Eigen::MatrixXd ref_kernel(num_params, num_params);

    double cur_x = 1.0;
    std::vector<double> power_x;
    for (uint32_t n = 0; n + 1 < 2 * num_params; ++n) {
      power_x.emplace_back(cur_x);
      cur_x *= cur_rel_x;
    }

    for (uint32_t r = 0; r < num_params; ++r) {
      for (uint32_t c = 0; c < num_params; ++c) {
        ref_kernel(r, c) = 2.0 * power_x[r + c];
      }
    }

    kernel_matrix_.block(cur_index * num_params, cur_index * num_params,
                         num_params, num_params) += weight * ref_kernel;
  }
  return true;
}

uint32_t Spline1dKernel::FindIndex(const double x) const {
  auto upper_bound = std::upper_bound(x_knots_.begin() + 1, x_knots_.end(), x);
  return std::min(static_cast<uint32_t>(x_knots_.size() - 1),
                  static_cast<uint32_t>(upper_bound - x_knots_.begin())) -
         1;
}

void Spline1dKernel::AddDistanceOffset(const double weight) {
  for (uint32_t i = 1; i < x_knots_.size(); ++i) {
    const double cur_x = x_knots_[i] - x_knots_[i - 1];
    double pw_x = 2.0 * weight;
    for (uint32_t j = 0; j < spline_order_ + 1; ++j) {
      offset_((i - 1) * (spline_order_ + 1) + j, 0) -= pw_x;
      pw_x *= cur_x;
    }
  }
}
}  // namespace planning
}  // namespace apollo
<|endoftext|>