<commit_before>//  Copyright (c) 2014, Google Inc.  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.
#include <iostream>

#include <gflags/gflags.h>
#include <glog/logging.h>

#include "auth.h"
#include "tao/util.h"

using std::string;

using tao::Base64WEncode;
using tao::InitializeApp;
using tao::MarshalKeyPrin;
using tao::MarshalSpeaksfor;

int main(int argc, char **argv) {
  InitializeApp(&argc, &argv, false);

  // A fake key for the parent.
  string taoKeyName("test tao key");
  string taoName;
  if (!MarshalKeyPrin(taoKeyName, &taoName)) {
    LOG(FATAL) << "Could not marshal a fake key auth.Prin value";
  }

  // A dummy key string to encode as bytes in MarshalSpeaksfor
  string testKey("test key");
  string speaksfor;
  if (!MarshalSpeaksfor(testKey, taoName, &speaksfor)) {
    LOG(FATAL) << "Could not marshal a speaksfor statement";
  }

  string encoded;
  if (!Base64WEncode(speaksfor, &encoded)) {
    LOG(FATAL) << "Could not encode the speaksfor in Base64W";
  }

  std::cout << encoded << std::endl;
  return 0;
}
<commit_msg>Add a test of the generated marshalling code.<commit_after>//  Copyright (c) 2014, Google Inc.  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.
#include <iostream>

#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/stubs/common.h>

#include "auth.h"
#include "tao/util.h"

using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::StringOutputStream;
using std::string;
using tao::Base64WEncode;
using tao::Bytes;
using tao::InitializeApp;
using tao::MarshalKeyPrin;
using tao::MarshalSpeaksfor;
using tao::Prin;
using tao::PrinExt;
using tao::SubPrin;

namespace {
// This is the canonical implementation of make_unique for C++11. It is wrapped
// in an anonymous namespace to keep it from conflicting with the real thing if
// it exists.
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
}  // namespace

int main(int argc, char **argv) {
  InitializeApp(&argc, &argv, false);

  Prin p;
  p.type_ = "key";

  auto bytes = make_unique<Bytes>();
  bytes->elt_ = "These are not key bytes";
  p.key_ = std::move(bytes);

  p.ext_ = make_unique<SubPrin>();
  auto ext = make_unique<PrinExt>();
  ext->name_ = "Validated";
  p.ext_->elts_.emplace_back(std::move(ext));

  string serialized_prin;
  {
    StringOutputStream raw_output_stream(&serialized_prin);
    CodedOutputStream output_stream(&raw_output_stream);
    p.Marshal(&output_stream);
  }

  string encoded_prin;
  if (!Base64WEncode(serialized_prin, &encoded_prin)) {
    LOG(FATAL) << "Could not encode the prin in Base64W";
  }

  std::cout << "A Prin encoded with Base64W:" << std::endl;
  std::cout << encoded_prin << std::endl;

  // A fake key for the parent.
  string taoKeyName("test tao key");
  string taoName;
  if (!MarshalKeyPrin(taoKeyName, &taoName)) {
    LOG(FATAL) << "Could not marshal a fake key auth.Prin value";
  }

  // A dummy key string to encode as bytes in MarshalSpeaksfor
  string testKey("test key");
  string speaksfor;
  if (!MarshalSpeaksfor(testKey, taoName, &speaksfor)) {
    LOG(FATAL) << "Could not marshal a speaksfor statement";
  }

  string encoded;
  if (!Base64WEncode(speaksfor, &encoded)) {
    LOG(FATAL) << "Could not encode the speaksfor in Base64W";
  }

  std::cout << "A Speaksfor encoded with Base64W:" << std::endl;
  std::cout << encoded << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_REGFILE_HH__
#define __ARCH_X86_REGFILE_HH__

#include "arch/x86/floatregfile.hh"
#include "arch/x86/intregfile.hh"
#include "arch/x86/isa_traits.hh"
#include "arch/x86/miscregfile.hh"
#include "arch/x86/types.hh"
#include "sim/host.hh"

#include <string>

class Checkpoint;

namespace X86ISA
{
    class RegFile
    {
      protected:
        Addr rip; //Program Counter
        Addr nextRip; //Next Program Counter

      public:
        Addr readPC();
        void SetPC(Addr val);

        Addr readNextPC();
        void setNextPC(Addr val);

        Addr readNextNPC();
        void setNextNPC(Addr val);

      protected:
        IntRegFile intRegFile; // integer register file
        FloatRegFile floatRegFile; // floating point register file
        MiscRegFile miscRegFile; // control register file

      public:

        void clear();

        int FlattenIntIndex(int reg);

        MiscReg readMiscReg(int miscReg);

        MiscReg readMiscRegWithEffect(int miscReg, ThreadContext *tc);

        void setMiscReg(int miscReg, const MiscReg &val);

        void setMiscRegWithEffect(int miscReg, const MiscReg &val,
                ThreadContext * tc);

        int instAsid()
        {
            //XXX This doesn't make sense in x86
            return 0;
        }

        int dataAsid()
        {
            //XXX This doesn't make sense in x86
            return 0;
        }

        FloatReg readFloatReg(int floatReg, int width);

        FloatReg readFloatReg(int floatReg);

        FloatRegBits readFloatRegBits(int floatReg, int width);

        FloatRegBits readFloatRegBits(int floatReg);

        void setFloatReg(int floatReg, const FloatReg &val, int width);

        void setFloatReg(int floatReg, const FloatReg &val);

        void setFloatRegBits(int floatReg, const FloatRegBits &val, int width);

        void setFloatRegBits(int floatReg, const FloatRegBits &val);

        IntReg readIntReg(int intReg);

        void setIntReg(int intReg, const IntReg &val);

        void serialize(std::ostream &os);
        void unserialize(Checkpoint *cp, const std::string &section);

      public:

        void changeContext(RegContextParam param, RegContextVal val);
    };

    int flattenIntIndex(ThreadContext * tc, int reg);

    void copyRegs(ThreadContext *src, ThreadContext *dest);

    void copyMiscRegs(ThreadContext *src, ThreadContext *dest);

    int InterruptLevel(uint64_t softint);

}; // namespace X86ISA

#endif // __ARCH_X86_REGFILE_HH__
<commit_msg>Correct a typo<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_REGFILE_HH__
#define __ARCH_X86_REGFILE_HH__

#include "arch/x86/floatregfile.hh"
#include "arch/x86/intregfile.hh"
#include "arch/x86/isa_traits.hh"
#include "arch/x86/miscregfile.hh"
#include "arch/x86/types.hh"
#include "sim/host.hh"

#include <string>

class Checkpoint;

namespace X86ISA
{
    class RegFile
    {
      protected:
        Addr rip; //Program Counter
        Addr nextRip; //Next Program Counter

      public:
        Addr readPC();
        void setPC(Addr val);

        Addr readNextPC();
        void setNextPC(Addr val);

        Addr readNextNPC();
        void setNextNPC(Addr val);

      protected:
        IntRegFile intRegFile; // integer register file
        FloatRegFile floatRegFile; // floating point register file
        MiscRegFile miscRegFile; // control register file

      public:

        void clear();

        int FlattenIntIndex(int reg);

        MiscReg readMiscReg(int miscReg);

        MiscReg readMiscRegWithEffect(int miscReg, ThreadContext *tc);

        void setMiscReg(int miscReg, const MiscReg &val);

        void setMiscRegWithEffect(int miscReg, const MiscReg &val,
                ThreadContext * tc);

        int instAsid()
        {
            //XXX This doesn't make sense in x86
            return 0;
        }

        int dataAsid()
        {
            //XXX This doesn't make sense in x86
            return 0;
        }

        FloatReg readFloatReg(int floatReg, int width);

        FloatReg readFloatReg(int floatReg);

        FloatRegBits readFloatRegBits(int floatReg, int width);

        FloatRegBits readFloatRegBits(int floatReg);

        void setFloatReg(int floatReg, const FloatReg &val, int width);

        void setFloatReg(int floatReg, const FloatReg &val);

        void setFloatRegBits(int floatReg, const FloatRegBits &val, int width);

        void setFloatRegBits(int floatReg, const FloatRegBits &val);

        IntReg readIntReg(int intReg);

        void setIntReg(int intReg, const IntReg &val);

        void serialize(std::ostream &os);
        void unserialize(Checkpoint *cp, const std::string &section);

      public:

        void changeContext(RegContextParam param, RegContextVal val);
    };

    int flattenIntIndex(ThreadContext * tc, int reg);

    void copyRegs(ThreadContext *src, ThreadContext *dest);

    void copyMiscRegs(ThreadContext *src, ThreadContext *dest);

    int InterruptLevel(uint64_t softint);

}; // namespace X86ISA

#endif // __ARCH_X86_REGFILE_HH__
<|endoftext|>


<commit_before>#include "details/compiler/compiler.h"
#include "details/compiler/compdb.h"
#include "details/program/program.h"
#include "details/reporting/report.h"
#include "details/errors/errors.h"
#include "details/pass/a-src2ast/ast-from-source.h"
#include "details/pass/b-ast-normalize/normalize.h"
#include "details/pass/c-ast2ir/source-ast-to-ir.h"
#include "details/pass/d-object-map/attach.h"
#include "details/semantic/atom-factory.h"
#include "details/intrinsic/std.core.h"
#include "libnanyc-config.h"
#include "libnanyc-traces.h"
#include "embed-nsl.hxx" // generated
#include <yuni/io/file.h>
#include <libnanyc.h>
#include <utility>
#include <memory>
#include <iostream>

namespace ny {
namespace compiler {

namespace {

constexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;

Logs::Report buildGenerateReport(void* ptr, Logs::Level level) {
	return (*((ny::Logs::Report*) ptr)).fromErrLevel(level);
}

void copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {
	if (opts.filename.len != 0) {
		if (unlikely(opts.filename.len > memoryHardlimit))
			throw "input filename bigger than internal limit";
		yuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});
		source.filename = source.storageFilename;
	}
	if (opts.content.len != 0) {
		if (unlikely(opts.content.len > memoryHardlimit))
			throw "input source content bigger than internal limit";
		source.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));
		source.content = source.storageContent;
	}
}

bool compileSource(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts) {
	auto report = mainreport.subgroup();
	report.data().origins.location.filename = source.filename;
	report.data().origins.location.target.clear();
	bool compiled = true;
	compiled &= makeASTFromSource(source);
	compiled &= passDuplicateAndNormalizeAST(source, report);
	compiled &= passTransformASTToIR(source, report, gopts);
	compiled  = compiled and attach(compdb, source);
	return compiled;
}

bool importSourceAndCompile(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts, const nysource_opts_t& opts) {
	copySourceOpts(source, opts);
	return compileSource(mainreport, compdb, source, gopts);
}

Atom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {
	Atom* atom = nullptr;
	root.eachChild(entrypoint, [&](Atom & child) -> bool {
		if (unlikely(atom != nullptr))
			throw "': multiple entry points found";
		atom = &child;
		return true;
	});
	if (unlikely(!atom))
		throw "()': function not found";
	if (unlikely(not atom->isFunction() or atom->isClassMember()))
		throw "': the atom is not a function";
	return *atom;
}

bool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {
	using ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);
	try {
		auto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);
		ParameterList params;
		ParameterList tmplparams;
		ClassdefTableView cdeftblView{compdb.cdeftable};
		ny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);
		bool instanciated = ny::semantic::instanciateAtom(settings);
		report.appendEntry(settings.report);
		if (config::traces::atomTable)
			compdb.cdeftable.atoms.root.printTree(compdb.cdeftable);
		if (likely(instanciated)) {
			compdb.entrypoint.atomid = atom.atomid;
			compdb.entrypoint.instanceid = settings.instanceid;
			return true;
		}
	}
	catch (const char* e) {
		report.error() << "failed to instanciate '" << entrypoint << e;
	}
	compdb.entrypoint.atomid = (uint32_t) -1;
	compdb.entrypoint.instanceid = (uint32_t) -1;
	return false;
}

std::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {
	ny::Logs::Report report{compdb.messages};
	Logs::Handler errorHandler{&report, &buildGenerateReport};
	try {
		auto& opts = compdb.opts;
		uint32_t scount = opts.sources.count;
		if (unlikely(scount == 0))
			throw "no input source code";
		if (config::importNSL)
			ny::intrinsic::import::all(compdb.intrinsics);
		if (config::importNSL)
			scount += corefilesCount;
		if (unlikely(opts.with_nsl_unittests == nytrue))
			scount += unittestCount;
		auto& sources = compdb.sources;
		sources.count = scount;
		sources.items = std::make_unique<Source[]>(scount);
		bool compiled = true;
		uint32_t offset = 0;
		if (config::importNSL) {
			registerNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {
				compiled &= compileSource(report, compdb, source, opts);
			});
		}
		if (opts.with_nsl_unittests == nytrue) {
			registerUnittestFiles(sources, offset, [&](ny::compiler::Source& source) {
				compiled &= compileSource(report, compdb, source, opts);
			});
		}
		for (uint32_t i = 0; i != opts.sources.count; ++i) {
			auto& source = sources[offset + i];
			compiled &= importSourceAndCompile(report, compdb, source, opts, opts.sources.items[i]);
		}
		compiled = compiled
			and compdb.cdeftable.atoms.fetchAndIndexCoreObjects() // indexing bool, u32, f64...
			and ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); // typedef
		if (config::traces::preAtomTable)
			compdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});
		if (unlikely(not compiled))
			return nullptr;
		auto& entrypoint = compdb.opts.entrypoint;
		if (unlikely(entrypoint.len == 0))
			return nullptr;
		bool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));
		if (unlikely(not epinst))
			return nullptr;
		return std::make_unique<ny::Program>();
	}
	catch (const std::bad_alloc& e) {
		report.ice() << "not enough memory when compiling";
	}
	catch (const std::exception& e) {
		report.ice() << "exception: " << e.what();
	}
	catch (const char* e) {
		report.error() << e;
	}
	catch (...) {
		report.ice() << "uncaught exception when compiling";
	}
	return nullptr;
}

} // namespace

nyprogram_t* compile(nycompile_opts_t& opts) {
	try {
		if (opts.on_build_start)
			opts.userdata = opts.on_build_start(opts.userdata);
		auto compdb = std::make_unique<Compdb>(opts);
		auto program = compile(*compdb);
		if (opts.on_build_stop)
			opts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));
		if (opts.on_report and not compdb->messages.entries.empty())
			opts.on_report(opts.userdata, reinterpret_cast<const nyreport_t*>(&compdb->messages));
		if (unlikely(!program))
			return nullptr;
		program->compdb = std::move(compdb);
		return ny::Program::pointer(program.release());
	}
	catch (...) {
	}
	if (opts.on_build_stop)
		opts.on_build_stop(opts.userdata, nyfalse);
	return nullptr;
}

} // namespace compiler
} // namespace ny
<commit_msg>fix warning unused variable<commit_after>#include "details/compiler/compiler.h"
#include "details/compiler/compdb.h"
#include "details/program/program.h"
#include "details/reporting/report.h"
#include "details/errors/errors.h"
#include "details/pass/a-src2ast/ast-from-source.h"
#include "details/pass/b-ast-normalize/normalize.h"
#include "details/pass/c-ast2ir/source-ast-to-ir.h"
#include "details/pass/d-object-map/attach.h"
#include "details/semantic/atom-factory.h"
#include "details/intrinsic/std.core.h"
#include "libnanyc-config.h"
#include "libnanyc-traces.h"
#include "embed-nsl.hxx" // generated
#include <yuni/io/file.h>
#include <libnanyc.h>
#include <utility>
#include <memory>
#include <iostream>

namespace ny {
namespace compiler {

namespace {

constexpr uint32_t memoryHardlimit = 64 * 1024 * 1024;

Logs::Report buildGenerateReport(void* ptr, Logs::Level level) {
	return (*((ny::Logs::Report*) ptr)).fromErrLevel(level);
}

void copySourceOpts(ny::compiler::Source& source, const nysource_opts_t& opts) {
	if (opts.filename.len != 0) {
		if (unlikely(opts.filename.len > memoryHardlimit))
			throw "input filename bigger than internal limit";
		yuni::IO::Canonicalize(source.storageFilename, AnyString{opts.filename.c_str, static_cast<uint32_t>(opts.filename.len)});
		source.filename = source.storageFilename;
	}
	if (opts.content.len != 0) {
		if (unlikely(opts.content.len > memoryHardlimit))
			throw "input source content bigger than internal limit";
		source.storageContent.assign(opts.content.c_str, static_cast<uint32_t>(opts.content.len));
		source.content = source.storageContent;
	}
}

bool compileSource(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts) {
	auto report = mainreport.subgroup();
	report.data().origins.location.filename = source.filename;
	report.data().origins.location.target.clear();
	bool compiled = true;
	compiled &= makeASTFromSource(source);
	compiled &= passDuplicateAndNormalizeAST(source, report);
	compiled &= passTransformASTToIR(source, report, gopts);
	compiled  = compiled and attach(compdb, source);
	return compiled;
}

bool importSourceAndCompile(ny::Logs::Report& mainreport, ny::compiler::Compdb& compdb, ny::compiler::Source& source, const nycompile_opts_t& gopts, const nysource_opts_t& opts) {
	copySourceOpts(source, opts);
	return compileSource(mainreport, compdb, source, gopts);
}

Atom& findEntrypointAtom(Atom& root, const AnyString& entrypoint) {
	Atom* atom = nullptr;
	root.eachChild(entrypoint, [&](Atom & child) -> bool {
		if (unlikely(atom != nullptr))
			throw "': multiple entry points found";
		atom = &child;
		return true;
	});
	if (unlikely(!atom))
		throw "()': function not found";
	if (unlikely(not atom->isFunction() or atom->isClassMember()))
		throw "': the atom is not a function";
	return *atom;
}

bool instanciate(ny::compiler::Compdb& compdb, ny::Logs::Report& report, AnyString entrypoint) {
	using ParameterList = decltype(ny::semantic::FuncOverloadMatch::result.params);
	try {
		auto& atom = findEntrypointAtom(compdb.cdeftable.atoms.root, entrypoint);
		ParameterList params;
		ParameterList tmplparams;
		ClassdefTableView cdeftblView{compdb.cdeftable};
		ny::semantic::Settings settings(atom, cdeftblView, compdb, params, tmplparams);
		bool instanciated = ny::semantic::instanciateAtom(settings);
		report.appendEntry(settings.report);
		if (config::traces::atomTable)
			compdb.cdeftable.atoms.root.printTree(compdb.cdeftable);
		if (likely(instanciated)) {
			compdb.entrypoint.atomid = atom.atomid;
			compdb.entrypoint.instanceid = settings.instanceid;
			return true;
		}
	}
	catch (const char* e) {
		report.error() << "failed to instanciate '" << entrypoint << e;
	}
	compdb.entrypoint.atomid = (uint32_t) -1;
	compdb.entrypoint.instanceid = (uint32_t) -1;
	return false;
}

std::unique_ptr<ny::Program> compile(ny::compiler::Compdb& compdb) {
	ny::Logs::Report report{compdb.messages};
	Logs::Handler errorHandler{&report, &buildGenerateReport};
	try {
		auto& opts = compdb.opts;
		uint32_t scount = opts.sources.count;
		if (unlikely(scount == 0))
			throw "no input source code";
		if (config::importNSL)
			ny::intrinsic::import::all(compdb.intrinsics);
		if (config::importNSL)
			scount += corefilesCount;
		if (unlikely(opts.with_nsl_unittests == nytrue))
			scount += unittestCount;
		auto& sources = compdb.sources;
		sources.count = scount;
		sources.items = std::make_unique<Source[]>(scount);
		bool compiled = true;
		uint32_t offset = 0;
		if (config::importNSL) {
			registerNSLCoreFiles(sources, offset, [&](ny::compiler::Source& source) {
				compiled &= compileSource(report, compdb, source, opts);
			});
		}
		if (opts.with_nsl_unittests == nytrue) {
			registerUnittestFiles(sources, offset, [&](ny::compiler::Source& source) {
				compiled &= compileSource(report, compdb, source, opts);
			});
		}
		for (uint32_t i = 0; i != opts.sources.count; ++i) {
			auto& source = sources[offset + i];
			compiled &= importSourceAndCompile(report, compdb, source, opts, opts.sources.items[i]);
		}
		compiled = compiled
			and compdb.cdeftable.atoms.fetchAndIndexCoreObjects() // indexing bool, u32, f64...
			and ny::semantic::resolveStrictParameterTypes(compdb, compdb.cdeftable.atoms.root); // typedef
		if (config::traces::preAtomTable)
			compdb.cdeftable.atoms.root.printTree(ClassdefTableView{compdb.cdeftable});
		if (unlikely(not compiled))
			return nullptr;
		auto& entrypoint = compdb.opts.entrypoint;
		if (unlikely(entrypoint.len == 0))
			return nullptr;
		bool epinst = instanciate(compdb, report, AnyString(entrypoint.c_str, static_cast<uint32_t>(entrypoint.len)));
		if (unlikely(not epinst))
			return nullptr;
		return std::make_unique<ny::Program>();
	}
	catch (const std::bad_alloc&) {
		report.ice() << "not enough memory when compiling";
	}
	catch (const std::exception& e) {
		report.ice() << "exception: " << e.what();
	}
	catch (const char* e) {
		report.error() << e;
	}
	catch (...) {
		report.ice() << "uncaught exception when compiling";
	}
	return nullptr;
}

} // namespace

nyprogram_t* compile(nycompile_opts_t& opts) {
	try {
		if (opts.on_build_start)
			opts.userdata = opts.on_build_start(opts.userdata);
		auto compdb = std::make_unique<Compdb>(opts);
		auto program = compile(*compdb);
		if (opts.on_build_stop)
			opts.on_build_stop(opts.userdata, (program ? nytrue : nyfalse));
		if (opts.on_report and not compdb->messages.entries.empty())
			opts.on_report(opts.userdata, reinterpret_cast<const nyreport_t*>(&compdb->messages));
		if (unlikely(!program))
			return nullptr;
		program->compdb = std::move(compdb);
		return ny::Program::pointer(program.release());
	}
	catch (...) {
	}
	if (opts.on_build_stop)
		opts.on_build_stop(opts.userdata, nyfalse);
	return nullptr;
}

} // namespace compiler
} // namespace ny
<|endoftext|>


<commit_before>// Copyright (c) 2017 Emilian Cioca
namespace Jwl
{
	namespace detail
	{
		// Index of all Entities for each component and tag type.
		// Sorted to allow for logical operations, such as ANDing, between multiple tables in the index.
		extern std::unordered_map<unsigned, std::vector<Entity*>> entityIndex;

		// Index of all Components of a particular type.
		// Not sorted since no logical operations are performed using these tables.
		extern std::unordered_map<unsigned, std::vector<ComponentBase*>> componentIndex;

		// A lightweight tag representing the end of a query's range. We use this rather than creating another
		// potentially large end-iterator. Our custom iterators already have all the information they need to
		// detect if they have expired, so we use this tag to ask them when they has finished enumerating the range.
		struct RangeEndSentinel {};

		// Enumerates a table of the componentIndex while performing a cast and a dereference.
		template<class Component>
		class ComponentIterator : public std::iterator<std::forward_iterator_tag, Component>
		{
			using Iterator = std::vector<ComponentBase*>::iterator;
		public:
			ComponentIterator(Iterator _itr, Iterator _itrEnd)
				: itr(_itr), itrEnd(_itrEnd)
			{}

			ComponentIterator& operator++()
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				++itr;
				return *this;
			}

			Component& operator*() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *static_cast<Component*>(*itr);
			}

			bool operator==(RangeEndSentinel) const { return IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !IsTerminated(); }

			bool IsTerminated() const { return itr == itrEnd; }

		private:
			// The current position in the target table.
			Iterator itr;
			// Ensures that we don't surpass the table while we are skipping items.
			const Iterator itrEnd;
		};

		// A safe iterator used to enumerate the entityIndex tables.
		// Although it models a single iterator, it knows when it has reached the end of the table.
		class SafeIterator : public std::iterator<std::forward_iterator_tag, Entity*>
		{
			using Iterator = std::vector<Entity*>::iterator;
		public:
			SafeIterator(Iterator _itr, Iterator _itrEnd)
				: itr(_itr), itrEnd(_itrEnd)
			{}

			SafeIterator& operator++()
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				++itr;
				return *this;
			}

			Entity& operator*() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *(*itr);
			}

			Entity* Get() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *itr;
			}

			bool operator==(RangeEndSentinel) const { return IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !IsTerminated(); }

			bool IsTerminated() const { return itr == itrEnd; }
			void Terminate() { itr = itrEnd; }

		private:
			// The current position in the table.
			Iterator itr;
			// Ensures that we don't surpass the table while we are skipping items.
			const Iterator itrEnd;
		};

		// Provides functions to advance two SafeIterators as a logical AND of two entityIndex tables.
		// This provider pattern will allow us to add more operations in the future.
		struct Intersection
		{
			static void FindFirst(SafeIterator& itr1, SafeIterator& itr2)
			{
				while (!(itr1.IsTerminated() || itr2.IsTerminated()))
				{
					Entity* p1 = itr1.Get();
					Entity* p2 = itr2.Get();

					if (p1 < p2)
					{
						++itr1;
					}
					else if (p1 > p2)
					{
						++itr2;
					}
					else
					{
						break;
					}
				}

				// Itr1 is the one that is checked for death, so propagate the termination if Itr2 finished first.
				if (itr2.IsTerminated())
				{
					itr1.Terminate();
				}
			}

			static void FindNext(SafeIterator& itr1, SafeIterator& itr2)
			{
				FindFirst(++itr1, itr2);
			}
		};

		// Enumerates a SafeIterator and a templated iterator while performing a logical operation between them.
		// The templated iterator expands into a subtree of more LogicalIterators.
		template<class Iterator, class Operation>
		class LogicalIterator : public std::iterator<std::forward_iterator_tag, Entity*>
		{
		public:
			LogicalIterator(SafeIterator _itr1, Iterator _itr2)
				: itr1(_itr1), itr2(_itr2)
			{
				Operation::FindFirst(itr1, itr2.GetCurrentItr());
			}

			LogicalIterator& operator++()
			{
				// Update the right-hand side of the iterator hierarchy.
				++itr2;

				// Intersect the result of the subtree with our left-hand SafeIterator.
				Operation::FindNext(itr1, itr2.GetCurrentItr());
				return *this;
			}

			SafeIterator& GetCurrentItr() { return itr1; }

			Entity& operator*() const { return *itr1; }

			bool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }

		private:
			SafeIterator itr1;
			Iterator itr2;
		};

		// LogicalIterator specialization for the bottom of the hierarchy.
		// Directly operates on two SafeIterators.
		template<class Operation>
		class LogicalIterator<SafeIterator, Operation> : public std::iterator<std::forward_iterator_tag, Entity*>
		{
		public:
			LogicalIterator(SafeIterator _itr1, SafeIterator _itr2)
				: itr1(_itr1), itr2(_itr2)
			{
				Operation::FindFirst(itr1, itr2);
			}

			LogicalIterator& operator++()
			{
				Operation::FindNext(itr1, itr2);
				return *this;
			}

			SafeIterator& GetCurrentItr() { return itr1; }

			Entity& operator*() const { return *itr1; }

			bool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }

		private:
			SafeIterator itr1;
			SafeIterator itr2;
		};

		// Represents a lazy-evaluated range that can be used in a range-based for loop.
		template<class RootIterator>
		class Range
		{
		public:
			Range(RootIterator _itr)
				: itr(_itr)
			{}

			RootIterator& begin()
			{
				return itr;
			}

			RangeEndSentinel end() const
			{
				return {};
			}

		private:
			// The starting position of the range.
			RootIterator itr;
		};

		// Template deduction assisted construction.
		template<class Iterator>
		auto BuildLogicalIterator(SafeIterator&& set1, Iterator&& set2)
		{
			return LogicalIterator<Iterator, Intersection>(set1, set2);
		}

		// Constructs a logical iterator representing the start of the sequence.
		template<typename Arg1, typename Arg2, typename... Args>
		auto BuildRootIterator()
		{
			auto& index = entityIndex[Arg1::GetComponentId()];
			auto begin = index.begin();
			auto end = index.end();

			return BuildLogicalIterator(SafeIterator(begin, end), BuildRootIterator<Arg2, Args...>());
		}

		// BuildRootIterator() base case.
		template<typename Arg>
		SafeIterator BuildRootIterator()
		{
			auto& index = entityIndex[Arg::GetComponentId()];
			auto begin = index.begin();
			auto end = index.end();

			return SafeIterator(begin, end);
		}
	}

	// Returns an enumerable range of all enabled Components of the specified type.
	// By providing you the Component directly you don't have to waste time calling Entity.Get<>().
	// This is a faster option than With<>() but it only allows you to specify a single Component type.
	template<class Component>
	auto All()
	{
		static_assert(std::is_base_of_v<ComponentBase, Component>,
			"Template argument must be a Component.");

		static_assert(!std::is_base_of_v<TagBase, Component>,
			"Cannot query tags with All<>(). Use With<>() instead.");

		static_assert(std::is_same_v<Component, typename Component::StaticComponentType>,
			"Only a direct inheritor from Component<> can be used in a query.");

		using namespace detail;
		auto& index = componentIndex[Component::GetComponentId()];
		auto itr = ComponentIterator<Component>(index.begin(), index.end());

		return detail::Range(itr);
	}

	// Returns an enumerable range of all Entities which have an active instance of each specified Component/Tag.
	// Disabled Components and Components belonging to disabled Entities are not considered.
	// * Adding/Removing Components or Tags of the queried types will invalidate the returned Range *
	// For this reason, you must not do this until after you are finished using the Range.
	template<typename... Args>
	auto With()
	{
		static_assert(sizeof...(Args),
			"With<>() must receive at least one template argument.");

		static_assert(Meta::all_of_v<std::is_base_of<ComponentBase, Args>::value...>,
			"All template arguments must be either Components or Tags.");

		static_assert(Meta::all_of_v<std::is_same<Args, typename Args::StaticComponentType>::value...>,
			"Only a direct inheritor from Component<> can be used in a query.");

		using namespace detail;
		auto&& itr = BuildRootIterator<Args...>();

		return detail::Range(itr);
	}

	// Returns all Entities which have an active instance of each specified Component/Tag.
	// Disabled Components and Components belonging to disabled Entities are not considered.
	// Unlike With<>(), adding or removing Components/Tags of the queried type will NOT invalidate the returned Range.
	// * This should only be used if necessary, as it is much slower than using With<>() *
	template<typename Arg1, typename... Args>
	std::vector<Entity::Ptr> CaptureWith()
	{
		std::vector<Entity::Ptr> result;
		if constexpr (sizeof...(Args) == 0)
		{
			using namespace detail;
			result.reserve(entityIndex[Arg1::GetComponentId()].size());
		}

		for (Entity& ent : With<Arg1, Args...>())
		{
			result.emplace_back(ent.GetPtr());
		}

		return result;
	}

	// Returns the raw vector container of the specified Component.
	// This can be useful in special cases when you need custom iterator logic.
	template<class Component>
	std::vector<ComponentBase*>& GetComponentIndex()
	{
		using namespace detail;
		return componentIndex[Component::GetComponentId()];
	}
}
<commit_msg>Simplified the implementation of LogicalIterator<commit_after>// Copyright (c) 2017 Emilian Cioca
namespace Jwl
{
	namespace detail
	{
		// Index of all Entities for each component and tag type.
		// Sorted to allow for logical operations, such as ANDing, between multiple tables in the index.
		extern std::unordered_map<unsigned, std::vector<Entity*>> entityIndex;

		// Index of all Components of a particular type.
		// Not sorted since no logical operations are performed using these tables.
		extern std::unordered_map<unsigned, std::vector<ComponentBase*>> componentIndex;

		// A lightweight tag representing the end of a query's range. We use this rather than creating another
		// potentially large end-iterator. Our custom iterators already have all the information they need to
		// detect if they have expired, so we use this tag to ask them when they has finished enumerating the range.
		struct RangeEndSentinel {};

		// Enumerates a table of the componentIndex while performing a cast and a dereference.
		template<class Component>
		class ComponentIterator : public std::iterator<std::forward_iterator_tag, Component>
		{
			using Iterator = std::vector<ComponentBase*>::iterator;
		public:
			ComponentIterator(Iterator _itr, Iterator _itrEnd)
				: itr(_itr), itrEnd(_itrEnd)
			{}

			ComponentIterator& operator++()
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				++itr;
				return *this;
			}

			Component& operator*() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *static_cast<Component*>(*itr);
			}

			bool operator==(RangeEndSentinel) const { return IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !IsTerminated(); }

			bool IsTerminated() const { return itr == itrEnd; }

		private:
			// The current position in the target table.
			Iterator itr;
			// Ensures that we don't surpass the table while we are skipping items.
			const Iterator itrEnd;
		};

		// A safe iterator used to enumerate the entityIndex tables.
		// Although it models a single iterator, it knows when it has reached the end of the table.
		class SafeIterator : public std::iterator<std::forward_iterator_tag, Entity*>
		{
			using Iterator = std::vector<Entity*>::iterator;
		public:
			SafeIterator(Iterator _itr, Iterator _itrEnd)
				: itr(_itr), itrEnd(_itrEnd)
			{}

			SafeIterator& operator++()
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				++itr;
				return *this;
			}

			Entity& operator*() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *(*itr);
			}

			Entity* Get() const
			{
				ASSERT(!IsTerminated(), "Invalid range is in use.");
				return *itr;
			}

			bool operator==(RangeEndSentinel) const { return IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !IsTerminated(); }

			bool IsTerminated() const { return itr == itrEnd; }
			void Terminate() { itr = itrEnd; }

		private:
			// The current position in the table.
			Iterator itr;
			// Ensures that we don't surpass the table while we are skipping items.
			const Iterator itrEnd;
		};

		// Provides functions to advance two SafeIterators as a logical AND of two entityIndex tables.
		// This provider pattern will allow us to add more operations in the future.
		struct Intersection
		{
			static void FindFirst(SafeIterator& itr1, SafeIterator& itr2)
			{
				while (!(itr1.IsTerminated() || itr2.IsTerminated()))
				{
					Entity* p1 = itr1.Get();
					Entity* p2 = itr2.Get();

					if (p1 < p2)
					{
						++itr1;
					}
					else if (p1 > p2)
					{
						++itr2;
					}
					else
					{
						break;
					}
				}

				// Itr1 is the one that is checked for death, so propagate the termination if Itr2 finished first.
				if (itr2.IsTerminated())
				{
					itr1.Terminate();
				}
			}

			static void FindNext(SafeIterator& itr1, SafeIterator& itr2)
			{
				FindFirst(++itr1, itr2);
			}
		};

		// Enumerates a SafeIterator and a templated iterator while performing a logical operation between them.
		// The templated iterator can expand into a subtree of more LogicalIterators, or be a SafeIterator itself.
		template<class Iterator, class Operation>
		class LogicalIterator : public std::iterator<std::forward_iterator_tag, Entity*>
		{
			static constexpr bool isLeaf = std::is_same_v<Iterator, SafeIterator>;
		public:
			LogicalIterator(SafeIterator _itr1, Iterator _itr2)
				: itr1(_itr1), itr2(_itr2)
			{
				if constexpr (isLeaf)
				{
					Operation::FindFirst(itr1, itr2);
				}
				else
				{
					Operation::FindFirst(itr1, itr2.GetCurrentItr());
				}
			}

			LogicalIterator& operator++()
			{
				if constexpr (isLeaf)
				{
					Operation::FindNext(itr1, itr2);
				}
				else
				{
					// Intersect the result of the right-hand subtree with our left-hand SafeIterator.
					++itr2;
					Operation::FindNext(itr1, itr2.GetCurrentItr());
				}

				return *this;
			}

			SafeIterator& GetCurrentItr() { return itr1; }
			Entity& operator*() const { return *itr1; }

			bool operator==(RangeEndSentinel) const { return itr1.IsTerminated(); }
			bool operator!=(RangeEndSentinel) const { return !itr1.IsTerminated(); }

		private:
			SafeIterator itr1;
			Iterator itr2;
		};

		// Represents a lazy-evaluated range that can be used in a range-based for loop.
		template<class RootIterator>
		class Range
		{
		public:
			Range(RootIterator _itr)
				: itr(_itr)
			{}

			RootIterator& begin()
			{
				return itr;
			}

			RangeEndSentinel end() const
			{
				return {};
			}

		private:
			// The starting position of the range.
			RootIterator itr;
		};

		// Template deduction assisted construction.
		template<class Iterator>
		auto BuildLogicalIterator(SafeIterator&& set1, Iterator&& set2)
		{
			return LogicalIterator<Iterator, Intersection>(set1, set2);
		}

		// Constructs a logical iterator representing the start of the sequence.
		template<typename Arg1, typename Arg2, typename... Args>
		auto BuildRootIterator()
		{
			auto& index = entityIndex[Arg1::GetComponentId()];
			auto begin = index.begin();
			auto end = index.end();

			return BuildLogicalIterator(SafeIterator(begin, end), BuildRootIterator<Arg2, Args...>());
		}

		// BuildRootIterator() base case.
		template<typename Arg>
		SafeIterator BuildRootIterator()
		{
			auto& index = entityIndex[Arg::GetComponentId()];
			auto begin = index.begin();
			auto end = index.end();

			return SafeIterator(begin, end);
		}
	}

	// Returns an enumerable range of all enabled Components of the specified type.
	// By providing you the Component directly you don't have to waste time calling Entity.Get<>().
	// This is a faster option than With<>() but it only allows you to specify a single Component type.
	template<class Component>
	auto All()
	{
		static_assert(std::is_base_of_v<ComponentBase, Component>,
			"Template argument must be a Component.");

		static_assert(!std::is_base_of_v<TagBase, Component>,
			"Cannot query tags with All<>(). Use With<>() instead.");

		static_assert(std::is_same_v<Component, typename Component::StaticComponentType>,
			"Only a direct inheritor from Component<> can be used in a query.");

		using namespace detail;
		auto& index = componentIndex[Component::GetComponentId()];
		auto itr = ComponentIterator<Component>(index.begin(), index.end());

		return detail::Range(itr);
	}

	// Returns an enumerable range of all Entities which have an active instance of each specified Component/Tag.
	// Disabled Components and Components belonging to disabled Entities are not considered.
	// * Adding/Removing Components or Tags of the queried types will invalidate the returned Range *
	// For this reason, you must not do this until after you are finished using the Range.
	template<typename... Args>
	auto With()
	{
		static_assert(sizeof...(Args),
			"With<>() must receive at least one template argument.");

		static_assert(Meta::all_of_v<std::is_base_of<ComponentBase, Args>::value...>,
			"All template arguments must be either Components or Tags.");

		static_assert(Meta::all_of_v<std::is_same<Args, typename Args::StaticComponentType>::value...>,
			"Only a direct inheritor from Component<> can be used in a query.");

		using namespace detail;
		auto&& itr = BuildRootIterator<Args...>();

		return detail::Range(itr);
	}

	// Returns all Entities which have an active instance of each specified Component/Tag.
	// Disabled Components and Components belonging to disabled Entities are not considered.
	// Unlike With<>(), adding or removing Components/Tags of the queried type will NOT invalidate the returned Range.
	// * This should only be used if necessary, as it is much slower than using With<>() *
	template<typename Arg1, typename... Args>
	std::vector<Entity::Ptr> CaptureWith()
	{
		std::vector<Entity::Ptr> result;
		if constexpr (sizeof...(Args) == 0)
		{
			using namespace detail;
			result.reserve(entityIndex[Arg1::GetComponentId()].size());
		}

		for (Entity& ent : With<Arg1, Args...>())
		{
			result.emplace_back(ent.GetPtr());
		}

		return result;
	}

	// Returns the raw vector container of the specified Component.
	// This can be useful in special cases when you need custom iterator logic.
	template<class Component>
	std::vector<ComponentBase*>& GetComponentIndex()
	{
		using namespace detail;
		return componentIndex[Component::GetComponentId()];
	}
}
<|endoftext|>


<commit_before>## Main type definition

# Based on
#   https://github.com/NaaS/system/blob/master/naasferatu/front-end/hadoop*.naas
# More recent version of target code available at
#   https://lsds.doc.ic.ac.uk/gitlab/naas/naas-box-system/tree/master/src/applications/hadoop_data_model

type hadoop_wc : record
  key_len : integer
    { signed = true,
    # FIXME not sure if the target allows us to specify endianness at present.
    #endianness = big,
    # "size" in bytes
    byte_size = 2 }
  key : string
    { byte_size = "hadoop_wc.key_len" }
  value : integer
    { signed = false,
    #endianness = big,
    byte_size = 8 }
<commit_msg>not using FQNs to simplify name handling in the compiler for such references;<commit_after>## Main type definition

# Based on
#   https://github.com/NaaS/system/blob/master/naasferatu/front-end/hadoop*.naas
# More recent version of target code available at
#   https://lsds.doc.ic.ac.uk/gitlab/naas/naas-box-system/tree/master/src/applications/hadoop_data_model

type hadoop_wc : record
  key_len : integer
    { signed = true,
    # FIXME not sure if the target allows us to specify endianness at present.
    #endianness = big,
    # "size" in bytes
    byte_size = 2 }
  key : string
    { byte_size = key_len }
  value : integer
    { signed = false,
    #endianness = big,
    byte_size = 8 }
<|endoftext|>


<commit_before>#include "segments.hpp"
#include "../utils/utils.hpp"
#include <cmath>
#include <cstdio>
#include <cstring>

using namespace geom2d;

static unsigned int Nsegs = 10;
static unsigned int Width = 100;
static unsigned int Height = 100;
static unsigned int Nangles = 32;
static unsigned long Nsteps = 1000000;
static double MaxR = 15;
static double MinR = 1;

void parseargs(int, const char*[]);
void helpmsg(int);
void mkinst(FILE*);

int main(int argc, const char *argv[]) {
	parseargs(argc, argv);
	mkinst(stdout);
	return 0;
}

void parseargs(int argc, const char *argv[]) {
	for (int i = 1; i < argc; i++) {
		if (i < argc-1 && strcmp(argv[i], "nsegs") == 0) {
			Nsegs = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "width") == 0) {
			Width = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "height") == 0) {
			Height = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "nangles") == 0) {
			Nangles = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "nsteps") == 0) {
			Nsteps = strtoul(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "maxr") == 0) {
			MaxR = strtod(argv[++i], NULL);

		} else if (i < argc-1 && strcmp(argv[i], "minr") == 0) {
			MinR = strtod(argv[++i], NULL);

		} else if (i < argc-1 && strcmp(argv[i], "h") == 0) {
			helpmsg(0);

		} else {
			helpmsg(1);
		}
	}
}

void helpmsg(int status) {
	puts("Usage: mkinst [options]");
	printf("-nsegs	the number of segments (default: %u)\n", Nsegs);
	printf("-width	width of the grid (default: %u)\n", Width);
	printf("-height	height of the grid (default: %u)\n", Height);
	printf("-nangles	the number of angles (must be even, default: %u)\n", Nangles);
	printf("-nsteps	number of steps in the random walk (default: %lu)\n", Nsteps);
	printf("-maxr	the max segment radius (default: %g)\n", MaxR);
	printf("-minr	the min segment radius (default: %g)\n", MinR);
	exit(status);
}

void mkinst(FILE *out) {
	Segments dom(Width, Height, Nangles, std::vector<Segments::Seg>());

	std::vector<LineSg> lines;
	for (unsigned int i = 0; i < Nsegs; i++) {
	redo:
		Segments::Seg seg;
		seg.radius = randgen.real()*(MaxR-MinR) + MinR;
		seg.start.rot = randgen.integer(0, Nangles-1);
		seg.start.x = randgen.integer(1, Width - 2);
		seg.start.y = randgen.integer(1, Height - 2);

		LineSg line = dom.line(seg, seg.start);
		for (auto l = lines.begin(); l != lines.end(); l++) {
			if (l->hits(line))
				goto redo;
		}

		lines.push_back(line);
		dom.segs.push_back(seg);
	}

	Segments::State st = dom.initialstate();
	for (unsigned int i = 0; i < Nsteps; i++) {
		Segments::Operators ops(dom, st);
		if (ops.size() == 0)
			break;
		unsigned int n = randgen.integer(0, ops.size()-1);
		Segments::Edge e(dom, st, ops[n]);
		st = e.state;
	}

	fprintf(out, "%u %u %u\n", Width, Height, Nangles);
	fprintf(out, "%u\n", Nsegs);
	for (unsigned int i = 0; i < dom.segs.size(); i++) {
		const Segments::Pose &goal = st.poses[i];
		const Segments::Seg &sg = dom.segs[i];
		fprintf(out, "%g ", sg.radius);
		fprintf(out, "%u %u %u ", sg.start.x, sg.start.y, sg.start.rot);
		fprintf(out, "%u %u %u\n", goal.x, goal.y, goal.rot);
	}

}
<commit_msg>segments: options have a leading -.<commit_after>#include "segments.hpp"
#include "../utils/utils.hpp"
#include <cmath>
#include <cstdio>
#include <cstring>

using namespace geom2d;

static unsigned int Nsegs = 10;
static unsigned int Width = 100;
static unsigned int Height = 100;
static unsigned int Nangles = 32;
static unsigned long Nsteps = 1000000;
static double MaxR = 15;
static double MinR = 1;

void parseargs(int, const char*[]);
void helpmsg(int);
void mkinst(FILE*);

int main(int argc, const char *argv[]) {
	parseargs(argc, argv);
	mkinst(stdout);
	return 0;
}

void parseargs(int argc, const char *argv[]) {
	for (int i = 1; i < argc; i++) {
		if (i < argc-1 && strcmp(argv[i], "-nsegs") == 0) {
			Nsegs = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "-width") == 0) {
			Width = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "-height") == 0) {
			Height = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "-nangles") == 0) {
			Nangles = strtol(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "-nsteps") == 0) {
			Nsteps = strtoul(argv[++i], NULL, 10);

		} else if (i < argc-1 && strcmp(argv[i], "-maxr") == 0) {
			MaxR = strtod(argv[++i], NULL);

		} else if (i < argc-1 && strcmp(argv[i], "-minr") == 0) {
			MinR = strtod(argv[++i], NULL);

		} else if (i < argc-1 && strcmp(argv[i], "-h") == 0) {
			helpmsg(0);

		} else {
			helpmsg(1);
		}
	}
}

void helpmsg(int status) {
	puts("Usage: mkinst [options]");
	printf("-nsegs	the number of segments (default: %u)\n", Nsegs);
	printf("-width	width of the grid (default: %u)\n", Width);
	printf("-height	height of the grid (default: %u)\n", Height);
	printf("-nangles	the number of angles (must be even, default: %u)\n", Nangles);
	printf("-nsteps	number of steps in the random walk (default: %lu)\n", Nsteps);
	printf("-maxr	the max segment radius (default: %g)\n", MaxR);
	printf("-minr	the min segment radius (default: %g)\n", MinR);
	exit(status);
}

void mkinst(FILE *out) {
	Segments dom(Width, Height, Nangles, std::vector<Segments::Seg>());

	std::vector<LineSg> lines;
	for (unsigned int i = 0; i < Nsegs; i++) {
	redo:
		Segments::Seg seg;
		seg.radius = randgen.real()*(MaxR-MinR) + MinR;
		seg.start.rot = randgen.integer(0, Nangles-1);
		seg.start.x = randgen.integer(1, Width - 2);
		seg.start.y = randgen.integer(1, Height - 2);

		LineSg line = dom.line(seg, seg.start);
		for (auto l = lines.begin(); l != lines.end(); l++) {
			if (l->hits(line))
				goto redo;
		}

		lines.push_back(line);
		dom.segs.push_back(seg);
	}

	Segments::State st = dom.initialstate();
	for (unsigned int i = 0; i < Nsteps; i++) {
		Segments::Operators ops(dom, st);
		if (ops.size() == 0)
			break;
		unsigned int n = randgen.integer(0, ops.size()-1);
		Segments::Edge e(dom, st, ops[n]);
		st = e.state;
	}

	fprintf(out, "%u %u %u\n", Width, Height, Nangles);
	fprintf(out, "%u\n", Nsegs);
	for (unsigned int i = 0; i < dom.segs.size(); i++) {
		const Segments::Pose &goal = st.poses[i];
		const Segments::Seg &sg = dom.segs[i];
		fprintf(out, "%g ", sg.radius);
		fprintf(out, "%u %u %u ", sg.start.x, sg.start.y, sg.start.rot);
		fprintf(out, "%u %u %u\n", goal.x, goal.y, goal.rot);
	}

}
<|endoftext|>


<commit_before>#include "VulkanFragmentShader.h"

#include <stdio.h>

void VulkanFragmentShader::LoadShader(const int8* ShaderFileName)
{
	Array<int8> Glsl;
	FILE* file = fopen(ShaderFileName, "r");

	Array<uint32> Spirv = CompileGLSL(ShaderFileName, ShaderType::FragmentShader, Glsl);
}
<commit_msg>Closed file in FragmentShader.cpp<commit_after>#include "VulkanFragmentShader.h"

#include <stdio.h>

void VulkanFragmentShader::LoadShader(const int8* ShaderFileName)
{
	Array<int8> Glsl;
	FILE* file = fopen(ShaderFileName, "r");

	Array<uint32> Spirv = CompileGLSL(ShaderFileName, ShaderType::FragmentShader, Glsl);
	fclose(file);
}

<|endoftext|>


<commit_before>#include <osgWidget/VncClient>

#include <osgDB/Registry>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

class EscapeHandler : public osgGA::GUIEventHandler
{
    public:

        EscapeHandler() {}

        bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
        {
            if (ea.getHandled()) return false;

            switch(ea.getEventType())
            {
                case(osgGA::GUIEventAdapter::KEYUP):
                {
                    if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Escape)
                    {
                        osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
                        if (view) view->getViewerBase()->setDone(true);

                        return true;
                    }
                }

                default:
                    return false;
            }
            return false;
        }
};

int main(int argc,char** argv)
{
    osg::ArgumentParser arguments(&argc, argv);
    arguments.getApplicationUsage()->addCommandLineOption("--login <url> <username> <password>", "Provide authentication information for http file access.");
    arguments.getApplicationUsage()->addCommandLineOption("--password <password>", "Provide password for any vnc url on command line not mentioned in --login.");
    osgViewer::Viewer viewer(arguments);

    osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
                                   osg::Vec3(1.0f,0.0f,0.0f),
                                   osg::Vec3(0.0f,0.0f,1.0f),
                                   osg::Vec4(1.0f,1.0f,1.0f,1.0f),
                                   osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);

    osg::ref_ptr<osg::Group> group = new osg::Group;

    std::string password;
    while(arguments.read("--password",password))
    {
    }

    std::string url, username, password;
    while (arguments.read("--login", url, username, password))
    {
        osgDB::Registry::instance()->getOrCreateAuthenticationMap()->addAuthenticationDetails(
            url,
            new osgDB::AuthenticationDetails(username, password)
        );
    }

    for(int i=1; i<arguments.argc(); ++i)
    {
        if (!arguments.isOption(i))
        {
            std::string hostname = arguments[i];

            if (!password.empty())
            {
                const osgDB::AuthenticationMap* authenticationMap = osgDB::Registry::instance()->getOrCreateAuthenticationMap();
                const osgDB::AuthenticationDetails* details = authenticationMap->getAuthenticationDetails(hostname);
                if (details == NULL)
                {
                    authenticationMap->addAuthenticationDetails(hostname, new osgDB::AuthenticationDetails("", password));
                }
            }

            osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient;
            if (vncClient->connect(arguments[i], hints))
            {
                group->addChild(vncClient.get());

                hints.position.x() += 1.1f;
            }
        }
    }

    viewer.setSceneData(group.get());

    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add a custom escape handler, but disable the standard viewer one to enable the vnc images to handle
    // the escape without it getting caught by the viewer.
    viewer.addEventHandler(new EscapeHandler);
    viewer.setKeyEventSetsDone(0);

    return viewer.run();
}

<commit_msg>Build fix<commit_after>#include <osgWidget/VncClient>

#include <osgDB/Registry>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

class EscapeHandler : public osgGA::GUIEventHandler
{
    public:

        EscapeHandler() {}

        bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
        {
            if (ea.getHandled()) return false;

            switch(ea.getEventType())
            {
                case(osgGA::GUIEventAdapter::KEYUP):
                {
                    if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Escape)
                    {
                        osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
                        if (view) view->getViewerBase()->setDone(true);

                        return true;
                    }
                }

                default:
                    return false;
            }
            return false;
        }
};

int main(int argc,char** argv)
{
    osg::ArgumentParser arguments(&argc, argv);
    arguments.getApplicationUsage()->addCommandLineOption("--login <url> <username> <password>", "Provide authentication information for http file access.");
    arguments.getApplicationUsage()->addCommandLineOption("--password <password>", "Provide password for any vnc url on command line not mentioned in --login.");
    osgViewer::Viewer viewer(arguments);

    osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
                                   osg::Vec3(1.0f,0.0f,0.0f),
                                   osg::Vec3(0.0f,0.0f,1.0f),
                                   osg::Vec4(1.0f,1.0f,1.0f,1.0f),
                                   osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);

    osg::ref_ptr<osg::Group> group = new osg::Group;

    std::string password;
    while(arguments.read("--password",password))
    {
    }

    std::string url, username;
    while (arguments.read("--login", url, username, password))
    {
        osgDB::Registry::instance()->getOrCreateAuthenticationMap()->addAuthenticationDetails(
            url,
            new osgDB::AuthenticationDetails(username, password)
        );
    }

    for(int i=1; i<arguments.argc(); ++i)
    {
        if (!arguments.isOption(i))
        {
            std::string hostname = arguments[i];

            if (!password.empty())
            {
                osgDB::AuthenticationMap* authenticationMap = osgDB::Registry::instance()->getOrCreateAuthenticationMap();
                const osgDB::AuthenticationDetails* details = authenticationMap->getAuthenticationDetails(hostname);
                if (details == NULL)
                {
                    authenticationMap->addAuthenticationDetails(hostname, new osgDB::AuthenticationDetails("", password));
                }
            }

            osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient;
            if (vncClient->connect(arguments[i], hints))
            {
                group->addChild(vncClient.get());

                hints.position.x() += 1.1f;
            }
        }
    }

    viewer.setSceneData(group.get());

    viewer.addEventHandler(new osgViewer::StatsHandler);

    // add a custom escape handler, but disable the standard viewer one to enable the vnc images to handle
    // the escape without it getting caught by the viewer.
    viewer.addEventHandler(new EscapeHandler);
    viewer.setKeyEventSetsDone(0);

    return viewer.run();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: frmload.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: mba $ $Date: 2002-07-18 15:02:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_FRMLOAD_HXX
#define _SFX_FRMLOAD_HXX

#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_
#include <com/sun/star/frame/XLoadEventListener.hpp>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSYNCHRONOUSFRAMELOADER_HPP_
#include <com/sun/star/frame/XSynchronousFrameLoader.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_
#include <com/sun/star/document/XExtendedFilterDetection.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <cppuhelper/factory.hxx>
#include <tools/link.hxx>
#include <tools/string.hxx>

class SfxObjectFactory;
class SfxFilterMatcher;
class LoadEnvironment_Impl;
class SfxMedium;

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace uno
            {
                class Any;
            }
            namespace lang
            {
                class XMultiServiceFactory;
            }
            namespace frame
            {
                class XFrame;
            }
            namespace beans
            {
                struct PropertyValue;
            }
        }
    }
}

#include "sfxuno.hxx"

#define REFERENCE ::com::sun::star::uno::Reference
#define SEQUENCE ::com::sun::star::uno::Sequence
#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException

class SfxFrameLoader_Impl : public ::cppu::WeakImplHelper3< ::com::sun::star::frame::XSynchronousFrameLoader, ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo >
{
    REFERENCE < ::com::sun::star::frame::XFrame > xFrame;
    REFERENCE < ::com::sun::star::frame::XLoadEventListener > xListener;
    LoadEnvironment_Impl*   pLoader;
    SfxFilterMatcher*       pMatcher;
    String                  aFilterName;
    SfxMedium*              pMedium;
    sal_Bool                bLoadDone;
    sal_Bool                bLoadState;

    DECL_LINK( LoadDone_Impl, void* );

public:
                            SfxFrameLoader_Impl( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
    virtual                 ~SfxFrameLoader_Impl();

    SFX_DECL_XSERVICEINFO

    //----------------------------------------------------------------------------------
    // XSynchronousFrameLoader
    //----------------------------------------------------------------------------------
    virtual sal_Bool SAL_CALL load( const SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor, const REFERENCE< ::com::sun::star::frame::XFrame >& xFrame ) throw( RUNTIME_EXCEPTION );
    virtual void SAL_CALL cancel() throw( RUNTIME_EXCEPTION );

    //----------------------------------------------------------------------------------
    // XExtendedFilterDetect
    //----------------------------------------------------------------------------------
    virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION );
};

#endif
<commit_msg>INTEGRATION: CWS fwkq1 (1.8.214); FILE MERGED 2003/07/14 17:59:16 mba 1.8.214.1: #110843#: get rid of factories<commit_after>/*************************************************************************
 *
 *  $RCSfile: frmload.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 07:53:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_FRMLOAD_HXX
#define _SFX_FRMLOAD_HXX

#ifndef _COM_SUN_STAR_FRAME_XLOADEVENTLISTENER_HPP_
#include <com/sun/star/frame/XLoadEventListener.hpp>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSYNCHRONOUSFRAMELOADER_HPP_
#include <com/sun/star/frame/XSynchronousFrameLoader.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_
#include <com/sun/star/document/XExtendedFilterDetection.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <cppuhelper/factory.hxx>
#include <tools/link.hxx>
#include <tools/string.hxx>

class SfxObjectFactory;
class SfxFilterMatcher;
class LoadEnvironment_Impl;
class SfxMedium;

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace uno
            {
                class Any;
            }
            namespace lang
            {
                class XMultiServiceFactory;
            }
            namespace frame
            {
                class XFrame;
            }
            namespace beans
            {
                struct PropertyValue;
            }
        }
    }
}

#include "sfxuno.hxx"

#define REFERENCE ::com::sun::star::uno::Reference
#define SEQUENCE ::com::sun::star::uno::Sequence
#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException

class SfxFrameLoader_Impl : public ::cppu::WeakImplHelper2< ::com::sun::star::frame::XSynchronousFrameLoader, ::com::sun::star::lang::XServiceInfo >
{
    REFERENCE < ::com::sun::star::frame::XFrame > xFrame;
    REFERENCE < ::com::sun::star::frame::XLoadEventListener > xListener;
    LoadEnvironment_Impl*   pLoader;
    SfxFilterMatcher*       pMatcher;
    String                  aFilterName;
    SfxMedium*              pMedium;
    sal_Bool                bLoadDone;
    sal_Bool                bLoadState;

    DECL_LINK( LoadDone_Impl, void* );

public:
                            SfxFrameLoader_Impl( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );
    virtual                 ~SfxFrameLoader_Impl();

    SFX_DECL_XSERVICEINFO

    //----------------------------------------------------------------------------------
    // XSynchronousFrameLoader
    //----------------------------------------------------------------------------------
    virtual sal_Bool SAL_CALL load( const SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor, const REFERENCE< ::com::sun::star::frame::XFrame >& xFrame ) throw( RUNTIME_EXCEPTION );
    virtual void SAL_CALL cancel() throw( RUNTIME_EXCEPTION );
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sorgitm.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:18:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFX_SORGITM_HXX
#define _SFX_SORGITM_HXX

#ifndef _SFXSTRITEM_HXX //autogen wg. SfxStringItem
#include <svtools/stritem.hxx>
#endif

// class SfxScriptOrganizerItem ---------------------------------------------

class SfxScriptOrganizerItem : public SfxStringItem
{
private:
    String                  aLanguage;

public:
    TYPEINFO();
    SfxScriptOrganizerItem();
    SfxScriptOrganizerItem( const String &rLanguage );
    SfxScriptOrganizerItem( const SfxScriptOrganizerItem& );
    virtual ~SfxScriptOrganizerItem();

    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = NULL ) const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
    String  getLanguage() { return aLanguage; };
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.730); FILE MERGED 2008/04/01 15:38:17 thb 1.3.730.2: #i85898# Stripping all external header guards 2008/03/31 13:37:54 rt 1.3.730.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: sorgitm.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFX_SORGITM_HXX
#define _SFX_SORGITM_HXX

#include <svtools/stritem.hxx>

// class SfxScriptOrganizerItem ---------------------------------------------

class SfxScriptOrganizerItem : public SfxStringItem
{
private:
    String                  aLanguage;

public:
    TYPEINFO();
    SfxScriptOrganizerItem();
    SfxScriptOrganizerItem( const String &rLanguage );
    SfxScriptOrganizerItem( const SfxScriptOrganizerItem& );
    virtual ~SfxScriptOrganizerItem();

    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = NULL ) const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
    String  getLanguage() { return aLanguage; };
};

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <iostream>

#include <pegtl.hh>
#include <pegtl/analyze.hh>
#include <pegtl/read_parser.hh>

namespace sexpr
{
   using namespace pegtl;

   struct hash_comment
         : until< eolf > {};

   struct list;

   struct list_comment
         : if_must< at_one< '(' >, disable< list > > {};

   struct read_include
         : seq< one< ' ' >, one< '"' >, plus< not_one< '"' > >, one< '"' > > {};

   struct hash_include
         : if_must< string< 'i', 'n', 'c', 'l', 'u', 'd', 'e' >, read_include > {};

   struct hashed
         : if_must< one< '#' >, sor< hash_include, list_comment, hash_comment > > {};

   struct number
         : plus< digit > {};

   struct symbol
         : identifier {};

   struct atom
         : sor< number, symbol > {};

   struct anything;

   struct list
         : if_must< one< '(' >, until< one< ')' >, anything > > {};

   struct normal
         : sor< atom, list > {};

   struct anything
         : sor< space, hashed, normal > {};

   struct main
         : until< eof, anything > {};

   template< typename Rule > struct action
         : public nothing< Rule > {};

   template<>
   struct action< plus< not_one< '"' > > >
   {
      template< typename Input >
      static void apply( const Input & in, std::string & fn )
      {
         fn = in.string();
      }
   };

   template<>
   struct action< hash_include >
   {
      template< typename Input >
      static void apply( const Input & in, std::string & fn )
      {
         std::string f2;
         read_parser( fn, in ).parse< main, action >( f2 );
      }
   };

} // sexpr

int main( int argc, char ** argv )
{
   pegtl::analyze< sexpr::main >();

   for ( int i = 1; i < argc; ++i ) {
      std::string fn;
      pegtl::parse< sexpr::main, sexpr::action >( i, argv, fn );
   }
   return 0;
}
<commit_msg>Fixed illegal code found by Clang 3.5<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <iostream>

#include <pegtl.hh>
#include <pegtl/analyze.hh>
#include <pegtl/read_parser.hh>

namespace sexpr
{
   using namespace pegtl;

   struct hash_comment
         : until< eolf > {};

   struct list;

   struct list_comment
         : if_must< at_one< '(' >, disable< list > > {};

   struct read_include
         : seq< one< ' ' >, one< '"' >, plus< not_one< '"' > >, one< '"' > > {};

   struct hash_include
         : if_must< string< 'i', 'n', 'c', 'l', 'u', 'd', 'e' >, read_include > {};

   struct hashed
         : if_must< one< '#' >, sor< hash_include, list_comment, hash_comment > > {};

   struct number
         : plus< digit > {};

   struct symbol
         : identifier {};

   struct atom
         : sor< number, symbol > {};

   struct anything;

   struct list
         : if_must< one< '(' >, until< one< ')' >, anything > > {};

   struct normal
         : sor< atom, list > {};

   struct anything
         : sor< space, hashed, normal > {};

   struct main
         : until< eof, anything > {};

   template< typename Rule > struct action
         : public nothing< Rule > {};

   template<>
   struct action< plus< not_one< '"' > > >
   {
      template< typename Input >
      static void apply( const Input & in, std::string & fn )
      {
         fn = in.string();
      }
   };

   template<>
   struct action< hash_include >
   {
      template< typename Input >
      static void apply( const Input & in, std::string & fn )
      {
         std::string f2;
         read_parser( fn, in ).parse< main, sexpr::action >( f2 );
      }
   };

} // sexpr

int main( int argc, char ** argv )
{
   pegtl::analyze< sexpr::main >();

   for ( int i = 1; i < argc; ++i ) {
      std::string fn;
      pegtl::parse< sexpr::main, sexpr::action >( i, argv, fn );
   }
   return 0;
}
<|endoftext|>