hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
29631adc7b3945b2bf749588cc44638bd4bae912
6,270
hpp
C++
method_adaptor.hpp
v2lab/max-sick-lms100
a92567a2314662bb7aefc836292181c784cbbc37
[ "MIT" ]
4
2015-05-01T18:05:20.000Z
2019-11-26T07:38:00.000Z
method_adaptor.hpp
v2lab/max-sick-lms100
a92567a2314662bb7aefc836292181c784cbbc37
[ "MIT" ]
null
null
null
method_adaptor.hpp
v2lab/max-sick-lms100
a92567a2314662bb7aefc836292181c784cbbc37
[ "MIT" ]
3
2017-10-12T00:19:06.000Z
2019-10-29T21:38:34.000Z
/* * Member function pointer to C-compatible function pointer conversion. * * The problem: * * - we want to register a member function to be called by C-based callback * system, with 'this' pointer preserved in a callback registration mechanism. * * - we might also want to have function arguments be converted from callback * system's wrapped values to C/C++ types. * * To do that I use the thechnique similar the one found in fast_mem_fn example * from boost::function_types library. The idea is to figure out member function * signature, transform it into a C-compatible function signature and generate a * wrapper with that signature. */ #ifndef BOOST_PP_IS_ITERATING #ifndef method_adaptor_hpp #define method_adaptor_hpp #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/function_types/function_pointer.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/is_member_function_pointer.hpp> #include <boost/utility/enable_if.hpp> #include <boost/config.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/add_reference.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/begin.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/deref.hpp> #ifndef METHOD_ADAPTOR_PRE #define METHOD_ADAPTOR_PRE() #endif #ifndef METHOD_ADAPTOR_POST #define METHOD_ADAPTOR_POST() #endif namespace wrap { namespace ft = boost::function_types; namespace mpl = boost::mpl; using mpl::placeholders::_; /* * In the boost::function_types example I used as inspiration here was a * metafunction computing optimal parameter type for argument forwarding, that * took care that anything larger then sizeof(void*) is passed by reference. * Instead we have here a conversion metafunction which can be customized in * client code, allowing to convert arguments from types supported by callback * system to the ones used in the called API. */ template<typename T> struct param_type : mpl::identity<T> { static T convert_param(typename param_type<T>::type arg) { return arg; } }; #define PARAM_CONVERSION(inner_type, outer_type, arg) \ template<> struct param_type<inner_type> { \ typedef outer_type type; \ static inline inner_type convert_param(outer_type arg); \ }; \ inner_type param_type<inner_type>::convert_param(outer_type arg) namespace detail { template<typename T> struct parameter_types : mpl::transform<ft::parameter_types<T>,param_type<_> >::type { }; } /**********************************************************************************/ /* * Borrowed technique. A bit of original documentation: * * Finally we provide a macro that does have similar semantics to the * function template mem_fn of the Bind library. * * We can't use a function template and use a macro instead, because we use * a member function pointer that is a compile time constant. So we first * have to deduce the type and create a template that accepts this type as a * non-type template argument, which is passed in in a second step. The * macro hides this lengthy expression from the user. */ #define METHOD_ADAPTOR(mfp) wrap::make_method_adaptor(mfp).make_method_adaptor<mfp>() template< typename MFPT, MFPT MemberFunction , size_t Arity = ft::function_arity<MFPT>::value > struct method_adaptor; template<typename MFPT> struct method_adaptor_maker { typedef typename mpl::push_front< detail::parameter_types<MFPT>, typename ft::result_type<MFPT>::type >::type wrapper_sig; template<MFPT Callee> typename ft::function_pointer< wrapper_sig >::type make_method_adaptor() { return method_adaptor<MFPT,Callee>::call; } }; template<typename MFPT> typename boost::enable_if<boost::is_member_function_pointer<MFPT>, method_adaptor_maker<MFPT> >::type make_method_adaptor(MFPT) { return method_adaptor_maker<MFPT>(); } /**********************************************************************************/ /* preprocessor-based code generator to continue the repetitive part, above */ #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/iteration/local.hpp> #include <boost/preprocessor/repetition/enum_shifted.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #define BOOST_PP_FILENAME_1 "method_adaptor.hpp" #define BOOST_PP_ITERATION_LIMITS (1,BOOST_FT_MAX_ARITY) #include BOOST_PP_ITERATE() } // namespace wrap /**********************************************************************************/ #endif #else /**********************************************************************************/ /* repetition body */ #define N BOOST_PP_FRAME_ITERATION(1) template< typename MFPT, MFPT MemberFunction > struct method_adaptor<MFPT, MemberFunction, N > { // decompose the result and the parameter types (public for introspection) typedef typename ft::result_type<MFPT>::type result_type; typedef detail::parameter_types<MFPT> parameter_types; private: // iterate the parameter types typedef typename mpl::begin<parameter_types>::type i0; typedef typename mpl::begin<ft::parameter_types<MFPT> >::type t0; #if N>1 #define BOOST_PP_LOCAL_LIMITS (0,N-2) #define BOOST_PP_LOCAL_MACRO(j) \ typedef typename mpl::next< i ## j >::type BOOST_PP_CAT(i,BOOST_PP_INC(j)) ; \ typedef typename mpl::next< t ## j >::type BOOST_PP_CAT(t,BOOST_PP_INC(j)) ; #include BOOST_PP_LOCAL_ITERATE() #endif public: static result_type call( BOOST_PP_ENUM_BINARY_PARAMS(N, typename mpl::deref<i,>::type a) ) { typename mpl::deref< t0 >::type self = param_type< typename mpl::deref< t0 >::type >::convert_param(a0); METHOD_ADAPTOR_PRE() #define CONV(z,i,data) param_type< typename mpl::deref< BOOST_PP_CAT(t,i) >::type >::convert_param( BOOST_PP_CAT(a,i) ) return (self.*MemberFunction)(BOOST_PP_ENUM_SHIFTED(N,CONV,~)); #undef CONV METHOD_ADAPTOR_POST() }; }; #undef N /**********************************************************************************/ #endif
33.351064
120
0.696651
v2lab
2968c3637024fa8a2a43a4e7bd6aa82f994e7391
2,861
cpp
C++
examples/script_error_handling.cpp
a1ien/sol2
358c34e5e978524d7c0dbf3f69987f57dfb30da6
[ "MIT" ]
null
null
null
examples/script_error_handling.cpp
a1ien/sol2
358c34e5e978524d7c0dbf3f69987f57dfb30da6
[ "MIT" ]
null
null
null
examples/script_error_handling.cpp
a1ien/sol2
358c34e5e978524d7c0dbf3f69987f57dfb30da6
[ "MIT" ]
null
null
null
#define SOL_CHECK_ARGUMENTS 1 #include <sol.hpp> #include "assert.hpp" #include <iostream> int main(int, char**) { std::cout << "=== script error handling example ===" << std::endl; sol::state lua; std::string code = R"( bad&$#*$syntax bad.code = 2 return 24 )"; /* OPTION 1 */ // Handling code like this can be robust // If you disable exceptions, then obviously you would remove // the try-catch branches, // and then rely on the `lua_atpanic` function being called // and trapping errors there before exiting the application { // script_default_on_error throws / panics when the code is bad: trap the error try { int value = lua.script(code, sol::script_default_on_error); // This will never be reached std::cout << value << std::endl; c_assert(value == 24); } catch (const sol::error& err) { std::cout << "Something went horribly wrong: thrown error" << "\n\t" << err.what() << std::endl; } } /* OPTION 2 */ // Use the script_pass_on_error handler // this simply passes through the protected_function_result, // rather than throwing it or calling panic // This will check code validity and also whether or not it runs well { sol::protected_function_result result = lua.script(code, sol::script_pass_on_error); c_assert(!result.valid()); if (!result.valid()) { sol::error err = result; sol::call_status status = result.status(); std::cout << "Something went horribly wrong: " << sol::to_string(status) << " error" << "\n\t" << err.what() << std::endl; } } /* OPTION 3 */ // This is a lower-level, more explicit way to load code // This explicitly loads the code, giving you access to any errors // plus the load status // then, it turns the loaded code into a sol::protected_function // which is then called so that the code can run // you can then check that too, for any errors // The two previous approaches are recommended { sol::load_result loaded_chunk = lua.load(code); c_assert(!loaded_chunk.valid()); if (!loaded_chunk.valid()) { sol::error err = loaded_chunk; sol::load_status status = loaded_chunk.status(); std::cout << "Something went horribly wrong loading the code: " << sol::to_string(status) << " error" << "\n\t" << err.what() << std::endl; } else { // Because the syntax is bad, this will never be reached c_assert(false); // If there is a runtime error (lua GC memory error, nil access, etc.) // it will be caught here sol::protected_function script_func = loaded_chunk; sol::protected_function_result result = script_func(); if (!result.valid()) { sol::error err = result; sol::call_status status = result.status(); std::cout << "Something went horribly wrong running the code: " << sol::to_string(status) << " error" << "\n\t" << err.what() << std::endl; } } } std::cout << std::endl; return 0; }
32.885057
143
0.670045
a1ien
296c0148cc9d30e34b83f4f3911b36954176a43c
5,965
cc
C++
src/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonov.cc
Haydelj/SCIRun
f7ee04d85349b946224dbff183438663e54b9413
[ "MIT" ]
92
2015-02-09T22:42:11.000Z
2022-03-25T09:14:50.000Z
src/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonov.cc
Haydelj/SCIRun
f7ee04d85349b946224dbff183438663e54b9413
[ "MIT" ]
1,618
2015-01-05T19:39:13.000Z
2022-03-27T20:28:45.000Z
src/Modules/Legacy/Inverse/SolveInverseProblemWithTikhonov.cc
Haydelj/SCIRun
f7ee04d85349b946224dbff183438663e54b9413
[ "MIT" ]
64
2015-02-20T17:51:23.000Z
2021-11-19T07:08:08.000Z
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// File : SolveInverseProblemWithTikhonov.cc /// Author : Jaume Coll-Font, Moritz Dannhauer, Ayla Khan, Dan White /// Date : September 06th, 2017 (last update) #include <Core/Datatypes/String.h> #include <Core/Datatypes/Scalar.h> #include <Modules/Legacy/Inverse/SolveInverseProblemWithTikhonov.h> #include <Modules/Legacy/Inverse/LCurvePlot.h> #include <Core/Algorithms/Base/AlgorithmBase.h> #include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithStandardTikhonovImpl.h> #include <Core/Datatypes/DenseColumnMatrix.h> #include <Core/Datatypes/MatrixIO.h> #include <Core/Datatypes/Legacy/Field/Field.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Modules; using namespace SCIRun::Modules::Inverse; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Inverse; // Module definitions. Sets the info into the staticInfo_ MODULE_INFO_DEF(SolveInverseProblemWithTikhonov, Inverse, SCIRun) // Constructor neeeds to have empty inputs and the parent's constructor has staticInfo_ as an input (adapted to thsi module in MODULE_INFO_DEF macro) // Constructor needs to initialize all input/output ports SolveInverseProblemWithTikhonov::SolveInverseProblemWithTikhonov() : Module(staticInfo_) { INITIALIZE_PORT(ForwardMatrix); INITIALIZE_PORT(WeightingInSourceSpace); INITIALIZE_PORT(MeasuredPotentials); INITIALIZE_PORT(WeightingInSensorSpace); INITIALIZE_PORT(InverseSolution); INITIALIZE_PORT(RegularizationParameter); INITIALIZE_PORT(RegInverse); } void SolveInverseProblemWithTikhonov::setStateDefaults() { setStateStringFromAlgo(Parameters::TikhonovImplementation); setStateStringFromAlgoOption(Parameters::RegularizationMethod); setStateIntFromAlgo(Parameters::regularizationChoice); setStateDoubleFromAlgo(Parameters::LambdaFromDirectEntry); setStateDoubleFromAlgo(Parameters::LambdaMin); setStateDoubleFromAlgo(Parameters::LambdaMax); setStateIntFromAlgo(Parameters::LambdaNum); setStateDoubleFromAlgo(Parameters::LambdaResolution); setStateDoubleFromAlgo(Parameters::LambdaSliderValue); setStateIntFromAlgo(Parameters::regularizationSolutionSubcase); setStateIntFromAlgo(Parameters::regularizationResidualSubcase); } // execute function void SolveInverseProblemWithTikhonov::execute() { // load required inputs auto forward_matrix_h = getRequiredInput(ForwardMatrix); auto hMatrixMeasDat = getRequiredInput(MeasuredPotentials); // load optional inputs auto hMatrixRegMat = getOptionalInput(WeightingInSourceSpace); auto hMatrixNoiseCov = getOptionalInput(WeightingInSensorSpace); if (needToExecute()) { auto state = get_state(); // set parameters state->setValue( Parameters::TikhonovImplementation, std::string("standardTikhonov") ); setAlgoStringFromState(Parameters::TikhonovImplementation); setAlgoOptionFromState(Parameters::RegularizationMethod); setAlgoIntFromState(Parameters::regularizationChoice); setAlgoDoubleFromState(Parameters::LambdaFromDirectEntry); setAlgoDoubleFromState(Parameters::LambdaMin); setAlgoDoubleFromState(Parameters::LambdaMax); setAlgoIntFromState(Parameters::LambdaNum); setAlgoDoubleFromState(Parameters::LambdaResolution); setAlgoDoubleFromState(Parameters::LambdaSliderValue); setAlgoIntFromState(Parameters::regularizationSolutionSubcase); setAlgoIntFromState(Parameters::regularizationResidualSubcase); // run auto output = algo().run( withInputData((ForwardMatrix, forward_matrix_h)(MeasuredPotentials,hMatrixMeasDat)(MeasuredPotentials,hMatrixMeasDat)(WeightingInSourceSpace,optionalAlgoInput(hMatrixRegMat))(WeightingInSensorSpace,optionalAlgoInput(hMatrixNoiseCov))) ); // set outputs sendOutputFromAlgorithm(InverseSolution,output); sendOutputFromAlgorithm(RegularizationParameter,output); sendOutputFromAlgorithm(RegInverse,output); auto lambda = output.get<DenseMatrix>(TikhonovAlgoAbstractBase::RegularizationParameter); auto lambda_array = output.get<DenseMatrix>(TikhonovAlgoAbstractBase::LambdaArray); auto lambda_index = output.get<DenseMatrix>(TikhonovAlgoAbstractBase::Lambda_Index); auto regularization_method = state->getValue(Parameters::RegularizationMethod).toString(); if (regularization_method== "lcurve") { LCurvePlot helper; auto str = helper.update_lcurve_gui(id(),lambda,lambda_array,lambda_index); state->setTransientValue("LambdaCorner", lambda->get(0,0)); state->setTransientValue("LambdaCurveInfo", str); state->setTransientValue("LambdaCurve", lambda_array); state->setTransientValue("LambdaCornerPlot", helper.cornerPlot()); } } }
43.860294
265
0.800838
Haydelj
296c9f6eea7ec7ba60a2f6812ade2ae325ca0cf7
11,473
hpp
C++
include/mpicxx/detail/source_location.hpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-10-20T06:53:05.000Z
2020-10-20T06:53:05.000Z
include/mpicxx/detail/source_location.hpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
null
null
null
include/mpicxx/detail/source_location.hpp
arkantos493/MPICXX
ffbaeaaa3c7248e2087c3716ec71e0612aafe689
[ "MIT" ]
1
2020-08-13T17:46:40.000Z
2020-08-13T17:46:40.000Z
/** * @file * @author Marcel Breyer * @date 2020-07-21 * @copyright This file is distributed under the MIT License. * * @brief Provides a class similar to [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location). * @details Differences are: * - The new macro `MPICXX_PRETTY_FUNC_NAME__` is defined as `__PRETTY_FUNC__` ([GCC](https://gcc.gnu.org/) and * [clang](https://clang.llvm.org/)), `__FUNCSIG__` ([MSVC](https://visualstudio.microsoft.com/de/vs/features/cplusplus/)) or * `__func__` (otherwise). This macro can be used as first parameter to the static * @ref mpicxx::detail::source_location::current() function to get a better function name. * - Includes a member-function @ref mpicxx::detail::source_location::rank() which holds the current MPI rank (if a MPI environment * is currently active). * - The @ref mpicxx::detail::source_location::stack_trace() function can be used to print/get the current function call stack. */ #ifndef MPICXX_SOURCE_LOCATION_HPP #define MPICXX_SOURCE_LOCATION_HPP #include <fmt/format.h> #include <mpi.h> #include <optional> #include <string> #include <vector> /** * @def MPICXX_PRETTY_FUNC_NAME__ * @brief The @ref MPICXX_PRETTY_FUNC_NAME__ macro is defined as `__PRETTY_FUNC__` ([GCC](https://gcc.gnu.org/) and * [clang](https://clang.llvm.org/)), `__FUNCSIG__` ([MSVC](https://visualstudio.microsoft.com/de/vs/features/cplusplus/)) or * `__func__` (otherwise). * @details It can be used as compiler independent way to enable a better function name when used as first parameter to * @ref mpicxx::detail::source_location::current(). */ #ifdef __GNUG__ #include <execinfo.h> #include <cxxabi.h> #define MPICXX_PRETTY_FUNC_NAME__ __PRETTY_FUNCTION__ #elif _MSC_VER #define MPICXX_PRETTY_FUNC_NAME__ __FUNCSIG__ #else #define MPICXX_PRETTY_FUNC_NAME__ __func__ #endif namespace mpicxx::detail { /** * @brief Represents information of a specific source code location. * @details Example usage: * @snippet examples/detail/source_location.cpp mwe */ class source_location { public: /** * @brief Constructs a new @ref mpicxx::detail::source_location with the respective information about the current call side. * @details The MPI rank is set to [`std::nullopt`](https://en.cppreference.com/w/cpp/utility/optional/nullopt) if an error occurred * during the call to [*MPI_Comm_rank*](https://www.mpi-forum.org/docs/mpi-3.1/mpi31-report/node155.htm) * (an exception is thrown or a return code different than * [*MPI_SUCCESS*](https://www.mpi-forum.org/docs/mpi-3.1/mpi31-report/node222.htm) is returned). * @param[in] func the function name (including its signature if supported via the macro `MPICXX_PRETTY_FUNC_NAME__`) * @param[in] file the file name (absolute path) * @param[in] line the line number * @param[in] column the column number * @return the @ref mpicxx::detail::source_location holding the call side location information * @nodiscard * * @attention @p column is always (independent of the call side position) default initialized to 0! * * @calls{ * int MPI_Initialized(int *flag); // exactly once * int MPI_Finalized(int *flag); // exactly once * int MPI_Comm_rank(MPI_Comm comm, int *rank); // at most once * } */ [[nodiscard]] static source_location current( const char* func = __builtin_FUNCTION(), const char* file = __builtin_FILE(), const int line = __builtin_LINE(), const int column = 0 ) noexcept { source_location loc; loc.file_ = file; loc.func_ = func; loc.line_ = line; loc.column_ = column; try { // get the current MPI rank iff the MPI environment is active int is_initialized, is_finalized; MPI_Initialized(&is_initialized); MPI_Finalized(&is_finalized); if (static_cast<bool>(is_initialized) && !static_cast<bool>(is_finalized)) { int rank; int err = MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (err == MPI_SUCCESS) { loc.rank_ = std::make_optional(rank); } } } catch (...) { // something went wrong during the MPI calls -> no information could be retrieved loc.rank_ = std::nullopt; } return loc; } /** * @brief Returns the current stack trace. * @details For a better stack trace (precise function names) the linker flag `-rdynamic` is set if and only if **any** * `MPICXX_ASSERTION_...` has been activated during [`Cmake`](https://cmake.org/)'s configuration step. * * A sample stack trace (while `-rdynamic` is set) could look like: * @code * stack trace: * #5 ./output.s: test(int) [+0x3] * #4 ./output.s: foo() [+0x1] * #3 ./output.s: main() [+0x1] * #2 /lib/x86_64-linux-gnu/libc.so.6: __libc_start_main() [+0xe] * #1 ./output.s: _start() [+0x2] * @endcode * @param[in] max_call_stack_size the maximum depth of the stack trace report * @return the stack trace * @nodiscard * * @attention The stack trace report is only available under [GCC](https://gcc.gnu.org/) and [clang](https://clang.llvm.org/) * (to be precise: only if `__GNUG__` is defined). This function does nothing if `__GNUG__` isn't defined. */ [[nodiscard]] static inline std::string stack_trace([[maybe_unused]] const int max_call_stack_size = 64) { #if defined(MPICXX_ENABLE_STACK_TRACE) && defined(__GNUG__) using std::to_string; fmt::memory_buffer buf; fmt::format_to(buf, "stack trace:\n"); std::vector<std::string> symbols; symbols.reserve(max_call_stack_size); { // storage array for stack trace address data std::vector<void*> addrlist(max_call_stack_size); // retrieve current stack addresses const int addrlen = backtrace(addrlist.data(), max_call_stack_size); // no stack addresses could be retrieved if (addrlen == 0) { return fmt::format("{} <empty, possibly corrupt>\n", to_string(buf)); } // resolve addresses into symbol strings char** symbollist = backtrace_symbols(addrlist.data(), addrlen); for (int i = 0; i < addrlen; ++i) { symbols.emplace_back(symbollist[i]); } free(symbollist); } // iterate over the returned symbol lines -> skip the first and second symbol because they are unimportant for (std::size_t i = 2; i < symbols.size(); ++i) { fmt::format_to(buf, " #{:<6}", symbols.size() - i); // file_name(function_name+offset) -> split the symbol line accordingly const std::size_t position1 = std::min(symbols[i].find_first_of("("), symbols[i].size()); const std::size_t position2 = std::min(symbols[i].find_first_of("+"), symbols[i].size()); const std::size_t position3 = std::min(symbols[i].find_first_of(")"), symbols[i].size()); std::string_view symbols_view(symbols[i]); std::string_view file_name = symbols_view.substr(0, position1); std::string function_name = symbols[i].substr(position1 + 1, position2 - position1 - 1); std::string_view function_offset = symbols_view.substr(position2, position3 - position2 - 1); // check if something went wrong while splitting the symbol line if (!file_name.empty() && !function_name.empty() && !function_offset.empty()) { // demangle function name int status = 0; char* function_name_demangled = abi::__cxa_demangle(function_name.data(), nullptr, nullptr, &status); if (status == 0) { // demangling successful -> print pretty function name fmt::format_to(buf, "{}: {} [{}]\n", file_name, function_name_demangled, function_offset); } else { // demangling failed -> print un-demangled function name fmt::format_to(buf, "{}: {}() [{}]\n", file_name, function_name, function_offset); } free(function_name_demangled); } else { // print complete symbol line if the splitting went wrong fmt::format_to(buf, "{}\n", symbols[i]); } } return fmt::format("{}\n", to_string(buf)); #elif defined(MPICXX_ENABLED_STACK_TRACE) && !defined(__GNUG__) // stack traces enabled but not supported return std::string("No stack trace supported!"); #else // stack traces not supported return std::string{}; #endif } /** * @brief Returns the absolute path name of the file. * @return the file name * @nodiscard */ [[nodiscard]] constexpr const char* file_name() const noexcept { return file_; } /** * @brief Returns the function name without additional signature information (i.e. return type or parameters). * @return the function name * @nodiscard */ [[nodiscard]] constexpr const char* function_name() const noexcept { return func_; } /** * @brief Returns the line number. * @return the line number * @nodiscard */ [[nodiscard]] constexpr int line() const noexcept { return line_; } /** * @brief Returns the column number. * @return the column number * @nodiscard * * @attention Default value in @ref mpicxx::detail::source_location::current() always 0! */ [[nodiscard]] constexpr int column() const noexcept { return column_; } /** * @brief Returns the rank if a MPI environment is currently active. * @details If no MPI environment is currently active, the returned * [`std::nullopt`](https://en.cppreference.com/w/cpp/utility/optional/nullopt) is empty. * @return a [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional) containing the current MPI rank * @nodiscard */ [[nodiscard]] constexpr std::optional<int> rank() const noexcept { return rank_; } private: const char* file_ = "unknown"; const char* func_ = "unknown"; int line_ = 0; int column_ = 0; std::optional<int> rank_ = std::nullopt; }; } #endif // MPICXX_SOURCE_LOCATION_HPP
45.892
140
0.580232
arkantos493
296db7a44919414d9c4be57e139a5404cd2cafb0
11,225
cpp
C++
src/hybrid_a_star_flow.cpp
HongweiSunny/Hybrid_A_Star
bb02fd767a9136779117afb6d14b3a6ba18a8914
[ "BSD-3-Clause" ]
49
2022-03-26T14:32:10.000Z
2022-03-31T23:29:34.000Z
src/hybrid_a_star_flow.cpp
HongweiSunny/Hybrid_A_Star
bb02fd767a9136779117afb6d14b3a6ba18a8914
[ "BSD-3-Clause" ]
1
2022-03-29T07:04:07.000Z
2022-03-29T09:47:49.000Z
src/hybrid_a_star_flow.cpp
HongweiSunny/Hybrid_A_Star
bb02fd767a9136779117afb6d14b3a6ba18a8914
[ "BSD-3-Clause" ]
8
2022-03-26T14:33:45.000Z
2022-03-31T05:27:12.000Z
/******************************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2022 Zhang Zhimeng * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 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 HOLDER 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. ******************************************************************************/ #include "hybrid_a_star/hybrid_a_star_flow.h" #include <nav_msgs/Path.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_datatypes.h> #include <tf/transform_broadcaster.h> double Mod2Pi(const double &x) { double v = fmod(x, 2 * M_PI); if (v < -M_PI) { v += 2.0 * M_PI; } else if (v > M_PI) { v -= 2.0 * M_PI; } return v; } HybridAStarFlow::HybridAStarFlow(ros::NodeHandle &nh) { double steering_angle = nh.param("planner/steering_angle", 10); int steering_angle_discrete_num = nh.param("planner/steering_angle_discrete_num", 1); double wheel_base = nh.param("planner/wheel_base", 1.0); double segment_length = nh.param("planner/segment_length", 1.6); int segment_length_discrete_num = nh.param("planner/segment_length_discrete_num", 8); double steering_penalty = nh.param("planner/steering_penalty", 1.05); double steering_change_penalty = nh.param("planner/steering_change_penalty", 1.5); double reversing_penalty = nh.param("planner/reversing_penalty", 2.0); double shot_distance = nh.param("planner/shot_distance", 5.0); kinodynamic_astar_searcher_ptr_ = std::make_shared<HybridAStar>( steering_angle, steering_angle_discrete_num, segment_length, segment_length_discrete_num, wheel_base, steering_penalty, reversing_penalty, steering_change_penalty, shot_distance ); costmap_sub_ptr_ = std::make_shared<CostMapSubscriber>(nh, "/map", 1); init_pose_sub_ptr_ = std::make_shared<InitPoseSubscriber2D>(nh, "/initialpose", 1); goal_pose_sub_ptr_ = std::make_shared<GoalPoseSubscriber2D>(nh, "/move_base_simple/goal", 1); path_pub_ = nh.advertise<nav_msgs::Path>("searched_path", 1); searched_tree_pub_ = nh.advertise<visualization_msgs::Marker>("searched_tree", 1); vehicle_path_pub_ = nh.advertise<visualization_msgs::MarkerArray>("vehicle_path", 1); has_map_ = false; } void HybridAStarFlow::Run() { ReadData(); if (!has_map_) { if (costmap_deque_.empty()) { return; } current_costmap_ptr_ = costmap_deque_.front(); costmap_deque_.pop_front(); const double map_resolution = 0.2; kinodynamic_astar_searcher_ptr_->Init( current_costmap_ptr_->info.origin.position.x, 1.0 * current_costmap_ptr_->info.width * current_costmap_ptr_->info.resolution, current_costmap_ptr_->info.origin.position.y, 1.0 * current_costmap_ptr_->info.height * current_costmap_ptr_->info.resolution, current_costmap_ptr_->info.resolution, map_resolution ); unsigned int map_w = std::floor(current_costmap_ptr_->info.width / map_resolution); unsigned int map_h = std::floor(current_costmap_ptr_->info.height / map_resolution); for (unsigned int w = 0; w < map_w; ++w) { for (unsigned int h = 0; h < map_h; ++h) { auto x = static_cast<unsigned int> ((w + 0.5) * map_resolution / current_costmap_ptr_->info.resolution); auto y = static_cast<unsigned int> ((h + 0.5) * map_resolution / current_costmap_ptr_->info.resolution); if (current_costmap_ptr_->data[y * current_costmap_ptr_->info.width + x]) { kinodynamic_astar_searcher_ptr_->SetObstacle(w, h); } } } has_map_ = true; } costmap_deque_.clear(); while (HasStartPose() && HasGoalPose()) { InitPoseData(); double start_yaw = tf::getYaw(current_init_pose_ptr_->pose.pose.orientation); double goal_yaw = tf::getYaw(current_goal_pose_ptr_->pose.orientation); Vec3d start_state = Vec3d( current_init_pose_ptr_->pose.pose.position.x, current_init_pose_ptr_->pose.pose.position.y, start_yaw ); Vec3d goal_state = Vec3d( current_goal_pose_ptr_->pose.position.x, current_goal_pose_ptr_->pose.position.y, goal_yaw ); if (kinodynamic_astar_searcher_ptr_->Search(start_state, goal_state)) { auto path = kinodynamic_astar_searcher_ptr_->GetPath(); PublishPath(path); PublishVehiclePath(path, 4.0, 2.0, 5u); PublishSearchedTree(kinodynamic_astar_searcher_ptr_->GetSearchedTree()); nav_msgs::Path path_ros; geometry_msgs::PoseStamped pose_stamped; for (const auto &pose: path) { pose_stamped.header.frame_id = "world"; pose_stamped.pose.position.x = pose.x(); pose_stamped.pose.position.y = pose.y(); pose_stamped.pose.position.z = 0.0; pose_stamped.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, pose.z()); path_ros.poses.emplace_back(pose_stamped); } path_ros.header.frame_id = "world"; path_ros.header.stamp = ros::Time::now(); static tf::TransformBroadcaster transform_broadcaster; for (const auto &pose: path_ros.poses) { tf::Transform transform; transform.setOrigin(tf::Vector3(pose.pose.position.x, pose.pose.position.y, 0.0)); tf::Quaternion q; q.setX(pose.pose.orientation.x); q.setY(pose.pose.orientation.y); q.setZ(pose.pose.orientation.z); q.setW(pose.pose.orientation.w); transform.setRotation(q); transform_broadcaster.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", "ground_link") ); ros::Duration(0.05).sleep(); } } // debug // std::cout << "visited nodes: " << kinodynamic_astar_searcher_ptr_->GetVisitedNodesNumber() << std::endl; kinodynamic_astar_searcher_ptr_->Reset(); } } void HybridAStarFlow::ReadData() { costmap_sub_ptr_->ParseData(costmap_deque_); init_pose_sub_ptr_->ParseData(init_pose_deque_); goal_pose_sub_ptr_->ParseData(goal_pose_deque_); } void HybridAStarFlow::InitPoseData() { current_init_pose_ptr_ = init_pose_deque_.front(); init_pose_deque_.pop_front(); current_goal_pose_ptr_ = goal_pose_deque_.front(); goal_pose_deque_.pop_front(); } bool HybridAStarFlow::HasGoalPose() { return !goal_pose_deque_.empty(); } bool HybridAStarFlow::HasStartPose() { return !init_pose_deque_.empty(); } void HybridAStarFlow::PublishPath(const VectorVec3d &path) { nav_msgs::Path nav_path; geometry_msgs::PoseStamped pose_stamped; for (const auto &pose: path) { pose_stamped.header.frame_id = "world"; pose_stamped.pose.position.x = pose.x(); pose_stamped.pose.position.y = pose.y(); pose_stamped.pose.position.z = 0.0; pose_stamped.pose.orientation = tf::createQuaternionMsgFromYaw(pose.z()); nav_path.poses.emplace_back(pose_stamped); } nav_path.header.frame_id = "world"; nav_path.header.stamp = timestamp_; path_pub_.publish(nav_path); } void HybridAStarFlow::PublishVehiclePath(const VectorVec3d &path, double width, double length, unsigned int vehicle_interval = 5u) { visualization_msgs::MarkerArray vehicle_array; for (unsigned int i = 0; i < path.size(); i += vehicle_interval) { visualization_msgs::Marker vehicle; if (i == 0) { vehicle.action = 3; } vehicle.header.frame_id = "world"; vehicle.header.stamp = ros::Time::now(); vehicle.type = visualization_msgs::Marker::CUBE; vehicle.id = static_cast<int>(i / vehicle_interval); vehicle.scale.x = width; vehicle.scale.y = length; vehicle.scale.z = 0.01; vehicle.color.a = 0.1; vehicle.color.r = 1.0; vehicle.color.b = 0.0; vehicle.color.g = 0.0; vehicle.pose.position.x = path[i].x(); vehicle.pose.position.y = path[i].y(); vehicle.pose.position.z = 0.0; vehicle.pose.orientation = tf::createQuaternionMsgFromYaw(path[i].z()); vehicle_array.markers.emplace_back(vehicle); } vehicle_path_pub_.publish(vehicle_array); } void HybridAStarFlow::PublishSearchedTree(const VectorVec4d &searched_tree) { visualization_msgs::Marker tree_list; tree_list.header.frame_id = "world"; tree_list.header.stamp = ros::Time::now(); tree_list.type = visualization_msgs::Marker::LINE_LIST; tree_list.action = visualization_msgs::Marker::ADD; tree_list.ns = "searched_tree"; tree_list.scale.x = 0.02; tree_list.color.a = 1.0; tree_list.color.r = 0; tree_list.color.g = 0; tree_list.color.b = 0; tree_list.pose.orientation.w = 1.0; tree_list.pose.orientation.x = 0.0; tree_list.pose.orientation.y = 0.0; tree_list.pose.orientation.z = 0.0; geometry_msgs::Point point; for (const auto &i: searched_tree) { point.x = i.x(); point.y = i.y(); point.z = 0.0; tree_list.points.emplace_back(point); point.x = i.z(); point.y = i.w(); point.z = 0.0; tree_list.points.emplace_back(point); } searched_tree_pub_.publish(tree_list); }
38.706897
114
0.632962
HongweiSunny
2970a5c707ae6637dbdcd0828f2ad0bc1058fd29
2,498
cpp
C++
src/DisplayManager.cpp
Artemijs/OpenGL
b012e381c8800a117414108df8ba3f210e3b8398
[ "MIT" ]
null
null
null
src/DisplayManager.cpp
Artemijs/OpenGL
b012e381c8800a117414108df8ba3f210e3b8398
[ "MIT" ]
null
null
null
src/DisplayManager.cpp
Artemijs/OpenGL
b012e381c8800a117414108df8ba3f210e3b8398
[ "MIT" ]
null
null
null
#include "DisplayManager.h" #include <iostream> #include <string> DisplayManager* DisplayManager::m_instance = NULL; DisplayManager::DisplayManager(){ //initialize sdls video subsystem if(SDL_Init(SDL_INIT_VIDEO)<0){ std::cout<<"failed to init sdl\n"; } //create window m_window = SDL_CreateWindow("temp_lol_name", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 512, 512, SDL_WINDOW_OPENGL); //check that it worked if(!m_window){ std::cout<<"unable to create window\n"; checkSDLError(__LINE__); } //create opengl context and attach it to our window m_context = SDL_GL_CreateContext(m_window); setGLAttribs(); //makes buffer swap synchronized with montinors vertical refresh SDL_GL_SetSwapInterval(0); #ifndef __APPLE__ glewExperimental = GL_TRUE; glewInit(); #endif std::cout<<"created display\n"; } DisplayManager* DisplayManager::instance(){ if(!m_instance) m_instance = new DisplayManager(); return m_instance; } SDL_GLContext* DisplayManager::getContext(){ return &m_context; } SDL_Window* DisplayManager::getWindow(){ return m_window; } bool DisplayManager::setGLAttribs(){ //set opengl version //SDL_GL_CONTEXT_CORE GIVES THE NEWEST VERSION AND DISABLES DEPRICATED VERSION SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); //TURN ON DOUBLE BUffer with 24 bit z buffer //may need to change this to 16 or 32 for "your system" SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); return true; } void DisplayManager::printSDL_GL_Attribs(){ int value =0; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value); std::cout<<" SDL_GL_CONTEXT_MAJOR_VERsION : "<<value<<"\n"; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value); std::cout<<" SDL_GL_CONTEXT_MINOR_VERsION : "<<value<<"\n"; } void DisplayManager::checkSDLError(int line){ std::string error = SDL_GetError(); if(error !=""){ std::cout<<"SDL error : "<<error<<"\n"; if(line != -1){ std::cout<<"\nLine : "<<line<<"\n"; } SDL_ClearError(); } } void DisplayManager::cleanUp(){ SDL_GL_DeleteContext(m_context); SDL_DestroyWindow(m_window); SDL_Quit(); } void DisplayManager::update(){ SDL_GL_SwapWindow(m_window); }
28.712644
126
0.689752
Artemijs
2971dcb3c6e53a44cd16313d7245645bedec2c85
8,238
cpp
C++
src/glbase/meshrenderer.cpp
traits/Traits3D
09eb850ad4e1054a5574346a6b479dc2d60b1f09
[ "Apache-2.0" ]
null
null
null
src/glbase/meshrenderer.cpp
traits/Traits3D
09eb850ad4e1054a5574346a6b479dc2d60b1f09
[ "Apache-2.0" ]
null
null
null
src/glbase/meshrenderer.cpp
traits/Traits3D
09eb850ad4e1054a5574346a6b479dc2d60b1f09
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include "glb/shader_std.h" #include "glb/meshrenderer.h" namespace traits3d { namespace gl { const std::string MeshRenderer::v_core_delta_ = "v_core_delta"; const std::string MeshRenderer::v_seam_delta_ = "v_seam_delta"; const char *MeshRenderer::VertexCoreCode = { #ifdef GL_ES_VERSION_3_0 "#version 300 es\n" #else "#version 330\n" #endif "uniform mat4 proj_matrix; \n" "uniform mat4 mv_matrix; \n" "layout (location = 0) in vec3 v_coordinates;\n" "in vec3 v_normals;\n" "uniform vec4 v_in_color;\n" "out vec4 v_out_color;\n" "void main()\n" "{\n" " gl_Position = proj_matrix * mv_matrix * vec4(v_coordinates, 1.0);\n" " v_out_color = v_in_color;\n" "}" }; const char *MeshRenderer::VertexSeamCode = { #ifdef GL_ES_VERSION_3_0 "#version 300 es\n" #else "#version 330\n" #endif "uniform mat4 proj_matrix; \n" "uniform mat4 mv_matrix; \n" "layout (location = 0) in vec3 v_coordinates;\n" "in vec3 v_normals;\n" "in vec4 v_in_color;\n" "out vec4 v_out_color;\n" "void main()\n" "{\n" " gl_Position = proj_matrix * mv_matrix * vec4(v_coordinates, 1.0);\n" " v_out_color = v_in_color;\n" "}" }; const char *MeshRenderer::FragmentCode = { #ifdef GL_ES_VERSION_3_0 "#version 300 es\n" #else "#version 330\n" #endif "in vec4 v_out_color;\n" "out vec4 frag_color;\n" "void main()\n" "{" " frag_color = v_out_color;\n" "}" }; MeshRenderer::MeshRenderer() { if (!core_shader_.create(VertexCoreCode, FragmentCode)) return; //todo throw if (!seam_shader_.create(VertexSeamCode, FragmentCode)) return; //todo throw core_vbo_ = std::make_unique<glb::VBO>(&vao_p, 3); seam_color_vbo_ = std::make_unique<glb::VBO>(&vao_p, 4); core_ibo_ = std::make_unique<glb::IBO>(&vao_p); offset_vbo_ = std::make_unique<glb::VBO>(&vao_p, 3); seam_ibo_ = std::make_unique<glb::IBO>(&vao_p); // Saum } void MeshRenderer::createData2(std::vector<TripleF> const &mesh_data, glb::IndexMaker::IndexType xsize, glb::IndexMaker::IndexType ysize) { if (mesh_data.empty() || mesh_data.size() != xsize * ysize) return; const glb::IndexMaker::IndexType len_data = mesh_data.size(); // mesh data std::vector<TripleF> mdata(len_data - xsize); std::copy(mesh_data.begin() + xsize, mesh_data.end(), mdata.begin()); if (!core_vbo_->setData(mdata)) return; // offsets std::vector<TripleF> odata(mdata); for (auto k = 0; k != odata.size(); ++k) odata[k] -= mesh_data[k]; if (!offset_vbo_->setData(odata)) return; //// indexes // //std::vector<IndexMaker::IndexType> midata(xsize*(ysize-1) + ); //for (auto k = xsize; k != len_data; ++k) //{ // midata[k] = //} } void MeshRenderer::createData(std::vector<TripleF> const &mesh_data, glb::IndexMaker::IndexType xsize, glb::IndexMaker::IndexType ysize) { if (mesh_data.empty() || mesh_data.size() != xsize * ysize) return; const glb::IndexMaker::IndexType len_data = xsize * ysize; float delta[] = { 0.01f, 0.004f }; std::vector<TripleF> mdata(5 * len_data - 4 * xsize + 4 * len_data - 4 * ysize); // original data std::copy(mesh_data.begin(), mesh_data.end(), mdata.begin()); // additional data for core and seams TripleF w[2]; // x direction for (auto i = 0; i != len_data - xsize; ++i) { w[0] = delta[0] * glm::normalize(mesh_data[i + xsize] - mesh_data[i]); w[1] = (delta[0] + delta[1]) * glm::normalize(mesh_data[i + xsize] - mesh_data[i]); // upper core mdata[len_data + i] = mesh_data[i] + w[0]; // lower core mdata[2 * len_data - xsize + i] = mesh_data[i + xsize] - w[0]; // upper seam mdata[3 * len_data - 2 * xsize + i] = mesh_data[i] + w[1]; // lower seam mdata[4 * len_data - 3 * xsize + i] = mesh_data[i + xsize] - w[1]; } auto start = 5 * len_data - 4 * xsize; // y direction auto i = 0; for (auto x = 0; x != xsize - 1; ++x) { for (auto y = 0; y != ysize; ++y) { auto row = y * xsize; w[0] = delta[0] * glm::normalize(mesh_data[row + x + 1] - mesh_data[row + x]); w[1] = w[0] * (1 + delta[1]); // right core mdata[start + i] = mesh_data[row + x] + w[0]; // left core mdata[start + len_data - ysize + i] = mesh_data[row + x + 1] - w[0]; // right seam mdata[start + 2 * (len_data - ysize) + i] = mesh_data[row + x + 1] - w[1]; // left seam mdata[start + 3 * (len_data - ysize) + i] = mesh_data[row + x] + w[1]; ++i; } } if (!core_vbo_->setData(mdata)) return; Color core_color(0, 0.8f, 0, 1); Color seam_color(0, 0.8f, 0, 0); ColorVector seam_colors(5 * len_data - 4 * xsize); // core std::fill(begin(seam_colors), begin(seam_colors) + 3 * len_data - 2 * xsize, core_color); // seam std::fill(begin(seam_colors) + 3 * len_data - 2 * xsize, end(seam_colors), seam_color); if (!seam_color_vbo_->setData(seam_colors)) return; // indexes std::vector<glb::IndexMaker::IndexType> midata(8 * len_data); i = 0; start = len_data; // top core data start for (auto y = 0; y < ysize - 1; ++y) { auto row = y * xsize; for (auto x = 0; x < xsize; ++x) { midata[i++] = row + x; midata[i++] = start + row + x; } midata[i++] = std::numeric_limits<glb::IndexMaker::IndexType>::max(); } start = 2 * len_data - xsize; // bottom core data start for (auto y = 0; y < ysize - 1; ++y) { auto row = y * xsize; for (auto x = 0; x < xsize; ++x) { midata[i++] = start + row + x; midata[i++] = row + xsize + x; } midata[i++] = std::numeric_limits<glb::IndexMaker::IndexType>::max(); } midata.resize(i - 1); core_ibo_->setData(midata, true); // seam i = 0; midata.resize(8 * len_data); auto start0 = len_data; // upper core auto start1 = 3 * len_data - 2 * xsize; // upper seam for (auto y = 0; y < ysize - 1; ++y) { auto row = y * xsize; for (auto x = 0; x < xsize; ++x) { midata[i++] = start0 + row + x; midata[i++] = start1 + row + x; } midata[i++] = std::numeric_limits<glb::IndexMaker::IndexType>::max(); } start0 = 2 * len_data - xsize; // lower core start1 = 4 * len_data - 3 * xsize; // lower seam for (auto y = 0; y < ysize - 1; ++y) { auto row = y * xsize; for (auto x = 0; x < xsize; ++x) { midata[i++] = start1 + row + x; midata[i++] = start0 + row + x; } midata[i++] = std::numeric_limits<glb::IndexMaker::IndexType>::max(); } midata.resize(i - 1); seam_ibo_->setData(midata, true); } void MeshRenderer::draw(glb::Transformation const &matrices) { //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); Color color(0, 0.8f, 0, 1); core_shader_.use(); core_vbo_->bindAttribute(core_shader_.programId(), glb::shadercode::Var::v_coordinates); core_shader_.setUniformVec4(color, glb::shadercode::Var::v_in_color); //core_shader_.setProjectionMatrix(proj_matrix); setStdMatrices(core_shader_, matrices); core_ibo_->draw(); glb::State blend(GL_BLEND, GL_TRUE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); seam_shader_.use(); core_vbo_->bindAttribute(seam_shader_.programId(), glb::shadercode::Var::v_coordinates); seam_color_vbo_->bindAttribute(seam_shader_.programId(), glb::shadercode::Var::v_in_color); setStdMatrices(seam_shader_, matrices); seam_ibo_->draw(); } } // ns } // ns
30.065693
138
0.55159
traits
297225d3536ae04e40a9f905ae879ad0228ce916
7,376
cpp
C++
TypeSafeNumber/TypeSafeNumber.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
7
2015-01-18T13:30:09.000Z
2021-08-21T19:50:26.000Z
TypeSafeNumber/TypeSafeNumber.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
1
2016-03-13T21:26:37.000Z
2016-03-13T21:26:37.000Z
TypeSafeNumber/TypeSafeNumber.cpp
jbcoe/CppSandbox
574dc31bbd3640a8cf1b7642c4a449bee687cce5
[ "MIT" ]
1
2016-02-16T04:56:25.000Z
2016-02-16T04:56:25.000Z
#include <iostream> template <typename Object_t, typename Underlying_t> struct StrongTypedef { StrongTypedef() : t_() { } explicit StrongTypedef(Underlying_t t) : t_(std::move(t)) { } const auto& raw_data() const { return t_; } auto& raw_data() { return t_; } private: Underlying_t t_; }; #define STRICT_TYPES #ifdef STRICT_TYPES #define DEFINE_STRONG_TYPEDEF_OPERATOR(StrongTypedef_, operator_) \ StrongTypedef_ operator operator_(const StrongTypedef_& s1, \ const StrongTypedef_& s2) \ { \ return StrongTypedef_(s1.raw_data() operator_ s2.raw_data()); \ } #define DEFINE_STRONG_TYPEDEF_OPERATOR_RT(StrongTypedef_, RT, operator_) \ RT operator operator_(const StrongTypedef_& s1, const StrongTypedef_& s2) \ { \ return RT(s1.raw_data() operator_ s2.raw_data()); \ } #define DEFINE_NUMERIC_TYPE(Type, Underlying) \ struct Type : StrongTypedef<Type, Underlying> \ { \ using StrongTypedef<Type, Underlying>::StrongTypedef; \ } #else #define DEFINE_NUMERIC_TYPE(Type, Underlying) typedef Underlying Type; #define DEFINE_STRONG_TYPEDEF_OPERATOR(A,B) #define DEFINE_STRONG_TYPEDEF_OPERATOR_RT(A,B,C) #endif DEFINE_NUMERIC_TYPE(Volatility, double); DEFINE_STRONG_TYPEDEF_OPERATOR(Volatility, +); DEFINE_STRONG_TYPEDEF_OPERATOR_RT(Volatility, double, *); Volatility v1; Volatility v2; auto v3 = v1 + v2; DEFINE_NUMERIC_TYPE(Length, double); DEFINE_NUMERIC_TYPE(Area, double); DEFINE_STRONG_TYPEDEF_OPERATOR_RT(Length, Area, *) DEFINE_STRONG_TYPEDEF_OPERATOR(Length, +) auto X = Length(1) * Length(3); auto X2 = Length(1) + Length(3); auto X3 = X + X2; template <typename Object_t, typename Underlying_t> class Numerical { public: typedef Numerical<Object_t, Underlying_t> Numerical_t; explicit Numerical(const Underlying_t& value) : m_value(value) { } Numerical() : m_value() { } Numerical(const Numerical_t& n) : m_value(n.m_value) { } Numerical_t& operator=(const Numerical_t& n) { m_value = n.m_value; return *this; } Numerical(Numerical_t&& n) : m_value(n.m_value) { } Numerical_t& operator=(Numerical_t&& n) { m_value = n.m_value; return *this; } Numerical_t& operator++() { ++m_value; return *this; } Underlying_t underlying_value() const { return m_value; } private: Underlying_t m_value; }; template <typename Object_t, typename Underlying_t> bool operator!=(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() != n2.underlying_value(); } template <typename Object_t, typename Underlying_t> bool operator==(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() == n2.underlying_value(); } template <typename Object_t, typename Underlying_t> bool operator<(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() < n2.underlying_value(); } template <typename Object_t, typename Underlying_t> bool operator>(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() > n2.underlying_value(); } template <typename Object_t, typename Underlying_t> bool operator<=(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() <= n2.underlying_value(); } template <typename Object_t, typename Underlying_t> bool operator>=(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return n1.underlying_value() >= n2.underlying_value(); } template <typename Object_t, typename Underlying_t> Numerical<Object_t, Underlying_t> operator+(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return Numerical<Object_t, Underlying_t>(n1.underlying_value() + n2.underlying_value()); } template <typename Object_t, typename Underlying_t> Numerical<Object_t, Underlying_t> operator-(const Numerical<Object_t, Underlying_t>& n1, const Numerical<Object_t, Underlying_t>& n2) { return Numerical<Object_t, Underlying_t>(n1.underlying_value() - n2.underlying_value()); } template <typename OS_t, typename Object_t, typename Underlying_t> OS_t& operator<<(OS_t& os, const Numerical<Object_t, Underlying_t>& n) { return os << n.underlying_value(); } template <typename Object_t> using Int_t = Numerical<Object_t, int>; template <typename Object_t> using Double_t = Numerical<Object_t, double>; template <typename Object_t> using Index_t = Numerical<Object_t, size_t>; #ifndef DEFINE_NUMERIC_TYPE #define DEFINE_NUMERIC_TYPE(x, underlying_type) \ class t_##x \ { \ }; \ typedef Numerical<t_##x, underlying_type> x #endif DEFINE_NUMERIC_TYPE(Squirrel, int); DEFINE_NUMERIC_TYPE(Speed, double); DEFINE_NUMERIC_TYPE(Distance, double); DEFINE_NUMERIC_TYPE(Time, double); static Speed operator/(const Distance& d, const Time& t) { return Speed(d.underlying_value() / t.underlying_value()); } static Distance operator*(const Time& t, const Speed& s) { return Distance(t.underlying_value() * s.underlying_value()); } static Distance operator*(const Speed& s, const Time& t) { return Distance(s.underlying_value() * t.underlying_value()); } ////////////////////////////////////////////// int main(int argc, char* argv[]) { DEFINE_NUMERIC_TYPE(Apple, int); DEFINE_NUMERIC_TYPE(Orange, int); Apple myAppleCount(5); Apple yourAppleCount(8); auto ourAppleCount = myAppleCount + yourAppleCount; std::cout << "My Apples: " << myAppleCount << "\n"; std::cout << "Your Apples: " << yourAppleCount << "\n"; std::cout << "Our Apples: " << ourAppleCount << "\n"; std::cout << "\n"; Orange myOrangeCount(5); Orange yourOrangeCount(8); auto ourOrangeCount = myOrangeCount + yourOrangeCount; std::cout << "My Oranges: " << myOrangeCount << "\n"; std::cout << "Your Oranges: " << yourOrangeCount << "\n"; std::cout << "Our Oranges: " << ourOrangeCount << "\n"; std::cout << "\n"; for (Orange i(1), five_oranges(5); i <= five_oranges; ++i) { std::cout << "Orange counter: " << i << "\n"; } // One cannot add apples to oranges // auto ourFruitCount = ourAppleCount + ourOrangeCount; auto s = Distance(10.0) / Time(8.0); std::cout << "\n"; std::cout << "Speed " << s << " = Distance " << Distance(10.0) << " / Time " << Time(8.0) << "\n"; }
27.217712
80
0.625542
jbcoe
297715abf09ea3515cc07bbc46b92e81dbaea9a3
1,283
cc
C++
src/net/reporting/reporting_report.cc
lazymartin/naiveproxy
696e8714278e85e67e56a2eaea11f26c53116f0c
[ "BSD-3-Clause" ]
null
null
null
src/net/reporting/reporting_report.cc
lazymartin/naiveproxy
696e8714278e85e67e56a2eaea11f26c53116f0c
[ "BSD-3-Clause" ]
null
null
null
src/net/reporting/reporting_report.cc
lazymartin/naiveproxy
696e8714278e85e67e56a2eaea11f26c53116f0c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/reporting/reporting_report.h" #include <memory> #include <string> #include <utility> #include "base/time/time.h" #include "base/values.h" #include "url/gurl.h" namespace net { ReportingReport::ReportingReport( const NetworkIsolationKey& network_isolation_key, const GURL& url, const std::string& user_agent, const std::string& group, const std::string& type, std::unique_ptr<const base::Value> body, int depth, base::TimeTicks queued, int attempts) : network_isolation_key(network_isolation_key), url(url), user_agent(user_agent), group(group), type(type), body(std::move(body)), depth(depth), queued(queued), attempts(attempts) {} ReportingReport::~ReportingReport() = default; ReportingEndpointGroupKey ReportingReport::GetGroupKey() const { return ReportingEndpointGroupKey(network_isolation_key, url::Origin::Create(url), group); } bool ReportingReport::IsUploadPending() const { return status == Status::PENDING || status == Status::DOOMED; } } // namespace net
26.183673
73
0.68901
lazymartin
2979c0f092ca39085774a29e8479dba5543d7cf1
8,191
cpp
C++
Source/Graphics/Sprite/SpriteAnimationList.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
Source/Graphics/Sprite/SpriteAnimationList.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
Source/Graphics/Sprite/SpriteAnimationList.cpp
amitukind/WebGL-Game-Engine
c78973803938c1cfba703d9bb437ec46a4c48045
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2018-2021 Piotr Doan. All rights reserved. Software distributed under the permissive MIT License. */ #include "Graphics/Precompiled.hpp" #include "Graphics/Sprite/SpriteAnimationList.hpp" #include "Graphics/TextureAtlas.hpp" #include <Core/SystemStorage.hpp> #include <System/ResourceManager.hpp> #include <Script/ScriptState.hpp> using namespace Graphics; SpriteAnimationList::Frame::Frame() = default; SpriteAnimationList::Frame::Frame(TextureView&& textureView, float duration) : textureView(std::move(textureView)) , duration(duration) { } SpriteAnimationList::Frame SpriteAnimationList::Animation::GetFrameByTime(float animationTime) const { // Calculate current frame. for(const auto& frame : frames) { if(animationTime <= frame.duration) return frame; animationTime -= frame.duration; } // Return empty frame if animation time does not correspond to any. return SpriteAnimationList::Frame(); } SpriteAnimationList::SpriteAnimationList() = default; SpriteAnimationList::~SpriteAnimationList() = default; SpriteAnimationList::CreateResult SpriteAnimationList::Create() { LOG_PROFILE_SCOPE("Create sprite animation list"); // Create class instance. auto instance = std::unique_ptr<SpriteAnimationList>(new SpriteAnimationList()); return Common::Success(std::move(instance)); } SpriteAnimationList::CreateResult SpriteAnimationList::Create( System::FileHandle& file, const LoadFromFile& params) { LOG_PROFILE_SCOPE("Load sprite animation list from \"{}\" file...", file.GetPath().generic_string()); LOG("Loading sprite animation list from \"{}\" file...", file.GetPath().generic_string()); // Validate arguments. CHECK_ARGUMENT_OR_RETURN(params.engineSystems, Common::Failure(CreateErrors::InvalidArgument)); // Acquire engine systems. auto* resourceManager = params.engineSystems->Locate<System::ResourceManager>(); // Create base instance. auto createResult = Create(); if(!createResult) { LOG_ERROR("Could not create base instance!"); return createResult; } auto instance = createResult.Unwrap(); // Load resource script. Script::ScriptState::LoadFromFile resourceParams; resourceParams.engineSystems = params.engineSystems; auto resourceScript = Script::ScriptState::Create(file, resourceParams).UnwrapOr(nullptr); if(resourceScript == nullptr) { LOG_ERROR("Could not load sprite animation list resource file!"); return Common::Failure(CreateErrors::FailedResourceLoading); } // Get global table. lua_getglobal(*resourceScript, "SpriteAnimationList"); SCOPE_GUARD([&resourceScript] { lua_pop(*resourceScript, 1); }); if(!lua_istable(*resourceScript, -1)) { LOG_ERROR("Table \"SpriteAnimationList\" is missing!"); return Common::Failure(CreateErrors::InvalidResourceContents); } // Load texture atlas. std::shared_ptr<TextureAtlas> textureAtlas; { lua_getfield(*resourceScript, -1, "TextureAtlas"); SCOPE_GUARD([&resourceScript] { lua_pop(*resourceScript, 1); }); if(!lua_isstring(*resourceScript, -1)) { LOG_ERROR("String \"SpriteAnimationList.TextureAtlas\" is missing!"); return Common::Failure(CreateErrors::InvalidResourceContents); } std::filesystem::path textureAtlasPath = lua_tostring(*resourceScript, -1); TextureAtlas::LoadFromFile textureAtlasParams; textureAtlasParams.engineSystems = params.engineSystems; textureAtlas = resourceManager->AcquireRelative<TextureAtlas>( textureAtlasPath, file.GetPath(), textureAtlasParams).UnwrapOr(nullptr); if(textureAtlas == nullptr) { LOG_ERROR("Could not load referenced texture atlas!"); return Common::Failure(CreateErrors::FailedResourceLoading); } } // Read animation entries. lua_getfield(*resourceScript, -1, "Animations"); SCOPE_GUARD([&resourceScript] { lua_pop(*resourceScript, 1); }); if(!lua_istable(*resourceScript, -1)) { LOG_ERROR("Table \"SpriteAnimationList.Animations\" is missing!"); return Common::Failure(CreateErrors::InvalidResourceContents); } for(lua_pushnil(*resourceScript); lua_next(*resourceScript, -2); lua_pop(*resourceScript, 1)) { // Check if key is a string. if(!lua_isstring(*resourceScript, -2)) { LOG_WARNING("Key \"SpriteAnimationList.Animations\" is not a string!"); LOG_WARNING("Skipping one ill formated sprite animation!"); continue; } std::string animationName = lua_tostring(*resourceScript, -2); // Read animation frames. Animation animation; for(lua_pushnil(*resourceScript); lua_next(*resourceScript, -2); lua_pop(*resourceScript, 1)) { // Make sure that we have a table. if(!lua_istable(*resourceScript, -1)) { LOG_WARNING("Value in \"SpriteAnimationList.Animations[\"{}\"]\" " "is not a table!", animationName); LOG_WARNING("Skipping one ill formated sprite animation frame!"); continue; } // Get sequence frame. TextureView textureView; { lua_pushinteger(*resourceScript, 1); lua_gettable(*resourceScript, -2); SCOPE_GUARD([&resourceScript] { lua_pop(*resourceScript, 1); }); if(!lua_isstring(*resourceScript, -1)) { LOG_WARNING("Field in \"SpriteAnimationList.Animations[{}][0]\" " "is not a string!", animationName); LOG_WARNING("Skipping one ill formated sprite animation frame!"); continue; } textureView = textureAtlas->GetRegion(lua_tostring(*resourceScript, -1)); } // Get frame duration. float frameDuration = 0.0f; { lua_pushinteger(*resourceScript, 2); lua_gettable(*resourceScript, -2); SCOPE_GUARD([&resourceScript] { lua_pop(*resourceScript, 1); }); if(!lua_isnumber(*resourceScript, -1)) { LOG_WARNING("Field in \"SpriteAnimationList.Animations[\"{}\"][1]\" " "is not a number!", animationName); LOG_WARNING("Skipping one ill formated sprite animation frame!"); continue; } frameDuration = (float)lua_tonumber(*resourceScript, -1); } // Add frame to animation. animation.frames.emplace_back(std::move(textureView), frameDuration); animation.duration += frameDuration; } // Add animation to list. instance->m_animationList.emplace_back(std::move(animation)); instance->m_animationMap.emplace(animationName, Common::NumericalCast<uint32_t>(instance->m_animationList.size() - 1)); } return Common::Success(std::move(instance)); } SpriteAnimationList::AnimationIndexResult SpriteAnimationList::GetAnimationIndex(std::string animationName) const { auto it = m_animationMap.find(animationName); if(it == m_animationMap.end()) { return Common::Failure(); } return Common::Success(it->second); } const SpriteAnimationList::Animation* SpriteAnimationList::GetAnimationByIndex(std::size_t animationIndex) const { // Make sure that index is valid. bool isIndexValid = animationIndex >= 0 && animationIndex < m_animationList.size(); ASSERT(isIndexValid, "Invalid sprite animation index!"); // Return animation pointed by index. return isIndexValid ? &m_animationList[animationIndex] : nullptr; }
33.028226
100
0.62764
amitukind
297a948a50b208dbfa75c7f5ff4dc89c84ea355e
72,717
cpp
C++
Source/Plugins/bsfSL/BsSLFXCompiler.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
1,745
2018-03-16T02:10:28.000Z
2022-03-26T17:34:21.000Z
Source/Plugins/bsfSL/BsSLFXCompiler.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
395
2018-03-16T10:18:20.000Z
2021-08-04T16:52:08.000Z
Source/Plugins/bsfSL/BsSLFXCompiler.cpp
bsf2dev/bsf
b318cd4eb1b0299773d625e6c870b8d503cf539e
[ "MIT" ]
267
2018-03-17T19:32:54.000Z
2022-02-17T16:55:50.000Z
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "BsSLFXCompiler.h" #include "RenderAPI/BsGpuProgram.h" #include <regex> #include "Material/BsShader.h" #include "Material/BsTechnique.h" #include "Material/BsPass.h" #include "RenderAPI/BsSamplerState.h" #include "RenderAPI/BsRenderAPI.h" #include "Debug/BsDebug.h" #include "Material/BsShaderManager.h" #include "Material/BsShaderInclude.h" #include "Math/BsMatrix4.h" #include "Resources/BsBuiltinResources.h" #include "Material/BsShaderVariation.h" #include "Renderer/BsRenderer.h" #include "Renderer/BsRendererManager.h" #include "FileSystem/BsFileSystem.h" #include "FileSystem/BsDataStream.h" #define XSC_ENABLE_LANGUAGE_EXT 1 #include "Xsc/Xsc.h" extern "C" { #include "BsMMAlloc.h" #define YY_NO_UNISTD_H 1 #include "BsParserFX.h" #include "BsLexerFX.h" } using namespace std; namespace bs { // Print out the FX AST, only for debug purposes void SLFXDebugPrint(ASTFXNode* node, String indent) { BS_LOG(Info, BSLCompiler, indent + "NODE {0}", node->type); for (int i = 0; i < node->options->count; i++) { OptionDataType odt = OPTION_LOOKUP[(int)node->options->entries[i].type].dataType; if (odt == ODT_Complex) { BS_LOG(Info, BSLCompiler, "{0}{1}. {2}", indent, i, node->options->entries[i].type); SLFXDebugPrint(node->options->entries[i].value.nodePtr, indent + "\t"); continue; } String value; switch (odt) { case ODT_Bool: value = toString(node->options->entries[i].value.intValue != 0); break; case ODT_Int: value = toString(node->options->entries[i].value.intValue); break; case ODT_Float: value = toString(node->options->entries[i].value.floatValue); break; case ODT_String: value = node->options->entries[i].value.strValue; break; case ODT_Matrix: { Matrix4 mat4 = *(Matrix4*)(node->options->entries[i].value.matrixValue); value = toString(mat4); } break; default: break; } BS_LOG(Info, BSLCompiler, "{0}{1}. {2} = {3}", indent, i, node->options->entries[i].type, value); } } class XscLog : public Xsc::Log { public: void SubmitReport(const Xsc::Report& report) override { switch (report.Type()) { case Xsc::ReportTypes::Info: mInfos.push_back({ FullIndent(), report }); break; case Xsc::ReportTypes::Warning: mWarnings.push_back({ FullIndent(), report }); break; case Xsc::ReportTypes::Error: mErrors.push_back({ FullIndent(), report }); break; } } void getMessages(StringStream& output) { printAndClearReports(output, mInfos); printAndClearReports(output, mWarnings, (mWarnings.size() == 1 ? "WARNING" : "WARNINGS")); printAndClearReports(output, mErrors, (mErrors.size() == 1 ? "ERROR" : "ERRORS")); } private: struct IndentReport { std::string indent; Xsc::Report report; }; static void printMultiLineString(StringStream& output, const std::string& str, const std::string& indent) { // Determine at which position the actual text begins (excluding the "error (X:Y) : " or the like) auto textStartPos = str.find(" : "); if (textStartPos != std::string::npos) textStartPos += 3; else textStartPos = 0; std::string newLineIndent(textStartPos, ' '); size_t start = 0; bool useNewLineIndent = false; while (start < str.size()) { output << indent; if (useNewLineIndent) output << newLineIndent; // Print next line auto end = str.find('\n', start); if (end != std::string::npos) { output << str.substr(start, end - start); start = end + 1; } else { output << str.substr(start); start = end; } output << std::endl; useNewLineIndent = true; } } void printReport(StringStream& output, const IndentReport& r) { // Print optional context description if (!r.report.Context().empty()) printMultiLineString(output, r.report.Context(), r.indent); // Print report message const auto& msg = r.report.Message(); printMultiLineString(output, msg, r.indent); // Print optional line and line-marker if (r.report.HasLine()) { const auto& line = r.report.Line(); const auto& marker = r.report.Marker(); // Print line output << r.indent << line << std::endl; // Print line marker output << r.indent << marker << std::endl; } // Print optional hints for (const auto& hint : r.report.GetHints()) output << r.indent << hint << std::endl; } void printAndClearReports(StringStream& output, Vector<IndentReport>& reports, const String& headline = "") { if (!reports.empty()) { if (!headline.empty()) { String s = toString((UINT32)reports.size()) + " " + headline; output << s << std::endl; output << String(s.size(), '-') << std::endl; } for (const auto& r : reports) printReport(output, r); reports.clear(); } } Vector<IndentReport> mInfos; Vector<IndentReport> mWarnings; Vector<IndentReport> mErrors; }; GpuParamObjectType ReflTypeToTextureType(Xsc::Reflection::BufferType type) { switch(type) { case Xsc::Reflection::BufferType::RWTexture1D: return GPOT_RWTEXTURE1D; case Xsc::Reflection::BufferType::RWTexture1DArray: return GPOT_RWTEXTURE1DARRAY; case Xsc::Reflection::BufferType::RWTexture2D: return GPOT_RWTEXTURE2D; case Xsc::Reflection::BufferType::RWTexture2DArray: return GPOT_RWTEXTURE2DARRAY; case Xsc::Reflection::BufferType::RWTexture3D: return GPOT_RWTEXTURE3D; case Xsc::Reflection::BufferType::Texture1D: return GPOT_TEXTURE1D; case Xsc::Reflection::BufferType::Texture1DArray: return GPOT_TEXTURE1DARRAY; case Xsc::Reflection::BufferType::Texture2D: return GPOT_TEXTURE2D; case Xsc::Reflection::BufferType::Texture2DArray: return GPOT_TEXTURE2DARRAY; case Xsc::Reflection::BufferType::Texture3D: return GPOT_TEXTURE3D; case Xsc::Reflection::BufferType::TextureCube: return GPOT_TEXTURECUBE; case Xsc::Reflection::BufferType::TextureCubeArray: return GPOT_TEXTURECUBEARRAY; case Xsc::Reflection::BufferType::Texture2DMS: return GPOT_TEXTURE2DMS; case Xsc::Reflection::BufferType::Texture2DMSArray: return GPOT_TEXTURE2DMSARRAY; default: return GPOT_UNKNOWN; } } GpuParamObjectType ReflTypeToBufferType(Xsc::Reflection::BufferType type) { switch(type) { case Xsc::Reflection::BufferType::Buffer: return GPOT_RWTYPED_BUFFER; case Xsc::Reflection::BufferType::StructuredBuffer: return GPOT_STRUCTURED_BUFFER; case Xsc::Reflection::BufferType::ByteAddressBuffer: return GPOT_BYTE_BUFFER; case Xsc::Reflection::BufferType::RWBuffer: return GPOT_RWTYPED_BUFFER; case Xsc::Reflection::BufferType::RWStructuredBuffer: return GPOT_RWSTRUCTURED_BUFFER; case Xsc::Reflection::BufferType::RWByteAddressBuffer: return GPOT_RWBYTE_BUFFER; case Xsc::Reflection::BufferType::AppendStructuredBuffer: return GPOT_RWAPPEND_BUFFER; case Xsc::Reflection::BufferType::ConsumeStructuredBuffer: return GPOT_RWCONSUME_BUFFER; default: return GPOT_UNKNOWN; } } GpuParamDataType ReflTypeToDataType(Xsc::Reflection::DataType type) { switch (type) { case Xsc::Reflection::DataType::Bool: return GPDT_BOOL; case Xsc::Reflection::DataType::Float: return GPDT_FLOAT1; case Xsc::Reflection::DataType::Float2: return GPDT_FLOAT2; case Xsc::Reflection::DataType::Float3: return GPDT_FLOAT3; case Xsc::Reflection::DataType::Float4: return GPDT_FLOAT4; case Xsc::Reflection::DataType::UInt: case Xsc::Reflection::DataType::Int: return GPDT_INT1; case Xsc::Reflection::DataType::UInt2: case Xsc::Reflection::DataType::Int2: return GPDT_INT2; case Xsc::Reflection::DataType::UInt3: case Xsc::Reflection::DataType::Int3: return GPDT_INT3; case Xsc::Reflection::DataType::UInt4: case Xsc::Reflection::DataType::Int4: return GPDT_INT4; case Xsc::Reflection::DataType::Float2x2: return GPDT_MATRIX_2X2; case Xsc::Reflection::DataType::Float2x3: return GPDT_MATRIX_2X3; case Xsc::Reflection::DataType::Float2x4: return GPDT_MATRIX_2X4; case Xsc::Reflection::DataType::Float3x2: return GPDT_MATRIX_3X4; case Xsc::Reflection::DataType::Float3x3: return GPDT_MATRIX_3X3; case Xsc::Reflection::DataType::Float3x4: return GPDT_MATRIX_3X4; case Xsc::Reflection::DataType::Float4x2: return GPDT_MATRIX_4X2; case Xsc::Reflection::DataType::Float4x3: return GPDT_MATRIX_4X3; case Xsc::Reflection::DataType::Float4x4: return GPDT_MATRIX_4X4; default: return GPDT_UNKNOWN; } } HTexture getBuiltinTexture(UINT32 idx) { if (idx == 1) return BuiltinResources::getTexture(BuiltinTexture::White); else if (idx == 2) return BuiltinResources::getTexture(BuiltinTexture::Black); else if (idx == 3) return BuiltinResources::getTexture(BuiltinTexture::Normal); return HTexture(); } UINT32 getStructSize(INT32 structIdx, const std::vector<Xsc::Reflection::Struct>& structLookup) { if(structIdx < 0 || structIdx >= (INT32)structLookup.size()) return 0; UINT32 size = 0; const Xsc::Reflection::Struct& structInfo = structLookup[structIdx]; for(auto& entry : structInfo.members) { if(entry.type == Xsc::Reflection::VariableType::Variable) { // Note: We're ignoring any padding. Since we can't guarantee the padding will be same for structs across // different render backends it's expected for the user to set up structs in such a way so padding is not // needed (i.e. add padding variables manually). GpuParamDataType type = ReflTypeToDataType((Xsc::Reflection::DataType)entry.baseType); const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[(int)type]; size += typeInfo.numColumns * typeInfo.numRows * typeInfo.baseTypeSize * entry.arraySize; } else if(entry.type == Xsc::Reflection::VariableType::Struct) size += getStructSize(entry.baseType, structLookup); } return size; } TextureAddressingMode parseTexAddrMode(Xsc::Reflection::TextureAddressMode addrMode) { switch (addrMode) { case Xsc::Reflection::TextureAddressMode::Border: return TAM_BORDER; case Xsc::Reflection::TextureAddressMode::Clamp: return TAM_CLAMP; case Xsc::Reflection::TextureAddressMode::Mirror: case Xsc::Reflection::TextureAddressMode::MirrorOnce: return TAM_MIRROR; case Xsc::Reflection::TextureAddressMode::Wrap: default: return TAM_WRAP; } } CompareFunction parseCompFunction(Xsc::Reflection::ComparisonFunc compFunc) { switch(compFunc) { case Xsc::Reflection::ComparisonFunc::Always: default: return CMPF_ALWAYS_PASS; case Xsc::Reflection::ComparisonFunc::Never: return CMPF_ALWAYS_FAIL; case Xsc::Reflection::ComparisonFunc::Equal: return CMPF_EQUAL; case Xsc::Reflection::ComparisonFunc::Greater: return CMPF_GREATER; case Xsc::Reflection::ComparisonFunc::GreaterEqual: return CMPF_GREATER_EQUAL; case Xsc::Reflection::ComparisonFunc::Less: return CMPF_LESS; case Xsc::Reflection::ComparisonFunc::LessEqual: return CMPF_LESS_EQUAL; case Xsc::Reflection::ComparisonFunc::NotEqual: return CMPF_NOT_EQUAL; } } SPtr<SamplerState> parseSamplerState(const Xsc::Reflection::SamplerState& sampState) { SAMPLER_STATE_DESC desc; desc.addressMode.u = parseTexAddrMode(sampState.addressU); desc.addressMode.v = parseTexAddrMode(sampState.addressV); desc.addressMode.w = parseTexAddrMode(sampState.addressW); desc.borderColor[0] = sampState.borderColor[0]; desc.borderColor[1] = sampState.borderColor[1]; desc.borderColor[2] = sampState.borderColor[2]; desc.borderColor[3] = sampState.borderColor[3]; desc.comparisonFunc = parseCompFunction(sampState.comparisonFunc); desc.maxAniso = sampState.maxAnisotropy; desc.mipMax = sampState.maxLOD; desc.mipMin = sampState.minLOD; desc.mipmapBias = sampState.mipLODBias; switch (sampState.filter) { case Xsc::Reflection::Filter::MinMagMipPoint: case Xsc::Reflection::Filter::ComparisonMinMagMipPoint: desc.minFilter = FO_POINT; desc.magFilter = FO_POINT; desc.mipFilter = FO_POINT; break; case Xsc::Reflection::Filter::MinMagPointMipLinear: case Xsc::Reflection::Filter::ComparisonMinMagPointMipLinear: desc.minFilter = FO_POINT; desc.magFilter = FO_POINT; desc.mipFilter = FO_LINEAR; break; case Xsc::Reflection::Filter::MinPointMagLinearMipPoint: case Xsc::Reflection::Filter::ComparisonMinPointMagLinearMipPoint: desc.minFilter = FO_POINT; desc.magFilter = FO_LINEAR; desc.mipFilter = FO_POINT; break; case Xsc::Reflection::Filter::MinPointMagMipLinear: case Xsc::Reflection::Filter::ComparisonMinPointMagMipLinear: desc.minFilter = FO_POINT; desc.magFilter = FO_LINEAR; desc.mipFilter = FO_LINEAR; break; case Xsc::Reflection::Filter::MinLinearMagMipPoint: case Xsc::Reflection::Filter::ComparisonMinLinearMagMipPoint: desc.minFilter = FO_LINEAR; desc.magFilter = FO_POINT; desc.mipFilter = FO_POINT; break; case Xsc::Reflection::Filter::MinLinearMagPointMipLinear: case Xsc::Reflection::Filter::ComparisonMinLinearMagPointMipLinear: desc.minFilter = FO_LINEAR; desc.magFilter = FO_POINT; desc.mipFilter = FO_LINEAR; break; case Xsc::Reflection::Filter::MinMagLinearMipPoint: case Xsc::Reflection::Filter::ComparisonMinMagLinearMipPoint: desc.minFilter = FO_LINEAR; desc.magFilter = FO_LINEAR; desc.mipFilter = FO_POINT; break; case Xsc::Reflection::Filter::MinMagMipLinear: case Xsc::Reflection::Filter::ComparisonMinMagMipLinear: desc.minFilter = FO_LINEAR; desc.magFilter = FO_LINEAR; desc.mipFilter = FO_LINEAR; break; case Xsc::Reflection::Filter::Anisotropic: case Xsc::Reflection::Filter::ComparisonAnisotropic: desc.minFilter = FO_ANISOTROPIC; desc.magFilter = FO_ANISOTROPIC; desc.mipFilter = FO_ANISOTROPIC; break; default: break; } return SamplerState::create(desc); } void parseParameters(const Xsc::Reflection::ReflectionData& reflData, SHADER_DESC& desc) { for(auto& entry : reflData.uniforms) { if ((entry.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0) continue; String ident = entry.ident.c_str(); auto parseCommonAttributes = [&entry, &ident, &desc]() { if (!entry.readableName.empty()) { SHADER_PARAM_ATTRIBUTE attribute; attribute.value.assign(entry.readableName.data(), entry.readableName.size()); attribute.nextParamIdx = (UINT32)-1; attribute.type = ShaderParamAttributeType::Name; desc.setParameterAttribute(ident, attribute); } if ((entry.flags & Xsc::Reflection::Uniform::Flags::HideInInspector) != 0) { SHADER_PARAM_ATTRIBUTE attribute; attribute.nextParamIdx = (UINT32)-1; attribute.type = ShaderParamAttributeType::HideInInspector; desc.setParameterAttribute(ident, attribute); } if ((entry.flags & Xsc::Reflection::Uniform::Flags::HDR) != 0) { SHADER_PARAM_ATTRIBUTE attribute; attribute.nextParamIdx = (UINT32)-1; attribute.type = ShaderParamAttributeType::HDR; desc.setParameterAttribute(ident, attribute); } }; switch(entry.type) { case Xsc::Reflection::VariableType::UniformBuffer: desc.setParamBlockAttribs(entry.ident.c_str(), false, GBU_STATIC); break; case Xsc::Reflection::VariableType::Buffer: { GpuParamObjectType objType = ReflTypeToTextureType((Xsc::Reflection::BufferType)entry.baseType); if(objType != GPOT_UNKNOWN) { // Ignore parameters that were already registered in some previous variation. Note that this implies // you cannot have same names for different parameters in different variations. if (desc.textureParams.find(ident) != desc.textureParams.end()) continue; if (entry.defaultValue == -1) desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, objType)); else { const Xsc::Reflection::DefaultValue& defVal = reflData.defaultValues[entry.defaultValue]; desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, objType), getBuiltinTexture(defVal.integer)); } parseCommonAttributes(); } else { // Ignore parameters that were already registered in some previous variation. Note that this implies // you cannot have same names for different parameters in different variations. if (desc.bufferParams.find(ident) != desc.bufferParams.end()) continue; objType = ReflTypeToBufferType((Xsc::Reflection::BufferType)entry.baseType); desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, objType)); parseCommonAttributes(); } } break; case Xsc::Reflection::VariableType::Sampler: { auto findIter = reflData.samplerStates.find(entry.ident); if (findIter != reflData.samplerStates.end()) { // Ignore parameters that were already registered in some previous variation. Note that this implies // you cannot have same names for different parameters in different variations. if(desc.samplerParams.find(ident) != desc.samplerParams.end()) continue; String alias = findIter->second.alias.c_str(); if(findIter->second.isNonDefault) { SPtr<SamplerState> defaultVal = parseSamplerState(findIter->second); desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, GPOT_SAMPLER2D), defaultVal); if (!alias.empty()) desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, alias, GPOT_SAMPLER2D), defaultVal); } else { desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, GPOT_SAMPLER2D)); if (!alias.empty()) desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, alias, GPOT_SAMPLER2D)); } } else { desc.addParameter(SHADER_OBJECT_PARAM_DESC(ident, ident, GPOT_SAMPLER2D)); } break; } case Xsc::Reflection::VariableType::Variable: { bool isBlockInternal = false; if(entry.uniformBlock != -1) { std::string blockName = reflData.constantBuffers[entry.uniformBlock].ident; for (auto& uniform : reflData.uniforms) { if (uniform.type == Xsc::Reflection::VariableType::UniformBuffer && uniform.ident == blockName) { isBlockInternal = (uniform.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0; break; } } } if (!isBlockInternal) { GpuParamDataType type = ReflTypeToDataType((Xsc::Reflection::DataType)entry.baseType); if ((entry.flags & Xsc::Reflection::Uniform::Flags::Color) != 0 && (type == GPDT_FLOAT3 || type == GPDT_FLOAT4)) { type = GPDT_COLOR; } UINT32 arraySize = entry.arraySize; if (entry.defaultValue == -1) desc.addParameter(SHADER_DATA_PARAM_DESC(ident, ident, type, StringID::NONE, arraySize)); else { const Xsc::Reflection::DefaultValue& defVal = reflData.defaultValues[entry.defaultValue]; desc.addParameter(SHADER_DATA_PARAM_DESC(ident, ident, type, StringID::NONE, arraySize, 0), (UINT8*)defVal.matrix); } if(!entry.spriteUVRef.empty() && (type == GPDT_FLOAT4)) { SHADER_PARAM_ATTRIBUTE attribute; attribute.value.assign(entry.spriteUVRef.data(), entry.spriteUVRef.size()); attribute.nextParamIdx = (UINT32)-1; attribute.type = ShaderParamAttributeType::SpriteUV; desc.setParameterAttribute(ident, attribute); } parseCommonAttributes(); } } break; case Xsc::Reflection::VariableType::Struct: { INT32 structIdx = entry.baseType; UINT32 structSize = getStructSize(structIdx, reflData.structs); desc.addParameter(SHADER_DATA_PARAM_DESC(ident, ident, GPDT_STRUCT, StringID::NONE, entry.arraySize, structSize)); } break; default: ; } } } /** Types of supported code output when cross compiling HLSL to GLSL. */ enum class CrossCompileOutput { GLSL45, GLSL41, VKSL45, MVKSL }; String crossCompile(const String& hlsl, GpuProgramType type, CrossCompileOutput outputType, bool optionalEntry, UINT32& startBindingSlot, SHADER_DESC* shaderDesc = nullptr, Vector<GpuProgramType>* detectedTypes = nullptr) { SPtr<StringStream> input = bs_shared_ptr_new<StringStream>(); bool isVKSL = outputType == CrossCompileOutput::VKSL45 || outputType == CrossCompileOutput::MVKSL; switch(outputType) { case CrossCompileOutput::GLSL41: case CrossCompileOutput::GLSL45: *input << "#define OPENGL 1" << std::endl; break; case CrossCompileOutput::VKSL45: *input << "#define VULKAN 1" << std::endl; break; case CrossCompileOutput::MVKSL: *input << "#define METAL 1" << std::endl; break; } *input << hlsl; Xsc::ShaderInput inputDesc; inputDesc.shaderVersion = Xsc::InputShaderVersion::HLSL5; inputDesc.sourceCode = input; inputDesc.extensions = Xsc::Extensions::LayoutAttribute; switch (type) { case GPT_VERTEX_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::VertexShader; inputDesc.entryPoint = "vsmain"; break; case GPT_GEOMETRY_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::GeometryShader; inputDesc.entryPoint = "gsmain"; break; case GPT_HULL_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationControlShader; inputDesc.entryPoint = "hsmain"; break; case GPT_DOMAIN_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationEvaluationShader; inputDesc.entryPoint = "dsmain"; break; case GPT_FRAGMENT_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::FragmentShader; inputDesc.entryPoint = "fsmain"; break; case GPT_COMPUTE_PROGRAM: inputDesc.shaderTarget = Xsc::ShaderTarget::ComputeShader; inputDesc.entryPoint = "csmain"; break; default: break; } StringStream output; Xsc::ShaderOutput outputDesc; outputDesc.sourceCode = &output; outputDesc.options.autoBinding = isVKSL; outputDesc.options.autoBindingStartSlot = startBindingSlot; outputDesc.options.fragmentLocations = true; outputDesc.options.separateShaders = true; outputDesc.options.separateSamplers = isVKSL; outputDesc.options.allowExtensions = true; outputDesc.nameMangling.inputPrefix = "bs_"; outputDesc.nameMangling.outputPrefix = "bs_"; outputDesc.nameMangling.useAlwaysSemantics = true; outputDesc.nameMangling.renameBufferFields = true; switch(outputType) { case CrossCompileOutput::GLSL45: outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL450; break; case CrossCompileOutput::GLSL41: outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL410; break; case CrossCompileOutput::VKSL45: outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450; break; case CrossCompileOutput::MVKSL: outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450; break; } XscLog log; Xsc::Reflection::ReflectionData reflectionData; bool compileSuccess = Xsc::CompileShader(inputDesc, outputDesc, &log, &reflectionData); if (!compileSuccess) { // If enabled, don't fail if entry point isn't found bool done = true; if(optionalEntry) { bool entryFound = false; for (auto& entry : reflectionData.functions) { if(entry.ident == inputDesc.entryPoint) { entryFound = true; break; } } if (!entryFound) done = false; } if (done) { StringStream logOutput; log.getMessages(logOutput); BS_LOG(Error, BSLCompiler, "Shader cross compilation failed. Log: \n\n{0}", logOutput.str()); return ""; } } for (auto& entry : reflectionData.constantBuffers) startBindingSlot = std::max(startBindingSlot, entry.location + 1u); for (auto& entry : reflectionData.textures) startBindingSlot = std::max(startBindingSlot, entry.location + 1u); for (auto& entry : reflectionData.storageBuffers) startBindingSlot = std::max(startBindingSlot, entry.location + 1u); if(detectedTypes != nullptr) { for(auto& entry : reflectionData.functions) { if (entry.ident == "vsmain") detectedTypes->push_back(GPT_VERTEX_PROGRAM); else if (entry.ident == "fsmain") detectedTypes->push_back(GPT_FRAGMENT_PROGRAM); else if (entry.ident == "gsmain") detectedTypes->push_back(GPT_GEOMETRY_PROGRAM); else if (entry.ident == "dsmain") detectedTypes->push_back(GPT_DOMAIN_PROGRAM); else if (entry.ident == "hsmain") detectedTypes->push_back(GPT_HULL_PROGRAM); else if (entry.ident == "csmain") detectedTypes->push_back(GPT_COMPUTE_PROGRAM); } // If no entry points found, and error occurred, report error if(!compileSuccess && detectedTypes->empty()) { StringStream logOutput; log.getMessages(logOutput); BS_LOG(Error, BSLCompiler, "Shader cross compilation failed. Log: \n\n{0}", logOutput.str()); return ""; } } if (shaderDesc != nullptr) parseParameters(reflectionData, *shaderDesc); return output.str(); } String crossCompile(const String& hlsl, GpuProgramType type, CrossCompileOutput outputType, UINT32& startBindingSlot) { return crossCompile(hlsl, type, outputType, false, startBindingSlot); } void reflectHLSL(const String& hlsl, SHADER_DESC& shaderDesc, Vector<GpuProgramType>& entryPoints) { UINT32 dummy = 0; crossCompile(hlsl, GPT_VERTEX_PROGRAM, CrossCompileOutput::GLSL45, true, dummy, &shaderDesc, &entryPoints); } BSLFXCompileResult BSLFXCompiler::compile(const String& name, const String& source, const UnorderedMap<String, String>& defines, ShadingLanguageFlags languages) { // Parse global shader options & shader meta-data SHADER_DESC shaderDesc; Vector<String> includes; BSLFXCompileResult output = compileShader(source, defines, languages, shaderDesc, includes); // Generate a shader from the parsed information output.shader = Shader::_createPtr(name, shaderDesc); output.shader->setIncludeFiles(includes); return output; } BSLFXCompileResult BSLFXCompiler::parseFX(ParseState* parseState, const char* source, const UnorderedMap<String, String>& defines) { for(auto& define : defines) { if (define.first.size() == 0) continue; addDefine(parseState, define.first.c_str()); if(define.second.size() > 0) addDefineExpr(parseState, define.second.c_str()); } yyscan_t scanner; YY_BUFFER_STATE state; BSLFXCompileResult output; if (yylex_init_extra(parseState, &scanner)) { output.errorMessage = "Internal error: Lexer failed to initialize."; return output; } // If debug output from lexer is needed uncomment this and add %debug option to lexer file //yyset_debug(true, scanner); // If debug output from parser is needed uncomment this and add %debug option to parser file //yydebug = true; state = yy_scan_string(source, scanner); bool parsingFailed = yyparse(parseState, scanner) > 0; if (parseState->hasError > 0) { output.errorMessage = parseState->errorMessage; output.errorLine = parseState->errorLine; output.errorColumn = parseState->errorColumn; if (parseState->errorFile != nullptr) output.errorFile = parseState->errorFile; goto cleanup; } else if(parsingFailed) { output.errorMessage = "Internal error: Parsing failed."; goto cleanup; } cleanup: yy_delete_buffer(state, scanner); yylex_destroy(scanner); return output; } BSLFXCompiler::ShaderMetaData BSLFXCompiler::parseShaderMetaData(ASTFXNode* shader) { ShaderMetaData metaData; metaData.language = "hlsl"; metaData.isMixin = shader->type == NT_Mixin; for (int i = 0; i < shader->options->count; i++) { NodeOption* option = &shader->options->entries[i]; switch (option->type) { case OT_Tags: { ASTFXNode* tagsNode = option->value.nodePtr; for (int j = 0; j < tagsNode->options->count; j++) { NodeOption* tagOption = &tagsNode->options->entries[j]; if (tagOption->type == OT_TagValue) metaData.tags.push_back(removeQuotes(tagOption->value.strValue)); } } break; case OT_Variations: { ASTFXNode* variationsNode = option->value.nodePtr; for (int j = 0; j < variationsNode->options->count; j++) { NodeOption* variationOption = &variationsNode->options->entries[j]; if(variationOption->type == OT_Variation) parseVariations(metaData, variationOption->value.nodePtr); } } break; case OT_Identifier: metaData.name = option->value.strValue; break; case OT_Mixin: metaData.includes.push_back(option->value.strValue); break; default: break; } } return metaData; } BSLFXCompileResult BSLFXCompiler::parseMetaDataAndOptions(ASTFXNode* rootNode, Vector<std::pair<ASTFXNode*, ShaderMetaData>>& shaderMetaData, Vector<SubShaderData>& subShaderData, SHADER_DESC& shaderDesc) { BSLFXCompileResult output; // Only enable for debug purposes //SLFXDebugPrint(parseState->rootNode, ""); if (rootNode == nullptr || rootNode->type != NT_Root) { output.errorMessage = "Root is null or not a shader."; return output; } // Parse global shader options & shader meta-data //// Go in reverse because options are added in reverse order during parsing for (int i = rootNode->options->count - 1; i >= 0; i--) { NodeOption* option = &rootNode->options->entries[i]; switch (option->type) { case OT_Options: parseOptions(option->value.nodePtr, shaderDesc); break; case OT_Shader: { // We initially parse only meta-data, so we can handle out-of-order mixin/shader definitions ShaderMetaData metaData = parseShaderMetaData(option->value.nodePtr); shaderMetaData.push_back(std::make_pair(option->value.nodePtr, metaData)); break; } case OT_SubShader: { SubShaderData data = parseSubShader(option->value.nodePtr); subShaderData.push_back(data); break; } default: break; } } return output; } void BSLFXCompiler::parseVariations(ShaderMetaData& metaData, ASTFXNode* variations) { assert(variations->type == NT_Variation); VariationData variationData; for (int i = 0; i < variations->options->count; i++) { NodeOption* option = &variations->options->entries[i]; switch (option->type) { case OT_Identifier: variationData.identifier = option->value.strValue; break; case OT_VariationOption: variationData.values.push_back(parseVariationOption(option->value.nodePtr)); break; case OT_Attributes: { AttributeData attribs = parseAttributes(option->value.nodePtr); for (auto& entry : attribs.attributes) { if (entry.first == OT_AttrName) variationData.name = entry.second; else if(entry.first == OT_AttrShow) variationData.internal = false; } } default: break; } } if (!variationData.identifier.empty()) metaData.variations.push_back(variationData); } BSLFXCompiler::VariationOption BSLFXCompiler::parseVariationOption(ASTFXNode* variationOption) { assert(variationOption->type == NT_VariationOption); VariationOption output; for (int i = 0; i < variationOption->options->count; i++) { NodeOption* option = &variationOption->options->entries[i]; switch (option->type) { case OT_VariationValue: output.value = option->value.intValue; break; case OT_Attributes: { AttributeData attribs = parseAttributes(option->value.nodePtr); for(auto& entry : attribs.attributes) { if(entry.first == OT_AttrName) output.name = entry.second; } } default: break; } } return output; } BSLFXCompiler::AttributeData BSLFXCompiler::parseAttributes(ASTFXNode* attributes) { assert(attributes->type == NT_Attributes); AttributeData attributeData; for (int i = 0; i < attributes->options->count; i++) { NodeOption* option = &attributes->options->entries[i]; switch (option->type) { case OT_AttrName: attributeData.attributes.push_back(std::pair<INT32, String>(OT_AttrName, removeQuotes(option->value.strValue))); break; case OT_AttrShow: attributeData.attributes.push_back(std::pair<INT32, String>(OT_AttrShow, "")); break; default: break; } } return attributeData; } QueueSortType BSLFXCompiler::parseSortType(CullAndSortModeValue sortType) { switch (sortType) { case CASV_BackToFront: return QueueSortType::BackToFront; case CASV_FrontToBack: return QueueSortType::FrontToBack; case CASV_None: return QueueSortType::None; default: break; } return QueueSortType::None; } CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc) { switch (compFunc) { case CFV_Pass: return CMPF_ALWAYS_PASS; case CFV_Fail: return CMPF_ALWAYS_FAIL; case CFV_LT: return CMPF_LESS; case CFV_LTE: return CMPF_LESS_EQUAL; case CFV_EQ: return CMPF_EQUAL; case CFV_NEQ: return CMPF_NOT_EQUAL; case CFV_GT: return CMPF_GREATER; case CFV_GTE: return CMPF_GREATER_EQUAL; } return CMPF_ALWAYS_PASS; } BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor) { switch (factor) { case OV_One: return BF_ONE; case OV_Zero: return BF_ZERO; case OV_DestColor: return BF_DEST_COLOR; case OV_SrcColor: return BF_SOURCE_COLOR; case OV_InvDestColor: return BF_INV_DEST_COLOR; case OV_InvSrcColor: return BF_INV_SOURCE_COLOR; case OV_DestAlpha: return BF_DEST_ALPHA; case OV_SrcAlpha: return BF_SOURCE_ALPHA; case OV_InvDestAlpha: return BF_INV_DEST_ALPHA; case OV_InvSrcAlpha: return BF_INV_SOURCE_ALPHA; default: break; } return BF_ONE; } BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op) { switch (op) { case BOV_Add: return BO_ADD; case BOV_Max: return BO_MAX; case BOV_Min: return BO_MIN; case BOV_Subtract: return BO_SUBTRACT; case BOV_RevSubtract: return BO_REVERSE_SUBTRACT; } return BO_ADD; } StencilOperation BSLFXCompiler::parseStencilOp(OpValue op) { switch (op) { case OV_Keep: return SOP_KEEP; case OV_Zero: return SOP_ZERO; case OV_Replace: return SOP_REPLACE; case OV_Incr: return SOP_INCREMENT; case OV_Decr: return SOP_DECREMENT; case OV_IncrWrap: return SOP_INCREMENT_WRAP; case OV_DecrWrap: return SOP_DECREMENT_WRAP; case OV_Invert: return SOP_INVERT; default: break; } return SOP_KEEP; } CullingMode BSLFXCompiler::parseCullMode(CullAndSortModeValue cm) { switch (cm) { case CASV_None: return CULL_NONE; case CASV_CW: return CULL_CLOCKWISE; case CASV_CCW: return CULL_COUNTERCLOCKWISE; default: break; } return CULL_COUNTERCLOCKWISE; } PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm) { if (fm == FMV_Wire) return PM_WIREFRAME; return PM_SOLID; } void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode) { if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp) return; for (int i = 0; i < stencilOpNode->options->count; i++) { NodeOption* option = &stencilOpNode->options->entries[i]; switch (option->type) { case OT_Fail: desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_ZFail: desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_PassOp: desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_CompareFunc: desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue); break; default: break; } } } void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode) { if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp) return; for (int i = 0; i < stencilOpNode->options->count; i++) { NodeOption* option = &stencilOpNode->options->entries[i]; switch (option->type) { case OT_Fail: desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_ZFail: desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_PassOp: desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue); break; case OT_CompareFunc: desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue); break; default: break; } } } void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode) { if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef) return; for (int i = 0; i < blendDefNode->options->count; i++) { NodeOption* option = &blendDefNode->options->entries[i]; switch (option->type) { case OT_Source: desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue); break; case OT_Dest: desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue); break; case OT_Op: desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue); break; default: break; } } } void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode) { if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef) return; for (int i = 0; i < blendDefNode->options->count; i++) { NodeOption* option = &blendDefNode->options->entries[i]; switch (option->type) { case OT_Source: desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue); break; case OT_Dest: desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue); break; case OT_Op: desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue); break; default: break; } } } void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode, UINT32& index) { if (targetNode == nullptr || targetNode->type != NT_Target) return; for (int i = 0; i < targetNode->options->count; i++) { NodeOption* option = &targetNode->options->entries[i]; switch (option->type) { case OT_Index: index = option->value.intValue; break; default: break; } } if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS) return; RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index]; for (int i = 0; i < targetNode->options->count; i++) { NodeOption* option = &targetNode->options->entries[i]; switch (option->type) { case OT_Enabled: rtDesc.blendEnable = option->value.intValue > 0; break; case OT_Color: parseColorBlendDef(rtDesc, option->value.nodePtr); break; case OT_Alpha: parseAlphaBlendDef(rtDesc, option->value.nodePtr); break; case OT_WriteMask: rtDesc.renderTargetWriteMask = option->value.intValue; break; default: break; } } index++; } bool BSLFXCompiler::parseBlendState(PassData& desc, ASTFXNode* blendNode) { if (blendNode == nullptr || blendNode->type != NT_Blend) return false; bool isDefault = true; SmallVector<ASTFXNode*, 8> targets; for (int i = 0; i < blendNode->options->count; i++) { NodeOption* option = &blendNode->options->entries[i]; switch (option->type) { case OT_AlphaToCoverage: desc.blendDesc.alphaToCoverageEnable = option->value.intValue > 0; isDefault = false; break; case OT_IndependantBlend: desc.blendDesc.independantBlendEnable = option->value.intValue > 0; isDefault = false; break; case OT_Target: targets.add(option->value.nodePtr); isDefault = false; break; default: break; } } // Parse targets in reverse as their order matters and we want to visit them in the top-down order as defined in // the source code UINT32 index = 0; for(auto iter = targets.rbegin(); iter != targets.rend(); ++iter) parseRenderTargetBlendState(desc.blendDesc, *iter, index); return !isDefault; } bool BSLFXCompiler::parseRasterizerState(PassData& desc, ASTFXNode* rasterNode) { if (rasterNode == nullptr || rasterNode->type != NT_Raster) return false; bool isDefault = true; for (int i = 0; i < rasterNode->options->count; i++) { NodeOption* option = &rasterNode->options->entries[i]; switch (option->type) { case OT_FillMode: desc.rasterizerDesc.polygonMode = parseFillMode((FillModeValue)option->value.intValue); isDefault = false; break; case OT_CullMode: desc.rasterizerDesc.cullMode = parseCullMode((CullAndSortModeValue)option->value.intValue); isDefault = false; break; case OT_DepthBias: desc.rasterizerDesc.depthBias = option->value.floatValue; isDefault = false; break; case OT_SDepthBias: desc.rasterizerDesc.slopeScaledDepthBias = option->value.floatValue; isDefault = false; break; case OT_DepthClip: desc.rasterizerDesc.depthClipEnable = option->value.intValue > 0; isDefault = false; break; case OT_Scissor: desc.rasterizerDesc.scissorEnable = option->value.intValue > 0; isDefault = false; break; case OT_Multisample: desc.rasterizerDesc.multisampleEnable = option->value.intValue > 0; isDefault = false; break; case OT_AALine: desc.rasterizerDesc.antialiasedLineEnable = option->value.intValue > 0; isDefault = false; break; default: break; } } return !isDefault; } bool BSLFXCompiler::parseDepthState(PassData& passData, ASTFXNode* depthNode) { if (depthNode == nullptr || depthNode->type != NT_Depth) return false; bool isDefault = true; for (int i = 0; i < depthNode->options->count; i++) { NodeOption* option = &depthNode->options->entries[i]; switch (option->type) { case OT_DepthRead: passData.depthStencilDesc.depthReadEnable = option->value.intValue > 0; isDefault = false; break; case OT_DepthWrite: passData.depthStencilDesc.depthWriteEnable = option->value.intValue > 0; isDefault = false; break; case OT_CompareFunc: passData.depthStencilDesc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue); isDefault = false; break; default: break; } } return !isDefault; } bool BSLFXCompiler::parseStencilState(PassData& passData, ASTFXNode* stencilNode) { if (stencilNode == nullptr || stencilNode->type != NT_Stencil) return false; bool isDefault = true; for (int i = 0; i < stencilNode->options->count; i++) { NodeOption* option = &stencilNode->options->entries[i]; switch (option->type) { case OT_Enabled: passData.depthStencilDesc.stencilEnable = option->value.intValue > 0; isDefault = false; break; case OT_StencilReadMask: passData.depthStencilDesc.stencilReadMask = (UINT8)option->value.intValue; isDefault = false; break; case OT_StencilWriteMask: passData.depthStencilDesc.stencilWriteMask = (UINT8)option->value.intValue; isDefault = false; break; case OT_StencilOpFront: parseStencilFront(passData.depthStencilDesc, option->value.nodePtr); isDefault = false; break; case OT_StencilOpBack: parseStencilBack(passData.depthStencilDesc, option->value.nodePtr); isDefault = false; break; case OT_StencilRef: passData.stencilRefValue = option->value.intValue; break; default: break; } } return !isDefault; } void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<String>& codeBlocks, PassData& passData) { if (codeNode == nullptr || (codeNode->type != NT_Code)) { return; } UINT32 index = (UINT32)-1; for (int j = 0; j < codeNode->options->count; j++) { if (codeNode->options->entries[j].type == OT_Index) index = codeNode->options->entries[j].value.intValue; } if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size()) { passData.code += codeBlocks[index]; } } void BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<String>& codeBlocks, PassData& passData) { if (passNode == nullptr || passNode->type != NT_Pass) return; for (int i = 0; i < passNode->options->count; i++) { NodeOption* option = &passNode->options->entries[i]; switch (option->type) { case OT_Blend: passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr); break; case OT_Raster: passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr); break; case OT_Depth: passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr); break; case OT_Stencil: passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr); break; case OT_Code: parseCodeBlock(option->value.nodePtr, codeBlocks, passData); break; default: break; } } } void BSLFXCompiler::parseShader(ASTFXNode* shaderNode, const Vector<String>& codeBlocks, ShaderData& shaderData) { if (shaderNode == nullptr || (shaderNode->type != NT_Shader && shaderNode->type != NT_Mixin)) return; // There must always be at least one pass if(shaderData.passes.empty()) { shaderData.passes.push_back(PassData()); shaderData.passes.back().seqIdx = 0; } PassData combinedCommonPassData; UINT32 nextPassIdx = 0; // Go in reverse because options are added in reverse order during parsing for (int i = shaderNode->options->count - 1; i >= 0; i--) { NodeOption* option = &shaderNode->options->entries[i]; switch (option->type) { case OT_Pass: { UINT32 passIdx = nextPassIdx; PassData* passData = nullptr; for (auto& entry : shaderData.passes) { if (entry.seqIdx == passIdx) passData = &entry; } if (passData == nullptr) { shaderData.passes.push_back(PassData()); passData = &shaderData.passes.back(); passData->seqIdx = passIdx; } nextPassIdx = std::max(nextPassIdx, passIdx) + 1; passData->code = combinedCommonPassData.code + passData->code; ASTFXNode* passNode = option->value.nodePtr; parsePass(passNode, codeBlocks, *passData); } break; case OT_Code: { PassData commonPassData; parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData); for (auto& passData : shaderData.passes) passData.code += commonPassData.code; combinedCommonPassData.code += commonPassData.code; } break; case OT_FeatureSet: shaderData.metaData.featureSet = option->value.strValue; break; default: break; } } // Parse common pass states for (int i = 0; i < shaderNode->options->count; i++) { NodeOption* option = &shaderNode->options->entries[i]; switch (option->type) { case OT_Blend: for (auto& passData : shaderData.passes) passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr); break; case OT_Raster: for (auto& passData : shaderData.passes) passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr); break; case OT_Depth: for (auto& passData : shaderData.passes) passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr); break; case OT_Stencil: for (auto& passData : shaderData.passes) passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr); break; default: break; } } } BSLFXCompiler::SubShaderData BSLFXCompiler::parseSubShader(ASTFXNode* subShader) { SubShaderData subShaderData; //// Go in reverse because options are added in reverse order during parsing for (int i = subShader->options->count - 1; i >= 0; i--) { NodeOption* option = &subShader->options->entries[i]; switch (option->type) { case OT_Identifier: subShaderData.name = option->value.strValue; break; case OT_Index: subShaderData.codeBlockIndex = option->value.intValue; default: break; } } return subShaderData; } void BSLFXCompiler::parseOptions(ASTFXNode* optionsNode, SHADER_DESC& shaderDesc) { if (optionsNode == nullptr || optionsNode->type != NT_Options) return; for (int i = optionsNode->options->count - 1; i >= 0; i--) { NodeOption* option = &optionsNode->options->entries[i]; switch (option->type) { case OT_Separable: shaderDesc.separablePasses = option->value.intValue > 1; break; case OT_Sort: shaderDesc.queueSortType = parseSortType((CullAndSortModeValue)option->value.intValue); break; case OT_Priority: shaderDesc.queuePriority = option->value.intValue; break; case OT_Transparent: shaderDesc.flags |= ShaderFlag::Transparent; break; case OT_Forward: shaderDesc.flags |= ShaderFlag::Forward; break; default: break; } } } BSLFXCompileResult BSLFXCompiler::populateVariations(Vector<std::pair<ASTFXNode*, ShaderMetaData>>& shaderMetaData) { BSLFXCompileResult output; // Inherit variations from mixins bool* mixinWasParsed = bs_stack_alloc<bool>((UINT32)shaderMetaData.size()); std::function<bool(const ShaderMetaData&, ShaderMetaData&)> parseInherited = [&](const ShaderMetaData& metaData, ShaderMetaData& combinedMetaData) { for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter) { const String& include = *riter; UINT32 baseIdx = -1; for (UINT32 i = 0; i < (UINT32)shaderMetaData.size(); i++) { auto& entry = shaderMetaData[i]; if (!entry.second.isMixin) continue; if (entry.second.name == include) { bool matches = entry.second.language == metaData.language || entry.second.language == "Any"; // We want the last matching mixin, in order to allow mixins to override each other if (matches) baseIdx = i; } } if (baseIdx != (UINT32)-1) { auto& entry = shaderMetaData[baseIdx]; // Was already parsed previously, don't parse it multiple times (happens when multiple mixins // include the same mixin) if (mixinWasParsed[baseIdx]) continue; if (!parseInherited(entry.second, combinedMetaData)) return false; for (auto& variation : entry.second.variations) combinedMetaData.variations.push_back(variation); mixinWasParsed[baseIdx] = true; } else { output.errorMessage = "Mixin \"" + include + "\" cannot be found."; return false; } } return true; }; for (auto& entry : shaderMetaData) { const ShaderMetaData& metaData = entry.second; if (metaData.isMixin) continue; bs_zero_out(mixinWasParsed, shaderMetaData.size()); ShaderMetaData combinedMetaData = metaData; if (!parseInherited(metaData, combinedMetaData)) { bs_stack_free(mixinWasParsed); return output; } entry.second = combinedMetaData; } bs_stack_free(mixinWasParsed); return output; } void BSLFXCompiler::populateVariationParamInfos(const ShaderMetaData& shaderMetaData, SHADER_DESC& desc) { for(auto& entry : shaderMetaData.variations) { ShaderVariationParamInfo paramInfo; paramInfo.isInternal = entry.internal; paramInfo.name = entry.name; paramInfo.identifier = entry.identifier; for(auto& value : entry.values) { ShaderVariationParamValue paramValue; paramValue.name = value.name; paramValue.value = value.value; paramInfo.values.add(paramValue); } desc.variationParams.push_back(paramInfo); } } BSLFXCompileResult BSLFXCompiler::compileTechniques( const Vector<std::pair<ASTFXNode*, ShaderMetaData>>& shaderMetaData, const String& source, const UnorderedMap<String, String>& defines, ShadingLanguageFlags languages, SHADER_DESC& shaderDesc, Vector<String>& includes) { BSLFXCompileResult output; // Build a list of different variations and re-parse the source using the relevant defines UnorderedSet<String> includeSet; for (auto& entry : shaderMetaData) { const ShaderMetaData& metaData = entry.second; if (metaData.isMixin) continue; // Generate a list of variations Vector<ShaderVariation> variations; if (metaData.variations.empty()) variations.push_back(ShaderVariation()); else { Vector<const VariationData*> todo; for (UINT32 i = 0; i < (UINT32)metaData.variations.size(); i++) todo.push_back(&metaData.variations[i]); while (!todo.empty()) { const VariationData* current = todo.back(); todo.erase(todo.end() - 1); // Variation parameter that's either defined or isn't if (current->values.empty()) { // This is the first variation parameter, register new variations if (variations.empty()) { ShaderVariation a; ShaderVariation b; b.addParam(ShaderVariation::Param(current->identifier, 1)); variations.push_back(a); variations.push_back(b); } else // Duplicate existing variations, and add the parameter { UINT32 numVariations = (UINT32)variations.size(); for (UINT32 i = 0; i < numVariations; i++) { // Make a copy variations.push_back(variations[i]); // Add the parameter to existing variation variations[i].addParam(ShaderVariation::Param(current->identifier, 1)); } } } else // Variation parameter with multiple values { // This is the first variation parameter, register new variations if (variations.empty()) { for (UINT32 i = 0; i < (UINT32)current->values.size(); i++) { ShaderVariation variation; variation.addParam(ShaderVariation::Param(current->identifier, current->values[i].value)); variations.push_back(variation); } } else // Duplicate existing variations, and add the parameter { UINT32 numVariations = (UINT32)variations.size(); for (UINT32 i = 0; i < numVariations; i++) { for (UINT32 j = 1; j < (UINT32)current->values.size(); j++) { ShaderVariation copy = variations[i]; copy.addParam(ShaderVariation::Param(current->identifier, current->values[j].value)); variations.push_back(copy); } variations[i].addParam(ShaderVariation::Param(current->identifier, current->values[0].value)); } } } } } // For every variation, re-parse the file with relevant defines for (auto& variation : variations) { UnorderedMap<String, String> globalDefines = defines; UnorderedMap<String, String> variationDefines = variation.getDefines().getAll(); for (auto& define : variationDefines) globalDefines[define.first] = define.second; ParseState* variationParseState = parseStateCreate(); output = parseFX(variationParseState, source.c_str(), globalDefines); if (!output.errorMessage.empty()) parseStateDelete(variationParseState); else { Vector<String> codeBlocks; RawCode* rawCode = variationParseState->rawCodeBlock[RCT_CodeBlock]; while (rawCode != nullptr) { while ((INT32)codeBlocks.size() <= rawCode->index) codeBlocks.push_back(String()); codeBlocks[rawCode->index] = String(rawCode->code, rawCode->size); rawCode = rawCode->next; } output = compileTechniques(variationParseState, entry.second.name, codeBlocks, variation, languages, includeSet, shaderDesc); if (!output.errorMessage.empty()) return output; } } } // Generate a shader from the parsed techniques for (auto& entry : includeSet) includes.push_back(entry); // Verify techniques compile correctly bool hasError = false; StringStream gpuProgError; for (auto& technique : shaderDesc.techniques) { if(!technique->isSupported()) continue; UINT32 numPasses = technique->getNumPasses(); technique->compile(); for (UINT32 i = 0; i < numPasses; i++) { SPtr<Pass> pass = technique->getPass(i); auto checkCompileStatus = [&](const String& prefix, const SPtr<GpuProgram>& prog) { if (prog != nullptr) { prog->blockUntilCoreInitialized(); if (!prog->isCompiled()) { hasError = true; gpuProgError << prefix << ": " << prog->getCompileErrorMessage() << std::endl; } } }; const SPtr<GraphicsPipelineState>& graphicsPipeline = pass->getGraphicsPipelineState(); if (graphicsPipeline) { checkCompileStatus("Vertex program", graphicsPipeline->getVertexProgram()); checkCompileStatus("Fragment program", graphicsPipeline->getFragmentProgram()); checkCompileStatus("Geometry program", graphicsPipeline->getGeometryProgram()); checkCompileStatus("Hull program", graphicsPipeline->getHullProgram()); checkCompileStatus("Domain program", graphicsPipeline->getDomainProgram()); } const SPtr<ComputePipelineState>& computePipeline = pass->getComputePipelineState(); if (computePipeline) checkCompileStatus("Compute program", computePipeline->getProgram()); } } if (hasError) { output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str(); output.errorLine = 0; output.errorColumn = 0; } return output; } BSLFXCompileResult BSLFXCompiler::compileShader(String source, const UnorderedMap<String, String>& defines, ShadingLanguageFlags languages, SHADER_DESC& shaderDesc, Vector<String>& includes) { SPtr<ct::Renderer> renderer = RendererManager::instance().getActive(); // Run the lexer/parser and generate the AST ParseState* parseState = parseStateCreate(); BSLFXCompileResult output = parseFX(parseState, source.c_str(), defines); if (!output.errorMessage.empty()) { parseStateDelete(parseState); return output; } // Parse global shader options & shader meta-data Vector<pair<ASTFXNode*, ShaderMetaData>> shaderMetaData; Vector<SubShaderData> subShaderData; output = parseMetaDataAndOptions(parseState->rootNode, shaderMetaData, subShaderData, shaderDesc); if (!output.errorMessage.empty()) { parseStateDelete(parseState); return output; } // Parse sub-shader code blocks Vector<String> subShaderCodeBlocks; RawCode* rawCode = parseState->rawCodeBlock[RCT_SubShaderBlock]; while (rawCode != nullptr) { while ((INT32)subShaderCodeBlocks.size() <= rawCode->index) subShaderCodeBlocks.push_back(String()); subShaderCodeBlocks[rawCode->index] = String(rawCode->code, rawCode->size); rawCode = rawCode->next; } parseStateDelete(parseState); output = populateVariations(shaderMetaData); if (!output.errorMessage.empty()) return output; // Note: Must be called after populateVariations, to ensure variations from mixins are inherited for(auto& entry : shaderMetaData) { if(entry.second.isMixin) continue; populateVariationParamInfos(entry.second, shaderDesc); } output = compileTechniques(shaderMetaData, source, defines, languages, shaderDesc, includes); if (!output.errorMessage.empty()) return output; // Parse sub-shaders for (auto& entry : subShaderData) { if(entry.codeBlockIndex > (UINT32)subShaderCodeBlocks.size()) continue; const String& subShaderCode = subShaderCodeBlocks[entry.codeBlockIndex]; ct::ShaderExtensionPointInfo extPointInfo = renderer->getShaderExtensionPointInfo(entry.name); for (auto& extPointShader : extPointInfo.shaders) { Path path = gBuiltinResources().getRawShaderFolder(); path.append(extPointShader.path); path.setExtension(path.getExtension()); StringStream subShaderSource; const UnorderedMap<String, String> subShaderDefines = extPointShader.defines.getAll(); { Lock fileLock = FileScheduler::getLock(path); SPtr<DataStream> stream = FileSystem::openFile(path); if(stream) subShaderSource << stream->getAsString(); } subShaderSource << "\n"; subShaderSource << subShaderCode; SHADER_DESC subShaderDesc; Vector<String> subShaderIncludes; BSLFXCompileResult subShaderOutput = compileShader(subShaderSource.str(), subShaderDefines, languages, subShaderDesc, subShaderIncludes); if (!subShaderOutput.errorMessage.empty()) return subShaderOutput; // Clear the sub-shader descriptor of any data other than techniques Vector<SPtr<Technique>> techniques = subShaderDesc.techniques; subShaderDesc = SHADER_DESC(); subShaderDesc.techniques = techniques; SubShader subShader; subShader.name = extPointShader.name; subShader.shader = Shader::_createPtr(subShader.name, subShaderDesc); shaderDesc.subShaders.push_back(subShader); } } return output; } BSLFXCompileResult BSLFXCompiler::compileTechniques(ParseState* parseState, const String& name, const Vector<String>& codeBlocks, const ShaderVariation& variation, ShadingLanguageFlags languages, UnorderedSet<String>& includes, SHADER_DESC& shaderDesc) { BSLFXCompileResult output; if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Root) { parseStateDelete(parseState); output.errorMessage = "Root is null or not a shader."; return output; } Vector<pair<ASTFXNode*, ShaderData>> shaderData; // Go in reverse because options are added in reverse order during parsing for (int i = parseState->rootNode->options->count - 1; i >= 0; i--) { NodeOption* option = &parseState->rootNode->options->entries[i]; switch (option->type) { case OT_Shader: { // We initially parse only meta-data, so we can handle out-of-order technique definitions ShaderMetaData metaData = parseShaderMetaData(option->value.nodePtr); // Skip all techniques except the one we're parsing if(metaData.name != name && !metaData.isMixin) continue; shaderData.push_back(std::make_pair(option->value.nodePtr, ShaderData())); ShaderData& data = shaderData.back().second; data.metaData = metaData; break; } default: break; } } bool* mixinWasParsed = bs_stack_alloc<bool>((UINT32)shaderData.size()); std::function<bool(const ShaderMetaData&, ShaderData&)> parseInherited = [&](const ShaderMetaData& metaData, ShaderData& outShader) { for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter) { const String& includes = *riter; UINT32 baseIdx = -1; for(UINT32 i = 0; i < (UINT32)shaderData.size(); i++) { auto& entry = shaderData[i]; if (!entry.second.metaData.isMixin) continue; if (entry.second.metaData.name == includes) { bool matches = (entry.second.metaData.language == metaData.language || entry.second.metaData.language == "Any"); // We want the last matching mixin, in order to allow mixins to override each other if (matches) baseIdx = i; } } if (baseIdx != (UINT32)-1) { auto& entry = shaderData[baseIdx]; // Was already parsed previously, don't parse it multiple times (happens when multiple mixins // include the same mixin) if (mixinWasParsed[baseIdx]) continue; if (!parseInherited(entry.second.metaData, outShader)) return false; parseShader(entry.first, codeBlocks, outShader); mixinWasParsed[baseIdx] = true; } else { output.errorMessage = "Mixin \"" + includes + "\" cannot be found."; return false; } } return true; }; // Actually parse shaders for (auto& entry : shaderData) { const ShaderMetaData& metaData = entry.second.metaData; if (metaData.isMixin) continue; bs_zero_out(mixinWasParsed, shaderData.size()); if (!parseInherited(metaData, entry.second)) { parseStateDelete(parseState); bs_stack_free(mixinWasParsed); return output; } parseShader(entry.first, codeBlocks, entry.second); } bs_stack_free(mixinWasParsed); IncludeLink* includeLink = parseState->includes; while(includeLink != nullptr) { String includeFilename = includeLink->data->filename; auto iterFind = std::find(includes.begin(), includes.end(), includeFilename); if (iterFind == includes.end()) includes.insert(includeFilename); includeLink = includeLink->next; } parseStateDelete(parseState); // Parse extended HLSL code and generate per-program code, also convert to GLSL/VKSL/MSL const auto end = (UINT32)shaderData.size(); Vector<pair<ASTFXNode*, ShaderData>> outputShaderData; for(UINT32 i = 0; i < end; i++) { const ShaderMetaData& metaData = shaderData[i].second.metaData; if (metaData.isMixin) continue; ShaderData& shaderDataEntry = shaderData[i].second; ShaderData hlslShaderData = shaderData[i].second; ShaderData glslShaderData = shaderData[i].second; // When working with OpenGL, lower-end feature sets are supported. For other backends, high-end is always assumed. CrossCompileOutput glslVersion = CrossCompileOutput::GLSL41; if(glslShaderData.metaData.featureSet == "HighEnd") { glslShaderData.metaData.language = "glsl"; glslVersion = CrossCompileOutput::GLSL45; } else glslShaderData.metaData.language = "glsl4_1"; ShaderData vkslShaderData = shaderData[i].second; vkslShaderData.metaData.language = "vksl"; ShaderData mvksl = shaderData[i].second; mvksl.metaData.language = "mvksl"; const auto numPasses = (UINT32)shaderDataEntry.passes.size(); for(UINT32 j = 0; j < numPasses; j++) { PassData& passData = shaderDataEntry.passes[j]; // Find valid entry points and parameters // Note: XShaderCompiler needs to do a full pass when doing reflection, and for each individual program // type. If performance is ever important here it could be good to update XShaderCompiler so it can // somehow save the AST and then re-use it for multiple actions. Vector<GpuProgramType> types; reflectHLSL(passData.code, shaderDesc, types); auto crossCompilePass = [&types](PassData& passData, CrossCompileOutput language) { UINT32 binding = 0; for (auto& type : types) { switch (type) { case GPT_VERTEX_PROGRAM: passData.vertexCode = crossCompile(passData.code, GPT_VERTEX_PROGRAM, language, binding); break; case GPT_FRAGMENT_PROGRAM: passData.fragmentCode = crossCompile(passData.code, GPT_FRAGMENT_PROGRAM, language, binding); break; case GPT_GEOMETRY_PROGRAM: passData.geometryCode = crossCompile(passData.code, GPT_GEOMETRY_PROGRAM, language, binding); break; case GPT_HULL_PROGRAM: passData.hullCode = crossCompile(passData.code, GPT_HULL_PROGRAM, language, binding); break; case GPT_DOMAIN_PROGRAM: passData.domainCode = crossCompile(passData.code, GPT_DOMAIN_PROGRAM, language, binding); break; case GPT_COMPUTE_PROGRAM: passData.computeCode = crossCompile(passData.code, GPT_COMPUTE_PROGRAM, language, binding); break; default: break; } } }; if(languages.isSet(ShadingLanguageFlag::GLSL)) crossCompilePass(glslShaderData.passes[j], glslVersion); if(languages.isSet(ShadingLanguageFlag::VKSL)) crossCompilePass(vkslShaderData.passes[j], CrossCompileOutput::VKSL45); if(languages.isSet(ShadingLanguageFlag::MSL)) crossCompilePass(mvksl.passes[j], CrossCompileOutput::MVKSL); if(languages.isSet(ShadingLanguageFlag::HLSL)) { PassData& hlslPassData = hlslShaderData.passes[j]; // Clean non-standard HLSL // Note: Ideally we add a full HLSL output module to XShaderCompiler, instead of using simple regex. This // way the syntax could be enhanced with more complex features, while still being able to output pure // HLSL. static const std::regex attrRegex( R"(\[\s*layout\s*\(.*\)\s*\]|\[\s*internal\s*\]|\[\s*color\s*\]|\[\s*alias\s*\(.*\)\s*\]|\[\s*spriteuv\s*\(.*\)\s*\])"); hlslPassData.code = regex_replace(hlslPassData.code, attrRegex, ""); static const std::regex attr2Regex( R"(\[\s*hideInInspector\s*\]|\[\s*name\s*\(".*"\)\s*\]|\[\s*hdr\s*\])"); hlslPassData.code = regex_replace(hlslPassData.code, attr2Regex, ""); static const std::regex initializerRegex( R"(Texture2D\s*(\S*)\s*=.*;)"); hlslPassData.code = regex_replace(hlslPassData.code, initializerRegex, "Texture2D $1;"); static const std::regex warpWithSyncRegex( R"(Warp(Group|Device|All)MemoryBarrierWithWarpSync)"); hlslPassData.code = regex_replace(hlslPassData.code, warpWithSyncRegex, "$1MemoryBarrierWithGroupSync"); static const std::regex warpNoSyncRegex( R"(Warp(Group|Device|All)MemoryBarrier)"); hlslPassData.code = regex_replace(hlslPassData.code, warpNoSyncRegex, "$1MemoryBarrier"); // Note: I'm just copying HLSL code as-is. This code will contain all entry points which could have // an effect on compile time. It would be ideal to remove dead code depending on program type. This would // involve adding a HLSL code generator to XShaderCompiler. for (auto& type : types) { switch (type) { case GPT_VERTEX_PROGRAM: hlslPassData.vertexCode = hlslPassData.code; break; case GPT_FRAGMENT_PROGRAM: hlslPassData.fragmentCode = hlslPassData.code; break; case GPT_GEOMETRY_PROGRAM: hlslPassData.geometryCode = hlslPassData.code; break; case GPT_HULL_PROGRAM: hlslPassData.hullCode = hlslPassData.code; break; case GPT_DOMAIN_PROGRAM: hlslPassData.domainCode = hlslPassData.code; break; case GPT_COMPUTE_PROGRAM: hlslPassData.computeCode = hlslPassData.code; break; default: break; } } } } outputShaderData.push_back(std::make_pair(nullptr, hlslShaderData)); outputShaderData.push_back(std::make_pair(nullptr, glslShaderData)); outputShaderData.push_back(std::make_pair(nullptr, vkslShaderData)); outputShaderData.push_back(std::make_pair(nullptr, mvksl)); } for(auto& entry : outputShaderData) { const ShaderMetaData& metaData = entry.second.metaData; if (metaData.isMixin) continue; Map<UINT32, SPtr<Pass>, std::greater<UINT32>> passes; for (auto& passData : entry.second.passes) { PASS_DESC passDesc; passDesc.blendStateDesc = passData.blendDesc; passDesc.rasterizerStateDesc = passData.rasterizerDesc; passDesc.depthStencilStateDesc = passData.depthStencilDesc; auto createProgram = [](const String& language, const String& entry, const String& code, GpuProgramType type) -> GPU_PROGRAM_DESC { GPU_PROGRAM_DESC desc; desc.language = language; desc.entryPoint = entry; desc.source = code; desc.type = type; return desc; }; bool isHLSL = metaData.language == "hlsl"; passDesc.vertexProgramDesc = createProgram( metaData.language, isHLSL ? "vsmain" : "main", passData.vertexCode, GPT_VERTEX_PROGRAM); passDesc.fragmentProgramDesc = createProgram( metaData.language, isHLSL ? "fsmain" : "main", passData.fragmentCode, GPT_FRAGMENT_PROGRAM); passDesc.geometryProgramDesc = createProgram( metaData.language, isHLSL ? "gsmain" : "main", passData.geometryCode, GPT_GEOMETRY_PROGRAM); passDesc.hullProgramDesc = createProgram( metaData.language, isHLSL ? "hsmain" : "main", passData.hullCode, GPT_HULL_PROGRAM); passDesc.domainProgramDesc = createProgram( metaData.language, isHLSL ? "dsmain" : "main", passData.domainCode, GPT_DOMAIN_PROGRAM); passDesc.computeProgramDesc = createProgram( metaData.language, isHLSL ? "csmain" : "main", passData.computeCode, GPT_COMPUTE_PROGRAM); passDesc.stencilRefValue = passData.stencilRefValue; SPtr<Pass> pass = Pass::create(passDesc); if (pass != nullptr) passes[passData.seqIdx] = pass; } Vector<SPtr<Pass>> orderedPasses; for (auto& KVP : passes) orderedPasses.push_back(KVP.second); if (!orderedPasses.empty()) { SPtr<Technique> technique = Technique::create(metaData.language, metaData.tags, variation, orderedPasses); shaderDesc.techniques.push_back(technique); } } return output; } String BSLFXCompiler::removeQuotes(const char* input) { UINT32 len = (UINT32)strlen(input); String output(len - 2, ' '); for (UINT32 i = 0; i < (len - 2); i++) output[i] = input[i + 1]; return output; } }
28.821641
131
0.696398
bsf2dev
297c3d309ff4cc577ce15346ed48509833efdcf8
3,307
cpp
C++
src/lib/logical_query_plan/stored_table_node.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/lib/logical_query_plan/stored_table_node.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/lib/logical_query_plan/stored_table_node.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#include "stored_table_node.hpp" #include <memory> #include <optional> #include <string> #include <vector> #include "statistics/table_statistics.hpp" #include "storage/storage_manager.hpp" #include "storage/table.hpp" #include "types.hpp" namespace opossum { StoredTableNode::StoredTableNode(const std::string& table_name, const std::optional<std::string>& alias) : AbstractLQPNode(LQPNodeType::StoredTable), _table_name(table_name) { /** * Initialize output information. */ auto table = StorageManager::get().get_table(_table_name); _output_column_names = table->column_names(); set_alias(alias); } std::shared_ptr<AbstractLQPNode> StoredTableNode::_deep_copy_impl( const std::shared_ptr<AbstractLQPNode>& copied_left_input, const std::shared_ptr<AbstractLQPNode>& copied_right_input) const { return StoredTableNode::make(_table_name); } std::string StoredTableNode::description() const { return "[StoredTable] Name: '" + _table_name + "'"; } std::shared_ptr<const AbstractLQPNode> StoredTableNode::find_table_name_origin(const std::string& table_name) const { if (_table_alias) { return *_table_alias == table_name ? shared_from_this() : nullptr; } return table_name == _table_name ? shared_from_this() : nullptr; } const std::vector<std::string>& StoredTableNode::output_column_names() const { return _output_column_names; } std::shared_ptr<TableStatistics> StoredTableNode::derive_statistics_from( const std::shared_ptr<AbstractLQPNode>& left_input, const std::shared_ptr<AbstractLQPNode>& right_input) const { DebugAssert(!left_input && !right_input, "StoredTableNode must be leaf"); return StorageManager::get().get_table(_table_name)->table_statistics(); } const std::string& StoredTableNode::table_name() const { return _table_name; } std::string StoredTableNode::get_verbose_column_name(ColumnID column_id) const { if (_table_alias) { return "(" + _table_name + " AS " + *_table_alias + ")." + output_column_names()[column_id]; } return _table_name + "." + output_column_names()[column_id]; } bool StoredTableNode::shallow_equals(const AbstractLQPNode& rhs) const { Assert(rhs.type() == type(), "Can only compare nodes of the same type()"); const auto& stored_table_node = static_cast<const StoredTableNode&>(rhs); return _table_name == stored_table_node._table_name; } void StoredTableNode::_on_input_changed() { Fail("StoredTableNode cannot have inputs."); } std::optional<QualifiedColumnName> StoredTableNode::_resolve_local_table_name( const QualifiedColumnName& qualified_column_name) const { if (!qualified_column_name.table_name) { return qualified_column_name; } if (_table_alias) { if (*qualified_column_name.table_name != *_table_alias) { return std::nullopt; } } else { if (_table_name != *qualified_column_name.table_name) { return std::nullopt; } } auto reference_without_local_alias = qualified_column_name; reference_without_local_alias.table_name = std::nullopt; return reference_without_local_alias; } void StoredTableNode::set_excluded_chunk_ids(const std::vector<ChunkID>& chunks) { _excluded_chunk_ids = chunks; } const std::vector<ChunkID>& StoredTableNode::excluded_chunk_ids() const { return _excluded_chunk_ids; } } // namespace opossum
35.180851
117
0.75567
IanJamesMcKay
297c4610d2ecf5a6b5ce145df2ed76cd4d488e1d
1,116
cpp
C++
yc5110_hw6/yc5110_hw6_q2.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
yc5110_hw6/yc5110_hw6_q2.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
yc5110_hw6/yc5110_hw6_q2.cpp
YiwenCui/NYU-Bridge-Winter-2021
bcada20fc0fd7d940f556322dabc560f59259e57
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void printShiftedTriangle(int n, int m, char symbol); void printPineTree(int n, char symbol); int main() { int numOfTree; char symbol; cout << "please enter the number of trees (int) and desired symbol(char), separate by space: " << endl; cin >> numOfTree >> symbol; printPineTree(numOfTree, symbol); return 0; } void printShiftedTriangle(int n, int m, char symbol) { int lineCount, columnCount; for (lineCount = 1; lineCount <= n; lineCount++) { for (columnCount = 1; columnCount <= m + n - lineCount; columnCount++) { cout << " "; } for (columnCount = 2; columnCount < 2 * lineCount + 1; columnCount++) { cout << symbol; } cout << endl<<endl; } } void printPineTree(int n, char symbol) { int numOfTree; int numOfLines, numOfSpaces; for (numOfTree = 1, numOfLines = 2, numOfSpaces = n - numOfTree; numOfTree <= n; numOfTree++, numOfLines++, numOfSpaces--) { printShiftedTriangle(numOfLines, numOfSpaces, symbol); } }
23.25
126
0.607527
YiwenCui
2982f696b9a827b4da35f50983fa314bafd56610
8,864
cpp
C++
src/guide/glserver.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
null
null
null
src/guide/glserver.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
null
null
null
src/guide/glserver.cpp
rzvdaniel/GUI-
1501b54a038f7e3f66d683f125fa53d3ab73672c
[ "MIT" ]
null
null
null
#define N_IMPLEMENTS TGlServer //------------------------------------------------------------------- // glserver.cpp // (C) 2004 R.Predescu //------------------------------------------------------------------- #include "SDL.h" #include "guide/glserver.h" #include "guide/screen.h" #include "guide/debug.h" extern TKey TranslateKey(int); //------------------------------------------------------------------- // CheckError() // 26-Nov-98 floh created //------------------------------------------------------------------- inline static void CheckError(void) { GLenum error; while ((error=glGetError()) != GL_NO_ERROR) { t_printf("GL error: %s\n", gluErrorString(error)); } } //------------------------------------------------------------------- // TGlServer() // 08-Feb-2004 rzv created //------------------------------------------------------------------- TGlServer::TGlServer() { ClearBufferBit = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; } //------------------------------------------------------------------- // ~TGlServer() // 08-Feb-2004 rzv created //------------------------------------------------------------------- TGlServer::~TGlServer() { } //------------------------------------------------------------------- // HandleEvent() // 19-Oct-2004 rzv created //------------------------------------------------------------------- bool TGlServer::HandleEvent(SDL_Event *event) { TMessage msg; switch(event->type) { case SDL_MOUSEMOTION: msg.Msg = CM_MOUSEMOVE; msg.LParam = T_MAKELONG(event->motion.x, event->motion.y); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if(event->button.state == SDL_PRESSED) msg.Msg = CM_MOUSEDOWN; else msg.Msg = CM_MOUSEUP; msg.LParam = T_MAKELONG(event->motion.x, event->motion.y); msg.WParam = event->key.state; break; case SDL_KEYDOWN: if(event->key.keysym.sym >= 32 && event->key.keysym.sym <= 126) { msg.Msg = CM_CHAR; /*if ((event->key.keysym.unicode & 0xFF80) == 0) msg.WParam = event->key.keysym.unicode & 0x7F;*/ } else { msg.Msg = CM_KEYDOWN; msg.LParam = TranslateKey((int)event->key.keysym.sym); } break; case SDL_KEYUP: msg.Msg = CM_KEYUP; msg.LParam = TranslateKey((int)event->key.keysym.sym); break; case SDL_QUIT: QuitRequested = true; break; } // Pass the input to the TScreen object TScreen::Singleton->HandleInputMessage(&msg); return(QuitRequested); } //------------------------------------------------------------------- /** @brief One loop rendering and message handling. */ //------------------------------------------------------------------- void TGlServer::Loop(void) { // Paint everything Begin(); TScreen::Singleton->CMPaint(); End(); // Swap OpenGL buffers SDL_GL_SwapWindow(window); // Check for error conditions GLenum gl_error = glGetError(); if(gl_error != GL_NO_ERROR) t_printf("testgl: OpenGL error: %d\n", gl_error); // Print SDL errors const char* sdl_error = SDL_GetError(); if(sdl_error[0] != '\0') { t_printf("testgl: SDL error '%s'\n", sdl_error); SDL_ClearError(); } // Check if there is a pending event SDL_Event event; while(SDL_PollEvent(&event)) { HandleEvent(&event); } } //------------------------------------------------------------------- // Run() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::Run(void) { // Loop until done while(!QuitRequested) { Loop(); } } //------------------------------------------------------------------- // Idle() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::Idle(void) { Loop(); } //------------------------------------------------------------------- // OpenDisplay() // 08-Feb-2004 rzv created //------------------------------------------------------------------- bool TGlServer::OpenDisplay(void) { int done = 0; // Initialize SDL video if(SDL_Init(SDL_INIT_VIDEO) < 0) { t_printf("Couldn't initialize SDL: %s\n",SDL_GetError()); return false; } // tell SDL that the GL drawing is going to be double buffered SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // size of depth buffer SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, BitsPerPixel); // we aren't going to use the stencil buffer SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0); // this and the next three lines set the bits allocated per pixel for the accumulation buffer to 0 SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 0); SDL_GL_SetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, 0); window = SDL_CreateWindow("GUIde", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Width, Height, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(window); if (Fullscreen == true) { // Set video mode SDL_SetWindowFullscreen(window, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP); } // Hide mouse cursor because GUIde will render its own one SDL_ShowCursor(0); // Enable keyboard repeat //SDL_EnableKeyRepeat(500, 30); return true; } //------------------------------------------------------------------- // CloseDisplay() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::CloseDisplay(void) { // Show mouse cursor SDL_ShowCursor(1); SDL_DestroyWindow(window); SDL_Quit(); } //------------------------------------------------------------------- // Begin() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::Begin(void) { glClear(ClearBufferBit); glClearColor(ClearColor[0], ClearColor[1], ClearColor[2], ClearColor[3]); glViewport(0, 0, Width, Height); // Always have filled polygons glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // "An optimum compromise that allows all primitives to be // specified at integer positions, while still ensuring // predictable rasterization, is to translate x and y by 0.375, // as shown in the following code fragment. Such a translation // keeps polygon and pixel image edges safely away from the // centers of pixels, while moving line vertices close enough // to the pixel centers." - Red Book glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Width, Height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.375f, 0.375f, 0.0); glDisable(GL_LIGHTING); glDisable(GL_FOG); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); /* glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); glEnable(GL_CLIP_PLANE2); glEnable(GL_CLIP_PLANE3); */ } //------------------------------------------------------------------- // End() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::End(void) { /* glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); glDisable(GL_CLIP_PLANE2); glDisable(GL_CLIP_PLANE3); */ } //------------------------------------------------------------------- // BeginScene() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::BeginScene(void) { // "An optimum compromise that allows all primitives to be // specified at integer positions, while still ensuring // predictable rasterization, is to translate x and y by 0.375, // as shown in the following code fragment. Such a translation // keeps polygon and pixel image edges safely away from the // centers of pixels, while moving line vertices close enough // to the pixel centers." - Red Book glDisable(GL_LIGHTING); glDisable(GL_FOG); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); /* glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); glEnable(GL_CLIP_PLANE2); glEnable(GL_CLIP_PLANE3); */ glViewport(0, 0, Width, Height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, Width, Height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(0.375f, 0.375f, 0.0); } //------------------------------------------------------------------- // EndScene() // 08-Feb-2004 rzv created //------------------------------------------------------------------- void TGlServer::EndScene(void) { glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); /* glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); glDisable(GL_CLIP_PLANE2); glDisable(GL_CLIP_PLANE3); */ } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
27.190184
99
0.531476
rzvdaniel
2983a8bb5d49c1615ee7837e8d5376d6d3ec7d53
10,346
cpp
C++
Engine/source/app/badWordFilter.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Engine/source/app/badWordFilter.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Engine/source/app/badWordFilter.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "core/strings/stringFunctions.h" #include "console/consoleTypes.h" #include "console/simBase.h" #include "console/engineAPI.h" #include "app/badWordFilter.h" #include "core/module.h" MODULE_BEGIN( BadWordFilter ) MODULE_INIT { BadWordFilter::create(); } MODULE_SHUTDOWN { BadWordFilter::destroy(); } MODULE_END; BadWordFilter *gBadWordFilter = NULL; bool BadWordFilter::filteringEnabled = true; BadWordFilter::BadWordFilter() { VECTOR_SET_ASSOCIATION( filterTables ); dStrcpy(defaultReplaceStr, "knqwrtlzs", 32); filterTables.push_back(new FilterTable); curOffset = 0; } BadWordFilter::~BadWordFilter() { for(U32 i = 0; i < filterTables.size(); i++) delete filterTables[i]; } void BadWordFilter::create() { Con::addVariable("pref::enableBadWordFilter", TypeBool, &filteringEnabled, "@brief If true, the bad word filter will be enabled.\n\n" "@ingroup Game"); gBadWordFilter = new BadWordFilter; gBadWordFilter->addBadWord("shit"); gBadWordFilter->addBadWord("fuck"); gBadWordFilter->addBadWord("cock"); gBadWordFilter->addBadWord("bitch"); gBadWordFilter->addBadWord("cunt"); gBadWordFilter->addBadWord("nigger"); gBadWordFilter->addBadWord("bastard"); gBadWordFilter->addBadWord("dick"); gBadWordFilter->addBadWord("whore"); gBadWordFilter->addBadWord("goddamn"); gBadWordFilter->addBadWord("asshole"); } void BadWordFilter::destroy() { delete gBadWordFilter; gBadWordFilter = NULL; } U8 BadWordFilter::remapTable[257] = "------------------------------------------------OI---------------ABCDEFGHIJKLMNOPQRSTUVWXYZ------ABCDEFGHIJKLMNOPQRSTUVWXYZ-----C--F--TT--S-C-Z-----------S-C-ZY--CLOY-S-CA---R---UT-UP--IO-----AAAAAAACEEEEIIIIDNOOOOOXOUUUUYDBAAAAAAACEEEEIIIIDNOOOOO-OUUUUYDY"; U8 BadWordFilter::randomJunk[MaxBadwordLength+1] = "REMsg rk34n4ksqow;xnskq;KQoaWnZa"; BadWordFilter::FilterTable::FilterTable() { for(U32 i = 0; i < 26; i++) nextState[i] = TerminateNotFound; } bool BadWordFilter::addBadWord(const char *cword) { FilterTable *curFilterTable = filterTables[0]; // prescan the word to see if it has any skip chars const U8 *word = (const U8 *) cword; const U8 *walk = word; if(dStrlen(cword) > MaxBadwordLength) return false; while(*walk) { if(remapTable[*walk] == '-') return false; walk++; } while(*word) { U8 remap = remapTable[*word] - 'A'; U16 state = curFilterTable->nextState[remap]; if(state < TerminateNotFound) { // this character is already in the state table... curFilterTable = filterTables[state]; } else if(state == TerminateFound) { // a subset of this word is already in the table... // exit out. return false; } else if(state == TerminateNotFound) { if(word[1]) { curFilterTable->nextState[remap] = filterTables.size(); filterTables.push_back(new FilterTable); curFilterTable = filterTables[filterTables.size() - 1]; } else curFilterTable->nextState[remap] = TerminateFound; } word++; } return true; } bool BadWordFilter::setDefaultReplaceStr(const char *str) { U32 len = dStrlen(str); if(len < 2 || len >= sizeof(defaultReplaceStr)) return false; dStrcpy(defaultReplaceStr, str, 32); return true; } void BadWordFilter::filterString(char *cstring, const char *replaceStr) { if(!replaceStr) replaceStr = defaultReplaceStr; U8 *string = (U8 *) cstring; U8 *starts[MaxBadwordLength]; U8 *curStart = string; U32 replaceLen = dStrlen(replaceStr); while(*curStart) { FilterTable *curFilterTable = filterTables[0]; S32 index = 0; U8 *walk = curStart; while(*walk) { U8 remap = remapTable[*walk]; if(remap != '-') { starts[index++] = walk; U16 table = curFilterTable->nextState[remap - 'A']; if(table < TerminateNotFound) curFilterTable = filterTables[table]; else if(table == TerminateNotFound) { curStart++; break; } else // terminate found { for(U32 i = 0; i < index; i++) { starts[i][0] = (U8 )replaceStr[curOffset % replaceLen]; curOffset += randomJunk[curOffset & (MaxBadwordLength - 1)]; } curStart = walk + 1; break; } } walk++; } if(!*walk) curStart++; } } bool BadWordFilter::containsBadWords(const char *cstring) { U8 *string = (U8 *) cstring; U8 *curStart = string; while(*curStart) { FilterTable *curFilterTable = filterTables[0]; U8 *walk = curStart; while(*walk) { U8 remap = remapTable[*walk]; if(remap != '-') { U16 table = curFilterTable->nextState[remap - 'A']; if(table < TerminateNotFound) curFilterTable = filterTables[table]; else if(table == TerminateNotFound) { curStart++; break; } else // terminate found return true; } walk++; } if(!*walk) curStart++; } return false; } DefineEngineFunction(addBadWord, bool, (const char* badWord),, "@brief Add a string to the bad word filter\n\n" "The bad word filter is a table containing words which will not be " "displayed in chat windows. Instead, a designated replacement string will be displayed. " "There are already a number of bad words automatically defined.\n\n" "@param badWord Exact text of the word to restrict.\n" "@return True if word was successfully added, false if the word or a subset of it already exists in the table\n" "@see filterString()\n\n" "@tsexample\n" "// In this game, \"Foobar\" is banned\n" "%badWord = \"Foobar\";\n\n" "// Returns true, word was successfully added\n" "addBadWord(%badWord);\n\n" "// Returns false, word has already been added\n" "addBadWord(\"Foobar\");" "@endtsexample\n" "@ingroup Game") { return gBadWordFilter->addBadWord(badWord); } DefineEngineFunction(filterString, const char *, (const char* baseString, const char* replacementChars), (nullAsType<const char*>(), nullAsType<const char*>()), "@brief Replaces the characters in a string with designated text\n\n" "Uses the bad word filter to determine which characters within the string will be replaced.\n\n" "@param baseString The original string to filter.\n" "@param replacementChars A string containing letters you wish to swap in the baseString.\n" "@return The new scrambled string \n" "@see addBadWord()\n" "@see containsBadWords()\n" "@tsexample\n" "// Create the base string, can come from anywhere\n" "%baseString = \"Foobar\";\n\n" "// Create a string of random letters\n" "%replacementChars = \"knqwrtlzs\";\n\n" "// Filter the string\n" "%newString = filterString(%baseString, %replacementChars);\n\n" "// Print the new string to console\n" "echo(%newString);" "@endtsexample\n" "@ingroup Game") { const char *replaceStr = NULL; if(replacementChars) replaceStr = replacementChars; else replaceStr = gBadWordFilter->getDefaultReplaceStr(); dsize_t retLen = dStrlen(baseString) + 1; char *ret = Con::getReturnBuffer(retLen); dStrcpy(ret, baseString, retLen); gBadWordFilter->filterString(ret, replaceStr); return ret; } DefineEngineFunction(containsBadWords, bool, (const char* text),, "@brief Checks to see if text is a bad word\n\n" "The text is considered to be a bad word if it has been added to the bad word filter.\n\n" "@param text Text to scan for bad words\n" "@return True if the text has bad word(s), false if it is clean\n" "@see addBadWord()\n" "@see filterString()\n" "@tsexample\n" "// In this game, \"Foobar\" is banned\n" "%badWord = \"Foobar\";\n\n" "// Add a banned word to the bad word filter\n" "addBadWord(%badWord);\n\n" "// Create the base string, can come from anywhere like user chat\n" "%userText = \"Foobar\";\n\n" "// Create a string of random letters\n" "%replacementChars = \"knqwrtlzs\";\n\n" "// If the text contains a bad word, filter it before printing\n" "// Otherwise print the original text\n" "if(containsBadWords(%userText))\n" "{\n" " // Filter the string\n" " %filteredText = filterString(%userText, %replacementChars);\n\n" " // Print filtered text\n" " echo(%filteredText);\n" "}\n" "else\n" " echo(%userText);\n\n" "@endtsexample\n" "@ingroup Game") { return gBadWordFilter->containsBadWords(text); }
30.976048
295
0.61821
vbillet
2984839bcea56d0f3b6656b7124d96aa192f3f06
1,101
cpp
C++
src/synthetic_workload/src/mt_exec_concurrent_children.cpp
nightduck/ros2_synthetic_workload
520afb02b30e763f3bcec8cef8e831be140eb922
[ "Apache-2.0" ]
null
null
null
src/synthetic_workload/src/mt_exec_concurrent_children.cpp
nightduck/ros2_synthetic_workload
520afb02b30e763f3bcec8cef8e831be140eb922
[ "Apache-2.0" ]
null
null
null
src/synthetic_workload/src/mt_exec_concurrent_children.cpp
nightduck/ros2_synthetic_workload
520afb02b30e763f3bcec8cef8e831be140eb922
[ "Apache-2.0" ]
null
null
null
#include "nodes.hpp" int main(int argc, char const *argv[]) { rclcpp::init(argc, argv); // Measure time to chew cycles on this machine { RCLCPP_INFO(rclcpp::get_logger("global_logger"), "Benchmarking..."); auto clock = rclcpp::Clock(); rclcpp::Time start = clock.now(); uint64_t x = start.nanoseconds(); // Burn time here for(int i = 0; i < 100000000; i++) { x = burn(x); } rclcpp::Duration duration = clock.now() - start; RCLCPP_INFO(rclcpp::get_logger("global_logger"), "This machine runs burn in %.9fns, result %lld", 10*duration.seconds(), x); } rclcpp::executors::MultiThreadedExecutor exec(rclcpp::ExecutorOptions(), 2); auto tmr = std::make_shared<StaggeredPubTimer>(); auto hi = std::make_shared<Sub>("ha", 80ms); auto me = std::make_shared<Sub>("ma", 80ms); auto lo = std::make_shared<Sub>("la", 80ms); exec.add_node(tmr); exec.add_node(hi); exec.add_node(me); exec.add_node(lo); exec.spin(); rclcpp::shutdown(); return 0; }
26.214286
132
0.593097
nightduck
298649a23191026eb9769533e710d8febe7ec77f
175
hpp
C++
src/agl/glsl/function/vector/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/vector/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/vector/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "addition.hpp" #include "division.hpp" #include "multiplication.hpp" #include "perpendicular.hpp" #include "subtraction.hpp" #include "unary_minus.hpp"
19.444444
29
0.771429
the-last-willy
298775ae40fd05efed586600ce96655e5ee2b6c3
9,665
cc
C++
src/compiler/gap-resolver.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
null
null
null
src/compiler/gap-resolver.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
null
null
null
src/compiler/gap-resolver.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/gap-resolver.h" #include <algorithm> #include <set> namespace v8 { namespace internal { namespace compiler { namespace { static constexpr int kFloat32Bit = RepresentationBit(MachineRepresentation::kFloat32); static constexpr int kFloat64Bit = RepresentationBit(MachineRepresentation::kFloat64); // Splits a FP move between two location operands into the equivalent series of // moves between smaller sub-operands, e.g. a double move to two single moves. // This helps reduce the number of cycles that would normally occur under FP // aliasing, and makes swaps much easier to implement. MoveOperands* Split(MoveOperands* move, MachineRepresentation smaller_rep, ParallelMove* moves) { DCHECK(!kSimpleFPAliasing); // Splitting is only possible when the slot size is the same as float size. DCHECK_EQ(kPointerSize, kFloatSize); const LocationOperand& src_loc = LocationOperand::cast(move->source()); const LocationOperand& dst_loc = LocationOperand::cast(move->destination()); MachineRepresentation dst_rep = dst_loc.representation(); DCHECK_NE(smaller_rep, dst_rep); auto src_kind = src_loc.location_kind(); auto dst_kind = dst_loc.location_kind(); int aliases = 1 << (ElementSizeLog2Of(dst_rep) - ElementSizeLog2Of(smaller_rep)); int base = -1; USE(base); DCHECK_EQ(aliases, RegisterConfiguration::Default()->GetAliases( dst_rep, 0, smaller_rep, &base)); int src_index = -1; int slot_size = (1 << ElementSizeLog2Of(smaller_rep)) / kPointerSize; int src_step = 1; if (src_kind == LocationOperand::REGISTER) { src_index = src_loc.register_code() * aliases; } else { src_index = src_loc.index(); // For operands that occupy multiple slots, the index refers to the last // slot. On little-endian architectures, we start at the high slot and use a // negative step so that register-to-slot moves are in the correct order. src_step = -slot_size; } int dst_index = -1; int dst_step = 1; if (dst_kind == LocationOperand::REGISTER) { dst_index = dst_loc.register_code() * aliases; } else { dst_index = dst_loc.index(); dst_step = -slot_size; } // Reuse 'move' for the first fragment. It is not pending. move->set_source(AllocatedOperand(src_kind, smaller_rep, src_index)); move->set_destination(AllocatedOperand(dst_kind, smaller_rep, dst_index)); // Add the remaining fragment moves. for (int i = 1; i < aliases; ++i) { src_index += src_step; dst_index += dst_step; moves->AddMove(AllocatedOperand(src_kind, smaller_rep, src_index), AllocatedOperand(dst_kind, smaller_rep, dst_index)); } // Return the first fragment. return move; } } // namespace void GapResolver::Resolve(ParallelMove* moves) { // Clear redundant moves, and collect FP move representations if aliasing // is non-simple. int reps = 0; for (size_t i = 0; i < moves->size();) { MoveOperands* move = (*moves)[i]; if (move->IsRedundant()) { (*moves)[i] = moves->back(); moves->pop_back(); continue; } i++; if (!kSimpleFPAliasing && move->destination().IsFPRegister()) { reps |= RepresentationBit( LocationOperand::cast(move->destination()).representation()); } } if (!kSimpleFPAliasing) { if (reps && !base::bits::IsPowerOfTwo(reps)) { // Start with the smallest FP moves, so we never encounter smaller moves // in the middle of a cycle of larger moves. if ((reps & kFloat32Bit) != 0) { split_rep_ = MachineRepresentation::kFloat32; for (size_t i = 0; i < moves->size(); ++i) { auto move = (*moves)[i]; if (!move->IsEliminated() && move->destination().IsFloatRegister()) PerformMove(moves, move); } } if ((reps & kFloat64Bit) != 0) { split_rep_ = MachineRepresentation::kFloat64; for (size_t i = 0; i < moves->size(); ++i) { auto move = (*moves)[i]; if (!move->IsEliminated() && move->destination().IsDoubleRegister()) PerformMove(moves, move); } } } split_rep_ = MachineRepresentation::kSimd128; } for (size_t i = 0; i < moves->size(); ++i) { auto move = (*moves)[i]; if (!move->IsEliminated()) PerformMove(moves, move); } } void GapResolver::PerformMove(ParallelMove* moves, MoveOperands* move) { // Each call to this function performs a move and deletes it from the move // graph. We first recursively perform any move blocking this one. We mark a // move as "pending" on entry to PerformMove in order to detect cycles in the // move graph. We use operand swaps to resolve cycles, which means that a // call to PerformMove could change any source operand in the move graph. DCHECK(!move->IsPending()); DCHECK(!move->IsRedundant()); // Clear this move's destination to indicate a pending move. The actual // destination is saved on the side. InstructionOperand source = move->source(); DCHECK(!source.IsInvalid()); // Or else it will look eliminated. InstructionOperand destination = move->destination(); move->SetPending(); // We may need to split moves between FP locations differently. const bool is_fp_loc_move = !kSimpleFPAliasing && destination.IsFPLocationOperand(); // Perform a depth-first traversal of the move graph to resolve dependencies. // Any unperformed, unpending move with a source the same as this one's // destination blocks this one so recursively perform all such moves. for (size_t i = 0; i < moves->size(); ++i) { auto other = (*moves)[i]; if (other->IsEliminated()) continue; if (other->IsPending()) continue; if (other->source().InterferesWith(destination)) { if (is_fp_loc_move && LocationOperand::cast(other->source()).representation() > split_rep_) { // 'other' must also be an FP location move. Break it into fragments // of the same size as 'move'. 'other' is set to one of the fragments, // and the rest are appended to 'moves'. other = Split(other, split_rep_, moves); // 'other' may not block destination now. if (!other->source().InterferesWith(destination)) continue; } // Though PerformMove can change any source operand in the move graph, // this call cannot create a blocking move via a swap (this loop does not // miss any). Assume there is a non-blocking move with source A and this // move is blocked on source B and there is a swap of A and B. Then A and // B must be involved in the same cycle (or they would not be swapped). // Since this move's destination is B and there is only a single incoming // edge to an operand, this move must also be involved in the same cycle. // In that case, the blocking move will be created but will be "pending" // when we return from PerformMove. PerformMove(moves, other); } } // This move's source may have changed due to swaps to resolve cycles and so // it may now be the last move in the cycle. If so remove it. source = move->source(); if (source.EqualsCanonicalized(destination)) { move->Eliminate(); return; } // We are about to resolve this move and don't need it marked as pending, so // restore its destination. move->set_destination(destination); // The move may be blocked on a (at most one) pending move, in which case we // have a cycle. Search for such a blocking move and perform a swap to // resolve it. auto blocker = std::find_if(moves->begin(), moves->end(), [&](MoveOperands* move) { return !move->IsEliminated() && move->source().InterferesWith(destination); }); if (blocker == moves->end()) { // The easy case: This move is not blocked. assembler_->AssembleMove(&source, &destination); move->Eliminate(); return; } // Ensure source is a register or both are stack slots, to limit swap cases. if (source.IsStackSlot() || source.IsFPStackSlot()) { std::swap(source, destination); } assembler_->AssembleSwap(&source, &destination); move->Eliminate(); // Update outstanding moves whose source may now have been moved. if (is_fp_loc_move) { // We may have to split larger moves. for (size_t i = 0; i < moves->size(); ++i) { auto other = (*moves)[i]; if (other->IsEliminated()) continue; if (source.InterferesWith(other->source())) { if (LocationOperand::cast(other->source()).representation() > split_rep_) { other = Split(other, split_rep_, moves); if (!source.InterferesWith(other->source())) continue; } other->set_source(destination); } else if (destination.InterferesWith(other->source())) { if (LocationOperand::cast(other->source()).representation() > split_rep_) { other = Split(other, split_rep_, moves); if (!destination.InterferesWith(other->source())) continue; } other->set_source(source); } } } else { for (auto other : *moves) { if (other->IsEliminated()) continue; if (source.EqualsCanonicalized(other->source())) { other->set_source(destination); } else if (destination.EqualsCanonicalized(other->source())) { other->set_source(source); } } } } } // namespace compiler } // namespace internal } // namespace v8
38.66
80
0.659493
YBApp-Bot
298b6ccaf76b244851bb90ebd22481d388b292b5
2,045
hpp
C++
shared_model/interfaces/iroha_internal/transaction_batch.hpp
e-ivkov/iroha
5fec6c585721ec98a7e2e5220ca5525099e5f670
[ "Apache-2.0" ]
24
2016-09-26T17:11:46.000Z
2020-03-03T13:42:58.000Z
shared_model/interfaces/iroha_internal/transaction_batch.hpp
e-ivkov/iroha
5fec6c585721ec98a7e2e5220ca5525099e5f670
[ "Apache-2.0" ]
11
2016-10-13T10:09:55.000Z
2019-06-13T08:49:11.000Z
shared_model/interfaces/iroha_internal/transaction_batch.hpp
e-ivkov/iroha
5fec6c585721ec98a7e2e5220ca5525099e5f670
[ "Apache-2.0" ]
4
2016-09-27T13:18:28.000Z
2019-08-05T20:47:15.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_TRANSACTION_BATCH_HPP #define IROHA_TRANSACTION_BATCH_HPP #include <boost/optional.hpp> #include "cryptography/hash.hpp" #include "interfaces/base/model_primitive.hpp" #include "interfaces/common_objects/transaction_sequence_common.hpp" #include "interfaces/common_objects/types.hpp" namespace shared_model { namespace interface { /** * Represents collection of transactions, which are to be processed together */ class TransactionBatch : public ModelPrimitive<TransactionBatch> { public: /** * Get transactions list * @return list of transactions from the batch */ virtual const types::SharedTxsCollectionType &transactions() const = 0; // TODO [IR-1874] Akvinikym 16.11.18: rename the field /** * Get the concatenation of reduced hashes as a single hash * @param reduced_hashes collection of reduced hashes * @return concatenated reduced hashes */ virtual const types::HashType &reducedHash() const = 0; /** * Checks if every transaction has quorum signatures * @return true if every transaction has quorum signatures, false * otherwise */ virtual bool hasAllSignatures() const = 0; /** * Add signature to concrete transaction in the batch * @param number_of_tx - number of transaction for inserting signature * @param signed_blob - signed blob of transaction * @param public_key - public key of inserter * @return true if signature has been inserted */ virtual bool addSignature( size_t number_of_tx, const shared_model::crypto::Signed &signed_blob, const shared_model::crypto::PublicKey &public_key) = 0; /// Pretty print the batch contents. std::string toString() const; }; } // namespace interface } // namespace shared_model #endif // IROHA_TRANSACTION_BATCH_HPP
31.461538
80
0.681663
e-ivkov
298b7a8f5e4b8db97cf8c4d8c8efed728fb493fd
261
cpp
C++
lc/st/0015.cpp
Aeon113/Notes
2fd9c9f7a94d79deacd9c6ae3edc13da11cb3a04
[ "BSD-3-Clause" ]
null
null
null
lc/st/0015.cpp
Aeon113/Notes
2fd9c9f7a94d79deacd9c6ae3edc13da11cb3a04
[ "BSD-3-Clause" ]
null
null
null
lc/st/0015.cpp
Aeon113/Notes
2fd9c9f7a94d79deacd9c6ae3edc13da11cb3a04
[ "BSD-3-Clause" ]
null
null
null
class Solution { public: int hammingWeight(uint32_t n) { int res = 0; while (n) { switch(n & 0x3u) { case 0: break; case 1: case 2: ++res; break; default: res += 2; break; } n = (n >> 2u); } return res; } };
10.875
32
0.478927
Aeon113
298cda02a2bf49627a599618711396345ad1b60a
7,055
cpp
C++
Source/Readers/ExperimentalHTKMLFReader/MLFDataDeserializer.cpp
Asahi300/aisample
fd5877eb06a594b6699b04342a8d95782e8f6e6e
[ "RSA-MD" ]
1
2019-04-22T09:08:58.000Z
2019-04-22T09:08:58.000Z
Source/Readers/ExperimentalHTKMLFReader/MLFDataDeserializer.cpp
JamesLinus/CNTK
2854d878cfff08ba426e2387f087143f5a81e0a1
[ "RSA-MD" ]
null
null
null
Source/Readers/ExperimentalHTKMLFReader/MLFDataDeserializer.cpp
JamesLinus/CNTK
2854d878cfff08ba426e2387f087143f5a81e0a1
[ "RSA-MD" ]
null
null
null
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #include "stdafx.h" #include "MLFDataDeserializer.h" #include "ConfigHelper.h" #include "../HTKMLFReader/htkfeatio.h" #include "../HTKMLFReader/msra_mgram.h" #include "latticearchive.h" namespace Microsoft { namespace MSR { namespace CNTK { static float s_oneFloat = 1.0; static double s_oneDouble = 1.0; // Currently we only have a single mlf chunk that contains a vector of all labels. // TODO: This will be changed in the future to work only on a subset of chunks // at each point in time. class MLFDataDeserializer::MLFChunk : public Chunk { MLFDataDeserializer* m_parent; public: MLFChunk(MLFDataDeserializer* parent) : m_parent(parent) {} virtual std::vector<SequenceDataPtr> GetSequence(size_t sequenceId) override { return m_parent->GetSequenceById(sequenceId); } }; // Inner class for an utterance. struct MLFUtterance : SequenceDescription { size_t m_sequenceStart; }; MLFDataDeserializer::MLFDataDeserializer(CorpusDescriptorPtr corpus, const ConfigParameters& labelConfig, const std::wstring& name) { bool frameMode = labelConfig.Find("frameMode", "true"); if (!frameMode) { LogicError("Currently only reader only supports fram mode. Please check your configuration."); } ConfigHelper config(labelConfig); config.CheckLabelType(); size_t dimension = config.GetLabelDimension(); // TODO: Similarly to the old reader, currently we assume all Mlfs will have same root name (key) // restrict MLF reader to these files--will make stuff much faster without having to use shortened input files // TODO: currently we do not use symbol and word tables. const msra::lm::CSymbolSet* wordTable = nullptr; std::unordered_map<const char*, int>* symbolTable = nullptr; std::vector<std::wstring> mlfPaths = config.GetMlfPaths(); std::wstring stateListPath = static_cast<std::wstring>(labelConfig(L"labelMappingFile", L"")); // TODO: Currently we still use the old IO module. This will be refactored later. const double htkTimeToFrame = 100000.0; // default is 10ms msra::asr::htkmlfreader<msra::asr::htkmlfentry, msra::lattices::lattice::htkmlfwordsequence> labels(mlfPaths, std::set<wstring>(), stateListPath, wordTable, symbolTable, htkTimeToFrame); // Make sure 'msra::asr::htkmlfreader' type has a move constructor static_assert( std::is_move_constructible< msra::asr::htkmlfreader<msra::asr::htkmlfentry, msra::lattices::lattice::htkmlfwordsequence>>::value, "Type 'msra::asr::htkmlfreader' should be move constructible!"); m_elementType = config.GetElementType(); MLFUtterance description; description.m_isValid = true; size_t totalFrames = 0; for (const auto& l : labels) { description.m_key.major = l.first; const auto& utterance = l.second; description.m_sequenceStart = m_classIds.size(); description.m_isValid = true; size_t numberOfFrames = 0; foreach_index(i, utterance) { const auto& timespan = utterance[i]; if ((i == 0 && timespan.firstframe != 0) || (i > 0 && utterance[i - 1].firstframe + utterance[i - 1].numframes != timespan.firstframe)) { RuntimeError("Labels are not in the consecutive order MLF in label set: %ls", l.first.c_str()); } if (timespan.classid >= dimension) { RuntimeError("Class id %d exceeds the model output dimension %d.", (int)timespan.classid,(int)dimension); } if (timespan.classid != static_cast<msra::dbn::CLASSIDTYPE>(timespan.classid)) { RuntimeError("CLASSIDTYPE has too few bits"); } for (size_t t = timespan.firstframe; t < timespan.firstframe + timespan.numframes; t++) { m_classIds.push_back(timespan.classid); numberOfFrames++; } } description.m_numberOfSamples = numberOfFrames; totalFrames += numberOfFrames; m_utteranceIndex.push_back(m_frames.size()); m_keyToSequence[description.m_key.major] = m_utteranceIndex.size() - 1; MLFFrame f; f.m_chunkId = 0; f.m_numberOfSamples = 1; f.m_key.major = description.m_key.major; f.m_isValid = description.m_isValid; for (size_t k = 0; k < description.m_numberOfSamples; ++k) { f.m_id = m_frames.size(); f.m_key.minor = k; f.m_index = description.m_sequenceStart + k; m_frames.push_back(f); m_sequences.push_back(&m_frames[f.m_id]); } } m_sequences.reserve(m_frames.size()); for (int i = 0; i < m_frames.size(); ++i) { m_sequences.push_back(&m_frames[i]); } fprintf(stderr, "MLFDataDeserializer::MLFDataDeserializer: read %d sequences\n", (int)m_sequences.size()); fprintf(stderr, "MLFDataDeserializer::MLFDataDeserializer: read %d utterances\n", (int)m_keyToSequence.size()); StreamDescriptionPtr stream = std::make_shared<StreamDescription>(); stream->m_id = 0; stream->m_name = name; stream->m_sampleLayout = std::make_shared<TensorShape>(dimension); stream->m_storageType = StorageType::sparse_csc; stream->m_elementType = m_elementType; m_streams.push_back(stream); } const SequenceDescriptions& MLFDataDeserializer::GetSequenceDescriptions() const { return m_sequences; } std::vector<StreamDescriptionPtr> MLFDataDeserializer::GetStreamDescriptions() const { return m_streams; } size_t MLFDataDeserializer::GetTotalNumberOfChunks() { // Currently all mlf data is in memory. return 1; } ChunkPtr MLFDataDeserializer::GetChunk(size_t chunkId) { UNUSED(chunkId); assert(chunkId == 0); return std::make_shared<MLFChunk>(this); } std::vector<SequenceDataPtr> MLFDataDeserializer::GetSequenceById(size_t sequenceId) { size_t label = m_classIds[m_frames[sequenceId].m_index]; SparseSequenceDataPtr r = std::make_shared<SparseSequenceData>(); r->m_indices.resize(1); r->m_indices[0] = std::vector<size_t>{ label }; if (m_elementType == ElementType::tfloat) { r->m_data = &s_oneFloat; } else { assert(m_elementType == ElementType::tdouble); r->m_data = &s_oneDouble; } return std::vector<SequenceDataPtr> { r }; } static SequenceDescription s_InvalidSequence { 0, 0, 0, false }; const SequenceDescription* MLFDataDeserializer::GetSequenceDescriptionByKey(const KeyType& key) { auto sequenceId = m_keyToSequence.find(key.major); if (sequenceId == m_keyToSequence.end()) { return &s_InvalidSequence; } size_t index = m_utteranceIndex[sequenceId->second] + key.minor; return m_sequences[index]; } }}}
33.755981
190
0.668887
Asahi300
298e6ba25051d6fa4fe9e2f4467fb3ef4bf31faf
166
cpp
C++
Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/ControlChannelTrigger HTTP client sample/C++/HttpClientTransportHelper/pch.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/ControlChannelTrigger HTTP client sample/C++/HttpClientTransportHelper/pch.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/ControlChannelTrigger HTTP client sample/C++/HttpClientTransportHelper/pch.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // // pch.cpp // Include the standard header and generate the precompiled header. // #include "pch.h"
18.444444
67
0.716867
zzgchina888
298f4da94fa6892f614f1dec73429de7817453f9
1,035
cpp
C++
casbin/ip_parser/parser/parseIPv4.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
casbin/ip_parser/parser/parseIPv4.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
casbin/ip_parser/parser/parseIPv4.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
#include "casbin/pch.h" #ifndef PARSEIPV4_CPP #define PARSEIPV4_CPP #include "casbin/ip_parser/parser/parseIPv4.h" namespace casbin { IP parseIPv4(std::string_view s) { std::vector<byte> pb(IP ::IPv4len, 0); IP ipv4; for (int i = 0; i < IP ::IPv4len; i++) { if (s.length() == 0) { // Missing octets. ipv4.isLegal = false; return ipv4; } if (i > 0) { if (s[0] != '.') { ipv4.isLegal = false; return ipv4; } s = s.substr(1, s.length() - 1); } std::pair<int, int> p = dtoi(s); if ((p.first >= big || p.second == 0) || p.first > 0xFF) { ipv4.isLegal = false; return ipv4; } s = s.substr(p.second, s.length() - p.second); pb[i] = p.first; } if (s.length() != 0) { ipv4.isLegal = false; return ipv4; } return IPv4(pb[0], pb[1], pb[2], pb[3]); } } // namespace casbin #endif // PARSEIPV4_CPP
23.522727
66
0.470531
sheny1xuan
299359f19c1ab43248bd0c342ed5a56de48cd833
10,064
hh
C++
hackt_docker/hackt/src/AST/PRS.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/AST/PRS.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/AST/PRS.hh
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "AST/PRS.hh" PRS-specific syntax tree classes. $Id: PRS.hh,v 1.15 2011/02/08 02:06:44 fang Exp $ This used to be the following before it was renamed: Id: art_parser_prs.h,v 1.15.12.1 2005/12/11 00:45:09 fang Exp */ #ifndef __HAC_AST_PRS_H__ #define __HAC_AST_PRS_H__ #include "AST/common.hh" #include "AST/PRS_fwd.hh" #include "AST/expr_base.hh" #include "AST/lang.hh" #include "AST/attribute.hh" #include "util/STL/pair_fwd.hh" #include "util/memory/count_ptr.hh" namespace HAC { namespace entity { // be careful of namespaces... class generic_attribute; namespace PRS { class rule; class rule_conditional; class precharge_expr; } } namespace parser { class inst_ref_expr_list; struct expr_attr_list; /** This is the namespace for the PRS sub-language. */ namespace PRS { using util::memory::count_ptr; //============================================================================= // local forward declarations class rule; class body; //============================================================================= /// a single production rule class body_item { public: typedef void return_type; protected: // no members public: body_item(); virtual ~body_item(); virtual ostream& what(ostream& o) const = 0; virtual line_position leftmost(void) const = 0; virtual line_position rightmost(void) const = 0; #define PRS_ITEM_CHECK_PROTO \ body_item::return_type \ check_rule(context&) const virtual PRS_ITEM_CHECK_PROTO = 0; }; // end class body_item //============================================================================= /** Pairs a literal instance reference with an optional list of parameters. May need to extract single unqualified ID for PRS macro. Need to derive the interface from inst_ref_expr to be able to use as parts of expression trees. */ class literal : public inst_ref_expr { typedef inst_ref_expr::meta_return_type meta_return_type; // typedef inst_ref_expr::nonmeta_return_type nonmeta_return_type; /// not const, b/c we may wish to transfer it to macro excl_ptr<inst_ref_expr> ref; /// not const, b/c we may wish to transfer it to macro excl_ptr<const expr_attr_list> params; /** If true this refers to an internal node, and should use a different lookup. */ bool internal; public: explicit literal(inst_ref_expr*); explicit literal(excl_ptr<inst_ref_expr>&); literal(inst_ref_expr*, const expr_attr_list*); ~literal(); #if 0 excl_ptr<inst_ref_expr>& release_reference(void) { return ref; } #endif excl_ptr<const token_identifier> extract_identifier(void); excl_ptr<const expr_attr_list> extract_parameters(void); void attach_parameters(const expr_attr_list*); void mark_internal(void) { internal = true; } ostream& what(ostream&) const; ostream& dump(ostream&) const; line_position leftmost(void) const; line_position rightmost(void) const; /// This wraps a call to ref's check, and also attaches/checks params CHECK_META_REFERENCE_PROTO; /// this is not actually used CHECK_NONMETA_REFERENCE_PROTO; EXPAND_CONST_REFERENCE_PROTO; // overrides base prs_literal_ptr_type check_prs_literal(const context&) const; prs_literal_ptr_type check_prs_rhs(context&) const; // no need to override the following, because they all defer to // the above two (pure virtual) methods. // CHECK_META_EXPR_PROTO // CHECK_NONMETA_EXPR_PROTO // CHECK_GENERIC_PROTO // CHECK_PRS_EXPR_PROTO protected: typedef entity::generic_attribute attribute_type; public: // so macro::check_prs_rule can use this static attribute_type check_literal_attribute(const generic_attribute&, const context&); }; // end class literal //============================================================================= /** Store precharge expression. */ class precharge { const excl_ptr<const node_position> dir; const excl_ptr<const expr> pchg_expr; public: precharge(const node_position*, const expr*); ~precharge(); ostream& what(ostream&) const; line_position leftmost(void) const; line_position rightmost(void) const; entity::PRS::precharge_expr check_prs_expr(context& c) const; // CHECK_PRS_EXPR_PROTO; }; // end class precharge //============================================================================= /** Single production rule. */ class rule : public body_item { public: typedef entity::generic_attribute attribute_type; protected: const excl_ptr<const generic_attribute_list> attribs; const excl_ptr<const expr> guard; const excl_ptr<const char_punctuation_type> arrow; const excl_ptr<const literal> r; const excl_ptr<const char_punctuation_type> dir; public: rule(const generic_attribute_list*, const expr* g, const char_punctuation_type* a, literal* rhs, const char_punctuation_type* d); ~rule(); ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; PRS_ITEM_CHECK_PROTO; protected: static attribute_type check_prs_attribute(const generic_attribute&, context&); }; // end class rule //============================================================================= /** Repetition of production rules in a loop. */ class loop : public body_item { protected: const excl_ptr<const char_punctuation_type> lp; const excl_ptr<const token_identifier> index; const excl_ptr<const range> bounds; const excl_ptr<const rule_list> rules; const excl_ptr<const char_punctuation_type> rp; public: loop(const char_punctuation_type* l, const token_identifier* id, const range* b, const rule_list* rl, const char_punctuation_type* r); ~loop(); ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; PRS_ITEM_CHECK_PROTO; }; // end class loop //============================================================================= /** Guarded PRS body clause. */ class guarded_body { const excl_ptr<const expr> guard; const excl_ptr<const char_punctuation_type> arrow; const excl_ptr<const rule_list> rules; public: typedef void return_type; public: guarded_body(const expr*, const char_punctuation_type*, const rule_list*); ~guarded_body(); ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; return_type check_clause(context&) const; }; // end class guarded_body //============================================================================= /** Class for wrapping production rules inside conditionals. */ class conditional : public body_item { const excl_ptr<const guarded_prs_list> gp; public: // explicit conditional(const guarded_prs_list*); ~conditional(); ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; PRS_ITEM_CHECK_PROTO; }; // end class conditional //============================================================================= /** temporary hacks: PRS-macros look like function calls. The programmer can design these to do whatever. */ class macro : public body_item { // these are rule-style attributes, we currently ignore const excl_ptr<const generic_attribute_list> attribs; excl_ptr<const token_identifier> name; // attributes also go here excl_ptr<const expr_attr_list> params; const excl_ptr<const inst_ref_expr_list> args; public: macro(const generic_attribute_list*, literal*, const inst_ref_expr_list*); ~macro(); ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; PRS_ITEM_CHECK_PROTO; }; // end class macro //============================================================================= /** Collection of production rules. Now is also a body_item because of nested bodies. */ class body : public language_body, public body_item { protected: const excl_ptr<const inst_ref_expr_list> supplies; const excl_ptr<const rule_list> rules; public: body(const generic_keyword_type* t, const inst_ref_expr_list*, const rule_list* r); virtual ~body(); virtual ostream& what(ostream& o) const; line_position leftmost(void) const; line_position rightmost(void) const; // needs the return-type of language-body // virtual? ROOT_CHECK_PROTO; PRS_ITEM_CHECK_PROTO; protected: bool __check_rules(context&) const; }; // end class body //============================================================================= /** Structure for grouping rules into subcircuits. */ class subcircuit : public body { /// really, only use a name/string parameter for now const excl_ptr<const expr_list> params; public: subcircuit(const generic_keyword_type*, const expr_list*, const rule_list*); ~subcircuit(); ostream& what(ostream& o) const; using body::leftmost; using body::rightmost; // needs the return-type of language-body ROOT_CHECK_PROTO; PRS_ITEM_CHECK_PROTO; }; // end class subcircuit //============================================================================= /** Shortcut loop of AND or OR operation. Don't know if this will be useful outside of the PRS context. */ class op_loop : public expr { protected: const excl_ptr<const char_punctuation_type> lp; const excl_ptr<const char_punctuation_type> op; const excl_ptr<const token_identifier> index; const excl_ptr<const range> bounds; const excl_ptr<const expr> ex; const excl_ptr<const char_punctuation_type> rp; public: op_loop(const char_punctuation_type* l, const char_punctuation_type* o, const token_identifier* id, const range* b, const expr* e, const char_punctuation_type* r); ~op_loop(); ostream& what(ostream& o) const; ostream& dump(ostream&) const; line_position leftmost(void) const; line_position rightmost(void) const; CHECK_META_EXPR_PROTO; CHECK_NONMETA_EXPR_PROTO; CHECK_PRS_EXPR_PROTO; }; // end class op_loop //============================================================================= } // end namespace PRS } // end namespace parser } // end namespace HAC #endif // __HAC_AST_PRS_H__
22.61573
79
0.673688
broken-wheel
29948fd48437b065114b31d2b2d9f42f89e9ae35
2,202
hh
C++
maxutils/maxbase/include/maxbase/pam_utils.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
maxutils/maxbase/include/maxbase/pam_utils.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
maxutils/maxbase/include/maxbase/pam_utils.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2026-01-04 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxbase/ccdefs.hh> #include <string> namespace maxbase { class PamResult { public: enum class Result { SUCCESS, WRONG_USER_PW, /**< Username or password was wrong */ ACCOUNT_INVALID, /**< pam_acct_mgmt returned error */ MISC_ERROR /**< Miscellaneous error */ }; Result type {Result::MISC_ERROR}; std::string error; }; /** * Check if the user & password can log into the given PAM service. This function will block until the * operation completes. * * @param user Username * @param password Password * @param service Which PAM service is the user logging to * @param expected_msg The first expected message from the PAM authentication system. * Typically "Password: ". If set to empty, the message is not checked. * @return A result struct with the result and an error message. */ PamResult pam_authenticate(const std::string& user, const std::string& password, const std::string& service, const std::string& expected_msg = "Password: "); /** * Check if the user & password can log into the given PAM service. This function will block until the * operation completes. * * @param user Username * @param password Password * @param client_remote Client address, used for logging * @param service Which PAM service is the user logging to * @param expected_msg The first expected message from the PAM authentication system. * Typically "Password: ". If set to empty, the message is not checked. * @return A result struct with the result and an error message. */ PamResult pam_authenticate(const std::string& user, const std::string& password, const std::string& client_remote, const std::string& service, const std::string& expected_msg); }
33.876923
104
0.698002
mariadb-ThienLy
2994964070c06bf1431bce650253ff5235b584f0
79,825
cpp
C++
external/vulkancts/modules/vulkan/renderpass/vktRenderPassMultisampleTests.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
1
2021-02-25T09:06:00.000Z
2021-02-25T09:06:00.000Z
external/vulkancts/modules/vulkan/renderpass/vktRenderPassMultisampleTests.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/renderpass/vktRenderPassMultisampleTests.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2017 Google Inc. * * 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 * \brief Tests for render passses with multisample attachments *//*--------------------------------------------------------------------*/ #include "vktRenderPassMultisampleTests.hpp" #include "vktRenderPassTestsUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vktTestGroupUtil.hpp" #include "vkDefs.hpp" #include "vkDeviceUtil.hpp" #include "vkImageUtil.hpp" #include "vkMemUtil.hpp" #include "vkPlatform.hpp" #include "vkPrograms.hpp" #include "vkQueryUtil.hpp" #include "vkRef.hpp" #include "vkRefUtil.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkObjUtil.hpp" #include "tcuFloat.hpp" #include "tcuImageCompare.hpp" #include "tcuFormatUtil.hpp" #include "tcuMaybe.hpp" #include "tcuResultCollector.hpp" #include "tcuTestLog.hpp" #include "tcuTextureUtil.hpp" #include "tcuVectorUtil.hpp" #include "deUniquePtr.hpp" #include "deSharedPtr.hpp" using namespace vk; using tcu::BVec4; using tcu::IVec2; using tcu::IVec4; using tcu::UVec2; using tcu::UVec4; using tcu::Vec2; using tcu::Vec4; using tcu::Maybe; using tcu::just; using tcu::nothing; using tcu::ConstPixelBufferAccess; using tcu::PixelBufferAccess; using tcu::TestLog; using std::pair; using std::string; using std::vector; typedef de::SharedPtr<vk::Unique<VkImage> > VkImageSp; typedef de::SharedPtr<vk::Unique<VkImageView> > VkImageViewSp; typedef de::SharedPtr<vk::Unique<VkBuffer> > VkBufferSp; typedef de::SharedPtr<vk::Unique<VkPipeline> > VkPipelineSp; namespace vkt { namespace { using namespace renderpass; enum { MAX_COLOR_ATTACHMENT_COUNT = 4u }; template<typename T> de::SharedPtr<T> safeSharedPtr (T* ptr) { try { return de::SharedPtr<T>(ptr); } catch (...) { delete ptr; throw; } } VkImageAspectFlags getImageAspectFlags (VkFormat vkFormat) { const tcu::TextureFormat format (mapVkFormat(vkFormat)); const bool hasDepth (tcu::hasDepthComponent(format.order)); const bool hasStencil (tcu::hasStencilComponent(format.order)); if (hasDepth || hasStencil) { return (hasDepth ? VK_IMAGE_ASPECT_DEPTH_BIT : (VkImageAspectFlagBits)0u) | (hasStencil ? VK_IMAGE_ASPECT_STENCIL_BIT : (VkImageAspectFlagBits)0u); } else return VK_IMAGE_ASPECT_COLOR_BIT; } void bindBufferMemory (const DeviceInterface& vk, VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memOffset) { VK_CHECK(vk.bindBufferMemory(device, buffer, mem, memOffset)); } void bindImageMemory (const DeviceInterface& vk, VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memOffset) { VK_CHECK(vk.bindImageMemory(device, image, mem, memOffset)); } de::MovePtr<Allocation> createBufferMemory (const DeviceInterface& vk, VkDevice device, Allocator& allocator, VkBuffer buffer) { de::MovePtr<Allocation> allocation (allocator.allocate(getBufferMemoryRequirements(vk, device, buffer), MemoryRequirement::HostVisible)); bindBufferMemory(vk, device, buffer, allocation->getMemory(), allocation->getOffset()); return allocation; } de::MovePtr<Allocation> createImageMemory (const DeviceInterface& vk, VkDevice device, Allocator& allocator, VkImage image) { de::MovePtr<Allocation> allocation (allocator.allocate(getImageMemoryRequirements(vk, device, image), MemoryRequirement::Any)); bindImageMemory(vk, device, image, allocation->getMemory(), allocation->getOffset()); return allocation; } Move<VkImage> createImage (const DeviceInterface& vk, VkDevice device, VkImageCreateFlags flags, VkImageType imageType, VkFormat format, VkExtent3D extent, deUint32 mipLevels, deUint32 arrayLayers, VkSampleCountFlagBits samples, VkImageTiling tiling, VkImageUsageFlags usage, VkSharingMode sharingMode, deUint32 queueFamilyCount, const deUint32* pQueueFamilyIndices, VkImageLayout initialLayout) { const VkImageCreateInfo pCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, DE_NULL, flags, imageType, format, extent, mipLevels, arrayLayers, samples, tiling, usage, sharingMode, queueFamilyCount, pQueueFamilyIndices, initialLayout }; return createImage(vk, device, &pCreateInfo); } Move<VkImageView> createImageView (const DeviceInterface& vk, VkDevice device, VkImageViewCreateFlags flags, VkImage image, VkImageViewType viewType, VkFormat format, VkComponentMapping components, VkImageSubresourceRange subresourceRange) { const VkImageViewCreateInfo pCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, DE_NULL, flags, image, viewType, format, components, subresourceRange, }; return createImageView(vk, device, &pCreateInfo); } Move<VkImage> createImage (const InstanceInterface& vki, VkPhysicalDevice physicalDevice, const DeviceInterface& vkd, VkDevice device, VkFormat vkFormat, VkSampleCountFlagBits sampleCountBit, VkImageUsageFlags usage, deUint32 width, deUint32 height) { try { const tcu::TextureFormat format (mapVkFormat(vkFormat)); const VkImageType imageType (VK_IMAGE_TYPE_2D); const VkImageTiling imageTiling (VK_IMAGE_TILING_OPTIMAL); const VkFormatProperties formatProperties (getPhysicalDeviceFormatProperties(vki, physicalDevice, vkFormat)); const VkImageFormatProperties imageFormatProperties (getPhysicalDeviceImageFormatProperties(vki, physicalDevice, vkFormat, imageType, imageTiling, usage, 0u)); const VkExtent3D imageExtent = { width, height, 1u }; if ((tcu::hasDepthComponent(format.order) || tcu::hasStencilComponent(format.order)) && (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) == 0) TCU_THROW(NotSupportedError, "Format can't be used as depth stencil attachment"); if (!(tcu::hasDepthComponent(format.order) || tcu::hasStencilComponent(format.order)) && (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) == 0) TCU_THROW(NotSupportedError, "Format can't be used as color attachment"); if (imageFormatProperties.maxExtent.width < imageExtent.width || imageFormatProperties.maxExtent.height < imageExtent.height || ((imageFormatProperties.sampleCounts & sampleCountBit) == 0)) { TCU_THROW(NotSupportedError, "Image type not supported"); } return createImage(vkd, device, 0u, imageType, vkFormat, imageExtent, 1u, 1u, sampleCountBit, imageTiling, usage, VK_SHARING_MODE_EXCLUSIVE, 0u, DE_NULL, VK_IMAGE_LAYOUT_UNDEFINED); } catch (const vk::Error& error) { if (error.getError() == VK_ERROR_FORMAT_NOT_SUPPORTED) TCU_THROW(NotSupportedError, "Image format not supported"); throw; } } Move<VkImageView> createImageAttachmentView (const DeviceInterface& vkd, VkDevice device, VkImage image, VkFormat format, VkImageAspectFlags aspect) { const VkImageSubresourceRange range = { aspect, 0u, 1u, 0u, 1u }; return createImageView(vkd, device, 0u, image, VK_IMAGE_VIEW_TYPE_2D, format, makeComponentMappingRGBA(), range); } Move<VkImageView> createSrcPrimaryInputImageView (const DeviceInterface& vkd, VkDevice device, VkImage image, VkFormat format, VkImageAspectFlags aspect) { const VkImageSubresourceRange range = { aspect == (VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT) ? (VkImageAspectFlags)VK_IMAGE_ASPECT_DEPTH_BIT : aspect, 0u, 1u, 0u, 1u }; return createImageView(vkd, device, 0u, image, VK_IMAGE_VIEW_TYPE_2D, format, makeComponentMappingRGBA(), range); } Move<VkImageView> createSrcSecondaryInputImageView (const DeviceInterface& vkd, VkDevice device, VkImage image, VkFormat format, VkImageAspectFlags aspect) { if (aspect == (VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT)) { const VkImageSubresourceRange range = { VK_IMAGE_ASPECT_STENCIL_BIT, 0u, 1u, 0u, 1u }; return createImageView(vkd, device, 0u, image, VK_IMAGE_VIEW_TYPE_2D, format, makeComponentMappingRGBA(), range); } else return Move<VkImageView>(); } VkDeviceSize getPixelSize (VkFormat vkFormat) { const tcu::TextureFormat format (mapVkFormat(vkFormat)); return format.getPixelSize(); } Move<VkBuffer> createBuffer (const DeviceInterface& vkd, VkDevice device, VkFormat format, deUint32 width, deUint32 height) { const VkBufferUsageFlags bufferUsage (VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); const VkDeviceSize pixelSize (getPixelSize(format)); const VkBufferCreateInfo createInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, DE_NULL, 0u, width * height * pixelSize, bufferUsage, VK_SHARING_MODE_EXCLUSIVE, 0u, DE_NULL }; return createBuffer(vkd, device, &createInfo); } VkSampleCountFlagBits sampleCountBitFromomSampleCount (deUint32 count) { switch (count) { case 1: return VK_SAMPLE_COUNT_1_BIT; case 2: return VK_SAMPLE_COUNT_2_BIT; case 4: return VK_SAMPLE_COUNT_4_BIT; case 8: return VK_SAMPLE_COUNT_8_BIT; case 16: return VK_SAMPLE_COUNT_16_BIT; case 32: return VK_SAMPLE_COUNT_32_BIT; case 64: return VK_SAMPLE_COUNT_64_BIT; default: DE_FATAL("Invalid sample count"); return (VkSampleCountFlagBits)(0x1u << count); } } std::vector<VkImageSp> createMultisampleImages (const InstanceInterface& vki, VkPhysicalDevice physicalDevice, const DeviceInterface& vkd, VkDevice device, VkFormat format, deUint32 sampleCount, deUint32 width, deUint32 height) { std::vector<VkImageSp> images (sampleCount); for (size_t imageNdx = 0; imageNdx < images.size(); imageNdx++) images[imageNdx] = safeSharedPtr(new vk::Unique<VkImage>(createImage(vki, physicalDevice, vkd, device, format, sampleCountBitFromomSampleCount(sampleCount), VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, width, height))); return images; } std::vector<VkImageSp> createSingleSampleImages (const InstanceInterface& vki, VkPhysicalDevice physicalDevice, const DeviceInterface& vkd, VkDevice device, VkFormat format, deUint32 sampleCount, deUint32 width, deUint32 height) { std::vector<VkImageSp> images (sampleCount); for (size_t imageNdx = 0; imageNdx < images.size(); imageNdx++) images[imageNdx] = safeSharedPtr(new vk::Unique<VkImage>(createImage(vki, physicalDevice, vkd, device, format, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, width, height))); return images; } std::vector<de::SharedPtr<Allocation> > createImageMemory (const DeviceInterface& vkd, VkDevice device, Allocator& allocator, const std::vector<VkImageSp> images) { std::vector<de::SharedPtr<Allocation> > memory (images.size()); for (size_t memoryNdx = 0; memoryNdx < memory.size(); memoryNdx++) memory[memoryNdx] = safeSharedPtr(createImageMemory(vkd, device, allocator, **images[memoryNdx]).release()); return memory; } std::vector<VkImageViewSp> createImageAttachmentViews (const DeviceInterface& vkd, VkDevice device, const std::vector<VkImageSp>& images, VkFormat format, VkImageAspectFlagBits aspect) { std::vector<VkImageViewSp> views (images.size()); for (size_t imageNdx = 0; imageNdx < images.size(); imageNdx++) views[imageNdx] = safeSharedPtr(new vk::Unique<VkImageView>(createImageAttachmentView(vkd, device, **images[imageNdx], format, aspect))); return views; } std::vector<VkBufferSp> createBuffers (const DeviceInterface& vkd, VkDevice device, VkFormat format, deUint32 sampleCount, deUint32 width, deUint32 height) { std::vector<VkBufferSp> buffers (sampleCount); for (size_t bufferNdx = 0; bufferNdx < buffers.size(); bufferNdx++) buffers[bufferNdx] = safeSharedPtr(new vk::Unique<VkBuffer>(createBuffer(vkd, device, format, width, height))); return buffers; } std::vector<de::SharedPtr<Allocation> > createBufferMemory (const DeviceInterface& vkd, VkDevice device, Allocator& allocator, const std::vector<VkBufferSp> buffers) { std::vector<de::SharedPtr<Allocation> > memory (buffers.size()); for (size_t memoryNdx = 0; memoryNdx < memory.size(); memoryNdx++) memory[memoryNdx] = safeSharedPtr(createBufferMemory(vkd, device, allocator, **buffers[memoryNdx]).release()); return memory; } template<typename AttachmentDesc, typename AttachmentRef, typename SubpassDesc, typename SubpassDep, typename RenderPassCreateInfo> Move<VkRenderPass> createRenderPass (const DeviceInterface& vkd, VkDevice device, VkFormat srcFormat, VkFormat dstFormat, deUint32 sampleCount, RenderPassType renderPassType) { const VkSampleCountFlagBits samples (sampleCountBitFromomSampleCount(sampleCount)); const deUint32 splitSubpassCount (deDivRoundUp32(sampleCount, MAX_COLOR_ATTACHMENT_COUNT)); const tcu::TextureFormat format (mapVkFormat(srcFormat)); const bool isDepthStencilFormat (tcu::hasDepthComponent(format.order) || tcu::hasStencilComponent(format.order)); vector<SubpassDesc> subpasses; vector<vector<AttachmentRef> > dstAttachmentRefs (splitSubpassCount); vector<vector<AttachmentRef> > dstResolveAttachmentRefs (splitSubpassCount); vector<AttachmentDesc> attachments; vector<SubpassDep> dependencies; const AttachmentRef srcAttachmentRef // VkAttachmentReference || VkAttachmentReference2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // deUint32 attachment; || deUint32 attachment; isDepthStencilFormat // VkImageLayout layout; || VkImageLayout layout; ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 0u // || VkImageAspectFlags aspectMask; ); const AttachmentRef srcAttachmentInputRef // VkAttachmentReference || VkAttachmentReference2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // deUint32 attachment; || deUint32 attachment; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, // VkImageLayout layout; || VkImageLayout layout; (renderPassType == RENDERPASS_TYPE_RENDERPASS2) // || VkImageAspectFlags aspectMask; ? getImageAspectFlags(srcFormat) : 0u ); { const AttachmentDesc srcAttachment // VkAttachmentDescription || VkAttachmentDescription2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // VkAttachmentDescriptionFlags flags; || VkAttachmentDescriptionFlags flags; srcFormat, // VkFormat format; || VkFormat format; samples, // VkSampleCountFlagBits samples; || VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp loadOp; || VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp storeOp; || VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; || VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; || VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; || VkImageLayout initialLayout; VK_IMAGE_LAYOUT_GENERAL // VkImageLayout finalLayout; || VkImageLayout finalLayout; ); attachments.push_back(srcAttachment); } for (deUint32 splitSubpassIndex = 0; splitSubpassIndex < splitSubpassCount; splitSubpassIndex++) { for (deUint32 sampleNdx = 0; sampleNdx < de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, sampleCount - splitSubpassIndex * MAX_COLOR_ATTACHMENT_COUNT); sampleNdx++) { // Multisample color attachment { const AttachmentDesc dstAttachment // VkAttachmentDescription || VkAttachmentDescription2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // VkAttachmentDescriptionFlags flags; || VkAttachmentDescriptionFlags flags; dstFormat, // VkFormat format; || VkFormat format; samples, // VkSampleCountFlagBits samples; || VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp loadOp; || VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp storeOp; || VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; || VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; || VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; || VkImageLayout initialLayout; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout; || VkImageLayout finalLayout; ); const AttachmentRef dstAttachmentRef // VkAttachmentReference || VkAttachmentReference2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; (deUint32)attachments.size(), // deUint32 attachment; || deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout layout; || VkImageLayout layout; 0u // || VkImageAspectFlags aspectMask; ); attachments.push_back(dstAttachment); dstAttachmentRefs[splitSubpassIndex].push_back(dstAttachmentRef); } // Resolve attachment { const AttachmentDesc dstAttachment // VkAttachmentDescription || VkAttachmentDescription2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // VkAttachmentDescriptionFlags flags; || VkAttachmentDescriptionFlags flags; dstFormat, // VkFormat format; || VkFormat format; VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples; || VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp loadOp; || VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; || VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; || VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp stencilStoreOp; || VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; || VkImageLayout initialLayout; VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL // VkImageLayout finalLayout; || VkImageLayout finalLayout; ); const AttachmentRef dstAttachmentRef // VkAttachmentReference || VkAttachmentReference2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; (deUint32)attachments.size(), // deUint32 attachment; || deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout layout; || VkImageLayout layout; 0u // || VkImageAspectFlags aspectMask; ); attachments.push_back(dstAttachment); dstResolveAttachmentRefs[splitSubpassIndex].push_back(dstAttachmentRef); } } } { { const SubpassDesc subpass // VkSubpassDescription || VkSubpassDescription2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; (VkSubpassDescriptionFlags)0, // VkSubpassDescriptionFlags flags; || VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; || VkPipelineBindPoint pipelineBindPoint; 0u, // || deUint32 viewMask; 0u, // deUint32 inputAttachmentCount; || deUint32 inputAttachmentCount; DE_NULL, // const VkAttachmentReference* pInputAttachments; || const VkAttachmentReference2KHR* pInputAttachments; isDepthStencilFormat ? 0u : 1u, // deUint32 colorAttachmentCount; || deUint32 colorAttachmentCount; isDepthStencilFormat ? DE_NULL : &srcAttachmentRef, // const VkAttachmentReference* pColorAttachments; || const VkAttachmentReference2KHR* pColorAttachments; DE_NULL, // const VkAttachmentReference* pResolveAttachments; || const VkAttachmentReference2KHR* pResolveAttachments; isDepthStencilFormat ? &srcAttachmentRef : DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; || const VkAttachmentReference2KHR* pDepthStencilAttachment; 0u, // deUint32 preserveAttachmentCount; || deUint32 preserveAttachmentCount; DE_NULL // const deUint32* pPreserveAttachments; || const deUint32* pPreserveAttachments; ); subpasses.push_back(subpass); } for (deUint32 splitSubpassIndex = 0; splitSubpassIndex < splitSubpassCount; splitSubpassIndex++) { { const SubpassDesc subpass // VkSubpassDescription || VkSubpassDescription2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; (VkSubpassDescriptionFlags)0, // VkSubpassDescriptionFlags flags; || VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; || VkPipelineBindPoint pipelineBindPoint; 0u, // || deUint32 viewMask; 1u, // deUint32 inputAttachmentCount; || deUint32 inputAttachmentCount; &srcAttachmentInputRef, // const VkAttachmentReference* pInputAttachments; || const VkAttachmentReference2KHR* pInputAttachments; (deUint32)dstAttachmentRefs[splitSubpassIndex].size(), // deUint32 colorAttachmentCount; || deUint32 colorAttachmentCount; &dstAttachmentRefs[splitSubpassIndex][0], // const VkAttachmentReference* pColorAttachments; || const VkAttachmentReference2KHR* pColorAttachments; &dstResolveAttachmentRefs[splitSubpassIndex][0], // const VkAttachmentReference* pResolveAttachments; || const VkAttachmentReference2KHR* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; || const VkAttachmentReference2KHR* pDepthStencilAttachment; 0u, // deUint32 preserveAttachmentCount; || deUint32 preserveAttachmentCount; DE_NULL // const deUint32* pPreserveAttachments; || const deUint32* pPreserveAttachments; ); subpasses.push_back(subpass); } { const SubpassDep dependency // VkSubpassDependency || VkSubpassDependency2KHR ( // || VkStructureType sType; DE_NULL, // || const void* pNext; 0u, // deUint32 srcSubpass; || deUint32 srcSubpass; splitSubpassIndex + 1, // deUint32 dstSubpass; || deUint32 dstSubpass; VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // VkPipelineStageFlags srcStageMask; || VkPipelineStageFlags srcStageMask; VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags dstStageMask; || VkPipelineStageFlags dstStageMask; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask; || VkAccessFlags srcAccessMask; VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, // VkAccessFlags dstAccessMask; || VkAccessFlags dstAccessMask; VK_DEPENDENCY_BY_REGION_BIT, // VkDependencyFlags dependencyFlags; || VkDependencyFlags dependencyFlags; 0u // || deInt32 viewOffset; ); dependencies.push_back(dependency); } }; const RenderPassCreateInfo renderPassCreator // VkRenderPassCreateInfo || VkRenderPassCreateInfo2KHR ( // VkStructureType sType; || VkStructureType sType; DE_NULL, // const void* pNext; || const void* pNext; (VkRenderPassCreateFlags)0u, // VkRenderPassCreateFlags flags; || VkRenderPassCreateFlags flags; (deUint32)attachments.size(), // deUint32 attachmentCount; || deUint32 attachmentCount; &attachments[0], // const VkAttachmentDescription* pAttachments; || const VkAttachmentDescription2KHR* pAttachments; (deUint32)subpasses.size(), // deUint32 subpassCount; || deUint32 subpassCount; &subpasses[0], // const VkSubpassDescription* pSubpasses; || const VkSubpassDescription2KHR* pSubpasses; (deUint32)dependencies.size(), // deUint32 dependencyCount; || deUint32 dependencyCount; &dependencies[0], // const VkSubpassDependency* pDependencies; || const VkSubpassDependency2KHR* pDependencies; 0u, // || deUint32 correlatedViewMaskCount; DE_NULL // || const deUint32* pCorrelatedViewMasks; ); return renderPassCreator.createRenderPass(vkd, device); } } Move<VkRenderPass> createRenderPass (const DeviceInterface& vkd, VkDevice device, VkFormat srcFormat, VkFormat dstFormat, deUint32 sampleCount, const RenderPassType renderPassType) { switch (renderPassType) { case RENDERPASS_TYPE_LEGACY: return createRenderPass<AttachmentDescription1, AttachmentReference1, SubpassDescription1, SubpassDependency1, RenderPassCreateInfo1>(vkd, device, srcFormat, dstFormat, sampleCount, renderPassType); case RENDERPASS_TYPE_RENDERPASS2: return createRenderPass<AttachmentDescription2, AttachmentReference2, SubpassDescription2, SubpassDependency2, RenderPassCreateInfo2>(vkd, device, srcFormat, dstFormat, sampleCount, renderPassType); default: TCU_THROW(InternalError, "Impossible"); } } Move<VkFramebuffer> createFramebuffer (const DeviceInterface& vkd, VkDevice device, VkRenderPass renderPass, VkImageView srcImageView, const std::vector<VkImageViewSp>& dstMultisampleImageViews, const std::vector<VkImageViewSp>& dstSinglesampleImageViews, deUint32 width, deUint32 height) { std::vector<VkImageView> attachments; attachments.reserve(dstMultisampleImageViews.size() + dstSinglesampleImageViews.size() + 1u); attachments.push_back(srcImageView); DE_ASSERT(dstMultisampleImageViews.size() == dstSinglesampleImageViews.size()); for (size_t ndx = 0; ndx < dstMultisampleImageViews.size(); ndx++) { attachments.push_back(**dstMultisampleImageViews[ndx]); attachments.push_back(**dstSinglesampleImageViews[ndx]); } const VkFramebufferCreateInfo createInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, DE_NULL, 0u, renderPass, (deUint32)attachments.size(), &attachments[0], width, height, 1u }; return createFramebuffer(vkd, device, &createInfo); } Move<VkPipelineLayout> createRenderPipelineLayout (const DeviceInterface& vkd, VkDevice device) { const VkPushConstantRange pushConstant = { VK_SHADER_STAGE_FRAGMENT_BIT, 0u, 4u }; const VkPipelineLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, DE_NULL, (vk::VkPipelineLayoutCreateFlags)0, 0u, DE_NULL, 1u, &pushConstant }; return createPipelineLayout(vkd, device, &createInfo); } Move<VkPipeline> createRenderPipeline (const DeviceInterface& vkd, VkDevice device, VkFormat srcFormat, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, const vk::BinaryCollection& binaryCollection, deUint32 width, deUint32 height, deUint32 sampleCount) { const tcu::TextureFormat format (mapVkFormat(srcFormat)); const bool isDepthStencilFormat (tcu::hasDepthComponent(format.order) || tcu::hasStencilComponent(format.order)); const Unique<VkShaderModule> vertexShaderModule (createShaderModule(vkd, device, binaryCollection.get("quad-vert"), 0u)); const Unique<VkShaderModule> fragmentShaderModule (createShaderModule(vkd, device, binaryCollection.get("quad-frag"), 0u)); // Disable blending const VkPipelineColorBlendAttachmentState attachmentBlendState = { VK_FALSE, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD, VK_COLOR_COMPONENT_R_BIT|VK_COLOR_COMPONENT_G_BIT|VK_COLOR_COMPONENT_B_BIT|VK_COLOR_COMPONENT_A_BIT }; const VkPipelineVertexInputStateCreateInfo vertexInputState = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, DE_NULL, (VkPipelineVertexInputStateCreateFlags)0u, 0u, DE_NULL, 0u, DE_NULL }; const std::vector<VkViewport> viewports (1, makeViewport(tcu::UVec2(width, height))); const std::vector<VkRect2D> scissors (1, makeRect2D(tcu::UVec2(width, height))); const VkPipelineMultisampleStateCreateInfo multisampleState = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, DE_NULL, (VkPipelineMultisampleStateCreateFlags)0u, sampleCountBitFromomSampleCount(sampleCount), VK_FALSE, 0.0f, DE_NULL, VK_FALSE, VK_FALSE, }; const VkPipelineDepthStencilStateCreateInfo depthStencilState = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, DE_NULL, (VkPipelineDepthStencilStateCreateFlags)0u, VK_TRUE, VK_TRUE, VK_COMPARE_OP_ALWAYS, VK_FALSE, VK_TRUE, { VK_STENCIL_OP_KEEP, VK_STENCIL_OP_INCREMENT_AND_WRAP, VK_STENCIL_OP_KEEP, VK_COMPARE_OP_ALWAYS, ~0u, ~0u, 0xFFu / (sampleCount + 1) }, { VK_STENCIL_OP_KEEP, VK_STENCIL_OP_INCREMENT_AND_WRAP, VK_STENCIL_OP_KEEP, VK_COMPARE_OP_ALWAYS, ~0u, ~0u, 0xFFu / (sampleCount + 1) }, 0.0f, 1.0f }; const VkPipelineColorBlendStateCreateInfo blendState = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, DE_NULL, (VkPipelineColorBlendStateCreateFlags)0u, VK_FALSE, VK_LOGIC_OP_COPY, (isDepthStencilFormat ? 0u : 1u), (isDepthStencilFormat ? DE_NULL : &attachmentBlendState), { 0.0f, 0.0f, 0.0f, 0.0f } }; return makeGraphicsPipeline(vkd, // const DeviceInterface& vk device, // const VkDevice device pipelineLayout, // const VkPipelineLayout pipelineLayout *vertexShaderModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlShaderModule DE_NULL, // const VkShaderModule tessellationEvalShaderModule DE_NULL, // const VkShaderModule geometryShaderModule *fragmentShaderModule, // const VkShaderModule fragmentShaderModule renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // const VkPrimitiveTopology topology 0u, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputState, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo &multisampleState, // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo &depthStencilState, // const VkPipelineDepthStencilStateCreateInfo* depthStencilStateCreateInfo &blendState); // const VkPipelineColorBlendStateCreateInfo* colorBlendStateCreateInfo } Move<VkDescriptorSetLayout> createSplitDescriptorSetLayout (const DeviceInterface& vkd, VkDevice device, VkFormat vkFormat) { const tcu::TextureFormat format (mapVkFormat(vkFormat)); const bool hasDepth (tcu::hasDepthComponent(format.order)); const bool hasStencil (tcu::hasStencilComponent(format.order)); const VkDescriptorSetLayoutBinding bindings[] = { { 0u, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1u, VK_SHADER_STAGE_FRAGMENT_BIT, DE_NULL }, { 1u, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1u, VK_SHADER_STAGE_FRAGMENT_BIT, DE_NULL } }; const VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, DE_NULL, 0u, hasDepth && hasStencil ? 2u : 1u, bindings }; return createDescriptorSetLayout(vkd, device, &createInfo); } Move<VkPipelineLayout> createSplitPipelineLayout (const DeviceInterface& vkd, VkDevice device, VkDescriptorSetLayout descriptorSetLayout) { const VkPushConstantRange pushConstant = { VK_SHADER_STAGE_FRAGMENT_BIT, 0u, 4u }; const VkPipelineLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, DE_NULL, (vk::VkPipelineLayoutCreateFlags)0, 1u, &descriptorSetLayout, 1u, &pushConstant }; return createPipelineLayout(vkd, device, &createInfo); } Move<VkPipeline> createSplitPipeline (const DeviceInterface& vkd, VkDevice device, VkRenderPass renderPass, deUint32 subpassIndex, VkPipelineLayout pipelineLayout, const vk::BinaryCollection& binaryCollection, deUint32 width, deUint32 height, deUint32 sampleCount) { const Unique<VkShaderModule> vertexShaderModule (createShaderModule(vkd, device, binaryCollection.get("quad-vert"), 0u)); const Unique<VkShaderModule> fragmentShaderModule (createShaderModule(vkd, device, binaryCollection.get("quad-split-frag"), 0u)); // Disable blending const VkPipelineColorBlendAttachmentState attachmentBlendState = { VK_FALSE, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD, VK_COLOR_COMPONENT_R_BIT|VK_COLOR_COMPONENT_G_BIT|VK_COLOR_COMPONENT_B_BIT|VK_COLOR_COMPONENT_A_BIT }; const std::vector<VkPipelineColorBlendAttachmentState> attachmentBlendStates (de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, sampleCount), attachmentBlendState); const VkPipelineVertexInputStateCreateInfo vertexInputState = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, DE_NULL, (VkPipelineVertexInputStateCreateFlags)0u, 0u, DE_NULL, 0u, DE_NULL }; const std::vector<VkViewport> viewports (1, makeViewport(tcu::UVec2(width, height))); const std::vector<VkRect2D> scissors (1, makeRect2D(tcu::UVec2(width, height))); const VkPipelineMultisampleStateCreateInfo multisampleState = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, DE_NULL, (VkPipelineMultisampleStateCreateFlags)0u, sampleCountBitFromomSampleCount(sampleCount), VK_FALSE, 0.0f, DE_NULL, VK_FALSE, VK_FALSE, }; const VkPipelineColorBlendStateCreateInfo blendState = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, DE_NULL, (VkPipelineColorBlendStateCreateFlags)0u, VK_FALSE, VK_LOGIC_OP_COPY, (deUint32)attachmentBlendStates.size(), &attachmentBlendStates[0], { 0.0f, 0.0f, 0.0f, 0.0f } }; return makeGraphicsPipeline(vkd, // const DeviceInterface& vk device, // const VkDevice device pipelineLayout, // const VkPipelineLayout pipelineLayout *vertexShaderModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlShaderModule DE_NULL, // const VkShaderModule tessellationEvalShaderModule DE_NULL, // const VkShaderModule geometryShaderModule *fragmentShaderModule, // const VkShaderModule fragmentShaderModule renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, // const VkPrimitiveTopology topology subpassIndex, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputState, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo &multisampleState, // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo DE_NULL, // const VkPipelineDepthStencilStateCreateInfo* depthStencilStateCreateInfo &blendState); // const VkPipelineColorBlendStateCreateInfo* colorBlendStateCreateInfo } vector<VkPipelineSp> createSplitPipelines (const DeviceInterface& vkd, VkDevice device, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, const vk::BinaryCollection& binaryCollection, deUint32 width, deUint32 height, deUint32 sampleCount) { std::vector<VkPipelineSp> pipelines (deDivRoundUp32(sampleCount, MAX_COLOR_ATTACHMENT_COUNT), (VkPipelineSp)0u); for (size_t ndx = 0; ndx < pipelines.size(); ndx++) pipelines[ndx] = safeSharedPtr(new Unique<VkPipeline>(createSplitPipeline(vkd, device, renderPass, (deUint32)(ndx + 1), pipelineLayout, binaryCollection, width, height, sampleCount))); return pipelines; } Move<VkDescriptorPool> createSplitDescriptorPool (const DeviceInterface& vkd, VkDevice device) { const VkDescriptorPoolSize size = { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2u }; const VkDescriptorPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, DE_NULL, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 2u, 1u, &size }; return createDescriptorPool(vkd, device, &createInfo); } Move<VkDescriptorSet> createSplitDescriptorSet (const DeviceInterface& vkd, VkDevice device, VkDescriptorPool pool, VkDescriptorSetLayout layout, VkImageView primaryImageView, VkImageView secondaryImageView) { const VkDescriptorSetAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, DE_NULL, pool, 1u, &layout }; Move<VkDescriptorSet> set (allocateDescriptorSet(vkd, device, &allocateInfo)); { const VkDescriptorImageInfo imageInfos[] = { { (VkSampler)0u, primaryImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }, { (VkSampler)0u, secondaryImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL } }; const VkWriteDescriptorSet writes[] = { { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, DE_NULL, *set, 0u, 0u, 1u, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &imageInfos[0], DE_NULL, DE_NULL }, { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, DE_NULL, *set, 1u, 0u, 1u, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &imageInfos[1], DE_NULL, DE_NULL } }; const deUint32 count = secondaryImageView != (VkImageView)0 ? 2u : 1u; vkd.updateDescriptorSets(device, count, writes, 0u, DE_NULL); } return set; } struct TestConfig { TestConfig (VkFormat format_, deUint32 sampleCount_, RenderPassType renderPassType_) : format (format_) , sampleCount (sampleCount_) , renderPassType (renderPassType_) { } VkFormat format; deUint32 sampleCount; RenderPassType renderPassType; }; VkImageUsageFlags getSrcImageUsage (VkFormat vkFormat) { const tcu::TextureFormat format (mapVkFormat(vkFormat)); const bool hasDepth (tcu::hasDepthComponent(format.order)); const bool hasStencil (tcu::hasStencilComponent(format.order)); if (hasDepth || hasStencil) return VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; else return VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; } VkFormat getDstFormat (VkFormat vkFormat) { const tcu::TextureFormat format (mapVkFormat(vkFormat)); const bool hasDepth (tcu::hasDepthComponent(format.order)); const bool hasStencil (tcu::hasStencilComponent(format.order)); if (hasDepth && hasStencil) return VK_FORMAT_R32G32_SFLOAT; else if (hasDepth || hasStencil) return VK_FORMAT_R32_SFLOAT; else return vkFormat; } class MultisampleRenderPassTestInstance : public TestInstance { public: MultisampleRenderPassTestInstance (Context& context, TestConfig config); ~MultisampleRenderPassTestInstance (void); tcu::TestStatus iterate (void); template<typename RenderpassSubpass> tcu::TestStatus iterateInternal (void); private: const bool m_extensionSupported; const RenderPassType m_renderPassType; const VkFormat m_srcFormat; const VkFormat m_dstFormat; const deUint32 m_sampleCount; const deUint32 m_width; const deUint32 m_height; const VkImageAspectFlags m_srcImageAspect; const VkImageUsageFlags m_srcImageUsage; const Unique<VkImage> m_srcImage; const de::UniquePtr<Allocation> m_srcImageMemory; const Unique<VkImageView> m_srcImageView; const Unique<VkImageView> m_srcPrimaryInputImageView; const Unique<VkImageView> m_srcSecondaryInputImageView; const std::vector<VkImageSp> m_dstMultisampleImages; const std::vector<de::SharedPtr<Allocation> > m_dstMultisampleImageMemory; const std::vector<VkImageViewSp> m_dstMultisampleImageViews; const std::vector<VkImageSp> m_dstSinglesampleImages; const std::vector<de::SharedPtr<Allocation> > m_dstSinglesampleImageMemory; const std::vector<VkImageViewSp> m_dstSinglesampleImageViews; const std::vector<VkBufferSp> m_dstBuffers; const std::vector<de::SharedPtr<Allocation> > m_dstBufferMemory; const Unique<VkRenderPass> m_renderPass; const Unique<VkFramebuffer> m_framebuffer; const Unique<VkPipelineLayout> m_renderPipelineLayout; const Unique<VkPipeline> m_renderPipeline; const Unique<VkDescriptorSetLayout> m_splitDescriptorSetLayout; const Unique<VkPipelineLayout> m_splitPipelineLayout; const std::vector<VkPipelineSp> m_splitPipelines; const Unique<VkDescriptorPool> m_splitDescriptorPool; const Unique<VkDescriptorSet> m_splitDescriptorSet; const Unique<VkCommandPool> m_commandPool; tcu::ResultCollector m_resultCollector; }; MultisampleRenderPassTestInstance::MultisampleRenderPassTestInstance (Context& context, TestConfig config) : TestInstance (context) , m_extensionSupported ((config.renderPassType == RENDERPASS_TYPE_RENDERPASS2) && context.requireDeviceExtension("VK_KHR_create_renderpass2")) , m_renderPassType (config.renderPassType) , m_srcFormat (config.format) , m_dstFormat (getDstFormat(config.format)) , m_sampleCount (config.sampleCount) , m_width (32u) , m_height (32u) , m_srcImageAspect (getImageAspectFlags(m_srcFormat)) , m_srcImageUsage (getSrcImageUsage(m_srcFormat)) , m_srcImage (createImage(context.getInstanceInterface(), context.getPhysicalDevice(), context.getDeviceInterface(), context.getDevice(), m_srcFormat, sampleCountBitFromomSampleCount(m_sampleCount), m_srcImageUsage, m_width, m_height)) , m_srcImageMemory (createImageMemory(context.getDeviceInterface(), context.getDevice(), context.getDefaultAllocator(), *m_srcImage)) , m_srcImageView (createImageAttachmentView(context.getDeviceInterface(), context.getDevice(), *m_srcImage, m_srcFormat, m_srcImageAspect)) , m_srcPrimaryInputImageView (createSrcPrimaryInputImageView(context.getDeviceInterface(), context.getDevice(), *m_srcImage, m_srcFormat, m_srcImageAspect)) , m_srcSecondaryInputImageView (createSrcSecondaryInputImageView(context.getDeviceInterface(), context.getDevice(), *m_srcImage, m_srcFormat, m_srcImageAspect)) , m_dstMultisampleImages (createMultisampleImages(context.getInstanceInterface(), context.getPhysicalDevice(), context.getDeviceInterface(), context.getDevice(), m_dstFormat, m_sampleCount, m_width, m_height)) , m_dstMultisampleImageMemory (createImageMemory(context.getDeviceInterface(), context.getDevice(), context.getDefaultAllocator(), m_dstMultisampleImages)) , m_dstMultisampleImageViews (createImageAttachmentViews(context.getDeviceInterface(), context.getDevice(), m_dstMultisampleImages, m_dstFormat, VK_IMAGE_ASPECT_COLOR_BIT)) , m_dstSinglesampleImages (createSingleSampleImages(context.getInstanceInterface(), context.getPhysicalDevice(), context.getDeviceInterface(), context.getDevice(), m_dstFormat, m_sampleCount, m_width, m_height)) , m_dstSinglesampleImageMemory (createImageMemory(context.getDeviceInterface(), context.getDevice(), context.getDefaultAllocator(), m_dstSinglesampleImages)) , m_dstSinglesampleImageViews (createImageAttachmentViews(context.getDeviceInterface(), context.getDevice(), m_dstSinglesampleImages, m_dstFormat, VK_IMAGE_ASPECT_COLOR_BIT)) , m_dstBuffers (createBuffers(context.getDeviceInterface(), context.getDevice(), m_dstFormat, m_sampleCount, m_width, m_height)) , m_dstBufferMemory (createBufferMemory(context.getDeviceInterface(), context.getDevice(), context.getDefaultAllocator(), m_dstBuffers)) , m_renderPass (createRenderPass(context.getDeviceInterface(), context.getDevice(), m_srcFormat, m_dstFormat, m_sampleCount, config.renderPassType)) , m_framebuffer (createFramebuffer(context.getDeviceInterface(), context.getDevice(), *m_renderPass, *m_srcImageView, m_dstMultisampleImageViews, m_dstSinglesampleImageViews, m_width, m_height)) , m_renderPipelineLayout (createRenderPipelineLayout(context.getDeviceInterface(), context.getDevice())) , m_renderPipeline (createRenderPipeline(context.getDeviceInterface(), context.getDevice(), m_srcFormat, *m_renderPass, *m_renderPipelineLayout, context.getBinaryCollection(), m_width, m_height, m_sampleCount)) , m_splitDescriptorSetLayout (createSplitDescriptorSetLayout(context.getDeviceInterface(), context.getDevice(), m_srcFormat)) , m_splitPipelineLayout (createSplitPipelineLayout(context.getDeviceInterface(), context.getDevice(), *m_splitDescriptorSetLayout)) , m_splitPipelines (createSplitPipelines(context.getDeviceInterface(), context.getDevice(), *m_renderPass, *m_splitPipelineLayout, context.getBinaryCollection(), m_width, m_height, m_sampleCount)) , m_splitDescriptorPool (createSplitDescriptorPool(context.getDeviceInterface(), context.getDevice())) , m_splitDescriptorSet (createSplitDescriptorSet(context.getDeviceInterface(), context.getDevice(), *m_splitDescriptorPool, *m_splitDescriptorSetLayout, *m_srcPrimaryInputImageView, *m_srcSecondaryInputImageView)) , m_commandPool (createCommandPool(context.getDeviceInterface(), context.getDevice(), VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, context.getUniversalQueueFamilyIndex())) { } MultisampleRenderPassTestInstance::~MultisampleRenderPassTestInstance (void) { } tcu::TestStatus MultisampleRenderPassTestInstance::iterate (void) { switch (m_renderPassType) { case RENDERPASS_TYPE_LEGACY: return iterateInternal<RenderpassSubpass1>(); case RENDERPASS_TYPE_RENDERPASS2: return iterateInternal<RenderpassSubpass2>(); default: TCU_THROW(InternalError, "Impossible"); } } template<typename RenderpassSubpass> tcu::TestStatus MultisampleRenderPassTestInstance::iterateInternal (void) { const DeviceInterface& vkd (m_context.getDeviceInterface()); const VkDevice device (m_context.getDevice()); const Unique<VkCommandBuffer> commandBuffer (allocateCommandBuffer(vkd, device, *m_commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY)); const typename RenderpassSubpass::SubpassBeginInfo subpassBeginInfo (DE_NULL, VK_SUBPASS_CONTENTS_INLINE); const typename RenderpassSubpass::SubpassEndInfo subpassEndInfo (DE_NULL); beginCommandBuffer(vkd, *commandBuffer); { const VkRenderPassBeginInfo beginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, DE_NULL, *m_renderPass, *m_framebuffer, { { 0u, 0u }, { m_width, m_height } }, 0u, DE_NULL }; RenderpassSubpass::cmdBeginRenderPass(vkd, *commandBuffer, &beginInfo, &subpassBeginInfo); // Stencil needs to be cleared if it exists. if (tcu::hasStencilComponent(mapVkFormat(m_srcFormat).order)) { const VkClearAttachment clearAttachment = { VK_IMAGE_ASPECT_STENCIL_BIT, // VkImageAspectFlags aspectMask; 0, // deUint32 colorAttachment; makeClearValueDepthStencil(0, 0) // VkClearValue clearValue; }; const VkClearRect clearRect = { { { 0u, 0u }, { m_width, m_height } }, 0, // deUint32 baseArrayLayer; 1 // deUint32 layerCount; }; vkd.cmdClearAttachments(*commandBuffer, 1, &clearAttachment, 1, &clearRect); } } vkd.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_renderPipeline); for (deUint32 sampleNdx = 0; sampleNdx < m_sampleCount; sampleNdx++) { vkd.cmdPushConstants(*commandBuffer, *m_renderPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0u, sizeof(sampleNdx), &sampleNdx); vkd.cmdDraw(*commandBuffer, 6u, 1u, 0u, 0u); } for (deUint32 splitPipelineNdx = 0; splitPipelineNdx < m_splitPipelines.size(); splitPipelineNdx++) { RenderpassSubpass::cmdNextSubpass(vkd, *commandBuffer, &subpassBeginInfo, &subpassEndInfo); vkd.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, **m_splitPipelines[splitPipelineNdx]); vkd.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *m_splitPipelineLayout, 0u, 1u, &*m_splitDescriptorSet, 0u, DE_NULL); vkd.cmdPushConstants(*commandBuffer, *m_splitPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0u, sizeof(splitPipelineNdx), &splitPipelineNdx); vkd.cmdDraw(*commandBuffer, 6u, 1u, 0u, 0u); } RenderpassSubpass::cmdEndRenderPass(vkd, *commandBuffer, &subpassEndInfo); for (size_t dstNdx = 0; dstNdx < m_dstSinglesampleImages.size(); dstNdx++) copyImageToBuffer(vkd, *commandBuffer, **m_dstSinglesampleImages[dstNdx], **m_dstBuffers[dstNdx], tcu::IVec2(m_width, m_height), VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); endCommandBuffer(vkd, *commandBuffer); submitCommandsAndWait(vkd, device, m_context.getUniversalQueue(), *commandBuffer); { const tcu::TextureFormat format (mapVkFormat(m_dstFormat)); const tcu::TextureFormat srcFormat (mapVkFormat(m_srcFormat)); const bool hasDepth (tcu::hasDepthComponent(srcFormat.order)); const bool hasStencil (tcu::hasStencilComponent(srcFormat.order)); for (deUint32 sampleNdx = 0; sampleNdx < m_sampleCount; sampleNdx++) { Allocation *dstBufMem = m_dstBufferMemory[sampleNdx].get(); invalidateAlloc(vkd, device, *dstBufMem); const std::string name ("Sample" + de::toString(sampleNdx)); const void* const ptr (dstBufMem->getHostPtr()); const tcu::ConstPixelBufferAccess access (format, m_width, m_height, 1, ptr); tcu::TextureLevel reference (format, m_width, m_height); if (hasDepth || hasStencil) { if (hasDepth) { for (deUint32 y = 0; y < m_height; y++) for (deUint32 x = 0; x < m_width; x++) { const deUint32 x1 = x ^ sampleNdx; const deUint32 y1 = y ^ sampleNdx; const float range = 1.0f; float depth = 0.0f; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits for (size_t bitNdx = 0; bitNdx < 10; bitNdx++) { depth += (range / (float)divider) * (((bitNdx % 2 == 0 ? x1 : y1) & (0x1u << (bitNdx / 2u))) == 0u ? 0u : 1u); divider *= 2; } reference.getAccess().setPixel(Vec4(depth, 0.0f, 0.0f, 0.0f), x, y); } } if (hasStencil) { for (deUint32 y = 0; y < m_height; y++) for (deUint32 x = 0; x < m_width; x++) { const deUint32 stencil = sampleNdx + 1u; if (hasDepth) { const Vec4 src (reference.getAccess().getPixel(x, y)); reference.getAccess().setPixel(Vec4(src.x(), (float)stencil, 0.0f, 0.0f), x, y); } else reference.getAccess().setPixel(Vec4((float)stencil, 0.0f, 0.0f, 0.0f), x, y); } } { const Vec4 threshold (hasDepth ? (1.0f / 1024.0f) : 0.0f, 0.0f, 0.0f, 0.0f); if (!tcu::floatThresholdCompare(m_context.getTestContext().getLog(), name.c_str(), name.c_str(), reference.getAccess(), access, threshold, tcu::COMPARE_LOG_ON_ERROR)) m_resultCollector.fail("Compare failed for sample " + de::toString(sampleNdx)); } } else { const tcu::TextureChannelClass channelClass (tcu::getTextureChannelClass(format.type)); switch (channelClass) { case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER: { const UVec4 bits (tcu::getTextureFormatBitDepth(format).cast<deUint32>()); const UVec4 minValue (0); const UVec4 range (UVec4(1u) << tcu::min(bits, UVec4(31))); const int componentCount (tcu::getNumUsedChannels(format.order)); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); for (deUint32 y = 0; y < m_height; y++) for (deUint32 x = 0; x < m_width; x++) { const deUint32 x1 = x ^ sampleNdx; const deUint32 y1 = y ^ sampleNdx; UVec4 color (minValue); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; color[compNdx] += (range[compNdx] / divider) * (((nextSrcBit % 2 == 0 ? x1 : y1) & (0x1u << (nextSrcBit / 2u))) == 0u ? 0u : 1u); nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } reference.getAccess().setPixel(color, x, y); } if (!tcu::intThresholdCompare(m_context.getTestContext().getLog(), name.c_str(), name.c_str(), reference.getAccess(), access, UVec4(0u), tcu::COMPARE_LOG_ON_ERROR)) m_resultCollector.fail("Compare failed for sample " + de::toString(sampleNdx)); break; } case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER: { const UVec4 bits (tcu::getTextureFormatBitDepth(format).cast<deUint32>()); const IVec4 minValue (0); const IVec4 range ((UVec4(1u) << tcu::min(bits, UVec4(30))).cast<deInt32>()); const int componentCount (tcu::getNumUsedChannels(format.order)); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); for (deUint32 y = 0; y < m_height; y++) for (deUint32 x = 0; x < m_width; x++) { const deUint32 x1 = x ^ sampleNdx; const deUint32 y1 = y ^ sampleNdx; IVec4 color (minValue); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; color[compNdx] += (range[compNdx] / divider) * (((nextSrcBit % 2 == 0 ? x1 : y1) & (0x1u << (nextSrcBit / 2u))) == 0u ? 0u : 1u); nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } reference.getAccess().setPixel(color, x, y); } if (!tcu::intThresholdCompare(m_context.getTestContext().getLog(), name.c_str(), name.c_str(), reference.getAccess(), access, UVec4(0u), tcu::COMPARE_LOG_ON_ERROR)) m_resultCollector.fail("Compare failed for sample " + de::toString(sampleNdx)); break; } case tcu::TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_FLOATING_POINT: { const tcu::TextureFormatInfo info (tcu::getTextureFormatInfo(format)); const UVec4 bits (tcu::getTextureFormatBitDepth(format).cast<deUint32>()); const Vec4 minLimit (-65536.0); const Vec4 maxLimit (65536.0); const Vec4 minValue (tcu::max(info.valueMin, minLimit)); const Vec4 range (tcu::min(info.valueMax, maxLimit) - minValue); const int componentCount (tcu::getNumUsedChannels(format.order)); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); for (deUint32 y = 0; y < m_height; y++) for (deUint32 x = 0; x < m_width; x++) { const deUint32 x1 = x ^ sampleNdx; const deUint32 y1 = y ^ sampleNdx; Vec4 color (minValue); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; color[compNdx] += (range[compNdx] / (float)divider) * (((nextSrcBit % 2 == 0 ? x1 : y1) & (0x1u << (nextSrcBit / 2u))) == 0u ? 0u : 1u); nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } if (tcu::isSRGB(format)) reference.getAccess().setPixel(tcu::linearToSRGB(color), x, y); else reference.getAccess().setPixel(color, x, y); } if (channelClass == tcu::TEXTURECHANNELCLASS_FLOATING_POINT) { // Convert target format ulps to float ulps and allow 64ulp differences const UVec4 threshold (64u * (UVec4(1u) << (UVec4(23) - tcu::getTextureFormatMantissaBitDepth(format).cast<deUint32>()))); if (!tcu::floatUlpThresholdCompare(m_context.getTestContext().getLog(), name.c_str(), name.c_str(), reference.getAccess(), access, threshold, tcu::COMPARE_LOG_ON_ERROR)) m_resultCollector.fail("Compare failed for sample " + de::toString(sampleNdx)); } else { // Allow error of 4 times the minimum presentable difference const Vec4 threshold (4.0f * 1.0f / ((UVec4(1u) << tcu::getTextureFormatMantissaBitDepth(format).cast<deUint32>()) - 1u).cast<float>()); if (!tcu::floatThresholdCompare(m_context.getTestContext().getLog(), name.c_str(), name.c_str(), reference.getAccess(), access, threshold, tcu::COMPARE_LOG_ON_ERROR)) m_resultCollector.fail("Compare failed for sample " + de::toString(sampleNdx)); } break; } default: DE_FATAL("Unknown channel class"); } } } } return tcu::TestStatus(m_resultCollector.getResult(), m_resultCollector.getMessage()); } struct Programs { void init (vk::SourceCollections& dst, TestConfig config) const { const tcu::TextureFormat format (mapVkFormat(config.format)); const tcu::TextureChannelClass channelClass (tcu::getTextureChannelClass(format.type)); dst.glslSources.add("quad-vert") << glu::VertexSource( "#version 450\n" "out gl_PerVertex {\n" "\tvec4 gl_Position;\n" "};\n" "highp float;\n" "void main (void) {\n" "\tgl_Position = vec4(((gl_VertexIndex + 2) / 3) % 2 == 0 ? -1.0 : 1.0,\n" "\t ((gl_VertexIndex + 1) / 3) % 2 == 0 ? -1.0 : 1.0, 0.0, 1.0);\n" "}\n"); if (tcu::hasDepthComponent(format.order)) { const Vec4 minValue (0.0f); const Vec4 range (1.0f); std::ostringstream fragmentShader; fragmentShader << "#version 450\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint sampleIndex;\n" "} pushConstants;\n" "void main (void)\n" "{\n" "\thighp uint sampleIndex = pushConstants.sampleIndex;\n" "\tgl_SampleMask[0] = int((~0x0u) << sampleIndex);\n" "\thighp float depth;\n" "\thighp uint x = sampleIndex ^ uint(gl_FragCoord.x);\n" "\thighp uint y = sampleIndex ^ uint(gl_FragCoord.y);\n"; fragmentShader << "\tdepth = " << minValue[0] << ";\n"; { deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits for (size_t bitNdx = 0; bitNdx < 10; bitNdx++) { fragmentShader << "\tdepth += " << (range[0] / (float)divider) << " * float(bitfieldExtract(" << (bitNdx % 2 == 0 ? "x" : "y") << ", " << (bitNdx / 2) << ", 1));\n"; divider *= 2; } } fragmentShader << "\tgl_FragDepth = depth;\n" "}\n"; dst.glslSources.add("quad-frag") << glu::FragmentSource(fragmentShader.str()); } else if (tcu::hasStencilComponent(format.order)) { dst.glslSources.add("quad-frag") << glu::FragmentSource( "#version 450\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint sampleIndex;\n" "} pushConstants;\n" "void main (void)\n" "{\n" "\thighp uint sampleIndex = pushConstants.sampleIndex;\n" "\tgl_SampleMask[0] = int((~0x0u) << sampleIndex);\n" "}\n"); } else { switch (channelClass) { case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER: { const UVec4 bits (tcu::getTextureFormatBitDepth(format).cast<deUint32>()); const UVec4 minValue (0); const UVec4 range (UVec4(1u) << tcu::min(bits, UVec4(31))); std::ostringstream fragmentShader; fragmentShader << "#version 450\n" "layout(location = 0) out highp uvec4 o_color;\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint sampleIndex;\n" "} pushConstants;\n" "void main (void)\n" "{\n" "\thighp uint sampleIndex = pushConstants.sampleIndex;\n" "\tgl_SampleMask[0] = int(0x1u << sampleIndex);\n" "\thighp uint color[4];\n" "\thighp uint x = sampleIndex ^ uint(gl_FragCoord.x);\n" "\thighp uint y = sampleIndex ^ uint(gl_FragCoord.y);\n"; for (int ndx = 0; ndx < 4; ndx++) fragmentShader << "\tcolor[" << ndx << "] = " << minValue[ndx] << ";\n"; { const int componentCount = tcu::getNumUsedChannels(format.order); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; fragmentShader << "\tcolor[" << compNdx << "] += " << (range[compNdx] / divider) << " * bitfieldExtract(" << (nextSrcBit % 2 == 0 ? "x" : "y") << ", " << (nextSrcBit / 2) << ", 1);\n"; nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } } fragmentShader << "\to_color = uvec4(color[0], color[1], color[2], color[3]);\n" "}\n"; dst.glslSources.add("quad-frag") << glu::FragmentSource(fragmentShader.str()); break; } case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER: { const UVec4 bits (tcu::getTextureFormatBitDepth(format).cast<deUint32>()); const IVec4 minValue (0); const IVec4 range ((UVec4(1u) << tcu::min(bits, UVec4(30))).cast<deInt32>()); const IVec4 maxV ((UVec4(1u) << (bits - UVec4(1u))).cast<deInt32>()); const IVec4 clampMax (maxV - 1); const IVec4 clampMin (-maxV); std::ostringstream fragmentShader; fragmentShader << "#version 450\n" "layout(location = 0) out highp ivec4 o_color;\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint sampleIndex;\n" "} pushConstants;\n" "void main (void)\n" "{\n" "\thighp uint sampleIndex = pushConstants.sampleIndex;\n" "\tgl_SampleMask[0] = int(0x1u << sampleIndex);\n" "\thighp int color[4];\n" "\thighp uint x = sampleIndex ^ uint(gl_FragCoord.x);\n" "\thighp uint y = sampleIndex ^ uint(gl_FragCoord.y);\n"; for (int ndx = 0; ndx < 4; ndx++) fragmentShader << "\tcolor[" << ndx << "] = " << minValue[ndx] << ";\n"; { const int componentCount = tcu::getNumUsedChannels(format.order); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; fragmentShader << "\tcolor[" << compNdx << "] += " << (range[compNdx] / divider) << " * int(bitfieldExtract(" << (nextSrcBit % 2 == 0 ? "x" : "y") << ", " << (nextSrcBit / 2) << ", 1));\n"; nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } } // The spec doesn't define whether signed-integers are clamped on output, // so we'll clamp them explicitly to have well-defined outputs. fragmentShader << "\to_color = clamp(ivec4(color[0], color[1], color[2], color[3]), " << "ivec4" << clampMin << ", ivec4" << clampMax << ");\n" << "}\n"; dst.glslSources.add("quad-frag") << glu::FragmentSource(fragmentShader.str()); break; } case tcu::TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_FLOATING_POINT: { const tcu::TextureFormatInfo info (tcu::getTextureFormatInfo(format)); const UVec4 bits (tcu::getTextureFormatMantissaBitDepth(format).cast<deUint32>()); const Vec4 minLimit (-65536.0); const Vec4 maxLimit (65536.0); const Vec4 minValue (tcu::max(info.valueMin, minLimit)); const Vec4 range (tcu::min(info.valueMax, maxLimit) - minValue); std::ostringstream fragmentShader; fragmentShader << "#version 450\n" "layout(location = 0) out highp vec4 o_color;\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint sampleIndex;\n" "} pushConstants;\n" "void main (void)\n" "{\n" "\thighp uint sampleIndex = pushConstants.sampleIndex;\n" "\tgl_SampleMask[0] = int(0x1u << sampleIndex);\n" "\thighp float color[4];\n" "\thighp uint x = sampleIndex ^ uint(gl_FragCoord.x);\n" "\thighp uint y = sampleIndex ^ uint(gl_FragCoord.y);\n"; for (int ndx = 0; ndx < 4; ndx++) fragmentShader << "\tcolor[" << ndx << "] = " << minValue[ndx] << ";\n"; { const int componentCount = tcu::getNumUsedChannels(format.order); const deUint32 bitSize (bits[0] + bits[1] + bits[2] + bits[3]); deUint32 dstBitsUsed[4] = { 0u, 0u, 0u, 0u }; deUint32 nextSrcBit = 0; deUint32 divider = 2; // \note Limited to ten bits since the target is 32x32, so there are 10 input bits while (nextSrcBit < de::min(bitSize, 10u)) { for (int compNdx = 0; compNdx < componentCount; compNdx++) { if (dstBitsUsed[compNdx] > bits[compNdx]) continue; fragmentShader << "\tcolor[" << compNdx << "] += " << (range[compNdx] / (float)divider) << " * float(bitfieldExtract(" << (nextSrcBit % 2 == 0 ? "x" : "y") << ", " << (nextSrcBit / 2) << ", 1));\n"; nextSrcBit++; dstBitsUsed[compNdx]++; } divider *= 2; } } fragmentShader << "\to_color = vec4(color[0], color[1], color[2], color[3]);\n" "}\n"; dst.glslSources.add("quad-frag") << glu::FragmentSource(fragmentShader.str()); break; } default: DE_FATAL("Unknown channel class"); } } if (tcu::hasDepthComponent(format.order) || tcu::hasStencilComponent(format.order)) { std::ostringstream splitShader; splitShader << "#version 450\n"; if (tcu::hasDepthComponent(format.order) && tcu::hasStencilComponent(format.order)) { splitShader << "layout(input_attachment_index = 0, set = 0, binding = 0) uniform highp subpassInputMS i_depth;\n" << "layout(input_attachment_index = 0, set = 0, binding = 1) uniform highp usubpassInputMS i_stencil;\n"; } else if (tcu::hasDepthComponent(format.order)) splitShader << "layout(input_attachment_index = 0, set = 0, binding = 0) uniform highp subpassInputMS i_depth;\n"; else if (tcu::hasStencilComponent(format.order)) splitShader << "layout(input_attachment_index = 0, set = 0, binding = 0) uniform highp usubpassInputMS i_stencil;\n"; splitShader << "layout(push_constant) uniform PushConstant {\n" "\thighp uint splitSubpassIndex;\n" "} pushConstants;\n"; for (deUint32 attachmentNdx = 0; attachmentNdx < de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, config.sampleCount); attachmentNdx++) { if (tcu::hasDepthComponent(format.order) && tcu::hasStencilComponent(format.order)) splitShader << "layout(location = " << attachmentNdx << ") out highp vec2 o_color" << attachmentNdx << ";\n"; else splitShader << "layout(location = " << attachmentNdx << ") out highp float o_color" << attachmentNdx << ";\n"; } splitShader << "void main (void)\n" "{\n"; for (deUint32 attachmentNdx = 0; attachmentNdx < de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, config.sampleCount); attachmentNdx++) { if (tcu::hasDepthComponent(format.order)) splitShader << "\thighp float depth" << attachmentNdx << " = subpassLoad(i_depth, int(" << MAX_COLOR_ATTACHMENT_COUNT << " * pushConstants.splitSubpassIndex + " << attachmentNdx << "u)).x;\n"; if (tcu::hasStencilComponent(format.order)) splitShader << "\thighp uint stencil" << attachmentNdx << " = subpassLoad(i_stencil, int(" << MAX_COLOR_ATTACHMENT_COUNT << " * pushConstants.splitSubpassIndex + " << attachmentNdx << "u)).x;\n"; if (tcu::hasDepthComponent(format.order) && tcu::hasStencilComponent(format.order)) splitShader << "\to_color" << attachmentNdx << " = vec2(depth" << attachmentNdx << ", float(stencil" << attachmentNdx << "));\n"; else if (tcu::hasDepthComponent(format.order)) splitShader << "\to_color" << attachmentNdx << " = float(depth" << attachmentNdx << ");\n"; else if (tcu::hasStencilComponent(format.order)) splitShader << "\to_color" << attachmentNdx << " = float(stencil" << attachmentNdx << ");\n"; } splitShader << "}\n"; dst.glslSources.add("quad-split-frag") << glu::FragmentSource(splitShader.str()); } else { std::string subpassType; std::string outputType; switch (channelClass) { case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER: subpassType = "usubpassInputMS"; outputType = "uvec4"; break; case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER: subpassType = "isubpassInputMS"; outputType = "ivec4"; break; case tcu::TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT: case tcu::TEXTURECHANNELCLASS_FLOATING_POINT: subpassType = "subpassInputMS"; outputType = "vec4"; break; default: DE_FATAL("Unknown channel class"); } std::ostringstream splitShader; splitShader << "#version 450\n" "layout(input_attachment_index = 0, set = 0, binding = 0) uniform highp " << subpassType << " i_color;\n" "layout(push_constant) uniform PushConstant {\n" "\thighp uint splitSubpassIndex;\n" "} pushConstants;\n"; for (deUint32 attachmentNdx = 0; attachmentNdx < de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, config.sampleCount); attachmentNdx++) splitShader << "layout(location = " << attachmentNdx << ") out highp " << outputType << " o_color" << attachmentNdx << ";\n"; splitShader << "void main (void)\n" "{\n"; for (deUint32 attachmentNdx = 0; attachmentNdx < de::min((deUint32)MAX_COLOR_ATTACHMENT_COUNT, config.sampleCount); attachmentNdx++) splitShader << "\to_color" << attachmentNdx << " = subpassLoad(i_color, int(" << MAX_COLOR_ATTACHMENT_COUNT << " * pushConstants.splitSubpassIndex + " << attachmentNdx << "u));\n"; splitShader << "}\n"; dst.glslSources.add("quad-split-frag") << glu::FragmentSource(splitShader.str()); } } }; std::string formatToName (VkFormat format) { const std::string formatStr = de::toString(format); const std::string prefix = "VK_FORMAT_"; DE_ASSERT(formatStr.substr(0, prefix.length()) == prefix); return de::toLower(formatStr.substr(prefix.length())); } void initTests (tcu::TestCaseGroup* group, RenderPassType renderPassType) { static const VkFormat formats[] = { VK_FORMAT_R5G6B5_UNORM_PACK16, VK_FORMAT_R8_UNORM, VK_FORMAT_R8_SNORM, VK_FORMAT_R8_UINT, VK_FORMAT_R8_SINT, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_SNORM, VK_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_SINT, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_A8B8G8R8_UNORM_PACK32, VK_FORMAT_A8B8G8R8_SNORM_PACK32, VK_FORMAT_A8B8G8R8_UINT_PACK32, VK_FORMAT_A8B8G8R8_SINT_PACK32, VK_FORMAT_A8B8G8R8_SRGB_PACK32, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_A2R10G10B10_UNORM_PACK32, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2B10G10R10_UINT_PACK32, VK_FORMAT_R16_UNORM, VK_FORMAT_R16_SNORM, VK_FORMAT_R16_UINT, VK_FORMAT_R16_SINT, VK_FORMAT_R16_SFLOAT, VK_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SFLOAT, VK_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SFLOAT, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT, VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_D16_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT, VK_FORMAT_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT }; const deUint32 sampleCounts[] = { 2u, 4u, 8u, 16u, 32u }; tcu::TestContext& testCtx (group->getTestContext()); for (size_t formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++) { const VkFormat format (formats[formatNdx]); const std::string formatName (formatToName(format)); de::MovePtr<tcu::TestCaseGroup> formatGroup (new tcu::TestCaseGroup(testCtx, formatName.c_str(), formatName.c_str())); for (size_t sampleCountNdx = 0; sampleCountNdx < DE_LENGTH_OF_ARRAY(sampleCounts); sampleCountNdx++) { const deUint32 sampleCount (sampleCounts[sampleCountNdx]); const TestConfig testConfig (format, sampleCount, renderPassType); const std::string testName ("samples_" + de::toString(sampleCount)); formatGroup->addChild(new InstanceFactory1<MultisampleRenderPassTestInstance, TestConfig, Programs>(testCtx, tcu::NODETYPE_SELF_VALIDATE, testName.c_str(), testName.c_str(), testConfig)); } group->addChild(formatGroup.release()); } } } // anonymous tcu::TestCaseGroup* createRenderPassMultisampleTests (tcu::TestContext& testCtx) { return createTestGroup(testCtx, "multisample", "Multisample render pass tests", initTests, RENDERPASS_TYPE_LEGACY); } tcu::TestCaseGroup* createRenderPass2MultisampleTests (tcu::TestContext& testCtx) { return createTestGroup(testCtx, "multisample", "Multisample render pass tests", initTests, RENDERPASS_TYPE_RENDERPASS2); } } // vkt
38.120821
240
0.675102
jljusten
2994d67d3bbf366a8f0401d3b7f7fb238dd697bf
476,963
cpp
C++
src/parser/SV3_1aPpParser.cpp
pieter3d/Surelog
4c21d5791553cf23090b5c4cdfa61a56d9a38482
[ "Apache-2.0" ]
null
null
null
src/parser/SV3_1aPpParser.cpp
pieter3d/Surelog
4c21d5791553cf23090b5c4cdfa61a56d9a38482
[ "Apache-2.0" ]
null
null
null
src/parser/SV3_1aPpParser.cpp
pieter3d/Surelog
4c21d5791553cf23090b5c4cdfa61a56d9a38482
[ "Apache-2.0" ]
null
null
null
// Generated from SV3_1aPpParser.g4 by ANTLR 4.9.2 #include "SV3_1aPpParserListener.h" #include "SV3_1aPpParser.h" using namespace antlrcpp; using namespace antlr4; SV3_1aPpParser::SV3_1aPpParser(TokenStream *input) : Parser(input) { _interpreter = new atn::ParserATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache); } SV3_1aPpParser::~SV3_1aPpParser() { delete _interpreter; } std::string SV3_1aPpParser::getGrammarFileName() const { return "SV3_1aPpParser.g4"; } const std::vector<std::string>& SV3_1aPpParser::getRuleNames() const { return _ruleNames; } dfa::Vocabulary& SV3_1aPpParser::getVocabulary() const { return _vocabulary; } //----------------- Top_level_ruleContext ------------------------------------------------------------------ SV3_1aPpParser::Top_level_ruleContext::Top_level_ruleContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } SV3_1aPpParser::Null_ruleContext* SV3_1aPpParser::Top_level_ruleContext::null_rule() { return getRuleContext<SV3_1aPpParser::Null_ruleContext>(0); } SV3_1aPpParser::Source_textContext* SV3_1aPpParser::Top_level_ruleContext::source_text() { return getRuleContext<SV3_1aPpParser::Source_textContext>(0); } tree::TerminalNode* SV3_1aPpParser::Top_level_ruleContext::EOF() { return getToken(SV3_1aPpParser::EOF, 0); } size_t SV3_1aPpParser::Top_level_ruleContext::getRuleIndex() const { return SV3_1aPpParser::RuleTop_level_rule; } void SV3_1aPpParser::Top_level_ruleContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterTop_level_rule(this); } void SV3_1aPpParser::Top_level_ruleContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitTop_level_rule(this); } SV3_1aPpParser::Top_level_ruleContext* SV3_1aPpParser::top_level_rule() { Top_level_ruleContext *_localctx = _tracker.createInstance<Top_level_ruleContext>(_ctx, getState()); enterRule(_localctx, 0, SV3_1aPpParser::RuleTop_level_rule); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(202); null_rule(); setState(203); source_text(); setState(204); match(SV3_1aPpParser::EOF); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Source_textContext ------------------------------------------------------------------ SV3_1aPpParser::Source_textContext::Source_textContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<SV3_1aPpParser::DescriptionContext *> SV3_1aPpParser::Source_textContext::description() { return getRuleContexts<SV3_1aPpParser::DescriptionContext>(); } SV3_1aPpParser::DescriptionContext* SV3_1aPpParser::Source_textContext::description(size_t i) { return getRuleContext<SV3_1aPpParser::DescriptionContext>(i); } size_t SV3_1aPpParser::Source_textContext::getRuleIndex() const { return SV3_1aPpParser::RuleSource_text; } void SV3_1aPpParser::Source_textContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSource_text(this); } void SV3_1aPpParser::Source_textContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSource_text(this); } SV3_1aPpParser::Source_textContext* SV3_1aPpParser::source_text() { Source_textContext *_localctx = _tracker.createInstance<Source_textContext>(_ctx, getState()); enterRule(_localctx, 2, SV3_1aPpParser::RuleSource_text); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(209); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment) | (1ULL << SV3_1aPpParser::TICK_VARIABLE) | (1ULL << SV3_1aPpParser::TICK_DEFINE) | (1ULL << SV3_1aPpParser::TICK_CELLDEFINE) | (1ULL << SV3_1aPpParser::TICK_ENDCELLDEFINE) | (1ULL << SV3_1aPpParser::TICK_DEFAULT_NETTYPE) | (1ULL << SV3_1aPpParser::TICK_UNDEF) | (1ULL << SV3_1aPpParser::TICK_IFDEF) | (1ULL << SV3_1aPpParser::TICK_IFNDEF) | (1ULL << SV3_1aPpParser::TICK_ELSE) | (1ULL << SV3_1aPpParser::TICK_ELSIF) | (1ULL << SV3_1aPpParser::TICK_ELSEIF) | (1ULL << SV3_1aPpParser::TICK_ENDIF) | (1ULL << SV3_1aPpParser::TICK_INCLUDE) | (1ULL << SV3_1aPpParser::TICK_PRAGMA) | (1ULL << SV3_1aPpParser::TICK_BEGIN_KEYWORDS) | (1ULL << SV3_1aPpParser::TICK_END_KEYWORDS) | (1ULL << SV3_1aPpParser::TICK_RESETALL) | (1ULL << SV3_1aPpParser::TICK_TIMESCALE) | (1ULL << SV3_1aPpParser::TICK_UNCONNECTED_DRIVE) | (1ULL << SV3_1aPpParser::TICK_NOUNCONNECTED_DRIVE) | (1ULL << SV3_1aPpParser::TICK_LINE) | (1ULL << SV3_1aPpParser::TICK_DEFAULT_DECAY_TIME) | (1ULL << SV3_1aPpParser::TICK_DEFAULT_TRIREG_STRENGTH) | (1ULL << SV3_1aPpParser::TICK_DELAY_MODE_DISTRIBUTED) | (1ULL << SV3_1aPpParser::TICK_DELAY_MODE_PATH) | (1ULL << SV3_1aPpParser::TICK_DELAY_MODE_UNIT) | (1ULL << SV3_1aPpParser::TICK_DELAY_MODE_ZERO) | (1ULL << SV3_1aPpParser::TICK_UNDEFINEALL) | (1ULL << SV3_1aPpParser::TICK_ACCELERATE) | (1ULL << SV3_1aPpParser::TICK_NOACCELERATE) | (1ULL << SV3_1aPpParser::TICK_PROTECT) | (1ULL << SV3_1aPpParser::TICK_USELIB) | (1ULL << SV3_1aPpParser::TICK_DISABLE_PORTFAULTS) | (1ULL << SV3_1aPpParser::TICK_ENABLE_PORTFAULTS) | (1ULL << SV3_1aPpParser::TICK_NOSUPPRESS_FAULTS) | (1ULL << SV3_1aPpParser::TICK_SUPPRESS_FAULTS) | (1ULL << SV3_1aPpParser::TICK_SIGNED) | (1ULL << SV3_1aPpParser::TICK_UNSIGNED) | (1ULL << SV3_1aPpParser::TICK_ENDPROTECT) | (1ULL << SV3_1aPpParser::TICK_PROTECTED) | (1ULL << SV3_1aPpParser::TICK_ENDPROTECTED) | (1ULL << SV3_1aPpParser::TICK_EXPAND_VECTORNETS) | (1ULL << SV3_1aPpParser::TICK_NOEXPAND_VECTORNETS) | (1ULL << SV3_1aPpParser::TICK_AUTOEXPAND_VECTORNETS) | (1ULL << SV3_1aPpParser::TICK_REMOVE_GATENAME) | (1ULL << SV3_1aPpParser::TICK_NOREMOVE_GATENAMES) | (1ULL << SV3_1aPpParser::TICK_REMOVE_NETNAME) | (1ULL << SV3_1aPpParser::TICK_NOREMOVE_NETNAMES) | (1ULL << SV3_1aPpParser::TICK_FILE__) | (1ULL << SV3_1aPpParser::TICK_LINE__) | (1ULL << SV3_1aPpParser::MODULE) | (1ULL << SV3_1aPpParser::ENDMODULE) | (1ULL << SV3_1aPpParser::INTERFACE) | (1ULL << SV3_1aPpParser::ENDINTERFACE) | (1ULL << SV3_1aPpParser::PROGRAM) | (1ULL << SV3_1aPpParser::ENDPROGRAM) | (1ULL << SV3_1aPpParser::PRIMITIVE) | (1ULL << SV3_1aPpParser::ENDPRIMITIVE) | (1ULL << SV3_1aPpParser::PACKAGE) | (1ULL << SV3_1aPpParser::ENDPACKAGE))) != 0) || ((((_la - 64) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 64)) & ((1ULL << (SV3_1aPpParser::CHECKER - 64)) | (1ULL << (SV3_1aPpParser::ENDCHECKER - 64)) | (1ULL << (SV3_1aPpParser::CONFIG - 64)) | (1ULL << (SV3_1aPpParser::ENDCONFIG - 64)) | (1ULL << (SV3_1aPpParser::Macro_identifier - 64)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 64)) | (1ULL << (SV3_1aPpParser::String - 64)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 64)) | (1ULL << (SV3_1aPpParser::Spaces - 64)) | (1ULL << (SV3_1aPpParser::Pound_Pound_delay - 64)) | (1ULL << (SV3_1aPpParser::Pound_delay - 64)) | (1ULL << (SV3_1aPpParser::TIMESCALE - 64)) | (1ULL << (SV3_1aPpParser::Number - 64)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 64)) | (1ULL << (SV3_1aPpParser::TEXT_CR - 64)) | (1ULL << (SV3_1aPpParser::ESCAPED_CR - 64)) | (1ULL << (SV3_1aPpParser::CR - 64)) | (1ULL << (SV3_1aPpParser::TICK_QUOTE - 64)) | (1ULL << (SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE - 64)) | (1ULL << (SV3_1aPpParser::TICK_TICK - 64)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 64)) | (1ULL << (SV3_1aPpParser::PARENS_CLOSE - 64)) | (1ULL << (SV3_1aPpParser::COMMA - 64)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 64)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 64)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 64)) | (1ULL << (SV3_1aPpParser::CURLY_CLOSE - 64)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 64)) | (1ULL << (SV3_1aPpParser::SQUARE_CLOSE - 64)) | (1ULL << (SV3_1aPpParser::Special - 64)) | (1ULL << (SV3_1aPpParser::ANY - 64)))) != 0)) { setState(206); description(); setState(211); _errHandler->sync(this); _la = _input->LA(1); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Null_ruleContext ------------------------------------------------------------------ SV3_1aPpParser::Null_ruleContext::Null_ruleContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t SV3_1aPpParser::Null_ruleContext::getRuleIndex() const { return SV3_1aPpParser::RuleNull_rule; } void SV3_1aPpParser::Null_ruleContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNull_rule(this); } void SV3_1aPpParser::Null_ruleContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNull_rule(this); } SV3_1aPpParser::Null_ruleContext* SV3_1aPpParser::null_rule() { Null_ruleContext *_localctx = _tracker.createInstance<Null_ruleContext>(_ctx, getState()); enterRule(_localctx, 4, SV3_1aPpParser::RuleNull_rule); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- DescriptionContext ------------------------------------------------------------------ SV3_1aPpParser::DescriptionContext::DescriptionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::DescriptionContext::escaped_identifier() { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(0); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::DescriptionContext::unterminated_string() { return getRuleContext<SV3_1aPpParser::Unterminated_stringContext>(0); } SV3_1aPpParser::StringContext* SV3_1aPpParser::DescriptionContext::string() { return getRuleContext<SV3_1aPpParser::StringContext>(0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::DescriptionContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } SV3_1aPpParser::Macro_definitionContext* SV3_1aPpParser::DescriptionContext::macro_definition() { return getRuleContext<SV3_1aPpParser::Macro_definitionContext>(0); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::DescriptionContext::comments() { return getRuleContext<SV3_1aPpParser::CommentsContext>(0); } SV3_1aPpParser::Celldefine_directiveContext* SV3_1aPpParser::DescriptionContext::celldefine_directive() { return getRuleContext<SV3_1aPpParser::Celldefine_directiveContext>(0); } SV3_1aPpParser::Endcelldefine_directiveContext* SV3_1aPpParser::DescriptionContext::endcelldefine_directive() { return getRuleContext<SV3_1aPpParser::Endcelldefine_directiveContext>(0); } SV3_1aPpParser::Default_nettype_directiveContext* SV3_1aPpParser::DescriptionContext::default_nettype_directive() { return getRuleContext<SV3_1aPpParser::Default_nettype_directiveContext>(0); } SV3_1aPpParser::Undef_directiveContext* SV3_1aPpParser::DescriptionContext::undef_directive() { return getRuleContext<SV3_1aPpParser::Undef_directiveContext>(0); } SV3_1aPpParser::Ifdef_directiveContext* SV3_1aPpParser::DescriptionContext::ifdef_directive() { return getRuleContext<SV3_1aPpParser::Ifdef_directiveContext>(0); } SV3_1aPpParser::Ifndef_directiveContext* SV3_1aPpParser::DescriptionContext::ifndef_directive() { return getRuleContext<SV3_1aPpParser::Ifndef_directiveContext>(0); } SV3_1aPpParser::Else_directiveContext* SV3_1aPpParser::DescriptionContext::else_directive() { return getRuleContext<SV3_1aPpParser::Else_directiveContext>(0); } SV3_1aPpParser::Elsif_directiveContext* SV3_1aPpParser::DescriptionContext::elsif_directive() { return getRuleContext<SV3_1aPpParser::Elsif_directiveContext>(0); } SV3_1aPpParser::Elseif_directiveContext* SV3_1aPpParser::DescriptionContext::elseif_directive() { return getRuleContext<SV3_1aPpParser::Elseif_directiveContext>(0); } SV3_1aPpParser::Endif_directiveContext* SV3_1aPpParser::DescriptionContext::endif_directive() { return getRuleContext<SV3_1aPpParser::Endif_directiveContext>(0); } SV3_1aPpParser::Include_directiveContext* SV3_1aPpParser::DescriptionContext::include_directive() { return getRuleContext<SV3_1aPpParser::Include_directiveContext>(0); } SV3_1aPpParser::Resetall_directiveContext* SV3_1aPpParser::DescriptionContext::resetall_directive() { return getRuleContext<SV3_1aPpParser::Resetall_directiveContext>(0); } SV3_1aPpParser::Begin_keywords_directiveContext* SV3_1aPpParser::DescriptionContext::begin_keywords_directive() { return getRuleContext<SV3_1aPpParser::Begin_keywords_directiveContext>(0); } SV3_1aPpParser::End_keywords_directiveContext* SV3_1aPpParser::DescriptionContext::end_keywords_directive() { return getRuleContext<SV3_1aPpParser::End_keywords_directiveContext>(0); } SV3_1aPpParser::Timescale_directiveContext* SV3_1aPpParser::DescriptionContext::timescale_directive() { return getRuleContext<SV3_1aPpParser::Timescale_directiveContext>(0); } SV3_1aPpParser::Unconnected_drive_directiveContext* SV3_1aPpParser::DescriptionContext::unconnected_drive_directive() { return getRuleContext<SV3_1aPpParser::Unconnected_drive_directiveContext>(0); } SV3_1aPpParser::Nounconnected_drive_directiveContext* SV3_1aPpParser::DescriptionContext::nounconnected_drive_directive() { return getRuleContext<SV3_1aPpParser::Nounconnected_drive_directiveContext>(0); } SV3_1aPpParser::Line_directiveContext* SV3_1aPpParser::DescriptionContext::line_directive() { return getRuleContext<SV3_1aPpParser::Line_directiveContext>(0); } SV3_1aPpParser::Default_decay_time_directiveContext* SV3_1aPpParser::DescriptionContext::default_decay_time_directive() { return getRuleContext<SV3_1aPpParser::Default_decay_time_directiveContext>(0); } SV3_1aPpParser::Default_trireg_strenght_directiveContext* SV3_1aPpParser::DescriptionContext::default_trireg_strenght_directive() { return getRuleContext<SV3_1aPpParser::Default_trireg_strenght_directiveContext>(0); } SV3_1aPpParser::Delay_mode_distributed_directiveContext* SV3_1aPpParser::DescriptionContext::delay_mode_distributed_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_distributed_directiveContext>(0); } SV3_1aPpParser::Delay_mode_path_directiveContext* SV3_1aPpParser::DescriptionContext::delay_mode_path_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_path_directiveContext>(0); } SV3_1aPpParser::Delay_mode_unit_directiveContext* SV3_1aPpParser::DescriptionContext::delay_mode_unit_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_unit_directiveContext>(0); } SV3_1aPpParser::Delay_mode_zero_directiveContext* SV3_1aPpParser::DescriptionContext::delay_mode_zero_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_zero_directiveContext>(0); } SV3_1aPpParser::Protect_directiveContext* SV3_1aPpParser::DescriptionContext::protect_directive() { return getRuleContext<SV3_1aPpParser::Protect_directiveContext>(0); } SV3_1aPpParser::Endprotect_directiveContext* SV3_1aPpParser::DescriptionContext::endprotect_directive() { return getRuleContext<SV3_1aPpParser::Endprotect_directiveContext>(0); } SV3_1aPpParser::Protected_directiveContext* SV3_1aPpParser::DescriptionContext::protected_directive() { return getRuleContext<SV3_1aPpParser::Protected_directiveContext>(0); } SV3_1aPpParser::Endprotected_directiveContext* SV3_1aPpParser::DescriptionContext::endprotected_directive() { return getRuleContext<SV3_1aPpParser::Endprotected_directiveContext>(0); } SV3_1aPpParser::Expand_vectornets_directiveContext* SV3_1aPpParser::DescriptionContext::expand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Expand_vectornets_directiveContext>(0); } SV3_1aPpParser::Noexpand_vectornets_directiveContext* SV3_1aPpParser::DescriptionContext::noexpand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Noexpand_vectornets_directiveContext>(0); } SV3_1aPpParser::Autoexpand_vectornets_directiveContext* SV3_1aPpParser::DescriptionContext::autoexpand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Autoexpand_vectornets_directiveContext>(0); } SV3_1aPpParser::Remove_gatename_directiveContext* SV3_1aPpParser::DescriptionContext::remove_gatename_directive() { return getRuleContext<SV3_1aPpParser::Remove_gatename_directiveContext>(0); } SV3_1aPpParser::Noremove_gatenames_directiveContext* SV3_1aPpParser::DescriptionContext::noremove_gatenames_directive() { return getRuleContext<SV3_1aPpParser::Noremove_gatenames_directiveContext>(0); } SV3_1aPpParser::Remove_netname_directiveContext* SV3_1aPpParser::DescriptionContext::remove_netname_directive() { return getRuleContext<SV3_1aPpParser::Remove_netname_directiveContext>(0); } SV3_1aPpParser::Noremove_netnames_directiveContext* SV3_1aPpParser::DescriptionContext::noremove_netnames_directive() { return getRuleContext<SV3_1aPpParser::Noremove_netnames_directiveContext>(0); } SV3_1aPpParser::Accelerate_directiveContext* SV3_1aPpParser::DescriptionContext::accelerate_directive() { return getRuleContext<SV3_1aPpParser::Accelerate_directiveContext>(0); } SV3_1aPpParser::Noaccelerate_directiveContext* SV3_1aPpParser::DescriptionContext::noaccelerate_directive() { return getRuleContext<SV3_1aPpParser::Noaccelerate_directiveContext>(0); } SV3_1aPpParser::Undefineall_directiveContext* SV3_1aPpParser::DescriptionContext::undefineall_directive() { return getRuleContext<SV3_1aPpParser::Undefineall_directiveContext>(0); } SV3_1aPpParser::Uselib_directiveContext* SV3_1aPpParser::DescriptionContext::uselib_directive() { return getRuleContext<SV3_1aPpParser::Uselib_directiveContext>(0); } SV3_1aPpParser::Disable_portfaults_directiveContext* SV3_1aPpParser::DescriptionContext::disable_portfaults_directive() { return getRuleContext<SV3_1aPpParser::Disable_portfaults_directiveContext>(0); } SV3_1aPpParser::Enable_portfaults_directiveContext* SV3_1aPpParser::DescriptionContext::enable_portfaults_directive() { return getRuleContext<SV3_1aPpParser::Enable_portfaults_directiveContext>(0); } SV3_1aPpParser::Nosuppress_faults_directiveContext* SV3_1aPpParser::DescriptionContext::nosuppress_faults_directive() { return getRuleContext<SV3_1aPpParser::Nosuppress_faults_directiveContext>(0); } SV3_1aPpParser::Suppress_faults_directiveContext* SV3_1aPpParser::DescriptionContext::suppress_faults_directive() { return getRuleContext<SV3_1aPpParser::Suppress_faults_directiveContext>(0); } SV3_1aPpParser::Signed_directiveContext* SV3_1aPpParser::DescriptionContext::signed_directive() { return getRuleContext<SV3_1aPpParser::Signed_directiveContext>(0); } SV3_1aPpParser::Unsigned_directiveContext* SV3_1aPpParser::DescriptionContext::unsigned_directive() { return getRuleContext<SV3_1aPpParser::Unsigned_directiveContext>(0); } SV3_1aPpParser::Pragma_directiveContext* SV3_1aPpParser::DescriptionContext::pragma_directive() { return getRuleContext<SV3_1aPpParser::Pragma_directiveContext>(0); } SV3_1aPpParser::Sv_file_directiveContext* SV3_1aPpParser::DescriptionContext::sv_file_directive() { return getRuleContext<SV3_1aPpParser::Sv_file_directiveContext>(0); } SV3_1aPpParser::Sv_line_directiveContext* SV3_1aPpParser::DescriptionContext::sv_line_directive() { return getRuleContext<SV3_1aPpParser::Sv_line_directiveContext>(0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::DescriptionContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } SV3_1aPpParser::ModuleContext* SV3_1aPpParser::DescriptionContext::module() { return getRuleContext<SV3_1aPpParser::ModuleContext>(0); } SV3_1aPpParser::EndmoduleContext* SV3_1aPpParser::DescriptionContext::endmodule() { return getRuleContext<SV3_1aPpParser::EndmoduleContext>(0); } SV3_1aPpParser::Sv_interfaceContext* SV3_1aPpParser::DescriptionContext::sv_interface() { return getRuleContext<SV3_1aPpParser::Sv_interfaceContext>(0); } SV3_1aPpParser::EndinterfaceContext* SV3_1aPpParser::DescriptionContext::endinterface() { return getRuleContext<SV3_1aPpParser::EndinterfaceContext>(0); } SV3_1aPpParser::ProgramContext* SV3_1aPpParser::DescriptionContext::program() { return getRuleContext<SV3_1aPpParser::ProgramContext>(0); } SV3_1aPpParser::EndprogramContext* SV3_1aPpParser::DescriptionContext::endprogram() { return getRuleContext<SV3_1aPpParser::EndprogramContext>(0); } SV3_1aPpParser::PrimitiveContext* SV3_1aPpParser::DescriptionContext::primitive() { return getRuleContext<SV3_1aPpParser::PrimitiveContext>(0); } SV3_1aPpParser::EndprimitiveContext* SV3_1aPpParser::DescriptionContext::endprimitive() { return getRuleContext<SV3_1aPpParser::EndprimitiveContext>(0); } SV3_1aPpParser::Sv_packageContext* SV3_1aPpParser::DescriptionContext::sv_package() { return getRuleContext<SV3_1aPpParser::Sv_packageContext>(0); } SV3_1aPpParser::EndpackageContext* SV3_1aPpParser::DescriptionContext::endpackage() { return getRuleContext<SV3_1aPpParser::EndpackageContext>(0); } SV3_1aPpParser::CheckerContext* SV3_1aPpParser::DescriptionContext::checker() { return getRuleContext<SV3_1aPpParser::CheckerContext>(0); } SV3_1aPpParser::EndcheckerContext* SV3_1aPpParser::DescriptionContext::endchecker() { return getRuleContext<SV3_1aPpParser::EndcheckerContext>(0); } SV3_1aPpParser::ConfigContext* SV3_1aPpParser::DescriptionContext::config() { return getRuleContext<SV3_1aPpParser::ConfigContext>(0); } SV3_1aPpParser::EndconfigContext* SV3_1aPpParser::DescriptionContext::endconfig() { return getRuleContext<SV3_1aPpParser::EndconfigContext>(0); } SV3_1aPpParser::Text_blobContext* SV3_1aPpParser::DescriptionContext::text_blob() { return getRuleContext<SV3_1aPpParser::Text_blobContext>(0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::DescriptionContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::DescriptionContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } size_t SV3_1aPpParser::DescriptionContext::getRuleIndex() const { return SV3_1aPpParser::RuleDescription; } void SV3_1aPpParser::DescriptionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDescription(this); } void SV3_1aPpParser::DescriptionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDescription(this); } SV3_1aPpParser::DescriptionContext* SV3_1aPpParser::description() { DescriptionContext *_localctx = _tracker.createInstance<DescriptionContext>(_ctx, getState()); enterRule(_localctx, 6, SV3_1aPpParser::RuleDescription); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(286); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 1, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(214); escaped_identifier(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(215); unterminated_string(); break; } case 3: { enterOuterAlt(_localctx, 3); setState(216); string(); break; } case 4: { enterOuterAlt(_localctx, 4); setState(217); number(); break; } case 5: { enterOuterAlt(_localctx, 5); setState(218); macro_definition(); break; } case 6: { enterOuterAlt(_localctx, 6); setState(219); comments(); break; } case 7: { enterOuterAlt(_localctx, 7); setState(220); celldefine_directive(); break; } case 8: { enterOuterAlt(_localctx, 8); setState(221); endcelldefine_directive(); break; } case 9: { enterOuterAlt(_localctx, 9); setState(222); default_nettype_directive(); break; } case 10: { enterOuterAlt(_localctx, 10); setState(223); undef_directive(); break; } case 11: { enterOuterAlt(_localctx, 11); setState(224); ifdef_directive(); break; } case 12: { enterOuterAlt(_localctx, 12); setState(225); ifndef_directive(); break; } case 13: { enterOuterAlt(_localctx, 13); setState(226); else_directive(); break; } case 14: { enterOuterAlt(_localctx, 14); setState(227); elsif_directive(); break; } case 15: { enterOuterAlt(_localctx, 15); setState(228); elseif_directive(); break; } case 16: { enterOuterAlt(_localctx, 16); setState(229); endif_directive(); break; } case 17: { enterOuterAlt(_localctx, 17); setState(230); include_directive(); break; } case 18: { enterOuterAlt(_localctx, 18); setState(231); resetall_directive(); break; } case 19: { enterOuterAlt(_localctx, 19); setState(232); begin_keywords_directive(); break; } case 20: { enterOuterAlt(_localctx, 20); setState(233); end_keywords_directive(); break; } case 21: { enterOuterAlt(_localctx, 21); setState(234); timescale_directive(); break; } case 22: { enterOuterAlt(_localctx, 22); setState(235); unconnected_drive_directive(); break; } case 23: { enterOuterAlt(_localctx, 23); setState(236); nounconnected_drive_directive(); break; } case 24: { enterOuterAlt(_localctx, 24); setState(237); line_directive(); break; } case 25: { enterOuterAlt(_localctx, 25); setState(238); default_decay_time_directive(); break; } case 26: { enterOuterAlt(_localctx, 26); setState(239); default_trireg_strenght_directive(); break; } case 27: { enterOuterAlt(_localctx, 27); setState(240); delay_mode_distributed_directive(); break; } case 28: { enterOuterAlt(_localctx, 28); setState(241); delay_mode_path_directive(); break; } case 29: { enterOuterAlt(_localctx, 29); setState(242); delay_mode_unit_directive(); break; } case 30: { enterOuterAlt(_localctx, 30); setState(243); delay_mode_zero_directive(); break; } case 31: { enterOuterAlt(_localctx, 31); setState(244); protect_directive(); break; } case 32: { enterOuterAlt(_localctx, 32); setState(245); endprotect_directive(); break; } case 33: { enterOuterAlt(_localctx, 33); setState(246); protected_directive(); break; } case 34: { enterOuterAlt(_localctx, 34); setState(247); endprotected_directive(); break; } case 35: { enterOuterAlt(_localctx, 35); setState(248); expand_vectornets_directive(); break; } case 36: { enterOuterAlt(_localctx, 36); setState(249); noexpand_vectornets_directive(); break; } case 37: { enterOuterAlt(_localctx, 37); setState(250); autoexpand_vectornets_directive(); break; } case 38: { enterOuterAlt(_localctx, 38); setState(251); remove_gatename_directive(); break; } case 39: { enterOuterAlt(_localctx, 39); setState(252); noremove_gatenames_directive(); break; } case 40: { enterOuterAlt(_localctx, 40); setState(253); remove_netname_directive(); break; } case 41: { enterOuterAlt(_localctx, 41); setState(254); noremove_netnames_directive(); break; } case 42: { enterOuterAlt(_localctx, 42); setState(255); accelerate_directive(); break; } case 43: { enterOuterAlt(_localctx, 43); setState(256); noaccelerate_directive(); break; } case 44: { enterOuterAlt(_localctx, 44); setState(257); undefineall_directive(); break; } case 45: { enterOuterAlt(_localctx, 45); setState(258); uselib_directive(); break; } case 46: { enterOuterAlt(_localctx, 46); setState(259); disable_portfaults_directive(); break; } case 47: { enterOuterAlt(_localctx, 47); setState(260); enable_portfaults_directive(); break; } case 48: { enterOuterAlt(_localctx, 48); setState(261); nosuppress_faults_directive(); break; } case 49: { enterOuterAlt(_localctx, 49); setState(262); suppress_faults_directive(); break; } case 50: { enterOuterAlt(_localctx, 50); setState(263); signed_directive(); break; } case 51: { enterOuterAlt(_localctx, 51); setState(264); unsigned_directive(); break; } case 52: { enterOuterAlt(_localctx, 52); setState(265); pragma_directive(); break; } case 53: { enterOuterAlt(_localctx, 53); setState(266); sv_file_directive(); break; } case 54: { enterOuterAlt(_localctx, 54); setState(267); sv_line_directive(); break; } case 55: { enterOuterAlt(_localctx, 55); setState(268); macro_instance(); break; } case 56: { enterOuterAlt(_localctx, 56); setState(269); module(); break; } case 57: { enterOuterAlt(_localctx, 57); setState(270); endmodule(); break; } case 58: { enterOuterAlt(_localctx, 58); setState(271); sv_interface(); break; } case 59: { enterOuterAlt(_localctx, 59); setState(272); endinterface(); break; } case 60: { enterOuterAlt(_localctx, 60); setState(273); program(); break; } case 61: { enterOuterAlt(_localctx, 61); setState(274); endprogram(); break; } case 62: { enterOuterAlt(_localctx, 62); setState(275); primitive(); break; } case 63: { enterOuterAlt(_localctx, 63); setState(276); endprimitive(); break; } case 64: { enterOuterAlt(_localctx, 64); setState(277); sv_package(); break; } case 65: { enterOuterAlt(_localctx, 65); setState(278); endpackage(); break; } case 66: { enterOuterAlt(_localctx, 66); setState(279); checker(); break; } case 67: { enterOuterAlt(_localctx, 67); setState(280); endchecker(); break; } case 68: { enterOuterAlt(_localctx, 68); setState(281); config(); break; } case 69: { enterOuterAlt(_localctx, 69); setState(282); endconfig(); break; } case 70: { enterOuterAlt(_localctx, 70); setState(283); text_blob(); break; } case 71: { enterOuterAlt(_localctx, 71); setState(284); pound_delay(); break; } case 72: { enterOuterAlt(_localctx, 72); setState(285); pound_pound_delay(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Escaped_identifierContext ------------------------------------------------------------------ SV3_1aPpParser::Escaped_identifierContext::Escaped_identifierContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Escaped_identifierContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } size_t SV3_1aPpParser::Escaped_identifierContext::getRuleIndex() const { return SV3_1aPpParser::RuleEscaped_identifier; } void SV3_1aPpParser::Escaped_identifierContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEscaped_identifier(this); } void SV3_1aPpParser::Escaped_identifierContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEscaped_identifier(this); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::escaped_identifier() { Escaped_identifierContext *_localctx = _tracker.createInstance<Escaped_identifierContext>(_ctx, getState()); enterRule(_localctx, 8, SV3_1aPpParser::RuleEscaped_identifier); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(288); match(SV3_1aPpParser::Escaped_identifier); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Macro_instanceContext ------------------------------------------------------------------ SV3_1aPpParser::Macro_instanceContext::Macro_instanceContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } size_t SV3_1aPpParser::Macro_instanceContext::getRuleIndex() const { return SV3_1aPpParser::RuleMacro_instance; } void SV3_1aPpParser::Macro_instanceContext::copyFrom(Macro_instanceContext *ctx) { ParserRuleContext::copyFrom(ctx); } //----------------- MacroInstanceWithArgsContext ------------------------------------------------------------------ tree::TerminalNode* SV3_1aPpParser::MacroInstanceWithArgsContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } SV3_1aPpParser::Macro_actual_argsContext* SV3_1aPpParser::MacroInstanceWithArgsContext::macro_actual_args() { return getRuleContext<SV3_1aPpParser::Macro_actual_argsContext>(0); } tree::TerminalNode* SV3_1aPpParser::MacroInstanceWithArgsContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::MacroInstanceWithArgsContext::Macro_identifier() { return getToken(SV3_1aPpParser::Macro_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::MacroInstanceWithArgsContext::Macro_Escaped_identifier() { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::MacroInstanceWithArgsContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::MacroInstanceWithArgsContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::MacroInstanceWithArgsContext::MacroInstanceWithArgsContext(Macro_instanceContext *ctx) { copyFrom(ctx); } void SV3_1aPpParser::MacroInstanceWithArgsContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacroInstanceWithArgs(this); } void SV3_1aPpParser::MacroInstanceWithArgsContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacroInstanceWithArgs(this); } //----------------- MacroInstanceNoArgsContext ------------------------------------------------------------------ tree::TerminalNode* SV3_1aPpParser::MacroInstanceNoArgsContext::Macro_identifier() { return getToken(SV3_1aPpParser::Macro_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::MacroInstanceNoArgsContext::Macro_Escaped_identifier() { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, 0); } SV3_1aPpParser::MacroInstanceNoArgsContext::MacroInstanceNoArgsContext(Macro_instanceContext *ctx) { copyFrom(ctx); } void SV3_1aPpParser::MacroInstanceNoArgsContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacroInstanceNoArgs(this); } void SV3_1aPpParser::MacroInstanceNoArgsContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacroInstanceNoArgs(this); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::macro_instance() { Macro_instanceContext *_localctx = _tracker.createInstance<Macro_instanceContext>(_ctx, getState()); enterRule(_localctx, 10, SV3_1aPpParser::RuleMacro_instance); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(302); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 3, _ctx)) { case 1: { _localctx = parsetree_cast<Macro_instanceContext>(_tracker.createInstance<SV3_1aPpParser::MacroInstanceWithArgsContext>(_localctx)); enterOuterAlt(_localctx, 1); setState(290); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Macro_identifier || _la == SV3_1aPpParser::Macro_Escaped_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(294); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(291); match(SV3_1aPpParser::Spaces); setState(296); _errHandler->sync(this); _la = _input->LA(1); } setState(297); match(SV3_1aPpParser::PARENS_OPEN); setState(298); macro_actual_args(); setState(299); match(SV3_1aPpParser::PARENS_CLOSE); break; } case 2: { _localctx = parsetree_cast<Macro_instanceContext>(_tracker.createInstance<SV3_1aPpParser::MacroInstanceNoArgsContext>(_localctx)); enterOuterAlt(_localctx, 2); setState(301); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Macro_identifier || _la == SV3_1aPpParser::Macro_Escaped_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Unterminated_stringContext ------------------------------------------------------------------ SV3_1aPpParser::Unterminated_stringContext::Unterminated_stringContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Unterminated_stringContext::DOUBLE_QUOTE() { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, 0); } tree::TerminalNode* SV3_1aPpParser::Unterminated_stringContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<SV3_1aPpParser::String_blobContext *> SV3_1aPpParser::Unterminated_stringContext::string_blob() { return getRuleContexts<SV3_1aPpParser::String_blobContext>(); } SV3_1aPpParser::String_blobContext* SV3_1aPpParser::Unterminated_stringContext::string_blob(size_t i) { return getRuleContext<SV3_1aPpParser::String_blobContext>(i); } size_t SV3_1aPpParser::Unterminated_stringContext::getRuleIndex() const { return SV3_1aPpParser::RuleUnterminated_string; } void SV3_1aPpParser::Unterminated_stringContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUnterminated_string(this); } void SV3_1aPpParser::Unterminated_stringContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUnterminated_string(this); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::unterminated_string() { Unterminated_stringContext *_localctx = _tracker.createInstance<Unterminated_stringContext>(_ctx, getState()); enterRule(_localctx, 12, SV3_1aPpParser::RuleUnterminated_string); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(304); match(SV3_1aPpParser::DOUBLE_QUOTE); setState(308); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Escaped_identifier || ((((_la - 71) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 71)) & ((1ULL << (SV3_1aPpParser::Simple_identifier - 71)) | (1ULL << (SV3_1aPpParser::Spaces - 71)) | (1ULL << (SV3_1aPpParser::Pound_Pound_delay - 71)) | (1ULL << (SV3_1aPpParser::Pound_delay - 71)) | (1ULL << (SV3_1aPpParser::TIMESCALE - 71)) | (1ULL << (SV3_1aPpParser::Number - 71)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 71)) | (1ULL << (SV3_1aPpParser::TEXT_CR - 71)) | (1ULL << (SV3_1aPpParser::ESCAPED_CR - 71)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 71)) | (1ULL << (SV3_1aPpParser::PARENS_CLOSE - 71)) | (1ULL << (SV3_1aPpParser::COMMA - 71)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 71)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 71)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 71)) | (1ULL << (SV3_1aPpParser::CURLY_CLOSE - 71)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 71)) | (1ULL << (SV3_1aPpParser::SQUARE_CLOSE - 71)) | (1ULL << (SV3_1aPpParser::Special - 71)) | (1ULL << (SV3_1aPpParser::ANY - 71)))) != 0)) { setState(305); string_blob(); setState(310); _errHandler->sync(this); _la = _input->LA(1); } setState(311); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Macro_actual_argsContext ------------------------------------------------------------------ SV3_1aPpParser::Macro_actual_argsContext::Macro_actual_argsContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<SV3_1aPpParser::Macro_argContext *> SV3_1aPpParser::Macro_actual_argsContext::macro_arg() { return getRuleContexts<SV3_1aPpParser::Macro_argContext>(); } SV3_1aPpParser::Macro_argContext* SV3_1aPpParser::Macro_actual_argsContext::macro_arg(size_t i) { return getRuleContext<SV3_1aPpParser::Macro_argContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Macro_actual_argsContext::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Macro_actual_argsContext::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } size_t SV3_1aPpParser::Macro_actual_argsContext::getRuleIndex() const { return SV3_1aPpParser::RuleMacro_actual_args; } void SV3_1aPpParser::Macro_actual_argsContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacro_actual_args(this); } void SV3_1aPpParser::Macro_actual_argsContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacro_actual_args(this); } SV3_1aPpParser::Macro_actual_argsContext* SV3_1aPpParser::macro_actual_args() { Macro_actual_argsContext *_localctx = _tracker.createInstance<Macro_actual_argsContext>(_ctx, getState()); enterRule(_localctx, 14, SV3_1aPpParser::RuleMacro_actual_args); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(316); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment) | (1ULL << SV3_1aPpParser::TICK_DEFINE))) != 0) || ((((_la - 68) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 68)) & ((1ULL << (SV3_1aPpParser::Macro_identifier - 68)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 68)) | (1ULL << (SV3_1aPpParser::String - 68)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 68)) | (1ULL << (SV3_1aPpParser::Spaces - 68)) | (1ULL << (SV3_1aPpParser::Pound_Pound_delay - 68)) | (1ULL << (SV3_1aPpParser::Pound_delay - 68)) | (1ULL << (SV3_1aPpParser::Number - 68)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 68)) | (1ULL << (SV3_1aPpParser::TEXT_CR - 68)) | (1ULL << (SV3_1aPpParser::CR - 68)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 68)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 68)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 68)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 68)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 68)) | (1ULL << (SV3_1aPpParser::Special - 68)) | (1ULL << (SV3_1aPpParser::ANY - 68)))) != 0)) { setState(313); macro_arg(); setState(318); _errHandler->sync(this); _la = _input->LA(1); } setState(328); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::COMMA) { setState(319); match(SV3_1aPpParser::COMMA); setState(323); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment) | (1ULL << SV3_1aPpParser::TICK_DEFINE))) != 0) || ((((_la - 68) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 68)) & ((1ULL << (SV3_1aPpParser::Macro_identifier - 68)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 68)) | (1ULL << (SV3_1aPpParser::String - 68)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 68)) | (1ULL << (SV3_1aPpParser::Spaces - 68)) | (1ULL << (SV3_1aPpParser::Pound_Pound_delay - 68)) | (1ULL << (SV3_1aPpParser::Pound_delay - 68)) | (1ULL << (SV3_1aPpParser::Number - 68)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 68)) | (1ULL << (SV3_1aPpParser::TEXT_CR - 68)) | (1ULL << (SV3_1aPpParser::CR - 68)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 68)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 68)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 68)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 68)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 68)) | (1ULL << (SV3_1aPpParser::Special - 68)) | (1ULL << (SV3_1aPpParser::ANY - 68)))) != 0)) { setState(320); macro_arg(); setState(325); _errHandler->sync(this); _la = _input->LA(1); } setState(330); _errHandler->sync(this); _la = _input->LA(1); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- CommentsContext ------------------------------------------------------------------ SV3_1aPpParser::CommentsContext::CommentsContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::CommentsContext::One_line_comment() { return getToken(SV3_1aPpParser::One_line_comment, 0); } tree::TerminalNode* SV3_1aPpParser::CommentsContext::Block_comment() { return getToken(SV3_1aPpParser::Block_comment, 0); } size_t SV3_1aPpParser::CommentsContext::getRuleIndex() const { return SV3_1aPpParser::RuleComments; } void SV3_1aPpParser::CommentsContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterComments(this); } void SV3_1aPpParser::CommentsContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitComments(this); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::comments() { CommentsContext *_localctx = _tracker.createInstance<CommentsContext>(_ctx, getState()); enterRule(_localctx, 16, SV3_1aPpParser::RuleComments); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(331); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::One_line_comment || _la == SV3_1aPpParser::Block_comment)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- NumberContext ------------------------------------------------------------------ SV3_1aPpParser::NumberContext::NumberContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::NumberContext::Number() { return getToken(SV3_1aPpParser::Number, 0); } size_t SV3_1aPpParser::NumberContext::getRuleIndex() const { return SV3_1aPpParser::RuleNumber; } void SV3_1aPpParser::NumberContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNumber(this); } void SV3_1aPpParser::NumberContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNumber(this); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::number() { NumberContext *_localctx = _tracker.createInstance<NumberContext>(_ctx, getState()); enterRule(_localctx, 18, SV3_1aPpParser::RuleNumber); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(333); match(SV3_1aPpParser::Number); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Pound_delayContext ------------------------------------------------------------------ SV3_1aPpParser::Pound_delayContext::Pound_delayContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Pound_delayContext::Pound_delay() { return getToken(SV3_1aPpParser::Pound_delay, 0); } size_t SV3_1aPpParser::Pound_delayContext::getRuleIndex() const { return SV3_1aPpParser::RulePound_delay; } void SV3_1aPpParser::Pound_delayContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPound_delay(this); } void SV3_1aPpParser::Pound_delayContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPound_delay(this); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::pound_delay() { Pound_delayContext *_localctx = _tracker.createInstance<Pound_delayContext>(_ctx, getState()); enterRule(_localctx, 20, SV3_1aPpParser::RulePound_delay); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(335); match(SV3_1aPpParser::Pound_delay); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Pound_pound_delayContext ------------------------------------------------------------------ SV3_1aPpParser::Pound_pound_delayContext::Pound_pound_delayContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Pound_pound_delayContext::Pound_Pound_delay() { return getToken(SV3_1aPpParser::Pound_Pound_delay, 0); } size_t SV3_1aPpParser::Pound_pound_delayContext::getRuleIndex() const { return SV3_1aPpParser::RulePound_pound_delay; } void SV3_1aPpParser::Pound_pound_delayContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPound_pound_delay(this); } void SV3_1aPpParser::Pound_pound_delayContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPound_pound_delay(this); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::pound_pound_delay() { Pound_pound_delayContext *_localctx = _tracker.createInstance<Pound_pound_delayContext>(_ctx, getState()); enterRule(_localctx, 22, SV3_1aPpParser::RulePound_pound_delay); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(337); match(SV3_1aPpParser::Pound_Pound_delay); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Macro_definitionContext ------------------------------------------------------------------ SV3_1aPpParser::Macro_definitionContext::Macro_definitionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } SV3_1aPpParser::Define_directiveContext* SV3_1aPpParser::Macro_definitionContext::define_directive() { return getRuleContext<SV3_1aPpParser::Define_directiveContext>(0); } SV3_1aPpParser::Multiline_args_macro_definitionContext* SV3_1aPpParser::Macro_definitionContext::multiline_args_macro_definition() { return getRuleContext<SV3_1aPpParser::Multiline_args_macro_definitionContext>(0); } SV3_1aPpParser::Simple_no_args_macro_definitionContext* SV3_1aPpParser::Macro_definitionContext::simple_no_args_macro_definition() { return getRuleContext<SV3_1aPpParser::Simple_no_args_macro_definitionContext>(0); } SV3_1aPpParser::Multiline_no_args_macro_definitionContext* SV3_1aPpParser::Macro_definitionContext::multiline_no_args_macro_definition() { return getRuleContext<SV3_1aPpParser::Multiline_no_args_macro_definitionContext>(0); } SV3_1aPpParser::Simple_args_macro_definitionContext* SV3_1aPpParser::Macro_definitionContext::simple_args_macro_definition() { return getRuleContext<SV3_1aPpParser::Simple_args_macro_definitionContext>(0); } size_t SV3_1aPpParser::Macro_definitionContext::getRuleIndex() const { return SV3_1aPpParser::RuleMacro_definition; } void SV3_1aPpParser::Macro_definitionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacro_definition(this); } void SV3_1aPpParser::Macro_definitionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacro_definition(this); } SV3_1aPpParser::Macro_definitionContext* SV3_1aPpParser::macro_definition() { Macro_definitionContext *_localctx = _tracker.createInstance<Macro_definitionContext>(_ctx, getState()); enterRule(_localctx, 24, SV3_1aPpParser::RuleMacro_definition); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(344); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 8, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(339); define_directive(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(340); multiline_args_macro_definition(); break; } case 3: { enterOuterAlt(_localctx, 3); setState(341); simple_no_args_macro_definition(); break; } case 4: { enterOuterAlt(_localctx, 4); setState(342); multiline_no_args_macro_definition(); break; } case 5: { enterOuterAlt(_localctx, 5); setState(343); simple_args_macro_definition(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Include_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Include_directiveContext::Include_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Include_directiveContext::TICK_INCLUDE() { return getToken(SV3_1aPpParser::TICK_INCLUDE, 0); } tree::TerminalNode* SV3_1aPpParser::Include_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Include_directiveContext::String() { return getToken(SV3_1aPpParser::String, 0); } tree::TerminalNode* SV3_1aPpParser::Include_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Include_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Include_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Include_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleInclude_directive; } void SV3_1aPpParser::Include_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterInclude_directive(this); } void SV3_1aPpParser::Include_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitInclude_directive(this); } SV3_1aPpParser::Include_directiveContext* SV3_1aPpParser::include_directive() { Include_directiveContext *_localctx = _tracker.createInstance<Include_directiveContext>(_ctx, getState()); enterRule(_localctx, 26, SV3_1aPpParser::RuleInclude_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(346); match(SV3_1aPpParser::TICK_INCLUDE); setState(347); match(SV3_1aPpParser::Spaces); setState(352); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::String: { setState(348); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::Simple_identifier: { setState(349); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(350); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(351); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Line_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Line_directiveContext::Line_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Line_directiveContext::TICK_LINE() { return getToken(SV3_1aPpParser::TICK_LINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Line_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Line_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Line_directiveContext::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Line_directiveContext::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } tree::TerminalNode* SV3_1aPpParser::Line_directiveContext::String() { return getToken(SV3_1aPpParser::String, 0); } size_t SV3_1aPpParser::Line_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleLine_directive; } void SV3_1aPpParser::Line_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterLine_directive(this); } void SV3_1aPpParser::Line_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitLine_directive(this); } SV3_1aPpParser::Line_directiveContext* SV3_1aPpParser::line_directive() { Line_directiveContext *_localctx = _tracker.createInstance<Line_directiveContext>(_ctx, getState()); enterRule(_localctx, 28, SV3_1aPpParser::RuleLine_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(354); match(SV3_1aPpParser::TICK_LINE); setState(355); match(SV3_1aPpParser::Spaces); setState(356); number(); setState(357); match(SV3_1aPpParser::String); setState(358); match(SV3_1aPpParser::Spaces); setState(359); number(); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Default_nettype_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Default_nettype_directiveContext::Default_nettype_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Default_nettype_directiveContext::TICK_DEFAULT_NETTYPE() { return getToken(SV3_1aPpParser::TICK_DEFAULT_NETTYPE, 0); } tree::TerminalNode* SV3_1aPpParser::Default_nettype_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Default_nettype_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } size_t SV3_1aPpParser::Default_nettype_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDefault_nettype_directive; } void SV3_1aPpParser::Default_nettype_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDefault_nettype_directive(this); } void SV3_1aPpParser::Default_nettype_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDefault_nettype_directive(this); } SV3_1aPpParser::Default_nettype_directiveContext* SV3_1aPpParser::default_nettype_directive() { Default_nettype_directiveContext *_localctx = _tracker.createInstance<Default_nettype_directiveContext>(_ctx, getState()); enterRule(_localctx, 30, SV3_1aPpParser::RuleDefault_nettype_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(361); match(SV3_1aPpParser::TICK_DEFAULT_NETTYPE); setState(362); match(SV3_1aPpParser::Spaces); setState(363); match(SV3_1aPpParser::Simple_identifier); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Sv_file_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Sv_file_directiveContext::Sv_file_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Sv_file_directiveContext::TICK_FILE__() { return getToken(SV3_1aPpParser::TICK_FILE__, 0); } size_t SV3_1aPpParser::Sv_file_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleSv_file_directive; } void SV3_1aPpParser::Sv_file_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSv_file_directive(this); } void SV3_1aPpParser::Sv_file_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSv_file_directive(this); } SV3_1aPpParser::Sv_file_directiveContext* SV3_1aPpParser::sv_file_directive() { Sv_file_directiveContext *_localctx = _tracker.createInstance<Sv_file_directiveContext>(_ctx, getState()); enterRule(_localctx, 32, SV3_1aPpParser::RuleSv_file_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(365); match(SV3_1aPpParser::TICK_FILE__); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Sv_line_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Sv_line_directiveContext::Sv_line_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Sv_line_directiveContext::TICK_LINE__() { return getToken(SV3_1aPpParser::TICK_LINE__, 0); } size_t SV3_1aPpParser::Sv_line_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleSv_line_directive; } void SV3_1aPpParser::Sv_line_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSv_line_directive(this); } void SV3_1aPpParser::Sv_line_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSv_line_directive(this); } SV3_1aPpParser::Sv_line_directiveContext* SV3_1aPpParser::sv_line_directive() { Sv_line_directiveContext *_localctx = _tracker.createInstance<Sv_line_directiveContext>(_ctx, getState()); enterRule(_localctx, 34, SV3_1aPpParser::RuleSv_line_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(367); match(SV3_1aPpParser::TICK_LINE__); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Timescale_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Timescale_directiveContext::Timescale_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Timescale_directiveContext::TICK_TIMESCALE() { return getToken(SV3_1aPpParser::TICK_TIMESCALE, 0); } tree::TerminalNode* SV3_1aPpParser::Timescale_directiveContext::TIMESCALE() { return getToken(SV3_1aPpParser::TIMESCALE, 0); } size_t SV3_1aPpParser::Timescale_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleTimescale_directive; } void SV3_1aPpParser::Timescale_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterTimescale_directive(this); } void SV3_1aPpParser::Timescale_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitTimescale_directive(this); } SV3_1aPpParser::Timescale_directiveContext* SV3_1aPpParser::timescale_directive() { Timescale_directiveContext *_localctx = _tracker.createInstance<Timescale_directiveContext>(_ctx, getState()); enterRule(_localctx, 36, SV3_1aPpParser::RuleTimescale_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(369); match(SV3_1aPpParser::TICK_TIMESCALE); setState(370); match(SV3_1aPpParser::TIMESCALE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Undef_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Undef_directiveContext::Undef_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Undef_directiveContext::TICK_UNDEF() { return getToken(SV3_1aPpParser::TICK_UNDEF, 0); } tree::TerminalNode* SV3_1aPpParser::Undef_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Undef_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Undef_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Undef_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Undef_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleUndef_directive; } void SV3_1aPpParser::Undef_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUndef_directive(this); } void SV3_1aPpParser::Undef_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUndef_directive(this); } SV3_1aPpParser::Undef_directiveContext* SV3_1aPpParser::undef_directive() { Undef_directiveContext *_localctx = _tracker.createInstance<Undef_directiveContext>(_ctx, getState()); enterRule(_localctx, 38, SV3_1aPpParser::RuleUndef_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(372); match(SV3_1aPpParser::TICK_UNDEF); setState(373); match(SV3_1aPpParser::Spaces); setState(377); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(374); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(375); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(376); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Ifdef_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Ifdef_directiveContext::Ifdef_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Ifdef_directiveContext::TICK_IFDEF() { return getToken(SV3_1aPpParser::TICK_IFDEF, 0); } tree::TerminalNode* SV3_1aPpParser::Ifdef_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Ifdef_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Ifdef_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Ifdef_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Ifdef_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleIfdef_directive; } void SV3_1aPpParser::Ifdef_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterIfdef_directive(this); } void SV3_1aPpParser::Ifdef_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitIfdef_directive(this); } SV3_1aPpParser::Ifdef_directiveContext* SV3_1aPpParser::ifdef_directive() { Ifdef_directiveContext *_localctx = _tracker.createInstance<Ifdef_directiveContext>(_ctx, getState()); enterRule(_localctx, 40, SV3_1aPpParser::RuleIfdef_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(379); match(SV3_1aPpParser::TICK_IFDEF); setState(380); match(SV3_1aPpParser::Spaces); setState(384); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(381); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(382); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(383); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Ifdef_directive_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::Ifdef_directive_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::TICK_IFDEF() { return getToken(SV3_1aPpParser::TICK_IFDEF, 0); } tree::TerminalNode* SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleIfdef_directive_in_macro_body; } void SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterIfdef_directive_in_macro_body(this); } void SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitIfdef_directive_in_macro_body(this); } SV3_1aPpParser::Ifdef_directive_in_macro_bodyContext* SV3_1aPpParser::ifdef_directive_in_macro_body() { Ifdef_directive_in_macro_bodyContext *_localctx = _tracker.createInstance<Ifdef_directive_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 42, SV3_1aPpParser::RuleIfdef_directive_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(386); match(SV3_1aPpParser::TICK_IFDEF); setState(387); match(SV3_1aPpParser::Spaces); setState(391); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::EOF: case SV3_1aPpParser::Simple_identifier: { setState(388); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(389); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(390); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Ifndef_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Ifndef_directiveContext::Ifndef_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Ifndef_directiveContext::TICK_IFNDEF() { return getToken(SV3_1aPpParser::TICK_IFNDEF, 0); } tree::TerminalNode* SV3_1aPpParser::Ifndef_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Ifndef_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Ifndef_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Ifndef_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Ifndef_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleIfndef_directive; } void SV3_1aPpParser::Ifndef_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterIfndef_directive(this); } void SV3_1aPpParser::Ifndef_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitIfndef_directive(this); } SV3_1aPpParser::Ifndef_directiveContext* SV3_1aPpParser::ifndef_directive() { Ifndef_directiveContext *_localctx = _tracker.createInstance<Ifndef_directiveContext>(_ctx, getState()); enterRule(_localctx, 44, SV3_1aPpParser::RuleIfndef_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(393); match(SV3_1aPpParser::TICK_IFNDEF); setState(394); match(SV3_1aPpParser::Spaces); setState(398); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(395); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(396); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(397); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Ifndef_directive_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::Ifndef_directive_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::TICK_IFNDEF() { return getToken(SV3_1aPpParser::TICK_IFNDEF, 0); } tree::TerminalNode* SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleIfndef_directive_in_macro_body; } void SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterIfndef_directive_in_macro_body(this); } void SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitIfndef_directive_in_macro_body(this); } SV3_1aPpParser::Ifndef_directive_in_macro_bodyContext* SV3_1aPpParser::ifndef_directive_in_macro_body() { Ifndef_directive_in_macro_bodyContext *_localctx = _tracker.createInstance<Ifndef_directive_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 46, SV3_1aPpParser::RuleIfndef_directive_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(400); match(SV3_1aPpParser::TICK_IFNDEF); setState(401); match(SV3_1aPpParser::Spaces); setState(405); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::EOF: case SV3_1aPpParser::Simple_identifier: { setState(402); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(403); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(404); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Elsif_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Elsif_directiveContext::Elsif_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Elsif_directiveContext::TICK_ELSIF() { return getToken(SV3_1aPpParser::TICK_ELSIF, 0); } tree::TerminalNode* SV3_1aPpParser::Elsif_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Elsif_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Elsif_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Elsif_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Elsif_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleElsif_directive; } void SV3_1aPpParser::Elsif_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterElsif_directive(this); } void SV3_1aPpParser::Elsif_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitElsif_directive(this); } SV3_1aPpParser::Elsif_directiveContext* SV3_1aPpParser::elsif_directive() { Elsif_directiveContext *_localctx = _tracker.createInstance<Elsif_directiveContext>(_ctx, getState()); enterRule(_localctx, 48, SV3_1aPpParser::RuleElsif_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(407); match(SV3_1aPpParser::TICK_ELSIF); setState(408); match(SV3_1aPpParser::Spaces); setState(412); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(409); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(410); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(411); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Elsif_directive_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::Elsif_directive_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::TICK_ELSIF() { return getToken(SV3_1aPpParser::TICK_ELSIF, 0); } tree::TerminalNode* SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleElsif_directive_in_macro_body; } void SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterElsif_directive_in_macro_body(this); } void SV3_1aPpParser::Elsif_directive_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitElsif_directive_in_macro_body(this); } SV3_1aPpParser::Elsif_directive_in_macro_bodyContext* SV3_1aPpParser::elsif_directive_in_macro_body() { Elsif_directive_in_macro_bodyContext *_localctx = _tracker.createInstance<Elsif_directive_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 50, SV3_1aPpParser::RuleElsif_directive_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(414); match(SV3_1aPpParser::TICK_ELSIF); setState(415); match(SV3_1aPpParser::Spaces); setState(419); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::EOF: case SV3_1aPpParser::Simple_identifier: { setState(416); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(417); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(418); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Elseif_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Elseif_directiveContext::Elseif_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Elseif_directiveContext::TICK_ELSEIF() { return getToken(SV3_1aPpParser::TICK_ELSEIF, 0); } tree::TerminalNode* SV3_1aPpParser::Elseif_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Elseif_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Elseif_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Elseif_directiveContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Elseif_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleElseif_directive; } void SV3_1aPpParser::Elseif_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterElseif_directive(this); } void SV3_1aPpParser::Elseif_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitElseif_directive(this); } SV3_1aPpParser::Elseif_directiveContext* SV3_1aPpParser::elseif_directive() { Elseif_directiveContext *_localctx = _tracker.createInstance<Elseif_directiveContext>(_ctx, getState()); enterRule(_localctx, 52, SV3_1aPpParser::RuleElseif_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(421); match(SV3_1aPpParser::TICK_ELSEIF); setState(422); match(SV3_1aPpParser::Spaces); setState(426); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(423); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Escaped_identifier: { setState(424); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(425); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Elseif_directive_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::Elseif_directive_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::TICK_ELSEIF() { return getToken(SV3_1aPpParser::TICK_ELSEIF, 0); } tree::TerminalNode* SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } size_t SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleElseif_directive_in_macro_body; } void SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterElseif_directive_in_macro_body(this); } void SV3_1aPpParser::Elseif_directive_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitElseif_directive_in_macro_body(this); } SV3_1aPpParser::Elseif_directive_in_macro_bodyContext* SV3_1aPpParser::elseif_directive_in_macro_body() { Elseif_directive_in_macro_bodyContext *_localctx = _tracker.createInstance<Elseif_directive_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 54, SV3_1aPpParser::RuleElseif_directive_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(428); match(SV3_1aPpParser::TICK_ELSEIF); setState(429); match(SV3_1aPpParser::Spaces); setState(433); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::EOF: case SV3_1aPpParser::Simple_identifier: { setState(430); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(431); match(SV3_1aPpParser::Escaped_identifier); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(432); macro_instance(); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Else_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Else_directiveContext::Else_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Else_directiveContext::TICK_ELSE() { return getToken(SV3_1aPpParser::TICK_ELSE, 0); } size_t SV3_1aPpParser::Else_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleElse_directive; } void SV3_1aPpParser::Else_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterElse_directive(this); } void SV3_1aPpParser::Else_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitElse_directive(this); } SV3_1aPpParser::Else_directiveContext* SV3_1aPpParser::else_directive() { Else_directiveContext *_localctx = _tracker.createInstance<Else_directiveContext>(_ctx, getState()); enterRule(_localctx, 56, SV3_1aPpParser::RuleElse_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(435); match(SV3_1aPpParser::TICK_ELSE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Endif_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Endif_directiveContext::Endif_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Endif_directiveContext::TICK_ENDIF() { return getToken(SV3_1aPpParser::TICK_ENDIF, 0); } tree::TerminalNode* SV3_1aPpParser::Endif_directiveContext::One_line_comment() { return getToken(SV3_1aPpParser::One_line_comment, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Endif_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Endif_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Endif_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndif_directive; } void SV3_1aPpParser::Endif_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndif_directive(this); } void SV3_1aPpParser::Endif_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndif_directive(this); } SV3_1aPpParser::Endif_directiveContext* SV3_1aPpParser::endif_directive() { Endif_directiveContext *_localctx = _tracker.createInstance<Endif_directiveContext>(_ctx, getState()); enterRule(_localctx, 58, SV3_1aPpParser::RuleEndif_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(446); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 20, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(437); match(SV3_1aPpParser::TICK_ENDIF); setState(441); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(438); match(SV3_1aPpParser::Spaces); setState(443); _errHandler->sync(this); _la = _input->LA(1); } setState(444); match(SV3_1aPpParser::One_line_comment); break; } case 2: { enterOuterAlt(_localctx, 2); setState(445); match(SV3_1aPpParser::TICK_ENDIF); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Resetall_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Resetall_directiveContext::Resetall_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Resetall_directiveContext::TICK_RESETALL() { return getToken(SV3_1aPpParser::TICK_RESETALL, 0); } size_t SV3_1aPpParser::Resetall_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleResetall_directive; } void SV3_1aPpParser::Resetall_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterResetall_directive(this); } void SV3_1aPpParser::Resetall_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitResetall_directive(this); } SV3_1aPpParser::Resetall_directiveContext* SV3_1aPpParser::resetall_directive() { Resetall_directiveContext *_localctx = _tracker.createInstance<Resetall_directiveContext>(_ctx, getState()); enterRule(_localctx, 60, SV3_1aPpParser::RuleResetall_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(448); match(SV3_1aPpParser::TICK_RESETALL); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Begin_keywords_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Begin_keywords_directiveContext::Begin_keywords_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Begin_keywords_directiveContext::TICK_BEGIN_KEYWORDS() { return getToken(SV3_1aPpParser::TICK_BEGIN_KEYWORDS, 0); } tree::TerminalNode* SV3_1aPpParser::Begin_keywords_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Begin_keywords_directiveContext::String() { return getToken(SV3_1aPpParser::String, 0); } size_t SV3_1aPpParser::Begin_keywords_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleBegin_keywords_directive; } void SV3_1aPpParser::Begin_keywords_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterBegin_keywords_directive(this); } void SV3_1aPpParser::Begin_keywords_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitBegin_keywords_directive(this); } SV3_1aPpParser::Begin_keywords_directiveContext* SV3_1aPpParser::begin_keywords_directive() { Begin_keywords_directiveContext *_localctx = _tracker.createInstance<Begin_keywords_directiveContext>(_ctx, getState()); enterRule(_localctx, 62, SV3_1aPpParser::RuleBegin_keywords_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(450); match(SV3_1aPpParser::TICK_BEGIN_KEYWORDS); setState(451); match(SV3_1aPpParser::Spaces); setState(452); match(SV3_1aPpParser::String); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- End_keywords_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::End_keywords_directiveContext::End_keywords_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::End_keywords_directiveContext::TICK_END_KEYWORDS() { return getToken(SV3_1aPpParser::TICK_END_KEYWORDS, 0); } size_t SV3_1aPpParser::End_keywords_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEnd_keywords_directive; } void SV3_1aPpParser::End_keywords_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEnd_keywords_directive(this); } void SV3_1aPpParser::End_keywords_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEnd_keywords_directive(this); } SV3_1aPpParser::End_keywords_directiveContext* SV3_1aPpParser::end_keywords_directive() { End_keywords_directiveContext *_localctx = _tracker.createInstance<End_keywords_directiveContext>(_ctx, getState()); enterRule(_localctx, 64, SV3_1aPpParser::RuleEnd_keywords_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(454); match(SV3_1aPpParser::TICK_END_KEYWORDS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Pragma_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Pragma_directiveContext::Pragma_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Pragma_directiveContext::TICK_PRAGMA() { return getToken(SV3_1aPpParser::TICK_PRAGMA, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } std::vector<SV3_1aPpParser::Pragma_expressionContext *> SV3_1aPpParser::Pragma_directiveContext::pragma_expression() { return getRuleContexts<SV3_1aPpParser::Pragma_expressionContext>(); } SV3_1aPpParser::Pragma_expressionContext* SV3_1aPpParser::Pragma_directiveContext::pragma_expression(size_t i) { return getRuleContext<SV3_1aPpParser::Pragma_expressionContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Pragma_directiveContext::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Pragma_directiveContext::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } size_t SV3_1aPpParser::Pragma_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RulePragma_directive; } void SV3_1aPpParser::Pragma_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPragma_directive(this); } void SV3_1aPpParser::Pragma_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPragma_directive(this); } SV3_1aPpParser::Pragma_directiveContext* SV3_1aPpParser::pragma_directive() { Pragma_directiveContext *_localctx = _tracker.createInstance<Pragma_directiveContext>(_ctx, getState()); enterRule(_localctx, 66, SV3_1aPpParser::RulePragma_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(456); match(SV3_1aPpParser::TICK_PRAGMA); setState(457); match(SV3_1aPpParser::Spaces); setState(458); match(SV3_1aPpParser::Simple_identifier); setState(469); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 22, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(459); pragma_expression(); setState(464); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 21, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(460); match(SV3_1aPpParser::Special); setState(461); pragma_expression(); } setState(466); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 21, _ctx); } } setState(471); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 22, _ctx); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Celldefine_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Celldefine_directiveContext::Celldefine_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Celldefine_directiveContext::TICK_CELLDEFINE() { return getToken(SV3_1aPpParser::TICK_CELLDEFINE, 0); } tree::TerminalNode* SV3_1aPpParser::Celldefine_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Celldefine_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Celldefine_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Celldefine_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleCelldefine_directive; } void SV3_1aPpParser::Celldefine_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterCelldefine_directive(this); } void SV3_1aPpParser::Celldefine_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitCelldefine_directive(this); } SV3_1aPpParser::Celldefine_directiveContext* SV3_1aPpParser::celldefine_directive() { Celldefine_directiveContext *_localctx = _tracker.createInstance<Celldefine_directiveContext>(_ctx, getState()); enterRule(_localctx, 68, SV3_1aPpParser::RuleCelldefine_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(472); match(SV3_1aPpParser::TICK_CELLDEFINE); setState(476); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(473); match(SV3_1aPpParser::Spaces); setState(478); _errHandler->sync(this); _la = _input->LA(1); } setState(479); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Endcelldefine_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Endcelldefine_directiveContext::Endcelldefine_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Endcelldefine_directiveContext::TICK_ENDCELLDEFINE() { return getToken(SV3_1aPpParser::TICK_ENDCELLDEFINE, 0); } tree::TerminalNode* SV3_1aPpParser::Endcelldefine_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Endcelldefine_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Endcelldefine_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Endcelldefine_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndcelldefine_directive; } void SV3_1aPpParser::Endcelldefine_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndcelldefine_directive(this); } void SV3_1aPpParser::Endcelldefine_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndcelldefine_directive(this); } SV3_1aPpParser::Endcelldefine_directiveContext* SV3_1aPpParser::endcelldefine_directive() { Endcelldefine_directiveContext *_localctx = _tracker.createInstance<Endcelldefine_directiveContext>(_ctx, getState()); enterRule(_localctx, 70, SV3_1aPpParser::RuleEndcelldefine_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(481); match(SV3_1aPpParser::TICK_ENDCELLDEFINE); setState(485); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(482); match(SV3_1aPpParser::Spaces); setState(487); _errHandler->sync(this); _la = _input->LA(1); } setState(488); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Protect_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Protect_directiveContext::Protect_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Protect_directiveContext::TICK_PROTECT() { return getToken(SV3_1aPpParser::TICK_PROTECT, 0); } tree::TerminalNode* SV3_1aPpParser::Protect_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Protect_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Protect_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Protect_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleProtect_directive; } void SV3_1aPpParser::Protect_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterProtect_directive(this); } void SV3_1aPpParser::Protect_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitProtect_directive(this); } SV3_1aPpParser::Protect_directiveContext* SV3_1aPpParser::protect_directive() { Protect_directiveContext *_localctx = _tracker.createInstance<Protect_directiveContext>(_ctx, getState()); enterRule(_localctx, 72, SV3_1aPpParser::RuleProtect_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(490); match(SV3_1aPpParser::TICK_PROTECT); setState(494); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(491); match(SV3_1aPpParser::Spaces); setState(496); _errHandler->sync(this); _la = _input->LA(1); } setState(497); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Endprotect_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Endprotect_directiveContext::Endprotect_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Endprotect_directiveContext::TICK_ENDPROTECT() { return getToken(SV3_1aPpParser::TICK_ENDPROTECT, 0); } tree::TerminalNode* SV3_1aPpParser::Endprotect_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Endprotect_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Endprotect_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Endprotect_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndprotect_directive; } void SV3_1aPpParser::Endprotect_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndprotect_directive(this); } void SV3_1aPpParser::Endprotect_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndprotect_directive(this); } SV3_1aPpParser::Endprotect_directiveContext* SV3_1aPpParser::endprotect_directive() { Endprotect_directiveContext *_localctx = _tracker.createInstance<Endprotect_directiveContext>(_ctx, getState()); enterRule(_localctx, 74, SV3_1aPpParser::RuleEndprotect_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(499); match(SV3_1aPpParser::TICK_ENDPROTECT); setState(503); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(500); match(SV3_1aPpParser::Spaces); setState(505); _errHandler->sync(this); _la = _input->LA(1); } setState(506); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Protected_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Protected_directiveContext::Protected_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Protected_directiveContext::TICK_PROTECTED() { return getToken(SV3_1aPpParser::TICK_PROTECTED, 0); } size_t SV3_1aPpParser::Protected_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleProtected_directive; } void SV3_1aPpParser::Protected_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterProtected_directive(this); } void SV3_1aPpParser::Protected_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitProtected_directive(this); } SV3_1aPpParser::Protected_directiveContext* SV3_1aPpParser::protected_directive() { Protected_directiveContext *_localctx = _tracker.createInstance<Protected_directiveContext>(_ctx, getState()); enterRule(_localctx, 76, SV3_1aPpParser::RuleProtected_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(508); match(SV3_1aPpParser::TICK_PROTECTED); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Endprotected_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Endprotected_directiveContext::Endprotected_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Endprotected_directiveContext::TICK_ENDPROTECTED() { return getToken(SV3_1aPpParser::TICK_ENDPROTECTED, 0); } size_t SV3_1aPpParser::Endprotected_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndprotected_directive; } void SV3_1aPpParser::Endprotected_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndprotected_directive(this); } void SV3_1aPpParser::Endprotected_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndprotected_directive(this); } SV3_1aPpParser::Endprotected_directiveContext* SV3_1aPpParser::endprotected_directive() { Endprotected_directiveContext *_localctx = _tracker.createInstance<Endprotected_directiveContext>(_ctx, getState()); enterRule(_localctx, 78, SV3_1aPpParser::RuleEndprotected_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(510); match(SV3_1aPpParser::TICK_ENDPROTECTED); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Expand_vectornets_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Expand_vectornets_directiveContext::Expand_vectornets_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Expand_vectornets_directiveContext::TICK_EXPAND_VECTORNETS() { return getToken(SV3_1aPpParser::TICK_EXPAND_VECTORNETS, 0); } size_t SV3_1aPpParser::Expand_vectornets_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleExpand_vectornets_directive; } void SV3_1aPpParser::Expand_vectornets_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterExpand_vectornets_directive(this); } void SV3_1aPpParser::Expand_vectornets_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitExpand_vectornets_directive(this); } SV3_1aPpParser::Expand_vectornets_directiveContext* SV3_1aPpParser::expand_vectornets_directive() { Expand_vectornets_directiveContext *_localctx = _tracker.createInstance<Expand_vectornets_directiveContext>(_ctx, getState()); enterRule(_localctx, 80, SV3_1aPpParser::RuleExpand_vectornets_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(512); match(SV3_1aPpParser::TICK_EXPAND_VECTORNETS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Noexpand_vectornets_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Noexpand_vectornets_directiveContext::Noexpand_vectornets_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Noexpand_vectornets_directiveContext::TICK_NOEXPAND_VECTORNETS() { return getToken(SV3_1aPpParser::TICK_NOEXPAND_VECTORNETS, 0); } size_t SV3_1aPpParser::Noexpand_vectornets_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNoexpand_vectornets_directive; } void SV3_1aPpParser::Noexpand_vectornets_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNoexpand_vectornets_directive(this); } void SV3_1aPpParser::Noexpand_vectornets_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNoexpand_vectornets_directive(this); } SV3_1aPpParser::Noexpand_vectornets_directiveContext* SV3_1aPpParser::noexpand_vectornets_directive() { Noexpand_vectornets_directiveContext *_localctx = _tracker.createInstance<Noexpand_vectornets_directiveContext>(_ctx, getState()); enterRule(_localctx, 82, SV3_1aPpParser::RuleNoexpand_vectornets_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(514); match(SV3_1aPpParser::TICK_NOEXPAND_VECTORNETS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Autoexpand_vectornets_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Autoexpand_vectornets_directiveContext::Autoexpand_vectornets_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Autoexpand_vectornets_directiveContext::TICK_AUTOEXPAND_VECTORNETS() { return getToken(SV3_1aPpParser::TICK_AUTOEXPAND_VECTORNETS, 0); } size_t SV3_1aPpParser::Autoexpand_vectornets_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleAutoexpand_vectornets_directive; } void SV3_1aPpParser::Autoexpand_vectornets_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterAutoexpand_vectornets_directive(this); } void SV3_1aPpParser::Autoexpand_vectornets_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitAutoexpand_vectornets_directive(this); } SV3_1aPpParser::Autoexpand_vectornets_directiveContext* SV3_1aPpParser::autoexpand_vectornets_directive() { Autoexpand_vectornets_directiveContext *_localctx = _tracker.createInstance<Autoexpand_vectornets_directiveContext>(_ctx, getState()); enterRule(_localctx, 84, SV3_1aPpParser::RuleAutoexpand_vectornets_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(516); match(SV3_1aPpParser::TICK_AUTOEXPAND_VECTORNETS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Uselib_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Uselib_directiveContext::Uselib_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Uselib_directiveContext::TICK_USELIB() { return getToken(SV3_1aPpParser::TICK_USELIB, 0); } std::vector<SV3_1aPpParser::Text_blobContext *> SV3_1aPpParser::Uselib_directiveContext::text_blob() { return getRuleContexts<SV3_1aPpParser::Text_blobContext>(); } SV3_1aPpParser::Text_blobContext* SV3_1aPpParser::Uselib_directiveContext::text_blob(size_t i) { return getRuleContext<SV3_1aPpParser::Text_blobContext>(i); } size_t SV3_1aPpParser::Uselib_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleUselib_directive; } void SV3_1aPpParser::Uselib_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUselib_directive(this); } void SV3_1aPpParser::Uselib_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUselib_directive(this); } SV3_1aPpParser::Uselib_directiveContext* SV3_1aPpParser::uselib_directive() { Uselib_directiveContext *_localctx = _tracker.createInstance<Uselib_directiveContext>(_ctx, getState()); enterRule(_localctx, 86, SV3_1aPpParser::RuleUselib_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(518); match(SV3_1aPpParser::TICK_USELIB); setState(520); _errHandler->sync(this); alt = 1; do { switch (alt) { case 1: { setState(519); text_blob(); break; } default: throw NoViableAltException(this); } setState(522); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 27, _ctx); } while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Disable_portfaults_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Disable_portfaults_directiveContext::Disable_portfaults_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Disable_portfaults_directiveContext::TICK_DISABLE_PORTFAULTS() { return getToken(SV3_1aPpParser::TICK_DISABLE_PORTFAULTS, 0); } size_t SV3_1aPpParser::Disable_portfaults_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDisable_portfaults_directive; } void SV3_1aPpParser::Disable_portfaults_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDisable_portfaults_directive(this); } void SV3_1aPpParser::Disable_portfaults_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDisable_portfaults_directive(this); } SV3_1aPpParser::Disable_portfaults_directiveContext* SV3_1aPpParser::disable_portfaults_directive() { Disable_portfaults_directiveContext *_localctx = _tracker.createInstance<Disable_portfaults_directiveContext>(_ctx, getState()); enterRule(_localctx, 88, SV3_1aPpParser::RuleDisable_portfaults_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(524); match(SV3_1aPpParser::TICK_DISABLE_PORTFAULTS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Enable_portfaults_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Enable_portfaults_directiveContext::Enable_portfaults_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Enable_portfaults_directiveContext::TICK_ENABLE_PORTFAULTS() { return getToken(SV3_1aPpParser::TICK_ENABLE_PORTFAULTS, 0); } size_t SV3_1aPpParser::Enable_portfaults_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEnable_portfaults_directive; } void SV3_1aPpParser::Enable_portfaults_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEnable_portfaults_directive(this); } void SV3_1aPpParser::Enable_portfaults_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEnable_portfaults_directive(this); } SV3_1aPpParser::Enable_portfaults_directiveContext* SV3_1aPpParser::enable_portfaults_directive() { Enable_portfaults_directiveContext *_localctx = _tracker.createInstance<Enable_portfaults_directiveContext>(_ctx, getState()); enterRule(_localctx, 90, SV3_1aPpParser::RuleEnable_portfaults_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(526); match(SV3_1aPpParser::TICK_ENABLE_PORTFAULTS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Nosuppress_faults_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Nosuppress_faults_directiveContext::Nosuppress_faults_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Nosuppress_faults_directiveContext::TICK_NOSUPPRESS_FAULTS() { return getToken(SV3_1aPpParser::TICK_NOSUPPRESS_FAULTS, 0); } size_t SV3_1aPpParser::Nosuppress_faults_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNosuppress_faults_directive; } void SV3_1aPpParser::Nosuppress_faults_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNosuppress_faults_directive(this); } void SV3_1aPpParser::Nosuppress_faults_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNosuppress_faults_directive(this); } SV3_1aPpParser::Nosuppress_faults_directiveContext* SV3_1aPpParser::nosuppress_faults_directive() { Nosuppress_faults_directiveContext *_localctx = _tracker.createInstance<Nosuppress_faults_directiveContext>(_ctx, getState()); enterRule(_localctx, 92, SV3_1aPpParser::RuleNosuppress_faults_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(528); match(SV3_1aPpParser::TICK_NOSUPPRESS_FAULTS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Suppress_faults_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Suppress_faults_directiveContext::Suppress_faults_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Suppress_faults_directiveContext::TICK_SUPPRESS_FAULTS() { return getToken(SV3_1aPpParser::TICK_SUPPRESS_FAULTS, 0); } size_t SV3_1aPpParser::Suppress_faults_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleSuppress_faults_directive; } void SV3_1aPpParser::Suppress_faults_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSuppress_faults_directive(this); } void SV3_1aPpParser::Suppress_faults_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSuppress_faults_directive(this); } SV3_1aPpParser::Suppress_faults_directiveContext* SV3_1aPpParser::suppress_faults_directive() { Suppress_faults_directiveContext *_localctx = _tracker.createInstance<Suppress_faults_directiveContext>(_ctx, getState()); enterRule(_localctx, 94, SV3_1aPpParser::RuleSuppress_faults_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(530); match(SV3_1aPpParser::TICK_SUPPRESS_FAULTS); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Signed_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Signed_directiveContext::Signed_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Signed_directiveContext::TICK_SIGNED() { return getToken(SV3_1aPpParser::TICK_SIGNED, 0); } size_t SV3_1aPpParser::Signed_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleSigned_directive; } void SV3_1aPpParser::Signed_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSigned_directive(this); } void SV3_1aPpParser::Signed_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSigned_directive(this); } SV3_1aPpParser::Signed_directiveContext* SV3_1aPpParser::signed_directive() { Signed_directiveContext *_localctx = _tracker.createInstance<Signed_directiveContext>(_ctx, getState()); enterRule(_localctx, 96, SV3_1aPpParser::RuleSigned_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(532); match(SV3_1aPpParser::TICK_SIGNED); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Unsigned_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Unsigned_directiveContext::Unsigned_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Unsigned_directiveContext::TICK_UNSIGNED() { return getToken(SV3_1aPpParser::TICK_UNSIGNED, 0); } size_t SV3_1aPpParser::Unsigned_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleUnsigned_directive; } void SV3_1aPpParser::Unsigned_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUnsigned_directive(this); } void SV3_1aPpParser::Unsigned_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUnsigned_directive(this); } SV3_1aPpParser::Unsigned_directiveContext* SV3_1aPpParser::unsigned_directive() { Unsigned_directiveContext *_localctx = _tracker.createInstance<Unsigned_directiveContext>(_ctx, getState()); enterRule(_localctx, 98, SV3_1aPpParser::RuleUnsigned_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(534); match(SV3_1aPpParser::TICK_UNSIGNED); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Remove_gatename_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Remove_gatename_directiveContext::Remove_gatename_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Remove_gatename_directiveContext::TICK_REMOVE_GATENAME() { return getToken(SV3_1aPpParser::TICK_REMOVE_GATENAME, 0); } size_t SV3_1aPpParser::Remove_gatename_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleRemove_gatename_directive; } void SV3_1aPpParser::Remove_gatename_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterRemove_gatename_directive(this); } void SV3_1aPpParser::Remove_gatename_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitRemove_gatename_directive(this); } SV3_1aPpParser::Remove_gatename_directiveContext* SV3_1aPpParser::remove_gatename_directive() { Remove_gatename_directiveContext *_localctx = _tracker.createInstance<Remove_gatename_directiveContext>(_ctx, getState()); enterRule(_localctx, 100, SV3_1aPpParser::RuleRemove_gatename_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(536); match(SV3_1aPpParser::TICK_REMOVE_GATENAME); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Noremove_gatenames_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Noremove_gatenames_directiveContext::Noremove_gatenames_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Noremove_gatenames_directiveContext::TICK_NOREMOVE_GATENAMES() { return getToken(SV3_1aPpParser::TICK_NOREMOVE_GATENAMES, 0); } size_t SV3_1aPpParser::Noremove_gatenames_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNoremove_gatenames_directive; } void SV3_1aPpParser::Noremove_gatenames_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNoremove_gatenames_directive(this); } void SV3_1aPpParser::Noremove_gatenames_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNoremove_gatenames_directive(this); } SV3_1aPpParser::Noremove_gatenames_directiveContext* SV3_1aPpParser::noremove_gatenames_directive() { Noremove_gatenames_directiveContext *_localctx = _tracker.createInstance<Noremove_gatenames_directiveContext>(_ctx, getState()); enterRule(_localctx, 102, SV3_1aPpParser::RuleNoremove_gatenames_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(538); match(SV3_1aPpParser::TICK_NOREMOVE_GATENAMES); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Remove_netname_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Remove_netname_directiveContext::Remove_netname_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Remove_netname_directiveContext::TICK_REMOVE_NETNAME() { return getToken(SV3_1aPpParser::TICK_REMOVE_NETNAME, 0); } size_t SV3_1aPpParser::Remove_netname_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleRemove_netname_directive; } void SV3_1aPpParser::Remove_netname_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterRemove_netname_directive(this); } void SV3_1aPpParser::Remove_netname_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitRemove_netname_directive(this); } SV3_1aPpParser::Remove_netname_directiveContext* SV3_1aPpParser::remove_netname_directive() { Remove_netname_directiveContext *_localctx = _tracker.createInstance<Remove_netname_directiveContext>(_ctx, getState()); enterRule(_localctx, 104, SV3_1aPpParser::RuleRemove_netname_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(540); match(SV3_1aPpParser::TICK_REMOVE_NETNAME); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Noremove_netnames_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Noremove_netnames_directiveContext::Noremove_netnames_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Noremove_netnames_directiveContext::TICK_NOREMOVE_NETNAMES() { return getToken(SV3_1aPpParser::TICK_NOREMOVE_NETNAMES, 0); } size_t SV3_1aPpParser::Noremove_netnames_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNoremove_netnames_directive; } void SV3_1aPpParser::Noremove_netnames_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNoremove_netnames_directive(this); } void SV3_1aPpParser::Noremove_netnames_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNoremove_netnames_directive(this); } SV3_1aPpParser::Noremove_netnames_directiveContext* SV3_1aPpParser::noremove_netnames_directive() { Noremove_netnames_directiveContext *_localctx = _tracker.createInstance<Noremove_netnames_directiveContext>(_ctx, getState()); enterRule(_localctx, 106, SV3_1aPpParser::RuleNoremove_netnames_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(542); match(SV3_1aPpParser::TICK_NOREMOVE_NETNAMES); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Accelerate_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Accelerate_directiveContext::Accelerate_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Accelerate_directiveContext::TICK_ACCELERATE() { return getToken(SV3_1aPpParser::TICK_ACCELERATE, 0); } size_t SV3_1aPpParser::Accelerate_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleAccelerate_directive; } void SV3_1aPpParser::Accelerate_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterAccelerate_directive(this); } void SV3_1aPpParser::Accelerate_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitAccelerate_directive(this); } SV3_1aPpParser::Accelerate_directiveContext* SV3_1aPpParser::accelerate_directive() { Accelerate_directiveContext *_localctx = _tracker.createInstance<Accelerate_directiveContext>(_ctx, getState()); enterRule(_localctx, 108, SV3_1aPpParser::RuleAccelerate_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(544); match(SV3_1aPpParser::TICK_ACCELERATE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Noaccelerate_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Noaccelerate_directiveContext::Noaccelerate_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Noaccelerate_directiveContext::TICK_NOACCELERATE() { return getToken(SV3_1aPpParser::TICK_NOACCELERATE, 0); } size_t SV3_1aPpParser::Noaccelerate_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNoaccelerate_directive; } void SV3_1aPpParser::Noaccelerate_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNoaccelerate_directive(this); } void SV3_1aPpParser::Noaccelerate_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNoaccelerate_directive(this); } SV3_1aPpParser::Noaccelerate_directiveContext* SV3_1aPpParser::noaccelerate_directive() { Noaccelerate_directiveContext *_localctx = _tracker.createInstance<Noaccelerate_directiveContext>(_ctx, getState()); enterRule(_localctx, 110, SV3_1aPpParser::RuleNoaccelerate_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(546); match(SV3_1aPpParser::TICK_NOACCELERATE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Default_trireg_strenght_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Default_trireg_strenght_directiveContext::Default_trireg_strenght_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Default_trireg_strenght_directiveContext::TICK_DEFAULT_TRIREG_STRENGTH() { return getToken(SV3_1aPpParser::TICK_DEFAULT_TRIREG_STRENGTH, 0); } tree::TerminalNode* SV3_1aPpParser::Default_trireg_strenght_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Default_trireg_strenght_directiveContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } size_t SV3_1aPpParser::Default_trireg_strenght_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDefault_trireg_strenght_directive; } void SV3_1aPpParser::Default_trireg_strenght_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDefault_trireg_strenght_directive(this); } void SV3_1aPpParser::Default_trireg_strenght_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDefault_trireg_strenght_directive(this); } SV3_1aPpParser::Default_trireg_strenght_directiveContext* SV3_1aPpParser::default_trireg_strenght_directive() { Default_trireg_strenght_directiveContext *_localctx = _tracker.createInstance<Default_trireg_strenght_directiveContext>(_ctx, getState()); enterRule(_localctx, 112, SV3_1aPpParser::RuleDefault_trireg_strenght_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(548); match(SV3_1aPpParser::TICK_DEFAULT_TRIREG_STRENGTH); setState(549); match(SV3_1aPpParser::Spaces); setState(550); number(); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Default_decay_time_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Default_decay_time_directiveContext::Default_decay_time_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Default_decay_time_directiveContext::TICK_DEFAULT_DECAY_TIME() { return getToken(SV3_1aPpParser::TICK_DEFAULT_DECAY_TIME, 0); } tree::TerminalNode* SV3_1aPpParser::Default_decay_time_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Default_decay_time_directiveContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::Default_decay_time_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Default_decay_time_directiveContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } size_t SV3_1aPpParser::Default_decay_time_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDefault_decay_time_directive; } void SV3_1aPpParser::Default_decay_time_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDefault_decay_time_directive(this); } void SV3_1aPpParser::Default_decay_time_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDefault_decay_time_directive(this); } SV3_1aPpParser::Default_decay_time_directiveContext* SV3_1aPpParser::default_decay_time_directive() { Default_decay_time_directiveContext *_localctx = _tracker.createInstance<Default_decay_time_directiveContext>(_ctx, getState()); enterRule(_localctx, 114, SV3_1aPpParser::RuleDefault_decay_time_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(552); match(SV3_1aPpParser::TICK_DEFAULT_DECAY_TIME); setState(553); match(SV3_1aPpParser::Spaces); setState(557); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Number: { setState(554); number(); break; } case SV3_1aPpParser::Simple_identifier: { setState(555); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Fixed_point_number: { setState(556); match(SV3_1aPpParser::Fixed_point_number); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Unconnected_drive_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Unconnected_drive_directiveContext::Unconnected_drive_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Unconnected_drive_directiveContext::TICK_UNCONNECTED_DRIVE() { return getToken(SV3_1aPpParser::TICK_UNCONNECTED_DRIVE, 0); } tree::TerminalNode* SV3_1aPpParser::Unconnected_drive_directiveContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Unconnected_drive_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } size_t SV3_1aPpParser::Unconnected_drive_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleUnconnected_drive_directive; } void SV3_1aPpParser::Unconnected_drive_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUnconnected_drive_directive(this); } void SV3_1aPpParser::Unconnected_drive_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUnconnected_drive_directive(this); } SV3_1aPpParser::Unconnected_drive_directiveContext* SV3_1aPpParser::unconnected_drive_directive() { Unconnected_drive_directiveContext *_localctx = _tracker.createInstance<Unconnected_drive_directiveContext>(_ctx, getState()); enterRule(_localctx, 116, SV3_1aPpParser::RuleUnconnected_drive_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(559); match(SV3_1aPpParser::TICK_UNCONNECTED_DRIVE); setState(560); match(SV3_1aPpParser::Spaces); setState(561); match(SV3_1aPpParser::Simple_identifier); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Nounconnected_drive_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Nounconnected_drive_directiveContext::Nounconnected_drive_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Nounconnected_drive_directiveContext::TICK_NOUNCONNECTED_DRIVE() { return getToken(SV3_1aPpParser::TICK_NOUNCONNECTED_DRIVE, 0); } tree::TerminalNode* SV3_1aPpParser::Nounconnected_drive_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Nounconnected_drive_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Nounconnected_drive_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } size_t SV3_1aPpParser::Nounconnected_drive_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleNounconnected_drive_directive; } void SV3_1aPpParser::Nounconnected_drive_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterNounconnected_drive_directive(this); } void SV3_1aPpParser::Nounconnected_drive_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitNounconnected_drive_directive(this); } SV3_1aPpParser::Nounconnected_drive_directiveContext* SV3_1aPpParser::nounconnected_drive_directive() { Nounconnected_drive_directiveContext *_localctx = _tracker.createInstance<Nounconnected_drive_directiveContext>(_ctx, getState()); enterRule(_localctx, 118, SV3_1aPpParser::RuleNounconnected_drive_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(563); match(SV3_1aPpParser::TICK_NOUNCONNECTED_DRIVE); setState(567); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(564); match(SV3_1aPpParser::Spaces); setState(569); _errHandler->sync(this); _la = _input->LA(1); } setState(570); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Delay_mode_distributed_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Delay_mode_distributed_directiveContext::Delay_mode_distributed_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Delay_mode_distributed_directiveContext::TICK_DELAY_MODE_DISTRIBUTED() { return getToken(SV3_1aPpParser::TICK_DELAY_MODE_DISTRIBUTED, 0); } size_t SV3_1aPpParser::Delay_mode_distributed_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDelay_mode_distributed_directive; } void SV3_1aPpParser::Delay_mode_distributed_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDelay_mode_distributed_directive(this); } void SV3_1aPpParser::Delay_mode_distributed_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDelay_mode_distributed_directive(this); } SV3_1aPpParser::Delay_mode_distributed_directiveContext* SV3_1aPpParser::delay_mode_distributed_directive() { Delay_mode_distributed_directiveContext *_localctx = _tracker.createInstance<Delay_mode_distributed_directiveContext>(_ctx, getState()); enterRule(_localctx, 120, SV3_1aPpParser::RuleDelay_mode_distributed_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(572); match(SV3_1aPpParser::TICK_DELAY_MODE_DISTRIBUTED); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Delay_mode_path_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Delay_mode_path_directiveContext::Delay_mode_path_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Delay_mode_path_directiveContext::TICK_DELAY_MODE_PATH() { return getToken(SV3_1aPpParser::TICK_DELAY_MODE_PATH, 0); } size_t SV3_1aPpParser::Delay_mode_path_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDelay_mode_path_directive; } void SV3_1aPpParser::Delay_mode_path_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDelay_mode_path_directive(this); } void SV3_1aPpParser::Delay_mode_path_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDelay_mode_path_directive(this); } SV3_1aPpParser::Delay_mode_path_directiveContext* SV3_1aPpParser::delay_mode_path_directive() { Delay_mode_path_directiveContext *_localctx = _tracker.createInstance<Delay_mode_path_directiveContext>(_ctx, getState()); enterRule(_localctx, 122, SV3_1aPpParser::RuleDelay_mode_path_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(574); match(SV3_1aPpParser::TICK_DELAY_MODE_PATH); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Delay_mode_unit_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Delay_mode_unit_directiveContext::Delay_mode_unit_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Delay_mode_unit_directiveContext::TICK_DELAY_MODE_UNIT() { return getToken(SV3_1aPpParser::TICK_DELAY_MODE_UNIT, 0); } size_t SV3_1aPpParser::Delay_mode_unit_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDelay_mode_unit_directive; } void SV3_1aPpParser::Delay_mode_unit_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDelay_mode_unit_directive(this); } void SV3_1aPpParser::Delay_mode_unit_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDelay_mode_unit_directive(this); } SV3_1aPpParser::Delay_mode_unit_directiveContext* SV3_1aPpParser::delay_mode_unit_directive() { Delay_mode_unit_directiveContext *_localctx = _tracker.createInstance<Delay_mode_unit_directiveContext>(_ctx, getState()); enterRule(_localctx, 124, SV3_1aPpParser::RuleDelay_mode_unit_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(576); match(SV3_1aPpParser::TICK_DELAY_MODE_UNIT); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Delay_mode_zero_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Delay_mode_zero_directiveContext::Delay_mode_zero_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Delay_mode_zero_directiveContext::TICK_DELAY_MODE_ZERO() { return getToken(SV3_1aPpParser::TICK_DELAY_MODE_ZERO, 0); } size_t SV3_1aPpParser::Delay_mode_zero_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDelay_mode_zero_directive; } void SV3_1aPpParser::Delay_mode_zero_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDelay_mode_zero_directive(this); } void SV3_1aPpParser::Delay_mode_zero_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDelay_mode_zero_directive(this); } SV3_1aPpParser::Delay_mode_zero_directiveContext* SV3_1aPpParser::delay_mode_zero_directive() { Delay_mode_zero_directiveContext *_localctx = _tracker.createInstance<Delay_mode_zero_directiveContext>(_ctx, getState()); enterRule(_localctx, 126, SV3_1aPpParser::RuleDelay_mode_zero_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(578); match(SV3_1aPpParser::TICK_DELAY_MODE_ZERO); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Undefineall_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Undefineall_directiveContext::Undefineall_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Undefineall_directiveContext::TICK_UNDEFINEALL() { return getToken(SV3_1aPpParser::TICK_UNDEFINEALL, 0); } size_t SV3_1aPpParser::Undefineall_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleUndefineall_directive; } void SV3_1aPpParser::Undefineall_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterUndefineall_directive(this); } void SV3_1aPpParser::Undefineall_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitUndefineall_directive(this); } SV3_1aPpParser::Undefineall_directiveContext* SV3_1aPpParser::undefineall_directive() { Undefineall_directiveContext *_localctx = _tracker.createInstance<Undefineall_directiveContext>(_ctx, getState()); enterRule(_localctx, 128, SV3_1aPpParser::RuleUndefineall_directive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(580); match(SV3_1aPpParser::TICK_UNDEFINEALL); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- ModuleContext ------------------------------------------------------------------ SV3_1aPpParser::ModuleContext::ModuleContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::ModuleContext::MODULE() { return getToken(SV3_1aPpParser::MODULE, 0); } size_t SV3_1aPpParser::ModuleContext::getRuleIndex() const { return SV3_1aPpParser::RuleModule; } void SV3_1aPpParser::ModuleContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterModule(this); } void SV3_1aPpParser::ModuleContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitModule(this); } SV3_1aPpParser::ModuleContext* SV3_1aPpParser::module() { ModuleContext *_localctx = _tracker.createInstance<ModuleContext>(_ctx, getState()); enterRule(_localctx, 130, SV3_1aPpParser::RuleModule); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(582); match(SV3_1aPpParser::MODULE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndmoduleContext ------------------------------------------------------------------ SV3_1aPpParser::EndmoduleContext::EndmoduleContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndmoduleContext::ENDMODULE() { return getToken(SV3_1aPpParser::ENDMODULE, 0); } size_t SV3_1aPpParser::EndmoduleContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndmodule; } void SV3_1aPpParser::EndmoduleContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndmodule(this); } void SV3_1aPpParser::EndmoduleContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndmodule(this); } SV3_1aPpParser::EndmoduleContext* SV3_1aPpParser::endmodule() { EndmoduleContext *_localctx = _tracker.createInstance<EndmoduleContext>(_ctx, getState()); enterRule(_localctx, 132, SV3_1aPpParser::RuleEndmodule); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(584); match(SV3_1aPpParser::ENDMODULE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Sv_interfaceContext ------------------------------------------------------------------ SV3_1aPpParser::Sv_interfaceContext::Sv_interfaceContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Sv_interfaceContext::INTERFACE() { return getToken(SV3_1aPpParser::INTERFACE, 0); } size_t SV3_1aPpParser::Sv_interfaceContext::getRuleIndex() const { return SV3_1aPpParser::RuleSv_interface; } void SV3_1aPpParser::Sv_interfaceContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSv_interface(this); } void SV3_1aPpParser::Sv_interfaceContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSv_interface(this); } SV3_1aPpParser::Sv_interfaceContext* SV3_1aPpParser::sv_interface() { Sv_interfaceContext *_localctx = _tracker.createInstance<Sv_interfaceContext>(_ctx, getState()); enterRule(_localctx, 134, SV3_1aPpParser::RuleSv_interface); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(586); match(SV3_1aPpParser::INTERFACE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndinterfaceContext ------------------------------------------------------------------ SV3_1aPpParser::EndinterfaceContext::EndinterfaceContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndinterfaceContext::ENDINTERFACE() { return getToken(SV3_1aPpParser::ENDINTERFACE, 0); } size_t SV3_1aPpParser::EndinterfaceContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndinterface; } void SV3_1aPpParser::EndinterfaceContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndinterface(this); } void SV3_1aPpParser::EndinterfaceContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndinterface(this); } SV3_1aPpParser::EndinterfaceContext* SV3_1aPpParser::endinterface() { EndinterfaceContext *_localctx = _tracker.createInstance<EndinterfaceContext>(_ctx, getState()); enterRule(_localctx, 136, SV3_1aPpParser::RuleEndinterface); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(588); match(SV3_1aPpParser::ENDINTERFACE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- ProgramContext ------------------------------------------------------------------ SV3_1aPpParser::ProgramContext::ProgramContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::ProgramContext::PROGRAM() { return getToken(SV3_1aPpParser::PROGRAM, 0); } size_t SV3_1aPpParser::ProgramContext::getRuleIndex() const { return SV3_1aPpParser::RuleProgram; } void SV3_1aPpParser::ProgramContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterProgram(this); } void SV3_1aPpParser::ProgramContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitProgram(this); } SV3_1aPpParser::ProgramContext* SV3_1aPpParser::program() { ProgramContext *_localctx = _tracker.createInstance<ProgramContext>(_ctx, getState()); enterRule(_localctx, 138, SV3_1aPpParser::RuleProgram); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(590); match(SV3_1aPpParser::PROGRAM); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndprogramContext ------------------------------------------------------------------ SV3_1aPpParser::EndprogramContext::EndprogramContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndprogramContext::ENDPROGRAM() { return getToken(SV3_1aPpParser::ENDPROGRAM, 0); } size_t SV3_1aPpParser::EndprogramContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndprogram; } void SV3_1aPpParser::EndprogramContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndprogram(this); } void SV3_1aPpParser::EndprogramContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndprogram(this); } SV3_1aPpParser::EndprogramContext* SV3_1aPpParser::endprogram() { EndprogramContext *_localctx = _tracker.createInstance<EndprogramContext>(_ctx, getState()); enterRule(_localctx, 140, SV3_1aPpParser::RuleEndprogram); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(592); match(SV3_1aPpParser::ENDPROGRAM); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- PrimitiveContext ------------------------------------------------------------------ SV3_1aPpParser::PrimitiveContext::PrimitiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::PrimitiveContext::PRIMITIVE() { return getToken(SV3_1aPpParser::PRIMITIVE, 0); } size_t SV3_1aPpParser::PrimitiveContext::getRuleIndex() const { return SV3_1aPpParser::RulePrimitive; } void SV3_1aPpParser::PrimitiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPrimitive(this); } void SV3_1aPpParser::PrimitiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPrimitive(this); } SV3_1aPpParser::PrimitiveContext* SV3_1aPpParser::primitive() { PrimitiveContext *_localctx = _tracker.createInstance<PrimitiveContext>(_ctx, getState()); enterRule(_localctx, 142, SV3_1aPpParser::RulePrimitive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(594); match(SV3_1aPpParser::PRIMITIVE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndprimitiveContext ------------------------------------------------------------------ SV3_1aPpParser::EndprimitiveContext::EndprimitiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndprimitiveContext::ENDPRIMITIVE() { return getToken(SV3_1aPpParser::ENDPRIMITIVE, 0); } size_t SV3_1aPpParser::EndprimitiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndprimitive; } void SV3_1aPpParser::EndprimitiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndprimitive(this); } void SV3_1aPpParser::EndprimitiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndprimitive(this); } SV3_1aPpParser::EndprimitiveContext* SV3_1aPpParser::endprimitive() { EndprimitiveContext *_localctx = _tracker.createInstance<EndprimitiveContext>(_ctx, getState()); enterRule(_localctx, 144, SV3_1aPpParser::RuleEndprimitive); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(596); match(SV3_1aPpParser::ENDPRIMITIVE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Sv_packageContext ------------------------------------------------------------------ SV3_1aPpParser::Sv_packageContext::Sv_packageContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Sv_packageContext::PACKAGE() { return getToken(SV3_1aPpParser::PACKAGE, 0); } size_t SV3_1aPpParser::Sv_packageContext::getRuleIndex() const { return SV3_1aPpParser::RuleSv_package; } void SV3_1aPpParser::Sv_packageContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSv_package(this); } void SV3_1aPpParser::Sv_packageContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSv_package(this); } SV3_1aPpParser::Sv_packageContext* SV3_1aPpParser::sv_package() { Sv_packageContext *_localctx = _tracker.createInstance<Sv_packageContext>(_ctx, getState()); enterRule(_localctx, 146, SV3_1aPpParser::RuleSv_package); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(598); match(SV3_1aPpParser::PACKAGE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndpackageContext ------------------------------------------------------------------ SV3_1aPpParser::EndpackageContext::EndpackageContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndpackageContext::ENDPACKAGE() { return getToken(SV3_1aPpParser::ENDPACKAGE, 0); } size_t SV3_1aPpParser::EndpackageContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndpackage; } void SV3_1aPpParser::EndpackageContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndpackage(this); } void SV3_1aPpParser::EndpackageContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndpackage(this); } SV3_1aPpParser::EndpackageContext* SV3_1aPpParser::endpackage() { EndpackageContext *_localctx = _tracker.createInstance<EndpackageContext>(_ctx, getState()); enterRule(_localctx, 148, SV3_1aPpParser::RuleEndpackage); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(600); match(SV3_1aPpParser::ENDPACKAGE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- CheckerContext ------------------------------------------------------------------ SV3_1aPpParser::CheckerContext::CheckerContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::CheckerContext::CHECKER() { return getToken(SV3_1aPpParser::CHECKER, 0); } size_t SV3_1aPpParser::CheckerContext::getRuleIndex() const { return SV3_1aPpParser::RuleChecker; } void SV3_1aPpParser::CheckerContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterChecker(this); } void SV3_1aPpParser::CheckerContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitChecker(this); } SV3_1aPpParser::CheckerContext* SV3_1aPpParser::checker() { CheckerContext *_localctx = _tracker.createInstance<CheckerContext>(_ctx, getState()); enterRule(_localctx, 150, SV3_1aPpParser::RuleChecker); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(602); match(SV3_1aPpParser::CHECKER); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndcheckerContext ------------------------------------------------------------------ SV3_1aPpParser::EndcheckerContext::EndcheckerContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndcheckerContext::ENDCHECKER() { return getToken(SV3_1aPpParser::ENDCHECKER, 0); } size_t SV3_1aPpParser::EndcheckerContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndchecker; } void SV3_1aPpParser::EndcheckerContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndchecker(this); } void SV3_1aPpParser::EndcheckerContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndchecker(this); } SV3_1aPpParser::EndcheckerContext* SV3_1aPpParser::endchecker() { EndcheckerContext *_localctx = _tracker.createInstance<EndcheckerContext>(_ctx, getState()); enterRule(_localctx, 152, SV3_1aPpParser::RuleEndchecker); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(604); match(SV3_1aPpParser::ENDCHECKER); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- ConfigContext ------------------------------------------------------------------ SV3_1aPpParser::ConfigContext::ConfigContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::ConfigContext::CONFIG() { return getToken(SV3_1aPpParser::CONFIG, 0); } size_t SV3_1aPpParser::ConfigContext::getRuleIndex() const { return SV3_1aPpParser::RuleConfig; } void SV3_1aPpParser::ConfigContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterConfig(this); } void SV3_1aPpParser::ConfigContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitConfig(this); } SV3_1aPpParser::ConfigContext* SV3_1aPpParser::config() { ConfigContext *_localctx = _tracker.createInstance<ConfigContext>(_ctx, getState()); enterRule(_localctx, 154, SV3_1aPpParser::RuleConfig); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(606); match(SV3_1aPpParser::CONFIG); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- EndconfigContext ------------------------------------------------------------------ SV3_1aPpParser::EndconfigContext::EndconfigContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::EndconfigContext::ENDCONFIG() { return getToken(SV3_1aPpParser::ENDCONFIG, 0); } size_t SV3_1aPpParser::EndconfigContext::getRuleIndex() const { return SV3_1aPpParser::RuleEndconfig; } void SV3_1aPpParser::EndconfigContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEndconfig(this); } void SV3_1aPpParser::EndconfigContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEndconfig(this); } SV3_1aPpParser::EndconfigContext* SV3_1aPpParser::endconfig() { EndconfigContext *_localctx = _tracker.createInstance<EndconfigContext>(_ctx, getState()); enterRule(_localctx, 156, SV3_1aPpParser::RuleEndconfig); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(608); match(SV3_1aPpParser::ENDCONFIG); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Define_directiveContext ------------------------------------------------------------------ SV3_1aPpParser::Define_directiveContext::Define_directiveContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Define_directiveContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Define_directiveContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Define_directiveContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } tree::TerminalNode* SV3_1aPpParser::Define_directiveContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Define_directiveContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Define_directiveContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } size_t SV3_1aPpParser::Define_directiveContext::getRuleIndex() const { return SV3_1aPpParser::RuleDefine_directive; } void SV3_1aPpParser::Define_directiveContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDefine_directive(this); } void SV3_1aPpParser::Define_directiveContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDefine_directive(this); } SV3_1aPpParser::Define_directiveContext* SV3_1aPpParser::define_directive() { Define_directiveContext *_localctx = _tracker.createInstance<Define_directiveContext>(_ctx, getState()); enterRule(_localctx, 158, SV3_1aPpParser::RuleDefine_directive); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(610); match(SV3_1aPpParser::TICK_DEFINE); setState(611); match(SV3_1aPpParser::Spaces); setState(612); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(616); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(613); match(SV3_1aPpParser::Spaces); setState(618); _errHandler->sync(this); _la = _input->LA(1); } setState(619); match(SV3_1aPpParser::CR); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Multiline_no_args_macro_definitionContext ------------------------------------------------------------------ SV3_1aPpParser::Multiline_no_args_macro_definitionContext::Multiline_no_args_macro_definitionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Multiline_no_args_macro_definitionContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Multiline_no_args_macro_definitionContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Multiline_no_args_macro_definitionContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Escaped_macro_definition_bodyContext* SV3_1aPpParser::Multiline_no_args_macro_definitionContext::escaped_macro_definition_body() { return getRuleContext<SV3_1aPpParser::Escaped_macro_definition_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Multiline_no_args_macro_definitionContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Multiline_no_args_macro_definitionContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } size_t SV3_1aPpParser::Multiline_no_args_macro_definitionContext::getRuleIndex() const { return SV3_1aPpParser::RuleMultiline_no_args_macro_definition; } void SV3_1aPpParser::Multiline_no_args_macro_definitionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMultiline_no_args_macro_definition(this); } void SV3_1aPpParser::Multiline_no_args_macro_definitionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMultiline_no_args_macro_definition(this); } SV3_1aPpParser::Multiline_no_args_macro_definitionContext* SV3_1aPpParser::multiline_no_args_macro_definition() { Multiline_no_args_macro_definitionContext *_localctx = _tracker.createInstance<Multiline_no_args_macro_definitionContext>(_ctx, getState()); enterRule(_localctx, 160, SV3_1aPpParser::RuleMultiline_no_args_macro_definition); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(621); match(SV3_1aPpParser::TICK_DEFINE); setState(622); match(SV3_1aPpParser::Spaces); setState(623); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(627); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 31, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(624); match(SV3_1aPpParser::Spaces); } setState(629); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 31, _ctx); } setState(630); escaped_macro_definition_body(); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Multiline_args_macro_definitionContext ------------------------------------------------------------------ SV3_1aPpParser::Multiline_args_macro_definitionContext::Multiline_args_macro_definitionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Multiline_args_macro_definitionContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Multiline_args_macro_definitionContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Multiline_args_macro_definitionContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Macro_argumentsContext* SV3_1aPpParser::Multiline_args_macro_definitionContext::macro_arguments() { return getRuleContext<SV3_1aPpParser::Macro_argumentsContext>(0); } SV3_1aPpParser::Escaped_macro_definition_bodyContext* SV3_1aPpParser::Multiline_args_macro_definitionContext::escaped_macro_definition_body() { return getRuleContext<SV3_1aPpParser::Escaped_macro_definition_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Multiline_args_macro_definitionContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Multiline_args_macro_definitionContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } size_t SV3_1aPpParser::Multiline_args_macro_definitionContext::getRuleIndex() const { return SV3_1aPpParser::RuleMultiline_args_macro_definition; } void SV3_1aPpParser::Multiline_args_macro_definitionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMultiline_args_macro_definition(this); } void SV3_1aPpParser::Multiline_args_macro_definitionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMultiline_args_macro_definition(this); } SV3_1aPpParser::Multiline_args_macro_definitionContext* SV3_1aPpParser::multiline_args_macro_definition() { Multiline_args_macro_definitionContext *_localctx = _tracker.createInstance<Multiline_args_macro_definitionContext>(_ctx, getState()); enterRule(_localctx, 162, SV3_1aPpParser::RuleMultiline_args_macro_definition); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(632); match(SV3_1aPpParser::TICK_DEFINE); setState(633); match(SV3_1aPpParser::Spaces); setState(634); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(635); macro_arguments(); setState(639); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 32, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(636); match(SV3_1aPpParser::Spaces); } setState(641); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 32, _ctx); } setState(642); escaped_macro_definition_body(); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_no_args_macro_definitionContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_no_args_macro_definitionContext::Simple_no_args_macro_definitionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_no_args_macro_definitionContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Simple_macro_definition_bodyContext* SV3_1aPpParser::Simple_no_args_macro_definitionContext::simple_macro_definition_body() { return getRuleContext<SV3_1aPpParser::Simple_macro_definition_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definitionContext::One_line_comment() { return getToken(SV3_1aPpParser::One_line_comment, 0); } size_t SV3_1aPpParser::Simple_no_args_macro_definitionContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_no_args_macro_definition; } void SV3_1aPpParser::Simple_no_args_macro_definitionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_no_args_macro_definition(this); } void SV3_1aPpParser::Simple_no_args_macro_definitionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_no_args_macro_definition(this); } SV3_1aPpParser::Simple_no_args_macro_definitionContext* SV3_1aPpParser::simple_no_args_macro_definition() { Simple_no_args_macro_definitionContext *_localctx = _tracker.createInstance<Simple_no_args_macro_definitionContext>(_ctx, getState()); enterRule(_localctx, 164, SV3_1aPpParser::RuleSimple_no_args_macro_definition); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(661); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 34, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(644); match(SV3_1aPpParser::TICK_DEFINE); setState(645); match(SV3_1aPpParser::Spaces); setState(646); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(647); match(SV3_1aPpParser::Spaces); setState(648); simple_macro_definition_body(); setState(649); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::One_line_comment || _la == SV3_1aPpParser::CR)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } break; } case 2: { enterOuterAlt(_localctx, 2); setState(651); match(SV3_1aPpParser::TICK_DEFINE); setState(652); match(SV3_1aPpParser::Spaces); setState(653); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(657); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(654); match(SV3_1aPpParser::Spaces); setState(659); _errHandler->sync(this); _la = _input->LA(1); } setState(660); match(SV3_1aPpParser::CR); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_args_macro_definitionContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_args_macro_definitionContext::Simple_args_macro_definitionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_args_macro_definitionContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Macro_argumentsContext* SV3_1aPpParser::Simple_args_macro_definitionContext::macro_arguments() { return getRuleContext<SV3_1aPpParser::Macro_argumentsContext>(0); } SV3_1aPpParser::Simple_macro_definition_bodyContext* SV3_1aPpParser::Simple_args_macro_definitionContext::simple_macro_definition_body() { return getRuleContext<SV3_1aPpParser::Simple_macro_definition_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definitionContext::One_line_comment() { return getToken(SV3_1aPpParser::One_line_comment, 0); } size_t SV3_1aPpParser::Simple_args_macro_definitionContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_args_macro_definition; } void SV3_1aPpParser::Simple_args_macro_definitionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_args_macro_definition(this); } void SV3_1aPpParser::Simple_args_macro_definitionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_args_macro_definition(this); } SV3_1aPpParser::Simple_args_macro_definitionContext* SV3_1aPpParser::simple_args_macro_definition() { Simple_args_macro_definitionContext *_localctx = _tracker.createInstance<Simple_args_macro_definitionContext>(_ctx, getState()); enterRule(_localctx, 166, SV3_1aPpParser::RuleSimple_args_macro_definition); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(683); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 36, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(663); match(SV3_1aPpParser::TICK_DEFINE); setState(664); match(SV3_1aPpParser::Spaces); setState(665); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(666); macro_arguments(); setState(667); match(SV3_1aPpParser::Spaces); setState(668); simple_macro_definition_body(); setState(669); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::One_line_comment || _la == SV3_1aPpParser::CR)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } break; } case 2: { enterOuterAlt(_localctx, 2); setState(671); match(SV3_1aPpParser::TICK_DEFINE); setState(672); match(SV3_1aPpParser::Spaces); setState(673); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::Escaped_identifier || _la == SV3_1aPpParser::Simple_identifier)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } setState(674); macro_arguments(); setState(678); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(675); match(SV3_1aPpParser::Spaces); setState(680); _errHandler->sync(this); _la = _input->LA(1); } setState(681); match(SV3_1aPpParser::CR); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Identifier_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Identifier_in_macro_bodyContext::Identifier_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<tree::TerminalNode *> SV3_1aPpParser::Identifier_in_macro_bodyContext::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Identifier_in_macro_bodyContext::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Identifier_in_macro_bodyContext::TICK_TICK() { return getTokens(SV3_1aPpParser::TICK_TICK); } tree::TerminalNode* SV3_1aPpParser::Identifier_in_macro_bodyContext::TICK_TICK(size_t i) { return getToken(SV3_1aPpParser::TICK_TICK, i); } size_t SV3_1aPpParser::Identifier_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleIdentifier_in_macro_body; } void SV3_1aPpParser::Identifier_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterIdentifier_in_macro_body(this); } void SV3_1aPpParser::Identifier_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitIdentifier_in_macro_body(this); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::identifier_in_macro_body() { Identifier_in_macro_bodyContext *_localctx = _tracker.createInstance<Identifier_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 168, SV3_1aPpParser::RuleIdentifier_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(691); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 38, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(685); match(SV3_1aPpParser::Simple_identifier); setState(687); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 37, _ctx)) { case 1: { setState(686); match(SV3_1aPpParser::TICK_TICK); break; } default: break; } } setState(693); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 38, _ctx); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_no_args_macro_definition_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::Simple_no_args_macro_definition_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::simple_macro_definition_body_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext>(0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } tree::TerminalNode* SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::TICK_VARIABLE() { return getToken(SV3_1aPpParser::TICK_VARIABLE, 0); } size_t SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_no_args_macro_definition_in_macro_body; } void SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_no_args_macro_definition_in_macro_body(this); } void SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_no_args_macro_definition_in_macro_body(this); } SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::simple_no_args_macro_definition_in_macro_body() { Simple_no_args_macro_definition_in_macro_bodyContext *_localctx = _tracker.createInstance<Simple_no_args_macro_definition_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 170, SV3_1aPpParser::RuleSimple_no_args_macro_definition_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; setState(722); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 43, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(694); match(SV3_1aPpParser::TICK_DEFINE); setState(695); match(SV3_1aPpParser::Spaces); setState(698); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: case SV3_1aPpParser::Spaces: { setState(696); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(697); match(SV3_1aPpParser::Escaped_identifier); break; } default: throw NoViableAltException(this); } setState(700); match(SV3_1aPpParser::Spaces); setState(701); simple_macro_definition_body_in_macro_body(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(702); match(SV3_1aPpParser::TICK_DEFINE); setState(703); match(SV3_1aPpParser::Spaces); setState(706); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 40, _ctx)) { case 1: { setState(704); identifier_in_macro_body(); break; } case 2: { setState(705); match(SV3_1aPpParser::Escaped_identifier); break; } default: break; } setState(711); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 41, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(708); match(SV3_1aPpParser::Spaces); } setState(713); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 41, _ctx); } break; } case 3: { enterOuterAlt(_localctx, 3); setState(714); match(SV3_1aPpParser::TICK_DEFINE); setState(715); match(SV3_1aPpParser::Spaces); setState(718); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::TICK_VARIABLE: case SV3_1aPpParser::Simple_identifier: { setState(716); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(717); match(SV3_1aPpParser::Escaped_identifier); break; } default: throw NoViableAltException(this); } setState(720); match(SV3_1aPpParser::TICK_VARIABLE); setState(721); simple_macro_definition_body_in_macro_body(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_args_macro_definition_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::Simple_args_macro_definition_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::TICK_DEFINE() { return getToken(SV3_1aPpParser::TICK_DEFINE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } SV3_1aPpParser::Macro_argumentsContext* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::macro_arguments() { return getRuleContext<SV3_1aPpParser::Macro_argumentsContext>(0); } SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::simple_macro_definition_body_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext>(0); } SV3_1aPpParser::Identifier_in_macro_bodyContext* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::identifier_in_macro_body() { return getRuleContext<SV3_1aPpParser::Identifier_in_macro_bodyContext>(0); } tree::TerminalNode* SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::Escaped_identifier() { return getToken(SV3_1aPpParser::Escaped_identifier, 0); } size_t SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_args_macro_definition_in_macro_body; } void SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_args_macro_definition_in_macro_body(this); } void SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_args_macro_definition_in_macro_body(this); } SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::simple_args_macro_definition_in_macro_body() { Simple_args_macro_definition_in_macro_bodyContext *_localctx = _tracker.createInstance<Simple_args_macro_definition_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 172, SV3_1aPpParser::RuleSimple_args_macro_definition_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(741); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 46, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(724); match(SV3_1aPpParser::TICK_DEFINE); setState(725); match(SV3_1aPpParser::Spaces); setState(728); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: case SV3_1aPpParser::PARENS_OPEN: { setState(726); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(727); match(SV3_1aPpParser::Escaped_identifier); break; } default: throw NoViableAltException(this); } setState(730); macro_arguments(); setState(731); match(SV3_1aPpParser::Spaces); setState(732); simple_macro_definition_body_in_macro_body(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(734); match(SV3_1aPpParser::TICK_DEFINE); setState(735); match(SV3_1aPpParser::Spaces); setState(738); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: case SV3_1aPpParser::PARENS_OPEN: { setState(736); identifier_in_macro_body(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(737); match(SV3_1aPpParser::Escaped_identifier); break; } default: throw NoViableAltException(this); } setState(740); macro_arguments(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Directive_in_macroContext ------------------------------------------------------------------ SV3_1aPpParser::Directive_in_macroContext::Directive_in_macroContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } SV3_1aPpParser::Celldefine_directiveContext* SV3_1aPpParser::Directive_in_macroContext::celldefine_directive() { return getRuleContext<SV3_1aPpParser::Celldefine_directiveContext>(0); } SV3_1aPpParser::Endcelldefine_directiveContext* SV3_1aPpParser::Directive_in_macroContext::endcelldefine_directive() { return getRuleContext<SV3_1aPpParser::Endcelldefine_directiveContext>(0); } SV3_1aPpParser::Default_nettype_directiveContext* SV3_1aPpParser::Directive_in_macroContext::default_nettype_directive() { return getRuleContext<SV3_1aPpParser::Default_nettype_directiveContext>(0); } SV3_1aPpParser::Undef_directiveContext* SV3_1aPpParser::Directive_in_macroContext::undef_directive() { return getRuleContext<SV3_1aPpParser::Undef_directiveContext>(0); } SV3_1aPpParser::Ifdef_directiveContext* SV3_1aPpParser::Directive_in_macroContext::ifdef_directive() { return getRuleContext<SV3_1aPpParser::Ifdef_directiveContext>(0); } SV3_1aPpParser::Ifndef_directiveContext* SV3_1aPpParser::Directive_in_macroContext::ifndef_directive() { return getRuleContext<SV3_1aPpParser::Ifndef_directiveContext>(0); } SV3_1aPpParser::Else_directiveContext* SV3_1aPpParser::Directive_in_macroContext::else_directive() { return getRuleContext<SV3_1aPpParser::Else_directiveContext>(0); } SV3_1aPpParser::Elsif_directiveContext* SV3_1aPpParser::Directive_in_macroContext::elsif_directive() { return getRuleContext<SV3_1aPpParser::Elsif_directiveContext>(0); } SV3_1aPpParser::Elseif_directiveContext* SV3_1aPpParser::Directive_in_macroContext::elseif_directive() { return getRuleContext<SV3_1aPpParser::Elseif_directiveContext>(0); } SV3_1aPpParser::Endif_directiveContext* SV3_1aPpParser::Directive_in_macroContext::endif_directive() { return getRuleContext<SV3_1aPpParser::Endif_directiveContext>(0); } SV3_1aPpParser::Include_directiveContext* SV3_1aPpParser::Directive_in_macroContext::include_directive() { return getRuleContext<SV3_1aPpParser::Include_directiveContext>(0); } SV3_1aPpParser::Resetall_directiveContext* SV3_1aPpParser::Directive_in_macroContext::resetall_directive() { return getRuleContext<SV3_1aPpParser::Resetall_directiveContext>(0); } SV3_1aPpParser::Timescale_directiveContext* SV3_1aPpParser::Directive_in_macroContext::timescale_directive() { return getRuleContext<SV3_1aPpParser::Timescale_directiveContext>(0); } SV3_1aPpParser::Unconnected_drive_directiveContext* SV3_1aPpParser::Directive_in_macroContext::unconnected_drive_directive() { return getRuleContext<SV3_1aPpParser::Unconnected_drive_directiveContext>(0); } SV3_1aPpParser::Nounconnected_drive_directiveContext* SV3_1aPpParser::Directive_in_macroContext::nounconnected_drive_directive() { return getRuleContext<SV3_1aPpParser::Nounconnected_drive_directiveContext>(0); } SV3_1aPpParser::Line_directiveContext* SV3_1aPpParser::Directive_in_macroContext::line_directive() { return getRuleContext<SV3_1aPpParser::Line_directiveContext>(0); } SV3_1aPpParser::Default_decay_time_directiveContext* SV3_1aPpParser::Directive_in_macroContext::default_decay_time_directive() { return getRuleContext<SV3_1aPpParser::Default_decay_time_directiveContext>(0); } SV3_1aPpParser::Default_trireg_strenght_directiveContext* SV3_1aPpParser::Directive_in_macroContext::default_trireg_strenght_directive() { return getRuleContext<SV3_1aPpParser::Default_trireg_strenght_directiveContext>(0); } SV3_1aPpParser::Delay_mode_distributed_directiveContext* SV3_1aPpParser::Directive_in_macroContext::delay_mode_distributed_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_distributed_directiveContext>(0); } SV3_1aPpParser::Delay_mode_path_directiveContext* SV3_1aPpParser::Directive_in_macroContext::delay_mode_path_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_path_directiveContext>(0); } SV3_1aPpParser::Delay_mode_unit_directiveContext* SV3_1aPpParser::Directive_in_macroContext::delay_mode_unit_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_unit_directiveContext>(0); } SV3_1aPpParser::Delay_mode_zero_directiveContext* SV3_1aPpParser::Directive_in_macroContext::delay_mode_zero_directive() { return getRuleContext<SV3_1aPpParser::Delay_mode_zero_directiveContext>(0); } SV3_1aPpParser::Protect_directiveContext* SV3_1aPpParser::Directive_in_macroContext::protect_directive() { return getRuleContext<SV3_1aPpParser::Protect_directiveContext>(0); } SV3_1aPpParser::Endprotect_directiveContext* SV3_1aPpParser::Directive_in_macroContext::endprotect_directive() { return getRuleContext<SV3_1aPpParser::Endprotect_directiveContext>(0); } SV3_1aPpParser::Protected_directiveContext* SV3_1aPpParser::Directive_in_macroContext::protected_directive() { return getRuleContext<SV3_1aPpParser::Protected_directiveContext>(0); } SV3_1aPpParser::Endprotected_directiveContext* SV3_1aPpParser::Directive_in_macroContext::endprotected_directive() { return getRuleContext<SV3_1aPpParser::Endprotected_directiveContext>(0); } SV3_1aPpParser::Expand_vectornets_directiveContext* SV3_1aPpParser::Directive_in_macroContext::expand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Expand_vectornets_directiveContext>(0); } SV3_1aPpParser::Noexpand_vectornets_directiveContext* SV3_1aPpParser::Directive_in_macroContext::noexpand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Noexpand_vectornets_directiveContext>(0); } SV3_1aPpParser::Autoexpand_vectornets_directiveContext* SV3_1aPpParser::Directive_in_macroContext::autoexpand_vectornets_directive() { return getRuleContext<SV3_1aPpParser::Autoexpand_vectornets_directiveContext>(0); } SV3_1aPpParser::Remove_gatename_directiveContext* SV3_1aPpParser::Directive_in_macroContext::remove_gatename_directive() { return getRuleContext<SV3_1aPpParser::Remove_gatename_directiveContext>(0); } SV3_1aPpParser::Noremove_gatenames_directiveContext* SV3_1aPpParser::Directive_in_macroContext::noremove_gatenames_directive() { return getRuleContext<SV3_1aPpParser::Noremove_gatenames_directiveContext>(0); } SV3_1aPpParser::Remove_netname_directiveContext* SV3_1aPpParser::Directive_in_macroContext::remove_netname_directive() { return getRuleContext<SV3_1aPpParser::Remove_netname_directiveContext>(0); } SV3_1aPpParser::Noremove_netnames_directiveContext* SV3_1aPpParser::Directive_in_macroContext::noremove_netnames_directive() { return getRuleContext<SV3_1aPpParser::Noremove_netnames_directiveContext>(0); } SV3_1aPpParser::Accelerate_directiveContext* SV3_1aPpParser::Directive_in_macroContext::accelerate_directive() { return getRuleContext<SV3_1aPpParser::Accelerate_directiveContext>(0); } SV3_1aPpParser::Noaccelerate_directiveContext* SV3_1aPpParser::Directive_in_macroContext::noaccelerate_directive() { return getRuleContext<SV3_1aPpParser::Noaccelerate_directiveContext>(0); } SV3_1aPpParser::Undefineall_directiveContext* SV3_1aPpParser::Directive_in_macroContext::undefineall_directive() { return getRuleContext<SV3_1aPpParser::Undefineall_directiveContext>(0); } SV3_1aPpParser::Uselib_directiveContext* SV3_1aPpParser::Directive_in_macroContext::uselib_directive() { return getRuleContext<SV3_1aPpParser::Uselib_directiveContext>(0); } SV3_1aPpParser::Disable_portfaults_directiveContext* SV3_1aPpParser::Directive_in_macroContext::disable_portfaults_directive() { return getRuleContext<SV3_1aPpParser::Disable_portfaults_directiveContext>(0); } SV3_1aPpParser::Enable_portfaults_directiveContext* SV3_1aPpParser::Directive_in_macroContext::enable_portfaults_directive() { return getRuleContext<SV3_1aPpParser::Enable_portfaults_directiveContext>(0); } SV3_1aPpParser::Nosuppress_faults_directiveContext* SV3_1aPpParser::Directive_in_macroContext::nosuppress_faults_directive() { return getRuleContext<SV3_1aPpParser::Nosuppress_faults_directiveContext>(0); } SV3_1aPpParser::Suppress_faults_directiveContext* SV3_1aPpParser::Directive_in_macroContext::suppress_faults_directive() { return getRuleContext<SV3_1aPpParser::Suppress_faults_directiveContext>(0); } SV3_1aPpParser::Signed_directiveContext* SV3_1aPpParser::Directive_in_macroContext::signed_directive() { return getRuleContext<SV3_1aPpParser::Signed_directiveContext>(0); } SV3_1aPpParser::Unsigned_directiveContext* SV3_1aPpParser::Directive_in_macroContext::unsigned_directive() { return getRuleContext<SV3_1aPpParser::Unsigned_directiveContext>(0); } SV3_1aPpParser::Sv_file_directiveContext* SV3_1aPpParser::Directive_in_macroContext::sv_file_directive() { return getRuleContext<SV3_1aPpParser::Sv_file_directiveContext>(0); } SV3_1aPpParser::Sv_line_directiveContext* SV3_1aPpParser::Directive_in_macroContext::sv_line_directive() { return getRuleContext<SV3_1aPpParser::Sv_line_directiveContext>(0); } SV3_1aPpParser::Sv_packageContext* SV3_1aPpParser::Directive_in_macroContext::sv_package() { return getRuleContext<SV3_1aPpParser::Sv_packageContext>(0); } SV3_1aPpParser::EndpackageContext* SV3_1aPpParser::Directive_in_macroContext::endpackage() { return getRuleContext<SV3_1aPpParser::EndpackageContext>(0); } SV3_1aPpParser::ModuleContext* SV3_1aPpParser::Directive_in_macroContext::module() { return getRuleContext<SV3_1aPpParser::ModuleContext>(0); } SV3_1aPpParser::EndmoduleContext* SV3_1aPpParser::Directive_in_macroContext::endmodule() { return getRuleContext<SV3_1aPpParser::EndmoduleContext>(0); } SV3_1aPpParser::Sv_interfaceContext* SV3_1aPpParser::Directive_in_macroContext::sv_interface() { return getRuleContext<SV3_1aPpParser::Sv_interfaceContext>(0); } SV3_1aPpParser::EndinterfaceContext* SV3_1aPpParser::Directive_in_macroContext::endinterface() { return getRuleContext<SV3_1aPpParser::EndinterfaceContext>(0); } SV3_1aPpParser::ProgramContext* SV3_1aPpParser::Directive_in_macroContext::program() { return getRuleContext<SV3_1aPpParser::ProgramContext>(0); } SV3_1aPpParser::EndprogramContext* SV3_1aPpParser::Directive_in_macroContext::endprogram() { return getRuleContext<SV3_1aPpParser::EndprogramContext>(0); } SV3_1aPpParser::PrimitiveContext* SV3_1aPpParser::Directive_in_macroContext::primitive() { return getRuleContext<SV3_1aPpParser::PrimitiveContext>(0); } SV3_1aPpParser::EndprimitiveContext* SV3_1aPpParser::Directive_in_macroContext::endprimitive() { return getRuleContext<SV3_1aPpParser::EndprimitiveContext>(0); } SV3_1aPpParser::CheckerContext* SV3_1aPpParser::Directive_in_macroContext::checker() { return getRuleContext<SV3_1aPpParser::CheckerContext>(0); } SV3_1aPpParser::EndcheckerContext* SV3_1aPpParser::Directive_in_macroContext::endchecker() { return getRuleContext<SV3_1aPpParser::EndcheckerContext>(0); } SV3_1aPpParser::ConfigContext* SV3_1aPpParser::Directive_in_macroContext::config() { return getRuleContext<SV3_1aPpParser::ConfigContext>(0); } SV3_1aPpParser::EndconfigContext* SV3_1aPpParser::Directive_in_macroContext::endconfig() { return getRuleContext<SV3_1aPpParser::EndconfigContext>(0); } SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::Directive_in_macroContext::simple_args_macro_definition_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext>(0); } SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::Directive_in_macroContext::simple_no_args_macro_definition_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext>(0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Directive_in_macroContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Directive_in_macroContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } size_t SV3_1aPpParser::Directive_in_macroContext::getRuleIndex() const { return SV3_1aPpParser::RuleDirective_in_macro; } void SV3_1aPpParser::Directive_in_macroContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDirective_in_macro(this); } void SV3_1aPpParser::Directive_in_macroContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDirective_in_macro(this); } SV3_1aPpParser::Directive_in_macroContext* SV3_1aPpParser::directive_in_macro() { Directive_in_macroContext *_localctx = _tracker.createInstance<Directive_in_macroContext>(_ctx, getState()); enterRule(_localctx, 174, SV3_1aPpParser::RuleDirective_in_macro); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(806); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 47, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(743); celldefine_directive(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(744); endcelldefine_directive(); break; } case 3: { enterOuterAlt(_localctx, 3); setState(745); default_nettype_directive(); break; } case 4: { enterOuterAlt(_localctx, 4); setState(746); undef_directive(); break; } case 5: { enterOuterAlt(_localctx, 5); setState(747); ifdef_directive(); break; } case 6: { enterOuterAlt(_localctx, 6); setState(748); ifndef_directive(); break; } case 7: { enterOuterAlt(_localctx, 7); setState(749); else_directive(); break; } case 8: { enterOuterAlt(_localctx, 8); setState(750); elsif_directive(); break; } case 9: { enterOuterAlt(_localctx, 9); setState(751); elseif_directive(); break; } case 10: { enterOuterAlt(_localctx, 10); setState(752); endif_directive(); break; } case 11: { enterOuterAlt(_localctx, 11); setState(753); include_directive(); break; } case 12: { enterOuterAlt(_localctx, 12); setState(754); resetall_directive(); break; } case 13: { enterOuterAlt(_localctx, 13); setState(755); timescale_directive(); break; } case 14: { enterOuterAlt(_localctx, 14); setState(756); unconnected_drive_directive(); break; } case 15: { enterOuterAlt(_localctx, 15); setState(757); nounconnected_drive_directive(); break; } case 16: { enterOuterAlt(_localctx, 16); setState(758); line_directive(); break; } case 17: { enterOuterAlt(_localctx, 17); setState(759); default_decay_time_directive(); break; } case 18: { enterOuterAlt(_localctx, 18); setState(760); default_trireg_strenght_directive(); break; } case 19: { enterOuterAlt(_localctx, 19); setState(761); delay_mode_distributed_directive(); break; } case 20: { enterOuterAlt(_localctx, 20); setState(762); delay_mode_path_directive(); break; } case 21: { enterOuterAlt(_localctx, 21); setState(763); delay_mode_unit_directive(); break; } case 22: { enterOuterAlt(_localctx, 22); setState(764); delay_mode_zero_directive(); break; } case 23: { enterOuterAlt(_localctx, 23); setState(765); protect_directive(); break; } case 24: { enterOuterAlt(_localctx, 24); setState(766); endprotect_directive(); break; } case 25: { enterOuterAlt(_localctx, 25); setState(767); protected_directive(); break; } case 26: { enterOuterAlt(_localctx, 26); setState(768); endprotected_directive(); break; } case 27: { enterOuterAlt(_localctx, 27); setState(769); expand_vectornets_directive(); break; } case 28: { enterOuterAlt(_localctx, 28); setState(770); noexpand_vectornets_directive(); break; } case 29: { enterOuterAlt(_localctx, 29); setState(771); autoexpand_vectornets_directive(); break; } case 30: { enterOuterAlt(_localctx, 30); setState(772); remove_gatename_directive(); break; } case 31: { enterOuterAlt(_localctx, 31); setState(773); noremove_gatenames_directive(); break; } case 32: { enterOuterAlt(_localctx, 32); setState(774); remove_netname_directive(); break; } case 33: { enterOuterAlt(_localctx, 33); setState(775); noremove_netnames_directive(); break; } case 34: { enterOuterAlt(_localctx, 34); setState(776); accelerate_directive(); break; } case 35: { enterOuterAlt(_localctx, 35); setState(777); noaccelerate_directive(); break; } case 36: { enterOuterAlt(_localctx, 36); setState(778); undefineall_directive(); break; } case 37: { enterOuterAlt(_localctx, 37); setState(779); uselib_directive(); break; } case 38: { enterOuterAlt(_localctx, 38); setState(780); disable_portfaults_directive(); break; } case 39: { enterOuterAlt(_localctx, 39); setState(781); enable_portfaults_directive(); break; } case 40: { enterOuterAlt(_localctx, 40); setState(782); nosuppress_faults_directive(); break; } case 41: { enterOuterAlt(_localctx, 41); setState(783); suppress_faults_directive(); break; } case 42: { enterOuterAlt(_localctx, 42); setState(784); signed_directive(); break; } case 43: { enterOuterAlt(_localctx, 43); setState(785); unsigned_directive(); break; } case 44: { enterOuterAlt(_localctx, 44); setState(786); sv_file_directive(); break; } case 45: { enterOuterAlt(_localctx, 45); setState(787); sv_line_directive(); break; } case 46: { enterOuterAlt(_localctx, 46); setState(788); sv_package(); break; } case 47: { enterOuterAlt(_localctx, 47); setState(789); endpackage(); break; } case 48: { enterOuterAlt(_localctx, 48); setState(790); module(); break; } case 49: { enterOuterAlt(_localctx, 49); setState(791); endmodule(); break; } case 50: { enterOuterAlt(_localctx, 50); setState(792); sv_interface(); break; } case 51: { enterOuterAlt(_localctx, 51); setState(793); endinterface(); break; } case 52: { enterOuterAlt(_localctx, 52); setState(794); program(); break; } case 53: { enterOuterAlt(_localctx, 53); setState(795); endprogram(); break; } case 54: { enterOuterAlt(_localctx, 54); setState(796); primitive(); break; } case 55: { enterOuterAlt(_localctx, 55); setState(797); endprimitive(); break; } case 56: { enterOuterAlt(_localctx, 56); setState(798); checker(); break; } case 57: { enterOuterAlt(_localctx, 57); setState(799); endchecker(); break; } case 58: { enterOuterAlt(_localctx, 58); setState(800); config(); break; } case 59: { enterOuterAlt(_localctx, 59); setState(801); endconfig(); break; } case 60: { enterOuterAlt(_localctx, 60); setState(802); simple_args_macro_definition_in_macro_body(); break; } case 61: { enterOuterAlt(_localctx, 61); setState(803); simple_no_args_macro_definition_in_macro_body(); break; } case 62: { enterOuterAlt(_localctx, 62); setState(804); pound_delay(); break; } case 63: { enterOuterAlt(_localctx, 63); setState(805); pound_pound_delay(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Macro_argumentsContext ------------------------------------------------------------------ SV3_1aPpParser::Macro_argumentsContext::Macro_argumentsContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Macro_argumentsContext::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Macro_argumentsContext::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Macro_argumentsContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Macro_argumentsContext::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Macro_argumentsContext::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<SV3_1aPpParser::Default_valueContext *> SV3_1aPpParser::Macro_argumentsContext::default_value() { return getRuleContexts<SV3_1aPpParser::Default_valueContext>(); } SV3_1aPpParser::Default_valueContext* SV3_1aPpParser::Macro_argumentsContext::default_value(size_t i) { return getRuleContext<SV3_1aPpParser::Default_valueContext>(i); } size_t SV3_1aPpParser::Macro_argumentsContext::getRuleIndex() const { return SV3_1aPpParser::RuleMacro_arguments; } void SV3_1aPpParser::Macro_argumentsContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacro_arguments(this); } void SV3_1aPpParser::Macro_argumentsContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacro_arguments(this); } SV3_1aPpParser::Macro_argumentsContext* SV3_1aPpParser::macro_arguments() { Macro_argumentsContext *_localctx = _tracker.createInstance<Macro_argumentsContext>(_ctx, getState()); enterRule(_localctx, 176, SV3_1aPpParser::RuleMacro_arguments); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(808); match(SV3_1aPpParser::PARENS_OPEN); setState(867); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Simple_identifier || _la == SV3_1aPpParser::Spaces) { setState(812); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(809); match(SV3_1aPpParser::Spaces); setState(814); _errHandler->sync(this); _la = _input->LA(1); } setState(815); match(SV3_1aPpParser::Simple_identifier); setState(819); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 49, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(816); match(SV3_1aPpParser::Spaces); } setState(821); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 49, _ctx); } setState(831); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::EQUAL_OP) { setState(822); match(SV3_1aPpParser::EQUAL_OP); setState(826); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 50, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(823); default_value(); } setState(828); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 50, _ctx); } setState(833); _errHandler->sync(this); _la = _input->LA(1); } setState(862); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::COMMA) { setState(834); match(SV3_1aPpParser::COMMA); setState(838); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(835); match(SV3_1aPpParser::Spaces); setState(840); _errHandler->sync(this); _la = _input->LA(1); } setState(841); match(SV3_1aPpParser::Simple_identifier); setState(845); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 53, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(842); match(SV3_1aPpParser::Spaces); } setState(847); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 53, _ctx); } setState(857); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::EQUAL_OP) { setState(848); match(SV3_1aPpParser::EQUAL_OP); setState(852); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 54, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(849); default_value(); } setState(854); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 54, _ctx); } setState(859); _errHandler->sync(this); _la = _input->LA(1); } setState(864); _errHandler->sync(this); _la = _input->LA(1); } setState(869); _errHandler->sync(this); _la = _input->LA(1); } setState(870); match(SV3_1aPpParser::PARENS_CLOSE); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Escaped_macro_definition_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Escaped_macro_definition_bodyContext::Escaped_macro_definition_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } SV3_1aPpParser::Escaped_macro_definition_body_alt1Context* SV3_1aPpParser::Escaped_macro_definition_bodyContext::escaped_macro_definition_body_alt1() { return getRuleContext<SV3_1aPpParser::Escaped_macro_definition_body_alt1Context>(0); } SV3_1aPpParser::Escaped_macro_definition_body_alt2Context* SV3_1aPpParser::Escaped_macro_definition_bodyContext::escaped_macro_definition_body_alt2() { return getRuleContext<SV3_1aPpParser::Escaped_macro_definition_body_alt2Context>(0); } size_t SV3_1aPpParser::Escaped_macro_definition_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleEscaped_macro_definition_body; } void SV3_1aPpParser::Escaped_macro_definition_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEscaped_macro_definition_body(this); } void SV3_1aPpParser::Escaped_macro_definition_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEscaped_macro_definition_body(this); } SV3_1aPpParser::Escaped_macro_definition_bodyContext* SV3_1aPpParser::escaped_macro_definition_body() { Escaped_macro_definition_bodyContext *_localctx = _tracker.createInstance<Escaped_macro_definition_bodyContext>(_ctx, getState()); enterRule(_localctx, 178, SV3_1aPpParser::RuleEscaped_macro_definition_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(874); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 58, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(872); escaped_macro_definition_body_alt1(); break; } case 2: { enterOuterAlt(_localctx, 2); setState(873); escaped_macro_definition_body_alt2(); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Escaped_macro_definition_body_alt1Context ------------------------------------------------------------------ SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Escaped_macro_definition_body_alt1Context(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::ESCAPED_CR() { return getTokens(SV3_1aPpParser::ESCAPED_CR); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::ESCAPED_CR(size_t i) { return getToken(SV3_1aPpParser::ESCAPED_CR, i); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::EOF() { return getToken(SV3_1aPpParser::EOF, 0); } std::vector<SV3_1aPpParser::Unterminated_stringContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::unterminated_string() { return getRuleContexts<SV3_1aPpParser::Unterminated_stringContext>(); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::unterminated_string(size_t i) { return getRuleContext<SV3_1aPpParser::Unterminated_stringContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Macro_identifier() { return getTokens(SV3_1aPpParser::Macro_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Macro_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Macro_Escaped_identifier() { return getTokens(SV3_1aPpParser::Macro_Escaped_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Macro_Escaped_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, i); } std::vector<SV3_1aPpParser::Escaped_identifierContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::escaped_identifier() { return getRuleContexts<SV3_1aPpParser::Escaped_identifierContext>(); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::escaped_identifier(size_t i) { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TEXT_CR() { return getTokens(SV3_1aPpParser::TEXT_CR); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TEXT_CR(size_t i) { return getToken(SV3_1aPpParser::TEXT_CR, i); } std::vector<SV3_1aPpParser::Pound_delayContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_delayContext>(); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(i); } std::vector<SV3_1aPpParser::Pound_pound_delayContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::pound_pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_pound_delayContext>(); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::pound_pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::PARENS_OPEN() { return getTokens(SV3_1aPpParser::PARENS_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::PARENS_OPEN(size_t i) { return getToken(SV3_1aPpParser::PARENS_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::PARENS_CLOSE() { return getTokens(SV3_1aPpParser::PARENS_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::PARENS_CLOSE(size_t i) { return getToken(SV3_1aPpParser::PARENS_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::DOUBLE_QUOTE() { return getTokens(SV3_1aPpParser::DOUBLE_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::DOUBLE_QUOTE(size_t i) { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_VARIABLE() { return getTokens(SV3_1aPpParser::TICK_VARIABLE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_VARIABLE(size_t i) { return getToken(SV3_1aPpParser::TICK_VARIABLE, i); } std::vector<SV3_1aPpParser::Directive_in_macroContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::directive_in_macro() { return getRuleContexts<SV3_1aPpParser::Directive_in_macroContext>(); } SV3_1aPpParser::Directive_in_macroContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::directive_in_macro(size_t i) { return getRuleContext<SV3_1aPpParser::Directive_in_macroContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Fixed_point_number() { return getTokens(SV3_1aPpParser::Fixed_point_number); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Fixed_point_number(size_t i) { return getToken(SV3_1aPpParser::Fixed_point_number, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::String() { return getTokens(SV3_1aPpParser::String); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::String(size_t i) { return getToken(SV3_1aPpParser::String, i); } std::vector<SV3_1aPpParser::CommentsContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::comments() { return getRuleContexts<SV3_1aPpParser::CommentsContext>(); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::comments(size_t i) { return getRuleContext<SV3_1aPpParser::CommentsContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_BACKSLASH_TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_BACKSLASH_TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_TICK() { return getTokens(SV3_1aPpParser::TICK_TICK); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::TICK_TICK(size_t i) { return getToken(SV3_1aPpParser::TICK_TICK, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::CURLY_OPEN() { return getTokens(SV3_1aPpParser::CURLY_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::CURLY_OPEN(size_t i) { return getToken(SV3_1aPpParser::CURLY_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::CURLY_CLOSE() { return getTokens(SV3_1aPpParser::CURLY_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::CURLY_CLOSE(size_t i) { return getToken(SV3_1aPpParser::CURLY_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::SQUARE_OPEN() { return getTokens(SV3_1aPpParser::SQUARE_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::SQUARE_OPEN(size_t i) { return getToken(SV3_1aPpParser::SQUARE_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::SQUARE_CLOSE() { return getTokens(SV3_1aPpParser::SQUARE_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::SQUARE_CLOSE(size_t i) { return getToken(SV3_1aPpParser::SQUARE_CLOSE, i); } size_t SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::getRuleIndex() const { return SV3_1aPpParser::RuleEscaped_macro_definition_body_alt1; } void SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEscaped_macro_definition_body_alt1(this); } void SV3_1aPpParser::Escaped_macro_definition_body_alt1Context::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEscaped_macro_definition_body_alt1(this); } SV3_1aPpParser::Escaped_macro_definition_body_alt1Context* SV3_1aPpParser::escaped_macro_definition_body_alt1() { Escaped_macro_definition_body_alt1Context *_localctx = _tracker.createInstance<Escaped_macro_definition_body_alt1Context>(_ctx, getState()); enterRule(_localctx, 180, SV3_1aPpParser::RuleEscaped_macro_definition_body_alt1); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(907); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 60, _ctx); while (alt != 1 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1 + 1) { setState(905); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 59, _ctx)) { case 1: { setState(876); unterminated_string(); break; } case 2: { setState(877); match(SV3_1aPpParser::Macro_identifier); break; } case 3: { setState(878); match(SV3_1aPpParser::Macro_Escaped_identifier); break; } case 4: { setState(879); escaped_identifier(); break; } case 5: { setState(880); match(SV3_1aPpParser::Simple_identifier); break; } case 6: { setState(881); number(); break; } case 7: { setState(882); match(SV3_1aPpParser::TEXT_CR); break; } case 8: { setState(883); pound_delay(); break; } case 9: { setState(884); pound_pound_delay(); break; } case 10: { setState(885); match(SV3_1aPpParser::ESCAPED_CR); break; } case 11: { setState(886); match(SV3_1aPpParser::PARENS_OPEN); break; } case 12: { setState(887); match(SV3_1aPpParser::PARENS_CLOSE); break; } case 13: { setState(888); match(SV3_1aPpParser::COMMA); break; } case 14: { setState(889); match(SV3_1aPpParser::EQUAL_OP); break; } case 15: { setState(890); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case 16: { setState(891); match(SV3_1aPpParser::TICK_VARIABLE); break; } case 17: { setState(892); directive_in_macro(); break; } case 18: { setState(893); match(SV3_1aPpParser::Spaces); break; } case 19: { setState(894); match(SV3_1aPpParser::Fixed_point_number); break; } case 20: { setState(895); match(SV3_1aPpParser::String); break; } case 21: { setState(896); comments(); break; } case 22: { setState(897); match(SV3_1aPpParser::TICK_QUOTE); break; } case 23: { setState(898); match(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); break; } case 24: { setState(899); match(SV3_1aPpParser::TICK_TICK); break; } case 25: { setState(900); match(SV3_1aPpParser::Special); break; } case 26: { setState(901); match(SV3_1aPpParser::CURLY_OPEN); break; } case 27: { setState(902); match(SV3_1aPpParser::CURLY_CLOSE); break; } case 28: { setState(903); match(SV3_1aPpParser::SQUARE_OPEN); break; } case 29: { setState(904); match(SV3_1aPpParser::SQUARE_CLOSE); break; } default: break; } } setState(909); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 60, _ctx); } setState(910); match(SV3_1aPpParser::ESCAPED_CR); setState(914); _errHandler->sync(this); _la = _input->LA(1); while (_la == SV3_1aPpParser::Spaces) { setState(911); match(SV3_1aPpParser::Spaces); setState(916); _errHandler->sync(this); _la = _input->LA(1); } setState(917); _la = _input->LA(1); if (!(_la == SV3_1aPpParser::EOF || _la == SV3_1aPpParser::CR)) { _errHandler->recoverInline(this); } else { _errHandler->reportMatch(this); consume(); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Escaped_macro_definition_body_alt2Context ------------------------------------------------------------------ SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Escaped_macro_definition_body_alt2Context(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::EOF() { return getToken(SV3_1aPpParser::EOF, 0); } std::vector<SV3_1aPpParser::Unterminated_stringContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::unterminated_string() { return getRuleContexts<SV3_1aPpParser::Unterminated_stringContext>(); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::unterminated_string(size_t i) { return getRuleContext<SV3_1aPpParser::Unterminated_stringContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Macro_identifier() { return getTokens(SV3_1aPpParser::Macro_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Macro_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Macro_Escaped_identifier() { return getTokens(SV3_1aPpParser::Macro_Escaped_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Macro_Escaped_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, i); } std::vector<SV3_1aPpParser::Escaped_identifierContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::escaped_identifier() { return getRuleContexts<SV3_1aPpParser::Escaped_identifierContext>(); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::escaped_identifier(size_t i) { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TEXT_CR() { return getTokens(SV3_1aPpParser::TEXT_CR); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TEXT_CR(size_t i) { return getToken(SV3_1aPpParser::TEXT_CR, i); } std::vector<SV3_1aPpParser::Pound_delayContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_delayContext>(); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(i); } std::vector<SV3_1aPpParser::Pound_pound_delayContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::pound_pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_pound_delayContext>(); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::pound_pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::ESCAPED_CR() { return getTokens(SV3_1aPpParser::ESCAPED_CR); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::ESCAPED_CR(size_t i) { return getToken(SV3_1aPpParser::ESCAPED_CR, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::PARENS_OPEN() { return getTokens(SV3_1aPpParser::PARENS_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::PARENS_OPEN(size_t i) { return getToken(SV3_1aPpParser::PARENS_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::PARENS_CLOSE() { return getTokens(SV3_1aPpParser::PARENS_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::PARENS_CLOSE(size_t i) { return getToken(SV3_1aPpParser::PARENS_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::DOUBLE_QUOTE() { return getTokens(SV3_1aPpParser::DOUBLE_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::DOUBLE_QUOTE(size_t i) { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_VARIABLE() { return getTokens(SV3_1aPpParser::TICK_VARIABLE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_VARIABLE(size_t i) { return getToken(SV3_1aPpParser::TICK_VARIABLE, i); } std::vector<SV3_1aPpParser::Directive_in_macroContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::directive_in_macro() { return getRuleContexts<SV3_1aPpParser::Directive_in_macroContext>(); } SV3_1aPpParser::Directive_in_macroContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::directive_in_macro(size_t i) { return getRuleContext<SV3_1aPpParser::Directive_in_macroContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Fixed_point_number() { return getTokens(SV3_1aPpParser::Fixed_point_number); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Fixed_point_number(size_t i) { return getToken(SV3_1aPpParser::Fixed_point_number, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::String() { return getTokens(SV3_1aPpParser::String); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::String(size_t i) { return getToken(SV3_1aPpParser::String, i); } std::vector<SV3_1aPpParser::CommentsContext *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::comments() { return getRuleContexts<SV3_1aPpParser::CommentsContext>(); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::comments(size_t i) { return getRuleContext<SV3_1aPpParser::CommentsContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_BACKSLASH_TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_BACKSLASH_TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_TICK() { return getTokens(SV3_1aPpParser::TICK_TICK); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::TICK_TICK(size_t i) { return getToken(SV3_1aPpParser::TICK_TICK, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::CURLY_OPEN() { return getTokens(SV3_1aPpParser::CURLY_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::CURLY_OPEN(size_t i) { return getToken(SV3_1aPpParser::CURLY_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::CURLY_CLOSE() { return getTokens(SV3_1aPpParser::CURLY_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::CURLY_CLOSE(size_t i) { return getToken(SV3_1aPpParser::CURLY_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::SQUARE_OPEN() { return getTokens(SV3_1aPpParser::SQUARE_OPEN); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::SQUARE_OPEN(size_t i) { return getToken(SV3_1aPpParser::SQUARE_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::SQUARE_CLOSE() { return getTokens(SV3_1aPpParser::SQUARE_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::SQUARE_CLOSE(size_t i) { return getToken(SV3_1aPpParser::SQUARE_CLOSE, i); } size_t SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::getRuleIndex() const { return SV3_1aPpParser::RuleEscaped_macro_definition_body_alt2; } void SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterEscaped_macro_definition_body_alt2(this); } void SV3_1aPpParser::Escaped_macro_definition_body_alt2Context::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitEscaped_macro_definition_body_alt2(this); } SV3_1aPpParser::Escaped_macro_definition_body_alt2Context* SV3_1aPpParser::escaped_macro_definition_body_alt2() { Escaped_macro_definition_body_alt2Context *_localctx = _tracker.createInstance<Escaped_macro_definition_body_alt2Context>(_ctx, getState()); enterRule(_localctx, 182, SV3_1aPpParser::RuleEscaped_macro_definition_body_alt2); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(950); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 63, _ctx); while (alt != 1 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1 + 1) { setState(948); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 62, _ctx)) { case 1: { setState(919); unterminated_string(); break; } case 2: { setState(920); match(SV3_1aPpParser::Macro_identifier); break; } case 3: { setState(921); match(SV3_1aPpParser::Macro_Escaped_identifier); break; } case 4: { setState(922); escaped_identifier(); break; } case 5: { setState(923); match(SV3_1aPpParser::Simple_identifier); break; } case 6: { setState(924); number(); break; } case 7: { setState(925); match(SV3_1aPpParser::TEXT_CR); break; } case 8: { setState(926); pound_delay(); break; } case 9: { setState(927); pound_pound_delay(); break; } case 10: { setState(928); match(SV3_1aPpParser::ESCAPED_CR); break; } case 11: { setState(929); match(SV3_1aPpParser::PARENS_OPEN); break; } case 12: { setState(930); match(SV3_1aPpParser::PARENS_CLOSE); break; } case 13: { setState(931); match(SV3_1aPpParser::COMMA); break; } case 14: { setState(932); match(SV3_1aPpParser::EQUAL_OP); break; } case 15: { setState(933); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case 16: { setState(934); match(SV3_1aPpParser::TICK_VARIABLE); break; } case 17: { setState(935); directive_in_macro(); break; } case 18: { setState(936); match(SV3_1aPpParser::Spaces); break; } case 19: { setState(937); match(SV3_1aPpParser::Fixed_point_number); break; } case 20: { setState(938); match(SV3_1aPpParser::String); break; } case 21: { setState(939); comments(); break; } case 22: { setState(940); match(SV3_1aPpParser::TICK_QUOTE); break; } case 23: { setState(941); match(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); break; } case 24: { setState(942); match(SV3_1aPpParser::TICK_TICK); break; } case 25: { setState(943); match(SV3_1aPpParser::Special); break; } case 26: { setState(944); match(SV3_1aPpParser::CURLY_OPEN); break; } case 27: { setState(945); match(SV3_1aPpParser::CURLY_CLOSE); break; } case 28: { setState(946); match(SV3_1aPpParser::SQUARE_OPEN); break; } case 29: { setState(947); match(SV3_1aPpParser::SQUARE_CLOSE); break; } default: break; } } setState(952); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 63, _ctx); } setState(961); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::CR: { setState(953); match(SV3_1aPpParser::CR); setState(957); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 64, _ctx); while (alt != 2 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1) { setState(954); match(SV3_1aPpParser::Spaces); } setState(959); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 64, _ctx); } break; } case SV3_1aPpParser::EOF: { setState(960); match(SV3_1aPpParser::EOF); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_macro_definition_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_macro_definition_bodyContext::Simple_macro_definition_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<SV3_1aPpParser::Unterminated_stringContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::unterminated_string() { return getRuleContexts<SV3_1aPpParser::Unterminated_stringContext>(); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::unterminated_string(size_t i) { return getRuleContext<SV3_1aPpParser::Unterminated_stringContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Macro_identifier() { return getTokens(SV3_1aPpParser::Macro_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Macro_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Macro_Escaped_identifier() { return getTokens(SV3_1aPpParser::Macro_Escaped_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Macro_Escaped_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, i); } std::vector<SV3_1aPpParser::Escaped_identifierContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::escaped_identifier() { return getRuleContexts<SV3_1aPpParser::Escaped_identifierContext>(); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::escaped_identifier(size_t i) { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } std::vector<SV3_1aPpParser::Pound_delayContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_delayContext>(); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(i); } std::vector<SV3_1aPpParser::Pound_pound_delayContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::pound_pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_pound_delayContext>(); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::pound_pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TEXT_CR() { return getTokens(SV3_1aPpParser::TEXT_CR); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TEXT_CR(size_t i) { return getToken(SV3_1aPpParser::TEXT_CR, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::PARENS_OPEN() { return getTokens(SV3_1aPpParser::PARENS_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::PARENS_OPEN(size_t i) { return getToken(SV3_1aPpParser::PARENS_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::PARENS_CLOSE() { return getTokens(SV3_1aPpParser::PARENS_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::PARENS_CLOSE(size_t i) { return getToken(SV3_1aPpParser::PARENS_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::DOUBLE_QUOTE() { return getTokens(SV3_1aPpParser::DOUBLE_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::DOUBLE_QUOTE(size_t i) { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_VARIABLE() { return getTokens(SV3_1aPpParser::TICK_VARIABLE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_VARIABLE(size_t i) { return getToken(SV3_1aPpParser::TICK_VARIABLE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Fixed_point_number() { return getTokens(SV3_1aPpParser::Fixed_point_number); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Fixed_point_number(size_t i) { return getToken(SV3_1aPpParser::Fixed_point_number, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::String() { return getTokens(SV3_1aPpParser::String); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::String(size_t i) { return getToken(SV3_1aPpParser::String, i); } std::vector<SV3_1aPpParser::CommentsContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::comments() { return getRuleContexts<SV3_1aPpParser::CommentsContext>(); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::comments(size_t i) { return getRuleContext<SV3_1aPpParser::CommentsContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_BACKSLASH_TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_BACKSLASH_TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_TICK() { return getTokens(SV3_1aPpParser::TICK_TICK); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_TICK(size_t i) { return getToken(SV3_1aPpParser::TICK_TICK, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::CURLY_OPEN() { return getTokens(SV3_1aPpParser::CURLY_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::CURLY_OPEN(size_t i) { return getToken(SV3_1aPpParser::CURLY_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::CURLY_CLOSE() { return getTokens(SV3_1aPpParser::CURLY_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::CURLY_CLOSE(size_t i) { return getToken(SV3_1aPpParser::CURLY_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::SQUARE_OPEN() { return getTokens(SV3_1aPpParser::SQUARE_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::SQUARE_OPEN(size_t i) { return getToken(SV3_1aPpParser::SQUARE_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::SQUARE_CLOSE() { return getTokens(SV3_1aPpParser::SQUARE_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::SQUARE_CLOSE(size_t i) { return getToken(SV3_1aPpParser::SQUARE_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_INCLUDE() { return getTokens(SV3_1aPpParser::TICK_INCLUDE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_bodyContext::TICK_INCLUDE(size_t i) { return getToken(SV3_1aPpParser::TICK_INCLUDE, i); } std::vector<SV3_1aPpParser::Directive_in_macroContext *> SV3_1aPpParser::Simple_macro_definition_bodyContext::directive_in_macro() { return getRuleContexts<SV3_1aPpParser::Directive_in_macroContext>(); } SV3_1aPpParser::Directive_in_macroContext* SV3_1aPpParser::Simple_macro_definition_bodyContext::directive_in_macro(size_t i) { return getRuleContext<SV3_1aPpParser::Directive_in_macroContext>(i); } size_t SV3_1aPpParser::Simple_macro_definition_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_macro_definition_body; } void SV3_1aPpParser::Simple_macro_definition_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_macro_definition_body(this); } void SV3_1aPpParser::Simple_macro_definition_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_macro_definition_body(this); } SV3_1aPpParser::Simple_macro_definition_bodyContext* SV3_1aPpParser::simple_macro_definition_body() { Simple_macro_definition_bodyContext *_localctx = _tracker.createInstance<Simple_macro_definition_bodyContext>(_ctx, getState()); enterRule(_localctx, 184, SV3_1aPpParser::RuleSimple_macro_definition_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(994); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 67, _ctx); while (alt != 1 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1 + 1) { setState(992); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 66, _ctx)) { case 1: { setState(963); unterminated_string(); break; } case 2: { setState(964); match(SV3_1aPpParser::Macro_identifier); break; } case 3: { setState(965); match(SV3_1aPpParser::Macro_Escaped_identifier); break; } case 4: { setState(966); escaped_identifier(); break; } case 5: { setState(967); match(SV3_1aPpParser::Simple_identifier); break; } case 6: { setState(968); number(); break; } case 7: { setState(969); pound_delay(); break; } case 8: { setState(970); pound_pound_delay(); break; } case 9: { setState(971); match(SV3_1aPpParser::TEXT_CR); break; } case 10: { setState(972); match(SV3_1aPpParser::PARENS_OPEN); break; } case 11: { setState(973); match(SV3_1aPpParser::PARENS_CLOSE); break; } case 12: { setState(974); match(SV3_1aPpParser::COMMA); break; } case 13: { setState(975); match(SV3_1aPpParser::EQUAL_OP); break; } case 14: { setState(976); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case 15: { setState(977); match(SV3_1aPpParser::TICK_VARIABLE); break; } case 16: { setState(978); match(SV3_1aPpParser::Spaces); break; } case 17: { setState(979); match(SV3_1aPpParser::Fixed_point_number); break; } case 18: { setState(980); match(SV3_1aPpParser::String); break; } case 19: { setState(981); comments(); break; } case 20: { setState(982); match(SV3_1aPpParser::TICK_QUOTE); break; } case 21: { setState(983); match(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); break; } case 22: { setState(984); match(SV3_1aPpParser::TICK_TICK); break; } case 23: { setState(985); match(SV3_1aPpParser::Special); break; } case 24: { setState(986); match(SV3_1aPpParser::CURLY_OPEN); break; } case 25: { setState(987); match(SV3_1aPpParser::CURLY_CLOSE); break; } case 26: { setState(988); match(SV3_1aPpParser::SQUARE_OPEN); break; } case 27: { setState(989); match(SV3_1aPpParser::SQUARE_CLOSE); break; } case 28: { setState(990); match(SV3_1aPpParser::TICK_INCLUDE); break; } case 29: { setState(991); directive_in_macro(); break; } default: break; } } setState(996); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 67, _ctx); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Simple_macro_definition_body_in_macro_bodyContext ------------------------------------------------------------------ SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Simple_macro_definition_body_in_macro_bodyContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } std::vector<SV3_1aPpParser::Unterminated_stringContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::unterminated_string() { return getRuleContexts<SV3_1aPpParser::Unterminated_stringContext>(); } SV3_1aPpParser::Unterminated_stringContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::unterminated_string(size_t i) { return getRuleContext<SV3_1aPpParser::Unterminated_stringContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Macro_identifier() { return getTokens(SV3_1aPpParser::Macro_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Macro_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_identifier, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Macro_Escaped_identifier() { return getTokens(SV3_1aPpParser::Macro_Escaped_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Macro_Escaped_identifier(size_t i) { return getToken(SV3_1aPpParser::Macro_Escaped_identifier, i); } std::vector<SV3_1aPpParser::Escaped_identifierContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::escaped_identifier() { return getRuleContexts<SV3_1aPpParser::Escaped_identifierContext>(); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::escaped_identifier(size_t i) { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } std::vector<SV3_1aPpParser::Pound_delayContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_delayContext>(); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(i); } std::vector<SV3_1aPpParser::Pound_pound_delayContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::pound_pound_delay() { return getRuleContexts<SV3_1aPpParser::Pound_pound_delayContext>(); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::pound_pound_delay(size_t i) { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TEXT_CR() { return getTokens(SV3_1aPpParser::TEXT_CR); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TEXT_CR(size_t i) { return getToken(SV3_1aPpParser::TEXT_CR, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::PARENS_OPEN() { return getTokens(SV3_1aPpParser::PARENS_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::PARENS_OPEN(size_t i) { return getToken(SV3_1aPpParser::PARENS_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::PARENS_CLOSE() { return getTokens(SV3_1aPpParser::PARENS_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::PARENS_CLOSE(size_t i) { return getToken(SV3_1aPpParser::PARENS_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::DOUBLE_QUOTE() { return getTokens(SV3_1aPpParser::DOUBLE_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::DOUBLE_QUOTE(size_t i) { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_VARIABLE() { return getTokens(SV3_1aPpParser::TICK_VARIABLE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_VARIABLE(size_t i) { return getToken(SV3_1aPpParser::TICK_VARIABLE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Fixed_point_number() { return getTokens(SV3_1aPpParser::Fixed_point_number); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Fixed_point_number(size_t i) { return getToken(SV3_1aPpParser::Fixed_point_number, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::String() { return getTokens(SV3_1aPpParser::String); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::String(size_t i) { return getToken(SV3_1aPpParser::String, i); } std::vector<SV3_1aPpParser::CommentsContext *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::comments() { return getRuleContexts<SV3_1aPpParser::CommentsContext>(); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::comments(size_t i) { return getRuleContext<SV3_1aPpParser::CommentsContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_BACKSLASH_TICK_QUOTE() { return getTokens(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_BACKSLASH_TICK_QUOTE(size_t i) { return getToken(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_TICK() { return getTokens(SV3_1aPpParser::TICK_TICK); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::TICK_TICK(size_t i) { return getToken(SV3_1aPpParser::TICK_TICK, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::CURLY_OPEN() { return getTokens(SV3_1aPpParser::CURLY_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::CURLY_OPEN(size_t i) { return getToken(SV3_1aPpParser::CURLY_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::CURLY_CLOSE() { return getTokens(SV3_1aPpParser::CURLY_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::CURLY_CLOSE(size_t i) { return getToken(SV3_1aPpParser::CURLY_CLOSE, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::SQUARE_OPEN() { return getTokens(SV3_1aPpParser::SQUARE_OPEN); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::SQUARE_OPEN(size_t i) { return getToken(SV3_1aPpParser::SQUARE_OPEN, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::SQUARE_CLOSE() { return getTokens(SV3_1aPpParser::SQUARE_CLOSE); } tree::TerminalNode* SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::SQUARE_CLOSE(size_t i) { return getToken(SV3_1aPpParser::SQUARE_CLOSE, i); } size_t SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::getRuleIndex() const { return SV3_1aPpParser::RuleSimple_macro_definition_body_in_macro_body; } void SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterSimple_macro_definition_body_in_macro_body(this); } void SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitSimple_macro_definition_body_in_macro_body(this); } SV3_1aPpParser::Simple_macro_definition_body_in_macro_bodyContext* SV3_1aPpParser::simple_macro_definition_body_in_macro_body() { Simple_macro_definition_body_in_macro_bodyContext *_localctx = _tracker.createInstance<Simple_macro_definition_body_in_macro_bodyContext>(_ctx, getState()); enterRule(_localctx, 186, SV3_1aPpParser::RuleSimple_macro_definition_body_in_macro_body); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { size_t alt; enterOuterAlt(_localctx, 1); setState(1026); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 69, _ctx); while (alt != 1 && alt != atn::ATN::INVALID_ALT_NUMBER) { if (alt == 1 + 1) { setState(1024); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 68, _ctx)) { case 1: { setState(997); unterminated_string(); break; } case 2: { setState(998); match(SV3_1aPpParser::Macro_identifier); break; } case 3: { setState(999); match(SV3_1aPpParser::Macro_Escaped_identifier); break; } case 4: { setState(1000); escaped_identifier(); break; } case 5: { setState(1001); match(SV3_1aPpParser::Simple_identifier); break; } case 6: { setState(1002); number(); break; } case 7: { setState(1003); pound_delay(); break; } case 8: { setState(1004); pound_pound_delay(); break; } case 9: { setState(1005); match(SV3_1aPpParser::TEXT_CR); break; } case 10: { setState(1006); match(SV3_1aPpParser::PARENS_OPEN); break; } case 11: { setState(1007); match(SV3_1aPpParser::PARENS_CLOSE); break; } case 12: { setState(1008); match(SV3_1aPpParser::COMMA); break; } case 13: { setState(1009); match(SV3_1aPpParser::EQUAL_OP); break; } case 14: { setState(1010); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case 15: { setState(1011); match(SV3_1aPpParser::TICK_VARIABLE); break; } case 16: { setState(1012); match(SV3_1aPpParser::Spaces); break; } case 17: { setState(1013); match(SV3_1aPpParser::Fixed_point_number); break; } case 18: { setState(1014); match(SV3_1aPpParser::String); break; } case 19: { setState(1015); comments(); break; } case 20: { setState(1016); match(SV3_1aPpParser::TICK_QUOTE); break; } case 21: { setState(1017); match(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); break; } case 22: { setState(1018); match(SV3_1aPpParser::TICK_TICK); break; } case 23: { setState(1019); match(SV3_1aPpParser::Special); break; } case 24: { setState(1020); match(SV3_1aPpParser::CURLY_OPEN); break; } case 25: { setState(1021); match(SV3_1aPpParser::CURLY_CLOSE); break; } case 26: { setState(1022); match(SV3_1aPpParser::SQUARE_OPEN); break; } case 27: { setState(1023); match(SV3_1aPpParser::SQUARE_CLOSE); break; } default: break; } } setState(1028); _errHandler->sync(this); alt = getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 69, _ctx); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Pragma_expressionContext ------------------------------------------------------------------ SV3_1aPpParser::Pragma_expressionContext::Pragma_expressionContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Pragma_expressionContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::String() { return getToken(SV3_1aPpParser::String, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::CURLY_OPEN() { return getToken(SV3_1aPpParser::CURLY_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::CURLY_CLOSE() { return getToken(SV3_1aPpParser::CURLY_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::SQUARE_OPEN() { return getToken(SV3_1aPpParser::SQUARE_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::SQUARE_CLOSE() { return getToken(SV3_1aPpParser::SQUARE_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::COMMA() { return getToken(SV3_1aPpParser::COMMA, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::EQUAL_OP() { return getToken(SV3_1aPpParser::EQUAL_OP, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::DOUBLE_QUOTE() { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, 0); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Pragma_expressionContext::escaped_identifier() { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Pragma_expressionContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Pragma_expressionContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::Special() { return getToken(SV3_1aPpParser::Special, 0); } tree::TerminalNode* SV3_1aPpParser::Pragma_expressionContext::ANY() { return getToken(SV3_1aPpParser::ANY, 0); } size_t SV3_1aPpParser::Pragma_expressionContext::getRuleIndex() const { return SV3_1aPpParser::RulePragma_expression; } void SV3_1aPpParser::Pragma_expressionContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPragma_expression(this); } void SV3_1aPpParser::Pragma_expressionContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPragma_expression(this); } SV3_1aPpParser::Pragma_expressionContext* SV3_1aPpParser::pragma_expression() { Pragma_expressionContext *_localctx = _tracker.createInstance<Pragma_expressionContext>(_ctx, getState()); enterRule(_localctx, 188, SV3_1aPpParser::RulePragma_expression); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1048); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { enterOuterAlt(_localctx, 1); setState(1029); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { enterOuterAlt(_localctx, 2); setState(1030); number(); break; } case SV3_1aPpParser::Spaces: { enterOuterAlt(_localctx, 3); setState(1031); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { enterOuterAlt(_localctx, 4); setState(1032); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::String: { enterOuterAlt(_localctx, 5); setState(1033); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::CURLY_OPEN: { enterOuterAlt(_localctx, 6); setState(1034); match(SV3_1aPpParser::CURLY_OPEN); break; } case SV3_1aPpParser::CURLY_CLOSE: { enterOuterAlt(_localctx, 7); setState(1035); match(SV3_1aPpParser::CURLY_CLOSE); break; } case SV3_1aPpParser::SQUARE_OPEN: { enterOuterAlt(_localctx, 8); setState(1036); match(SV3_1aPpParser::SQUARE_OPEN); break; } case SV3_1aPpParser::SQUARE_CLOSE: { enterOuterAlt(_localctx, 9); setState(1037); match(SV3_1aPpParser::SQUARE_CLOSE); break; } case SV3_1aPpParser::PARENS_OPEN: { enterOuterAlt(_localctx, 10); setState(1038); match(SV3_1aPpParser::PARENS_OPEN); break; } case SV3_1aPpParser::PARENS_CLOSE: { enterOuterAlt(_localctx, 11); setState(1039); match(SV3_1aPpParser::PARENS_CLOSE); break; } case SV3_1aPpParser::COMMA: { enterOuterAlt(_localctx, 12); setState(1040); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { enterOuterAlt(_localctx, 13); setState(1041); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { enterOuterAlt(_localctx, 14); setState(1042); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::Escaped_identifier: { enterOuterAlt(_localctx, 15); setState(1043); escaped_identifier(); break; } case SV3_1aPpParser::Pound_delay: { enterOuterAlt(_localctx, 16); setState(1044); pound_delay(); break; } case SV3_1aPpParser::Pound_Pound_delay: { enterOuterAlt(_localctx, 17); setState(1045); pound_pound_delay(); break; } case SV3_1aPpParser::Special: { enterOuterAlt(_localctx, 18); setState(1046); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { enterOuterAlt(_localctx, 19); setState(1047); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Macro_argContext ------------------------------------------------------------------ SV3_1aPpParser::Macro_argContext::Macro_argContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Macro_argContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::String() { return getToken(SV3_1aPpParser::String, 0); } SV3_1aPpParser::Paired_parensContext* SV3_1aPpParser::Macro_argContext::paired_parens() { return getRuleContext<SV3_1aPpParser::Paired_parensContext>(0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::EQUAL_OP() { return getToken(SV3_1aPpParser::EQUAL_OP, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::DOUBLE_QUOTE() { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, 0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Macro_argContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::TEXT_CR() { return getToken(SV3_1aPpParser::TEXT_CR, 0); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Macro_argContext::escaped_identifier() { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(0); } SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::Macro_argContext::simple_args_macro_definition_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_args_macro_definition_in_macro_bodyContext>(0); } SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext* SV3_1aPpParser::Macro_argContext::simple_no_args_macro_definition_in_macro_body() { return getRuleContext<SV3_1aPpParser::Simple_no_args_macro_definition_in_macro_bodyContext>(0); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Macro_argContext::comments() { return getRuleContext<SV3_1aPpParser::CommentsContext>(0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Macro_argContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Macro_argContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::Special() { return getToken(SV3_1aPpParser::Special, 0); } tree::TerminalNode* SV3_1aPpParser::Macro_argContext::ANY() { return getToken(SV3_1aPpParser::ANY, 0); } size_t SV3_1aPpParser::Macro_argContext::getRuleIndex() const { return SV3_1aPpParser::RuleMacro_arg; } void SV3_1aPpParser::Macro_argContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterMacro_arg(this); } void SV3_1aPpParser::Macro_argContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitMacro_arg(this); } SV3_1aPpParser::Macro_argContext* SV3_1aPpParser::macro_arg() { Macro_argContext *_localctx = _tracker.createInstance<Macro_argContext>(_ctx, getState()); enterRule(_localctx, 190, SV3_1aPpParser::RuleMacro_arg); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1069); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 71, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(1050); match(SV3_1aPpParser::Simple_identifier); break; } case 2: { enterOuterAlt(_localctx, 2); setState(1051); number(); break; } case 3: { enterOuterAlt(_localctx, 3); setState(1052); match(SV3_1aPpParser::Spaces); break; } case 4: { enterOuterAlt(_localctx, 4); setState(1053); match(SV3_1aPpParser::Fixed_point_number); break; } case 5: { enterOuterAlt(_localctx, 5); setState(1054); match(SV3_1aPpParser::String); break; } case 6: { enterOuterAlt(_localctx, 6); setState(1055); paired_parens(); break; } case 7: { enterOuterAlt(_localctx, 7); setState(1056); match(SV3_1aPpParser::EQUAL_OP); break; } case 8: { enterOuterAlt(_localctx, 8); setState(1057); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case 9: { enterOuterAlt(_localctx, 9); setState(1058); macro_instance(); break; } case 10: { enterOuterAlt(_localctx, 10); setState(1059); match(SV3_1aPpParser::CR); break; } case 11: { enterOuterAlt(_localctx, 11); setState(1060); match(SV3_1aPpParser::TEXT_CR); break; } case 12: { enterOuterAlt(_localctx, 12); setState(1061); escaped_identifier(); break; } case 13: { enterOuterAlt(_localctx, 13); setState(1062); simple_args_macro_definition_in_macro_body(); break; } case 14: { enterOuterAlt(_localctx, 14); setState(1063); simple_no_args_macro_definition_in_macro_body(); break; } case 15: { enterOuterAlt(_localctx, 15); setState(1064); comments(); break; } case 16: { enterOuterAlt(_localctx, 16); setState(1065); pound_delay(); break; } case 17: { enterOuterAlt(_localctx, 17); setState(1066); pound_pound_delay(); break; } case 18: { enterOuterAlt(_localctx, 18); setState(1067); match(SV3_1aPpParser::Special); break; } case 19: { enterOuterAlt(_localctx, 19); setState(1068); match(SV3_1aPpParser::ANY); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Paired_parensContext ------------------------------------------------------------------ SV3_1aPpParser::Paired_parensContext::Paired_parensContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::Simple_identifier() { return getTokens(SV3_1aPpParser::Simple_identifier); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::Simple_identifier(size_t i) { return getToken(SV3_1aPpParser::Simple_identifier, i); } std::vector<SV3_1aPpParser::NumberContext *> SV3_1aPpParser::Paired_parensContext::number() { return getRuleContexts<SV3_1aPpParser::NumberContext>(); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Paired_parensContext::number(size_t i) { return getRuleContext<SV3_1aPpParser::NumberContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::Spaces() { return getTokens(SV3_1aPpParser::Spaces); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::Spaces(size_t i) { return getToken(SV3_1aPpParser::Spaces, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::Fixed_point_number() { return getTokens(SV3_1aPpParser::Fixed_point_number); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::Fixed_point_number(size_t i) { return getToken(SV3_1aPpParser::Fixed_point_number, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::String() { return getTokens(SV3_1aPpParser::String); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::String(size_t i) { return getToken(SV3_1aPpParser::String, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::COMMA() { return getTokens(SV3_1aPpParser::COMMA); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::COMMA(size_t i) { return getToken(SV3_1aPpParser::COMMA, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::EQUAL_OP() { return getTokens(SV3_1aPpParser::EQUAL_OP); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::EQUAL_OP(size_t i) { return getToken(SV3_1aPpParser::EQUAL_OP, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::DOUBLE_QUOTE() { return getTokens(SV3_1aPpParser::DOUBLE_QUOTE); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::DOUBLE_QUOTE(size_t i) { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, i); } std::vector<SV3_1aPpParser::Macro_instanceContext *> SV3_1aPpParser::Paired_parensContext::macro_instance() { return getRuleContexts<SV3_1aPpParser::Macro_instanceContext>(); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Paired_parensContext::macro_instance(size_t i) { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::TEXT_CR() { return getTokens(SV3_1aPpParser::TEXT_CR); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::TEXT_CR(size_t i) { return getToken(SV3_1aPpParser::TEXT_CR, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::CR() { return getTokens(SV3_1aPpParser::CR); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::CR(size_t i) { return getToken(SV3_1aPpParser::CR, i); } std::vector<SV3_1aPpParser::Paired_parensContext *> SV3_1aPpParser::Paired_parensContext::paired_parens() { return getRuleContexts<SV3_1aPpParser::Paired_parensContext>(); } SV3_1aPpParser::Paired_parensContext* SV3_1aPpParser::Paired_parensContext::paired_parens(size_t i) { return getRuleContext<SV3_1aPpParser::Paired_parensContext>(i); } std::vector<SV3_1aPpParser::Escaped_identifierContext *> SV3_1aPpParser::Paired_parensContext::escaped_identifier() { return getRuleContexts<SV3_1aPpParser::Escaped_identifierContext>(); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Paired_parensContext::escaped_identifier(size_t i) { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(i); } std::vector<SV3_1aPpParser::CommentsContext *> SV3_1aPpParser::Paired_parensContext::comments() { return getRuleContexts<SV3_1aPpParser::CommentsContext>(); } SV3_1aPpParser::CommentsContext* SV3_1aPpParser::Paired_parensContext::comments(size_t i) { return getRuleContext<SV3_1aPpParser::CommentsContext>(i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::Special() { return getTokens(SV3_1aPpParser::Special); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::Special(size_t i) { return getToken(SV3_1aPpParser::Special, i); } std::vector<tree::TerminalNode *> SV3_1aPpParser::Paired_parensContext::ANY() { return getTokens(SV3_1aPpParser::ANY); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::ANY(size_t i) { return getToken(SV3_1aPpParser::ANY, i); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::CURLY_OPEN() { return getToken(SV3_1aPpParser::CURLY_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::CURLY_CLOSE() { return getToken(SV3_1aPpParser::CURLY_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::SQUARE_OPEN() { return getToken(SV3_1aPpParser::SQUARE_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Paired_parensContext::SQUARE_CLOSE() { return getToken(SV3_1aPpParser::SQUARE_CLOSE, 0); } size_t SV3_1aPpParser::Paired_parensContext::getRuleIndex() const { return SV3_1aPpParser::RulePaired_parens; } void SV3_1aPpParser::Paired_parensContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterPaired_parens(this); } void SV3_1aPpParser::Paired_parensContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitPaired_parens(this); } SV3_1aPpParser::Paired_parensContext* SV3_1aPpParser::paired_parens() { Paired_parensContext *_localctx = _tracker.createInstance<Paired_parensContext>(_ctx, getState()); enterRule(_localctx, 192, SV3_1aPpParser::RulePaired_parens); size_t _la = 0; #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1138); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::PARENS_OPEN: { enterOuterAlt(_localctx, 1); setState(1071); match(SV3_1aPpParser::PARENS_OPEN); setState(1090); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment))) != 0) || ((((_la - 68) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 68)) & ((1ULL << (SV3_1aPpParser::Macro_identifier - 68)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 68)) | (1ULL << (SV3_1aPpParser::String - 68)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 68)) | (1ULL << (SV3_1aPpParser::Spaces - 68)) | (1ULL << (SV3_1aPpParser::Number - 68)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 68)) | (1ULL << (SV3_1aPpParser::TEXT_CR - 68)) | (1ULL << (SV3_1aPpParser::CR - 68)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 68)) | (1ULL << (SV3_1aPpParser::COMMA - 68)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 68)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 68)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 68)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 68)) | (1ULL << (SV3_1aPpParser::Special - 68)) | (1ULL << (SV3_1aPpParser::ANY - 68)))) != 0)) { setState(1088); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(1072); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { setState(1073); number(); break; } case SV3_1aPpParser::Spaces: { setState(1074); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { setState(1075); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::String: { setState(1076); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::COMMA: { setState(1077); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { setState(1078); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { setState(1079); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(1080); macro_instance(); break; } case SV3_1aPpParser::TEXT_CR: { setState(1081); match(SV3_1aPpParser::TEXT_CR); break; } case SV3_1aPpParser::CR: { setState(1082); match(SV3_1aPpParser::CR); break; } case SV3_1aPpParser::PARENS_OPEN: case SV3_1aPpParser::CURLY_OPEN: case SV3_1aPpParser::SQUARE_OPEN: { setState(1083); paired_parens(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(1084); escaped_identifier(); break; } case SV3_1aPpParser::One_line_comment: case SV3_1aPpParser::Block_comment: { setState(1085); comments(); break; } case SV3_1aPpParser::Special: { setState(1086); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { setState(1087); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } setState(1092); _errHandler->sync(this); _la = _input->LA(1); } setState(1093); match(SV3_1aPpParser::PARENS_CLOSE); break; } case SV3_1aPpParser::CURLY_OPEN: { enterOuterAlt(_localctx, 2); setState(1094); match(SV3_1aPpParser::CURLY_OPEN); setState(1112); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment))) != 0) || ((((_la - 68) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 68)) & ((1ULL << (SV3_1aPpParser::Macro_identifier - 68)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 68)) | (1ULL << (SV3_1aPpParser::String - 68)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 68)) | (1ULL << (SV3_1aPpParser::Spaces - 68)) | (1ULL << (SV3_1aPpParser::Number - 68)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 68)) | (1ULL << (SV3_1aPpParser::CR - 68)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 68)) | (1ULL << (SV3_1aPpParser::COMMA - 68)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 68)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 68)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 68)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 68)) | (1ULL << (SV3_1aPpParser::Special - 68)) | (1ULL << (SV3_1aPpParser::ANY - 68)))) != 0)) { setState(1110); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(1095); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { setState(1096); number(); break; } case SV3_1aPpParser::Spaces: { setState(1097); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { setState(1098); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::String: { setState(1099); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::COMMA: { setState(1100); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { setState(1101); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { setState(1102); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(1103); macro_instance(); break; } case SV3_1aPpParser::CR: { setState(1104); match(SV3_1aPpParser::CR); break; } case SV3_1aPpParser::PARENS_OPEN: case SV3_1aPpParser::CURLY_OPEN: case SV3_1aPpParser::SQUARE_OPEN: { setState(1105); paired_parens(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(1106); escaped_identifier(); break; } case SV3_1aPpParser::One_line_comment: case SV3_1aPpParser::Block_comment: { setState(1107); comments(); break; } case SV3_1aPpParser::Special: { setState(1108); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { setState(1109); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } setState(1114); _errHandler->sync(this); _la = _input->LA(1); } setState(1115); match(SV3_1aPpParser::CURLY_CLOSE); break; } case SV3_1aPpParser::SQUARE_OPEN: { enterOuterAlt(_localctx, 3); setState(1116); match(SV3_1aPpParser::SQUARE_OPEN); setState(1134); _errHandler->sync(this); _la = _input->LA(1); while ((((_la & ~ 0x3fULL) == 0) && ((1ULL << _la) & ((1ULL << SV3_1aPpParser::Escaped_identifier) | (1ULL << SV3_1aPpParser::One_line_comment) | (1ULL << SV3_1aPpParser::Block_comment))) != 0) || ((((_la - 68) & ~ 0x3fULL) == 0) && ((1ULL << (_la - 68)) & ((1ULL << (SV3_1aPpParser::Macro_identifier - 68)) | (1ULL << (SV3_1aPpParser::Macro_Escaped_identifier - 68)) | (1ULL << (SV3_1aPpParser::String - 68)) | (1ULL << (SV3_1aPpParser::Simple_identifier - 68)) | (1ULL << (SV3_1aPpParser::Spaces - 68)) | (1ULL << (SV3_1aPpParser::Number - 68)) | (1ULL << (SV3_1aPpParser::Fixed_point_number - 68)) | (1ULL << (SV3_1aPpParser::CR - 68)) | (1ULL << (SV3_1aPpParser::PARENS_OPEN - 68)) | (1ULL << (SV3_1aPpParser::COMMA - 68)) | (1ULL << (SV3_1aPpParser::EQUAL_OP - 68)) | (1ULL << (SV3_1aPpParser::DOUBLE_QUOTE - 68)) | (1ULL << (SV3_1aPpParser::CURLY_OPEN - 68)) | (1ULL << (SV3_1aPpParser::SQUARE_OPEN - 68)) | (1ULL << (SV3_1aPpParser::Special - 68)) | (1ULL << (SV3_1aPpParser::ANY - 68)))) != 0)) { setState(1132); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { setState(1117); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { setState(1118); number(); break; } case SV3_1aPpParser::Spaces: { setState(1119); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { setState(1120); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::String: { setState(1121); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::COMMA: { setState(1122); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { setState(1123); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { setState(1124); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::Macro_identifier: case SV3_1aPpParser::Macro_Escaped_identifier: { setState(1125); macro_instance(); break; } case SV3_1aPpParser::CR: { setState(1126); match(SV3_1aPpParser::CR); break; } case SV3_1aPpParser::PARENS_OPEN: case SV3_1aPpParser::CURLY_OPEN: case SV3_1aPpParser::SQUARE_OPEN: { setState(1127); paired_parens(); break; } case SV3_1aPpParser::Escaped_identifier: { setState(1128); escaped_identifier(); break; } case SV3_1aPpParser::One_line_comment: case SV3_1aPpParser::Block_comment: { setState(1129); comments(); break; } case SV3_1aPpParser::Special: { setState(1130); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { setState(1131); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } setState(1136); _errHandler->sync(this); _la = _input->LA(1); } setState(1137); match(SV3_1aPpParser::SQUARE_CLOSE); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Text_blobContext ------------------------------------------------------------------ SV3_1aPpParser::Text_blobContext::Text_blobContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Text_blobContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::CR() { return getToken(SV3_1aPpParser::CR, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::ESCAPED_CR() { return getToken(SV3_1aPpParser::ESCAPED_CR, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::String() { return getToken(SV3_1aPpParser::String, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::COMMA() { return getToken(SV3_1aPpParser::COMMA, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::EQUAL_OP() { return getToken(SV3_1aPpParser::EQUAL_OP, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::DOUBLE_QUOTE() { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::CURLY_OPEN() { return getToken(SV3_1aPpParser::CURLY_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::CURLY_CLOSE() { return getToken(SV3_1aPpParser::CURLY_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::SQUARE_OPEN() { return getToken(SV3_1aPpParser::SQUARE_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::SQUARE_CLOSE() { return getToken(SV3_1aPpParser::SQUARE_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TICK_TICK() { return getToken(SV3_1aPpParser::TICK_TICK, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TICK_VARIABLE() { return getToken(SV3_1aPpParser::TICK_VARIABLE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TIMESCALE() { return getToken(SV3_1aPpParser::TIMESCALE, 0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::Text_blobContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::Text_blobContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TICK_QUOTE() { return getToken(SV3_1aPpParser::TICK_QUOTE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TICK_BACKSLASH_TICK_QUOTE() { return getToken(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::TEXT_CR() { return getToken(SV3_1aPpParser::TEXT_CR, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::Special() { return getToken(SV3_1aPpParser::Special, 0); } tree::TerminalNode* SV3_1aPpParser::Text_blobContext::ANY() { return getToken(SV3_1aPpParser::ANY, 0); } size_t SV3_1aPpParser::Text_blobContext::getRuleIndex() const { return SV3_1aPpParser::RuleText_blob; } void SV3_1aPpParser::Text_blobContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterText_blob(this); } void SV3_1aPpParser::Text_blobContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitText_blob(this); } SV3_1aPpParser::Text_blobContext* SV3_1aPpParser::text_blob() { Text_blobContext *_localctx = _tracker.createInstance<Text_blobContext>(_ctx, getState()); enterRule(_localctx, 194, SV3_1aPpParser::RuleText_blob); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1166); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { enterOuterAlt(_localctx, 1); setState(1140); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { enterOuterAlt(_localctx, 2); setState(1141); number(); break; } case SV3_1aPpParser::CR: { enterOuterAlt(_localctx, 3); setState(1142); match(SV3_1aPpParser::CR); break; } case SV3_1aPpParser::Spaces: { enterOuterAlt(_localctx, 4); setState(1143); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { enterOuterAlt(_localctx, 5); setState(1144); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::ESCAPED_CR: { enterOuterAlt(_localctx, 6); setState(1145); match(SV3_1aPpParser::ESCAPED_CR); break; } case SV3_1aPpParser::String: { enterOuterAlt(_localctx, 7); setState(1146); match(SV3_1aPpParser::String); break; } case SV3_1aPpParser::PARENS_OPEN: { enterOuterAlt(_localctx, 8); setState(1147); match(SV3_1aPpParser::PARENS_OPEN); break; } case SV3_1aPpParser::PARENS_CLOSE: { enterOuterAlt(_localctx, 9); setState(1148); match(SV3_1aPpParser::PARENS_CLOSE); break; } case SV3_1aPpParser::COMMA: { enterOuterAlt(_localctx, 10); setState(1149); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { enterOuterAlt(_localctx, 11); setState(1150); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { enterOuterAlt(_localctx, 12); setState(1151); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::CURLY_OPEN: { enterOuterAlt(_localctx, 13); setState(1152); match(SV3_1aPpParser::CURLY_OPEN); break; } case SV3_1aPpParser::CURLY_CLOSE: { enterOuterAlt(_localctx, 14); setState(1153); match(SV3_1aPpParser::CURLY_CLOSE); break; } case SV3_1aPpParser::SQUARE_OPEN: { enterOuterAlt(_localctx, 15); setState(1154); match(SV3_1aPpParser::SQUARE_OPEN); break; } case SV3_1aPpParser::SQUARE_CLOSE: { enterOuterAlt(_localctx, 16); setState(1155); match(SV3_1aPpParser::SQUARE_CLOSE); break; } case SV3_1aPpParser::TICK_TICK: { enterOuterAlt(_localctx, 17); setState(1156); match(SV3_1aPpParser::TICK_TICK); break; } case SV3_1aPpParser::TICK_VARIABLE: { enterOuterAlt(_localctx, 18); setState(1157); match(SV3_1aPpParser::TICK_VARIABLE); break; } case SV3_1aPpParser::TIMESCALE: { enterOuterAlt(_localctx, 19); setState(1158); match(SV3_1aPpParser::TIMESCALE); break; } case SV3_1aPpParser::Pound_delay: { enterOuterAlt(_localctx, 20); setState(1159); pound_delay(); break; } case SV3_1aPpParser::Pound_Pound_delay: { enterOuterAlt(_localctx, 21); setState(1160); pound_pound_delay(); break; } case SV3_1aPpParser::TICK_QUOTE: { enterOuterAlt(_localctx, 22); setState(1161); match(SV3_1aPpParser::TICK_QUOTE); break; } case SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE: { enterOuterAlt(_localctx, 23); setState(1162); match(SV3_1aPpParser::TICK_BACKSLASH_TICK_QUOTE); break; } case SV3_1aPpParser::TEXT_CR: { enterOuterAlt(_localctx, 24); setState(1163); match(SV3_1aPpParser::TEXT_CR); break; } case SV3_1aPpParser::Special: { enterOuterAlt(_localctx, 25); setState(1164); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { enterOuterAlt(_localctx, 26); setState(1165); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- StringContext ------------------------------------------------------------------ SV3_1aPpParser::StringContext::StringContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::StringContext::String() { return getToken(SV3_1aPpParser::String, 0); } size_t SV3_1aPpParser::StringContext::getRuleIndex() const { return SV3_1aPpParser::RuleString; } void SV3_1aPpParser::StringContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterString(this); } void SV3_1aPpParser::StringContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitString(this); } SV3_1aPpParser::StringContext* SV3_1aPpParser::string() { StringContext *_localctx = _tracker.createInstance<StringContext>(_ctx, getState()); enterRule(_localctx, 196, SV3_1aPpParser::RuleString); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { enterOuterAlt(_localctx, 1); setState(1168); match(SV3_1aPpParser::String); } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- Default_valueContext ------------------------------------------------------------------ SV3_1aPpParser::Default_valueContext::Default_valueContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::Default_valueContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::String() { return getToken(SV3_1aPpParser::String, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::CURLY_OPEN() { return getToken(SV3_1aPpParser::CURLY_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::CURLY_CLOSE() { return getToken(SV3_1aPpParser::CURLY_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::SQUARE_OPEN() { return getToken(SV3_1aPpParser::SQUARE_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::SQUARE_CLOSE() { return getToken(SV3_1aPpParser::SQUARE_CLOSE, 0); } SV3_1aPpParser::Paired_parensContext* SV3_1aPpParser::Default_valueContext::paired_parens() { return getRuleContext<SV3_1aPpParser::Paired_parensContext>(0); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::Default_valueContext::escaped_identifier() { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(0); } SV3_1aPpParser::Macro_instanceContext* SV3_1aPpParser::Default_valueContext::macro_instance() { return getRuleContext<SV3_1aPpParser::Macro_instanceContext>(0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::Special() { return getToken(SV3_1aPpParser::Special, 0); } tree::TerminalNode* SV3_1aPpParser::Default_valueContext::ANY() { return getToken(SV3_1aPpParser::ANY, 0); } size_t SV3_1aPpParser::Default_valueContext::getRuleIndex() const { return SV3_1aPpParser::RuleDefault_value; } void SV3_1aPpParser::Default_valueContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterDefault_value(this); } void SV3_1aPpParser::Default_valueContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitDefault_value(this); } SV3_1aPpParser::Default_valueContext* SV3_1aPpParser::default_value() { Default_valueContext *_localctx = _tracker.createInstance<Default_valueContext>(_ctx, getState()); enterRule(_localctx, 198, SV3_1aPpParser::RuleDefault_value); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1184); _errHandler->sync(this); switch (getInterpreter<atn::ParserATNSimulator>()->adaptivePredict(_input, 80, _ctx)) { case 1: { enterOuterAlt(_localctx, 1); setState(1170); match(SV3_1aPpParser::Simple_identifier); break; } case 2: { enterOuterAlt(_localctx, 2); setState(1171); number(); break; } case 3: { enterOuterAlt(_localctx, 3); setState(1172); match(SV3_1aPpParser::Spaces); break; } case 4: { enterOuterAlt(_localctx, 4); setState(1173); match(SV3_1aPpParser::Fixed_point_number); break; } case 5: { enterOuterAlt(_localctx, 5); setState(1174); match(SV3_1aPpParser::String); break; } case 6: { enterOuterAlt(_localctx, 6); setState(1175); match(SV3_1aPpParser::CURLY_OPEN); break; } case 7: { enterOuterAlt(_localctx, 7); setState(1176); match(SV3_1aPpParser::CURLY_CLOSE); break; } case 8: { enterOuterAlt(_localctx, 8); setState(1177); match(SV3_1aPpParser::SQUARE_OPEN); break; } case 9: { enterOuterAlt(_localctx, 9); setState(1178); match(SV3_1aPpParser::SQUARE_CLOSE); break; } case 10: { enterOuterAlt(_localctx, 10); setState(1179); paired_parens(); break; } case 11: { enterOuterAlt(_localctx, 11); setState(1180); escaped_identifier(); break; } case 12: { enterOuterAlt(_localctx, 12); setState(1181); macro_instance(); break; } case 13: { enterOuterAlt(_localctx, 13); setState(1182); match(SV3_1aPpParser::Special); break; } case 14: { enterOuterAlt(_localctx, 14); setState(1183); match(SV3_1aPpParser::ANY); break; } default: break; } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } //----------------- String_blobContext ------------------------------------------------------------------ SV3_1aPpParser::String_blobContext::String_blobContext(ParserRuleContext *parent, size_t invokingState) : ParserRuleContext(parent, invokingState) { } tree::TerminalNode* SV3_1aPpParser::String_blobContext::Simple_identifier() { return getToken(SV3_1aPpParser::Simple_identifier, 0); } SV3_1aPpParser::NumberContext* SV3_1aPpParser::String_blobContext::number() { return getRuleContext<SV3_1aPpParser::NumberContext>(0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::Spaces() { return getToken(SV3_1aPpParser::Spaces, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::Fixed_point_number() { return getToken(SV3_1aPpParser::Fixed_point_number, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::ESCAPED_CR() { return getToken(SV3_1aPpParser::ESCAPED_CR, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::PARENS_OPEN() { return getToken(SV3_1aPpParser::PARENS_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::PARENS_CLOSE() { return getToken(SV3_1aPpParser::PARENS_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::COMMA() { return getToken(SV3_1aPpParser::COMMA, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::EQUAL_OP() { return getToken(SV3_1aPpParser::EQUAL_OP, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::DOUBLE_QUOTE() { return getToken(SV3_1aPpParser::DOUBLE_QUOTE, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::CURLY_OPEN() { return getToken(SV3_1aPpParser::CURLY_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::CURLY_CLOSE() { return getToken(SV3_1aPpParser::CURLY_CLOSE, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::SQUARE_OPEN() { return getToken(SV3_1aPpParser::SQUARE_OPEN, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::SQUARE_CLOSE() { return getToken(SV3_1aPpParser::SQUARE_CLOSE, 0); } SV3_1aPpParser::Escaped_identifierContext* SV3_1aPpParser::String_blobContext::escaped_identifier() { return getRuleContext<SV3_1aPpParser::Escaped_identifierContext>(0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::TIMESCALE() { return getToken(SV3_1aPpParser::TIMESCALE, 0); } SV3_1aPpParser::Pound_delayContext* SV3_1aPpParser::String_blobContext::pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_delayContext>(0); } SV3_1aPpParser::Pound_pound_delayContext* SV3_1aPpParser::String_blobContext::pound_pound_delay() { return getRuleContext<SV3_1aPpParser::Pound_pound_delayContext>(0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::TEXT_CR() { return getToken(SV3_1aPpParser::TEXT_CR, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::Special() { return getToken(SV3_1aPpParser::Special, 0); } tree::TerminalNode* SV3_1aPpParser::String_blobContext::ANY() { return getToken(SV3_1aPpParser::ANY, 0); } size_t SV3_1aPpParser::String_blobContext::getRuleIndex() const { return SV3_1aPpParser::RuleString_blob; } void SV3_1aPpParser::String_blobContext::enterRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->enterString_blob(this); } void SV3_1aPpParser::String_blobContext::exitRule(tree::ParseTreeListener *listener) { auto parserListener = parsetreelistener_cast<SV3_1aPpParserListener>(listener); if (parserListener != nullptr) parserListener->exitString_blob(this); } SV3_1aPpParser::String_blobContext* SV3_1aPpParser::string_blob() { String_blobContext *_localctx = _tracker.createInstance<String_blobContext>(_ctx, getState()); enterRule(_localctx, 200, SV3_1aPpParser::RuleString_blob); #if __cplusplus > 201703L auto onExit = finally([=, this] { #else auto onExit = finally([=] { #endif exitRule(); }); try { setState(1207); _errHandler->sync(this); switch (_input->LA(1)) { case SV3_1aPpParser::Simple_identifier: { enterOuterAlt(_localctx, 1); setState(1186); match(SV3_1aPpParser::Simple_identifier); break; } case SV3_1aPpParser::Number: { enterOuterAlt(_localctx, 2); setState(1187); number(); break; } case SV3_1aPpParser::Spaces: { enterOuterAlt(_localctx, 3); setState(1188); match(SV3_1aPpParser::Spaces); break; } case SV3_1aPpParser::Fixed_point_number: { enterOuterAlt(_localctx, 4); setState(1189); match(SV3_1aPpParser::Fixed_point_number); break; } case SV3_1aPpParser::ESCAPED_CR: { enterOuterAlt(_localctx, 5); setState(1190); match(SV3_1aPpParser::ESCAPED_CR); break; } case SV3_1aPpParser::PARENS_OPEN: { enterOuterAlt(_localctx, 6); setState(1191); match(SV3_1aPpParser::PARENS_OPEN); break; } case SV3_1aPpParser::PARENS_CLOSE: { enterOuterAlt(_localctx, 7); setState(1192); match(SV3_1aPpParser::PARENS_CLOSE); break; } case SV3_1aPpParser::COMMA: { enterOuterAlt(_localctx, 8); setState(1193); match(SV3_1aPpParser::COMMA); break; } case SV3_1aPpParser::EQUAL_OP: { enterOuterAlt(_localctx, 9); setState(1194); match(SV3_1aPpParser::EQUAL_OP); break; } case SV3_1aPpParser::DOUBLE_QUOTE: { enterOuterAlt(_localctx, 10); setState(1195); match(SV3_1aPpParser::DOUBLE_QUOTE); break; } case SV3_1aPpParser::CURLY_OPEN: { enterOuterAlt(_localctx, 11); setState(1196); match(SV3_1aPpParser::CURLY_OPEN); break; } case SV3_1aPpParser::CURLY_CLOSE: { enterOuterAlt(_localctx, 12); setState(1197); match(SV3_1aPpParser::CURLY_CLOSE); break; } case SV3_1aPpParser::SQUARE_OPEN: { enterOuterAlt(_localctx, 13); setState(1198); match(SV3_1aPpParser::SQUARE_OPEN); break; } case SV3_1aPpParser::SQUARE_CLOSE: { enterOuterAlt(_localctx, 14); setState(1199); match(SV3_1aPpParser::SQUARE_CLOSE); break; } case SV3_1aPpParser::Escaped_identifier: { enterOuterAlt(_localctx, 15); setState(1200); escaped_identifier(); break; } case SV3_1aPpParser::TIMESCALE: { enterOuterAlt(_localctx, 16); setState(1201); match(SV3_1aPpParser::TIMESCALE); break; } case SV3_1aPpParser::Pound_delay: { enterOuterAlt(_localctx, 17); setState(1202); pound_delay(); break; } case SV3_1aPpParser::Pound_Pound_delay: { enterOuterAlt(_localctx, 18); setState(1203); pound_pound_delay(); break; } case SV3_1aPpParser::TEXT_CR: { enterOuterAlt(_localctx, 19); setState(1204); match(SV3_1aPpParser::TEXT_CR); break; } case SV3_1aPpParser::Special: { enterOuterAlt(_localctx, 20); setState(1205); match(SV3_1aPpParser::Special); break; } case SV3_1aPpParser::ANY: { enterOuterAlt(_localctx, 21); setState(1206); match(SV3_1aPpParser::ANY); break; } default: throw NoViableAltException(this); } } catch (RecognitionException &e) { _errHandler->reportError(this, e); _localctx->exception = std::current_exception(); _errHandler->recover(this, _localctx->exception); } return _localctx; } // Static vars and initialization. std::vector<dfa::DFA> SV3_1aPpParser::_decisionToDFA; atn::PredictionContextCache SV3_1aPpParser::_sharedContextCache; // We own the ATN which in turn owns the ATN states. atn::ATN SV3_1aPpParser::_atn; std::vector<uint16_t> SV3_1aPpParser::_serializedATN; std::vector<std::string> SV3_1aPpParser::_ruleNames = { "top_level_rule", "source_text", "null_rule", "description", "escaped_identifier", "macro_instance", "unterminated_string", "macro_actual_args", "comments", "number", "pound_delay", "pound_pound_delay", "macro_definition", "include_directive", "line_directive", "default_nettype_directive", "sv_file_directive", "sv_line_directive", "timescale_directive", "undef_directive", "ifdef_directive", "ifdef_directive_in_macro_body", "ifndef_directive", "ifndef_directive_in_macro_body", "elsif_directive", "elsif_directive_in_macro_body", "elseif_directive", "elseif_directive_in_macro_body", "else_directive", "endif_directive", "resetall_directive", "begin_keywords_directive", "end_keywords_directive", "pragma_directive", "celldefine_directive", "endcelldefine_directive", "protect_directive", "endprotect_directive", "protected_directive", "endprotected_directive", "expand_vectornets_directive", "noexpand_vectornets_directive", "autoexpand_vectornets_directive", "uselib_directive", "disable_portfaults_directive", "enable_portfaults_directive", "nosuppress_faults_directive", "suppress_faults_directive", "signed_directive", "unsigned_directive", "remove_gatename_directive", "noremove_gatenames_directive", "remove_netname_directive", "noremove_netnames_directive", "accelerate_directive", "noaccelerate_directive", "default_trireg_strenght_directive", "default_decay_time_directive", "unconnected_drive_directive", "nounconnected_drive_directive", "delay_mode_distributed_directive", "delay_mode_path_directive", "delay_mode_unit_directive", "delay_mode_zero_directive", "undefineall_directive", "module", "endmodule", "sv_interface", "endinterface", "program", "endprogram", "primitive", "endprimitive", "sv_package", "endpackage", "checker", "endchecker", "config", "endconfig", "define_directive", "multiline_no_args_macro_definition", "multiline_args_macro_definition", "simple_no_args_macro_definition", "simple_args_macro_definition", "identifier_in_macro_body", "simple_no_args_macro_definition_in_macro_body", "simple_args_macro_definition_in_macro_body", "directive_in_macro", "macro_arguments", "escaped_macro_definition_body", "escaped_macro_definition_body_alt1", "escaped_macro_definition_body_alt2", "simple_macro_definition_body", "simple_macro_definition_body_in_macro_body", "pragma_expression", "macro_arg", "paired_parens", "text_blob", "string", "default_value", "string_blob" }; std::vector<std::string> SV3_1aPpParser::_literalNames = { "", "", "", "", "", "'`define'", "'`celldefine'", "'`endcelldefine'", "'`default_nettype'", "'`undef'", "'`ifdef'", "'`ifndef'", "'`else'", "'`elsif'", "'`elseif'", "'`endif'", "'`include'", "'`pragma'", "'`begin_keywords'", "'`end_keywords'", "'`resetall'", "'`timescale'", "'`unconnected_drive'", "'`nounconnected_drive'", "'`line'", "'`default_decay_time'", "'`default_trireg_strength'", "'`delay_mode_distributed'", "'`delay_mode_path'", "'`delay_mode_unit'", "'`delay_mode_zero'", "'`undefineall'", "'`accelerate'", "'`noaccelerate'", "'`protect'", "'`uselib'", "'`disable_portfaults'", "'`enable_portfaults'", "'`nosuppress_faults'", "'`suppress_faults'", "'`signed'", "'`unsigned'", "'`endprotect'", "'`protected'", "'`endprotected'", "'`expand_vectornets'", "'`noexpand_vectornets'", "'`autoexpand_vectornets'", "'`remove_gatename'", "'`noremove_gatenames'", "'`remove_netname'", "'`noremove_netnames'", "'`__FILE__'", "'`__LINE__'", "'module'", "'endmodule'", "'interface'", "'endinterface'", "'program'", "'endprogram'", "'primivite'", "'endprimitive'", "'package'", "'endpackage'", "'checker'", "'endchecker'", "'config'", "'endconfig'", "", "", "", "", "", "", "", "", "", "", "", "", "", "'`\"'", "'`\\`\"'", "'``'", "'('", "')'", "','", "'='", "'\"'", "'{'", "'}'", "'['", "']'" }; std::vector<std::string> SV3_1aPpParser::_symbolicNames = { "", "Escaped_identifier", "One_line_comment", "Block_comment", "TICK_VARIABLE", "TICK_DEFINE", "TICK_CELLDEFINE", "TICK_ENDCELLDEFINE", "TICK_DEFAULT_NETTYPE", "TICK_UNDEF", "TICK_IFDEF", "TICK_IFNDEF", "TICK_ELSE", "TICK_ELSIF", "TICK_ELSEIF", "TICK_ENDIF", "TICK_INCLUDE", "TICK_PRAGMA", "TICK_BEGIN_KEYWORDS", "TICK_END_KEYWORDS", "TICK_RESETALL", "TICK_TIMESCALE", "TICK_UNCONNECTED_DRIVE", "TICK_NOUNCONNECTED_DRIVE", "TICK_LINE", "TICK_DEFAULT_DECAY_TIME", "TICK_DEFAULT_TRIREG_STRENGTH", "TICK_DELAY_MODE_DISTRIBUTED", "TICK_DELAY_MODE_PATH", "TICK_DELAY_MODE_UNIT", "TICK_DELAY_MODE_ZERO", "TICK_UNDEFINEALL", "TICK_ACCELERATE", "TICK_NOACCELERATE", "TICK_PROTECT", "TICK_USELIB", "TICK_DISABLE_PORTFAULTS", "TICK_ENABLE_PORTFAULTS", "TICK_NOSUPPRESS_FAULTS", "TICK_SUPPRESS_FAULTS", "TICK_SIGNED", "TICK_UNSIGNED", "TICK_ENDPROTECT", "TICK_PROTECTED", "TICK_ENDPROTECTED", "TICK_EXPAND_VECTORNETS", "TICK_NOEXPAND_VECTORNETS", "TICK_AUTOEXPAND_VECTORNETS", "TICK_REMOVE_GATENAME", "TICK_NOREMOVE_GATENAMES", "TICK_REMOVE_NETNAME", "TICK_NOREMOVE_NETNAMES", "TICK_FILE__", "TICK_LINE__", "MODULE", "ENDMODULE", "INTERFACE", "ENDINTERFACE", "PROGRAM", "ENDPROGRAM", "PRIMITIVE", "ENDPRIMITIVE", "PACKAGE", "ENDPACKAGE", "CHECKER", "ENDCHECKER", "CONFIG", "ENDCONFIG", "Macro_identifier", "Macro_Escaped_identifier", "String", "Simple_identifier", "Spaces", "Pound_Pound_delay", "Pound_delay", "TIMESCALE", "Number", "Fixed_point_number", "TEXT_CR", "ESCAPED_CR", "CR", "TICK_QUOTE", "TICK_BACKSLASH_TICK_QUOTE", "TICK_TICK", "PARENS_OPEN", "PARENS_CLOSE", "COMMA", "EQUAL_OP", "DOUBLE_QUOTE", "CURLY_OPEN", "CURLY_CLOSE", "SQUARE_OPEN", "SQUARE_CLOSE", "Special", "ANY" }; dfa::Vocabulary SV3_1aPpParser::_vocabulary(_literalNames, _symbolicNames); std::vector<std::string> SV3_1aPpParser::_tokenNames; SV3_1aPpParser::Initializer::Initializer() { for (size_t i = 0; i < _symbolicNames.size(); ++i) { std::string name = _vocabulary.getLiteralName(i); if (name.empty()) { name = _vocabulary.getSymbolicName(i); } if (name.empty()) { _tokenNames.push_back("<INVALID>"); } else { _tokenNames.push_back(name); } } static const uint16_t serializedATNSegment0[] = { 0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964, 0x3, 0x60, 0x4bc, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, 0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4, 0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, 0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4, 0xe, 0x9, 0xe, 0x4, 0xf, 0x9, 0xf, 0x4, 0x10, 0x9, 0x10, 0x4, 0x11, 0x9, 0x11, 0x4, 0x12, 0x9, 0x12, 0x4, 0x13, 0x9, 0x13, 0x4, 0x14, 0x9, 0x14, 0x4, 0x15, 0x9, 0x15, 0x4, 0x16, 0x9, 0x16, 0x4, 0x17, 0x9, 0x17, 0x4, 0x18, 0x9, 0x18, 0x4, 0x19, 0x9, 0x19, 0x4, 0x1a, 0x9, 0x1a, 0x4, 0x1b, 0x9, 0x1b, 0x4, 0x1c, 0x9, 0x1c, 0x4, 0x1d, 0x9, 0x1d, 0x4, 0x1e, 0x9, 0x1e, 0x4, 0x1f, 0x9, 0x1f, 0x4, 0x20, 0x9, 0x20, 0x4, 0x21, 0x9, 0x21, 0x4, 0x22, 0x9, 0x22, 0x4, 0x23, 0x9, 0x23, 0x4, 0x24, 0x9, 0x24, 0x4, 0x25, 0x9, 0x25, 0x4, 0x26, 0x9, 0x26, 0x4, 0x27, 0x9, 0x27, 0x4, 0x28, 0x9, 0x28, 0x4, 0x29, 0x9, 0x29, 0x4, 0x2a, 0x9, 0x2a, 0x4, 0x2b, 0x9, 0x2b, 0x4, 0x2c, 0x9, 0x2c, 0x4, 0x2d, 0x9, 0x2d, 0x4, 0x2e, 0x9, 0x2e, 0x4, 0x2f, 0x9, 0x2f, 0x4, 0x30, 0x9, 0x30, 0x4, 0x31, 0x9, 0x31, 0x4, 0x32, 0x9, 0x32, 0x4, 0x33, 0x9, 0x33, 0x4, 0x34, 0x9, 0x34, 0x4, 0x35, 0x9, 0x35, 0x4, 0x36, 0x9, 0x36, 0x4, 0x37, 0x9, 0x37, 0x4, 0x38, 0x9, 0x38, 0x4, 0x39, 0x9, 0x39, 0x4, 0x3a, 0x9, 0x3a, 0x4, 0x3b, 0x9, 0x3b, 0x4, 0x3c, 0x9, 0x3c, 0x4, 0x3d, 0x9, 0x3d, 0x4, 0x3e, 0x9, 0x3e, 0x4, 0x3f, 0x9, 0x3f, 0x4, 0x40, 0x9, 0x40, 0x4, 0x41, 0x9, 0x41, 0x4, 0x42, 0x9, 0x42, 0x4, 0x43, 0x9, 0x43, 0x4, 0x44, 0x9, 0x44, 0x4, 0x45, 0x9, 0x45, 0x4, 0x46, 0x9, 0x46, 0x4, 0x47, 0x9, 0x47, 0x4, 0x48, 0x9, 0x48, 0x4, 0x49, 0x9, 0x49, 0x4, 0x4a, 0x9, 0x4a, 0x4, 0x4b, 0x9, 0x4b, 0x4, 0x4c, 0x9, 0x4c, 0x4, 0x4d, 0x9, 0x4d, 0x4, 0x4e, 0x9, 0x4e, 0x4, 0x4f, 0x9, 0x4f, 0x4, 0x50, 0x9, 0x50, 0x4, 0x51, 0x9, 0x51, 0x4, 0x52, 0x9, 0x52, 0x4, 0x53, 0x9, 0x53, 0x4, 0x54, 0x9, 0x54, 0x4, 0x55, 0x9, 0x55, 0x4, 0x56, 0x9, 0x56, 0x4, 0x57, 0x9, 0x57, 0x4, 0x58, 0x9, 0x58, 0x4, 0x59, 0x9, 0x59, 0x4, 0x5a, 0x9, 0x5a, 0x4, 0x5b, 0x9, 0x5b, 0x4, 0x5c, 0x9, 0x5c, 0x4, 0x5d, 0x9, 0x5d, 0x4, 0x5e, 0x9, 0x5e, 0x4, 0x5f, 0x9, 0x5f, 0x4, 0x60, 0x9, 0x60, 0x4, 0x61, 0x9, 0x61, 0x4, 0x62, 0x9, 0x62, 0x4, 0x63, 0x9, 0x63, 0x4, 0x64, 0x9, 0x64, 0x4, 0x65, 0x9, 0x65, 0x4, 0x66, 0x9, 0x66, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x3, 0x7, 0x3, 0xd2, 0xa, 0x3, 0xc, 0x3, 0xe, 0x3, 0xd5, 0xb, 0x3, 0x3, 0x4, 0x3, 0x4, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x5, 0x5, 0x121, 0xa, 0x5, 0x3, 0x6, 0x3, 0x6, 0x3, 0x7, 0x3, 0x7, 0x7, 0x7, 0x127, 0xa, 0x7, 0xc, 0x7, 0xe, 0x7, 0x12a, 0xb, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x3, 0x7, 0x5, 0x7, 0x131, 0xa, 0x7, 0x3, 0x8, 0x3, 0x8, 0x7, 0x8, 0x135, 0xa, 0x8, 0xc, 0x8, 0xe, 0x8, 0x138, 0xb, 0x8, 0x3, 0x8, 0x3, 0x8, 0x3, 0x9, 0x7, 0x9, 0x13d, 0xa, 0x9, 0xc, 0x9, 0xe, 0x9, 0x140, 0xb, 0x9, 0x3, 0x9, 0x3, 0x9, 0x7, 0x9, 0x144, 0xa, 0x9, 0xc, 0x9, 0xe, 0x9, 0x147, 0xb, 0x9, 0x7, 0x9, 0x149, 0xa, 0x9, 0xc, 0x9, 0xe, 0x9, 0x14c, 0xb, 0x9, 0x3, 0xa, 0x3, 0xa, 0x3, 0xb, 0x3, 0xb, 0x3, 0xc, 0x3, 0xc, 0x3, 0xd, 0x3, 0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x3, 0xe, 0x5, 0xe, 0x15b, 0xa, 0xe, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x3, 0xf, 0x5, 0xf, 0x163, 0xa, 0xf, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x10, 0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3, 0x12, 0x3, 0x12, 0x3, 0x13, 0x3, 0x13, 0x3, 0x14, 0x3, 0x14, 0x3, 0x14, 0x3, 0x15, 0x3, 0x15, 0x3, 0x15, 0x3, 0x15, 0x3, 0x15, 0x5, 0x15, 0x17c, 0xa, 0x15, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x3, 0x16, 0x5, 0x16, 0x183, 0xa, 0x16, 0x3, 0x17, 0x3, 0x17, 0x3, 0x17, 0x3, 0x17, 0x3, 0x17, 0x5, 0x17, 0x18a, 0xa, 0x17, 0x3, 0x18, 0x3, 0x18, 0x3, 0x18, 0x3, 0x18, 0x3, 0x18, 0x5, 0x18, 0x191, 0xa, 0x18, 0x3, 0x19, 0x3, 0x19, 0x3, 0x19, 0x3, 0x19, 0x3, 0x19, 0x5, 0x19, 0x198, 0xa, 0x19, 0x3, 0x1a, 0x3, 0x1a, 0x3, 0x1a, 0x3, 0x1a, 0x3, 0x1a, 0x5, 0x1a, 0x19f, 0xa, 0x1a, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1b, 0x5, 0x1b, 0x1a6, 0xa, 0x1b, 0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1c, 0x5, 0x1c, 0x1ad, 0xa, 0x1c, 0x3, 0x1d, 0x3, 0x1d, 0x3, 0x1d, 0x3, 0x1d, 0x3, 0x1d, 0x5, 0x1d, 0x1b4, 0xa, 0x1d, 0x3, 0x1e, 0x3, 0x1e, 0x3, 0x1f, 0x3, 0x1f, 0x7, 0x1f, 0x1ba, 0xa, 0x1f, 0xc, 0x1f, 0xe, 0x1f, 0x1bd, 0xb, 0x1f, 0x3, 0x1f, 0x3, 0x1f, 0x5, 0x1f, 0x1c1, 0xa, 0x1f, 0x3, 0x20, 0x3, 0x20, 0x3, 0x21, 0x3, 0x21, 0x3, 0x21, 0x3, 0x21, 0x3, 0x22, 0x3, 0x22, 0x3, 0x23, 0x3, 0x23, 0x3, 0x23, 0x3, 0x23, 0x3, 0x23, 0x3, 0x23, 0x7, 0x23, 0x1d1, 0xa, 0x23, 0xc, 0x23, 0xe, 0x23, 0x1d4, 0xb, 0x23, 0x7, 0x23, 0x1d6, 0xa, 0x23, 0xc, 0x23, 0xe, 0x23, 0x1d9, 0xb, 0x23, 0x3, 0x24, 0x3, 0x24, 0x7, 0x24, 0x1dd, 0xa, 0x24, 0xc, 0x24, 0xe, 0x24, 0x1e0, 0xb, 0x24, 0x3, 0x24, 0x3, 0x24, 0x3, 0x25, 0x3, 0x25, 0x7, 0x25, 0x1e6, 0xa, 0x25, 0xc, 0x25, 0xe, 0x25, 0x1e9, 0xb, 0x25, 0x3, 0x25, 0x3, 0x25, 0x3, 0x26, 0x3, 0x26, 0x7, 0x26, 0x1ef, 0xa, 0x26, 0xc, 0x26, 0xe, 0x26, 0x1f2, 0xb, 0x26, 0x3, 0x26, 0x3, 0x26, 0x3, 0x27, 0x3, 0x27, 0x7, 0x27, 0x1f8, 0xa, 0x27, 0xc, 0x27, 0xe, 0x27, 0x1fb, 0xb, 0x27, 0x3, 0x27, 0x3, 0x27, 0x3, 0x28, 0x3, 0x28, 0x3, 0x29, 0x3, 0x29, 0x3, 0x2a, 0x3, 0x2a, 0x3, 0x2b, 0x3, 0x2b, 0x3, 0x2c, 0x3, 0x2c, 0x3, 0x2d, 0x3, 0x2d, 0x6, 0x2d, 0x20b, 0xa, 0x2d, 0xd, 0x2d, 0xe, 0x2d, 0x20c, 0x3, 0x2e, 0x3, 0x2e, 0x3, 0x2f, 0x3, 0x2f, 0x3, 0x30, 0x3, 0x30, 0x3, 0x31, 0x3, 0x31, 0x3, 0x32, 0x3, 0x32, 0x3, 0x33, 0x3, 0x33, 0x3, 0x34, 0x3, 0x34, 0x3, 0x35, 0x3, 0x35, 0x3, 0x36, 0x3, 0x36, 0x3, 0x37, 0x3, 0x37, 0x3, 0x38, 0x3, 0x38, 0x3, 0x39, 0x3, 0x39, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b, 0x5, 0x3b, 0x230, 0xa, 0x3b, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3d, 0x3, 0x3d, 0x7, 0x3d, 0x238, 0xa, 0x3d, 0xc, 0x3d, 0xe, 0x3d, 0x23b, 0xb, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3e, 0x3, 0x3e, 0x3, 0x3f, 0x3, 0x3f, 0x3, 0x40, 0x3, 0x40, 0x3, 0x41, 0x3, 0x41, 0x3, 0x42, 0x3, 0x42, 0x3, 0x43, 0x3, 0x43, 0x3, 0x44, 0x3, 0x44, 0x3, 0x45, 0x3, 0x45, 0x3, 0x46, 0x3, 0x46, 0x3, 0x47, 0x3, 0x47, 0x3, 0x48, 0x3, 0x48, 0x3, 0x49, 0x3, 0x49, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4b, 0x3, 0x4b, 0x3, 0x4c, 0x3, 0x4c, 0x3, 0x4d, 0x3, 0x4d, 0x3, 0x4e, 0x3, 0x4e, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x50, 0x3, 0x50, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x7, 0x51, 0x269, 0xa, 0x51, 0xc, 0x51, 0xe, 0x51, 0x26c, 0xb, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x52, 0x3, 0x52, 0x3, 0x52, 0x3, 0x52, 0x7, 0x52, 0x274, 0xa, 0x52, 0xc, 0x52, 0xe, 0x52, 0x277, 0xb, 0x52, 0x3, 0x52, 0x3, 0x52, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x7, 0x53, 0x280, 0xa, 0x53, 0xc, 0x53, 0xe, 0x53, 0x283, 0xb, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x7, 0x54, 0x292, 0xa, 0x54, 0xc, 0x54, 0xe, 0x54, 0x295, 0xb, 0x54, 0x3, 0x54, 0x5, 0x54, 0x298, 0xa, 0x54, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x7, 0x55, 0x2a7, 0xa, 0x55, 0xc, 0x55, 0xe, 0x55, 0x2aa, 0xb, 0x55, 0x3, 0x55, 0x3, 0x55, 0x5, 0x55, 0x2ae, 0xa, 0x55, 0x3, 0x56, 0x3, 0x56, 0x5, 0x56, 0x2b2, 0xa, 0x56, 0x7, 0x56, 0x2b4, 0xa, 0x56, 0xc, 0x56, 0xe, 0x56, 0x2b7, 0xb, 0x56, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x5, 0x57, 0x2bd, 0xa, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x5, 0x57, 0x2c5, 0xa, 0x57, 0x3, 0x57, 0x7, 0x57, 0x2c8, 0xa, 0x57, 0xc, 0x57, 0xe, 0x57, 0x2cb, 0xb, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x5, 0x57, 0x2d1, 0xa, 0x57, 0x3, 0x57, 0x3, 0x57, 0x5, 0x57, 0x2d5, 0xa, 0x57, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x5, 0x58, 0x2db, 0xa, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x5, 0x58, 0x2e5, 0xa, 0x58, 0x3, 0x58, 0x5, 0x58, 0x2e8, 0xa, 0x58, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x5, 0x59, 0x329, 0xa, 0x59, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x32d, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x330, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x334, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x337, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x33b, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x33e, 0xb, 0x5a, 0x7, 0x5a, 0x340, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x343, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x347, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x34a, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x34e, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x351, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x7, 0x5a, 0x355, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x358, 0xb, 0x5a, 0x7, 0x5a, 0x35a, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x35d, 0xb, 0x5a, 0x7, 0x5a, 0x35f, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x362, 0xb, 0x5a, 0x7, 0x5a, 0x364, 0xa, 0x5a, 0xc, 0x5a, 0xe, 0x5a, 0x367, 0xb, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x3, 0x5b, 0x3, 0x5b, 0x5, 0x5b, 0x36d, 0xa, 0x5b, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x7, 0x5c, 0x38c, 0xa, 0x5c, 0xc, 0x5c, 0xe, 0x5c, 0x38f, 0xb, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x7, 0x5c, 0x393, 0xa, 0x5c, 0xc, 0x5c, 0xe, 0x5c, 0x396, 0xb, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x7, 0x5d, 0x3b7, 0xa, 0x5d, 0xc, 0x5d, 0xe, 0x5d, 0x3ba, 0xb, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x7, 0x5d, 0x3be, 0xa, 0x5d, 0xc, 0x5d, 0xe, 0x5d, 0x3c1, 0xb, 0x5d, 0x3, 0x5d, 0x5, 0x5d, 0x3c4, 0xa, 0x5d, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x7, 0x5e, 0x3e3, 0xa, 0x5e, 0xc, 0x5e, 0xe, 0x5e, 0x3e6, 0xb, 0x5e, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x7, 0x5f, 0x403, 0xa, 0x5f, 0xc, 0x5f, 0xe, 0x5f, 0x406, 0xb, 0x5f, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x5, 0x60, 0x41b, 0xa, 0x60, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x5, 0x61, 0x430, 0xa, 0x61, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x7, 0x62, 0x443, 0xa, 0x62, 0xc, 0x62, 0xe, 0x62, 0x446, 0xb, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x7, 0x62, 0x459, 0xa, 0x62, 0xc, 0x62, 0xe, 0x62, 0x45c, 0xb, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x7, 0x62, 0x46f, 0xa, 0x62, 0xc, 0x62, 0xe, 0x62, 0x472, 0xb, 0x62, 0x3, 0x62, 0x5, 0x62, 0x475, 0xa, 0x62, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x5, 0x63, 0x491, 0xa, 0x63, 0x3, 0x64, 0x3, 0x64, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x5, 0x65, 0x4a3, 0xa, 0x65, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x5, 0x66, 0x4ba, 0xa, 0x66, 0x3, 0x66, 0x6, 0x38d, 0x3b8, 0x3e4, 0x404, 0x2, 0x67, 0x2, 0x4, 0x6, 0x8, 0xa, 0xc, 0xe, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0x2, 0x7, 0x3, 0x2, 0x46, 0x47, 0x3, 0x2, 0x4, 0x5, 0x4, 0x2, 0x3, 0x3, 0x49, 0x49, 0x4, 0x2, 0x4, 0x4, 0x52, 0x52, 0x3, 0x3, 0x52, 0x52, 0x2, 0x627, 0x2, 0xcc, 0x3, 0x2, 0x2, 0x2, 0x4, 0xd3, 0x3, 0x2, 0x2, 0x2, 0x6, 0xd6, 0x3, 0x2, 0x2, 0x2, 0x8, 0x120, 0x3, 0x2, 0x2, 0x2, 0xa, 0x122, 0x3, 0x2, 0x2, 0x2, 0xc, 0x130, 0x3, 0x2, 0x2, 0x2, 0xe, 0x132, 0x3, 0x2, 0x2, 0x2, 0x10, 0x13e, 0x3, 0x2, 0x2, 0x2, 0x12, 0x14d, 0x3, 0x2, 0x2, 0x2, 0x14, 0x14f, 0x3, 0x2, 0x2, 0x2, 0x16, 0x151, 0x3, 0x2, 0x2, 0x2, 0x18, 0x153, 0x3, 0x2, 0x2, 0x2, 0x1a, 0x15a, 0x3, 0x2, 0x2, 0x2, 0x1c, 0x15c, 0x3, 0x2, 0x2, 0x2, 0x1e, 0x164, 0x3, 0x2, 0x2, 0x2, 0x20, 0x16b, 0x3, 0x2, 0x2, 0x2, 0x22, 0x16f, 0x3, 0x2, 0x2, 0x2, 0x24, 0x171, 0x3, 0x2, 0x2, 0x2, 0x26, 0x173, 0x3, 0x2, 0x2, 0x2, 0x28, 0x176, 0x3, 0x2, 0x2, 0x2, 0x2a, 0x17d, 0x3, 0x2, 0x2, 0x2, 0x2c, 0x184, 0x3, 0x2, 0x2, 0x2, 0x2e, 0x18b, 0x3, 0x2, 0x2, 0x2, 0x30, 0x192, 0x3, 0x2, 0x2, 0x2, 0x32, 0x199, 0x3, 0x2, 0x2, 0x2, 0x34, 0x1a0, 0x3, 0x2, 0x2, 0x2, 0x36, 0x1a7, 0x3, 0x2, 0x2, 0x2, 0x38, 0x1ae, 0x3, 0x2, 0x2, 0x2, 0x3a, 0x1b5, 0x3, 0x2, 0x2, 0x2, 0x3c, 0x1c0, 0x3, 0x2, 0x2, 0x2, 0x3e, 0x1c2, 0x3, 0x2, 0x2, 0x2, 0x40, 0x1c4, 0x3, 0x2, 0x2, 0x2, 0x42, 0x1c8, 0x3, 0x2, 0x2, 0x2, 0x44, 0x1ca, 0x3, 0x2, 0x2, 0x2, 0x46, 0x1da, 0x3, 0x2, 0x2, 0x2, 0x48, 0x1e3, 0x3, 0x2, 0x2, 0x2, 0x4a, 0x1ec, 0x3, 0x2, 0x2, 0x2, 0x4c, 0x1f5, 0x3, 0x2, 0x2, 0x2, 0x4e, 0x1fe, 0x3, 0x2, 0x2, 0x2, 0x50, 0x200, 0x3, 0x2, 0x2, 0x2, 0x52, 0x202, 0x3, 0x2, 0x2, 0x2, 0x54, 0x204, 0x3, 0x2, 0x2, 0x2, 0x56, 0x206, 0x3, 0x2, 0x2, 0x2, 0x58, 0x208, 0x3, 0x2, 0x2, 0x2, 0x5a, 0x20e, 0x3, 0x2, 0x2, 0x2, 0x5c, 0x210, 0x3, 0x2, 0x2, 0x2, 0x5e, 0x212, 0x3, 0x2, 0x2, 0x2, 0x60, 0x214, 0x3, 0x2, 0x2, 0x2, 0x62, 0x216, 0x3, 0x2, 0x2, 0x2, 0x64, 0x218, 0x3, 0x2, 0x2, 0x2, 0x66, 0x21a, 0x3, 0x2, 0x2, 0x2, 0x68, 0x21c, 0x3, 0x2, 0x2, 0x2, 0x6a, 0x21e, 0x3, 0x2, 0x2, 0x2, 0x6c, 0x220, 0x3, 0x2, 0x2, 0x2, 0x6e, 0x222, 0x3, 0x2, 0x2, 0x2, 0x70, 0x224, 0x3, 0x2, 0x2, 0x2, 0x72, 0x226, 0x3, 0x2, 0x2, 0x2, 0x74, 0x22a, 0x3, 0x2, 0x2, 0x2, 0x76, 0x231, 0x3, 0x2, 0x2, 0x2, 0x78, 0x235, 0x3, 0x2, 0x2, 0x2, 0x7a, 0x23e, 0x3, 0x2, 0x2, 0x2, 0x7c, 0x240, 0x3, 0x2, 0x2, 0x2, 0x7e, 0x242, 0x3, 0x2, 0x2, 0x2, 0x80, 0x244, 0x3, 0x2, 0x2, 0x2, 0x82, 0x246, 0x3, 0x2, 0x2, 0x2, 0x84, 0x248, 0x3, 0x2, 0x2, 0x2, 0x86, 0x24a, 0x3, 0x2, 0x2, 0x2, 0x88, 0x24c, 0x3, 0x2, 0x2, 0x2, 0x8a, 0x24e, 0x3, 0x2, 0x2, 0x2, 0x8c, 0x250, 0x3, 0x2, 0x2, 0x2, 0x8e, 0x252, 0x3, 0x2, 0x2, 0x2, 0x90, 0x254, 0x3, 0x2, 0x2, 0x2, 0x92, 0x256, 0x3, 0x2, 0x2, 0x2, 0x94, 0x258, 0x3, 0x2, 0x2, 0x2, 0x96, 0x25a, 0x3, 0x2, 0x2, 0x2, 0x98, 0x25c, 0x3, 0x2, 0x2, 0x2, 0x9a, 0x25e, 0x3, 0x2, 0x2, 0x2, 0x9c, 0x260, 0x3, 0x2, 0x2, 0x2, 0x9e, 0x262, 0x3, 0x2, 0x2, 0x2, 0xa0, 0x264, 0x3, 0x2, 0x2, 0x2, 0xa2, 0x26f, 0x3, 0x2, 0x2, 0x2, 0xa4, 0x27a, 0x3, 0x2, 0x2, 0x2, 0xa6, 0x297, 0x3, 0x2, 0x2, 0x2, 0xa8, 0x2ad, 0x3, 0x2, 0x2, 0x2, 0xaa, 0x2b5, 0x3, 0x2, 0x2, 0x2, 0xac, 0x2d4, 0x3, 0x2, 0x2, 0x2, 0xae, 0x2e7, 0x3, 0x2, 0x2, 0x2, 0xb0, 0x328, 0x3, 0x2, 0x2, 0x2, 0xb2, 0x32a, 0x3, 0x2, 0x2, 0x2, 0xb4, 0x36c, 0x3, 0x2, 0x2, 0x2, 0xb6, 0x38d, 0x3, 0x2, 0x2, 0x2, 0xb8, 0x3b8, 0x3, 0x2, 0x2, 0x2, 0xba, 0x3e4, 0x3, 0x2, 0x2, 0x2, 0xbc, 0x404, 0x3, 0x2, 0x2, 0x2, 0xbe, 0x41a, 0x3, 0x2, 0x2, 0x2, 0xc0, 0x42f, 0x3, 0x2, 0x2, 0x2, 0xc2, 0x474, 0x3, 0x2, 0x2, 0x2, 0xc4, 0x490, 0x3, 0x2, 0x2, 0x2, 0xc6, 0x492, 0x3, 0x2, 0x2, 0x2, 0xc8, 0x4a2, 0x3, 0x2, 0x2, 0x2, 0xca, 0x4b9, 0x3, 0x2, 0x2, 0x2, 0xcc, 0xcd, 0x5, 0x6, 0x4, 0x2, 0xcd, 0xce, 0x5, 0x4, 0x3, 0x2, 0xce, 0xcf, 0x7, 0x2, 0x2, 0x3, 0xcf, 0x3, 0x3, 0x2, 0x2, 0x2, 0xd0, 0xd2, 0x5, 0x8, 0x5, 0x2, 0xd1, 0xd0, 0x3, 0x2, 0x2, 0x2, 0xd2, 0xd5, 0x3, 0x2, 0x2, 0x2, 0xd3, 0xd1, 0x3, 0x2, 0x2, 0x2, 0xd3, 0xd4, 0x3, 0x2, 0x2, 0x2, 0xd4, 0x5, 0x3, 0x2, 0x2, 0x2, 0xd5, 0xd3, 0x3, 0x2, 0x2, 0x2, 0xd6, 0xd7, 0x3, 0x2, 0x2, 0x2, 0xd7, 0x7, 0x3, 0x2, 0x2, 0x2, 0xd8, 0x121, 0x5, 0xa, 0x6, 0x2, 0xd9, 0x121, 0x5, 0xe, 0x8, 0x2, 0xda, 0x121, 0x5, 0xc6, 0x64, 0x2, 0xdb, 0x121, 0x5, 0x14, 0xb, 0x2, 0xdc, 0x121, 0x5, 0x1a, 0xe, 0x2, 0xdd, 0x121, 0x5, 0x12, 0xa, 0x2, 0xde, 0x121, 0x5, 0x46, 0x24, 0x2, 0xdf, 0x121, 0x5, 0x48, 0x25, 0x2, 0xe0, 0x121, 0x5, 0x20, 0x11, 0x2, 0xe1, 0x121, 0x5, 0x28, 0x15, 0x2, 0xe2, 0x121, 0x5, 0x2a, 0x16, 0x2, 0xe3, 0x121, 0x5, 0x2e, 0x18, 0x2, 0xe4, 0x121, 0x5, 0x3a, 0x1e, 0x2, 0xe5, 0x121, 0x5, 0x32, 0x1a, 0x2, 0xe6, 0x121, 0x5, 0x36, 0x1c, 0x2, 0xe7, 0x121, 0x5, 0x3c, 0x1f, 0x2, 0xe8, 0x121, 0x5, 0x1c, 0xf, 0x2, 0xe9, 0x121, 0x5, 0x3e, 0x20, 0x2, 0xea, 0x121, 0x5, 0x40, 0x21, 0x2, 0xeb, 0x121, 0x5, 0x42, 0x22, 0x2, 0xec, 0x121, 0x5, 0x26, 0x14, 0x2, 0xed, 0x121, 0x5, 0x76, 0x3c, 0x2, 0xee, 0x121, 0x5, 0x78, 0x3d, 0x2, 0xef, 0x121, 0x5, 0x1e, 0x10, 0x2, 0xf0, 0x121, 0x5, 0x74, 0x3b, 0x2, 0xf1, 0x121, 0x5, 0x72, 0x3a, 0x2, 0xf2, 0x121, 0x5, 0x7a, 0x3e, 0x2, 0xf3, 0x121, 0x5, 0x7c, 0x3f, 0x2, 0xf4, 0x121, 0x5, 0x7e, 0x40, 0x2, 0xf5, 0x121, 0x5, 0x80, 0x41, 0x2, 0xf6, 0x121, 0x5, 0x4a, 0x26, 0x2, 0xf7, 0x121, 0x5, 0x4c, 0x27, 0x2, 0xf8, 0x121, 0x5, 0x4e, 0x28, 0x2, 0xf9, 0x121, 0x5, 0x50, 0x29, 0x2, 0xfa, 0x121, 0x5, 0x52, 0x2a, 0x2, 0xfb, 0x121, 0x5, 0x54, 0x2b, 0x2, 0xfc, 0x121, 0x5, 0x56, 0x2c, 0x2, 0xfd, 0x121, 0x5, 0x66, 0x34, 0x2, 0xfe, 0x121, 0x5, 0x68, 0x35, 0x2, 0xff, 0x121, 0x5, 0x6a, 0x36, 0x2, 0x100, 0x121, 0x5, 0x6c, 0x37, 0x2, 0x101, 0x121, 0x5, 0x6e, 0x38, 0x2, 0x102, 0x121, 0x5, 0x70, 0x39, 0x2, 0x103, 0x121, 0x5, 0x82, 0x42, 0x2, 0x104, 0x121, 0x5, 0x58, 0x2d, 0x2, 0x105, 0x121, 0x5, 0x5a, 0x2e, 0x2, 0x106, 0x121, 0x5, 0x5c, 0x2f, 0x2, 0x107, 0x121, 0x5, 0x5e, 0x30, 0x2, 0x108, 0x121, 0x5, 0x60, 0x31, 0x2, 0x109, 0x121, 0x5, 0x62, 0x32, 0x2, 0x10a, 0x121, 0x5, 0x64, 0x33, 0x2, 0x10b, 0x121, 0x5, 0x44, 0x23, 0x2, 0x10c, 0x121, 0x5, 0x22, 0x12, 0x2, 0x10d, 0x121, 0x5, 0x24, 0x13, 0x2, 0x10e, 0x121, 0x5, 0xc, 0x7, 0x2, 0x10f, 0x121, 0x5, 0x84, 0x43, 0x2, 0x110, 0x121, 0x5, 0x86, 0x44, 0x2, 0x111, 0x121, 0x5, 0x88, 0x45, 0x2, 0x112, 0x121, 0x5, 0x8a, 0x46, 0x2, 0x113, 0x121, 0x5, 0x8c, 0x47, 0x2, 0x114, 0x121, 0x5, 0x8e, 0x48, 0x2, 0x115, 0x121, 0x5, 0x90, 0x49, 0x2, 0x116, 0x121, 0x5, 0x92, 0x4a, 0x2, 0x117, 0x121, 0x5, 0x94, 0x4b, 0x2, 0x118, 0x121, 0x5, 0x96, 0x4c, 0x2, 0x119, 0x121, 0x5, 0x98, 0x4d, 0x2, 0x11a, 0x121, 0x5, 0x9a, 0x4e, 0x2, 0x11b, 0x121, 0x5, 0x9c, 0x4f, 0x2, 0x11c, 0x121, 0x5, 0x9e, 0x50, 0x2, 0x11d, 0x121, 0x5, 0xc4, 0x63, 0x2, 0x11e, 0x121, 0x5, 0x16, 0xc, 0x2, 0x11f, 0x121, 0x5, 0x18, 0xd, 0x2, 0x120, 0xd8, 0x3, 0x2, 0x2, 0x2, 0x120, 0xd9, 0x3, 0x2, 0x2, 0x2, 0x120, 0xda, 0x3, 0x2, 0x2, 0x2, 0x120, 0xdb, 0x3, 0x2, 0x2, 0x2, 0x120, 0xdc, 0x3, 0x2, 0x2, 0x2, 0x120, 0xdd, 0x3, 0x2, 0x2, 0x2, 0x120, 0xde, 0x3, 0x2, 0x2, 0x2, 0x120, 0xdf, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe0, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe1, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe2, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe3, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe4, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe5, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe6, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe7, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe8, 0x3, 0x2, 0x2, 0x2, 0x120, 0xe9, 0x3, 0x2, 0x2, 0x2, 0x120, 0xea, 0x3, 0x2, 0x2, 0x2, 0x120, 0xeb, 0x3, 0x2, 0x2, 0x2, 0x120, 0xec, 0x3, 0x2, 0x2, 0x2, 0x120, 0xed, 0x3, 0x2, 0x2, 0x2, 0x120, 0xee, 0x3, 0x2, 0x2, 0x2, 0x120, 0xef, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf0, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf1, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf2, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf3, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf4, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf5, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf6, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf7, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf8, 0x3, 0x2, 0x2, 0x2, 0x120, 0xf9, 0x3, 0x2, 0x2, 0x2, 0x120, 0xfa, 0x3, 0x2, 0x2, 0x2, 0x120, 0xfb, 0x3, 0x2, 0x2, 0x2, 0x120, 0xfc, 0x3, 0x2, 0x2, 0x2, 0x120, 0xfd, 0x3, 0x2, 0x2, 0x2, 0x120, 0xfe, 0x3, 0x2, 0x2, 0x2, 0x120, 0xff, 0x3, 0x2, 0x2, 0x2, 0x120, 0x100, 0x3, 0x2, 0x2, 0x2, 0x120, 0x101, 0x3, 0x2, 0x2, 0x2, 0x120, 0x102, 0x3, 0x2, 0x2, 0x2, 0x120, 0x103, 0x3, 0x2, 0x2, 0x2, 0x120, 0x104, 0x3, 0x2, 0x2, 0x2, 0x120, 0x105, 0x3, 0x2, 0x2, 0x2, 0x120, 0x106, 0x3, 0x2, 0x2, 0x2, 0x120, 0x107, 0x3, 0x2, 0x2, 0x2, 0x120, 0x108, 0x3, 0x2, 0x2, 0x2, 0x120, 0x109, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10a, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10b, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10c, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10d, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10e, 0x3, 0x2, 0x2, 0x2, 0x120, 0x10f, 0x3, 0x2, 0x2, 0x2, 0x120, 0x110, 0x3, 0x2, 0x2, 0x2, 0x120, 0x111, 0x3, 0x2, 0x2, 0x2, 0x120, 0x112, 0x3, 0x2, 0x2, 0x2, 0x120, 0x113, 0x3, 0x2, 0x2, 0x2, 0x120, 0x114, 0x3, 0x2, 0x2, 0x2, 0x120, 0x115, 0x3, 0x2, 0x2, 0x2, 0x120, 0x116, 0x3, 0x2, 0x2, 0x2, 0x120, 0x117, 0x3, 0x2, 0x2, 0x2, 0x120, 0x118, 0x3, 0x2, 0x2, 0x2, 0x120, 0x119, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11a, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11b, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11c, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11d, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11e, 0x3, 0x2, 0x2, 0x2, 0x120, 0x11f, 0x3, 0x2, 0x2, 0x2, 0x121, 0x9, 0x3, 0x2, 0x2, 0x2, 0x122, 0x123, 0x7, 0x3, 0x2, 0x2, 0x123, 0xb, 0x3, 0x2, 0x2, 0x2, 0x124, 0x128, 0x9, 0x2, 0x2, 0x2, 0x125, 0x127, 0x7, 0x4a, 0x2, 0x2, 0x126, 0x125, 0x3, 0x2, 0x2, 0x2, 0x127, 0x12a, 0x3, 0x2, 0x2, 0x2, 0x128, 0x126, 0x3, 0x2, 0x2, 0x2, 0x128, 0x129, 0x3, 0x2, 0x2, 0x2, 0x129, 0x12b, 0x3, 0x2, 0x2, 0x2, 0x12a, 0x128, 0x3, 0x2, 0x2, 0x2, 0x12b, 0x12c, 0x7, 0x56, 0x2, 0x2, 0x12c, 0x12d, 0x5, 0x10, 0x9, 0x2, 0x12d, 0x12e, 0x7, 0x57, 0x2, 0x2, 0x12e, 0x131, 0x3, 0x2, 0x2, 0x2, 0x12f, 0x131, 0x9, 0x2, 0x2, 0x2, 0x130, 0x124, 0x3, 0x2, 0x2, 0x2, 0x130, 0x12f, 0x3, 0x2, 0x2, 0x2, 0x131, 0xd, 0x3, 0x2, 0x2, 0x2, 0x132, 0x136, 0x7, 0x5a, 0x2, 0x2, 0x133, 0x135, 0x5, 0xca, 0x66, 0x2, 0x134, 0x133, 0x3, 0x2, 0x2, 0x2, 0x135, 0x138, 0x3, 0x2, 0x2, 0x2, 0x136, 0x134, 0x3, 0x2, 0x2, 0x2, 0x136, 0x137, 0x3, 0x2, 0x2, 0x2, 0x137, 0x139, 0x3, 0x2, 0x2, 0x2, 0x138, 0x136, 0x3, 0x2, 0x2, 0x2, 0x139, 0x13a, 0x7, 0x52, 0x2, 0x2, 0x13a, 0xf, 0x3, 0x2, 0x2, 0x2, 0x13b, 0x13d, 0x5, 0xc0, 0x61, 0x2, 0x13c, 0x13b, 0x3, 0x2, 0x2, 0x2, 0x13d, 0x140, 0x3, 0x2, 0x2, 0x2, 0x13e, 0x13c, 0x3, 0x2, 0x2, 0x2, 0x13e, 0x13f, 0x3, 0x2, 0x2, 0x2, 0x13f, 0x14a, 0x3, 0x2, 0x2, 0x2, 0x140, 0x13e, 0x3, 0x2, 0x2, 0x2, 0x141, 0x145, 0x7, 0x58, 0x2, 0x2, 0x142, 0x144, 0x5, 0xc0, 0x61, 0x2, 0x143, 0x142, 0x3, 0x2, 0x2, 0x2, 0x144, 0x147, 0x3, 0x2, 0x2, 0x2, 0x145, 0x143, 0x3, 0x2, 0x2, 0x2, 0x145, 0x146, 0x3, 0x2, 0x2, 0x2, 0x146, 0x149, 0x3, 0x2, 0x2, 0x2, 0x147, 0x145, 0x3, 0x2, 0x2, 0x2, 0x148, 0x141, 0x3, 0x2, 0x2, 0x2, 0x149, 0x14c, 0x3, 0x2, 0x2, 0x2, 0x14a, 0x148, 0x3, 0x2, 0x2, 0x2, 0x14a, 0x14b, 0x3, 0x2, 0x2, 0x2, 0x14b, 0x11, 0x3, 0x2, 0x2, 0x2, 0x14c, 0x14a, 0x3, 0x2, 0x2, 0x2, 0x14d, 0x14e, 0x9, 0x3, 0x2, 0x2, 0x14e, 0x13, 0x3, 0x2, 0x2, 0x2, 0x14f, 0x150, 0x7, 0x4e, 0x2, 0x2, 0x150, 0x15, 0x3, 0x2, 0x2, 0x2, 0x151, 0x152, 0x7, 0x4c, 0x2, 0x2, 0x152, 0x17, 0x3, 0x2, 0x2, 0x2, 0x153, 0x154, 0x7, 0x4b, 0x2, 0x2, 0x154, 0x19, 0x3, 0x2, 0x2, 0x2, 0x155, 0x15b, 0x5, 0xa0, 0x51, 0x2, 0x156, 0x15b, 0x5, 0xa4, 0x53, 0x2, 0x157, 0x15b, 0x5, 0xa6, 0x54, 0x2, 0x158, 0x15b, 0x5, 0xa2, 0x52, 0x2, 0x159, 0x15b, 0x5, 0xa8, 0x55, 0x2, 0x15a, 0x155, 0x3, 0x2, 0x2, 0x2, 0x15a, 0x156, 0x3, 0x2, 0x2, 0x2, 0x15a, 0x157, 0x3, 0x2, 0x2, 0x2, 0x15a, 0x158, 0x3, 0x2, 0x2, 0x2, 0x15a, 0x159, 0x3, 0x2, 0x2, 0x2, 0x15b, 0x1b, 0x3, 0x2, 0x2, 0x2, 0x15c, 0x15d, 0x7, 0x12, 0x2, 0x2, 0x15d, 0x162, 0x7, 0x4a, 0x2, 0x2, 0x15e, 0x163, 0x7, 0x48, 0x2, 0x2, 0x15f, 0x163, 0x7, 0x49, 0x2, 0x2, 0x160, 0x163, 0x7, 0x3, 0x2, 0x2, 0x161, 0x163, 0x5, 0xc, 0x7, 0x2, 0x162, 0x15e, 0x3, 0x2, 0x2, 0x2, 0x162, 0x15f, 0x3, 0x2, 0x2, 0x2, 0x162, 0x160, 0x3, 0x2, 0x2, 0x2, 0x162, 0x161, 0x3, 0x2, 0x2, 0x2, 0x163, 0x1d, 0x3, 0x2, 0x2, 0x2, 0x164, 0x165, 0x7, 0x1a, 0x2, 0x2, 0x165, 0x166, 0x7, 0x4a, 0x2, 0x2, 0x166, 0x167, 0x5, 0x14, 0xb, 0x2, 0x167, 0x168, 0x7, 0x48, 0x2, 0x2, 0x168, 0x169, 0x7, 0x4a, 0x2, 0x2, 0x169, 0x16a, 0x5, 0x14, 0xb, 0x2, 0x16a, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x16b, 0x16c, 0x7, 0xa, 0x2, 0x2, 0x16c, 0x16d, 0x7, 0x4a, 0x2, 0x2, 0x16d, 0x16e, 0x7, 0x49, 0x2, 0x2, 0x16e, 0x21, 0x3, 0x2, 0x2, 0x2, 0x16f, 0x170, 0x7, 0x36, 0x2, 0x2, 0x170, 0x23, 0x3, 0x2, 0x2, 0x2, 0x171, 0x172, 0x7, 0x37, 0x2, 0x2, 0x172, 0x25, 0x3, 0x2, 0x2, 0x2, 0x173, 0x174, 0x7, 0x17, 0x2, 0x2, 0x174, 0x175, 0x7, 0x4d, 0x2, 0x2, 0x175, 0x27, 0x3, 0x2, 0x2, 0x2, 0x176, 0x177, 0x7, 0xb, 0x2, 0x2, 0x177, 0x17b, 0x7, 0x4a, 0x2, 0x2, 0x178, 0x17c, 0x7, 0x49, 0x2, 0x2, 0x179, 0x17c, 0x7, 0x3, 0x2, 0x2, 0x17a, 0x17c, 0x5, 0xc, 0x7, 0x2, 0x17b, 0x178, 0x3, 0x2, 0x2, 0x2, 0x17b, 0x179, 0x3, 0x2, 0x2, 0x2, 0x17b, 0x17a, 0x3, 0x2, 0x2, 0x2, 0x17c, 0x29, 0x3, 0x2, 0x2, 0x2, 0x17d, 0x17e, 0x7, 0xc, 0x2, 0x2, 0x17e, 0x182, 0x7, 0x4a, 0x2, 0x2, 0x17f, 0x183, 0x7, 0x49, 0x2, 0x2, 0x180, 0x183, 0x7, 0x3, 0x2, 0x2, 0x181, 0x183, 0x5, 0xc, 0x7, 0x2, 0x182, 0x17f, 0x3, 0x2, 0x2, 0x2, 0x182, 0x180, 0x3, 0x2, 0x2, 0x2, 0x182, 0x181, 0x3, 0x2, 0x2, 0x2, 0x183, 0x2b, 0x3, 0x2, 0x2, 0x2, 0x184, 0x185, 0x7, 0xc, 0x2, 0x2, 0x185, 0x189, 0x7, 0x4a, 0x2, 0x2, 0x186, 0x18a, 0x5, 0xaa, 0x56, 0x2, 0x187, 0x18a, 0x7, 0x3, 0x2, 0x2, 0x188, 0x18a, 0x5, 0xc, 0x7, 0x2, 0x189, 0x186, 0x3, 0x2, 0x2, 0x2, 0x189, 0x187, 0x3, 0x2, 0x2, 0x2, 0x189, 0x188, 0x3, 0x2, 0x2, 0x2, 0x18a, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x18b, 0x18c, 0x7, 0xd, 0x2, 0x2, 0x18c, 0x190, 0x7, 0x4a, 0x2, 0x2, 0x18d, 0x191, 0x7, 0x49, 0x2, 0x2, 0x18e, 0x191, 0x7, 0x3, 0x2, 0x2, 0x18f, 0x191, 0x5, 0xc, 0x7, 0x2, 0x190, 0x18d, 0x3, 0x2, 0x2, 0x2, 0x190, 0x18e, 0x3, 0x2, 0x2, 0x2, 0x190, 0x18f, 0x3, 0x2, 0x2, 0x2, 0x191, 0x2f, 0x3, 0x2, 0x2, 0x2, 0x192, 0x193, 0x7, 0xd, 0x2, 0x2, 0x193, 0x197, 0x7, 0x4a, 0x2, 0x2, 0x194, 0x198, 0x5, 0xaa, 0x56, 0x2, 0x195, 0x198, 0x7, 0x3, 0x2, 0x2, 0x196, 0x198, 0x5, 0xc, 0x7, 0x2, 0x197, 0x194, 0x3, 0x2, 0x2, 0x2, 0x197, 0x195, 0x3, 0x2, 0x2, 0x2, 0x197, 0x196, 0x3, 0x2, 0x2, 0x2, 0x198, 0x31, 0x3, 0x2, 0x2, 0x2, 0x199, 0x19a, 0x7, 0xf, 0x2, 0x2, 0x19a, 0x19e, 0x7, 0x4a, 0x2, 0x2, 0x19b, 0x19f, 0x7, 0x49, 0x2, 0x2, 0x19c, 0x19f, 0x7, 0x3, 0x2, 0x2, 0x19d, 0x19f, 0x5, 0xc, 0x7, 0x2, 0x19e, 0x19b, 0x3, 0x2, 0x2, 0x2, 0x19e, 0x19c, 0x3, 0x2, 0x2, 0x2, 0x19e, 0x19d, 0x3, 0x2, 0x2, 0x2, 0x19f, 0x33, 0x3, 0x2, 0x2, 0x2, 0x1a0, 0x1a1, 0x7, 0xf, 0x2, 0x2, 0x1a1, 0x1a5, 0x7, 0x4a, 0x2, 0x2, 0x1a2, 0x1a6, 0x5, 0xaa, 0x56, 0x2, 0x1a3, 0x1a6, 0x7, 0x3, 0x2, 0x2, 0x1a4, 0x1a6, 0x5, 0xc, 0x7, 0x2, 0x1a5, 0x1a2, 0x3, 0x2, 0x2, 0x2, 0x1a5, 0x1a3, 0x3, 0x2, 0x2, 0x2, 0x1a5, 0x1a4, 0x3, 0x2, 0x2, 0x2, 0x1a6, 0x35, 0x3, 0x2, 0x2, 0x2, 0x1a7, 0x1a8, 0x7, 0x10, 0x2, 0x2, 0x1a8, 0x1ac, 0x7, 0x4a, 0x2, 0x2, 0x1a9, 0x1ad, 0x7, 0x49, 0x2, 0x2, 0x1aa, 0x1ad, 0x7, 0x3, 0x2, 0x2, 0x1ab, 0x1ad, 0x5, 0xc, 0x7, 0x2, 0x1ac, 0x1a9, 0x3, 0x2, 0x2, 0x2, 0x1ac, 0x1aa, 0x3, 0x2, 0x2, 0x2, 0x1ac, 0x1ab, 0x3, 0x2, 0x2, 0x2, 0x1ad, 0x37, 0x3, 0x2, 0x2, 0x2, 0x1ae, 0x1af, 0x7, 0x10, 0x2, 0x2, 0x1af, 0x1b3, 0x7, 0x4a, 0x2, 0x2, 0x1b0, 0x1b4, 0x5, 0xaa, 0x56, 0x2, 0x1b1, 0x1b4, 0x7, 0x3, 0x2, 0x2, 0x1b2, 0x1b4, 0x5, 0xc, 0x7, 0x2, 0x1b3, 0x1b0, 0x3, 0x2, 0x2, 0x2, 0x1b3, 0x1b1, 0x3, 0x2, 0x2, 0x2, 0x1b3, 0x1b2, 0x3, 0x2, 0x2, 0x2, 0x1b4, 0x39, 0x3, 0x2, 0x2, 0x2, 0x1b5, 0x1b6, 0x7, 0xe, 0x2, 0x2, 0x1b6, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x1b7, 0x1bb, 0x7, 0x11, 0x2, 0x2, 0x1b8, 0x1ba, 0x7, 0x4a, 0x2, 0x2, 0x1b9, 0x1b8, 0x3, 0x2, 0x2, 0x2, 0x1ba, 0x1bd, 0x3, 0x2, 0x2, 0x2, 0x1bb, 0x1b9, 0x3, 0x2, 0x2, 0x2, 0x1bb, 0x1bc, 0x3, 0x2, 0x2, 0x2, 0x1bc, 0x1be, 0x3, 0x2, 0x2, 0x2, 0x1bd, 0x1bb, 0x3, 0x2, 0x2, 0x2, 0x1be, 0x1c1, 0x7, 0x4, 0x2, 0x2, 0x1bf, 0x1c1, 0x7, 0x11, 0x2, 0x2, 0x1c0, 0x1b7, 0x3, 0x2, 0x2, 0x2, 0x1c0, 0x1bf, 0x3, 0x2, 0x2, 0x2, 0x1c1, 0x3d, 0x3, 0x2, 0x2, 0x2, 0x1c2, 0x1c3, 0x7, 0x16, 0x2, 0x2, 0x1c3, 0x3f, 0x3, 0x2, 0x2, 0x2, 0x1c4, 0x1c5, 0x7, 0x14, 0x2, 0x2, 0x1c5, 0x1c6, 0x7, 0x4a, 0x2, 0x2, 0x1c6, 0x1c7, 0x7, 0x48, 0x2, 0x2, 0x1c7, 0x41, 0x3, 0x2, 0x2, 0x2, 0x1c8, 0x1c9, 0x7, 0x15, 0x2, 0x2, 0x1c9, 0x43, 0x3, 0x2, 0x2, 0x2, 0x1ca, 0x1cb, 0x7, 0x13, 0x2, 0x2, 0x1cb, 0x1cc, 0x7, 0x4a, 0x2, 0x2, 0x1cc, 0x1d7, 0x7, 0x49, 0x2, 0x2, 0x1cd, 0x1d2, 0x5, 0xbe, 0x60, 0x2, 0x1ce, 0x1cf, 0x7, 0x5f, 0x2, 0x2, 0x1cf, 0x1d1, 0x5, 0xbe, 0x60, 0x2, 0x1d0, 0x1ce, 0x3, 0x2, 0x2, 0x2, 0x1d1, 0x1d4, 0x3, 0x2, 0x2, 0x2, 0x1d2, 0x1d0, 0x3, 0x2, 0x2, 0x2, 0x1d2, 0x1d3, 0x3, 0x2, 0x2, 0x2, 0x1d3, 0x1d6, 0x3, 0x2, 0x2, 0x2, 0x1d4, 0x1d2, 0x3, 0x2, 0x2, 0x2, 0x1d5, 0x1cd, 0x3, 0x2, 0x2, 0x2, 0x1d6, 0x1d9, 0x3, 0x2, 0x2, 0x2, 0x1d7, 0x1d5, 0x3, 0x2, 0x2, 0x2, 0x1d7, 0x1d8, 0x3, 0x2, 0x2, 0x2, 0x1d8, 0x45, 0x3, 0x2, 0x2, 0x2, 0x1d9, 0x1d7, 0x3, 0x2, 0x2, 0x2, 0x1da, 0x1de, 0x7, 0x8, 0x2, 0x2, 0x1db, 0x1dd, 0x7, 0x4a, 0x2, 0x2, 0x1dc, 0x1db, 0x3, 0x2, 0x2, 0x2, 0x1dd, 0x1e0, 0x3, 0x2, 0x2, 0x2, 0x1de, 0x1dc, 0x3, 0x2, 0x2, 0x2, 0x1de, 0x1df, 0x3, 0x2, 0x2, 0x2, 0x1df, 0x1e1, 0x3, 0x2, 0x2, 0x2, 0x1e0, 0x1de, 0x3, 0x2, 0x2, 0x2, 0x1e1, 0x1e2, 0x7, 0x52, 0x2, 0x2, 0x1e2, 0x47, 0x3, 0x2, 0x2, 0x2, 0x1e3, 0x1e7, 0x7, 0x9, 0x2, 0x2, 0x1e4, 0x1e6, 0x7, 0x4a, 0x2, 0x2, 0x1e5, 0x1e4, 0x3, 0x2, 0x2, 0x2, 0x1e6, 0x1e9, 0x3, 0x2, 0x2, 0x2, 0x1e7, 0x1e5, 0x3, 0x2, 0x2, 0x2, 0x1e7, 0x1e8, 0x3, 0x2, 0x2, 0x2, 0x1e8, 0x1ea, 0x3, 0x2, 0x2, 0x2, 0x1e9, 0x1e7, 0x3, 0x2, 0x2, 0x2, 0x1ea, 0x1eb, 0x7, 0x52, 0x2, 0x2, 0x1eb, 0x49, 0x3, 0x2, 0x2, 0x2, 0x1ec, 0x1f0, 0x7, 0x24, 0x2, 0x2, 0x1ed, 0x1ef, 0x7, 0x4a, 0x2, 0x2, 0x1ee, 0x1ed, 0x3, 0x2, 0x2, 0x2, 0x1ef, 0x1f2, 0x3, 0x2, 0x2, 0x2, 0x1f0, 0x1ee, 0x3, 0x2, 0x2, 0x2, 0x1f0, 0x1f1, 0x3, 0x2, 0x2, 0x2, 0x1f1, 0x1f3, 0x3, 0x2, 0x2, 0x2, 0x1f2, 0x1f0, 0x3, 0x2, 0x2, 0x2, 0x1f3, 0x1f4, 0x7, 0x52, 0x2, 0x2, 0x1f4, 0x4b, 0x3, 0x2, 0x2, 0x2, 0x1f5, 0x1f9, 0x7, 0x2c, 0x2, 0x2, 0x1f6, 0x1f8, 0x7, 0x4a, 0x2, 0x2, 0x1f7, 0x1f6, 0x3, 0x2, 0x2, 0x2, 0x1f8, 0x1fb, 0x3, 0x2, 0x2, 0x2, 0x1f9, 0x1f7, 0x3, 0x2, 0x2, 0x2, 0x1f9, 0x1fa, 0x3, 0x2, 0x2, 0x2, 0x1fa, 0x1fc, 0x3, 0x2, 0x2, 0x2, 0x1fb, 0x1f9, 0x3, 0x2, 0x2, 0x2, 0x1fc, 0x1fd, 0x7, 0x52, 0x2, 0x2, 0x1fd, 0x4d, 0x3, 0x2, 0x2, 0x2, 0x1fe, 0x1ff, 0x7, 0x2d, 0x2, 0x2, 0x1ff, 0x4f, 0x3, 0x2, 0x2, 0x2, 0x200, 0x201, 0x7, 0x2e, 0x2, 0x2, 0x201, 0x51, 0x3, 0x2, 0x2, 0x2, 0x202, 0x203, 0x7, 0x2f, 0x2, 0x2, 0x203, 0x53, 0x3, 0x2, 0x2, 0x2, 0x204, 0x205, 0x7, 0x30, 0x2, 0x2, 0x205, 0x55, 0x3, 0x2, 0x2, 0x2, 0x206, 0x207, 0x7, 0x31, 0x2, 0x2, 0x207, 0x57, 0x3, 0x2, 0x2, 0x2, 0x208, 0x20a, 0x7, 0x25, 0x2, 0x2, 0x209, 0x20b, 0x5, 0xc4, 0x63, 0x2, 0x20a, 0x209, 0x3, 0x2, 0x2, 0x2, 0x20b, 0x20c, 0x3, 0x2, 0x2, 0x2, 0x20c, 0x20a, 0x3, 0x2, 0x2, 0x2, 0x20c, 0x20d, 0x3, 0x2, 0x2, 0x2, 0x20d, 0x59, 0x3, 0x2, 0x2, 0x2, 0x20e, 0x20f, 0x7, 0x26, 0x2, 0x2, 0x20f, 0x5b, 0x3, 0x2, 0x2, 0x2, 0x210, 0x211, 0x7, 0x27, 0x2, 0x2, 0x211, 0x5d, 0x3, 0x2, 0x2, 0x2, 0x212, 0x213, 0x7, 0x28, 0x2, 0x2, 0x213, 0x5f, 0x3, 0x2, 0x2, 0x2, 0x214, 0x215, 0x7, 0x29, 0x2, 0x2, 0x215, 0x61, 0x3, 0x2, 0x2, 0x2, 0x216, 0x217, 0x7, 0x2a, 0x2, 0x2, 0x217, 0x63, 0x3, 0x2, 0x2, 0x2, 0x218, 0x219, 0x7, 0x2b, 0x2, 0x2, 0x219, 0x65, 0x3, 0x2, 0x2, 0x2, 0x21a, 0x21b, 0x7, 0x32, 0x2, 0x2, 0x21b, 0x67, 0x3, 0x2, 0x2, 0x2, 0x21c, 0x21d, 0x7, 0x33, 0x2, 0x2, 0x21d, 0x69, 0x3, 0x2, 0x2, 0x2, 0x21e, 0x21f, 0x7, 0x34, 0x2, 0x2, 0x21f, 0x6b, 0x3, 0x2, 0x2, 0x2, 0x220, 0x221, 0x7, 0x35, 0x2, 0x2, 0x221, 0x6d, 0x3, 0x2, 0x2, 0x2, 0x222, 0x223, 0x7, 0x22, 0x2, 0x2, 0x223, 0x6f, 0x3, 0x2, 0x2, 0x2, 0x224, 0x225, 0x7, 0x23, 0x2, 0x2, 0x225, 0x71, 0x3, 0x2, 0x2, 0x2, 0x226, 0x227, 0x7, 0x1c, 0x2, 0x2, 0x227, 0x228, 0x7, 0x4a, 0x2, 0x2, 0x228, 0x229, 0x5, 0x14, 0xb, 0x2, 0x229, 0x73, 0x3, 0x2, 0x2, 0x2, 0x22a, 0x22b, 0x7, 0x1b, 0x2, 0x2, 0x22b, 0x22f, 0x7, 0x4a, 0x2, 0x2, 0x22c, 0x230, 0x5, 0x14, 0xb, 0x2, 0x22d, 0x230, 0x7, 0x49, 0x2, 0x2, 0x22e, 0x230, 0x7, 0x4f, 0x2, 0x2, 0x22f, 0x22c, 0x3, 0x2, 0x2, 0x2, 0x22f, 0x22d, 0x3, 0x2, 0x2, 0x2, 0x22f, 0x22e, 0x3, 0x2, 0x2, 0x2, 0x230, 0x75, 0x3, 0x2, 0x2, 0x2, 0x231, 0x232, 0x7, 0x18, 0x2, 0x2, 0x232, 0x233, 0x7, 0x4a, 0x2, 0x2, 0x233, 0x234, 0x7, 0x49, 0x2, 0x2, 0x234, 0x77, 0x3, 0x2, 0x2, 0x2, 0x235, 0x239, 0x7, 0x19, 0x2, 0x2, 0x236, 0x238, 0x7, 0x4a, 0x2, 0x2, 0x237, 0x236, 0x3, 0x2, 0x2, 0x2, 0x238, 0x23b, 0x3, 0x2, 0x2, 0x2, 0x239, 0x237, 0x3, 0x2, 0x2, 0x2, 0x239, 0x23a, 0x3, 0x2, 0x2, 0x2, 0x23a, 0x23c, 0x3, 0x2, 0x2, 0x2, 0x23b, 0x239, 0x3, 0x2, 0x2, 0x2, 0x23c, 0x23d, 0x7, 0x52, 0x2, 0x2, 0x23d, 0x79, 0x3, 0x2, 0x2, 0x2, 0x23e, 0x23f, 0x7, 0x1d, 0x2, 0x2, 0x23f, 0x7b, 0x3, 0x2, 0x2, 0x2, 0x240, 0x241, 0x7, 0x1e, 0x2, 0x2, 0x241, 0x7d, 0x3, 0x2, 0x2, 0x2, 0x242, 0x243, 0x7, 0x1f, 0x2, 0x2, 0x243, 0x7f, 0x3, 0x2, 0x2, 0x2, 0x244, 0x245, 0x7, 0x20, 0x2, 0x2, 0x245, 0x81, 0x3, 0x2, 0x2, 0x2, 0x246, 0x247, 0x7, 0x21, 0x2, 0x2, 0x247, 0x83, 0x3, 0x2, 0x2, 0x2, 0x248, 0x249, 0x7, 0x38, 0x2, 0x2, 0x249, 0x85, 0x3, 0x2, 0x2, 0x2, 0x24a, 0x24b, 0x7, 0x39, 0x2, 0x2, 0x24b, 0x87, 0x3, 0x2, 0x2, 0x2, 0x24c, 0x24d, 0x7, 0x3a, 0x2, 0x2, 0x24d, 0x89, 0x3, 0x2, 0x2, 0x2, 0x24e, 0x24f, 0x7, 0x3b, 0x2, 0x2, 0x24f, 0x8b, 0x3, 0x2, 0x2, 0x2, 0x250, 0x251, 0x7, 0x3c, 0x2, 0x2, 0x251, 0x8d, 0x3, 0x2, 0x2, 0x2, 0x252, 0x253, 0x7, 0x3d, 0x2, 0x2, 0x253, 0x8f, 0x3, 0x2, 0x2, 0x2, 0x254, 0x255, 0x7, 0x3e, 0x2, 0x2, 0x255, 0x91, 0x3, 0x2, 0x2, 0x2, 0x256, 0x257, 0x7, 0x3f, 0x2, 0x2, 0x257, 0x93, 0x3, 0x2, 0x2, 0x2, 0x258, 0x259, 0x7, 0x40, 0x2, 0x2, 0x259, 0x95, 0x3, 0x2, 0x2, 0x2, 0x25a, 0x25b, 0x7, 0x41, 0x2, 0x2, 0x25b, 0x97, 0x3, 0x2, 0x2, 0x2, 0x25c, 0x25d, 0x7, 0x42, 0x2, 0x2, 0x25d, 0x99, 0x3, 0x2, 0x2, 0x2, 0x25e, 0x25f, 0x7, 0x43, 0x2, 0x2, 0x25f, 0x9b, 0x3, 0x2, 0x2, 0x2, 0x260, 0x261, 0x7, 0x44, 0x2, 0x2, 0x261, 0x9d, 0x3, 0x2, 0x2, 0x2, 0x262, 0x263, 0x7, 0x45, 0x2, 0x2, 0x263, 0x9f, 0x3, 0x2, 0x2, 0x2, 0x264, 0x265, 0x7, 0x7, 0x2, 0x2, 0x265, 0x266, 0x7, 0x4a, 0x2, 0x2, 0x266, 0x26a, 0x9, 0x4, 0x2, 0x2, 0x267, 0x269, 0x7, 0x4a, 0x2, 0x2, 0x268, 0x267, 0x3, 0x2, 0x2, 0x2, 0x269, 0x26c, 0x3, 0x2, 0x2, 0x2, 0x26a, 0x268, 0x3, 0x2, 0x2, 0x2, 0x26a, 0x26b, 0x3, 0x2, 0x2, 0x2, 0x26b, 0x26d, 0x3, 0x2, 0x2, 0x2, 0x26c, 0x26a, 0x3, 0x2, 0x2, 0x2, 0x26d, 0x26e, 0x7, 0x52, 0x2, 0x2, 0x26e, 0xa1, 0x3, 0x2, 0x2, 0x2, 0x26f, 0x270, 0x7, 0x7, 0x2, 0x2, 0x270, 0x271, 0x7, 0x4a, 0x2, 0x2, 0x271, 0x275, 0x9, 0x4, 0x2, 0x2, 0x272, 0x274, 0x7, 0x4a, 0x2, 0x2, 0x273, 0x272, 0x3, 0x2, 0x2, 0x2, 0x274, 0x277, 0x3, 0x2, 0x2, 0x2, 0x275, 0x273, 0x3, 0x2, 0x2, 0x2, 0x275, 0x276, 0x3, 0x2, 0x2, 0x2, 0x276, 0x278, 0x3, 0x2, 0x2, 0x2, 0x277, 0x275, 0x3, 0x2, 0x2, 0x2, 0x278, 0x279, 0x5, 0xb4, 0x5b, 0x2, 0x279, 0xa3, 0x3, 0x2, 0x2, 0x2, 0x27a, 0x27b, 0x7, 0x7, 0x2, 0x2, 0x27b, 0x27c, 0x7, 0x4a, 0x2, 0x2, 0x27c, 0x27d, 0x9, 0x4, 0x2, 0x2, 0x27d, 0x281, 0x5, 0xb2, 0x5a, 0x2, 0x27e, 0x280, 0x7, 0x4a, 0x2, 0x2, 0x27f, 0x27e, 0x3, 0x2, 0x2, 0x2, 0x280, 0x283, 0x3, 0x2, 0x2, 0x2, 0x281, 0x27f, 0x3, 0x2, 0x2, 0x2, 0x281, 0x282, 0x3, 0x2, 0x2, 0x2, 0x282, 0x284, 0x3, 0x2, 0x2, 0x2, 0x283, 0x281, 0x3, 0x2, 0x2, 0x2, 0x284, 0x285, 0x5, 0xb4, 0x5b, 0x2, 0x285, 0xa5, 0x3, 0x2, 0x2, 0x2, 0x286, 0x287, 0x7, 0x7, 0x2, 0x2, 0x287, 0x288, 0x7, 0x4a, 0x2, 0x2, 0x288, 0x289, 0x9, 0x4, 0x2, 0x2, 0x289, 0x28a, 0x7, 0x4a, 0x2, 0x2, 0x28a, 0x28b, 0x5, 0xba, 0x5e, 0x2, 0x28b, 0x28c, 0x9, 0x5, 0x2, 0x2, 0x28c, 0x298, 0x3, 0x2, 0x2, 0x2, 0x28d, 0x28e, 0x7, 0x7, 0x2, 0x2, 0x28e, 0x28f, 0x7, 0x4a, 0x2, 0x2, 0x28f, 0x293, 0x9, 0x4, 0x2, 0x2, 0x290, 0x292, 0x7, 0x4a, 0x2, 0x2, 0x291, 0x290, 0x3, 0x2, 0x2, 0x2, 0x292, 0x295, 0x3, 0x2, 0x2, 0x2, 0x293, 0x291, 0x3, 0x2, 0x2, 0x2, 0x293, 0x294, 0x3, 0x2, 0x2, 0x2, 0x294, 0x296, 0x3, 0x2, 0x2, 0x2, 0x295, 0x293, 0x3, 0x2, 0x2, 0x2, 0x296, 0x298, 0x7, 0x52, 0x2, 0x2, 0x297, 0x286, 0x3, 0x2, 0x2, 0x2, 0x297, 0x28d, 0x3, 0x2, 0x2, 0x2, 0x298, 0xa7, 0x3, 0x2, 0x2, 0x2, 0x299, 0x29a, 0x7, 0x7, 0x2, 0x2, 0x29a, 0x29b, 0x7, 0x4a, 0x2, 0x2, 0x29b, 0x29c, 0x9, 0x4, 0x2, 0x2, 0x29c, 0x29d, 0x5, 0xb2, 0x5a, 0x2, 0x29d, 0x29e, 0x7, 0x4a, 0x2, 0x2, 0x29e, 0x29f, 0x5, 0xba, 0x5e, 0x2, 0x29f, 0x2a0, 0x9, 0x5, 0x2, 0x2, 0x2a0, 0x2ae, 0x3, 0x2, 0x2, 0x2, 0x2a1, 0x2a2, 0x7, 0x7, 0x2, 0x2, 0x2a2, 0x2a3, 0x7, 0x4a, 0x2, 0x2, 0x2a3, 0x2a4, 0x9, 0x4, 0x2, 0x2, 0x2a4, 0x2a8, 0x5, 0xb2, 0x5a, 0x2, 0x2a5, 0x2a7, 0x7, 0x4a, 0x2, 0x2, 0x2a6, 0x2a5, 0x3, 0x2, 0x2, 0x2, 0x2a7, 0x2aa, 0x3, 0x2, 0x2, 0x2, 0x2a8, 0x2a6, 0x3, 0x2, 0x2, 0x2, 0x2a8, 0x2a9, 0x3, 0x2, 0x2, 0x2, 0x2a9, 0x2ab, 0x3, 0x2, 0x2, 0x2, 0x2aa, 0x2a8, 0x3, 0x2, 0x2, 0x2, 0x2ab, 0x2ac, 0x7, 0x52, 0x2, 0x2, 0x2ac, 0x2ae, 0x3, 0x2, 0x2, 0x2, 0x2ad, 0x299, 0x3, 0x2, 0x2, 0x2, 0x2ad, 0x2a1, 0x3, 0x2, 0x2, 0x2, 0x2ae, 0xa9, 0x3, 0x2, 0x2, 0x2, 0x2af, 0x2b1, 0x7, 0x49, 0x2, 0x2, 0x2b0, 0x2b2, 0x7, 0x55, 0x2, 0x2, 0x2b1, 0x2b0, 0x3, 0x2, 0x2, 0x2, 0x2b1, 0x2b2, 0x3, 0x2, 0x2, 0x2, 0x2b2, 0x2b4, 0x3, 0x2, 0x2, 0x2, 0x2b3, 0x2af, 0x3, 0x2, 0x2, 0x2, 0x2b4, 0x2b7, 0x3, 0x2, 0x2, 0x2, 0x2b5, 0x2b3, 0x3, 0x2, 0x2, 0x2, 0x2b5, 0x2b6, 0x3, 0x2, 0x2, 0x2, 0x2b6, 0xab, 0x3, 0x2, 0x2, 0x2, 0x2b7, 0x2b5, 0x3, 0x2, 0x2, 0x2, 0x2b8, 0x2b9, 0x7, 0x7, 0x2, 0x2, 0x2b9, 0x2bc, 0x7, 0x4a, 0x2, 0x2, 0x2ba, 0x2bd, 0x5, 0xaa, 0x56, 0x2, 0x2bb, 0x2bd, 0x7, 0x3, 0x2, 0x2, 0x2bc, 0x2ba, 0x3, 0x2, 0x2, 0x2, 0x2bc, 0x2bb, 0x3, 0x2, 0x2, 0x2, 0x2bd, 0x2be, 0x3, 0x2, 0x2, 0x2, 0x2be, 0x2bf, 0x7, 0x4a, 0x2, 0x2, 0x2bf, 0x2d5, 0x5, 0xbc, 0x5f, 0x2, 0x2c0, 0x2c1, 0x7, 0x7, 0x2, 0x2, 0x2c1, 0x2c4, 0x7, 0x4a, 0x2, 0x2, 0x2c2, 0x2c5, 0x5, 0xaa, 0x56, 0x2, 0x2c3, 0x2c5, 0x7, 0x3, 0x2, 0x2, 0x2c4, 0x2c2, 0x3, 0x2, 0x2, 0x2, 0x2c4, 0x2c3, 0x3, 0x2, 0x2, 0x2, 0x2c5, 0x2c9, 0x3, 0x2, 0x2, 0x2, 0x2c6, 0x2c8, 0x7, 0x4a, 0x2, 0x2, 0x2c7, 0x2c6, 0x3, 0x2, 0x2, 0x2, 0x2c8, 0x2cb, 0x3, 0x2, 0x2, 0x2, 0x2c9, 0x2c7, 0x3, 0x2, 0x2, 0x2, 0x2c9, 0x2ca, 0x3, 0x2, 0x2, 0x2, 0x2ca, 0x2d5, 0x3, 0x2, 0x2, 0x2, 0x2cb, 0x2c9, 0x3, 0x2, 0x2, 0x2, 0x2cc, 0x2cd, 0x7, 0x7, 0x2, 0x2, 0x2cd, 0x2d0, 0x7, 0x4a, 0x2, 0x2, 0x2ce, 0x2d1, 0x5, 0xaa, 0x56, 0x2, 0x2cf, 0x2d1, 0x7, 0x3, 0x2, 0x2, 0x2d0, 0x2ce, 0x3, 0x2, 0x2, 0x2, 0x2d0, 0x2cf, 0x3, 0x2, 0x2, 0x2, 0x2d1, 0x2d2, 0x3, 0x2, 0x2, 0x2, 0x2d2, 0x2d3, 0x7, 0x6, 0x2, 0x2, 0x2d3, 0x2d5, 0x5, 0xbc, 0x5f, 0x2, 0x2d4, 0x2b8, 0x3, 0x2, 0x2, 0x2, 0x2d4, 0x2c0, 0x3, 0x2, 0x2, 0x2, 0x2d4, 0x2cc, 0x3, 0x2, 0x2, 0x2, 0x2d5, 0xad, 0x3, 0x2, 0x2, 0x2, 0x2d6, 0x2d7, 0x7, 0x7, 0x2, 0x2, 0x2d7, 0x2da, 0x7, 0x4a, 0x2, 0x2, 0x2d8, 0x2db, 0x5, 0xaa, 0x56, 0x2, 0x2d9, 0x2db, 0x7, 0x3, 0x2, 0x2, 0x2da, 0x2d8, 0x3, 0x2, 0x2, 0x2, 0x2da, 0x2d9, 0x3, 0x2, 0x2, 0x2, 0x2db, 0x2dc, 0x3, 0x2, 0x2, 0x2, 0x2dc, 0x2dd, 0x5, 0xb2, 0x5a, 0x2, 0x2dd, 0x2de, 0x7, 0x4a, 0x2, 0x2, 0x2de, 0x2df, 0x5, 0xbc, 0x5f, 0x2, 0x2df, 0x2e8, 0x3, 0x2, 0x2, 0x2, 0x2e0, 0x2e1, 0x7, 0x7, 0x2, 0x2, 0x2e1, 0x2e4, 0x7, 0x4a, 0x2, 0x2, 0x2e2, 0x2e5, 0x5, 0xaa, 0x56, 0x2, 0x2e3, 0x2e5, 0x7, 0x3, 0x2, 0x2, 0x2e4, 0x2e2, 0x3, 0x2, 0x2, 0x2, 0x2e4, 0x2e3, 0x3, 0x2, 0x2, 0x2, 0x2e5, 0x2e6, 0x3, 0x2, 0x2, 0x2, 0x2e6, 0x2e8, 0x5, 0xb2, 0x5a, 0x2, 0x2e7, 0x2d6, 0x3, 0x2, 0x2, 0x2, 0x2e7, 0x2e0, 0x3, 0x2, 0x2, 0x2, 0x2e8, 0xaf, 0x3, 0x2, 0x2, 0x2, 0x2e9, 0x329, 0x5, 0x46, 0x24, 0x2, 0x2ea, 0x329, 0x5, 0x48, 0x25, 0x2, 0x2eb, 0x329, 0x5, 0x20, 0x11, 0x2, 0x2ec, 0x329, 0x5, 0x28, 0x15, 0x2, 0x2ed, 0x329, 0x5, 0x2a, 0x16, 0x2, 0x2ee, 0x329, 0x5, 0x2e, 0x18, 0x2, 0x2ef, 0x329, 0x5, 0x3a, 0x1e, 0x2, 0x2f0, 0x329, 0x5, 0x32, 0x1a, 0x2, 0x2f1, 0x329, 0x5, 0x36, 0x1c, 0x2, 0x2f2, 0x329, 0x5, 0x3c, 0x1f, 0x2, 0x2f3, 0x329, 0x5, 0x1c, 0xf, 0x2, 0x2f4, 0x329, 0x5, 0x3e, 0x20, 0x2, 0x2f5, 0x329, 0x5, 0x26, 0x14, 0x2, 0x2f6, 0x329, 0x5, 0x76, 0x3c, 0x2, 0x2f7, 0x329, 0x5, 0x78, 0x3d, 0x2, 0x2f8, 0x329, 0x5, 0x1e, 0x10, 0x2, 0x2f9, 0x329, 0x5, 0x74, 0x3b, 0x2, 0x2fa, 0x329, 0x5, 0x72, 0x3a, 0x2, 0x2fb, 0x329, 0x5, 0x7a, 0x3e, 0x2, 0x2fc, 0x329, 0x5, 0x7c, 0x3f, 0x2, 0x2fd, 0x329, 0x5, 0x7e, 0x40, 0x2, 0x2fe, 0x329, 0x5, 0x80, 0x41, 0x2, 0x2ff, 0x329, 0x5, 0x4a, 0x26, 0x2, 0x300, 0x329, 0x5, 0x4c, 0x27, 0x2, 0x301, 0x329, 0x5, 0x4e, 0x28, 0x2, 0x302, 0x329, 0x5, 0x50, 0x29, 0x2, 0x303, 0x329, 0x5, 0x52, 0x2a, 0x2, 0x304, 0x329, 0x5, 0x54, 0x2b, 0x2, 0x305, 0x329, 0x5, 0x56, 0x2c, 0x2, 0x306, 0x329, 0x5, 0x66, 0x34, 0x2, 0x307, 0x329, 0x5, 0x68, 0x35, 0x2, 0x308, 0x329, 0x5, 0x6a, 0x36, 0x2, 0x309, 0x329, 0x5, 0x6c, 0x37, 0x2, 0x30a, 0x329, 0x5, 0x6e, 0x38, 0x2, 0x30b, 0x329, 0x5, 0x70, 0x39, 0x2, 0x30c, 0x329, 0x5, 0x82, 0x42, 0x2, 0x30d, 0x329, 0x5, 0x58, 0x2d, 0x2, 0x30e, 0x329, 0x5, 0x5a, 0x2e, 0x2, 0x30f, 0x329, 0x5, 0x5c, 0x2f, 0x2, 0x310, 0x329, 0x5, 0x5e, 0x30, 0x2, 0x311, 0x329, 0x5, 0x60, 0x31, 0x2, 0x312, 0x329, 0x5, 0x62, 0x32, 0x2, 0x313, 0x329, 0x5, 0x64, 0x33, 0x2, 0x314, 0x329, 0x5, 0x22, 0x12, 0x2, 0x315, 0x329, 0x5, 0x24, 0x13, 0x2, 0x316, 0x329, 0x5, 0x94, 0x4b, 0x2, 0x317, 0x329, 0x5, 0x96, 0x4c, 0x2, 0x318, 0x329, 0x5, 0x84, 0x43, 0x2, 0x319, 0x329, 0x5, 0x86, 0x44, 0x2, 0x31a, 0x329, 0x5, 0x88, 0x45, 0x2, 0x31b, 0x329, 0x5, 0x8a, 0x46, 0x2, 0x31c, 0x329, 0x5, 0x8c, 0x47, 0x2, 0x31d, 0x329, 0x5, 0x8e, 0x48, 0x2, 0x31e, 0x329, 0x5, 0x90, 0x49, 0x2, 0x31f, 0x329, 0x5, 0x92, 0x4a, 0x2, 0x320, 0x329, 0x5, 0x98, 0x4d, 0x2, 0x321, 0x329, 0x5, 0x9a, 0x4e, 0x2, 0x322, 0x329, 0x5, 0x9c, 0x4f, 0x2, 0x323, 0x329, 0x5, 0x9e, 0x50, 0x2, 0x324, 0x329, 0x5, 0xae, 0x58, 0x2, 0x325, 0x329, 0x5, 0xac, 0x57, 0x2, 0x326, 0x329, 0x5, 0x16, 0xc, 0x2, 0x327, 0x329, 0x5, 0x18, 0xd, 0x2, 0x328, 0x2e9, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ea, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2eb, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ec, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ed, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ee, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ef, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f0, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f1, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f2, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f3, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f4, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f5, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f6, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f7, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f8, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2f9, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2fa, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2fb, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2fc, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2fd, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2fe, 0x3, 0x2, 0x2, 0x2, 0x328, 0x2ff, 0x3, 0x2, 0x2, 0x2, 0x328, 0x300, 0x3, 0x2, 0x2, 0x2, 0x328, 0x301, 0x3, 0x2, 0x2, 0x2, 0x328, 0x302, 0x3, 0x2, 0x2, 0x2, 0x328, 0x303, 0x3, 0x2, 0x2, 0x2, 0x328, 0x304, 0x3, 0x2, 0x2, 0x2, 0x328, 0x305, 0x3, 0x2, 0x2, 0x2, 0x328, 0x306, 0x3, 0x2, 0x2, 0x2, 0x328, 0x307, 0x3, 0x2, 0x2, 0x2, 0x328, 0x308, 0x3, 0x2, 0x2, 0x2, 0x328, 0x309, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30a, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30b, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30c, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30d, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30e, 0x3, 0x2, 0x2, 0x2, 0x328, 0x30f, 0x3, 0x2, 0x2, 0x2, 0x328, 0x310, 0x3, 0x2, 0x2, 0x2, 0x328, 0x311, 0x3, 0x2, 0x2, 0x2, 0x328, 0x312, 0x3, 0x2, 0x2, 0x2, 0x328, 0x313, 0x3, 0x2, 0x2, 0x2, 0x328, 0x314, 0x3, 0x2, 0x2, 0x2, 0x328, 0x315, 0x3, 0x2, 0x2, 0x2, 0x328, 0x316, 0x3, 0x2, 0x2, 0x2, 0x328, 0x317, 0x3, 0x2, 0x2, 0x2, 0x328, 0x318, 0x3, 0x2, 0x2, 0x2, 0x328, 0x319, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31a, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31b, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31c, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31d, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31e, 0x3, 0x2, 0x2, 0x2, 0x328, 0x31f, 0x3, 0x2, 0x2, 0x2, 0x328, 0x320, 0x3, 0x2, 0x2, 0x2, 0x328, 0x321, 0x3, 0x2, 0x2, 0x2, 0x328, 0x322, 0x3, 0x2, 0x2, 0x2, 0x328, 0x323, 0x3, 0x2, 0x2, 0x2, 0x328, 0x324, 0x3, 0x2, 0x2, 0x2, 0x328, 0x325, 0x3, 0x2, 0x2, 0x2, 0x328, 0x326, 0x3, 0x2, 0x2, 0x2, 0x328, 0x327, 0x3, 0x2, 0x2, 0x2, 0x329, 0xb1, 0x3, 0x2, 0x2, 0x2, 0x32a, 0x365, 0x7, 0x56, 0x2, 0x2, 0x32b, 0x32d, 0x7, 0x4a, 0x2, 0x2, 0x32c, 0x32b, 0x3, 0x2, 0x2, 0x2, 0x32d, 0x330, 0x3, 0x2, 0x2, 0x2, 0x32e, 0x32c, 0x3, 0x2, 0x2, 0x2, 0x32e, 0x32f, 0x3, 0x2, 0x2, 0x2, 0x32f, 0x331, 0x3, 0x2, 0x2, 0x2, 0x330, 0x32e, 0x3, 0x2, 0x2, 0x2, 0x331, 0x335, 0x7, 0x49, 0x2, 0x2, 0x332, 0x334, 0x7, 0x4a, 0x2, 0x2, 0x333, 0x332, 0x3, 0x2, 0x2, 0x2, 0x334, 0x337, 0x3, 0x2, 0x2, 0x2, 0x335, 0x333, 0x3, 0x2, 0x2, 0x2, 0x335, 0x336, 0x3, 0x2, 0x2, 0x2, 0x336, 0x341, 0x3, 0x2, 0x2, 0x2, 0x337, 0x335, 0x3, 0x2, 0x2, 0x2, 0x338, 0x33c, 0x7, 0x59, 0x2, 0x2, 0x339, 0x33b, 0x5, 0xc8, 0x65, 0x2, 0x33a, 0x339, 0x3, 0x2, 0x2, 0x2, 0x33b, 0x33e, 0x3, 0x2, 0x2, 0x2, 0x33c, 0x33a, 0x3, 0x2, 0x2, 0x2, 0x33c, 0x33d, 0x3, 0x2, 0x2, 0x2, 0x33d, 0x340, 0x3, 0x2, 0x2, 0x2, 0x33e, 0x33c, 0x3, 0x2, 0x2, 0x2, 0x33f, 0x338, 0x3, 0x2, 0x2, 0x2, 0x340, 0x343, 0x3, 0x2, 0x2, 0x2, 0x341, 0x33f, 0x3, 0x2, 0x2, 0x2, 0x341, 0x342, 0x3, 0x2, 0x2, 0x2, 0x342, 0x360, 0x3, 0x2, 0x2, 0x2, 0x343, 0x341, 0x3, 0x2, 0x2, 0x2, 0x344, 0x348, 0x7, 0x58, 0x2, 0x2, 0x345, 0x347, 0x7, 0x4a, 0x2, 0x2, 0x346, 0x345, 0x3, 0x2, 0x2, 0x2, 0x347, 0x34a, 0x3, 0x2, 0x2, 0x2, 0x348, 0x346, 0x3, 0x2, 0x2, 0x2, 0x348, 0x349, 0x3, 0x2, 0x2, 0x2, 0x349, 0x34b, 0x3, 0x2, 0x2, 0x2, 0x34a, 0x348, 0x3, 0x2, 0x2, 0x2, 0x34b, 0x34f, 0x7, 0x49, 0x2, 0x2, 0x34c, 0x34e, 0x7, 0x4a, 0x2, 0x2, 0x34d, 0x34c, 0x3, 0x2, 0x2, 0x2, 0x34e, 0x351, 0x3, 0x2, 0x2, 0x2, 0x34f, 0x34d, 0x3, 0x2, 0x2, 0x2, 0x34f, 0x350, 0x3, 0x2, 0x2, 0x2, 0x350, 0x35b, 0x3, 0x2, 0x2, 0x2, 0x351, 0x34f, 0x3, 0x2, 0x2, 0x2, 0x352, 0x356, 0x7, 0x59, 0x2, 0x2, 0x353, 0x355, 0x5, 0xc8, 0x65, 0x2, 0x354, 0x353, 0x3, 0x2, 0x2, 0x2, 0x355, 0x358, 0x3, 0x2, 0x2, 0x2, 0x356, 0x354, 0x3, 0x2, 0x2, 0x2, 0x356, 0x357, 0x3, 0x2, 0x2, 0x2, 0x357, 0x35a, 0x3, 0x2, 0x2, 0x2, 0x358, 0x356, 0x3, 0x2, 0x2, 0x2, 0x359, 0x352, 0x3, 0x2, 0x2, 0x2, 0x35a, 0x35d, 0x3, 0x2, 0x2, 0x2, 0x35b, 0x359, 0x3, 0x2, 0x2, 0x2, 0x35b, 0x35c, 0x3, 0x2, 0x2, 0x2, 0x35c, 0x35f, 0x3, 0x2, 0x2, 0x2, 0x35d, 0x35b, 0x3, 0x2, 0x2, 0x2, 0x35e, 0x344, 0x3, 0x2, 0x2, 0x2, 0x35f, 0x362, 0x3, 0x2, 0x2, 0x2, 0x360, 0x35e, 0x3, 0x2, 0x2, 0x2, 0x360, 0x361, 0x3, 0x2, 0x2, 0x2, 0x361, 0x364, 0x3, 0x2, 0x2, 0x2, 0x362, 0x360, 0x3, 0x2, 0x2, 0x2, 0x363, 0x32e, 0x3, 0x2, 0x2, 0x2, 0x364, 0x367, 0x3, 0x2, 0x2, 0x2, 0x365, 0x363, 0x3, 0x2, 0x2, 0x2, 0x365, 0x366, 0x3, 0x2, 0x2, 0x2, 0x366, 0x368, 0x3, 0x2, 0x2, 0x2, 0x367, 0x365, 0x3, 0x2, 0x2, 0x2, 0x368, 0x369, 0x7, 0x57, 0x2, 0x2, 0x369, 0xb3, 0x3, 0x2, 0x2, 0x2, 0x36a, 0x36d, 0x5, 0xb6, 0x5c, 0x2, 0x36b, 0x36d, 0x5, 0xb8, 0x5d, 0x2, 0x36c, 0x36a, 0x3, 0x2, 0x2, 0x2, 0x36c, 0x36b, 0x3, 0x2, 0x2, 0x2, 0x36d, 0xb5, 0x3, 0x2, 0x2, 0x2, 0x36e, 0x38c, 0x5, 0xe, 0x8, 0x2, 0x36f, 0x38c, 0x7, 0x46, 0x2, 0x2, 0x370, 0x38c, 0x7, 0x47, 0x2, 0x2, 0x371, 0x38c, 0x5, 0xa, 0x6, 0x2, 0x372, 0x38c, 0x7, 0x49, 0x2, 0x2, 0x373, 0x38c, 0x5, 0x14, 0xb, 0x2, 0x374, 0x38c, 0x7, 0x50, 0x2, 0x2, 0x375, 0x38c, 0x5, 0x16, 0xc, 0x2, 0x376, 0x38c, 0x5, 0x18, 0xd, 0x2, 0x377, 0x38c, 0x7, 0x51, 0x2, 0x2, 0x378, 0x38c, 0x7, 0x56, 0x2, 0x2, 0x379, 0x38c, 0x7, 0x57, 0x2, 0x2, 0x37a, 0x38c, 0x7, 0x58, 0x2, 0x2, 0x37b, 0x38c, 0x7, 0x59, 0x2, 0x2, 0x37c, 0x38c, 0x7, 0x5a, 0x2, 0x2, 0x37d, 0x38c, 0x7, 0x6, 0x2, 0x2, 0x37e, 0x38c, 0x5, 0xb0, 0x59, 0x2, 0x37f, 0x38c, 0x7, 0x4a, 0x2, 0x2, 0x380, 0x38c, 0x7, 0x4f, 0x2, 0x2, 0x381, 0x38c, 0x7, 0x48, 0x2, 0x2, 0x382, 0x38c, 0x5, 0x12, 0xa, 0x2, 0x383, 0x38c, 0x7, 0x53, 0x2, 0x2, 0x384, 0x38c, 0x7, 0x54, 0x2, 0x2, 0x385, 0x38c, 0x7, 0x55, 0x2, 0x2, 0x386, 0x38c, 0x7, 0x5f, 0x2, 0x2, 0x387, 0x38c, 0x7, 0x5b, 0x2, 0x2, 0x388, 0x38c, 0x7, 0x5c, 0x2, 0x2, 0x389, 0x38c, 0x7, 0x5d, 0x2, 0x2, 0x38a, 0x38c, 0x7, 0x5e, 0x2, 0x2, 0x38b, 0x36e, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x36f, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x370, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x371, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x372, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x373, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x374, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x375, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x376, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x377, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x378, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x379, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37a, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37b, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37c, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37d, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37e, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x37f, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x380, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x381, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x382, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x383, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x384, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x385, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x386, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x387, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x388, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x389, 0x3, 0x2, 0x2, 0x2, 0x38b, 0x38a, 0x3, 0x2, 0x2, 0x2, 0x38c, 0x38f, 0x3, 0x2, 0x2, 0x2, 0x38d, 0x38e, 0x3, 0x2, 0x2, 0x2, 0x38d, 0x38b, 0x3, 0x2, 0x2, 0x2, 0x38e, 0x390, 0x3, 0x2, 0x2, 0x2, 0x38f, 0x38d, 0x3, 0x2, 0x2, 0x2, 0x390, 0x394, 0x7, 0x51, 0x2, 0x2, 0x391, 0x393, 0x7, 0x4a, 0x2, 0x2, 0x392, 0x391, 0x3, 0x2, 0x2, 0x2, 0x393, 0x396, 0x3, 0x2, 0x2, 0x2, 0x394, 0x392, 0x3, 0x2, 0x2, 0x2, 0x394, 0x395, 0x3, 0x2, 0x2, 0x2, 0x395, 0x397, 0x3, 0x2, 0x2, 0x2, 0x396, 0x394, 0x3, 0x2, 0x2, 0x2, 0x397, 0x398, 0x9, 0x6, 0x2, 0x2, 0x398, 0xb7, 0x3, 0x2, 0x2, 0x2, 0x399, 0x3b7, 0x5, 0xe, 0x8, 0x2, 0x39a, 0x3b7, 0x7, 0x46, 0x2, 0x2, 0x39b, 0x3b7, 0x7, 0x47, 0x2, 0x2, 0x39c, 0x3b7, 0x5, 0xa, 0x6, 0x2, 0x39d, 0x3b7, 0x7, 0x49, 0x2, 0x2, 0x39e, 0x3b7, 0x5, 0x14, 0xb, 0x2, 0x39f, 0x3b7, 0x7, 0x50, 0x2, 0x2, 0x3a0, 0x3b7, 0x5, 0x16, 0xc, 0x2, 0x3a1, 0x3b7, 0x5, 0x18, 0xd, 0x2, 0x3a2, 0x3b7, 0x7, 0x51, 0x2, 0x2, 0x3a3, 0x3b7, 0x7, 0x56, 0x2, 0x2, 0x3a4, 0x3b7, 0x7, 0x57, 0x2, 0x2, 0x3a5, 0x3b7, 0x7, 0x58, 0x2, 0x2, 0x3a6, 0x3b7, 0x7, 0x59, 0x2, 0x2, 0x3a7, 0x3b7, 0x7, 0x5a, 0x2, 0x2, 0x3a8, 0x3b7, 0x7, 0x6, 0x2, 0x2, 0x3a9, 0x3b7, 0x5, 0xb0, 0x59, 0x2, 0x3aa, 0x3b7, 0x7, 0x4a, 0x2, 0x2, 0x3ab, 0x3b7, 0x7, 0x4f, 0x2, 0x2, 0x3ac, 0x3b7, 0x7, 0x48, 0x2, 0x2, 0x3ad, 0x3b7, 0x5, 0x12, 0xa, 0x2, 0x3ae, 0x3b7, 0x7, 0x53, 0x2, 0x2, 0x3af, 0x3b7, 0x7, 0x54, 0x2, 0x2, 0x3b0, 0x3b7, 0x7, 0x55, 0x2, 0x2, 0x3b1, 0x3b7, 0x7, 0x5f, 0x2, 0x2, 0x3b2, 0x3b7, 0x7, 0x5b, 0x2, 0x2, 0x3b3, 0x3b7, 0x7, 0x5c, 0x2, 0x2, 0x3b4, 0x3b7, 0x7, 0x5d, 0x2, 0x2, 0x3b5, 0x3b7, 0x7, 0x5e, 0x2, 0x2, 0x3b6, 0x399, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39a, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39b, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39c, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39d, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39e, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x39f, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a0, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a1, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a2, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a3, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a4, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a5, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a6, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a7, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a8, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3a9, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3aa, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3ab, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3ac, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3ad, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3ae, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3af, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b0, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b1, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b2, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b3, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b4, 0x3, 0x2, 0x2, 0x2, 0x3b6, 0x3b5, 0x3, 0x2, 0x2, 0x2, 0x3b7, 0x3ba, 0x3, 0x2, 0x2, 0x2, 0x3b8, 0x3b9, 0x3, 0x2, 0x2, 0x2, 0x3b8, 0x3b6, 0x3, 0x2, 0x2, 0x2, 0x3b9, 0x3c3, 0x3, 0x2, 0x2, 0x2, 0x3ba, 0x3b8, 0x3, 0x2, 0x2, 0x2, 0x3bb, 0x3bf, 0x7, 0x52, 0x2, 0x2, 0x3bc, 0x3be, 0x7, 0x4a, 0x2, 0x2, 0x3bd, 0x3bc, 0x3, 0x2, 0x2, 0x2, 0x3be, 0x3c1, 0x3, 0x2, 0x2, 0x2, 0x3bf, 0x3bd, 0x3, 0x2, 0x2, 0x2, 0x3bf, 0x3c0, 0x3, 0x2, 0x2, 0x2, 0x3c0, 0x3c4, 0x3, 0x2, 0x2, 0x2, 0x3c1, 0x3bf, 0x3, 0x2, 0x2, 0x2, 0x3c2, 0x3c4, 0x7, 0x2, 0x2, 0x3, 0x3c3, 0x3bb, 0x3, 0x2, 0x2, 0x2, 0x3c3, 0x3c2, 0x3, 0x2, 0x2, 0x2, 0x3c4, 0xb9, 0x3, 0x2, 0x2, 0x2, 0x3c5, 0x3e3, 0x5, 0xe, 0x8, 0x2, 0x3c6, 0x3e3, 0x7, 0x46, 0x2, 0x2, 0x3c7, 0x3e3, 0x7, 0x47, 0x2, 0x2, 0x3c8, 0x3e3, 0x5, 0xa, 0x6, 0x2, 0x3c9, 0x3e3, 0x7, 0x49, 0x2, 0x2, 0x3ca, 0x3e3, 0x5, 0x14, 0xb, 0x2, 0x3cb, 0x3e3, 0x5, 0x16, 0xc, 0x2, 0x3cc, 0x3e3, 0x5, 0x18, 0xd, 0x2, 0x3cd, 0x3e3, 0x7, 0x50, 0x2, 0x2, 0x3ce, 0x3e3, 0x7, 0x56, 0x2, 0x2, 0x3cf, 0x3e3, 0x7, 0x57, 0x2, 0x2, 0x3d0, 0x3e3, 0x7, 0x58, 0x2, 0x2, 0x3d1, 0x3e3, 0x7, 0x59, 0x2, 0x2, 0x3d2, 0x3e3, 0x7, 0x5a, 0x2, 0x2, 0x3d3, 0x3e3, 0x7, 0x6, 0x2, 0x2, 0x3d4, 0x3e3, 0x7, 0x4a, 0x2, 0x2, 0x3d5, 0x3e3, 0x7, 0x4f, 0x2, 0x2, 0x3d6, 0x3e3, 0x7, 0x48, 0x2, 0x2, 0x3d7, 0x3e3, 0x5, 0x12, 0xa, 0x2, 0x3d8, 0x3e3, 0x7, 0x53, 0x2, 0x2, 0x3d9, 0x3e3, 0x7, 0x54, 0x2, 0x2, 0x3da, 0x3e3, 0x7, 0x55, 0x2, 0x2, 0x3db, 0x3e3, 0x7, 0x5f, 0x2, 0x2, 0x3dc, 0x3e3, 0x7, 0x5b, 0x2, 0x2, 0x3dd, 0x3e3, 0x7, 0x5c, 0x2, 0x2, 0x3de, 0x3e3, 0x7, 0x5d, 0x2, 0x2, 0x3df, 0x3e3, 0x7, 0x5e, 0x2, 0x2, 0x3e0, 0x3e3, 0x7, 0x12, 0x2, 0x2, 0x3e1, 0x3e3, 0x5, 0xb0, 0x59, 0x2, 0x3e2, 0x3c5, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3c6, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3c7, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3c8, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3c9, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3ca, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3cb, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3cc, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3cd, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3ce, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3cf, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d0, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d1, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d2, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d3, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d4, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d5, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d6, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d7, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d8, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3d9, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3da, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3db, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3dc, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3dd, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3de, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3df, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3e0, 0x3, 0x2, 0x2, 0x2, 0x3e2, 0x3e1, 0x3, 0x2, 0x2, 0x2, 0x3e3, 0x3e6, 0x3, 0x2, 0x2, 0x2, 0x3e4, 0x3e5, 0x3, 0x2, 0x2, 0x2, 0x3e4, 0x3e2, 0x3, 0x2, 0x2, 0x2, 0x3e5, 0xbb, 0x3, 0x2, 0x2, 0x2, 0x3e6, 0x3e4, 0x3, 0x2, 0x2, 0x2, 0x3e7, 0x403, 0x5, 0xe, 0x8, 0x2, 0x3e8, 0x403, 0x7, 0x46, 0x2, 0x2, 0x3e9, 0x403, 0x7, 0x47, 0x2, 0x2, 0x3ea, 0x403, 0x5, 0xa, 0x6, 0x2, 0x3eb, 0x403, 0x7, 0x49, 0x2, 0x2, 0x3ec, 0x403, 0x5, 0x14, 0xb, 0x2, 0x3ed, 0x403, 0x5, 0x16, 0xc, 0x2, 0x3ee, 0x403, 0x5, 0x18, 0xd, 0x2, 0x3ef, 0x403, 0x7, 0x50, 0x2, 0x2, 0x3f0, 0x403, 0x7, 0x56, 0x2, 0x2, 0x3f1, 0x403, 0x7, 0x57, 0x2, 0x2, 0x3f2, 0x403, 0x7, 0x58, 0x2, 0x2, 0x3f3, 0x403, 0x7, 0x59, 0x2, 0x2, 0x3f4, 0x403, 0x7, 0x5a, 0x2, 0x2, 0x3f5, 0x403, 0x7, 0x6, 0x2, 0x2, 0x3f6, 0x403, 0x7, 0x4a, 0x2, 0x2, 0x3f7, 0x403, 0x7, 0x4f, 0x2, 0x2, 0x3f8, 0x403, 0x7, 0x48, 0x2, 0x2, 0x3f9, 0x403, 0x5, 0x12, 0xa, 0x2, 0x3fa, 0x403, 0x7, 0x53, 0x2, 0x2, 0x3fb, 0x403, 0x7, 0x54, 0x2, 0x2, 0x3fc, 0x403, 0x7, 0x55, 0x2, 0x2, 0x3fd, 0x403, 0x7, 0x5f, 0x2, 0x2, 0x3fe, 0x403, 0x7, 0x5b, 0x2, 0x2, 0x3ff, 0x403, 0x7, 0x5c, 0x2, 0x2, 0x400, 0x403, 0x7, 0x5d, 0x2, 0x2, 0x401, 0x403, 0x7, 0x5e, 0x2, 0x2, 0x402, 0x3e7, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3e8, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3e9, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ea, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3eb, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ec, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ed, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ee, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ef, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f0, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f1, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f2, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f3, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f4, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f5, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f6, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f7, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f8, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3f9, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3fa, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3fb, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3fc, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3fd, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3fe, 0x3, 0x2, 0x2, 0x2, 0x402, 0x3ff, 0x3, 0x2, 0x2, 0x2, 0x402, 0x400, 0x3, 0x2, 0x2, 0x2, 0x402, 0x401, 0x3, 0x2, 0x2, 0x2, 0x403, 0x406, 0x3, 0x2, 0x2, 0x2, 0x404, 0x405, 0x3, 0x2, 0x2, 0x2, 0x404, 0x402, 0x3, 0x2, 0x2, 0x2, 0x405, 0xbd, 0x3, 0x2, 0x2, 0x2, 0x406, 0x404, 0x3, 0x2, 0x2, 0x2, 0x407, 0x41b, 0x7, 0x49, 0x2, 0x2, 0x408, 0x41b, 0x5, 0x14, 0xb, 0x2, 0x409, 0x41b, 0x7, 0x4a, 0x2, 0x2, 0x40a, 0x41b, 0x7, 0x4f, 0x2, 0x2, 0x40b, 0x41b, 0x7, 0x48, 0x2, 0x2, 0x40c, 0x41b, 0x7, 0x5b, 0x2, 0x2, 0x40d, 0x41b, 0x7, 0x5c, 0x2, 0x2, 0x40e, 0x41b, 0x7, 0x5d, 0x2, 0x2, 0x40f, 0x41b, 0x7, 0x5e, 0x2, 0x2, 0x410, 0x41b, 0x7, 0x56, 0x2, 0x2, 0x411, 0x41b, 0x7, 0x57, 0x2, 0x2, 0x412, 0x41b, 0x7, 0x58, 0x2, 0x2, 0x413, 0x41b, 0x7, 0x59, 0x2, 0x2, 0x414, 0x41b, 0x7, 0x5a, 0x2, 0x2, 0x415, 0x41b, 0x5, 0xa, 0x6, 0x2, 0x416, 0x41b, 0x5, 0x16, 0xc, 0x2, 0x417, 0x41b, 0x5, 0x18, 0xd, 0x2, 0x418, 0x41b, 0x7, 0x5f, 0x2, 0x2, 0x419, 0x41b, 0x7, 0x60, 0x2, 0x2, 0x41a, 0x407, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x408, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x409, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40a, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40b, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40c, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40d, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40e, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x40f, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x410, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x411, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x412, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x413, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x414, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x415, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x416, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x417, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x418, 0x3, 0x2, 0x2, 0x2, 0x41a, 0x419, 0x3, 0x2, 0x2, 0x2, 0x41b, 0xbf, 0x3, 0x2, 0x2, 0x2, 0x41c, 0x430, 0x7, 0x49, 0x2, 0x2, 0x41d, 0x430, 0x5, 0x14, 0xb, 0x2, 0x41e, 0x430, 0x7, 0x4a, 0x2, 0x2, 0x41f, 0x430, 0x7, 0x4f, 0x2, 0x2, 0x420, 0x430, 0x7, 0x48, 0x2, 0x2, 0x421, 0x430, 0x5, 0xc2, 0x62, 0x2, 0x422, 0x430, 0x7, 0x59, 0x2, 0x2, 0x423, 0x430, 0x7, 0x5a, 0x2, 0x2, 0x424, 0x430, 0x5, 0xc, 0x7, 0x2, 0x425, 0x430, 0x7, 0x52, 0x2, 0x2, 0x426, 0x430, 0x7, 0x50, 0x2, 0x2, 0x427, 0x430, 0x5, 0xa, 0x6, 0x2, 0x428, 0x430, 0x5, 0xae, 0x58, 0x2, 0x429, 0x430, 0x5, 0xac, 0x57, 0x2, 0x42a, 0x430, 0x5, 0x12, 0xa, 0x2, 0x42b, 0x430, 0x5, 0x16, 0xc, 0x2, 0x42c, 0x430, 0x5, 0x18, 0xd, 0x2, 0x42d, 0x430, 0x7, 0x5f, 0x2, 0x2, 0x42e, 0x430, 0x7, 0x60, 0x2, 0x2, 0x42f, 0x41c, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x41d, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x41e, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x41f, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x420, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x421, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x422, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x423, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x424, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x425, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x426, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x427, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x428, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x429, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x42a, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x42b, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x42c, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x42d, 0x3, 0x2, 0x2, 0x2, 0x42f, 0x42e, 0x3, 0x2, 0x2, 0x2, 0x430, 0xc1, 0x3, 0x2, 0x2, 0x2, 0x431, 0x444, 0x7, 0x56, 0x2, 0x2, 0x432, 0x443, 0x7, 0x49, 0x2, 0x2, 0x433, 0x443, 0x5, 0x14, 0xb, 0x2, 0x434, 0x443, 0x7, 0x4a, 0x2, 0x2, 0x435, 0x443, 0x7, 0x4f, 0x2, 0x2, 0x436, 0x443, 0x7, 0x48, 0x2, 0x2, 0x437, 0x443, 0x7, 0x58, 0x2, 0x2, 0x438, 0x443, 0x7, 0x59, 0x2, 0x2, 0x439, 0x443, 0x7, 0x5a, 0x2, 0x2, 0x43a, 0x443, 0x5, 0xc, 0x7, 0x2, 0x43b, 0x443, 0x7, 0x50, 0x2, 0x2, 0x43c, 0x443, 0x7, 0x52, 0x2, 0x2, 0x43d, 0x443, 0x5, 0xc2, 0x62, 0x2, 0x43e, 0x443, 0x5, 0xa, 0x6, 0x2, 0x43f, 0x443, 0x5, 0x12, 0xa, 0x2, 0x440, 0x443, 0x7, 0x5f, 0x2, 0x2, 0x441, 0x443, 0x7, 0x60, 0x2, 0x2, 0x442, 0x432, 0x3, 0x2, 0x2, 0x2, 0x442, 0x433, 0x3, 0x2, 0x2, 0x2, 0x442, 0x434, 0x3, 0x2, 0x2, 0x2, 0x442, 0x435, 0x3, 0x2, 0x2, 0x2, 0x442, 0x436, 0x3, 0x2, 0x2, 0x2, 0x442, 0x437, 0x3, 0x2, 0x2, 0x2, 0x442, 0x438, 0x3, 0x2, 0x2, 0x2, 0x442, 0x439, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43a, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43b, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43c, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43d, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43e, 0x3, 0x2, 0x2, 0x2, 0x442, 0x43f, 0x3, 0x2, 0x2, 0x2, 0x442, 0x440, 0x3, 0x2, 0x2, 0x2, 0x442, 0x441, 0x3, 0x2, 0x2, 0x2, 0x443, 0x446, 0x3, 0x2, 0x2, 0x2, 0x444, 0x442, 0x3, 0x2, 0x2, 0x2, 0x444, 0x445, 0x3, 0x2, 0x2, 0x2, 0x445, 0x447, 0x3, 0x2, 0x2, 0x2, 0x446, 0x444, 0x3, 0x2, 0x2, 0x2, 0x447, 0x475, 0x7, 0x57, 0x2, 0x2, 0x448, 0x45a, 0x7, 0x5b, 0x2, 0x2, 0x449, 0x459, 0x7, 0x49, 0x2, 0x2, 0x44a, 0x459, 0x5, 0x14, 0xb, 0x2, 0x44b, 0x459, 0x7, 0x4a, 0x2, 0x2, 0x44c, 0x459, 0x7, 0x4f, 0x2, 0x2, 0x44d, 0x459, 0x7, 0x48, 0x2, 0x2, 0x44e, 0x459, 0x7, 0x58, 0x2, 0x2, 0x44f, 0x459, 0x7, 0x59, 0x2, 0x2, 0x450, 0x459, 0x7, 0x5a, 0x2, 0x2, 0x451, 0x459, 0x5, 0xc, 0x7, 0x2, 0x452, 0x459, 0x7, 0x52, 0x2, 0x2, 0x453, 0x459, 0x5, 0xc2, 0x62, 0x2, 0x454, 0x459, 0x5, 0xa, 0x6, 0x2, 0x455, 0x459, 0x5, 0x12, 0xa, 0x2, 0x456, 0x459, 0x7, 0x5f, 0x2, 0x2, 0x457, 0x459, 0x7, 0x60, 0x2, 0x2, 0x458, 0x449, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44a, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44b, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44c, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44d, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44e, 0x3, 0x2, 0x2, 0x2, 0x458, 0x44f, 0x3, 0x2, 0x2, 0x2, 0x458, 0x450, 0x3, 0x2, 0x2, 0x2, 0x458, 0x451, 0x3, 0x2, 0x2, 0x2, 0x458, 0x452, 0x3, 0x2, 0x2, 0x2, 0x458, 0x453, 0x3, 0x2, 0x2, 0x2, 0x458, 0x454, 0x3, 0x2, 0x2, 0x2, 0x458, 0x455, 0x3, 0x2, 0x2, 0x2, 0x458, 0x456, 0x3, 0x2, 0x2, 0x2, 0x458, 0x457, 0x3, 0x2, 0x2, 0x2, 0x459, 0x45c, 0x3, 0x2, 0x2, 0x2, 0x45a, 0x458, 0x3, 0x2, 0x2, 0x2, 0x45a, 0x45b, 0x3, 0x2, 0x2, 0x2, 0x45b, 0x45d, 0x3, 0x2, 0x2, 0x2, 0x45c, 0x45a, 0x3, 0x2, 0x2, 0x2, 0x45d, 0x475, 0x7, 0x5c, 0x2, 0x2, 0x45e, 0x470, 0x7, 0x5d, 0x2, 0x2, 0x45f, 0x46f, 0x7, 0x49, 0x2, 0x2, 0x460, 0x46f, 0x5, 0x14, 0xb, 0x2, 0x461, 0x46f, 0x7, 0x4a, 0x2, 0x2, 0x462, 0x46f, 0x7, 0x4f, 0x2, 0x2, 0x463, 0x46f, 0x7, 0x48, 0x2, 0x2, 0x464, 0x46f, 0x7, 0x58, 0x2, 0x2, 0x465, 0x46f, 0x7, 0x59, 0x2, 0x2, 0x466, 0x46f, 0x7, 0x5a, 0x2, 0x2, 0x467, 0x46f, 0x5, 0xc, 0x7, 0x2, 0x468, 0x46f, 0x7, 0x52, 0x2, 0x2, 0x469, 0x46f, 0x5, 0xc2, 0x62, 0x2, 0x46a, 0x46f, 0x5, 0xa, 0x6, 0x2, 0x46b, 0x46f, 0x5, 0x12, 0xa, 0x2, 0x46c, 0x46f, 0x7, 0x5f, 0x2, 0x2, 0x46d, 0x46f, 0x7, 0x60, 0x2, 0x2, 0x46e, 0x45f, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x460, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x461, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x462, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x463, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x464, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x465, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x466, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x467, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x468, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x469, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x46a, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x46b, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x46c, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x46d, 0x3, 0x2, 0x2, 0x2, 0x46f, 0x472, 0x3, 0x2, 0x2, 0x2, 0x470, 0x46e, 0x3, 0x2, 0x2, 0x2, 0x470, 0x471, 0x3, 0x2, 0x2, 0x2, 0x471, 0x473, 0x3, 0x2, 0x2, 0x2, 0x472, 0x470, 0x3, 0x2, 0x2, 0x2, 0x473, 0x475, 0x7, 0x5e, 0x2, 0x2, 0x474, 0x431, 0x3, 0x2, 0x2, 0x2, 0x474, 0x448, 0x3, 0x2, 0x2, 0x2, 0x474, 0x45e, 0x3, 0x2, 0x2, 0x2, 0x475, 0xc3, 0x3, 0x2, 0x2, 0x2, 0x476, 0x491, 0x7, 0x49, 0x2, 0x2, 0x477, 0x491, 0x5, 0x14, 0xb, 0x2, 0x478, 0x491, 0x7, 0x52, 0x2, 0x2, 0x479, 0x491, 0x7, 0x4a, 0x2, 0x2, 0x47a, 0x491, 0x7, 0x4f, 0x2, 0x2, 0x47b, 0x491, 0x7, 0x51, 0x2, 0x2, 0x47c, 0x491, 0x7, 0x48, 0x2, 0x2, 0x47d, 0x491, 0x7, 0x56, 0x2, 0x2, 0x47e, 0x491, 0x7, 0x57, 0x2, 0x2, 0x47f, 0x491, 0x7, 0x58, 0x2, 0x2, 0x480, 0x491, 0x7, 0x59, 0x2, 0x2, 0x481, 0x491, 0x7, 0x5a, 0x2, 0x2, 0x482, 0x491, 0x7, 0x5b, 0x2, 0x2, 0x483, 0x491, 0x7, 0x5c, 0x2, 0x2, 0x484, 0x491, 0x7, 0x5d, 0x2, 0x2, 0x485, 0x491, 0x7, 0x5e, 0x2, 0x2, 0x486, 0x491, 0x7, 0x55, 0x2, 0x2, 0x487, 0x491, 0x7, 0x6, 0x2, 0x2, 0x488, 0x491, 0x7, 0x4d, 0x2, 0x2, 0x489, 0x491, 0x5, 0x16, 0xc, 0x2, 0x48a, 0x491, 0x5, 0x18, 0xd, 0x2, 0x48b, 0x491, 0x7, 0x53, 0x2, 0x2, 0x48c, 0x491, 0x7, 0x54, 0x2, 0x2, 0x48d, 0x491, 0x7, 0x50, 0x2, 0x2, 0x48e, 0x491, 0x7, 0x5f, 0x2, 0x2, 0x48f, 0x491, 0x7, 0x60, 0x2, 0x2, 0x490, 0x476, 0x3, 0x2, 0x2, 0x2, 0x490, 0x477, 0x3, 0x2, 0x2, 0x2, 0x490, 0x478, 0x3, 0x2, 0x2, 0x2, 0x490, 0x479, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47a, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47b, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47c, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47d, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47e, 0x3, 0x2, 0x2, 0x2, 0x490, 0x47f, 0x3, 0x2, 0x2, 0x2, 0x490, 0x480, 0x3, 0x2, 0x2, 0x2, 0x490, 0x481, 0x3, 0x2, 0x2, 0x2, 0x490, 0x482, 0x3, 0x2, 0x2, 0x2, 0x490, 0x483, 0x3, 0x2, 0x2, 0x2, 0x490, 0x484, 0x3, 0x2, 0x2, 0x2, 0x490, 0x485, 0x3, 0x2, 0x2, 0x2, 0x490, 0x486, 0x3, 0x2, 0x2, 0x2, 0x490, 0x487, 0x3, 0x2, 0x2, 0x2, 0x490, 0x488, 0x3, 0x2, 0x2, 0x2, 0x490, 0x489, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48a, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48b, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48c, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48d, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48e, 0x3, 0x2, 0x2, 0x2, 0x490, 0x48f, 0x3, 0x2, 0x2, 0x2, 0x491, 0xc5, 0x3, 0x2, 0x2, 0x2, 0x492, 0x493, 0x7, 0x48, 0x2, 0x2, 0x493, 0xc7, 0x3, 0x2, 0x2, 0x2, 0x494, 0x4a3, 0x7, 0x49, 0x2, 0x2, 0x495, 0x4a3, 0x5, 0x14, 0xb, 0x2, 0x496, 0x4a3, 0x7, 0x4a, 0x2, 0x2, 0x497, 0x4a3, 0x7, 0x4f, 0x2, 0x2, 0x498, 0x4a3, 0x7, 0x48, 0x2, 0x2, 0x499, 0x4a3, 0x7, 0x5b, 0x2, 0x2, 0x49a, 0x4a3, 0x7, 0x5c, 0x2, 0x2, 0x49b, 0x4a3, 0x7, 0x5d, 0x2, 0x2, 0x49c, 0x4a3, 0x7, 0x5e, 0x2, 0x2, 0x49d, 0x4a3, 0x5, 0xc2, 0x62, 0x2, 0x49e, 0x4a3, 0x5, 0xa, 0x6, 0x2, 0x49f, 0x4a3, 0x5, 0xc, 0x7, 0x2, 0x4a0, 0x4a3, 0x7, 0x5f, 0x2, 0x2, 0x4a1, 0x4a3, 0x7, 0x60, 0x2, 0x2, 0x4a2, 0x494, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x495, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x496, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x497, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x498, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x499, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49a, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49b, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49c, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49d, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49e, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x49f, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x4a0, 0x3, 0x2, 0x2, 0x2, 0x4a2, 0x4a1, 0x3, 0x2, 0x2, 0x2, 0x4a3, 0xc9, 0x3, 0x2, 0x2, 0x2, 0x4a4, 0x4ba, 0x7, 0x49, 0x2, 0x2, 0x4a5, 0x4ba, 0x5, 0x14, 0xb, 0x2, 0x4a6, 0x4ba, 0x7, 0x4a, 0x2, 0x2, 0x4a7, 0x4ba, 0x7, 0x4f, 0x2, 0x2, 0x4a8, 0x4ba, 0x7, 0x51, 0x2, 0x2, 0x4a9, 0x4ba, 0x7, 0x56, 0x2, 0x2, 0x4aa, 0x4ba, 0x7, 0x57, 0x2, 0x2, 0x4ab, 0x4ba, 0x7, 0x58, 0x2, 0x2, 0x4ac, 0x4ba, 0x7, 0x59, 0x2, 0x2, 0x4ad, 0x4ba, 0x7, 0x5a, 0x2, 0x2, 0x4ae, 0x4ba, 0x7, 0x5b, 0x2, 0x2, 0x4af, 0x4ba, 0x7, 0x5c, 0x2, 0x2, 0x4b0, 0x4ba, 0x7, 0x5d, 0x2, 0x2, 0x4b1, 0x4ba, 0x7, 0x5e, 0x2, 0x2, 0x4b2, 0x4ba, 0x5, 0xa, 0x6, 0x2, 0x4b3, 0x4ba, 0x7, 0x4d, 0x2, 0x2, 0x4b4, 0x4ba, 0x5, 0x16, 0xc, 0x2, 0x4b5, 0x4ba, 0x5, 0x18, 0xd, 0x2, 0x4b6, 0x4ba, 0x7, 0x50, 0x2, 0x2, 0x4b7, 0x4ba, 0x7, 0x5f, 0x2, 0x2, 0x4b8, 0x4ba, 0x7, 0x60, 0x2, 0x2, 0x4b9, 0x4a4, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4a5, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4a6, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4a7, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4a8, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4a9, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4aa, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4ab, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4ac, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4ad, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4ae, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4af, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b0, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b1, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b2, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b3, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b4, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b5, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b6, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b7, 0x3, 0x2, 0x2, 0x2, 0x4b9, 0x4b8, 0x3, 0x2, 0x2, 0x2, 0x4ba, 0xcb, 0x3, 0x2, 0x2, 0x2, 0x54, 0xd3, 0x120, 0x128, 0x130, 0x136, 0x13e, 0x145, 0x14a, 0x15a, 0x162, 0x17b, 0x182, 0x189, 0x190, 0x197, 0x19e, 0x1a5, 0x1ac, 0x1b3, 0x1bb, 0x1c0, 0x1d2, 0x1d7, 0x1de, 0x1e7, 0x1f0, 0x1f9, 0x20c, 0x22f, 0x239, 0x26a, 0x275, 0x281, 0x293, 0x297, 0x2a8, 0x2ad, 0x2b1, 0x2b5, 0x2bc, 0x2c4, 0x2c9, 0x2d0, 0x2d4, 0x2da, 0x2e4, 0x2e7, 0x328, 0x32e, 0x335, 0x33c, 0x341, 0x348, 0x34f, 0x356, 0x35b, 0x360, 0x365, 0x36c, 0x38b, 0x38d, 0x394, 0x3b6, 0x3b8, 0x3bf, 0x3c3, 0x3e2, 0x3e4, 0x402, 0x404, 0x41a, 0x42f, 0x442, 0x444, 0x458, 0x45a, 0x46e, 0x470, 0x474, 0x490, 0x4a2, 0x4b9, }; _serializedATN.insert(_serializedATN.end(), serializedATNSegment0, serializedATNSegment0 + sizeof(serializedATNSegment0) / sizeof(serializedATNSegment0[0])); atn::ATNDeserializer deserializer; _atn = deserializer.deserialize(_serializedATN); size_t count = _atn.getNumberOfDecisions(); _decisionToDFA.reserve(count); for (size_t i = 0; i < count; i++) { _decisionToDFA.emplace_back(_atn.getDecisionState(i), i); } } SV3_1aPpParser::Initializer SV3_1aPpParser::_init;
35.628819
183
0.692337
pieter3d
2994f6aedab245f59c466dd74f25216a43ccd0f1
1,458
cpp
C++
src/Network/Timer.cpp
demonatic/Rinx
6e89150ea1ee22a90534c682e32923a30ed044e8
[ "MIT" ]
3
2020-05-21T09:23:59.000Z
2021-03-17T09:17:55.000Z
src/Network/Timer.cpp
demonatic/Rinx
6e89150ea1ee22a90534c682e32923a30ed044e8
[ "MIT" ]
null
null
null
src/Network/Timer.cpp
demonatic/Rinx
6e89150ea1ee22a90534c682e32923a30ed044e8
[ "MIT" ]
null
null
null
#include "Rinx/Network/Timer.h" #include "Rinx/Network/EventLoop.h" #include "Rinx/Network/TimerHeap.h" namespace Rinx { RxTimer::RxTimer(RxEventLoop *eventloop):_id(std::numeric_limits<uint64_t>::max()), _heap_index(std::numeric_limits<size_t>::max()),_duration(0), _is_active(false),_is_repeat(false),_eventloop_belongs(eventloop) { } RxTimer::~RxTimer() { if(this->is_active()){ stop(); } } TimerID RxTimer::start_timer(uint64_t milliseconds, TimerCallback expiry_action,bool repeat) { uint64_t expire_time=Clock::get_now_tick()+milliseconds; RxTimerHeap &timer_heap=_eventloop_belongs->get_timer_heap(); if(_is_active){ this->stop(); } _is_repeat=repeat; _duration=milliseconds; _timeout_cb=expiry_action; timer_heap.add_timer(expire_time,this); this->set_active(true); return _id; } void RxTimer::stop() { RxTimerHeap &timer_heap=_eventloop_belongs->get_timer_heap(); timer_heap.remove_timer(this->_id); this->set_active(false); } bool RxTimer::is_active() const noexcept { return _is_active; } bool RxTimer::is_repeat() const noexcept { return _is_repeat; } TimerID RxTimer::get_id() const noexcept { return _id; } uint64_t RxTimer::get_duration() const noexcept { return _duration; } void RxTimer::expired() { this->_timeout_cb(); } void RxTimer::set_active(bool active) noexcept { this->_is_active=active; } } //namespace Rinx
19.184211
92
0.709877
demonatic
2995d8b0b827db402e30e324c0954f11c57155c4
887
hpp
C++
alpaka/include/alpaka/core/RemoveRestrict.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
25
2015-01-30T12:19:48.000Z
2020-10-30T07:52:45.000Z
alpaka/include/alpaka/core/RemoveRestrict.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
101
2015-01-06T11:31:26.000Z
2020-11-09T13:51:19.000Z
alpaka/include/alpaka/core/RemoveRestrict.hpp
ComputationalRadiationPhysics/mallocMC
bb2b32a4a56f7c892e14454bf6aa373a4870c32c
[ "MIT" ]
10
2015-06-10T07:54:30.000Z
2020-05-06T10:07:39.000Z
/* Copyright 2021 Rene Widera * * This file is part of alpaka. * * 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/. */ #pragma once #include <alpaka/core/BoostPredef.hpp> namespace alpaka { //! Removes __restrict__ from a type template<typename T> struct remove_restrict { using type = T; }; #if BOOST_COMP_MSVC template<typename T> struct remove_restrict<T* __restrict> { using type = T*; }; #else template<typename T> struct remove_restrict<T* __restrict__> { using type = T*; }; #endif //! Helper to remove __restrict__ from a type template<typename T> using remove_restrict_t = typename remove_restrict<T>::type; } // namespace alpaka
21.634146
70
0.659526
ComputationalRadiationPhysics
299723c4062ae1c9010a18020442c75dbb697dda
22,970
cpp
C++
rts/c/DyLib/Renderer/AAPLMathUtilities.cpp
MilesLitteral/futhark
338a524d4b9897257a963aa62e640ab6dc5532ef
[ "ISC" ]
1
2022-02-13T15:11:20.000Z
2022-02-13T15:11:20.000Z
rts/c/DyLib/Renderer/AAPLMathUtilities.cpp
MilesLitteral/futhark
338a524d4b9897257a963aa62e640ab6dc5532ef
[ "ISC" ]
null
null
null
rts/c/DyLib/Renderer/AAPLMathUtilities.cpp
MilesLitteral/futhark
338a524d4b9897257a963aa62e640ab6dc5532ef
[ "ISC" ]
null
null
null
/* See LICENSE folder for this sample’s licensing information. Abstract: Implementation of vector, matrix, and quaternion math utility functions useful for 3D graphics rendering with Metal Metal uses column-major matrices and column-vector inputs. linearIndex cr example with reference elements 0 4 8 12 00 10 20 30 sx 10 20 tx 1 5 9 13 --> 01 11 21 31 --> 01 sy 21 ty 2 6 10 14 02 12 22 32 02 12 sz tz 3 7 11 15 03 13 23 33 03 13 1/d 33 The "cr" names are for <column><row> */ #include "AAPLMathUtilities.h" #include <assert.h> #include <stdlib.h> uint32_t seed_lo, seed_hi; static float inline F16ToF32(const __fp16 *address) { return *address; } float AAPL_SIMD_OVERLOAD float32_from_float16(uint16_t i) { return F16ToF32((__fp16 *)&i); } static inline void F32ToF16(float F32, __fp16 *F16Ptr) { *F16Ptr = F32; } uint16_t AAPL_SIMD_OVERLOAD float16_from_float32(float f) { uint16_t f16; F32ToF16(f, (__fp16 *)&f16); return f16; } vector_float3 AAPL_SIMD_OVERLOAD generate_random_vector(float min, float max) { vector_float3 rand; float range = max - min; rand.x = ((double)random() / (double) (0x7FFFFFFF)) * range + min; rand.y = ((double)random() / (double) (0x7FFFFFFF)) * range + min; rand.z = ((double)random() / (double) (0x7FFFFFFF)) * range + min; return rand; } void AAPL_SIMD_OVERLOAD seedRand(uint32_t seed) { seed_lo = seed; seed_hi = ~seed; } int32_t AAPL_SIMD_OVERLOAD randi(void) { seed_hi = (seed_hi<<16) + (seed_hi>>16); seed_hi += seed_lo; seed_lo += seed_hi; return seed_hi; } float AAPL_SIMD_OVERLOAD randf(float x) { return (x * randi() / (float)0x7FFFFFFF); } float AAPL_SIMD_OVERLOAD degrees_from_radians(float radians) { return (radians / M_PI) * 180; } float AAPL_SIMD_OVERLOAD radians_from_degrees(float degrees) { return (degrees / 180) * M_PI; } static vector_float3 AAPL_SIMD_OVERLOAD vector_make(float x, float y, float z) { return (vector_float3){ x, y, z }; } vector_float3 AAPL_SIMD_OVERLOAD vector_lerp(vector_float3 v0, vector_float3 v1, float t) { return ((1 - t) * v0) + (t * v1); } vector_float4 AAPL_SIMD_OVERLOAD vector_lerp(vector_float4 v0, vector_float4 v1, float t) { return ((1 - t) * v0) + (t * v1); } //------------------------------------------------------------------------------ // matrix_make_rows takes input data with rows of elements. // This way, the calling code matrix data can look like the rows // of a matrix made for transforming column vectors. // Indices are m<column><row> matrix_float3x3 AAPL_SIMD_OVERLOAD matrix_make_rows( float m00, float m10, float m20, float m01, float m11, float m21, float m02, float m12, float m22) { return (matrix_float3x3){ { { m00, m01, m02 }, // each line here provides column data { m10, m11, m12 }, { m20, m21, m22 } } }; } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_make_rows( float m00, float m10, float m20, float m30, float m01, float m11, float m21, float m31, float m02, float m12, float m22, float m32, float m03, float m13, float m23, float m33) { return (matrix_float4x4){ { { m00, m01, m02, m03 }, // each line here provides column data { m10, m11, m12, m13 }, { m20, m21, m22, m23 }, { m30, m31, m32, m33 } } }; } // each arg is a column vector matrix_float3x3 AAPL_SIMD_OVERLOAD matrix_make_columns( vector_float3 col0, vector_float3 col1, vector_float3 col2) { return (matrix_float3x3){ col0, col1, col2 }; } // each arg is a column vector matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_make_columns( vector_float4 col0, vector_float4 col1, vector_float4 col2, vector_float4 col3) { return (matrix_float4x4){ col0, col1, col2, col3 }; } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_from_quaternion(quaternion_float q) { float xx = q.x * q.x; float xy = q.x * q.y; float xz = q.x * q.z; float xw = q.x * q.w; float yy = q.y * q.y; float yz = q.y * q.z; float yw = q.y * q.w; float zz = q.z * q.z; float zw = q.z * q.w; // indices are m<column><row> float m00 = 1 - 2 * (yy + zz); float m10 = 2 * (xy - zw); float m20 = 2 * (xz + yw); float m01 = 2 * (xy + zw); float m11 = 1 - 2 * (xx + zz); float m21 = 2 * (yz - xw); float m02 = 2 * (xz - yw); float m12 = 2 * (yz + xw); float m22 = 1 - 2 * (xx + yy); return matrix_make_rows(m00, m10, m20, m01, m11, m21, m02, m12, m22); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_rotation(float radians, vector_float3 axis) { axis = vector_normalize(axis); float ct = cosf(radians); float st = sinf(radians); float ci = 1 - ct; float x = axis.x, y = axis.y, z = axis.z; return matrix_make_rows( ct + x * x * ci, x * y * ci - z * st, x * z * ci + y * st, y * x * ci + z * st, ct + y * y * ci, y * z * ci - x * st, z * x * ci - y * st, z * y * ci + x * st, ct + z * z * ci ); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_rotation(float radians, float x, float y, float z) { return matrix3x3_rotation(radians, vector_make(x, y, z)); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_scale(float sx, float sy, float sz) { return matrix_make_rows(sx, 0, 0, 0, sy, 0, 0, 0, sz); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_scale(vector_float3 s) { return matrix_make_rows(s.x, 0, 0, 0, s.y, 0, 0, 0, s.z); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix3x3_upper_left(matrix_float4x4 m) { vector_float3 x = m.columns[0].xyz; vector_float3 y = m.columns[1].xyz; vector_float3 z = m.columns[2].xyz; return matrix_make_columns(x, y, z); } matrix_float3x3 AAPL_SIMD_OVERLOAD matrix_inverse_transpose(matrix_float3x3 m) { return matrix_invert(matrix_transpose(m)); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_from_quaternion(quaternion_float q) { float xx = q.x * q.x; float xy = q.x * q.y; float xz = q.x * q.z; float xw = q.x * q.w; float yy = q.y * q.y; float yz = q.y * q.z; float yw = q.y * q.w; float zz = q.z * q.z; float zw = q.z * q.w; // indices are m<column><row> float m00 = 1 - 2 * (yy + zz); float m10 = 2 * (xy - zw); float m20 = 2 * (xz + yw); float m01 = 2 * (xy + zw); float m11 = 1 - 2 * (xx + zz); float m21 = 2 * (yz - xw); float m02 = 2 * (xz - yw); float m12 = 2 * (yz + xw); float m22 = 1 - 2 * (xx + yy); matrix_float4x4 matrix = matrix_make_rows(m00, m10, m20, 0, m01, m11, m21, 0, m02, m12, m22, 0, 0, 0, 0, 1); return matrix; } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_rotation(float radians, vector_float3 axis) { axis = vector_normalize(axis); float ct = cosf(radians); float st = sinf(radians); float ci = 1 - ct; float x = axis.x, y = axis.y, z = axis.z; return matrix_make_rows( ct + x * x * ci, x * y * ci - z * st, x * z * ci + y * st, 0, y * x * ci + z * st, ct + y * y * ci, y * z * ci - x * st, 0, z * x * ci - y * st, z * y * ci + x * st, ct + z * z * ci, 0, 0, 0, 0, 1); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_rotation(float radians, float x, float y, float z) { return matrix4x4_rotation(radians, vector_make(x, y, z)); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_identity(void) { return matrix_make_rows(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_scale(float sx, float sy, float sz) { return matrix_make_rows(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_scale(vector_float3 s) { return matrix_make_rows(s.x, 0, 0, 0, 0, s.y, 0, 0, 0, 0, s.z, 0, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_translation(float tx, float ty, float tz) { return matrix_make_rows(1, 0, 0, tx, 0, 1, 0, ty, 0, 0, 1, tz, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_translation(vector_float3 t) { return matrix_make_rows(1, 0, 0, t.x, 0, 1, 0, t.y, 0, 0, 1, t.z, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix4x4_scale_translation(vector_float3 s, vector_float3 t) { return matrix_make_rows(s.x, 0, 0, t.x, 0, s.y, 0, t.y, 0, 0, s.z, t.z, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_look_at_left_hand(vector_float3 eye, vector_float3 target, vector_float3 up) { vector_float3 z = vector_normalize(target - eye); vector_float3 x = vector_normalize(vector_cross(up, z)); vector_float3 y = vector_cross(z, x); vector_float3 t = vector_make(-vector_dot(x, eye), -vector_dot(y, eye), -vector_dot(z, eye)); return matrix_make_rows(x.x, x.y, x.z, t.x, y.x, y.y, y.z, t.y, z.x, z.y, z.z, t.z, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_look_at_left_hand(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { vector_float3 eye = vector_make(eyeX, eyeY, eyeZ); vector_float3 center = vector_make(centerX, centerY, centerZ); vector_float3 up = vector_make(upX, upY, upZ); return matrix_look_at_left_hand(eye, center, up); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_look_at_right_hand(vector_float3 eye, vector_float3 target, vector_float3 up) { vector_float3 z = vector_normalize(eye - target); vector_float3 x = vector_normalize(vector_cross(up, z)); vector_float3 y = vector_cross(z, x); vector_float3 t = vector_make(-vector_dot(x, eye), -vector_dot(y, eye), -vector_dot(z, eye)); return matrix_make_rows(x.x, x.y, x.z, t.x, y.x, y.y, y.z, t.y, z.x, z.y, z.z, t.z, 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_look_at_right_hand(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { vector_float3 eye = vector_make(eyeX, eyeY, eyeZ); vector_float3 center = vector_make(centerX, centerY, centerZ); vector_float3 up = vector_make(upX, upY, upZ); return matrix_look_at_right_hand(eye, center, up); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_ortho_left_hand(float left, float right, float bottom, float top, float nearZ, float farZ) { return matrix_make_rows( 2 / (right - left), 0, 0, (left + right) / (left - right), 0, 2 / (top - bottom), 0, (top + bottom) / (bottom - top), 0, 0, 1 / (farZ - nearZ), nearZ / (nearZ - farZ), 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_ortho_right_hand(float left, float right, float bottom, float top, float nearZ, float farZ) { return matrix_make_rows( 2 / (right - left), 0, 0, (left + right) / (left - right), 0, 2 / (top - bottom), 0, (top + bottom) / (bottom - top), 0, 0, -1 / (farZ - nearZ), nearZ / (nearZ - farZ), 0, 0, 0, 1 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_perspective_left_hand(float fovyRadians, float aspect, float nearZ, float farZ) { float ys = 1 / tanf(fovyRadians * 0.5); float xs = ys / aspect; float zs = farZ / (farZ - nearZ); return matrix_make_rows(xs, 0, 0, 0, 0, ys, 0, 0, 0, 0, zs, -nearZ * zs, 0, 0, 1, 0 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_perspective_right_hand(float fovyRadians, float aspect, float nearZ, float farZ) { float ys = 1 / tanf(fovyRadians * 0.5); float xs = ys / aspect; float zs = farZ / (nearZ - farZ); return matrix_make_rows(xs, 0, 0, 0, 0, ys, 0, 0, 0, 0, zs, nearZ * zs, 0, 0, -1, 0 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_perspective_frustum_right_hand(float l, float r, float b, float t, float n, float f) { return matrix_make_rows( 2 * n / (r - l), 0, (r + l) / (r - l), 0, 0, 2 * n / (t - b), (t + b) / (t - b), 0, 0, 0, -f / (f - n), -f * n / (f - n), 0, 0, -1, 0 ); } matrix_float4x4 AAPL_SIMD_OVERLOAD matrix_inverse_transpose(matrix_float4x4 m) { return matrix_invert(matrix_transpose(m)); } quaternion_float AAPL_SIMD_OVERLOAD quaternion(float x, float y, float z, float w) { return (quaternion_float){ x, y, z, w }; } quaternion_float AAPL_SIMD_OVERLOAD quaternion(vector_float3 v, float w) { return (quaternion_float){ v.x, v.y, v.z, w }; } quaternion_float AAPL_SIMD_OVERLOAD quaternion_identity() { return quaternion(0, 0, 0, 1); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_axis_angle(vector_float3 axis, float radians) { float t = radians * 0.5; return quaternion(axis.x * sinf(t), axis.y * sinf(t), axis.z * sinf(t), cosf(t)); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_euler(vector_float3 euler) { quaternion_float q; float cx = cosf(euler.x / 2.f); float cy = cosf(euler.y / 2.f); float cz = cosf(euler.z / 2.f); float sx = sinf(euler.x / 2.f); float sy = sinf(euler.y / 2.f); float sz = sinf(euler.z / 2.f); q.w = cx * cy * cz + sx * sy * sz; q.x = sx * cy * cz - cx * sy * sz; q.y = cx * sy * cz + sx * cy * sz; q.z = cx * cy * sz - sx * sy * cz; return q; } quaternion_float AAPL_SIMD_OVERLOAD quaternion(matrix_float3x3 m) { float m00 = m.columns[0].x; float m11 = m.columns[1].y; float m22 = m.columns[2].z; float x = sqrtf(1 + m00 - m11 - m22) * 0.5; float y = sqrtf(1 - m00 + m11 - m22) * 0.5; float z = sqrtf(1 - m00 - m11 + m22) * 0.5; float w = sqrtf(1 + m00 + m11 + m22) * 0.5; return quaternion(x, y, z, w); } quaternion_float AAPL_SIMD_OVERLOAD quaternion(matrix_float4x4 m) { return quaternion(matrix3x3_upper_left(m)); } float AAPL_SIMD_OVERLOAD quaternion_length(quaternion_float q) { // return sqrt(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); return vector_length(q); } float AAPL_SIMD_OVERLOAD quaternion_length_squared(quaternion_float q) { // return q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; return vector_length_squared(q); } vector_float3 AAPL_SIMD_OVERLOAD quaternion_axis(quaternion_float q) { // This query doesn't make sense if w > 1, but the function does its // best by forcing q to be a unit quaternion if it obviously isn't. if (q.w > 1.0) { q = quaternion_normalize(q); } float axisLen = sqrtf(1 - q.w * q.w); if (axisLen < 1e-5) { // At lengths this small, direction is arbitrary return vector_make(1, 0, 0); } else { return vector_make(q.x / axisLen, q.y / axisLen, q.z / axisLen); } } float AAPL_SIMD_OVERLOAD quaternion_angle(quaternion_float q) { return 2 * acosf(q.w); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_normalize(quaternion_float q) { // return q / quaternion_length(q); return vector_normalize(q); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_inverse(quaternion_float q) { return quaternion_conjugate(q) / quaternion_length_squared(q); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_conjugate(quaternion_float q) { return quaternion(-q.x, -q.y, -q.z, q.w); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_multiply(quaternion_float q0, quaternion_float q1) { quaternion_float q; q.x = q0.w*q1.x + q0.x*q1.w + q0.y*q1.z - q0.z*q1.y; q.y = q0.w*q1.y - q0.x*q1.z + q0.y*q1.w + q0.z*q1.x; q.z = q0.w*q1.z + q0.x*q1.y - q0.y*q1.x + q0.z*q1.w; q.w = q0.w*q1.w - q0.x*q1.x - q0.y*q1.y - q0.z*q1.z; return q; } quaternion_float AAPL_SIMD_OVERLOAD quaternion_slerp(quaternion_float q0, quaternion_float q1, float t) { quaternion_float q; float cosHalfTheta = vector_dot(q0, q1); if (fabs(cosHalfTheta) >= 1.f) ///q0=q1 or q0=q1 { return q0; } float halfTheta = acosf(cosHalfTheta); float sinHalfTheta = sqrtf(1.f - cosHalfTheta * cosHalfTheta); if (fabs(sinHalfTheta) < 0.001f) { // q0 & q1 180 degrees not defined return q0*0.5f + q1*0.5f; } float srcWeight = sin((1 - t) * halfTheta) / sinHalfTheta; float dstWeight = sin(t * halfTheta) / sinHalfTheta; q = srcWeight*q0 + dstWeight*q1; return q; } vector_float3 AAPL_SIMD_OVERLOAD quaternion_rotate_vector(quaternion_float q, vector_float3 v) { vector_float3 qp = vector_make(q.x, q.y, q.z); float w = q.w; return 2 * vector_dot(qp, v) * qp + ((w * w) - vector_dot(qp, qp)) * v + 2 * w * vector_cross(qp, v); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_matrix3x3(matrix_float3x3 m) { quaternion_float q; float trace = 1 + m.columns[0][0] + m.columns[1][1] + m.columns[2][2]; if(trace > 0) { float diagonal = sqrt(trace) * 2.0; q.x = (m.columns[2][1] - m.columns[1][2]) / diagonal; q.y = (m.columns[0][2] - m.columns[2][0]) / diagonal; q.z = (m.columns[1][0] - m.columns[0][1]) / diagonal; q.w = diagonal / 4.0; } else if ((m.columns[0][0] > m.columns[1][1] ) && (m.columns[0][0] > m.columns[2][2])) { float diagonal = sqrt(1.0 + m.columns[0][0] - m.columns[1][1] - m.columns[2][2]) * 2.0; q.x = diagonal / 4.0; q.y = (m.columns[0][1] + m.columns[1][0]) / diagonal; q.z = (m.columns[0][2] + m.columns[2][0]) / diagonal; q.w = (m.columns[2][1] - m.columns[1][2]) / diagonal; } else if ( m.columns[1][1] > m.columns[2][2]) { float diagonal = sqrt(1.0 + m.columns[1][1] - m.columns[0][0] - m.columns[2][2]) * 2.0; q.x = (m.columns[0][1] + m.columns[1][0]) / diagonal; q.y = diagonal / 4.0; q.z = (m.columns[1][2] + m.columns[2][1]) / diagonal; q.w = (m.columns[0][2] - m.columns[2][0]) / diagonal; } else { float diagonal = sqrt(1.0 + m.columns[2][2] - m.columns[0][0] - m.columns[1][1]) * 2.0; q.x = (m.columns[0][2] + m.columns[2][0]) / diagonal; q.y = (m.columns[1][2] + m.columns[2][1]) / diagonal; q.z = diagonal / 4.0; q.w = (m.columns[1][0] - m.columns[0][1]) / diagonal; } q = quaternion_normalize(q); return q; } static inline quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_direction_vectors(vector_float3 forward, vector_float3 up, int right_handed) { forward = vector_normalize(forward); up = vector_normalize(up); vector_float3 side = vector_normalize(vector_cross(up, forward)); matrix_float3x3 m = { side, up, forward }; quaternion_float q = quaternion_from_matrix3x3(m); if(right_handed) { q = q.yxwz; q.xw = -q.xw; } q = vector_normalize(q); return q; } quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_direction_vectors_right_hand(vector_float3 forward, vector_float3 up) { return quaternion_from_direction_vectors(forward, up, 1); } quaternion_float AAPL_SIMD_OVERLOAD quaternion_from_direction_vectors_left_hand(vector_float3 forward, vector_float3 up) { return quaternion_from_direction_vectors(forward, up, 0); } vector_float3 AAPL_SIMD_OVERLOAD forward_direction_vector_from_quaternion(quaternion_float q) { vector_float3 direction; direction.x = 2.0 * (q.x*q.z - q.w*q.y); direction.y = 2.0 * (q.y*q.z + q.w*q.x); direction.z = 1.0 - 2.0 * ((q.x * q.x) + (q.y * q.y)); direction = vector_normalize(direction); return direction; } vector_float3 AAPL_SIMD_OVERLOAD up_direction_vector_from_quaternion(quaternion_float q) { vector_float3 direction; direction.x = 2.0 * (q.x*q.y + q.w*q.z); direction.y = 1.0 - 2.0 * (q.x*q.x + q.z*q.z); direction.z = 2.0 * (q.y*q.z - q.w*q.x); direction = vector_normalize(direction); // Negate for a right-handed coordinate system return direction; } vector_float3 AAPL_SIMD_OVERLOAD right_direction_vector_from_quaternion(quaternion_float q) { vector_float3 direction; direction.x = 1.0 - 2.0 * (q.y * q.y + q.z * q.z); direction.y = 2.0 * (q.x * q.y - q.w * q.z); direction.z = 2.0 * (q.x * q.z + q.w * q.y); direction = vector_normalize(direction); // Negate for a right-handed coordinate system return direction; }
36.059655
144
0.552852
MilesLitteral
2998287fdd5ba0d16182726e8e58792abd6895a0
1,337
cpp
C++
NGS_testing/utility/utilityTest.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
3
2015-11-23T14:24:06.000Z
2017-11-21T21:04:06.000Z
NGS_testing/utility/utilityTest.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
NGS_testing/utility/utilityTest.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
#include "NGS++.h" #include "gtest.h" #include "gnuplot_i.hpp" using namespace std; TEST(utility, MeanTest) { const vector<float> ourValues= {22, 11, 30, 0 ,50}; EXPECT_FLOAT_EQ(utility::getMean(ourValues),22.6); } TEST(utility, SDTest) { const vector<float> ourValues= {22, 11, 30, 0 ,50}; EXPECT_NEAR(utility::getSd(ourValues, utility::getMean(ourValues)),19.047, 0.001); } TEST(utility, QuartTest) { const vector<long long> ourValues= {22, 11, 30, 0 ,50}; auto quart = utility::quartilesofVector(ourValues); EXPECT_EQ(quart.at(0), 11); EXPECT_EQ(quart.at(1), 22); EXPECT_EQ(quart.at(2), 30); } TEST(utility, querySamTest) { const int PAIRED=1; const int MINUS_STRAND=16; EXPECT_TRUE( utility::SAM::querySamFlag(PAIRED,SamQuery::IS_PAIRED) ); EXPECT_FALSE( utility::SAM::querySamFlag(PAIRED,SamQuery::NEXT_UNMAPPED) ); EXPECT_FALSE( utility::SAM::querySamFlag(MINUS_STRAND,SamQuery::FAIL_QUAL) ); EXPECT_TRUE( utility::SAM::querySamFlag(MINUS_STRAND,SamQuery::SEQ_REV_STRAND) ); } TEST(clustering, hausdorff) { const int IDENTICAL=0; vector<float> vecA= {1.5,2.5,2.5,1.5}; vector<float> vecB= {8,1,1,8}; EXPECT_EQ(clustering::hausdorffTwoRegions(vecA,vecA), IDENTICAL); EXPECT_NE(clustering::hausdorffTwoRegions(vecA,vecB), IDENTICAL); }
21.918033
86
0.691847
NGS-lib
29989d7fe323d9ae3c9ae0bc612f83d807c84f04
8,531
cpp
C++
cppcache/integration/test/PartitionRegionOpsTest.cpp
gaussianrecurrence/geode-native
fbecd6bc77b9c4d63ebacb8a74167bedb88d1414
[ "Apache-2.0" ]
1
2018-09-08T05:05:22.000Z
2018-09-08T05:05:22.000Z
cppcache/integration/test/PartitionRegionOpsTest.cpp
pivotal-jbarrett/geode-native
50a441c4c0f78679558d520eaf20022ae51de3ff
[ "Apache-2.0" ]
1
2020-10-05T11:41:41.000Z
2020-10-05T11:41:41.000Z
cppcache/integration/test/PartitionRegionOpsTest.cpp
pivotal-jbarrett/geode-native
50a441c4c0f78679558d520eaf20022ae51de3ff
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <chrono> #include <fstream> #include <future> #include <iostream> #include <random> #include <thread> #include <gtest/gtest.h> #include <geode/Cache.hpp> #include <geode/PoolManager.hpp> #include <geode/RegionFactory.hpp> #include <geode/RegionShortcut.hpp> #include "CacheRegionHelper.hpp" #include "framework/Cluster.h" #include "framework/Framework.h" #include "framework/Gfsh.h" namespace { using apache::geode::client::Cache; using apache::geode::client::Cacheable; using apache::geode::client::CacheableKey; using apache::geode::client::CacheableString; using apache::geode::client::HashMapOfCacheable; using apache::geode::client::Pool; using apache::geode::client::Region; using apache::geode::client::RegionShortcut; using std::chrono::minutes; std::string getClientLogName() { std::string testSuiteName(::testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name()); std::string testCaseName( ::testing::UnitTest::GetInstance()->current_test_info()->name()); std::string logFileName(testSuiteName + "/" + testCaseName + "/client.log"); return logFileName; } Cache createCache() { using apache::geode::client::CacheFactory; auto cache = CacheFactory() .set("log-level", "debug") .set("log-file", getClientLogName()) .set("statistic-sampling-enabled", "false") .create(); return cache; } std::shared_ptr<Pool> createPool(Cluster& cluster, Cache& cache, bool singleHop) { auto poolFactory = cache.getPoolManager().createFactory(); cluster.applyLocators(poolFactory); poolFactory.setPRSingleHopEnabled(singleHop); poolFactory.setLoadConditioningInterval(std::chrono::milliseconds::zero()); poolFactory.setIdleTimeout(std::chrono::milliseconds::zero()); return poolFactory.create("default"); } std::shared_ptr<Region> setupRegion(Cache& cache, const std::shared_ptr<Pool>& pool) { auto region = cache.createRegionFactory(RegionShortcut::PROXY) .setPoolName(pool->getName()) .create("region"); return region; } void putEntries(std::shared_ptr<Region> region, int numEntries, int offsetForValue) { for (int i = 0; i < numEntries; i++) { auto key = CacheableKey::create(i); region->put(key, Cacheable::create(std::to_string(i + offsetForValue))); } } void getEntries(std::shared_ptr<Region> region, int numEntries) { for (int i = 0; i < numEntries; i++) { auto key = CacheableKey::create(i); auto value = region->get(key); ASSERT_NE(nullptr, value); } } void removeLogFromPreviousExecution() { std::string logFileName(getClientLogName()); std::ifstream previousTestLog(logFileName.c_str()); if (previousTestLog.good()) { std::cout << "Removing log from previous execution: " << logFileName << std::endl; remove(logFileName.c_str()); } } void verifyMetadataWasRemovedAtFirstError() { std::ifstream testLog(getClientLogName().c_str()); std::string fileLine; bool ioErrors = false; bool timeoutErrors = false; bool metadataRemovedDueToIoErr = false; bool metadataRemovedDueToTimeout = false; std::regex timeoutRegex( "sendRequestConnWithRetry: Giving up for endpoint(.*)reason: timed out " "waiting for endpoint."); std::regex ioErrRegex( "sendRequestConnWithRetry: Giving up for endpoint(.*)reason: IO error " "for endpoint."); std::regex removingMetadataDueToIoErrRegex( "Removing bucketServerLocation(.*)due to GF_IOERR"); std::regex removingMetadataDueToTimeoutRegex( "Removing bucketServerLocation(.*)due to GF_TIMEOUT"); if (testLog.is_open()) { while (std::getline(testLog, fileLine)) { if (std::regex_search(fileLine, timeoutRegex)) { timeoutErrors = true; } else if (std::regex_search(fileLine, ioErrRegex)) { ioErrors = true; } else if (std::regex_search(fileLine, removingMetadataDueToIoErrRegex)) { metadataRemovedDueToIoErr = true; } else if (std::regex_search(fileLine, removingMetadataDueToTimeoutRegex)) { metadataRemovedDueToTimeout = true; } } } EXPECT_EQ(timeoutErrors, metadataRemovedDueToTimeout); EXPECT_EQ(ioErrors, metadataRemovedDueToIoErr); EXPECT_NE(metadataRemovedDueToTimeout, metadataRemovedDueToIoErr); } void putPartitionedRegionWithRedundancyServerGoesDown(bool singleHop) { Cluster cluster{LocatorCount{1}, ServerCount{2}}; cluster.start(); cluster.getGfsh() .create() .region() .withName("region") .withType("PARTITION") .withRedundantCopies("1") .execute(); auto cache = createCache(); auto pool = createPool(cluster, cache, singleHop); auto region = setupRegion(cache, pool); int ENTRIES = 30; putEntries(region, ENTRIES, 0); cluster.getServers()[1].stop(); putEntries(region, ENTRIES, 1); cluster.getServers()[1].start(); putEntries(region, ENTRIES, 2); } void getPartitionedRegionWithRedundancyServerGoesDown(bool singleHop) { Cluster cluster{LocatorCount{1}, ServerCount{2}}; cluster.start(); cluster.getGfsh() .create() .region() .withName("region") .withType("PARTITION") .withRedundantCopies("1") .execute(); auto cache = createCache(); auto pool = createPool(cluster, cache, singleHop); auto region = setupRegion(cache, pool); int ENTRIES = 30; putEntries(region, ENTRIES, 0); getEntries(region, ENTRIES); cluster.getServers()[1].stop(); getEntries(region, ENTRIES); cluster.getServers()[1].start(); getEntries(region, ENTRIES); } /** * In this test case we verify that in a partition region with redundancy * when one server goes down, all gets are still served. * Single-hop is enabled in the client. * It can be observed in the logs that when one of the server goes down * the bucketServerLocations for that server are removed from the * client metadata. */ TEST(PartitionRegionOpsTest, getPartitionedRegionWithRedundancyServerGoesDownSingleHop) { removeLogFromPreviousExecution(); getPartitionedRegionWithRedundancyServerGoesDown(true); verifyMetadataWasRemovedAtFirstError(); } /** * In this test case we verify that in a partition region with redundancy * when one server goes down, all puts are still served. * Single-hop is enabled in the client. * It can be observed in the logs that when one of the server goes down * the bucketServerLocations for that server are removed from the * client metadata. * When the server is brought back again, the meta data is refreshed * after putting again values. */ TEST(PartitionRegionOpsTest, putPartitionedRegionWithRedundancyServerGoesDownSingleHop) { removeLogFromPreviousExecution(); putPartitionedRegionWithRedundancyServerGoesDown(true); verifyMetadataWasRemovedAtFirstError(); } /** * In this test case we verify that in a partition region with redundancy * when one server goes down, all gets are still served. * Single hop is not enabled in the client. */ TEST(PartitionRegionOpsTest, getPartitionedRegionWithRedundancyServerGoesDownNoSingleHop) { getPartitionedRegionWithRedundancyServerGoesDown(false); } /** * In this test case we verify that in a partition region with redundancy * when one server goes down, all puts are still served. * Single-hop is not enabled in the client. */ TEST(PartitionRegionOpsTest, putPartitionedRegionWithRedundancyServerGoesDownNoSingleHop) { putPartitionedRegionWithRedundancyServerGoesDown(false); } } // namespace
32.192453
80
0.707186
gaussianrecurrence
299ba99627f6fde9d05afedbabdbc5a072c5a0b9
9,531
cpp
C++
Game.cpp
veethebraun/ld42
c0f183557883f125c9678eb5b73151a74524a699
[ "MIT" ]
null
null
null
Game.cpp
veethebraun/ld42
c0f183557883f125c9678eb5b73151a74524a699
[ "MIT" ]
null
null
null
Game.cpp
veethebraun/ld42
c0f183557883f125c9678eb5b73151a74524a699
[ "MIT" ]
null
null
null
// // Created by vbrau on 4/18/2018. // #include <iostream> #include "Game.h" #include "GUI/Commands/TileClickCommand.h" #include "GUI/Commands/TimeTickCommand.h" #include "GUI/Commands/SelectBuildingCommand.h" #include "GUI/Commands/NewRowCommand.h" #include "GUI/Commands/LaunchCommand.h" #include "GUI/Commands/PlayGameCommand.h" #include "GUI/Commands/HowToCommand.h" GameCommand * Game::handleCommand(GameCommand *cmd) { if (current_scene == SceneList::TITLE || current_scene == SceneList::HOWTO) { auto play = dynamic_cast<PlayGameCommand*>(cmd); if (play != nullptr) { needToHandleClick = true; current_scene = SceneList ::GAME; } auto howto = dynamic_cast<HowToCommand*>(cmd); if (howto != nullptr) { needToHandleClick = true; current_scene = SceneList::HOWTO; } } if (current_scene == SceneList::WIN || current_scene == SceneList::LOSE) { auto play = dynamic_cast<PlayGameCommand*>(cmd); if (play != nullptr) { needToHandleClick = true; for (const auto&building : activeBuildings) { delete building; } activeBuildings.clear(); init(); current_scene = SceneList ::GAME; } } if (current_scene == SceneList::GAME) { auto tile = dynamic_cast<TileClickCommand *>(cmd); if (tile != nullptr) { placeBuilding(tile->getI(), tile->getJ()); } auto build = dynamic_cast<SelectBuildingCommand *>(cmd); if (build != nullptr) { currentBuildingSelection = build->getBuildingType(); if (currentBuildingSelection == BuildingType::NONE) { message = ""; } } auto time = dynamic_cast<TimeTickCommand *>(cmd); if (time != nullptr) { handleTimeTick(); } auto newRow = dynamic_cast<NewRowCommand *>(cmd); if (newRow != nullptr) { addNewRow(); } auto launch = dynamic_cast<LaunchCommand *>(cmd); if (launch != nullptr) { if (readyToLaunch) triggerWin(); } } return nullptr; } void Game::init() { fillBuildings(); current_scene = SceneList::TITLE; resource = new Resources(); fillGrid(eligibleForBuild, true); buildingsFree = true; currentBuildingSelection = BuildingType ::MAT_STORAGE; placeBuilding(0,0); currentBuildingSelection = BuildingType ::WIND; placeBuilding(3,0); currentBuildingSelection = BuildingType ::MINE; placeBuilding(2,5); currentBuildingSelection = BuildingType ::STEEL; placeBuilding(4,4); buildingsFree = false; resource->resetResources(); resource->addResources({WIND_POWER_GEN-MINE_POWER-STEEL_REFINERY_POWER,0,0,0,0}); level = 0; dropCounter = 0; nextNewRow = -1; shrinkRow = 0; } SceneList Game::getCurrentScene() const { return current_scene; } void Game::clearAfterFrame() { needToHandleClick = false; playExplode = false; } void Game::placeBuilding(int x, int y) { if (currentBuildingSelection != BuildingType::NONE) { auto building = buildingFactory.getNewBuilding(currentBuildingSelection, x, y); if (building->canBuild(resource) || buildingsFree) { if (doesBuildingFit(building)) { populateBuilding(building); building->onBuild(resource); if (currentBuildingSelection == BuildingType::ROCKET) { readyToLaunch = true; } currentBuildingSelection = BuildingType::NONE; needToHandleClick = true; setMessage(""); } else { setMessage("Bad Location"); } } else { setMessage("Insufficient Resources"); } } } bool Game::hasBuilding(int x, int y) { return buildings.at((size_t) x).at((size_t )y); } bool Game::doesBuildingFit(Building *building) { auto bdg_locs = building->getLocs(); for (const auto &loc : bdg_locs) { int i = building->getX() + loc[0]; int j = building->getY() + loc[1]; if (!building->isLocRequired(loc)) continue; if (i < 0 || i >= GRID_ROWS || j < 0 || j >= GRID_COLS) return false; if (hasBuilding(i, j)) return false; if (!eligibleForBuild.at((size_t) i).at((size_t)j)) return false; if (building->getBuildingType() == BuildingType::MINE) { if (building->getX() == 0) return false; } } return true; } void Game::printBuildings() { for (size_t i=0; i<GRID_ROWS; i++){ for (size_t j=0; j<GRID_COLS; j++) { std::cout << (buildings.at(i).at(j)); } std::cout << std::endl; } } void Game::handleTimeTick() { for (const auto &building : activeBuildings) { building->resourceGeneration(resource); } dropCounter++; if (dropCounter > NUM_TIME_STEPS_FOR_DROP) { dropBuildings(); dropCounter = 0; } } Resources *Game::getResource() const { return resource; } BuildingType Game::getCurrentBuildingSelection() const { return currentBuildingSelection; } const char * Game::getMessage() const { return message; } void Game::setMessage(const char *message) { Game::message = message; } void Game::dropBuildings() { fillBuildings(); std::vector<Building*> buildingsToRemove; for (const auto &building : activeBuildings) { building->dropLevel(resource); if (!building->isOnBoard(GRID_ROWS, GRID_COLS)) { buildingsToRemove.push_back(building) ; } } if (!buildingsToRemove.empty()) { playExplode = true; } activeBuildings.erase( remove_if( begin(activeBuildings),end(activeBuildings), [&](Building* x){return find(begin(buildingsToRemove),end(buildingsToRemove),x)!=end(buildingsToRemove);}), end(activeBuildings) ); for (const auto &item : buildingsToRemove) { delete item; } for (const auto &building : activeBuildings) { auto bdgloc = building->getXY(); for (const auto &loc : building->getLocs()) { auto i = static_cast<size_t>(bdgloc[0] + loc[0]); auto j = static_cast<size_t>(bdgloc[1] + loc[1]); if (i < GRID_ROWS && j < GRID_COLS) buildings.at(i).at(j) = true; } } Grid newEligibility = {{{false}}}; for (size_t i=1; i< GRID_ROWS; i++) { for (size_t j=0; j<GRID_COLS; j++) { newEligibility.at(i).at(j) = eligibleForBuild.at(i-1).at(j); } } eligibleForBuild = newEligibility; bool lost = true; for (size_t i=0; i< GRID_ROWS; i++) { for (size_t j = 0; j < GRID_COLS; j++) { if (eligibleForBuild.at(i).at(j)) { lost = false; break; } } } if (lost) { current_scene = SceneList ::LOSE; } nextNewRow += 1; level++; } void Game::populateBuilding(Building *building) { Point2d bdgloc = building->getXY(); activeBuildings.push_back(building); for (const auto &loc : building->getLocs()) { auto i = static_cast<size_t>(bdgloc[0] + loc[0]); auto j = static_cast<size_t>(bdgloc[1] + loc[1]); if (i < GRID_ROWS && j < GRID_COLS) { buildings.at(i).at(j) = true; } } } const std::vector<Building *> &Game::getActiveBuildings() const { return activeBuildings; } void Game::fillBuildings() { for (int i=0; i<GRID_ROWS; i++) { for (int j=0; j<GRID_COLS; j++) { buildings.at((size_t)i).at((size_t)j) = false; } } } bool Game::buildableAt(size_t i, size_t j) { return eligibleForBuild.at(i).at(j); } void Game::addNewRow() { if (nextNewRow < 0 || nextNewRow >= GRID_ROWS || shrinkRow*2 >= GRID_COLS) return; bool good = false; for (const auto &item : eligibleForBuild.at((size_t)nextNewRow)) { if (!item) { good = true; break; } } if (!good) return; if (resource->getSteel() > STEEL_FOR_NEW_ROW || buildingsFree) { for (auto j = (size_t)shrinkRow; j < GRID_COLS-shrinkRow; j++) { eligibleForBuild.at((size_t) nextNewRow).at(j) = true; } resource->addResources({0,0,-STEEL_FOR_NEW_ROW,0,0}); nextNewRow -= 1; } shrinkRow = (level-nextNewRow)/SHRINK_COL_EVERY_N_ROWS; } void Game::fillGrid(Grid &grid, bool val) { for (size_t i=0; i<GRID_ROWS; i++) { for (size_t j = 0; j < GRID_COLS; j++) { grid.at(i).at(j) = val; } } } void Game::printEligibleBuildings() { for (size_t i=0; i<GRID_ROWS; i++){ for (size_t j=0; j<GRID_COLS; j++) { std::cout << (eligibleForBuild.at(i).at(j)); } std::cout << std::endl; } } int Game::getLevel() const { return level; } bool Game::isReadyToLaunch() const { return readyToLaunch; } void Game::triggerWin() { current_scene = SceneList ::WIN; } bool Game::closeToDrop() { return NUM_TIME_STEPS_FOR_DROP - dropCounter < NUM_TIME_STEPS_FOR_DROP/2; } bool Game::isNeedToHandleClick() const { return needToHandleClick; } bool Game::isPlayExplode() const { return playExplode; }
26.475
155
0.577904
veethebraun
299bc19f65ea75308f4e8f085432b7b996bd1e88
6,666
cc
C++
ann_0.2/samples/ann_sample.cc
hrakaroo/soda-water-ray-tracer
5a0e94db3601efe43e28d69249b8c822627a40e2
[ "Unlicense" ]
3
2019-03-22T20:50:37.000Z
2019-06-26T21:13:50.000Z
ann_0.2/samples/ann_sample.cc
hrakaroo/soda-water-ray-tracer
5a0e94db3601efe43e28d69249b8c822627a40e2
[ "Unlicense" ]
null
null
null
ann_0.2/samples/ann_sample.cc
hrakaroo/soda-water-ray-tracer
5a0e94db3601efe43e28d69249b8c822627a40e2
[ "Unlicense" ]
3
2019-06-26T21:13:44.000Z
2020-05-26T22:03:46.000Z
//---------------------------------------------------------------------- // File: ann_sample.cc // Programmer: Sunil Arya and David Mount // Last modified: 03/04/98 (Release 0.1) // Description: Sample program for ANN //---------------------------------------------------------------------- // Copyright (c) 1997-1998 University of Maryland and Sunil Arya and David // Mount All Rights Reserved. // // This software and related documentation is part of the // Approximate Nearest Neighbor Library (ANN). // // Permission to use, copy, and distribute this software and its // documentation is hereby granted free of charge, provided that // (1) it is not a component of a commercial product, and // (2) this notice appears in all copies of the software and // related documentation. // // The University of Maryland (U.M.) and the authors make no representations // about the suitability or fitness of this software for any purpose. It is // provided "as is" without express or implied warranty. //---------------------------------------------------------------------- #include <stdio.h> // C I/O #include <fstream.h> // file I/O #include <string.h> // string manipulation #include <math.h> // math routines #include <ANN/ANN.h> // ANN declarations //---------------------------------------------------------------------- // ann_sample // // This is a simple sample program for the ANN library. After compiling, // it can be run as follows. // // ann_sample [-d dim] [-max mpts] [-nn k] [-e eps] [-df data] [-qf query] // // where // dim is the dimension of the space (default = 2) // mpts maximum number of data points (default = 1000) // k number of nearest neighbors per query (default 1) // eps is the error bound (default = 0.0) // data file containing data points // query file containing query points // // Results are sent to the standard output. //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Parameters that are set in getArgs() //---------------------------------------------------------------------- void getArgs(int argc, char **argv); // get command-line arguments int k = 1; // number of nearest neighbors int dim = 2; // dimension double eps = 0; // error bound int m_pts = 1000; // maximum number of data points istream *data_in = NULL; // input for data points istream *query_in = NULL; // input for query points ANNbool readPt(istream &in, ANNpoint p) // read point (false on EOF) { for (int i = 0; i < dim; i++) { if(!(in >> p[i])) return ANNfalse; } return ANNtrue; } void printPt(ostream &out, ANNpoint p) // print point { out << "(" << p[0]; for (int i = 1; i < dim; i++) { out << ", " << p[i]; } out << ")\n"; } main(int argc, char **argv) { int n_pts; // actual number of data points ANNpointArray data_pts; // data points ANNpoint query_pt; // query point ANNidxArray nn_idx; // near neighbor indices ANNdistArray dists; // near neighbor distances ANNkd_tree *the_tree; // search structure getArgs(argc, argv); // read command-line arguments query_pt = annAllocPt(dim); // allocate query point data_pts = annAllocPts(m_pts, dim); // allocate data points nn_idx = new ANNidx[k]; // allocate near neigh indices dists = new ANNdist[k]; // allocate near neighbor dists n_pts = 0; // read data points cout << "Data Points:\n"; while (n_pts < m_pts && readPt(*data_in, data_pts[n_pts])) { printPt(cout, data_pts[n_pts]); n_pts++; } the_tree = new ANNkd_tree( // build search structure data_pts, // the data points n_pts, // number of points dim); // dimension of space while (readPt(*query_in, query_pt)) { // read query points cout << "Query point: "; // echo query point printPt(cout, query_pt); the_tree->annkSearch( // search query_pt, // query point k, // number of near neighbors nn_idx, // nearest neighbors (returned) dists, // distance (returned) eps); // error bound cout << "\tNN:\tIndex\tDistance\n"; for (int i = 0; i < k; i++) { // print summary dists[i] = sqrt(dists[i]); // unsquare distance cout << "\t" << i << "\t" << nn_idx[i] << "\t" << dists[i] << "\n"; } } } //---------------------------------------------------------------------- // getArgs - get command line arguments //---------------------------------------------------------------------- void getArgs(int argc, char **argv) { static ifstream dataStream; // data file stream static ifstream queryStream; // query file stream if (argc <= 1) { // no arguments cerr << "Usage:\n\n" << " ann_sample [-d dim] [-max m] [-nn k] [-e eps] [-df data]" " [-qf query]\n\n" << " where:\n" << " dim dimension of the space (default = 2)\n" << " m maximum number of data points (default = 1000)\n" << " k number of nearest neighbors per query (default 1)\n" << " eps the error bound (default = 0.0)\n" << " data name of file containing data points\n" << " query name of file containing query points\n\n" << " Results are sent to the standard output.\n" << "\n" << " To run this demo use:\n" << " ann_sample -df data_pts -qf query_pts\n"; exit(0); } int i = 1; while (i < argc) { // read arguments if (!strcmp(argv[i], "-d")) { // -d option dim = atoi(argv[++i]); // get dimension to dump } else if (!strcmp(argv[i], "-max")) { // -max option m_pts = atoi(argv[++i]); // get max number of points } else if (!strcmp(argv[i], "-nn")) { // -nn option k = atoi(argv[++i]); // get number of near neighbors } else if (!strcmp(argv[i], "-e")) { // -e option sscanf(argv[++i], "%lf", &eps); // get error bound } else if (!strcmp(argv[i], "-df")) { // -df option dataStream.open(argv[++i], ios::in);// open data file if (!dataStream) { cerr << "Cannot open data file\n"; exit(1); } data_in = &dataStream; // make this the data stream } else if (!strcmp(argv[i], "-qf")) { // -qf option queryStream.open(argv[++i], ios::in);// open query file if (!queryStream) { cerr << "Cannot open query file\n"; exit(1); } query_in = &queryStream; // make this query stream } else { // illegal syntax cerr << "Unrecognized option.\n"; exit(1); } i++; } if (data_in == NULL || query_in == NULL) { cerr << "-df and -qf options must be specified\n"; exit(1); } }
34.360825
77
0.546355
hrakaroo
299bda8a4f2e27ef2564f41758237be080a20ab4
2,832
cpp
C++
inject/breakpoint.cpp
CyrusVorazan/th09mp
c052633efda6254481b0bb96eaf4c3d01b1aa6fc
[ "MIT" ]
5
2020-03-04T16:40:10.000Z
2021-01-23T17:10:57.000Z
inject/breakpoint.cpp
CyrusVorazan/th09mp
c052633efda6254481b0bb96eaf4c3d01b1aa6fc
[ "MIT" ]
null
null
null
inject/breakpoint.cpp
CyrusVorazan/th09mp
c052633efda6254481b0bb96eaf4c3d01b1aa6fc
[ "MIT" ]
1
2021-01-20T21:28:54.000Z
2021-01-20T21:28:54.000Z
#include "breakpoint.h" #include "inject.h" #include <Windows.h> #include <cstdio> namespace th09mp { uint32_t __stdcall BPProcess(struct th09mp::BPInfo* BPInfo, struct th09mp::x86Regs* Regs) { uint32_t esp_previous = Regs->esp; th09mp::BPCaveExec DoCaveExec = BPInfo->BPFunc(Regs, BPInfo->BPParams); if (DoCaveExec == BPCaveExec::True) { Regs->Return = BPInfo->Cave; } uint32_t esp_difference = 0; if (esp_previous != Regs->esp) { esp_difference = Regs->esp - esp_previous; memmove((char*)Regs + esp_difference, Regs, sizeof(th09mp::x86Regs)); } return esp_difference; } void BPCreate(uint32_t addr, th09mp::BPFunc_t Func, void* BPParams, int BPParamsSize, int Cavesize) { if (Cavesize < 5) { std::fprintf(stderr, "BP ERROR: Cavesize (%d) less than 5\n", Cavesize); return; } struct th09mp::BP* Breakpoint = static_cast<th09mp::BP*>(::VirtualAlloc(NULL, sizeof(th09mp::BP) + BPParamsSize + Cavesize + 9, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); if (BPParams != nullptr) { memcpy(&Breakpoint->ParamsAndCodecave[0], BPParams, BPParamsSize); } Breakpoint->BPInfo.BPParams = &Breakpoint->ParamsAndCodecave[0]; memcpy(&Breakpoint->EntryCode[0], th09mp::BPEntry, sizeof(th09mp::BPEntry)); *(void**)&Breakpoint->EntryCode[4] = &Breakpoint->BPInfo; memset(&Breakpoint->int3Padding[0], 0xCC, 3); SetJumpTo(&Breakpoint->EntryCode[9], (int)&Breakpoint->EntryCode[13], (int)BPProcess); memset(&Breakpoint->ParamsAndCodecave[BPParamsSize], 0xCC, 3); Breakpoint->BPInfo.Cave = &Breakpoint->ParamsAndCodecave[BPParamsSize + 3]; memset(&Breakpoint->BPInfo.Cave[Cavesize + 5], 0xCC, 3); memcpy(Breakpoint->BPInfo.Cave, (void*)addr, Cavesize); Breakpoint->BPInfo.Cave[Cavesize] = 0xE9; SetJumpTo(&Breakpoint->BPInfo.Cave[Cavesize + 1], (int)&Breakpoint->BPInfo.Cave[Cavesize + 5], addr + Cavesize); int BPCaveByte = 0; while(BPCaveByte < Cavesize) { if ((Breakpoint->BPInfo.Cave[BPCaveByte] == (char)0xE8) || (Breakpoint->BPInfo.Cave[BPCaveByte] == (char)0xE9)) { uint32_t CallAddr = addr + *(int*)&Breakpoint->BPInfo.Cave[BPCaveByte + 1] + 5; SetJumpTo(&Breakpoint->BPInfo.Cave[BPCaveByte + 1], (int)&Breakpoint->BPInfo.Cave[BPCaveByte + 5], CallAddr); BPCaveByte += 5; continue; } else { BPCaveByte += 1; continue; } } Breakpoint->BPInfo.BPFunc = Func; Breakpoint->BPInfo.BPAddr = addr; Breakpoint->BPInfo.Cavesize = Cavesize; char* BPCall = new char[Cavesize]; BPCall[0] = 0xE8; SetJumpTo(&BPCall[1], addr + 5, (int)Breakpoint->EntryCode); for (int i = Cavesize - 5; i < Cavesize - 5; i++) { BPCall[5 + i] = 0x90; } WriteCode((char*)addr, BPCall, Cavesize); delete[] BPCall; return; } }
33.714286
182
0.663842
CyrusVorazan
299dda8fbd59750e04f4455c99cd9f808f7f5206
34,084
cc
C++
internal/ceres/covariance_impl.cc
txstc55/ceres-solver
95471f681b7e1b3354443bd02f1c2cdf2d8dd76d
[ "BSD-3-Clause" ]
2
2020-04-04T15:12:13.000Z
2021-06-10T10:50:00.000Z
internal/ceres/covariance_impl.cc
txstc55/ceres-solver
95471f681b7e1b3354443bd02f1c2cdf2d8dd76d
[ "BSD-3-Clause" ]
null
null
null
internal/ceres/covariance_impl.cc
txstc55/ceres-solver
95471f681b7e1b3354443bd02f1c2cdf2d8dd76d
[ "BSD-3-Clause" ]
2
2020-01-21T02:07:11.000Z
2021-06-10T10:50:32.000Z
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2015 Google Inc. All rights reserved. // http://ceres-solver.org/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * 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 Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // 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. // // Author: sameeragarwal@google.com (Sameer Agarwal) #include "ceres/covariance_impl.h" #include <algorithm> #include <cstdlib> #include <memory> #include <numeric> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include "Eigen/SparseCore" #include "Eigen/SparseQR" #include "Eigen/SVD" #include "ceres/compressed_col_sparse_matrix_utils.h" #include "ceres/compressed_row_sparse_matrix.h" #include "ceres/covariance.h" #include "ceres/crs_matrix.h" #include "ceres/internal/eigen.h" #include "ceres/map_util.h" #include "ceres/parallel_for.h" #include "ceres/parallel_utils.h" #include "ceres/parameter_block.h" #include "ceres/problem_impl.h" #include "ceres/residual_block.h" #include "ceres/suitesparse.h" #include "ceres/wall_time.h" #include "glog/logging.h" namespace ceres { namespace internal { using std::make_pair; using std::map; using std::pair; using std::sort; using std::swap; using std::vector; typedef vector<pair<const double*, const double*>> CovarianceBlocks; CovarianceImpl::CovarianceImpl(const Covariance::Options& options) : options_(options), is_computed_(false), is_valid_(false) { #ifdef CERES_NO_THREADS if (options_.num_threads > 1) { LOG(WARNING) << "No threading support is compiled into this binary; " << "only options.num_threads = 1 is supported. Switching " << "to single threaded mode."; options_.num_threads = 1; } #endif evaluate_options_.num_threads = options_.num_threads; evaluate_options_.apply_loss_function = options_.apply_loss_function; } CovarianceImpl::~CovarianceImpl() { } template <typename T> void CheckForDuplicates(vector<T> blocks) { sort(blocks.begin(), blocks.end()); typename vector<T>::iterator it = std::adjacent_find(blocks.begin(), blocks.end()); if (it != blocks.end()) { // In case there are duplicates, we search for their location. map<T, vector<int>> blocks_map; for (int i = 0; i < blocks.size(); ++i) { blocks_map[blocks[i]].push_back(i); } std::ostringstream duplicates; while (it != blocks.end()) { duplicates << "("; for (int i = 0; i < blocks_map[*it].size() - 1; ++i) { duplicates << blocks_map[*it][i] << ", "; } duplicates << blocks_map[*it].back() << ")"; it = std::adjacent_find(it + 1, blocks.end()); if (it < blocks.end()) { duplicates << " and "; } } LOG(FATAL) << "Covariance::Compute called with duplicate blocks at " << "indices " << duplicates.str(); } } bool CovarianceImpl::Compute(const CovarianceBlocks& covariance_blocks, ProblemImpl* problem) { CheckForDuplicates<pair<const double*, const double*>>(covariance_blocks); problem_ = problem; parameter_block_to_row_index_.clear(); covariance_matrix_.reset(NULL); is_valid_ = (ComputeCovarianceSparsity(covariance_blocks, problem) && ComputeCovarianceValues()); is_computed_ = true; return is_valid_; } bool CovarianceImpl::Compute(const vector<const double*>& parameter_blocks, ProblemImpl* problem) { CheckForDuplicates<const double*>(parameter_blocks); CovarianceBlocks covariance_blocks; for (int i = 0; i < parameter_blocks.size(); ++i) { for (int j = i; j < parameter_blocks.size(); ++j) { covariance_blocks.push_back(make_pair(parameter_blocks[i], parameter_blocks[j])); } } return Compute(covariance_blocks, problem); } bool CovarianceImpl::GetCovarianceBlockInTangentOrAmbientSpace( const double* original_parameter_block1, const double* original_parameter_block2, bool lift_covariance_to_ambient_space, double* covariance_block) const { CHECK(is_computed_) << "Covariance::GetCovarianceBlock called before Covariance::Compute"; CHECK(is_valid_) << "Covariance::GetCovarianceBlock called when Covariance::Compute " << "returned false."; // If either of the two parameter blocks is constant, then the // covariance block is also zero. if (constant_parameter_blocks_.count(original_parameter_block1) > 0 || constant_parameter_blocks_.count(original_parameter_block2) > 0) { const ProblemImpl::ParameterMap& parameter_map = problem_->parameter_map(); ParameterBlock* block1 = FindOrDie(parameter_map, const_cast<double*>(original_parameter_block1)); ParameterBlock* block2 = FindOrDie(parameter_map, const_cast<double*>(original_parameter_block2)); const int block1_size = block1->Size(); const int block2_size = block2->Size(); const int block1_local_size = block1->LocalSize(); const int block2_local_size = block2->LocalSize(); if (!lift_covariance_to_ambient_space) { MatrixRef(covariance_block, block1_local_size, block2_local_size) .setZero(); } else { MatrixRef(covariance_block, block1_size, block2_size).setZero(); } return true; } const double* parameter_block1 = original_parameter_block1; const double* parameter_block2 = original_parameter_block2; const bool transpose = parameter_block1 > parameter_block2; if (transpose) { swap(parameter_block1, parameter_block2); } // Find where in the covariance matrix the block is located. const int row_begin = FindOrDie(parameter_block_to_row_index_, parameter_block1); const int col_begin = FindOrDie(parameter_block_to_row_index_, parameter_block2); const int* rows = covariance_matrix_->rows(); const int* cols = covariance_matrix_->cols(); const int row_size = rows[row_begin + 1] - rows[row_begin]; const int* cols_begin = cols + rows[row_begin]; // The only part that requires work is walking the compressed column // vector to determine where the set of columns correspnding to the // covariance block begin. int offset = 0; while (cols_begin[offset] != col_begin && offset < row_size) { ++offset; } if (offset == row_size) { LOG(ERROR) << "Unable to find covariance block for " << original_parameter_block1 << " " << original_parameter_block2; return false; } const ProblemImpl::ParameterMap& parameter_map = problem_->parameter_map(); ParameterBlock* block1 = FindOrDie(parameter_map, const_cast<double*>(parameter_block1)); ParameterBlock* block2 = FindOrDie(parameter_map, const_cast<double*>(parameter_block2)); const LocalParameterization* local_param1 = block1->local_parameterization(); const LocalParameterization* local_param2 = block2->local_parameterization(); const int block1_size = block1->Size(); const int block1_local_size = block1->LocalSize(); const int block2_size = block2->Size(); const int block2_local_size = block2->LocalSize(); ConstMatrixRef cov(covariance_matrix_->values() + rows[row_begin], block1_size, row_size); // Fast path when there are no local parameterizations or if the // user does not want it lifted to the ambient space. if ((local_param1 == NULL && local_param2 == NULL) || !lift_covariance_to_ambient_space) { if (transpose) { MatrixRef(covariance_block, block2_local_size, block1_local_size) = cov.block(0, offset, block1_local_size, block2_local_size).transpose(); } else { MatrixRef(covariance_block, block1_local_size, block2_local_size) = cov.block(0, offset, block1_local_size, block2_local_size); } return true; } // If local parameterizations are used then the covariance that has // been computed is in the tangent space and it needs to be lifted // back to the ambient space. // // This is given by the formula // // C'_12 = J_1 C_12 J_2' // // Where C_12 is the local tangent space covariance for parameter // blocks 1 and 2. J_1 and J_2 are respectively the local to global // jacobians for parameter blocks 1 and 2. // // See Result 5.11 on page 142 of Hartley & Zisserman (2nd Edition) // for a proof. // // TODO(sameeragarwal): Add caching of local parameterization, so // that they are computed just once per parameter block. Matrix block1_jacobian(block1_size, block1_local_size); if (local_param1 == NULL) { block1_jacobian.setIdentity(); } else { local_param1->ComputeJacobian(parameter_block1, block1_jacobian.data()); } Matrix block2_jacobian(block2_size, block2_local_size); // Fast path if the user is requesting a diagonal block. if (parameter_block1 == parameter_block2) { block2_jacobian = block1_jacobian; } else { if (local_param2 == NULL) { block2_jacobian.setIdentity(); } else { local_param2->ComputeJacobian(parameter_block2, block2_jacobian.data()); } } if (transpose) { MatrixRef(covariance_block, block2_size, block1_size) = block2_jacobian * cov.block(0, offset, block1_local_size, block2_local_size).transpose() * block1_jacobian.transpose(); } else { MatrixRef(covariance_block, block1_size, block2_size) = block1_jacobian * cov.block(0, offset, block1_local_size, block2_local_size) * block2_jacobian.transpose(); } return true; } bool CovarianceImpl::GetCovarianceMatrixInTangentOrAmbientSpace( const vector<const double*>& parameters, bool lift_covariance_to_ambient_space, double* covariance_matrix) const { CHECK(is_computed_) << "Covariance::GetCovarianceMatrix called before Covariance::Compute"; CHECK(is_valid_) << "Covariance::GetCovarianceMatrix called when Covariance::Compute " << "returned false."; const ProblemImpl::ParameterMap& parameter_map = problem_->parameter_map(); // For OpenMP compatibility we need to define these vectors in advance const int num_parameters = parameters.size(); vector<int> parameter_sizes; vector<int> cum_parameter_size; parameter_sizes.reserve(num_parameters); cum_parameter_size.resize(num_parameters + 1); cum_parameter_size[0] = 0; for (int i = 0; i < num_parameters; ++i) { ParameterBlock* block = FindOrDie(parameter_map, const_cast<double*>(parameters[i])); if (lift_covariance_to_ambient_space) { parameter_sizes.push_back(block->Size()); } else { parameter_sizes.push_back(block->LocalSize()); } } std::partial_sum(parameter_sizes.begin(), parameter_sizes.end(), cum_parameter_size.begin() + 1); const int max_covariance_block_size = *std::max_element(parameter_sizes.begin(), parameter_sizes.end()); const int covariance_size = cum_parameter_size.back(); // Assemble the blocks in the covariance matrix. MatrixRef covariance(covariance_matrix, covariance_size, covariance_size); const int num_threads = options_.num_threads; std::unique_ptr<double[]> workspace( new double[num_threads * max_covariance_block_size * max_covariance_block_size]); bool success = true; // Technically the following code is a double nested loop where // i = 1:n, j = i:n. int iteration_count = (num_parameters * (num_parameters + 1)) / 2; problem_->context()->EnsureMinimumThreads(num_threads); ParallelFor( problem_->context(), 0, iteration_count, num_threads, [&](int thread_id, int k) { int i, j; LinearIndexToUpperTriangularIndex(k, num_parameters, &i, &j); int covariance_row_idx = cum_parameter_size[i]; int covariance_col_idx = cum_parameter_size[j]; int size_i = parameter_sizes[i]; int size_j = parameter_sizes[j]; double* covariance_block = workspace.get() + thread_id * max_covariance_block_size * max_covariance_block_size; if (!GetCovarianceBlockInTangentOrAmbientSpace( parameters[i], parameters[j], lift_covariance_to_ambient_space, covariance_block)) { success = false; } covariance.block(covariance_row_idx, covariance_col_idx, size_i, size_j) = MatrixRef(covariance_block, size_i, size_j); if (i != j) { covariance.block(covariance_col_idx, covariance_row_idx, size_j, size_i) = MatrixRef(covariance_block, size_i, size_j).transpose(); } }); return success; } // Determine the sparsity pattern of the covariance matrix based on // the block pairs requested by the user. bool CovarianceImpl::ComputeCovarianceSparsity( const CovarianceBlocks& original_covariance_blocks, ProblemImpl* problem) { EventLogger event_logger("CovarianceImpl::ComputeCovarianceSparsity"); // Determine an ordering for the parameter block, by sorting the // parameter blocks by their pointers. vector<double*> all_parameter_blocks; problem->GetParameterBlocks(&all_parameter_blocks); const ProblemImpl::ParameterMap& parameter_map = problem->parameter_map(); std::unordered_set<ParameterBlock*> parameter_blocks_in_use; vector<ResidualBlock*> residual_blocks; problem->GetResidualBlocks(&residual_blocks); for (int i = 0; i < residual_blocks.size(); ++i) { ResidualBlock* residual_block = residual_blocks[i]; parameter_blocks_in_use.insert(residual_block->parameter_blocks(), residual_block->parameter_blocks() + residual_block->NumParameterBlocks()); } constant_parameter_blocks_.clear(); vector<double*>& active_parameter_blocks = evaluate_options_.parameter_blocks; active_parameter_blocks.clear(); for (int i = 0; i < all_parameter_blocks.size(); ++i) { double* parameter_block = all_parameter_blocks[i]; ParameterBlock* block = FindOrDie(parameter_map, parameter_block); if (!block->IsConstant() && (parameter_blocks_in_use.count(block) > 0)) { active_parameter_blocks.push_back(parameter_block); } else { constant_parameter_blocks_.insert(parameter_block); } } std::sort(active_parameter_blocks.begin(), active_parameter_blocks.end()); // Compute the number of rows. Map each parameter block to the // first row corresponding to it in the covariance matrix using the // ordering of parameter blocks just constructed. int num_rows = 0; parameter_block_to_row_index_.clear(); for (int i = 0; i < active_parameter_blocks.size(); ++i) { double* parameter_block = active_parameter_blocks[i]; const int parameter_block_size = problem->ParameterBlockLocalSize(parameter_block); parameter_block_to_row_index_[parameter_block] = num_rows; num_rows += parameter_block_size; } // Compute the number of non-zeros in the covariance matrix. Along // the way flip any covariance blocks which are in the lower // triangular part of the matrix. int num_nonzeros = 0; CovarianceBlocks covariance_blocks; for (int i = 0; i < original_covariance_blocks.size(); ++i) { const pair<const double*, const double*>& block_pair = original_covariance_blocks[i]; if (constant_parameter_blocks_.count(block_pair.first) > 0 || constant_parameter_blocks_.count(block_pair.second) > 0) { continue; } int index1 = FindOrDie(parameter_block_to_row_index_, block_pair.first); int index2 = FindOrDie(parameter_block_to_row_index_, block_pair.second); const int size1 = problem->ParameterBlockLocalSize(block_pair.first); const int size2 = problem->ParameterBlockLocalSize(block_pair.second); num_nonzeros += size1 * size2; // Make sure we are constructing a block upper triangular matrix. if (index1 > index2) { covariance_blocks.push_back(make_pair(block_pair.second, block_pair.first)); } else { covariance_blocks.push_back(block_pair); } } if (covariance_blocks.size() == 0) { VLOG(2) << "No non-zero covariance blocks found"; covariance_matrix_.reset(NULL); return true; } // Sort the block pairs. As a consequence we get the covariance // blocks as they will occur in the CompressedRowSparseMatrix that // will store the covariance. sort(covariance_blocks.begin(), covariance_blocks.end()); // Fill the sparsity pattern of the covariance matrix. covariance_matrix_.reset( new CompressedRowSparseMatrix(num_rows, num_rows, num_nonzeros)); int* rows = covariance_matrix_->mutable_rows(); int* cols = covariance_matrix_->mutable_cols(); // Iterate over parameter blocks and in turn over the rows of the // covariance matrix. For each parameter block, look in the upper // triangular part of the covariance matrix to see if there are any // blocks requested by the user. If this is the case then fill out a // set of compressed rows corresponding to this parameter block. // // The key thing that makes this loop work is the fact that the // row/columns of the covariance matrix are ordered by the pointer // values of the parameter blocks. Thus iterating over the keys of // parameter_block_to_row_index_ corresponds to iterating over the // rows of the covariance matrix in order. int i = 0; // index into covariance_blocks. int cursor = 0; // index into the covariance matrix. for (const auto& entry : parameter_block_to_row_index_) { const double* row_block = entry.first; const int row_block_size = problem->ParameterBlockLocalSize(row_block); int row_begin = entry.second; // Iterate over the covariance blocks contained in this row block // and count the number of columns in this row block. int num_col_blocks = 0; int num_columns = 0; for (int j = i; j < covariance_blocks.size(); ++j, ++num_col_blocks) { const pair<const double*, const double*>& block_pair = covariance_blocks[j]; if (block_pair.first != row_block) { break; } num_columns += problem->ParameterBlockLocalSize(block_pair.second); } // Fill out all the compressed rows for this parameter block. for (int r = 0; r < row_block_size; ++r) { rows[row_begin + r] = cursor; for (int c = 0; c < num_col_blocks; ++c) { const double* col_block = covariance_blocks[i + c].second; const int col_block_size = problem->ParameterBlockLocalSize(col_block); int col_begin = FindOrDie(parameter_block_to_row_index_, col_block); for (int k = 0; k < col_block_size; ++k) { cols[cursor++] = col_begin++; } } } i+= num_col_blocks; } rows[num_rows] = cursor; return true; } bool CovarianceImpl::ComputeCovarianceValues() { if (options_.algorithm_type == DENSE_SVD) { return ComputeCovarianceValuesUsingDenseSVD(); } if (options_.algorithm_type == SPARSE_QR) { if (options_.sparse_linear_algebra_library_type == EIGEN_SPARSE) { return ComputeCovarianceValuesUsingEigenSparseQR(); } if (options_.sparse_linear_algebra_library_type == SUITE_SPARSE) { #if !defined(CERES_NO_SUITESPARSE) return ComputeCovarianceValuesUsingSuiteSparseQR(); #else LOG(ERROR) << "SuiteSparse is required to use the SPARSE_QR algorithm " << "with " << "Covariance::Options::sparse_linear_algebra_library_type " << "= SUITE_SPARSE."; return false; #endif } LOG(ERROR) << "Unsupported " << "Covariance::Options::sparse_linear_algebra_library_type " << "= " << SparseLinearAlgebraLibraryTypeToString( options_.sparse_linear_algebra_library_type); return false; } LOG(ERROR) << "Unsupported Covariance::Options::algorithm_type = " << CovarianceAlgorithmTypeToString(options_.algorithm_type); return false; } bool CovarianceImpl::ComputeCovarianceValuesUsingSuiteSparseQR() { EventLogger event_logger( "CovarianceImpl::ComputeCovarianceValuesUsingSparseQR"); #ifndef CERES_NO_SUITESPARSE if (covariance_matrix_.get() == NULL) { // Nothing to do, all zeros covariance matrix. return true; } CRSMatrix jacobian; problem_->Evaluate(evaluate_options_, NULL, NULL, NULL, &jacobian); event_logger.AddEvent("Evaluate"); // Construct a compressed column form of the Jacobian. const int num_rows = jacobian.num_rows; const int num_cols = jacobian.num_cols; const int num_nonzeros = jacobian.values.size(); vector<SuiteSparse_long> transpose_rows(num_cols + 1, 0); vector<SuiteSparse_long> transpose_cols(num_nonzeros, 0); vector<double> transpose_values(num_nonzeros, 0); for (int idx = 0; idx < num_nonzeros; ++idx) { transpose_rows[jacobian.cols[idx] + 1] += 1; } for (int i = 1; i < transpose_rows.size(); ++i) { transpose_rows[i] += transpose_rows[i - 1]; } for (int r = 0; r < num_rows; ++r) { for (int idx = jacobian.rows[r]; idx < jacobian.rows[r + 1]; ++idx) { const int c = jacobian.cols[idx]; const int transpose_idx = transpose_rows[c]; transpose_cols[transpose_idx] = r; transpose_values[transpose_idx] = jacobian.values[idx]; ++transpose_rows[c]; } } for (int i = transpose_rows.size() - 1; i > 0 ; --i) { transpose_rows[i] = transpose_rows[i - 1]; } transpose_rows[0] = 0; cholmod_sparse cholmod_jacobian; cholmod_jacobian.nrow = num_rows; cholmod_jacobian.ncol = num_cols; cholmod_jacobian.nzmax = num_nonzeros; cholmod_jacobian.nz = NULL; cholmod_jacobian.p = reinterpret_cast<void*>(&transpose_rows[0]); cholmod_jacobian.i = reinterpret_cast<void*>(&transpose_cols[0]); cholmod_jacobian.x = reinterpret_cast<void*>(&transpose_values[0]); cholmod_jacobian.z = NULL; cholmod_jacobian.stype = 0; // Matrix is not symmetric. cholmod_jacobian.itype = CHOLMOD_LONG; cholmod_jacobian.xtype = CHOLMOD_REAL; cholmod_jacobian.dtype = CHOLMOD_DOUBLE; cholmod_jacobian.sorted = 1; cholmod_jacobian.packed = 1; cholmod_common cc; cholmod_l_start(&cc); cholmod_sparse* R = NULL; SuiteSparse_long* permutation = NULL; // Compute a Q-less QR factorization of the Jacobian. Since we are // only interested in inverting J'J = R'R, we do not need Q. This // saves memory and gives us R as a permuted compressed column // sparse matrix. // // TODO(sameeragarwal): Currently the symbolic factorization and the // numeric factorization is done at the same time, and this does not // explicitly account for the block column and row structure in the // matrix. When using AMD, we have observed in the past that // computing the ordering with the block matrix is significantly // more efficient, both in runtime as well as the quality of // ordering computed. So, it maybe worth doing that analysis // separately. const SuiteSparse_long rank = SuiteSparseQR<double>(SPQR_ORDERING_BESTAMD, SPQR_DEFAULT_TOL, cholmod_jacobian.ncol, &cholmod_jacobian, &R, &permutation, &cc); event_logger.AddEvent("Numeric Factorization"); if (R == nullptr) { LOG(ERROR) << "Something is wrong. SuiteSparseQR returned R = nullptr."; free(permutation); cholmod_l_finish(&cc); return false; } if (rank < cholmod_jacobian.ncol) { LOG(ERROR) << "Jacobian matrix is rank deficient. " << "Number of columns: " << cholmod_jacobian.ncol << " rank: " << rank; free(permutation); cholmod_l_free_sparse(&R, &cc); cholmod_l_finish(&cc); return false; } vector<int> inverse_permutation(num_cols); if (permutation) { for (SuiteSparse_long i = 0; i < num_cols; ++i) { inverse_permutation[permutation[i]] = i; } } else { for (SuiteSparse_long i = 0; i < num_cols; ++i) { inverse_permutation[i] = i; } } const int* rows = covariance_matrix_->rows(); const int* cols = covariance_matrix_->cols(); double* values = covariance_matrix_->mutable_values(); // The following loop exploits the fact that the i^th column of A^{-1} // is given by the solution to the linear system // // A x = e_i // // where e_i is a vector with e(i) = 1 and all other entries zero. // // Since the covariance matrix is symmetric, the i^th row and column // are equal. const int num_threads = options_.num_threads; std::unique_ptr<double[]> workspace(new double[num_threads * num_cols]); problem_->context()->EnsureMinimumThreads(num_threads); ParallelFor( problem_->context(), 0, num_cols, num_threads, [&](int thread_id, int r) { const int row_begin = rows[r]; const int row_end = rows[r + 1]; if (row_end != row_begin) { double* solution = workspace.get() + thread_id * num_cols; SolveRTRWithSparseRHS<SuiteSparse_long>( num_cols, static_cast<SuiteSparse_long*>(R->i), static_cast<SuiteSparse_long*>(R->p), static_cast<double*>(R->x), inverse_permutation[r], solution); for (int idx = row_begin; idx < row_end; ++idx) { const int c = cols[idx]; values[idx] = solution[inverse_permutation[c]]; } } }); free(permutation); cholmod_l_free_sparse(&R, &cc); cholmod_l_finish(&cc); event_logger.AddEvent("Inversion"); return true; #else // CERES_NO_SUITESPARSE return false; #endif // CERES_NO_SUITESPARSE } bool CovarianceImpl::ComputeCovarianceValuesUsingDenseSVD() { EventLogger event_logger( "CovarianceImpl::ComputeCovarianceValuesUsingDenseSVD"); if (covariance_matrix_.get() == NULL) { // Nothing to do, all zeros covariance matrix. return true; } CRSMatrix jacobian; problem_->Evaluate(evaluate_options_, NULL, NULL, NULL, &jacobian); event_logger.AddEvent("Evaluate"); Matrix dense_jacobian(jacobian.num_rows, jacobian.num_cols); dense_jacobian.setZero(); for (int r = 0; r < jacobian.num_rows; ++r) { for (int idx = jacobian.rows[r]; idx < jacobian.rows[r + 1]; ++idx) { const int c = jacobian.cols[idx]; dense_jacobian(r, c) = jacobian.values[idx]; } } event_logger.AddEvent("ConvertToDenseMatrix"); Eigen::JacobiSVD<Matrix> svd(dense_jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV); event_logger.AddEvent("SingularValueDecomposition"); const Vector singular_values = svd.singularValues(); const int num_singular_values = singular_values.rows(); Vector inverse_squared_singular_values(num_singular_values); inverse_squared_singular_values.setZero(); const double max_singular_value = singular_values[0]; const double min_singular_value_ratio = sqrt(options_.min_reciprocal_condition_number); const bool automatic_truncation = (options_.null_space_rank < 0); const int max_rank = std::min(num_singular_values, num_singular_values - options_.null_space_rank); // Compute the squared inverse of the singular values. Truncate the // computation based on min_singular_value_ratio and // null_space_rank. When either of these two quantities are active, // the resulting covariance matrix is a Moore-Penrose inverse // instead of a regular inverse. for (int i = 0; i < max_rank; ++i) { const double singular_value_ratio = singular_values[i] / max_singular_value; if (singular_value_ratio < min_singular_value_ratio) { // Since the singular values are in decreasing order, if // automatic truncation is enabled, then from this point on // all values will fail the ratio test and there is nothing to // do in this loop. if (automatic_truncation) { break; } else { LOG(ERROR) << "Error: Covariance matrix is near rank deficient " << "and the user did not specify a non-zero" << "Covariance::Options::null_space_rank " << "to enable the computation of a Pseudo-Inverse. " << "Reciprocal condition number: " << singular_value_ratio * singular_value_ratio << " " << "min_reciprocal_condition_number: " << options_.min_reciprocal_condition_number; return false; } } inverse_squared_singular_values[i] = 1.0 / (singular_values[i] * singular_values[i]); } Matrix dense_covariance = svd.matrixV() * inverse_squared_singular_values.asDiagonal() * svd.matrixV().transpose(); event_logger.AddEvent("PseudoInverse"); const int num_rows = covariance_matrix_->num_rows(); const int* rows = covariance_matrix_->rows(); const int* cols = covariance_matrix_->cols(); double* values = covariance_matrix_->mutable_values(); for (int r = 0; r < num_rows; ++r) { for (int idx = rows[r]; idx < rows[r + 1]; ++idx) { const int c = cols[idx]; values[idx] = dense_covariance(r, c); } } event_logger.AddEvent("CopyToCovarianceMatrix"); return true; } bool CovarianceImpl::ComputeCovarianceValuesUsingEigenSparseQR() { EventLogger event_logger( "CovarianceImpl::ComputeCovarianceValuesUsingEigenSparseQR"); if (covariance_matrix_.get() == NULL) { // Nothing to do, all zeros covariance matrix. return true; } CRSMatrix jacobian; problem_->Evaluate(evaluate_options_, NULL, NULL, NULL, &jacobian); event_logger.AddEvent("Evaluate"); typedef Eigen::SparseMatrix<double, Eigen::ColMajor> EigenSparseMatrix; // Convert the matrix to column major order as required by SparseQR. EigenSparseMatrix sparse_jacobian = Eigen::MappedSparseMatrix<double, Eigen::RowMajor>( jacobian.num_rows, jacobian.num_cols, static_cast<int>(jacobian.values.size()), jacobian.rows.data(), jacobian.cols.data(), jacobian.values.data()); event_logger.AddEvent("ConvertToSparseMatrix"); Eigen::SparseQR<EigenSparseMatrix, Eigen::COLAMDOrdering<int>> qr_solver(sparse_jacobian); event_logger.AddEvent("QRDecomposition"); if (qr_solver.info() != Eigen::Success) { LOG(ERROR) << "Eigen::SparseQR decomposition failed."; return false; } if (qr_solver.rank() < jacobian.num_cols) { LOG(ERROR) << "Jacobian matrix is rank deficient. " << "Number of columns: " << jacobian.num_cols << " rank: " << qr_solver.rank(); return false; } const int* rows = covariance_matrix_->rows(); const int* cols = covariance_matrix_->cols(); double* values = covariance_matrix_->mutable_values(); // Compute the inverse column permutation used by QR factorization. Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> inverse_permutation = qr_solver.colsPermutation().inverse(); // The following loop exploits the fact that the i^th column of A^{-1} // is given by the solution to the linear system // // A x = e_i // // where e_i is a vector with e(i) = 1 and all other entries zero. // // Since the covariance matrix is symmetric, the i^th row and column // are equal. const int num_cols = jacobian.num_cols; const int num_threads = options_.num_threads; std::unique_ptr<double[]> workspace(new double[num_threads * num_cols]); problem_->context()->EnsureMinimumThreads(num_threads); ParallelFor( problem_->context(), 0, num_cols, num_threads, [&](int thread_id, int r) { const int row_begin = rows[r]; const int row_end = rows[r + 1]; if (row_end != row_begin) { double* solution = workspace.get() + thread_id * num_cols; SolveRTRWithSparseRHS<int>( num_cols, qr_solver.matrixR().innerIndexPtr(), qr_solver.matrixR().outerIndexPtr(), &qr_solver.matrixR().data().value(0), inverse_permutation.indices().coeff(r), solution); // Assign the values of the computed covariance using the // inverse permutation used in the QR factorization. for (int idx = row_begin; idx < row_end; ++idx) { const int c = cols[idx]; values[idx] = solution[inverse_permutation.indices().coeff(c)]; } } }); event_logger.AddEvent("Inverse"); return true; } } // namespace internal } // namespace ceres
37.088139
80
0.685424
txstc55
29a0d0b895ffca8b75cdc853c3c3bb7865089cc0
1,238
cc
C++
translator/attribute.cc
wahibium/KFF
609e5afac8a9477dd1af31eacadbcd5b61530113
[ "MIT" ]
11
2015-06-08T22:16:47.000Z
2022-03-19T15:11:14.000Z
translator/attribute.cc
wahibium/KFF
609e5afac8a9477dd1af31eacadbcd5b61530113
[ "MIT" ]
null
null
null
translator/attribute.cc
wahibium/KFF
609e5afac8a9477dd1af31eacadbcd5b61530113
[ "MIT" ]
4
2015-06-12T21:24:47.000Z
2021-04-23T09:58:33.000Z
#include "attribute.h" #include "common.h" #include "range.h" namespace kff { namespace translator { const std::string GridCallAttribute::name = "GridCall"; GridCallAttribute::GridCallAttribute(SgInitializedName *grid_var, KIND k): grid_var_(grid_var), kind_(k) { } GridCallAttribute::~GridCallAttribute() {} AstAttribute *GridCallAttribute::copy() { return new GridCallAttribute(grid_var_, kind_); } bool GridCallAttribute::IsGet() { return kind_ == GET; } bool GridCallAttribute::IsGetPeriodic() { return kind_ == GET_PERIODIC; } bool GridCallAttribute::IsEmit() { return kind_ == EMIT; } void CopyAllAttributes(SgNode *dst, SgNode *src) { // ROSE does not seem to have API for locating all attached // attributes or copy them all. So, as an ad-hoc work around, list // all potentially attahced attributes here to get them copied to // the destination node. if (rose_util::GetASTAttribute<StencilIndexVarAttribute>(src)) { rose_util::CopyASTAttribute<StencilIndexVarAttribute>( dst, src, false); LOG_DEBUG() << "StencilIndexVarAttribute found at: " << src->unparseToString() << "\n"; } } } // namespace translator } // namespace kff
25.791667
68
0.693053
wahibium
29a1f87e589ddd72c40a242dbb70a3ec6f5b5507
4,679
cpp
C++
tc 160+/PointsGame.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/PointsGame.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/PointsGame.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> #include <cmath> using namespace std; vector<int> X, Y; const int SZ = 531441; bool a_done[SZ], b_done[SZ]; double a_dp[SZ], b_dp[SZ]; int n; int all; int encode(int white, int used) { int ret = 0; for (int i=0; i<n; ++i) { if (!(used & (1<<i))) { ret = ret*3 + 0; } else if (white & (1<<i)) { ret = ret*3 + 1; } else { ret = ret*3 + 2; } } return ret; } void decode(int code, int &white, int &used) { white = 0; used = 0; for (int i=n-1; i>=0; --i) { int t = code % 3; code /= 3; if (t != 0) { used |= (1<<i); if (t == 1) { white |= (1<<i); } } } } inline double sqr(int x) { return x*x; } double dist(int a, int b) { return sqrt(sqr(X[a]-X[b]) + sqr(Y[a]-Y[b])); } double calc(int white) { double ret = 0; for (int i=0; i<n; ++i) { if (white & (1<<i)) { for (int j=0; j<n; ++j) { if (!(white & (1<<j))) { ret += dist(i, j); } } } } return ret; } double beta(int); double alpha(int state) { if (a_done[state]) { return a_dp[state]; } a_done[state] = 1; int white, used; decode(state, white, used); if (used == all) { return (a_dp[state] = calc(white)); } double sol = 0.0; for (int i=0; i<n; ++i) { if (!(used & (1<<i))) { sol = max(sol, beta(encode(white | (1<<i), used | (1<<i)))); } } return (a_dp[state] = sol); } double beta(int state) { if (b_done[state]) { return b_dp[state]; } b_done[state] = 1; int white, used; decode(state, white, used); if (used == all) { return (b_dp[state] = calc(white)); } double sol = 1e32; for (int i=0; i<n; ++i) { if (!(used & (1<<i))) { sol = min(sol, alpha(encode(white, used | (1<<i)))); } } return (b_dp[state] = sol); } class PointsGame { public: double gameValue(vector <int> pointsX, vector <int> pointsY) { X = pointsX; Y = pointsY; n = X.size(); memset(a_done, 0, sizeof a_done); memset(b_done, 0, sizeof b_done); all = (1<<n) - 1; return alpha(0); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {0,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 1.0; verify_case(0, Arg2, gameValue(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {0,0,1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,5,0,5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 12.198039027185569; verify_case(1, Arg2, gameValue(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {0,0,0,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,1,5,6}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 12.0; verify_case(2, Arg2, gameValue(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {0,1,2,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,0,0,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 6.0; verify_case(3, Arg2, gameValue(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PointsGame ___test; ___test.run_test(-1); } // END CUT HERE
30.782895
315
0.499466
ibudiselic
29a2be66a80ba00de24894c5d643cda4e492e37d
2,988
cpp
C++
tc 160+/TrueFalse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/TrueFalse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/TrueFalse.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; char cur[20]; bool ok[20]; int n; vector<int> c; vector<string> a; int cnt(int x) { int ret = 0; for (int i=0; i<n; ++i) if (cur[i] == a[x][i]) { ++ret; ok[i] = 1; } return ret; } bool go(int x) { if (x == n) { memset(ok, 0, sizeof ok); for (int i=0; i<(int)a.size(); ++i) if (cnt(i) != c[i]) return false; for (int i=0; i<n; ++i) if (!ok[i]) return false; return true; } for (char c='F'; c<='T'; c+='T'-'F') { cur[x] = c; if (go(x+1)) return true; } return false; } class TrueFalse { public: string answerKey(vector <string> graded) { c.clear(); a.clear(); for (int i=0; i<(int)graded.size(); ++i) { istringstream is(graded[i]); int x; string s; is >> x >> s; c.push_back(x); a.push_back(s); } n = a[0].size(); cur[n] = '\0'; if (go(0)) return string(cur); else return "inconsistent"; return "OH NOUZ"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"2 TTF", "1 FTF", "2 FTT"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "TTT"; verify_case(0, Arg1, answerKey(Arg0)); } void test_case_1() { string Arr0[] = {"7 TTFFTFT"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "TTFFTFT"; verify_case(1, Arg1, answerKey(Arg0)); } void test_case_2() { string Arr0[] = {"9 TTTFFFFTTFFTTFT", "7 FFFFFFFFFFFFFFF"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "inconsistent"; verify_case(2, Arg1, answerKey(Arg0)); } void test_case_3() { string Arr0[] = {"9 TTTFFFFTTFFTTFT", "7 FFFFFFFFFFFFFFF", "8 TTTTTTTTTTTTTTT"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "FFFFFFFTTTTTTTT"; verify_case(3, Arg1, answerKey(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TrueFalse ___test; ___test.run_test(-1); } // END CUT HERE
28.457143
315
0.563253
ibudiselic
29a5cae4b561c912cc31fafd84e4382a3c1d69e1
1,367
cpp
C++
clickhouse/columns/uuid.cpp
inkrement/clickhouse-cpp
4bdd041213196c6c3eb885ea6312b0bbe5545437
[ "Apache-2.0" ]
null
null
null
clickhouse/columns/uuid.cpp
inkrement/clickhouse-cpp
4bdd041213196c6c3eb885ea6312b0bbe5545437
[ "Apache-2.0" ]
null
null
null
clickhouse/columns/uuid.cpp
inkrement/clickhouse-cpp
4bdd041213196c6c3eb885ea6312b0bbe5545437
[ "Apache-2.0" ]
null
null
null
#include "uuid.h" #include "utils.h" #include <stdexcept> namespace clickhouse { ColumnUUID::ColumnUUID() : Column(Type::CreateUUID()) , data_(std::make_shared<ColumnUInt64>()) { } ColumnUUID::ColumnUUID(ColumnRef data) : Column(Type::CreateUUID()) , data_(data->As<ColumnUInt64>()) { if (data_->Size()%2 != 0) { throw std::runtime_error("number of entries must be even (two 64-bit numbers for each UUID)"); } } void ColumnUUID::Append(const UInt128& value) { data_->Append(value.first); data_->Append(value.second); } void ColumnUUID::Clear() { data_->Clear(); } const UInt128 ColumnUUID::At(size_t n) const { return UInt128(data_->At(n * 2), data_->At(n * 2 + 1)); } const UInt128 ColumnUUID::operator [] (size_t n) const { return UInt128((*data_)[n * 2], (*data_)[n * 2 + 1]); } void ColumnUUID::Append(ColumnRef column) { if (auto col = column->As<ColumnUUID>()) { data_->Append(col->data_); } } bool ColumnUUID::Load(CodedInputStream* input, size_t rows) { return data_->Load(input, rows * 2); } void ColumnUUID::Save(CodedOutputStream* output) { data_->Save(output); } size_t ColumnUUID::Size() const { return data_->Size() / 2; } ColumnRef ColumnUUID::Slice(size_t begin, size_t len) { return std::make_shared<ColumnUUID>(data_->Slice(begin * 2, len * 2)); } }
21.359375
102
0.647403
inkrement
29a62417cd03ec6cb9be9eb57c21cbba91f2182c
24,218
cpp
C++
openstudiocore/src/utilities/sql/Test/SqlFile_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2017-10-13T09:23:04.000Z
2017-10-13T09:23:04.000Z
openstudiocore/src/utilities/sql/Test/SqlFile_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
null
null
null
openstudiocore/src/utilities/sql/Test/SqlFile_GTest.cpp
OpenStudioThailand/OpenStudio
4e2173955e687ef1b934904acc10939ac0bed52f
[ "MIT" ]
1
2022-03-20T13:19:42.000Z
2022-03-20T13:19:42.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) 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. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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 HOLDER, THE UNITED STATES GOVERNMENT, OR ANY 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. **********************************************************************************************************************/ #include <gtest/gtest.h> #include "SqlFileFixture.hpp" #include "../../time/Date.hpp" #include "../../time/Calendar.hpp" #include "../../core/Optional.hpp" #include "../../data/DataEnums.hpp" #include "../../data/TimeSeries.hpp" #include "../../filetypes/EpwFile.hpp" #include "../../units/UnitFactory.hpp" #include "../../core/Application.hpp" #include <QRegularExpression> #include <resources.hxx> #include <iostream> using namespace std; using namespace boost; using namespace openstudio; TEST_F(SqlFileFixture, SummaryValues) { // check values ASSERT_TRUE(sqlFile.netSiteEnergy()); ASSERT_TRUE(sqlFile.totalSiteEnergy()); ASSERT_TRUE(sqlFile.netSourceEnergy()); ASSERT_TRUE(sqlFile.totalSourceEnergy()); EXPECT_NEAR(224.91, *(sqlFile.netSiteEnergy()), 2); // for 6.0, was 222.69 EXPECT_NEAR(224.91, *(sqlFile.totalSiteEnergy()), 2); // for 6.0, was 222.69 EXPECT_NEAR(570.38, *(sqlFile.netSourceEnergy()), 2); // for 6.0, was 564.41 EXPECT_NEAR(570.38, *(sqlFile.totalSourceEnergy()), 2); // for 6.0, was 564.41 } TEST_F(SqlFileFixture, EnvPeriods) { std::vector<std::string> availableEnvPeriods = sqlFile.availableEnvPeriods(); ASSERT_FALSE(availableEnvPeriods.empty()); EXPECT_EQ(static_cast<unsigned>(1), availableEnvPeriods.size()); //EXPECT_EQ("Chicago Ohare Intl Ap IL USA TMY3 WMO#=725300", availableEnvPeriods[0]); EXPECT_EQ("CHICAGO OHARE INTL AP IL USA TMY3 WMO#=725300", availableEnvPeriods[0]); } TEST_F(SqlFileFixture, TimeSeriesValues) { std::vector<std::string> availableEnvPeriods = sqlFile.availableEnvPeriods(); ASSERT_FALSE(availableEnvPeriods.empty()); EXPECT_EQ(static_cast<unsigned>(1), availableEnvPeriods.size()); //EXPECT_EQ("Chicago Ohare Intl Ap IL USA TMY3 WMO#=725300", availableEnvPeriods[0]); EXPECT_EQ("CHICAGO OHARE INTL AP IL USA TMY3 WMO#=725300", availableEnvPeriods[0]); openstudio::OptionalTimeSeries ts = sqlFile.timeSeries(availableEnvPeriods[0], "Hourly", "Site Outdoor Air Drybulb Temperature", "Environment"); ASSERT_TRUE(ts); // ASSERT_EQ(static_cast<unsigned>(8760), ts->dateTimes().size()); ASSERT_EQ(static_cast<unsigned>(8760), ts->daysFromFirstReport().size()); ASSERT_EQ(static_cast<unsigned>(8760), ts->values().size()); // EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0,1,0,0)), ts->dateTimes().front()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0,1,0,0)), ts->firstReportDateTime()); EXPECT_DOUBLE_EQ(-8.2625, ts->values()[0]); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,0,0)))); // DLM: there is commented out code in openstudio::OptionalTime SqlFile_Impl::timeSeriesInterval(const DataDictionaryItem& dataDictionary) // that does not recognize hourly as an interval type, so the following line is not expected to work //EXPECT_DOUBLE_EQ(-8.2625, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,0,1)))); EXPECT_DOUBLE_EQ(-8.2625, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,1,0,0)))); EXPECT_DOUBLE_EQ(-11.8875, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,1,0,1)))); // EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)), ts->dateTimes().back()); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)), ts->firstReportDateTime()+Time(ts->daysFromFirstReport(ts->daysFromFirstReport().size()-1))); EXPECT_DOUBLE_EQ(-5.6875, ts->values()[8759]); EXPECT_DOUBLE_EQ(-4.775, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,22,59,59)))); EXPECT_DOUBLE_EQ(-4.775, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,23,0,0)))); EXPECT_DOUBLE_EQ(-5.6875, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,23,0,1)))); EXPECT_DOUBLE_EQ(-5.6875, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)))); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,1)))); ts = sqlFile.timeSeries(availableEnvPeriods[0], "HVAC System Timestep", "Site Outdoor Air Drybulb Temperature", "Environment"); ASSERT_TRUE(ts); // EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,15,0)), ts->dateTimes().front()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,15,0)), ts->firstReportDateTime()); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,0,0)))); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,0,1)))); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,0,14)))); EXPECT_DOUBLE_EQ(-4.325, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,15,0)))); EXPECT_DOUBLE_EQ(-6.95, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,15,1)))); EXPECT_DOUBLE_EQ(-6.95, ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,0,30,0)))); EXPECT_DOUBLE_EQ(-12.2 , ts->value(DateTime(Date(MonthOfYear::Jan, 1), Time(0,1,0,0)))); // EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)), ts->dateTimes().back()); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)), ts->firstReportDateTime()+Time(ts->daysFromFirstReport(ts->daysFromFirstReport().size()-1))); EXPECT_DOUBLE_EQ(-5.0 , ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,22,59,59)))); EXPECT_DOUBLE_EQ(-5.0 , ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,23,0,0)))); EXPECT_DOUBLE_EQ(-5.275, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,23,0,1)))); EXPECT_DOUBLE_EQ(-5.275, ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,23,15,0)))); EXPECT_DOUBLE_EQ(-6.1 , ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,0)))); EXPECT_DOUBLE_EQ(ts->outOfRangeValue(), ts->value(DateTime(Date(MonthOfYear::Dec, 31), Time(0,24,0,1)))); } TEST_F(SqlFileFixture, TimeSeriesCount) { std::vector<std::string> availableTimeSeries = sqlFile.availableTimeSeries(); ASSERT_FALSE(availableTimeSeries.empty()); std::vector<std::string> availableEnvPeriods = sqlFile.availableEnvPeriods(); ASSERT_FALSE(availableEnvPeriods.empty()); // check that "Electricity:Facility" is available ASSERT_EQ(1, std::count(availableTimeSeries.begin(), availableTimeSeries.end(), "Electricity:Facility")); openstudio::OptionalTimeSeries ts = sqlFile.timeSeries(availableEnvPeriods[0], "Hourly", "Electricity:Facility", ""); ASSERT_TRUE(ts); // check that "Gas:Facility" is available ASSERT_EQ(1, std::count(availableTimeSeries.begin(), availableTimeSeries.end(), "Gas:Facility")); ts = sqlFile.timeSeries(availableEnvPeriods[0], "Hourly", "Gas:Facility", ""); ASSERT_TRUE(ts); // check that "NotAVariable:Facility" is not available EXPECT_TRUE(availableTimeSeries.end() == std::find(availableTimeSeries.begin(), availableTimeSeries.end(), "NotAVariable:Facility")); ts = sqlFile.timeSeries(availableEnvPeriods[0], "Hourly", "NotAVariable:Facility", ""); EXPECT_FALSE(ts); // check that "Electricity:Facility" is available ASSERT_EQ(1, std::count(availableTimeSeries.begin(), availableTimeSeries.end(), "Electricity:Facility")); ts = sqlFile.timeSeries(availableEnvPeriods[0], "Run Period", "Electricity:Facility", ""); ASSERT_TRUE(ts); // check that "Gas:Facility" is available ASSERT_EQ(1, std::count(availableTimeSeries.begin(), availableTimeSeries.end(), "Gas:Facility")); ts = sqlFile.timeSeries(availableEnvPeriods[0], "Run Period", "Gas:Facility", ""); ASSERT_TRUE(ts); // check that "NotAVariable:Facility" is not available EXPECT_TRUE(availableTimeSeries.end() == std::find(availableTimeSeries.begin(), availableTimeSeries.end(), "NotAVariable:Facility")); ts = sqlFile.timeSeries(availableEnvPeriods[0], "Run Period", "NotAVariable:Facility", ""); EXPECT_FALSE(ts); } TEST_F(SqlFileFixture, TimeSeries) { std::vector<std::string> availableEnvPeriods = sqlFile.availableEnvPeriods(); ASSERT_FALSE(availableEnvPeriods.empty()); // make a timeseries openstudio::OptionalTimeSeries ts = sqlFile.timeSeries(availableEnvPeriods[0], "Hourly", "Electricity:Facility", ""); ASSERT_TRUE(ts); // should have 365 days minus 1 hour // Time duration = ts->dateTimes().back() - ts->dateTimes().front(); Time duration = ts->firstReportDateTime() + Time(ts->daysFromFirstReport(ts->daysFromFirstReport().size()-1)) - ts->firstReportDateTime(); EXPECT_DOUBLE_EQ(365-1.0/24.0, duration.totalDays()); } TEST_F(SqlFileFixture, BadStatement) { OptionalDouble result = sqlFile.execAndReturnFirstDouble("SELECT * FROM NonExistantTable"); EXPECT_FALSE(result); } TEST_F(SqlFileFixture, CreateSqlFile) { openstudio::path outfile = openstudio::tempDir() / openstudio::toPath("OpenStudioSqlFileTest.sql"); if (openstudio::filesystem::exists(outfile)) { openstudio::filesystem::remove(outfile); } openstudio::Calendar c(2012); c.standardHolidays(); std::vector<double> values; values.push_back(100); values.push_back(10); values.push_back(1); values.push_back(100.5); TimeSeries timeSeries(c.startDate(), openstudio::Time(0,1), openstudio::createVector(values), "lux"); { openstudio::SqlFile sql(outfile, openstudio::EpwFile(resourcesPath() / toPath("utilities/Filetypes/USA_CO_Golden-NREL.724666_TMY3.epw")), openstudio::DateTime::now(), c); EXPECT_TRUE(sql.connectionOpen()); sql.insertTimeSeriesData("Sum", "Zone", "Zone", "DAYLIGHTING WINDOW", "Daylight Luminance", openstudio::ReportingFrequency::Hourly, boost::optional<std::string>(), "lux", timeSeries); sql.insertZone("CLASSROOM", 0, 0,0,0, 1,1,1, 3, 1, 1, 0, 2, 0, 2, 0, 2, 2, 8, 3, 3, 4, 4, 2, 2, true); std::vector<double> xs; std::vector<double> ys; xs.push_back(1.1); xs.push_back(2.2); xs.push_back(3.3); ys.push_back(2.8); ys.push_back(3.9); std::vector<DateTime> dates; dates.push_back(DateTime("2012-09-01 1:00")); dates.push_back(DateTime("2012-09-01 2:00")); std::vector<Matrix> maps; Matrix m1(3, 2); m1(0,0) = 0; m1(1,0) = 0.1; m1(2,0) = 0.2; m1(0,1) = 0.3; m1(1,1) = 0.4; m1(2,1) = 0.5; maps.push_back(m1); Matrix m2(3, 2); m1(0,0) = 2; m1(1,0) = 2.1; m1(2,0) = 2.2; m1(0,1) = 2.3; m1(1,1) = 2.4; m1(2,1) = 2.5; maps.push_back(m2); sql.insertIlluminanceMap("CLASSROOM", "CLASSROOM DAYLIGHT MAP", "GOLDEN", dates, xs, ys, 3.8, maps); } { openstudio::SqlFile sql(outfile); EXPECT_TRUE(sql.connectionOpen()); std::vector<std::string> envPeriods = sql.availableEnvPeriods(); ASSERT_EQ(envPeriods.size(), 1u); std::vector<std::string> reportingFrequencies = sql.availableReportingFrequencies(envPeriods[0]); ASSERT_EQ(reportingFrequencies.size(), 1u); std::vector<std::string> timeSeriesNames = sql.availableTimeSeries(); ASSERT_EQ(reportingFrequencies.size(), 1u); std::vector<std::string> keyValues = sql.availableKeyValues(envPeriods[0], reportingFrequencies[0], timeSeriesNames[0]); ASSERT_EQ(keyValues.size(), 1u); boost::optional<TimeSeries> ts = sql.timeSeries(envPeriods[0], reportingFrequencies[0], timeSeriesNames[0], keyValues[0]); ASSERT_TRUE(ts); EXPECT_EQ(openstudio::toStandardVector(ts->values()), openstudio::toStandardVector(timeSeries.values())); EXPECT_EQ(openstudio::toStandardVector(ts->daysFromFirstReport()), openstudio::toStandardVector(timeSeries.daysFromFirstReport())); } } TEST_F(SqlFileFixture, AnnualTotalCosts) { // Total annual costs for all fuel types EXPECT_NEAR(205284016.81, *(sqlFile2.annualTotalUtilityCost()), 0.1); // Costs by fuel type EXPECT_NEAR(28423.6, *(sqlFile2.annualTotalCost(FuelType::Electricity)), 0.1); EXPECT_NEAR(427.75, *(sqlFile2.annualTotalCost(FuelType::Gas)), 0.1); EXPECT_NEAR(331.01, *(sqlFile2.annualTotalCost(FuelType::DistrictCooling)), 0.1); EXPECT_NEAR(833.54, *(sqlFile2.annualTotalCost(FuelType::DistrictHeating)), 0.1); EXPECT_NEAR(0.91, *(sqlFile2.annualTotalCost(FuelType::Water)), 0.1); EXPECT_NEAR(205254000, *(sqlFile2.annualTotalCost(FuelType::FuelOil_1)), 100); // Costs by total building area by fuel type EXPECT_NEAR(11.84, *(sqlFile2.annualTotalCostPerBldgArea(FuelType::Electricity)), 0.1); EXPECT_NEAR(0.18, *(sqlFile2.annualTotalCostPerBldgArea(FuelType::Gas)), 0.1); // Costs by conditioned building area by fuel type EXPECT_NEAR(11.84, *(sqlFile2.annualTotalCostPerNetConditionedBldgArea(FuelType::Electricity)), 0.1); EXPECT_NEAR(0.18, *(sqlFile2.annualTotalCostPerNetConditionedBldgArea(FuelType::Gas)), 0.1); } void regressionTestSqlFile(const std::string& name, double netSiteEnergy, double firstVal, double lastVal) { openstudio::path fromPath = resourcesPath() / toPath("utilities/SqlFile") / toPath(name); openstudio::path path = toPath(name); if (openstudio::filesystem::exists(path)){ openstudio::filesystem::remove(path); } ASSERT_FALSE(openstudio::filesystem::exists(path)); ASSERT_TRUE(openstudio::filesystem::exists(fromPath)) << toString(fromPath); openstudio::filesystem::copy(fromPath, path); ASSERT_TRUE(openstudio::filesystem::exists(path)); boost::optional<SqlFile> sqlFile; EXPECT_NO_THROW(sqlFile = SqlFile(path)); ASSERT_TRUE(sqlFile); QRegularExpression re("1ZoneEvapCooler-V(.*)\\.sql"); QRegularExpressionMatch match = re.match(toQString(name)); ASSERT_TRUE(match.hasMatch()); VersionString expected(toString(match.captured(1))); VersionString actual(sqlFile->energyPlusVersion()); EXPECT_EQ(expected.major(), actual.major()); EXPECT_EQ(expected.minor(), actual.minor()); EXPECT_EQ(expected.patch(), actual.patch()); ASSERT_TRUE(sqlFile->hoursSimulated()); EXPECT_EQ(8760.0, sqlFile->hoursSimulated().get()) << name; ASSERT_TRUE(sqlFile->netSiteEnergy()); EXPECT_NEAR(netSiteEnergy, sqlFile->netSiteEnergy().get(), 0.1) << name; std::vector<std::string> availableEnvPeriods = sqlFile->availableEnvPeriods(); ASSERT_FALSE(availableEnvPeriods.empty()); EXPECT_EQ(static_cast<unsigned>(3), availableEnvPeriods.size()); { // Detailed openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Detailed", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "HVAC System Timestep", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "HVAC System Timestep", "Zone Mean Air Temperature", "MAIN ZONE"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Detailed", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_GE(N, 8760u*6u); // DLM: can't expect these to always be at timestep //EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 0, 10, 0)), ts->firstReportDateTime()); //EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 0, 10, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); // DLM: some sort of rounding error is occurring here //EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0, 23, 59, 59)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); } { // Timestep openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Timestep", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Zone Timestep", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Zone Timestep", "Zone Mean Air Temperature", "MAIN ZONE"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Timestep", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_EQ(N, 8760u * 6u); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 0, 10, 0)), ts->firstReportDateTime()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 0, 10, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); // DLM: some sort of rounding error is occurring here //EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(0, 23, 59, 59)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); } { // Hourly openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Hourly", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Hourly", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_EQ(N, 8760u); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 1, 0, 0)), ts->firstReportDateTime()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(0, 1, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); EXPECT_DOUBLE_EQ(firstVal, ts->values()[0]) << name; EXPECT_DOUBLE_EQ(lastVal, ts->values()[N-1]) << name; } { // Daily openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Daily", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Daily", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_EQ(N, 365u); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(1, 0, 0, 0)), ts->firstReportDateTime()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 1), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); } { // Monthly openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Monthly", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Monthly", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_EQ(N, 12u); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime()); EXPECT_EQ(DateTime(Date(MonthOfYear::Jan, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); } { // RunPeriod - synonymous with Environment and Annual openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "RunPeriod", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Run Period", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Run Period", "Zone Mean Air Temperature", "MAIN ZONE"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Environment", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Environment", "Zone Mean Air Temperature", "MAIN ZONE"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Annual", "Zone Mean Air Temperature", "Main Zone"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "Annual", "Zone Mean Air Temperature", "MAIN ZONE"); EXPECT_TRUE(ts); ts = sqlFile->timeSeries(availableEnvPeriods[0], "RunPeriod", "Zone Mean Air Temperature", "MAIN ZONE"); ASSERT_TRUE(ts); unsigned N = ts->daysFromFirstReport().size(); ASSERT_GT(N, 0u); ASSERT_EQ(N, ts->values().size()); EXPECT_EQ(N, 1u); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime()); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[0]); EXPECT_EQ(DateTime(Date(MonthOfYear::Dec, 31), Time(1, 0, 0, 0)), ts->firstReportDateTime() + ts->daysFromFirstReport()[N - 1]); } { // Bad key name openstudio::OptionalTimeSeries ts = sqlFile->timeSeries(availableEnvPeriods[0], "Hourly", "Zone Mean Air Temperature", "Zone that does not exist"); EXPECT_FALSE(ts); } } TEST_F(SqlFileFixture, Regressions) { // these files were created by running the 1ZoneEvapCooler.idf example file // adding the Output:SQLite,SimpleAndTabular object as well as several output variables // and using the USA_CO_Golden-NREL.724666_TMY3.epw weather file regressionTestSqlFile("1ZoneEvapCooler-V7-0-0.sql", 42.25, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V7-1-0.sql", 42.05, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V7-2-0.sql", 43.28, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V8-0-0.sql", 43.28, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V8-1-0.sql", 43.28, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V8-2-0.sql", 43.28, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V8-3-0.sql", 43.28, 20, 20); regressionTestSqlFile("1ZoneEvapCooler-V8-4-0.sql", 43.28, 20, 20); }
48.436
159
0.697498
OpenStudioThailand
29a728478cd6638426e2eb471bc96ff1ca46f788
2,608
cpp
C++
solved/pharmacy.cpp
AudreyFelicio/Kattis-Solutions
bc5856e1c7d9b8d8c2677e2af5e84a37110200e8
[ "MIT" ]
null
null
null
solved/pharmacy.cpp
AudreyFelicio/Kattis-Solutions
bc5856e1c7d9b8d8c2677e2af5e84a37110200e8
[ "MIT" ]
null
null
null
solved/pharmacy.cpp
AudreyFelicio/Kattis-Solutions
bc5856e1c7d9b8d8c2677e2af5e84a37110200e8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Prescription { int d; int time; }; bool cmp(const Prescription &p1, const Prescription &p2) { if (p1.d == p2.d) { return p1.time > p2.time; } return p1.d > p2.d; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, t; cin >> n >> t; priority_queue<Prescription, vector<Prescription>, decltype(&cmp)> remotes(&cmp); priority_queue<Prescription, vector<Prescription>, decltype(&cmp)> instores(&cmp); for (int i = 0; i < n; i++) { int a, b; char c; cin >> a >> c >> b; if (c == 'S') { instores.push({ a, b }); } else { remotes.push({ a, b }); } } double countInStore = instores.size(); double countRemote = remotes.size(); double totalInStore = 0; double totalRemote = 0; priority_queue<int, vector<int>, greater<int> > works; for (int i = 0; i < t; i++) { works.push(0); } while (!remotes.empty() && !instores.empty()) { Prescription currRemote = remotes.top(); Prescription currStore = instores.top(); int currTime = works.top(); works.pop(); if (currTime >= currStore.d) { instores.pop(); totalInStore += currTime + currStore.time - currStore.d; works.push(currTime + currStore.time); } else if (currTime >= currRemote.d) { remotes.pop(); totalRemote += currTime + currRemote.time - currRemote.d; works.push(currTime + currRemote.time); } else { if (currStore.d <= currRemote.d) { instores.pop(); totalInStore += currStore.time; works.push(currStore.d + currStore.time); } else { remotes.pop(); totalRemote += currRemote.time; works.push(currRemote.d + currRemote.time); } } } while (remotes.empty() && !instores.empty()) { Prescription currStore = instores.top(); instores.pop(); int currTime = works.top(); works.pop(); totalInStore += max(currTime, currStore.d) + currStore.time - currStore.d; works.push(max(currTime, currStore.d) + currStore.time); } while (!remotes.empty() && instores.empty()) { Prescription currRemote = remotes.top(); remotes.pop(); int currTime = works.top(); works.pop(); totalRemote += max(currTime, currRemote.d) + currRemote.time - currRemote.d; works.push(max(currTime, currRemote.d) + currRemote.time); } double statInStore = countInStore ? (totalInStore) / countInStore : 0.0; double statRemote = countRemote ? (totalRemote) / countRemote : 0.0; cout << setprecision(15) << statInStore << " " << statRemote << endl; }
30.682353
84
0.616948
AudreyFelicio
29a7d24e4aef3b090714d6f11c7495e9f09a7e12
3,182
cpp
C++
pq-async-tests/type_tests/bin_types_test.cpp
micheldenommee/libpq-async
c490e36c686969e2edcac5cde5c05e5efec8d7fc
[ "MIT" ]
1
2019-11-17T19:06:45.000Z
2019-11-17T19:06:45.000Z
pq-async-tests/type_tests/bin_types_test.cpp
micheldenommee/libpq-async
c490e36c686969e2edcac5cde5c05e5efec8d7fc
[ "MIT" ]
null
null
null
pq-async-tests/type_tests/bin_types_test.cpp
micheldenommee/libpq-async
c490e36c686969e2edcac5cde5c05e5efec8d7fc
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2011-2019 Michel Dénommée 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 <gmock/gmock.h> #include "../db_test_base.h" namespace pq_async{ namespace tests{ class bin_types_test : public db_test_base { public: void drop_table() { db->execute("drop table if exists bin_types_test"); } void create_table() { this->drop_table(); db->execute( "create table bin_types_test(" "id serial primary key, a bytea" ");" ); } void SetUp() override { db_test_base::SetUp(); this->create_table(); } void TearDown() override { this->drop_table(); db_test_base::TearDown(); } }; TEST_F(bin_types_test, bin_test_bin) { try{ //std::vector<int8_t> //SELECT E'\\xDEADBEEF'; /* parameters_t p("abc", 1, 2.3, std::array<int, 2>()); for(int i = 0; i < p.size(); ++i) std::cout << *(p.types() + i) << std::endl; */ int8_t a0[] = { (int8_t)222, (int8_t)173, (int8_t)190, (int8_t)239 }; auto id = db->query_value<int32_t>( "insert into bin_types_test (a) values (E'\\\\xDEADBEEF'::bytea) " "RETURNING id" ); auto r = db->query_single( "select * from bin_types_test where id = $1", id ); auto a = r->as_bytea("a"); ASSERT_THAT(a, testing::ElementsAreArray(a0)); db->execute("delete from bin_types_test where id = $1", id); id = db->query_value<int32_t>( "insert into bin_types_test (a) values ($1) " "RETURNING id", std::vector<int8_t>(a0, a0 + 4) ); r = db->query_single( "select * from bin_types_test where id = $1", id ); a = r->as_bytea("a"); ASSERT_THAT(a, testing::ElementsAreArray(a0)); }catch(const std::exception& err){ std::cout << "Error: " << err.what() << std::endl; FAIL(); } } }} //namespace pq_async::tests
27.431034
78
0.594909
micheldenommee
29aad12ce60b535be7063b34f662c9184a9b6d0c
10,963
cpp
C++
src/slg/kernels/materialdefs_funcs_carpaint_kernel.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
src/slg/kernels/materialdefs_funcs_carpaint_kernel.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
src/slg/kernels/materialdefs_funcs_carpaint_kernel.cpp
tschw/LuxCore
111009811c31a74595e25c290bfaa7d715db4192
[ "Apache-2.0" ]
null
null
null
#include <string> namespace slg { namespace ocl { std::string KernelSource_materialdefs_funcs_carpaint = "#line 2 \"materialdefs_funcs_carpaint.cl\"\n" "\n" "/***************************************************************************\n" " * Copyright 1998-2018 by authors (see AUTHORS.txt) *\n" " * *\n" " * This file is part of LuxCoreRender. *\n" " * *\n" " * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n" " * you may not use this file except in compliance with the License. *\n" " * You may obtain a copy of the License at *\n" " * *\n" " * http://www.apache.org/licenses/LICENSE-2.0 *\n" " * *\n" " * Unless required by applicable law or agreed to in writing, software *\n" " * distributed under the License is distributed on an \"AS IS\" BASIS, *\n" " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n" " * See the License for the specific language governing permissions and *\n" " * limitations under the License. *\n" " ***************************************************************************/\n" "\n" "//------------------------------------------------------------------------------\n" "// CarPaint material\n" "//\n" "// LuxRender carpaint material porting.\n" "//------------------------------------------------------------------------------\n" "\n" "#if defined (PARAM_ENABLE_MAT_CARPAINT)\n" "\n" "OPENCL_FORCE_INLINE BSDFEvent CarPaintMaterial_GetEventTypes() {\n" " return GLOSSY | REFLECT;\n" "}\n" "\n" "OPENCL_FORCE_NOT_INLINE float3 CarPaintMaterial_Evaluate(\n" " __global HitPoint *hitPoint, const float3 lightDir, const float3 eyeDir,\n" " BSDFEvent *event, float *directPdfW,\n" " const float3 kaVal, const float d, const float3 kdVal, \n" " const float3 ks1Val, const float m1, const float r1,\n" " const float3 ks2Val, const float m2, const float r2,\n" " const float3 ks3Val, const float m3, const float r3) {\n" " float3 H = normalize(lightDir + eyeDir);\n" " if (all(H == 0.f))\n" " {\n" " if (directPdfW)\n" " *directPdfW = 0.f;\n" " return BLACK;\n" " }\n" " if (H.z < 0.f)\n" " H = -H;\n" "\n" " float pdf = 0.f;\n" " int n = 1; // already counts the diffuse layer\n" "\n" " // Absorption\n" " const float cosi = fabs(lightDir.z);\n" " const float coso = fabs(eyeDir.z);\n" " const float3 alpha = Spectrum_Clamp(kaVal);\n" " const float3 absorption = CoatingAbsorption(cosi, coso, alpha, d);\n" "\n" " // Diffuse layer\n" " float3 result = absorption * Spectrum_Clamp(kdVal) * M_1_PI_F * fabs(lightDir.z);\n" "\n" " // 1st glossy layer\n" " const float3 ks1 = Spectrum_Clamp(ks1Val);\n" " if (Spectrum_Filter(ks1) > 0.f && m1 > 0.f)\n" " {\n" " const float rough1 = m1 * m1;\n" " result += (SchlickDistribution_D(rough1, H, 0.f) * SchlickDistribution_G(rough1, lightDir, eyeDir) / (4.f * coso)) * (ks1 * FresnelSchlick_Evaluate(r1, dot(eyeDir, H)));\n" " pdf += SchlickDistribution_Pdf(rough1, H, 0.f);\n" " ++n;\n" " }\n" " const float3 ks2 = Spectrum_Clamp(ks2Val);\n" " if (Spectrum_Filter(ks2) > 0.f && m2 > 0.f)\n" " {\n" " const float rough2 = m2 * m2;\n" " result += (SchlickDistribution_D(rough2, H, 0.f) * SchlickDistribution_G(rough2, lightDir, eyeDir) / (4.f * coso)) * (ks2 * FresnelSchlick_Evaluate(r2, dot(eyeDir, H)));\n" " pdf += SchlickDistribution_Pdf(rough2, H, 0.f);\n" " ++n;\n" " }\n" " const float3 ks3 = Spectrum_Clamp(ks3Val);\n" " if (Spectrum_Filter(ks3) > 0.f && m3 > 0.f)\n" " {\n" " const float rough3 = m3 * m3;\n" " result += (SchlickDistribution_D(rough3, H, 0.f) * SchlickDistribution_G(rough3, lightDir, eyeDir) / (4.f * coso)) * (ks3 * FresnelSchlick_Evaluate(r3, dot(eyeDir, H)));\n" " pdf += SchlickDistribution_Pdf(rough3, H, 0.f);\n" " ++n;\n" " }\n" "\n" " // Front face: coating+base\n" " *event = GLOSSY | REFLECT;\n" "\n" " // Finish pdf computation\n" " pdf /= 4.f * fabs(dot(lightDir, H));\n" " if (directPdfW)\n" " *directPdfW = (pdf + fabs(lightDir.z) * M_1_PI_F) / n;\n" "\n" " return result;\n" "}\n" "\n" "OPENCL_FORCE_NOT_INLINE float3 CarPaintMaterial_Sample(\n" " __global HitPoint *hitPoint, const float3 fixedDir, float3 *sampledDir,\n" " const float u0, const float u1,\n" "#if defined(PARAM_HAS_PASSTHROUGH)\n" " const float passThroughEvent,\n" "#endif\n" " float *pdfW, float *cosSampledDir, BSDFEvent *event,\n" " const float3 kaVal, const float d, const float3 kdVal, \n" " const float3 ks1Val, const float m1, const float r1,\n" " const float3 ks2Val, const float m2, const float r2,\n" " const float3 ks3Val, const float m3, const float r3) {\n" " if (fabs(fixedDir.z) < DEFAULT_COS_EPSILON_STATIC)\n" " return BLACK;\n" "\n" " // Test presence of components\n" " int n = 1; // already count the diffuse layer\n" " int sampled = 0; // sampled layer\n" " float3 result = BLACK;\n" " float pdf = 0.f;\n" " bool l1 = false, l2 = false, l3 = false;\n" " // 1st glossy layer\n" " const float3 ks1 = Spectrum_Clamp(ks1Val);\n" " if (Spectrum_Filter(ks1) > 0.f && m1 > 0.f)\n" " {\n" " l1 = true;\n" " ++n;\n" " }\n" " // 2nd glossy layer\n" " const float3 ks2 = Spectrum_Clamp(ks2Val);\n" " if (Spectrum_Filter(ks2) > 0.f && m2 > 0.f)\n" " {\n" " l2 = true;\n" " ++n;\n" " }\n" " // 3rd glossy layer\n" " const float3 ks3 = Spectrum_Clamp(ks3Val);\n" " if (Spectrum_Filter(ks3) > 0.f && m3 > 0.f)\n" " {\n" " l3 = true;\n" " ++n;\n" " }\n" "\n" " float3 wh;\n" " float cosWH;\n" " if (passThroughEvent < 1.f / n) {\n" " // Sample diffuse layer\n" " *sampledDir = (signbit(fixedDir.z) ? -1.f : 1.f) * CosineSampleHemisphereWithPdf(u0, u1, &pdf);\n" "\n" " *cosSampledDir = fabs((*sampledDir).z);\n" " if (*cosSampledDir < DEFAULT_COS_EPSILON_STATIC)\n" " return BLACK;\n" "\n" " // Absorption\n" " const float cosi = fabs(fixedDir.z);\n" " const float coso = fabs((*sampledDir).z);\n" " const float3 alpha = Spectrum_Clamp(kaVal);\n" " const float3 absorption = CoatingAbsorption(cosi, coso, alpha, d);\n" "\n" " // Evaluate base BSDF\n" " result = absorption * Spectrum_Clamp(kdVal) * pdf;\n" "\n" " wh = normalize(*sampledDir + fixedDir);\n" " if (wh.z < 0.f)\n" " wh = -wh;\n" " cosWH = fabs(dot(fixedDir, wh));\n" " } else if (passThroughEvent < 2.f / n && l1) {\n" " // Sample 1st glossy layer\n" " sampled = 1;\n" " const float rough1 = m1 * m1;\n" " float d;\n" " SchlickDistribution_SampleH(rough1, 0.f, u0, u1, &wh, &d, &pdf);\n" " cosWH = dot(fixedDir, wh);\n" " *sampledDir = 2.f * cosWH * wh - fixedDir;\n" " *cosSampledDir = fabs((*sampledDir).z);\n" " cosWH = fabs(cosWH);\n" "\n" " if (((*sampledDir).z < DEFAULT_COS_EPSILON_STATIC) ||\n" " (fixedDir.z * (*sampledDir).z < 0.f))\n" " return BLACK;\n" "\n" " pdf /= 4.f * cosWH;\n" " if (pdf <= 0.f)\n" " return BLACK;\n" "\n" " result = FresnelSchlick_Evaluate(r1, cosWH);\n" "\n" " const float G = SchlickDistribution_G(rough1, fixedDir, *sampledDir);\n" " result *= d * G / (4.f * fabs(fixedDir.z));\n" " } else if ((passThroughEvent < 2.f / n ||\n" " (!l1 && passThroughEvent < 3.f / n)) && l2) {\n" " // Sample 2nd glossy layer\n" " sampled = 2;\n" " const float rough2 = m2 * m2;\n" " float d;\n" " SchlickDistribution_SampleH(rough2, 0.f, u0, u1, &wh, &d, &pdf);\n" " cosWH = dot(fixedDir, wh);\n" " *sampledDir = 2.f * cosWH * wh - fixedDir;\n" " *cosSampledDir = fabs((*sampledDir).z);\n" " cosWH = fabs(cosWH);\n" "\n" " if (((*sampledDir).z < DEFAULT_COS_EPSILON_STATIC) ||\n" " (fixedDir.z * (*sampledDir).z < 0.f))\n" " return BLACK;\n" "\n" " pdf /= 4.f * cosWH;\n" " if (pdf <= 0.f)\n" " return BLACK;\n" "\n" " result = FresnelSchlick_Evaluate(r2, cosWH);\n" "\n" " const float G = SchlickDistribution_G(rough2, fixedDir, *sampledDir);\n" " result *= d * G / (4.f * fabs(fixedDir.z));\n" " } else if (l3) {\n" " // Sample 3rd glossy layer\n" " sampled = 3;\n" " const float rough3 = m3 * m3;\n" " float d;\n" " SchlickDistribution_SampleH(rough3, 0.f, u0, u1, &wh, &d, &pdf);\n" " cosWH = dot(fixedDir, wh);\n" " *sampledDir = 2.f * cosWH * wh - fixedDir;\n" " *cosSampledDir = fabs((*sampledDir).z);\n" " cosWH = fabs(cosWH);\n" "\n" " if (((*sampledDir).z < DEFAULT_COS_EPSILON_STATIC) ||\n" " (fixedDir.z * (*sampledDir).z < 0.f))\n" " return BLACK;\n" "\n" " pdf /= 4.f * cosWH;\n" " if (pdf <= 0.f)\n" " return BLACK;\n" "\n" " result = FresnelSchlick_Evaluate(r3, cosWH);\n" "\n" " const float G = SchlickDistribution_G(rough3, fixedDir, *sampledDir);\n" " result *= d * G / (4.f * fabs(fixedDir.z));\n" " } else {\n" " // Sampling issue\n" " return BLACK;\n" " }\n" " *event = GLOSSY | REFLECT;\n" " // Add other components\n" " // Diffuse\n" " if (sampled != 0) {\n" " // Absorption\n" " const float cosi = fabs(fixedDir.z);\n" " const float coso = fabs((*sampledDir).z);\n" " const float3 alpha = Spectrum_Clamp(kaVal);\n" " const float3 absorption = CoatingAbsorption(cosi, coso, alpha, d);\n" "\n" " const float pdf0 = fabs((*sampledDir).z) * M_1_PI_F;\n" " pdf += pdf0;\n" " result = absorption * Spectrum_Clamp(kdVal) * pdf0;\n" " }\n" " // 1st glossy\n" " if (l1 && sampled != 1) {\n" " const float rough1 = m1 * m1;\n" " const float d1 = SchlickDistribution_D(rough1, wh, 0.f);\n" " const float pdf1 = SchlickDistribution_Pdf(rough1, wh, 0.f) / (4.f * cosWH);\n" " if (pdf1 > 0.f) {\n" " result += (d1 *\n" " SchlickDistribution_G(rough1, fixedDir, *sampledDir) /\n" " (4.f * fabs(fixedDir.z))) *\n" " FresnelSchlick_Evaluate(r1, cosWH);\n" " pdf += pdf1;\n" " }\n" " }\n" " // 2nd glossy\n" " if (l2 && sampled != 2) {\n" " const float rough2 = m2 * m2;\n" " const float d2 = SchlickDistribution_D(rough2, wh, 0.f);\n" " const float pdf2 = SchlickDistribution_Pdf(rough2, wh, 0.f) / (4.f * cosWH);\n" " if (pdf2 > 0.f) {\n" " result += (d2 *\n" " SchlickDistribution_G(rough2, fixedDir, *sampledDir) /\n" " (4.f * fabs(fixedDir.z))) *\n" " FresnelSchlick_Evaluate(r2, cosWH);\n" " pdf += pdf2;\n" " }\n" " }\n" " // 3rd glossy\n" " if (l3 && sampled != 3) {\n" " const float rough3 = m3 * m3;\n" " const float d3 = SchlickDistribution_D(rough3, wh, 0.f);\n" " const float pdf3 = SchlickDistribution_Pdf(rough3, wh, 0.f) / (4.f * cosWH);\n" " if (pdf3 > 0.f) {\n" " result += (d3 *\n" " SchlickDistribution_G(rough3, fixedDir, *sampledDir) /\n" " (4.f * fabs(fixedDir.z))) *\n" " FresnelSchlick_Evaluate(r3, cosWH);\n" " pdf += pdf3;\n" " }\n" " }\n" " // Adjust pdf and result\n" " *pdfW = pdf / n;\n" " return result / *pdfW;\n" "}\n" "\n" "#endif\n" ; } }
36.421927
175
0.573018
tschw
29ae145b74d722e336c5d46383a35124c60b0575
1,597
cpp
C++
Engine/ac/dynobj/scriptset.cpp
Vikram1323/ags
6fda61b3536533bab6572cebf1afec90bd69dc66
[ "Artistic-2.0" ]
11
2015-01-25T09:59:17.000Z
2019-07-08T15:06:06.000Z
Engine/ac/dynobj/scriptset.cpp
jonreyno/ags-ios
988cd091dcb8be8c069890b52235ff86af07117e
[ "Artistic-2.0" ]
3
2019-05-09T01:24:14.000Z
2019-06-12T12:16:33.000Z
Engine/ac/dynobj/scriptset.cpp
jonreyno/ags-ios
988cd091dcb8be8c069890b52235ff86af07117e
[ "Artistic-2.0" ]
1
2019-05-09T00:42:31.000Z
2019-05-09T00:42:31.000Z
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= #include "ac/dynobj/scriptset.h" int ScriptSetBase::Dispose(const char *address, bool force) { Clear(); delete this; return 1; } const char *ScriptSetBase::GetType() { return "StringSet"; } int ScriptSetBase::Serialize(const char *address, char *buffer, int bufsize) { size_t total_sz = CalcSerializeSize(); if (bufsize < 0 || total_sz > (size_t)bufsize) { // buffer not big enough, ask for a bigger one return -((int)total_sz); } StartSerialize(buffer); SerializeInt(IsSorted()); SerializeInt(IsCaseSensitive()); SerializeContainer(); return EndSerialize(); } void ScriptSetBase::Unserialize(int index, const char *serializedData, int dataSize) { // NOTE: we expect sorted/case flags are read by external reader; // this is awkward, but I did not find better design solution atm StartUnserialize(serializedData, dataSize); UnserializeContainer(serializedData); ccRegisterUnserializedObject(index, this, this); }
31.313725
84
0.636193
Vikram1323
29af43aebf340ac15ac86508f2091910b2240dcf
16,587
cpp
C++
Source/GUI/Qt/GUI_Main_Technical_Table.cpp
MediaArea/BWFMetaEdit
9bac7edb79405fe49dc37609e73d72af82759724
[ "0BSD" ]
25
2017-10-16T05:16:42.000Z
2022-03-19T09:30:14.000Z
Source/GUI/Qt/GUI_Main_Technical_Table.cpp
MediaArea/BWFMetaEdit
9bac7edb79405fe49dc37609e73d72af82759724
[ "0BSD" ]
112
2017-10-18T18:10:37.000Z
2022-02-15T11:19:03.000Z
Source/GUI/Qt/GUI_Main_Technical_Table.cpp
MediaArea/BWFMetaEdit
9bac7edb79405fe49dc37609e73d72af82759724
[ "0BSD" ]
15
2017-10-31T00:02:48.000Z
2021-11-13T21:00:15.000Z
// BWF MetaEdit GUI - A GUI for BWF MetaEdit // // This code was created in 2010 for the Library of Congress and the // other federal government agencies participating in the Federal Agencies // Digital Guidelines Initiative and it is in the public domain. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- #include "GUI/Qt/GUI_Main_Technical_Table.h" #include "GUI/Qt/GUI_Main.h" #include "GUI/Qt/GUI_Main_xxxx_Bext.h" #include "GUI/Qt/GUI_Main_xxxx_TextEditDialog.h" #include "GUI/Qt/GUI_Main_xxxx_CueDialog.h" #include "Common/Core.h" #include "ZenLib/ZtringListList.h" #include <QLabel> #include <QEvent> #include <QFont> #include <QTextEdit> #include <QHeaderView> #include <QContextMenuEvent> #include <QAction> #include <QMenu> #include <QFileDialog> #include <QMessageBox> using namespace ZenLib; //--------------------------------------------------------------------------- //*************************************************************************** // Static objects //*************************************************************************** int GUI_Main_Technical_Table::SortColumn=FILENAME_COL; Qt::SortOrder GUI_Main_Technical_Table::SortOrder=Qt::AscendingOrder; //*************************************************************************** // Constructor/Destructor //*************************************************************************** //--------------------------------------------------------------------------- GUI_Main_Technical_Table::GUI_Main_Technical_Table(Core* _C, GUI_Main* parent) : GUI_Main_xxxx__Common(_C, parent) { setSelectionMode(SingleSelection); } //*************************************************************************** // Events //*************************************************************************** //--------------------------------------------------------------------------- void GUI_Main_Technical_Table::contextMenuEvent (QContextMenuEvent* Event) { //Retrieving data QTableWidgetItem* Item=itemAt(Event->pos()); if (Item==NULL) return; string FileName=FileName_Before+item(Item->row(), FILENAME_COL)->text().toUtf8().data(); string Field=horizontalHeaderItem(Item->column())->text().toUtf8().data(); ZtringList History; History.Write(Ztring().From_UTF8(C->History(FileName, Field))); Ztring Import; Ztring Export; Ztring Fill; Ztring Remove; if (Field=="XMP" || Field=="aXML" || Field=="iXML" || Field=="Cue") { Import="Import..."; //If you change this, change at the end of method too if (!C->Get(FileName, Field).empty()) { Export="Export..."; //If you change this, change at the end of method too Remove="Remove it"; //If you change this, change at the end of method too } } if (Field=="MD5Stored" && Fill_Enabled(FileName, Field, C->Get(FileName, "MD5Stored"))) { if (!C->Get(FileName, "MD5Generated").empty() && C->Get(FileName, "MD5Stored")!=C->Get(FileName, "MD5Generated")) Fill="Fill with MD5Generated"; //If you change this, change at the end of method too if (!item(Item->row(), Item->column())->text().isEmpty()) Remove="Remove it"; //If you change this, change at the end of method too } //Do we need a context menu? if (Import.empty() && Export.empty() && Fill.empty() && Remove.empty() && History.empty()) return; //Creating menu QMenu menu(this); //Handling export display if (!Import.empty()) menu.addAction(new QAction(QString().fromUtf8(Import.To_UTF8().c_str()), this)); if (!Export.empty()) menu.addAction(new QAction(QString().fromUtf8(Export.To_UTF8().c_str()), this)); if (!Import.empty() || !Export.empty()) menu.addSeparator(); //Handling Fill display if (!Fill.empty()) { menu.addAction(new QAction(QString().fromUtf8(Fill.To_UTF8().c_str()), this)); menu.addSeparator(); } //Handling history display size_t Pos=History.size(); if (!History.empty() && Field!="Cue" && !(Field=="MD5Stored" && !Fill_Enabled(FileName, Field, C->Get(FileName, "MD5Stored")))) do { Pos--; QString Text=QString().fromUtf8(History[Pos].To_UTF8().c_str()); if (!Text.isEmpty()) { QAction* Action=new QAction(Text, this); menu.addAction(Action); } } while (Pos>0); //Handling remove display if (!Remove.empty()) { menu.addSeparator(); menu.addAction(new QAction(QString().fromUtf8(Remove.To_UTF8().c_str()), this)); } //Displaying QAction* Action=menu.exec(Event->globalPos()); if (Action==NULL) return; //Retrieving data string ModifiedContent=Action->text().toUtf8().data(); //Specific cases if (ModifiedContent=="Remove it") //If you change this, change the creation text too ModifiedContent.clear(); if (ModifiedContent=="Export...") //If you change this, change the creation text too { //User interaction QString FileNamesQ = QFileDialog::getSaveFileName( this, tr("Export file..."), QString::fromUtf8(C->OpenSaveFolder.c_str()), "XML files (*.xml);;All files (*.*)"); if (FileNamesQ.isEmpty()) return; //Filling File F; if (!F.Create(ZenLib::Ztring().From_UTF8(FileNamesQ.toUtf8().data()))) return; if (Field=="Cue") F.Write(Ztring().From_UTF8(C->Get("cuexml", Field))); else F.Write(Ztring().From_UTF8(C->Get(FileName, Field))); return; } if (ModifiedContent=="Import...") //If you change this, change the creation text too { //User interaction QString FileNamesQ = QFileDialog::getOpenFileName( this, tr("Import file..."), QString::fromUtf8(C->OpenSaveFolder.c_str()), (Field=="XMP" || Field=="aXML" || Field=="iXML"|| Field=="Cue")?"XML files (*.xml);;All files (*.*)":"Text files (*.txt);;All files (*.*)"); if (FileNamesQ.isEmpty()) return; File F; if (!F.Open(ZenLib::Ztring().From_UTF8(FileNamesQ.toUtf8().data()))) return; int64u F_Size=F.Size_Get(); if (F_Size>((size_t)-1)-1) return; //Creating buffer int8u* Buffer=new int8u[(size_t)F_Size+1]; size_t Buffer_Offset=0; //Reading the file while(Buffer_Offset<F_Size) { size_t BytesRead=F.Read(Buffer+Buffer_Offset, (size_t)F_Size-Buffer_Offset); if (BytesRead==0) break; //Read is finished Buffer_Offset+=BytesRead; } if (Buffer_Offset<F_Size) return; Buffer[Buffer_Offset]='\0'; //Filling Ztring Value=Ztring().From_UTF8((const char*)Buffer); delete[] Buffer; Value.FindAndReplace(__T("\r\n"), __T("\n"), 0, Ztring_Recursive); Value.FindAndReplace(__T("\r"), __T("\n"), 0, Ztring_Recursive); if (!C->IsValid(FileName, Field=="Cue"?"cuexml":Field, Value.To_UTF8())) { QMessageBox MessageBox; MessageBox.setWindowTitle("BWF MetaEdit"); MessageBox.setText((string("Field does not conform to rules:\n")+C->IsValid_LastError(FileName)).c_str()); #if (QT_VERSION >= 0x040200) MessageBox.setStandardButtons(QMessageBox::Ok); #endif // (QT_VERSION >= 0x040200) MessageBox.setIcon(QMessageBox::Warning); MessageBox.setWindowIcon(QIcon(":/Image/Logo/Logo.png")); MessageBox.exec(); return; } ModifiedContent=Value.To_UTF8(); } //Filling if (Field=="XMP" || Field=="aXML" || Field=="iXML" || Field=="Cue") { if (Field=="Cue") C->Set(FileName, "cuexml", ModifiedContent); else C->Set(FileName, Field, ModifiedContent); item(Item->row(), Item->column())->setText(C->Get(FileName, Field).empty()?"No":"Yes"); } else if (Field=="MD5Stored" && ModifiedContent=="Fill with MD5Generated") { C->Set(FileName, "MD5Stored", C->Get(FileName, "MD5Generated")); SetText(Item->row(), "MD5Stored"); } else { Ztring NewValue=Ztring().From_UTF8(ModifiedContent); NewValue.FindAndReplace(__T("\r\n"), __T("\n"), 0, Ztring_Recursive); item(Item->row(), Item->column())->setText(NewValue.To_UTF8().c_str()); } //Configuring Colors_Update(item(Item->row(), Item->column()), FileName, Field); //Menu Main->Menu_Update(); } //--------------------------------------------------------------------------- bool GUI_Main_Technical_Table::edit (const QModelIndex &index, EditTrigger trigger, QEvent *Event) { //Must we edit or not if (!index.isValid()) return QTableWidget::edit(index, trigger, Event); //Normal editing //Init string FileName=FileName_Before+item(index.row(), FILENAME_COL)->text().toUtf8().data(); string Field=horizontalHeaderItem(index.column())->text().toUtf8().data(); //Should we handle edition manualy? if (trigger!=DoubleClicked && trigger!=AnyKeyPressed) return QTableWidget::edit(index, trigger, Event); //Normal editing //Retrieving data QString ModifiedContentQ; if (trigger==AnyKeyPressed) { ModifiedContentQ=((QKeyEvent*)Event)->text(); //What the user has pressed if (!ModifiedContentQ.isEmpty() && ModifiedContentQ[0]==127) ModifiedContentQ.clear(); } else ModifiedContentQ=QString::fromUtf8(C->Get(FileName, Field).c_str()); //Old value //bext if (Field=="bext") { if (Main->Bext_Toggle_Get()) { //Retrieving data int8u NewValue=Ztring().From_UTF8(C->Get(FileName, "BextVersion").c_str()).To_int8u(); if (NewValue>=Main->Bext_MaxVersion_Get()) { bool HasV1=C->Get(FileName, "LoudnessValue").empty() && C->Get(FileName, "LoudnessRange").empty() && C->Get(FileName, "MaxTruePeakLevel").empty() && C->Get(FileName, "MaxMomentaryLoudness").empty() && C->Get(FileName, "MaxShortTermLoudness").empty(); bool HasV0=HasV1 && C->Get(FileName, "UMID").empty(); if (HasV0) NewValue=0; else if (HasV1) NewValue=1; else NewValue=2; } else NewValue++; //Filling C->Set(FileName, "BextVersion", Ztring::ToZtring(NewValue).To_UTF8()); item(index.row(), index.column())->setText(Ztring(__T("Version ")+Ztring::ToZtring(NewValue)).To_UTF8().c_str()); dataChanged(indexFromItem(item(index.row(), index.column())), indexFromItem(item(index.row(), index.column()))); return false; } else { //User interaction GUI_Main_xxxx_Bext* Edit=new GUI_Main_xxxx_Bext(C, FileName, Main->Bext_MaxVersion_Get()); if (Edit->exec()!=QDialog::Accepted) { delete Edit; //Edit=NULL; return false; //No change } delete Edit; //Edit=NULL; string NewValue(C->Get(FileName, "BextVersion")); //Updating item(index.row(), index.column())->setText(QString::fromUtf8(string("Version "+NewValue).c_str())); dataChanged(indexFromItem(item(index.row(), index.column())), indexFromItem(item(index.row(), index.column()))); return false; } } //XML if (Field=="XMP" || Field=="aXML" || Field=="iXML") { //Retrieving data if (!ModifiedContentQ.isEmpty()) { Ztring ModifiedContent=Ztring().From_UTF8(C->Get(FileName, Field)); ModifiedContent.FindAndReplace(__T("\r\n"), __T("\n"), 0, Ztring_Recursive); ModifiedContentQ=QString::fromUtf8(ModifiedContent.To_UTF8().c_str()); } //User interaction GUI_Main_xxxx_TextEditDialog* Edit=new GUI_Main_xxxx_TextEditDialog(C, FileName, Field, ModifiedContentQ); if (Edit->exec()!=QDialog::Accepted) { delete Edit; //Edit=NULL; return false; //No change } delete Edit; //Edit=NULL; //Updating item(index.row(), index.column())->setText(C->Get(FileName, Field).empty()?"No":"Yes"); dataChanged(indexFromItem(item(index.row(), index.column())), indexFromItem(item(index.row(), index.column()))); return false; } //Cue if (Field=="Cue") { //User interaction GUI_Main_xxxx_CueDialog* Edit=new GUI_Main_xxxx_CueDialog(C, FileName); if (Edit->exec()!=QDialog::Accepted) { delete Edit; //Edit=NULL; return false; //No change } delete Edit; //Edit=NULL; //Updating item(index.row(), index.column())->setText(C->Get(FileName, Field).empty()?"No":"Yes"); dataChanged(indexFromItem(item(index.row(), index.column())), indexFromItem(item(index.row(), index.column()))); return false; } //MD5Stored if (Field=="MD5Stored") { //User interaction GUI_Main_xxxx_TextEditDialog* Edit=new GUI_Main_xxxx_TextEditDialog(C, FileName, Field, ModifiedContentQ); if (Edit->exec()!=QDialog::Accepted) { delete Edit; //Edit=NULL; return false; //No change } delete Edit; //Edit=NULL; //Filling Ztring NewValue=Ztring().From_UTF8(C->Get(FileName, Field)); NewValue.FindAndReplace(__T("\r\n"), __T("\n"), 0, Ztring_Recursive); item(index.row(), index.column())->setText(QString::fromUtf8(NewValue.To_UTF8().c_str())); return false; } return false; } //*************************************************************************** // Helpers //*************************************************************************** //--------------------------------------------------------------------------- const string &GUI_Main_Technical_Table::Fill_Content () { return C->Technical_Get(); } //--------------------------------------------------------------------------- group GUI_Main_Technical_Table::Fill_Group () { return Group_Tech; } //--------------------------------------------------------------------------- bool GUI_Main_Technical_Table::Fill_Enabled (const string &FileName, const string &Field, const string &Value) { if (Field!="Cue" && Field!="XMP" && Field!="aXML" && Field!="iXML" && Field!="bext" && !(Field=="MD5Stored" && (Value.empty() || C->EmbedMD5_AuthorizeOverWritting))) return false; if (Field=="bext") { if (Main->Bext_MaxVersion_Get()>2 || Ztring().From_UTF8(C->Get(FileName, "BextVersion")).To_int16u()>Main->Bext_MaxVersion_Get() || (C->Get(FileName, "LoudnessValue").empty() && C->Get(FileName, "LoudnessRange").empty() && C->Get(FileName, "MaxTruePeakLevel").empty() && C->Get(FileName, "MaxMomentaryLoudness").empty() && C->Get(FileName, "MaxShortTermLoudness").empty())) return !C->Overwrite_Reject && Value!="No"; else return false; } if (!C->Overwrite_Reject) return true; if (Field=="Cue" || Field=="XMP" || Field=="aXML" || Field=="iXML") return Value!="Yes"; return Value.empty(); }
37.956522
382
0.516127
MediaArea
29b2f8cfdc3723dfd87739412655cc75ae0fa0b9
32,975
cxx
C++
TRD/AliTRDqaBlackEvents.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
TRD/AliTRDqaBlackEvents.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
TRD/AliTRDqaBlackEvents.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * withount fee, provided thats the abov copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDqaBlackEvents.cxx 23387 2008-01-17 17:25:16Z cblume $ */ //////////////////////////////////////////////////////////////////////////// // // // QA of black events // // // // Author: // // Sylwester Radomski (radomski@physi.uni-heidelberg.de) // // // //////////////////////////////////////////////////////////////////////////// #include "TH1D.h" #include "TH2D.h" #include "TH2S.h" #include "TF1.h" #include "TFile.h" #include "TCanvas.h" #include "TPad.h" #include "TLatex.h" #include "TStyle.h" #include "TGraph.h" #include "AliLog.h" #include "AliRawReader.h" #include "AliTRDrawStreamOld.h" #include "AliTRDqaBlackEvents.h" ClassImp(AliTRDqaBlackEvents) /////////////////////////////////////////////////////////////////////////////////////////////////// AliTRDqaBlackEvents::AliTRDqaBlackEvents() :TObject() ,fnEvents(0) ,fCreateFull(0) ,fThresh(0) ,fCount(0) ,fRefEv(0) ,fRefFileName(0x0) ,fOccupancy(0) ,fDetRob(0) ,fTBEvent(0) ,fRefHistPed(0) ,fRefHistNoise(0) ,fErrorHC(0) ,fErrorMCM(0) ,fErrorADC(0) ,fErrorSMHC(0) ,fErrorSMMCM(0) ,fErrorSMADC(0) ,fErrorGraphHC(0) ,fErrorGraphMCM(0) ,fErrorGraphADC(0) ,fGraphMCM(0) ,fMcmTracks(0) ,fMapMCM(0) ,fFracMCM(0) ,fSMHCped(0) ,fSMHCerr(0) ,fNoiseTotal(0) ,fPP(0) ,fMinNoise(0.5) ,fMaxNoise(2) ,fFitType(0) { // // Constructor // to create the histograms call Init() // for (Int_t i = 0; i < kDET; i++) { fPed[i] = 0x0; fNoise[i] = 0x0; fChPP[i] = 0x0; fNPointDist[i] = 0x0; fChPed[i] = 0x0; fChNoise[i] = 0x0; fNPoint[i] = 0x0; fData[i] = 0x0; fSignal[i] = 0x0; fnEntriesRM[i] = 0x0; fnEntriesRMDist[i] = 0x0; fChPedRes[i] = 0x0; fChNoiseRes[i] = 0x0; fErrorLocHC[i] = 0x0; fErrorLocMCM[i] = 0x0; fErrorLocADC[i] = 0x0; } for (Int_t i = 0; i < 3; i++) { fGraphPP[i] = 0x0; fSMLink[i] = 0x0; fGrLink[i] = 0x0; fppThresh[i] = 0; fnPP[i] = 0; fnLink[i] = 0; } for (Int_t i = 0; i < 2; i++) { fnErrorHC[i] = 0; fnErrorMCM[i] = 0; fnErrorADC[i] = 0; } for (Int_t i = 0; i < kSM; i++) { fSmNoiseRms[i] = 0x0; fSmNoiseFit[i] = 0x0; fSmPP[i] = 0x0; } for (Int_t i = 0; i < kSM+1; i++) { fNumberADC[i] = 0x0; fnADCinSM[i] = 0; } for (Int_t i = 0; i < 1000; i++) { fEvNoDist[i] = 0; } for (Int_t i = 0; i < kDET*kROB*kMCM; i++) { fFullSignal[i] = 0x0; fFullCounter[i] = 0; } //strncpy(fRefFileName,"",256); } /////////////////////////////////////////////////////////////////////////////////////////////////// AliTRDqaBlackEvents::AliTRDqaBlackEvents(const AliTRDqaBlackEvents &qa) :TObject(qa) ,fnEvents(0) ,fCreateFull(0) ,fThresh(0) ,fCount(0) ,fRefEv(0) ,fRefFileName(0x0) ,fOccupancy(0) ,fDetRob(0) ,fTBEvent(0) ,fRefHistPed(0) ,fRefHistNoise(0) ,fErrorHC(0) ,fErrorMCM(0) ,fErrorADC(0) ,fErrorSMHC(0) ,fErrorSMMCM(0) ,fErrorSMADC(0) ,fErrorGraphHC(0) ,fErrorGraphMCM(0) ,fErrorGraphADC(0) ,fGraphMCM(0) ,fMcmTracks(0) ,fMapMCM(0) ,fFracMCM(0) ,fSMHCped(0) ,fSMHCerr(0) ,fNoiseTotal(0) ,fPP(0) ,fMinNoise(0.5) ,fMaxNoise(2) ,fFitType(0) { // // Copy constructor // to create the histograms call Init() // for (Int_t i = 0; i < kDET; i++) { fPed[i] = 0x0; fNoise[i] = 0x0; fChPP[i] = 0x0; fNPointDist[i] = 0x0; fChPed[i] = 0x0; fChNoise[i] = 0x0; fNPoint[i] = 0x0; fData[i] = 0x0; fSignal[i] = 0x0; fnEntriesRM[i] = 0x0; fnEntriesRMDist[i] = 0x0; fChPedRes[i] = 0x0; fChNoiseRes[i] = 0x0; fErrorLocHC[i] = 0x0; fErrorLocMCM[i] = 0x0; fErrorLocADC[i] = 0x0; } for (Int_t i = 0; i < 3; i++) { fGraphPP[i] = 0x0; fSMLink[i] = 0x0; fGrLink[i] = 0x0; fppThresh[i] = 0; fnPP[i] = 0; fnLink[i] = 0; } for (Int_t i = 0; i < 2; i++) { fnErrorHC[i] = 0; fnErrorMCM[i] = 0; fnErrorADC[i] = 0; } for (Int_t i = 0; i < kSM; i++) { fSmNoiseRms[i] = 0x0; fSmNoiseFit[i] = 0x0; fSmPP[i] = 0x0; } for (Int_t i = 0; i < kSM+1; i++) { fNumberADC[i] = 0x0; fnADCinSM[i] = 0; } for (Int_t i = 0; i < 1000; i++) { fEvNoDist[i] = 0; } for (Int_t i = 0; i < kDET*kROB*kMCM; i++) { fFullSignal[i] = 0x0; fFullCounter[i] = 0; } //strncpy(fRefFileName,"",256); } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::Init() { // // creates histograms // //TFile *file = new //Info("Init", "Statring"); fnEvents = 0; // histograms for chambers for(Int_t det=0; det<kDET; det++) { fNPoint[det] = new TH2D(Form("entries_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); //fData[det] = new TH3F(Form("data_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5, 50, -0.5, 49.5); // pedestal noise maps using RMS and Fit fChPed[det] = new TH2D(Form("ped_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); fChNoise[det] = new TH2D(Form("noise_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); //fChPed[det] = new TH2D(Form("ped_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); //fChNoise[det] = new TH2D(Form("noise_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); // distribution per detector fPed[det] = new TH1D(Form("pedDist_%d", det), ";pedestals (ADC counts)", 100, 5, 15); fNoise[det] = new TH1D(Form("noiseDist_%d", det), ";noise (ADC counts)", 100, 0, 5); fSignal[det] = new TH1D(Form("signal_%d", det), ";signal (ADC counts)", 100, -0.5, 99.5); fChPP[det] = new TH1D(Form("pp_%d", det), ";pp (ADC)", 200, -0.5, 199.5); fnEntriesRM[det] = new TH2D(Form("entriesRM_%d", det), ";ROB,MCM", 8, -0.5, 7.5, 16, -0.5, 15.5); // histograms after reference subtraction fChPedRes[det] = new TH2D(Form("pedRef_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); fChNoiseRes[det] = new TH2D(Form("noiseRef_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); // error codes fErrorLocMCM[det] = new TH2D(Form("errorLocMCM_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); fErrorLocADC[det] = new TH2D(Form("errorLocADC_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); fErrorLocHC[det] = new TH2D(Form("errorLocHC_%d", det), "", 16, -0.5, 15.5, 144, -0.5, 143.5); } // histogram for each MCM for(Int_t i=0; i < kDET * kROB * kMCM; i++) fFullCounter[i] = 0; // histograms from the whole detector fOccupancy = new TH1D("occupancy", "", 20, -0.5, 19.5); fDetRob = new TH2D("DetRob", ";detector;ROB", kDET, -0.5, 539.5, 8, -0.5, 7.5); fTBEvent = new TH2D("tbEvent", ";event ID;time bin", 100, -0.5, 99.5, 30, -0.5, 29.5); // errors statistics and location fErrorHC = new TH1D("errorHC", ";error ID;", 18, -3.5, 14.5); fErrorMCM = new TH1D("errorMCM", ";error ID;", 18, -3.5, 14.5); fErrorADC = new TH1D("errorADC", ";error ID;", 18, -3.5, 14.5); fErrorSMHC = new TH1D("errorSM_HC", ";SM id", 18, -0.5, 17.5); fErrorSMMCM = new TH1D("errorSM_MCM", ";SM id", 18, -0.5, 17.5); fErrorSMADC = new TH1D("errorSM_ADC", ";SM id", 18, -0.5, 17.5); fErrorGraphHC = new TGraph(); fErrorGraphMCM = new TGraph(); fErrorGraphADC = new TGraph(); fGraphMCM = new TGraph(); for(Int_t i=0; i<3; i++) { fGraphPP[i] = new TGraph(); } fMapMCM = new TH2D("mapMCM", ";det;mcm", 540, -0.5, 539.5, kROB*kMCM, -0.5, kROB*kMCM-0.5); fFracMCM = new TH1D("fracMCM", ";frequency", 100, 0, 1); fErrorGraphHC->GetHistogram()->SetTitle("fraction of events with HC error;event number"); fErrorGraphMCM->GetHistogram()->SetTitle("fraction of events with MCM error;event number;"); fErrorGraphADC->GetHistogram()->SetTitle("fraction of events with ADC error;event number;"); fSMHCped = new TH2D("smHcPed", ";super module;half chamber", 18, -0.5, 17.5, 60, -0.5, 59.5); // link monitor const char *linkName[3] = {"smLink", "smBeaf", "smData"}; const char *linkGrName[3] = {"grSmLink", "grSmBeaf", "grSmData"}; for(Int_t i=0; i<3; i++) { fSMLink[i] = new TH2D(linkName[i], ";super module;link", 18, -0.5, 17.5, 60, -0.5, 59.5); fGrLink[i] = new TGraph(); fGrLink[i]->SetName(linkGrName[i]); } //fZSsize = new TH1D("zssizeSingle", ";threshold;nADC", 40, -0.5, 39.5); //Info("Init", "Done"); // number of ADC channels fired per SM and in total for(Int_t sm=0; sm<kSM+1; sm++) fNumberADC[sm] = new TGraph(); // fNoiseTotal = new TH1D("noiseTotal", "noise (ADC)", 250, 0, 10); fPP = new TH1D("peakPeak", "p-p (ADC)", 200, -0.5, 199.5); for(Int_t sm=0; sm<kSM; sm++) { fSmNoiseRms[sm] = new TH1D(Form("noiseRms_sm%d", sm), ";noise from RMS (ADC)", 100, 0, 10); fSmNoiseFit[sm] = new TH1D(Form("noiseFit_sm%d", sm), ";noise frim Fit (ADC)", 100, 0, 10); fSmPP[sm] = new TH1D(Form("peakPeak_sm%d", sm), ";peak-peak (ADC)", 200, -0.5, 199.5); } // event number consistancy for(Int_t i=0; i<1000; i++) { fEvNoDist[i] = new TH1D(Form("mcmEvDist_%d", i), ";#Delta Events", 201, -100.5, 100.5); } fRefEv = -1; fMcmTracks = new TObjArray(); // clean data direct for(Int_t det=0; det<kDET; det++) for(Int_t row=0; row<kROW; row++) for(Int_t pad=0; pad<kPAD; pad++) for(Int_t ch=0; ch<kCH; ch++) { fDataDirect[det][row][pad][ch] = 0; fSignalDirect[det][ch] = 0; // overdone } } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::Reset() { // // Resets the histograms // for(Int_t i=0; i<kDET; i++) { //fData[i]->Reset(); fChPed[i]->Reset(); fChNoise[i]->Reset(); } } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::SetRefFile(const char *filename) { //strncpy(fRefFileName,filename,256); fRefFileName = filename; } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::ReadRefHists(Int_t det) { // // Read the reference histograms // fRefHistPed = 0; fRefHistNoise = 0; TFile *file = 0x0; if (fRefFileName) file = TFile::Open(fRefFileName); if (!file) return; fRefHistPed = (TH2D*)file->Get(Form("ped_%d",det)); fRefHistNoise = (TH2D*)file->Get(Form("noise_%d", det)); if (file) file->Close(); } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::StartEvent() { // // start an event // // clear the mcm data for(Int_t i=0; i < kDET * kROB * kMCM; i++) { if (fFullSignal[i]) fFullSignal[i]->Reset(); fFullCounter[i] = 0; } for(Int_t i=0; i<2; i++) { fnErrorHC[i] = 0; fnErrorMCM[i] = 0; fnErrorADC[i] = 0; } Int_t ppThresh[3] = {10, 20, 40}; for(Int_t i=0; i<3; i++) { fppThresh[i] = ppThresh[i]; fnPP[i] = 0; fnLink[i] = 0; } for(Int_t sm=0; sm<kSM+1; sm++) fnADCinSM[sm] = 0; if (fRefEv > 0) fRefEv++; fEvNoDist[999]->Reset(); // keep only the last event } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::AddBuffer(AliTRDrawStreamOld *data, AliRawReader * const reader) { //printf ("try to read data\n"); Int_t nextBuff = data->NextBuffer(); //printf("done ...\n"); if (nextBuff == 0) return; Int_t sm = reader->GetEquipmentId() - 1024; //printf("reading SM %d\n", sm); AliInfo(Form("reading SM %d", sm)); if (sm < 0 || sm > 17) return; // lopp over stacks, links ... for (Int_t istack = 0; istack < 5; istack++) { for (Int_t ilink = 0; ilink < 12; ilink++) { //printf("HC = %d %d\n", istack, ilink); Int_t det = sm * 30 + istack * 6 + ilink/2; // check if data delivered if (!(data->IsLinkActiveInStack(istack, ilink))) continue; fSMLink[0]->Fill(sm, istack * 12 + ilink); fnLink[0]++; // check if beaf-beaf if (data->GetLinkMonitorError(istack, ilink)) { fSMLink[1]->Fill(sm, istack * 12 + ilink); fnLink[1]++; continue; } // fill histogram with HC header errors Int_t nErrHc = 0; Int_t nErrHcTot = 0; nErrHc = FillBits(fErrorHC, data->GetH0ErrorCode(istack, ilink), 0); if (!nErrHc) fErrorHC->Fill(-3); nErrHcTot += nErrHc; nErrHc = FillBits(fErrorHC, data->GetH1ErrorCode(istack, ilink), 2); if (!nErrHc) fErrorHC->Fill(-2); nErrHcTot += nErrHc; nErrHc = FillBits(fErrorHC, data->GetHCErrorCode(istack, ilink), 4); if (!nErrHc) fErrorHC->Fill(-1); nErrHcTot += nErrHc; // trending fnErrorHC[0]++; if (nErrHcTot > 0) { fnErrorHC[1]++; fErrorSMHC->Fill(sm); } // data integrity protection //if (data->GetHCErrorCode(istack, ilink) > 0) continue; if (data->GetH0ErrorCode(istack, ilink) > 0) continue; if (data->GetH1ErrorCode(istack, ilink) > 0) continue; fSMLink[2]->Fill(sm, istack * 12 + ilink); fnLink[2]++; for (Int_t imcm = 0; imcm < data->GetHCMCMmax(istack, ilink); imcm++ ){ //printf("mcm = %d %d %d\n", istack, ilink, imcm); // fill MCM error code Int_t nErrMcm = 0; Int_t nErrMcmTot = 0; nErrMcm = FillBits(fErrorMCM, data->GetMCMhdErrorCode(istack, ilink, imcm), 0); if (!nErrMcm) fErrorMCM->Fill(-3); nErrMcmTot += nErrMcm; nErrMcm = FillBits(fErrorMCM, data->GetMCMADCMaskErrorCode(istack, ilink, imcm), 5); if (!nErrMcm) fErrorMCM->Fill(-2); nErrMcmTot += nErrMcm; nErrMcm = FillBits(fErrorMCM, data->GetMCMErrorCode(istack, ilink, imcm), 10); if (!nErrMcm) fErrorMCM->Fill(-1); nErrMcmTot += nErrMcm; // trending fnErrorMCM[0]++; if (nErrMcmTot > 0) { fnErrorMCM[1]++; fErrorSMMCM->Fill(sm); } // MCM protection if ( (data->GetMCMhdErrorCode(istack,ilink,imcm)) & 2 ) continue; //if ((data->GetMCMADCMaskErrorCode(istack,ilink,imcm))) continue; //if ((data->GetMCMErrorCode(istack,ilink,imcm))) continue; Int_t mcmEvent = data->GetEventNumber(istack, ilink, imcm); // set the reference event number if (fRefEv < 0) { fRefEv = mcmEvent; printf("Reference Event Number = %d (%d %d %d)\n", fRefEv, istack, ilink, imcm); } // fill event distribution if (!(fnEvents%10)) { fEvNoDist[fnEvents/10]->Fill(mcmEvent - fRefEv); } fEvNoDist[999]->Fill(mcmEvent - fRefEv); Int_t mcm = data->GetMCM(istack, ilink, imcm); Int_t rob = data->GetROB(istack, ilink, imcm); // create a structure for an MCM if needed Int_t mcmIndex = det * (kMCM * kROB) + rob * kMCM + mcm; if (fCreateFull && !fFullSignal[mcmIndex]) fFullSignal[mcmIndex] = new TH2S(Form("mcm_%d_%d_%d_%d_%d", sm, istack, ilink/2, rob, mcm), Form("mcm-%d-%d-%d-%d-%d;ADC;time bin", sm, istack, ilink/2, rob, mcm), 21, -0.5, 20.5, 30, -0.5, 29.5); //Int_t zsADC[21][40]; /* for(Int_t ina=0; ina<21; ina++) for(Int_t th=0; th<40; th++) zsADC[ina][th] = 0; */ // first loop over ADC chanels for (Int_t iadc=0; iadc < data->GetADCcount(istack, ilink, imcm); iadc++) { //printf("ADC = %d\n", iadc); // fill ADC error bits Int_t nErrAdc = FillBits(fErrorADC, data->GetADCErrorCode(), 0); if (!nErrAdc) fErrorADC->Fill(-1); fnErrorADC[0]++; if (nErrAdc > 0) { fnErrorADC[1]++; fErrorSMADC->Fill(sm); } // ADC protection if ((data->GetADCErrorCode(istack,ilink,imcm,iadc))) continue; Int_t minV = 1024; Int_t maxV = 0; Int_t *sig = data->GetSignalDirect(istack, ilink, imcm, iadc); //Int_t adc = data->GetADCnumber(istack, ilink, imcm, iadc); Int_t row = data->GetRow(istack, ilink, imcm); Int_t col = data->GetCol(istack, ilink, imcm, iadc); // loop over Time Bins and fill histograms for(Int_t k=0; k < data->GetNumberOfTimeBins(istack, ilink); k++) { //fSignal[det]->Fill(sig[k]); //fData[det]->Fill(row, col, sig[k]); // slow if ((sig[k] >=0) && (sig[k] < kCH)) { fSignalDirect[det][sig[k]]++; fDataDirect[det][row][col][sig[k]]++; // direct data } // peak-peak minV = (minV < sig[k]) ? minV : sig[k]; maxV = (maxV > sig[k]) ? maxV : sig[k]; // check for active MCMs if (fCreateFull && fFullSignal[mcmIndex]) { if (sig[k] > fThresh || sig[k] < 0) fFullCounter[mcmIndex]++; //if (sm == 0 && istack == 0 && ilink/2 == 1 && rob == 1 && mcm == 15) fFullCounter[mcmIndex]++; // special //fFullSignal[mcmIndex]->Fill(adc, k, sig[k]); // slow } // zero suppresion tests /* for(Int_t th=0; th<40; th++) { if (sig[k] > th) { zsADC[iadc][th] = 1; if (iadc > 0) zsADC[iadc-1][th] = 1; if (iadc < 10) zsADC[iadc+1][th] = 1; } } */ } // tb if (maxV > 0) { fnADCinSM[sm]++; fnADCinSM[kSM]++; } Int_t adcPP = maxV - minV; //if (adcPP == 100) fFullCounter[mcmIndex] += 10; fPP->Fill(adcPP); fChPP[det]->Fill(adcPP); fSmPP[sm]->Fill(adcPP); for(Int_t i=0; i<3; i++) { if ((adcPP) > fppThresh[i]) fnPP[i]++; } } // adc // fill ZS histos /* for(Int_t th=0; th<40; th++) { Int_t nnADC = 0; for(Int_t ins=0; ins<21; ins++) nnADC += zsADC[ins][th]; fZSsize->Fill(th, nnADC); } */ // fill active MCMs if (fCreateFull && fFullSignal[mcmIndex] && (fFullCounter[mcmIndex] > fCount)) { for (Int_t iadc=0; iadc < data->GetADCcount(istack, ilink, imcm); iadc++) { // ADC protection if ((data->GetADCErrorCode(istack,ilink,imcm,iadc))) continue; //Int_t row = data->GetRow(istack, ilink, imcm); //Int_t col = data->GetCol(istack, ilink, imcm, iadc); Int_t adc = data->GetADCnumber(istack, ilink, imcm, iadc); Int_t *sig = data->GetSignalDirect(istack, ilink, imcm, iadc); // loop over Time Bins and fill histograms for(Int_t k=0; k < data->GetNumberOfTimeBins(istack, ilink); k++) { fFullSignal[mcmIndex]->Fill(adc, k, sig[k]); // slow } } // tb } } // mcm } // link } // stack // printf("end of loops\n"); } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::FinishEvent() { // // Processing at the end of the current event // for(Int_t i=0; i<3; i++) { fGraphPP[i]->SetPoint(fnEvents, fnEvents, fnPP[i]); } // trend of the number of links for(Int_t i=0; i<3; i++) { fGrLink[i]->SetPoint(fnEvents, fnEvents, fnLink[i]); } // save interesting histos Int_t mcmTrackCandidate = 0; for(Int_t i = 0; i < kDET * kROB * kMCM; i++) { if ((fFullCounter[i] > fCount) && fFullSignal[i] && CheckMCM(i) ) { fMcmTracks->AddLast(fFullSignal[i]->Clone(Form("event_%d_%s", fnEvents, fFullSignal[i]->GetName()))); mcmTrackCandidate++; Int_t mcmTrackletDet = i/(kROB * kMCM); Int_t mcmTrackletMcm = i%(kROB * kMCM); fMapMCM->Fill(mcmTrackletDet, mcmTrackletMcm); } } fGraphMCM->SetPoint(fnEvents, fnEvents, mcmTrackCandidate); AliInfo(Form("Number of MCM track candidates = %d\n", mcmTrackCandidate)); // update fraction of error graphs Double_t err; err = (fnErrorHC[0] > 0)? 100.*fnErrorHC[1]/fnErrorHC[0] : -1; fErrorGraphHC->SetPoint(fnEvents, fnEvents, err); err = (fnErrorMCM[0] > 0)? 100.*fnErrorMCM[1]/fnErrorMCM[0] : -1; fErrorGraphMCM->SetPoint(fnEvents, fnEvents, err); err = (fnErrorADC[0] > 0)? 100.*fnErrorADC[1]/fnErrorADC[0] : -1; fErrorGraphADC->SetPoint(fnEvents, fnEvents, err); // number of fired ADC per SM for(Int_t sm=0; sm<kSM+1; sm++) fNumberADC[sm]->SetPoint(fnEvents, fnEvents, fnADCinSM[sm]); fnEvents++; } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::Process(const char *filename) { // // Process something // //char fn[256]; //strncpy(fn,filename,256); //AliInfo(Form("FILENAME = %s (%s)\n", filename, fn)); Int_t map[kDET]; TH1D *hist = new TH1D("fitSignal", "", 50, -0.5, 49.5); TF1 *fit = new TF1("fit", "gaus(0)", 0, 20); fit->SetParameters(1e3, 10, 1); for(Int_t det=0; det<kDET; det++) { //AliInfo(Form("processing chamber %d\n", det)); map[det] = 0; //if (fData[det]->GetSum() < 10) continue; //if (fDataDirect[det][10][10][10] < 20) continue; //map[det] = 1; // rewrite signal-direct for(Int_t ch=0; ch<kCH; ch++) { fSignal[det]->Fill(ch, fSignalDirect[det][ch]); } // read reference distributions ReadRefHists(det); //for(Int_t row=0; row<fData[det]->GetXaxis()->GetNbins(); row++) { //for(Int_t pad=0; pad<fData[det]->GetYaxis()->GetNbins(); pad++) { for(Int_t row=0; row<kROW; row++) { for(Int_t pad=0; pad<kPAD; pad++) { // project the histogramm hist->Reset(); //for(Int_t bb=0; bb<50; bb++) { for(Int_t bb=0; bb<kCH; bb++) { //Int_t dataBin = fData[det]->FindBin(row, pad, bb); //Double_t v = fData[det]->GetBinContent(dataBin); hist->SetBinContent(bb+1, fDataDirect[det][row][pad][bb]); } Int_t bin = fChPed[det]->FindBin(row, pad); if (hist->GetSum() > 1) { map[det] = 1; Double_t ped = 0, noise = 0; if (fFitType == 0) { fit->SetParameters(1e3, 10, 1); hist->Fit(fit, "q0", "goff", 0, 20); TF1 *f = hist->GetFunction("fit"); ped = TMath::Abs(f->GetParameter(1)); noise = TMath::Abs(f->GetParameter(2)); fSmNoiseFit[det/30]->Fill(noise); } else { ped = hist->GetMean(); noise = hist->GetRMS(); fSmNoiseRms[det/30]->Fill(noise); //if (pad == 0) // AliInfo(Form("data %f %f %f\n", hist->GetSum(), ped, noise)); } fChPed[det]->SetBinContent(bin, ped); fChNoise[det]->SetBinContent(bin, noise); fNoiseTotal->Fill(noise); // subtract reference values Double_t refped = 0; Double_t refnoise = 0; if (fRefHistPed) refped = fRefHistPed->GetBinContent(bin); if (fRefHistPed) refnoise = fRefHistPed->GetBinContent(bin); // Original code, should it not be fRefHistNoise->GetBinContent(bin) // instead of fRefHistPed->GetBinContent(bin) (CBL) ??? //if (fRefHistNoise) refnoise = fRefHistPed->GetBinContent(bin); fChPedRes[det]->SetBinContent(bin, ped-refped); fChNoiseRes[det]->SetBinContent(bin, noise-refnoise); fPed[det]->Fill(ped); fNoise[det]->Fill(noise); // fill SM-HC plot Int_t sm = det / 30; Int_t hc = (pad < kPAD/2) ? 2* (det % 30) : 2* (det % 30) + 1; if (ped > 9. && ped < 11) fSMHCped->Fill(sm, hc, 1./1152.); // number of pads in HC } else { // not enought data found fChPed[det]->SetBinContent(bin, 0); fChNoise[det]->SetBinContent(bin, 0); fChPedRes[det]->SetBinContent(bin, 0); fChNoiseRes[det]->SetBinContent(bin, 0); } //delete hist; } } } //AliInfo(Form("Number of events = %d\n", fnEvents)); // normalize number of entries histos Int_t max = 0; for(Int_t i=0; i<kDET; i++) { if (!map[i]) continue; for(Int_t j=0; j<fNPoint[i]->GetXaxis()->GetNbins(); j++) { for(Int_t k=0; k<fNPoint[i]->GetYaxis()->GetNbins(); k++) { Int_t dataBin = fNPoint[i]->FindBin(j, k); Double_t v = fNPoint[i]->GetBinContent(dataBin); if (v > max) max = (Int_t)v; } } } char entriesDistName[100]; for(Int_t i=0; i<kDET; i++) { if (!map[i]) continue; snprintf(entriesDistName,100,"entriesDist_%d",i); fNPointDist[i] = new TH1D(entriesDistName, ";number of events", max+2, -0.5, max+1.5); for(Int_t j=0; j<fNPoint[i]->GetXaxis()->GetNbins(); j++) { for(Int_t k=0; k<fNPoint[i]->GetYaxis()->GetNbins(); k++) { Int_t dataBin = fNPoint[i]->FindBin(j, k); Double_t v = fNPoint[i]->GetBinContent(dataBin); //if (v > fnEvents) AliInfo(Form("N = %d V = %lf\n", fnEvents, v)); fNPointDist[i]->Fill(v); } } fNPoint[i]->Scale(1./fnEvents); } for(Int_t i=0; i<kDET; i++) { fnEntriesRM[i]->SetMaximum(fnEvents * 1.5); } // save histograms //AliInfo(Form("FILENAME 2 = %s (%d)\n", fn, fn)); TFile *file = new TFile(filename, "recreate"); for(Int_t det = 0; det < kDET; det++) { if (!map[det]) continue; fChPed[det]->Write(); fChNoise[det]->Write(); fNPoint[det]->Write(); fNPointDist[det]->Write(); fPed[det]->Write(); fNoise[det]->Write(); fSignal[det]->Write(); fnEntriesRM[det]->Write(); fChPP[det]->Write(); fChPedRes[det]->Write(); fChNoiseRes[det]->Write(); // save error hists fErrorLocMCM[det]->SetMinimum(0); fErrorLocMCM[det]->SetMaximum(fnEvents); fErrorLocMCM[det]->Write(); fErrorLocADC[det]->SetMinimum(0); fErrorLocADC[det]->SetMaximum(fnEvents); fErrorLocADC[det]->Write(); } for(Int_t sm=0; sm<kSM; sm++) { fSmNoiseRms[sm]->Write(); fSmNoiseFit[sm]->Write(); fSmPP[sm]->Write(); } Int_t nMcm = 0; for(Int_t i=0; i < kDET * kROB * kMCM; i++) { if (fFullSignal[i] && fFullCounter[i] > fCount) { fFullSignal[i]->Write(); nMcm++; } } AliInfo(Form("Number of saved MCMs = %d\n", nMcm)); fMcmTracks->Write(); AliInfo(Form("Number of tracks = %d\n", fMcmTracks->GetEntries())); // permanently problematic MCMs for(Int_t det=0; det<kDET; det++) { for(Int_t mcm=0; mcm<kROB*kMCM; mcm++) { Int_t mRob = mcm / kMCM; Int_t mMcm = mcm % kMCM; Int_t bin = fMapMCM->FindBin(det, mcm); Double_t frac = 1. * fMapMCM->GetBinContent(bin) / fnEvents; fFracMCM->Fill(frac); if (frac > 0.7) { AliInfo(Form("{%d, %d, %d, %f}, \n", det, mRob, mMcm, frac)); } } } fOccupancy->Write(); fDetRob->Write(); fTBEvent->Write(); // error hists fErrorHC->Write(); fErrorMCM->Write(); fErrorADC->Write(); fErrorSMHC->Write(); fErrorSMMCM->Write(); fErrorSMADC->Write(); // write graphs fErrorGraphHC->Write("trendErrorHC"); fErrorGraphMCM->Write("trendErrorMCM"); fErrorGraphADC->Write("trendErrorADC"); fGraphMCM->Write("trendMCM"); for(Int_t i=0; i<3; i++) { fGraphPP[i]->Write(Form("fracPP_%d", i)); } //fZSsize->Scale(1./fnEvents); //fZSsize->Write(); fMapMCM->SetMaximum(fnEvents); fMapMCM->Write(); fFracMCM->Write(); fSMHCped->Write(); for(Int_t i=0; i<3; i++ ) { fSMLink[i]->Write(); fGrLink[i]->Write(); } for(Int_t sm=0; sm<kSM; sm++) fNumberADC[sm]->Write(Form("nADCinSM%d",sm)); fNumberADC[kSM]->Write("nADCinEvent"); fNoiseTotal->Write(); fPP->Write(); for(Int_t i=0; i<1000; i++) { if (fEvNoDist[i]->GetSum() > 0) fEvNoDist[i]->Write(); } file->Close(); delete file; } /////////////////////////////////////////////////////////////////////////////////////////////////// Int_t AliTRDqaBlackEvents::CheckMCM(Int_t /*index*/) const { // // Checks a single MCM // return 1; // static Int_t data[21][3] = { // {1, 0, 1}, // {242, 0, 0}, // {242, 0, 1}, // {242, 0, 2}, // {242, 0, 4}, // {242, 0, 5}, // {242, 0, 6}, // {242, 0, 8}, // {242, 0, 12}, // {251, 7, 7}, // {254, 3, 11}, // {259, 3, 14}, // {260, 1, 9}, // {260, 3, 15}, // {273, 1, 7}, // {273, 1, 15}, // {276, 5, 11}, // {280, 6, 2}, // {299, 6, 4}, // {511, 2, 9}, // {517, 7, 15} // }; // for(Int_t i=0; i<21; i++) { // Int_t wIndex = data[i][0] * kROB*kMCM + data[i][1] * kMCM + data[i][2]; // if (index == wIndex) return 0; // } return 1; } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::DrawChamber(const char *filename, Int_t det, Int_t w, Int_t h) { // // Draw raport for one chamber: // pedestal map, noise map, distribution of pedestal and noise // // input: // name of the file with histograms (created with Process()) // detector Id (0 - 539) // // setup global style gStyle->SetPalette(1); gStyle->SetOptStat(0); gStyle->SetPadTopMargin(0.02); gStyle->SetPadBottomMargin(0.05); TFile *file = new TFile(filename, "READ"); TCanvas *c = new TCanvas("blackEvents",Form("blackEvents %d",det), w, h); c->SetVertical(kFALSE); c->Divide(3,1, 0.01, 0.01); c->cd(3); TPad *mPad = (TPad*) gPad; mPad->Divide(1,2,0.01,0.01); c->cd(1); TH2D *h2 = (TH2D*)file->Get(Form("ped_%d",det)); h2->SetMinimum(5); h2->SetMaximum(15); h2->SetTitle(";Z direction;#phi direction"); h2->Draw("colz"); c->cd(2); h2 = (TH2D*)file->Get(Form("noise_%d",det)); h2->SetMinimum(fMinNoise); h2->SetMaximum(fMaxNoise); h2->SetTitle(";Z direction;#phi direction"); h2->Draw("colz"); mPad->cd(1); //gPad->SetLogy(); TH1D *h1 = (TH1D*)file->Get(Form("pedDist_%d", det)); h1->Draw(); mPad->cd(2); gPad->SetLogy(); h1 = (TH1D*)file->Get(Form("noiseDist_%d", det)); h1->Draw(); h1->Fit("gaus"); TF1 *f = h1->GetFunction("gaus"); const char *tt = Form("#mu = %.2f #sigma = %0.2f ", f->GetParameter(1),f->GetParameter(2)); TLatex *ll = new TLatex(2, 100, tt); ll->SetTextSize(0.06); ll->Draw(); } /////////////////////////////////////////////////////////////////////////////////////////////////// void AliTRDqaBlackEvents::DrawSm(const char *filename, Int_t sm, Int_t w, Int_t h) { // // ???????????? // gStyle->SetPalette(1); gStyle->SetOptStat(0); gStyle->SetPadTopMargin(0.02); //gStyle->SetPadBottomMargin(0.05); //gStyle->SetPadLeftMargin(0.02); //gStyle->SetPadRightMargin(0.02); TFile *file = new TFile(filename, "READ"); TCanvas *c = new TCanvas("blackEventsSM",Form("blackEvents SM %d",sm), w, h); c->SetVertical(kFALSE); c->Divide(5, 6, 0.001, 0.01); for(Int_t i=0; i<30; i++) { TH2D *h2 = (TH2D*)file->Get(Form("noise_%d",i+30*sm)); if (!h2) continue; h2->SetMinimum(fMinNoise); h2->SetMaximum(fMaxNoise); // to be replaced by the official calculation Int_t stack = i/6; Int_t layer = i%6; Int_t index = (5-layer)*5 + stack + 1; //AliInfo(Form("%d %d %d %d\n", i, stack, layer, index)); c->cd(index); gPad->SetBottomMargin(0.02); gPad->SetTopMargin(0.02); h2->Draw("col"); } } /////////////////////////////////////////////////////////////////////////////////////////////////// Int_t AliTRDqaBlackEvents::FillBits(TH1D *hist, Int_t code, Int_t offset) { // // Fill bits // Int_t nb = 0; UInt_t test = 1; for(Int_t i=0; i<8; i++) { if (code & test) { hist->Fill(i+offset); nb++; } test *= 2; } return nb; } ///////////////////////////////////////////////////////////////////////////////////////////////////
27.342454
114
0.528643
AllaMaevskaya
29b95b0e5692a4119f1477a545fcc57820c2cd55
1,284
cc
C++
awgn.cc
aicodix/disorders
dd82ccef185ed7746f732bbf85a10187095f3599
[ "0BSD" ]
1
2021-05-28T21:04:53.000Z
2021-05-28T21:04:53.000Z
awgn.cc
aicodix/disorders
dd82ccef185ed7746f732bbf85a10187095f3599
[ "0BSD" ]
null
null
null
awgn.cc
aicodix/disorders
dd82ccef185ed7746f732bbf85a10187095f3599
[ "0BSD" ]
2
2021-07-09T15:04:08.000Z
2021-10-06T13:51:17.000Z
/* Additive white Gaussian noise Copyright 2020 Ahmet Inan <inan@aicodix.de> */ #include <iostream> #include <cmath> #include <random> #include <functional> #include "complex.hh" #include "wav.hh" int main(int argc, char **argv) { if (argc != 4) { std::cerr << "usage: " << argv[0] << " OUTPUT INPUT AWGN" << std::endl; return 1; } typedef float value; typedef DSP::Complex<value> cmplx; const char *out_name = argv[1]; const char *inp_name = argv[2]; value awgn = std::atof(argv[3]); DSP::ReadWAV<value> inp_file(inp_name); if (inp_file.channels() < 1 || inp_file.channels() > 2) { std::cerr << "Only real or analytic signal (one or two channels) supported." << std::endl; return 1; } DSP::WriteWAV<value> out_file(out_name, inp_file.rate(), inp_file.bits(), inp_file.channels()); value mean = 0; value sigma = std::sqrt(2 * std::pow(10, awgn / 10)); std::random_device rd; typedef std::default_random_engine generator; typedef std::normal_distribution<value> normal; auto noise = std::bind(normal(mean, sigma), generator(rd())); while (out_file.good() && inp_file.good()) { cmplx tmp; inp_file.read(reinterpret_cast<value *>(&tmp), 1); tmp += cmplx(noise(), noise()); out_file.write(reinterpret_cast<value *>(&tmp), 1); } return 0; }
23.777778
96
0.668224
aicodix
29ba28f94c8318d0df42d635902ab45a9c6b8feb
1,237
hpp
C++
demo_app/mipmap_pipelines.hpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
12
2021-07-24T18:33:22.000Z
2022-03-12T16:20:49.000Z
demo_app/mipmap_pipelines.hpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
null
null
null
demo_app/mipmap_pipelines.hpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
3
2021-08-04T02:27:12.000Z
2022-03-13T08:43:24.000Z
// Copyright 2021 NVIDIA CORPORATION // SPDX-License-Identifier: Apache-2.0 #ifndef VK_COMPUTE_MIPMAPS_DEMO_MIPMAP_PIPELINES_HPP_ #define VK_COMPUTE_MIPMAPS_DEMO_MIPMAP_PIPELINES_HPP_ #include "pipeline_alternative.hpp" #include <vulkan/vulkan.h> class ScopedImage; struct PipelineAlternative; // Class holding compute shader pipelines that computes srgba8 // mipmaps. There are a lot of pipelines stored here, due to testing // the performance effects of changes. class ComputeMipmapPipelines { protected: ComputeMipmapPipelines() = default; public: virtual ~ComputeMipmapPipelines() = default; // Record a command to generate mipmaps for the specified image // using info stored in the base level and the named pipeline // alternatives. No barrier is included before (i.e. it's your // responsibility), but a barrier is included after for read // visibility to fragment shaders. virtual void cmdBindGenerate(VkCommandBuffer cmdBuf, const ScopedImage& imageToMipmap, const PipelineAlternative& alternative) = 0; static ComputeMipmapPipelines* make(VkDevice device, const ScopedImage& image, bool dumpPipelineStats); }; #endif
32.552632
75
0.74131
nvpro-samples
29babc06881724e1bbeedbfee85646b6123ed545
2,437
cpp
C++
code/engine/xrGame/alife_online_offline_group_brain.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
58
2016-11-20T19:14:35.000Z
2021-12-27T21:03:35.000Z
code/engine/xrGame/alife_online_offline_group_brain.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
59
2016-09-10T10:44:20.000Z
2018-09-03T19:07:30.000Z
code/engine/xrGame/alife_online_offline_group_brain.cpp
InNoHurryToCode/xray-162
fff9feb9ffb681b3c6ba1dc7c4534fe80006f87e
[ "Apache-2.0" ]
39
2017-02-05T13:35:37.000Z
2022-03-14T11:00:12.000Z
//////////////////////////////////////////////////////////////////////////// // Module : alife_online_offline_group_brain.cpp // Created : 25.10.2005 // Modified : 25.10.2005 // Author : Dmitriy Iassenev // Description : ALife Online Offline Group brain class //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "alife_online_offline_group_brain.h" //#include "object_broker.h" #include "xrServer_Objects_ALife_Monsters.h" #ifdef XRGAME_EXPORTS #include "alife_monster_movement_manager.h" #include "alife_monster_detail_path_manager.h" //# include "alife_monster_patrol_path_manager.h" //# include "ai_space.h" //# include "ef_storage.h" //# include "ef_primary.h" //# include "alife_simulator.h" //# include "alife_graph_registry.h" #include "movement_manager_space.h" //# include "alife_smart_terrain_registry.h" #include "alife_object_registry.h" //# include "alife_time_manager.h" //# include "date_time.h" #ifdef DEBUG #include "level.h" //# include "map_location.h" //# include "map_manager.h" #endif #endif #define MAX_ITEM_FOOD_COUNT 3 #define MAX_ITEM_MEDIKIT_COUNT 3 #define MAX_AMMO_ATTACH_COUNT 1 CALifeOnlineOfflineGroupBrain::CALifeOnlineOfflineGroupBrain(object_type* object) { VERIFY(object); m_object = object; #ifdef XRGAME_EXPORTS m_movement_manager = xr_new<CALifeMonsterMovementManager>(object); #endif } CALifeOnlineOfflineGroupBrain::~CALifeOnlineOfflineGroupBrain() { #ifdef XRGAME_EXPORTS xr_delete(m_movement_manager); #endif } void CALifeOnlineOfflineGroupBrain::on_state_write(NET_Packet& packet) {} void CALifeOnlineOfflineGroupBrain::on_state_read(NET_Packet& packet) {} #ifdef XRGAME_EXPORTS void CALifeOnlineOfflineGroupBrain::on_register() {} void CALifeOnlineOfflineGroupBrain::on_unregister() {} void CALifeOnlineOfflineGroupBrain::on_location_change() {} void CALifeOnlineOfflineGroupBrain::update() { CALifeSmartTerrainTask* const task = object().get_current_task(); THROW2(task, "CALifeOnlineOfflineGroupBrain returned nil task, while npc is registered in it"); movement().path_type(MovementManager::ePathTypeGamePath); movement().detail().target(*task); movement().update(); } void CALifeOnlineOfflineGroupBrain::on_switch_online() { movement().on_switch_online(); } void CALifeOnlineOfflineGroupBrain::on_switch_offline() { movement().on_switch_offline(); } #endif // XRGAME_EXPORTS
30.848101
99
0.733279
InNoHurryToCode
29bbce56dee1f5b2994a599318982a918db4cb80
4,387
cc
C++
Print/src/ComboHitPrinter.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Print/src/ComboHitPrinter.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Print/src/ComboHitPrinter.cc
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#include "Offline/Print/inc/ComboHitPrinter.hh" #include "art/Framework/Principal/Provenance.h" #include <string> #include <iomanip> void mu2e::ComboHitPrinter::Print(art::Event const& event, std::ostream& os) { if(verbose()<1) return; if(tags().empty()) { // if a list of instances not specified, print all instances std::vector< art::Handle<ComboHitCollection> > vah = event.getMany<ComboHitCollection>(); for (auto const & ah : vah) Print(ah); } else { // print requested instances for(const auto& tag : tags() ) { auto ih = event.getValidHandle<ComboHitCollection>(tag); Print(ih); } } } void mu2e::ComboHitPrinter::Print(const art::Handle<ComboHitCollection>& handle, std::ostream& os) { if(verbose()<1) return; // the product tags with all four fields, with underscores std::string tag = handle.provenance()->productDescription().branchName(); tag.pop_back(); // remove trailing dot PrintHeader(tag,os); Print(*handle); } void mu2e::ComboHitPrinter::Print(const art::ValidHandle<ComboHitCollection>& handle, std::ostream& os) { if(verbose()<1) return; // the product tags with all four fields, with underscores std::string tag = handle.provenance()->productDescription().branchName(); tag.pop_back(); // remove trailing dot PrintHeader(tag,os); Print(*handle); } void mu2e::ComboHitPrinter::Print(const ComboHitCollection& coll, std::ostream& os) { if(verbose()<1) return; os << "ComboHitCollection has " << coll.size() << " hits\n"; if(verbose()==1) PrintListHeader(); int i = 0; for(const auto& obj: coll) Print(obj, i++); } void mu2e::ComboHitPrinter::Print(const art::Ptr<ComboHit>& obj, int ind, std::ostream& os) { if(verbose()<1) return; Print(*obj,ind); } void mu2e::ComboHitPrinter::Print(const mu2e::ComboHit& obj, int ind, std::ostream& os) { if(verbose()<1) return; os << std::setiosflags(std::ios::fixed | std::ios::right); if(ind>=0) os << std::setw(4) << ind; if(verbose()==1) { os << " " << std::setw(5) << obj.nCombo() << " " << std::setw(5) << obj.nStrawHits() << " " << " " << std::setw(8) << std::setprecision(3) << obj.pos().x() << " " << std::setw(8) << std::setprecision(3) << obj.pos().y() << " " << std::setw(9) << std::setprecision(3) << obj.pos().z() << " " << std::setw(7) << std::setprecision(1) << obj.time() << " " << std::setw(8) << std::setprecision(5) << obj.energyDep() << " " << std::setw(8) << std::setprecision(4) << obj.qual() << std::endl; } else if(verbose()==2) { os << " StrawId: " << std::setw(5) << obj.strawId().asUint16() << " StrawHitFlag: "; for(auto sn: obj.flag().bitNames()) { if(obj.flag().hasAnyProperty(StrawHitFlag(sn.first))) os << " " << sn.first; } os << "\n"; os << " nCombo: " << std::setw(2) << obj.nCombo() << " nStraw: " << std::setw(2) << obj.nStrawHits() << " time: " << std::setw(7) << std::setprecision(1) << obj.time() << " E: " << std::setw(8) << std::setprecision(5) << obj.energyDep() << " qual: " << std::setw(7) << std::setprecision(4) << obj.qual() << std::endl; os << " wireRes: " << std::setw(8) << std::setprecision(3) << obj.wireRes() << " transRes: " << std::setw(8) << std::setprecision(3) << obj.transRes() << " wireDist: " << std::setw(8) << std::setprecision(3) << obj.wireDist() << "\n"; os << " pos: " << std::setw(8) << std::setprecision(3) << obj.pos().x() << " " << std::setw(8) << std::setprecision(3) << obj.pos().y() << " " << std::setw(9) << std::setprecision(3) << obj.pos().z() << " dir: " << std::setw(8) << std::setprecision(3) << obj.wdir().x() << " " << std::setw(8) << std::setprecision(3) << obj.wdir().y() << " " << std::setw(9) << std::setprecision(3) << obj.wdir().z() << "\n"; os << " indexArray:"; for(auto ii: obj.indexArray()) os << " " << ii; os << std::endl; } } void mu2e::ComboHitPrinter::PrintHeader(const std::string& tag, std::ostream& os) { if(verbose()<1) return; os << "\nProductPrint " << tag << "\n"; } void mu2e::ComboHitPrinter::PrintListHeader(std::ostream& os) { if(verbose()<1) return; os << "ind nCombo nStraw x y z t E qual\n"; }
33.48855
93
0.562115
resnegfk
29bc4030b814e84e526e18ca38935cd597eb4f17
5,758
cpp
C++
dbms/src/Processors/Transforms/CreatingSetsTransform.cpp
enriqueChen/ClickHouse
aef0e2c0a387e26645fca340e6ec7fc332562149
[ "Apache-2.0" ]
null
null
null
dbms/src/Processors/Transforms/CreatingSetsTransform.cpp
enriqueChen/ClickHouse
aef0e2c0a387e26645fca340e6ec7fc332562149
[ "Apache-2.0" ]
null
null
null
dbms/src/Processors/Transforms/CreatingSetsTransform.cpp
enriqueChen/ClickHouse
aef0e2c0a387e26645fca340e6ec7fc332562149
[ "Apache-2.0" ]
1
2020-05-22T18:44:44.000Z
2020-05-22T18:44:44.000Z
#include <Processors/Transforms/CreatingSetsTransform.h> #include <DataStreams/BlockStreamProfileInfo.h> #include <DataStreams/IBlockInputStream.h> #include <DataStreams/IBlockOutputStream.h> #include <Interpreters/Set.h> #include <Interpreters/Join.h> #include <Storages/IStorage.h> #include <iomanip> #include <DataStreams/materializeBlock.h> namespace DB { namespace ErrorCodes { extern const int SET_SIZE_LIMIT_EXCEEDED; } CreatingSetsTransform::CreatingSetsTransform( Block out_header, const SubqueriesForSets & subqueries_for_sets_, const SizeLimits & network_transfer_limits, const Context & context) : IProcessor({}, {std::move(out_header)}) , subqueries_for_sets(subqueries_for_sets_) , cur_subquery(subqueries_for_sets.begin()) , network_transfer_limits(network_transfer_limits) , context(context) { } IProcessor::Status CreatingSetsTransform::prepare() { auto & output = outputs.front(); if (finished) { output.finish(); return Status::Finished; } /// Check can output. if (output.isFinished()) return Status::Finished; if (!output.canPush()) return Status::PortFull; return Status::Ready; } void CreatingSetsTransform::startSubquery(SubqueryForSet & subquery) { LOG_TRACE(log, (subquery.set ? "Creating set. " : "") << (subquery.join ? "Creating join. " : "") << (subquery.table ? "Filling temporary table. " : "")); elapsed_nanoseconds = 0; if (subquery.table) table_out = subquery.table->write({}, context); done_with_set = !subquery.set; done_with_join = !subquery.join; done_with_table = !subquery.table; if (done_with_set && done_with_join && done_with_table) throw Exception("Logical error: nothing to do with subquery", ErrorCodes::LOGICAL_ERROR); if (table_out) table_out->writePrefix(); } void CreatingSetsTransform::finishSubquery(SubqueryForSet & subquery) { size_t head_rows = 0; const BlockStreamProfileInfo & profile_info = subquery.source->getProfileInfo(); head_rows = profile_info.rows; if (subquery.join) subquery.join->setTotals(subquery.source->getTotals()); if (head_rows != 0) { std::stringstream msg; msg << std::fixed << std::setprecision(3); msg << "Created. "; if (subquery.set) msg << "Set with " << subquery.set->getTotalRowCount() << " entries from " << head_rows << " rows. "; if (subquery.join) msg << "Join with " << subquery.join->getTotalRowCount() << " entries from " << head_rows << " rows. "; if (subquery.table) msg << "Table with " << head_rows << " rows. "; msg << "In " << (static_cast<double>(elapsed_nanoseconds) / 1000000000ULL) << " sec."; LOG_DEBUG(log, msg.rdbuf()); } else { LOG_DEBUG(log, "Subquery has empty result."); } } void CreatingSetsTransform::init() { is_initialized = true; for (auto & elem : subqueries_for_sets) if (elem.second.source && elem.second.set) elem.second.set->setHeader(elem.second.source->getHeader()); } void CreatingSetsTransform::work() { if (!is_initialized) init(); Stopwatch watch; while (cur_subquery != subqueries_for_sets.end() && cur_subquery->second.source == nullptr) ++cur_subquery; if (cur_subquery == subqueries_for_sets.end()) { finished = true; return; } SubqueryForSet & subquery = cur_subquery->second; if (!started_cur_subquery) { startSubquery(subquery); started_cur_subquery = true; } auto finishCurrentSubquery = [&]() { if (table_out) table_out->writeSuffix(); watch.stop(); elapsed_nanoseconds += watch.elapsedNanoseconds(); finishSubquery(subquery); ++cur_subquery; started_cur_subquery = false; while (cur_subquery != subqueries_for_sets.end() && cur_subquery->second.source == nullptr) ++cur_subquery; if (cur_subquery == subqueries_for_sets.end()) finished = true; }; auto block = subquery.source->read(); if (!block) { finishCurrentSubquery(); return; } if (!done_with_set) { if (!subquery.set->insertFromBlock(block)) done_with_set = true; } if (!done_with_join) { subquery.renameColumns(block); if (subquery.joined_block_actions) subquery.joined_block_actions->execute(block); if (!subquery.join->insertFromBlock(block)) done_with_join = true; } if (!done_with_table) { block = materializeBlock(block); table_out->write(block); rows_to_transfer += block.rows(); bytes_to_transfer += block.bytes(); if (!network_transfer_limits.check(rows_to_transfer, bytes_to_transfer, "IN/JOIN external table", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED)) done_with_table = true; } if (done_with_set && done_with_join && done_with_table) { subquery.source->cancel(false); finishCurrentSubquery(); } else elapsed_nanoseconds += watch.elapsedNanoseconds(); } void CreatingSetsTransform::setProgressCallback(const ProgressCallback & callback) { for (auto & elem : subqueries_for_sets) if (elem.second.source) elem.second.source->setProgressCallback(callback); } void CreatingSetsTransform::setProcessListElement(QueryStatus * status) { for (auto & elem : subqueries_for_sets) if (elem.second.source) elem.second.source->setProcessListElement(status); } }
25.705357
115
0.638242
enriqueChen
29bd3599ae02f304974873a076b7847649ed25cf
531
cpp
C++
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/32.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
3
2019-10-28T01:12:46.000Z
2021-10-16T09:16:31.000Z
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/32.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
null
null
null
Chapter-6-Functions/Review Questions and Exercises/Algorithm Workbench/32.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
4
2020-04-10T17:22:17.000Z
2021-11-04T14:34:00.000Z
/******************************************************************** * * 32. Examine the following function header, then write an example * call to the function. * * void showValue(int quantity) * * Jesus Hilario Hernandez * December 3, 2018 * ********************************************************************/ #include <iostream> using namespace std; void showValue(int quantity) { cout << "The value is " << quantity << endl; } int main() { showValue(7); // <-- Answer Here! return 0; }
20.423077
69
0.45951
jesushilarioh
29c14e372539127879b1434f8bbd0de7ed4eef35
3,286
hpp
C++
include/cx/utility.hpp
zemasoft/wildcards
5662507f01f5d0a4ec22f45749214276ed366d1b
[ "BSL-1.0" ]
39
2018-04-17T08:25:12.000Z
2022-03-08T17:15:50.000Z
3rd/wildcards/include/cx/utility.hpp
CppCXY/EmmyLuaCodeStyle
ffd2205f59893e12ad07dc151edce26d1c599065
[ "MIT" ]
30
2022-01-28T06:03:31.000Z
2022-03-26T04:33:44.000Z
include/cx/utility.hpp
zemasoft/wildcards
5662507f01f5d0a4ec22f45749214276ed366d1b
[ "BSL-1.0" ]
4
2019-10-29T23:29:39.000Z
2021-02-06T10:52:13.000Z
// Copyright Tomas Zeman 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef CX_UTILITY_HPP #define CX_UTILITY_HPP #include <cstddef> // std::size_t #include <type_traits> // std::integral_constant #include <utility> // std::forward, std::move namespace cx { template <typename First, typename Second> struct pair { using first_type = First; using second_type = Second; constexpr pair() = default; constexpr pair(First frst, Second scnd) : first{std::move(frst)}, second{std::move(scnd)} { } First first; Second second; }; template <typename First, typename Second> constexpr bool operator==(const pair<First, Second>& lhs, const pair<First, Second>& rhs) { return lhs.first == rhs.first && lhs.second == rhs.second; } template <typename First, typename Second> constexpr bool operator!=(const pair<First, Second>& lhs, const pair<First, Second>& rhs) { return !(lhs == rhs); } template <typename First, typename Second> constexpr pair<First, Second> make_pair(First&& first, Second&& second) { return {std::forward<First>(first), std::forward<Second>(second)}; } template <typename T> struct tuple_size; template <typename First, typename Second> struct tuple_size<pair<First, Second>> : std::integral_constant<std::size_t, 2> { }; template <typename First, typename Second> struct tuple_size<const pair<First, Second>> : std::integral_constant<std::size_t, tuple_size<pair<First, Second>>::value> { }; template <std::size_t Index, typename T> struct tuple_element; template <typename First, typename Second> struct tuple_element<0, pair<First, Second>> { using type = First; constexpr static const First& get(const pair<First, Second>& p) { return p.first; } constexpr static First& get(pair<First, Second>& p) { return p.first; } }; template <typename First, typename Second> struct tuple_element<1, pair<First, Second>> { using type = Second; constexpr static const Second& get(const pair<First, Second>& p) { return p.second; } constexpr static Second& get(pair<First, Second>& p) { return p.second; } }; template <std::size_t Index, typename T> using tuple_element_t = typename tuple_element<Index, T>::type; template <std::size_t Index, typename First, typename Second> constexpr const tuple_element_t<Index, pair<First, Second>>& get(const pair<First, Second>& p) { return tuple_element<Index, pair<First, Second>>::get(p); } template <std::size_t Index, typename First, typename Second> constexpr tuple_element_t<Index, pair<First, Second>>& get(pair<First, Second>& p) { return tuple_element<Index, pair<First, Second>>::get(p); } template <typename First, typename Second> constexpr const First& get(const pair<First, Second>& p) { return p.first; } template <typename First, typename Second> constexpr First& get(pair<First, Second>& p) { return p.first; } template <typename Second, typename First> constexpr const Second& get(const pair<First, Second>& p) { return p.second; } template <typename Second, typename First> constexpr Second& get(pair<First, Second>& p) { return p.second; } } // namespace cx #endif // CX_UTILITY_HPP
23.304965
94
0.716372
zemasoft
29c2b3ed50987ca7dd32892994185b58281efd5e
4,888
cpp
C++
src/qt/ballotballotwindow.cpp
truthcoin/truthcoin-cpp
a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529
[ "MIT" ]
34
2015-06-23T16:06:35.000Z
2021-04-02T20:34:11.000Z
src/qt/ballotballotwindow.cpp
truthcoin/truthcoin-cpp
a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529
[ "MIT" ]
2
2016-05-13T15:21:08.000Z
2016-05-15T17:43:24.000Z
src/qt/ballotballotwindow.cpp
truthcoin/truthcoin-cpp
a85161e8a2bbb6bc4d0a5553403f0b8b1f9ac529
[ "MIT" ]
6
2015-06-23T18:12:18.000Z
2015-09-16T13:45:35.000Z
// Copyright (c) 2015 The Truthcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include <QClipboard> #include <QGridLayout> #include <QHBoxLayout> #include <QItemSelection> #include <QItemSelectionModel> #include <QKeyEvent> #include <QLabel> #include <QLineEdit> #include <QScrollBar> #include <QTableView> #include <QVBoxLayout> #include "ballotballotfilterproxymodel.h" #include "ballotballottablemodel.h" #include "ballotballotwindow.h" #include "ballotview.h" #include "primitives/market.h" #include "walletmodel.h" BallotBallotWindow::BallotBallotWindow(QWidget *parent) : ballotView((BallotView *)parent), tableModel(0), tableView(0), proxyModel(0) { setWindowTitle(tr("Ballots")); setMinimumSize(800,200); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0,0,0,0); vlayout->setSpacing(0); QGridLayout *glayout = new QGridLayout(); glayout->setHorizontalSpacing(0); glayout->setVerticalSpacing(0); vlayout->addLayout(glayout); tableView = new QTableView(); tableView->installEventFilter(this); tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); tableView->setTabKeyNavigation(false); tableView->setContextMenuPolicy(Qt::CustomContextMenu); tableView->setAlternatingRowColors(true); vlayout->addWidget(tableView); } void BallotBallotWindow::setModel(WalletModel *model) { if (!model) return; tableModel = model->getBallotBallotTableModel(); if (!tableModel) return; proxyModel = new BallotBallotFilterProxyModel(this); proxyModel->setSourceModel(tableModel); tableView->setModel(proxyModel); tableView->setAlternatingRowColors(true); tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); tableView->setSortingEnabled(true); tableView->sortByColumn(BallotBallotTableModel::Height, Qt::AscendingOrder); tableView->verticalHeader()->hide(); tableView->setColumnWidth(BallotBallotTableModel::Height, HEIGHT_COLUMN_WIDTH); tableView->setColumnWidth(BallotBallotTableModel::nDecisions, NDECISIONS_COLUMN_WIDTH); connect(tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(currentRowChanged(QModelIndex, QModelIndex))); } void BallotBallotWindow::onBranchChange(const marketBranch *branch) { if (!tableModel) return; tableModel->onBranchChange(branch); if (proxyModel->rowCount(QModelIndex())) { QModelIndex topLeft = proxyModel->index(0, 0, QModelIndex()); int columnCount = proxyModel->columnCount(QModelIndex()); if (columnCount > 0) { QModelIndex topRight = proxyModel->index(0, columnCount-1, QModelIndex()); QItemSelection selection(topLeft, topRight); tableView->selectionModel()->select(selection, QItemSelectionModel::Select); } tableView->setFocus(); currentRowChanged(topLeft, topLeft); } else { ballotView->onBallotChange((unsigned int)-1); } } bool BallotBallotWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == tableView) { if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if ((ke->key() == Qt::Key_C) && (ke->modifiers().testFlag(Qt::ControlModifier))) { /* Ctrl-C: copy the selected cells in TableModel */ QString selected_text; QItemSelectionModel *selection = tableView->selectionModel(); QModelIndexList indexes = selection->selectedIndexes(); int prev_row = -1; for(int i=0; i < indexes.size(); i++) { QModelIndex index = indexes.at(i); if (i) { char c = (index.row() != prev_row)? '\n': '\t'; selected_text.append(c); } QVariant data = tableView->model()->data(index); selected_text.append( data.toString() ); prev_row = index.row(); } QApplication::clipboard()->setText(selected_text); return true; } } } return QDialog::eventFilter(obj, event); } void BallotBallotWindow::currentRowChanged(const QModelIndex &curr, const QModelIndex &prev) { if (!tableModel || !tableView || !proxyModel || !curr.isValid()) return; int row = proxyModel->mapToSource(curr).row(); const marketPair *pair = tableModel->index(row); if (pair) ballotView->onBallotChange(pair->Height); }
33.251701
92
0.656097
truthcoin
29c386d0f424391b4d1ca8712f8d9f10da0f6462
421
cpp
C++
codeforces/450A.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
codeforces/450A.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
codeforces/450A.cpp
NafiAsib/competitive-programming
3255b2fe3329543baf9e720e1ccaf08466d77303
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n, m, num, hi = 0, index = 0, i, calc; cin>>n>>m; for(i = 1; i <= n; i++) { cin>>num; calc = (num/m); if(m*calc != num) calc += 1; //i/nt temp = (num%m)>0; //cout<<temp<<endl; if(calc >= hi) { hi = calc; index = i; } } cout<<index<<endl; return 0; }
16.84
46
0.39905
NafiAsib
29c41843d1fe27d9fde81c980b816c2ccad90b84
25,635
cc
C++
src/core/ext/filters/http/client/http_client_filter.cc
swami-raj/grpc
d3ed278a3710efa557c52d22468d5dfc32a07ac0
[ "Apache-2.0" ]
null
null
null
src/core/ext/filters/http/client/http_client_filter.cc
swami-raj/grpc
d3ed278a3710efa557c52d22468d5dfc32a07ac0
[ "Apache-2.0" ]
null
null
null
src/core/ext/filters/http/client/http_client_filter.cc
swami-raj/grpc
d3ed278a3710efa557c52d22468d5dfc32a07ac0
[ "Apache-2.0" ]
1
2021-10-15T19:31:46.000Z
2021-10-15T19:31:46.000Z
/* * Copyright 2015 gRPC authors. * * 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/http/client/http_client_filter.h" #include <stdint.h> #include <string.h> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/slice/b64.h" #include "src/core/lib/slice/percent_encoding.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/transport/static_metadata.h" #include "src/core/lib/transport/status_conversion.h" #include "src/core/lib/transport/transport_impl.h" #define EXPECTED_CONTENT_TYPE "application/grpc" #define EXPECTED_CONTENT_TYPE_LENGTH (sizeof(EXPECTED_CONTENT_TYPE) - 1) /* default maximum size of payload eligible for GET request */ static constexpr size_t kMaxPayloadSizeForGet = 2048; static void recv_initial_metadata_ready(void* user_data, grpc_error_handle error); static void recv_trailing_metadata_ready(void* user_data, grpc_error_handle error); static void on_send_message_next_done(void* arg, grpc_error_handle error); static void send_message_on_complete(void* arg, grpc_error_handle error); namespace { struct call_data { call_data(grpc_call_element* elem, const grpc_call_element_args& args) : call_combiner(args.call_combiner) { GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, ::recv_initial_metadata_ready, elem, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, ::recv_trailing_metadata_ready, elem, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&on_send_message_next_done, ::on_send_message_next_done, elem, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&send_message_on_complete, ::send_message_on_complete, elem, grpc_schedule_on_exec_ctx); } ~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); } grpc_core::CallCombiner* call_combiner; // State for handling send_initial_metadata ops. grpc_linked_mdelem method; grpc_linked_mdelem scheme; grpc_linked_mdelem te_trailers; grpc_linked_mdelem content_type; grpc_linked_mdelem user_agent; // State for handling recv_initial_metadata ops. grpc_metadata_batch* recv_initial_metadata; grpc_error_handle recv_initial_metadata_error = GRPC_ERROR_NONE; grpc_closure* original_recv_initial_metadata_ready = nullptr; grpc_closure recv_initial_metadata_ready; // State for handling recv_trailing_metadata ops. grpc_metadata_batch* recv_trailing_metadata; grpc_closure* original_recv_trailing_metadata_ready; grpc_closure recv_trailing_metadata_ready; grpc_error_handle recv_trailing_metadata_error = GRPC_ERROR_NONE; bool seen_recv_trailing_metadata_ready = false; // State for handling send_message ops. grpc_transport_stream_op_batch* send_message_batch; size_t send_message_bytes_read = 0; grpc_core::ManualConstructor<grpc_core::ByteStreamCache> send_message_cache; grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream> send_message_caching_stream; grpc_closure on_send_message_next_done; grpc_closure* original_send_message_on_complete; grpc_closure send_message_on_complete; }; struct channel_data { grpc_mdelem static_scheme; grpc_mdelem user_agent; size_t max_payload_size_for_get; }; } // namespace static grpc_error_handle client_filter_incoming_metadata( grpc_metadata_batch* b) { if (b->legacy_index()->named.status != nullptr) { /* If both gRPC status and HTTP status are provided in the response, we * should prefer the gRPC status code, as mentioned in * https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md. */ if (b->legacy_index()->named.grpc_status != nullptr || grpc_mdelem_static_value_eq(b->legacy_index()->named.status->md, GRPC_MDELEM_STATUS_200)) { b->Remove(GRPC_BATCH_STATUS); } else { char* val = grpc_dump_slice( GRPC_MDVALUE(b->legacy_index()->named.status->md), GPR_DUMP_ASCII); std::string msg = absl::StrCat("Received http2 header with status: ", val); grpc_error_handle e = grpc_error_set_str( grpc_error_set_int( grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Received http2 :status header with non-200 OK status"), GRPC_ERROR_STR_VALUE, grpc_slice_from_copied_string(val)), GRPC_ERROR_INT_GRPC_STATUS, grpc_http2_status_to_grpc_status(atoi(val))), GRPC_ERROR_STR_GRPC_MESSAGE, grpc_slice_from_cpp_string(std::move(msg))); gpr_free(val); return e; } } if (b->legacy_index()->named.grpc_message != nullptr) { grpc_slice pct_decoded_msg = grpc_core::PermissivePercentDecodeSlice( GRPC_MDVALUE(b->legacy_index()->named.grpc_message->md)); if (grpc_slice_is_equivalent( pct_decoded_msg, GRPC_MDVALUE(b->legacy_index()->named.grpc_message->md))) { grpc_slice_unref_internal(pct_decoded_msg); } else { grpc_metadata_batch_set_value(b->legacy_index()->named.grpc_message, pct_decoded_msg); } } if (b->legacy_index()->named.content_type != nullptr) { if (!grpc_mdelem_static_value_eq( b->legacy_index()->named.content_type->md, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) { if (grpc_slice_buf_start_eq( GRPC_MDVALUE(b->legacy_index()->named.content_type->md), EXPECTED_CONTENT_TYPE, EXPECTED_CONTENT_TYPE_LENGTH) && (GRPC_SLICE_START_PTR(GRPC_MDVALUE( b->legacy_index() ->named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] == '+' || GRPC_SLICE_START_PTR(GRPC_MDVALUE( b->legacy_index() ->named.content_type->md))[EXPECTED_CONTENT_TYPE_LENGTH] == ';')) { /* Although the C implementation doesn't (currently) generate them, any custom +-suffix is explicitly valid. */ /* TODO(klempner): We should consider preallocating common values such as +proto or +json, or at least stashing them if we see them. */ /* TODO(klempner): Should we be surfacing this to application code? */ } else { /* TODO(klempner): We're currently allowing this, but we shouldn't see it without a proxy so log for now. */ char* val = grpc_dump_slice( GRPC_MDVALUE(b->legacy_index()->named.content_type->md), GPR_DUMP_ASCII); gpr_log(GPR_INFO, "Unexpected content-type '%s'", val); gpr_free(val); } } b->Remove(GRPC_BATCH_CONTENT_TYPE); } return GRPC_ERROR_NONE; } static void recv_initial_metadata_ready(void* user_data, grpc_error_handle error) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(calld->recv_initial_metadata); calld->recv_initial_metadata_error = GRPC_ERROR_REF(error); } else { GRPC_ERROR_REF(error); } grpc_closure* closure = calld->original_recv_initial_metadata_ready; calld->original_recv_initial_metadata_ready = nullptr; if (calld->seen_recv_trailing_metadata_ready) { GRPC_CALL_COMBINER_START( calld->call_combiner, &calld->recv_trailing_metadata_ready, calld->recv_trailing_metadata_error, "continue recv_trailing_metadata"); } grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } static void recv_trailing_metadata_ready(void* user_data, grpc_error_handle error) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); if (calld->original_recv_initial_metadata_ready != nullptr) { calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error); calld->seen_recv_trailing_metadata_ready = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner, "deferring recv_trailing_metadata_ready until " "after recv_initial_metadata_ready"); return; } if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(calld->recv_trailing_metadata); } else { GRPC_ERROR_REF(error); } error = grpc_error_add_child( error, GRPC_ERROR_REF(calld->recv_initial_metadata_error)); grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready, error); } static void send_message_on_complete(void* arg, grpc_error_handle error) { grpc_call_element* elem = static_cast<grpc_call_element*>(arg); call_data* calld = static_cast<call_data*>(elem->call_data); calld->send_message_cache.Destroy(); // Set the batch's send_message bit back to true, so the retry code // above knows what was in this batch. calld->send_message_batch->send_message = true; grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_send_message_on_complete, GRPC_ERROR_REF(error)); } // Pulls a slice from the send_message byte stream, updating // calld->send_message_bytes_read. static grpc_error_handle pull_slice_from_send_message(call_data* calld) { grpc_slice incoming_slice; grpc_error_handle error = calld->send_message_caching_stream->Pull(&incoming_slice); if (error == GRPC_ERROR_NONE) { calld->send_message_bytes_read += GRPC_SLICE_LENGTH(incoming_slice); grpc_slice_unref_internal(incoming_slice); } return error; } // Reads as many slices as possible from the send_message byte stream. // Upon successful return, if calld->send_message_bytes_read == // calld->send_message_caching_stream->length(), then we have completed // reading from the byte stream; otherwise, an async read has been dispatched // and on_send_message_next_done() will be invoked when it is complete. static grpc_error_handle read_all_available_send_message_data( call_data* calld) { while (calld->send_message_caching_stream->Next( SIZE_MAX, &calld->on_send_message_next_done)) { grpc_error_handle error = pull_slice_from_send_message(calld); if (error != GRPC_ERROR_NONE) return error; if (calld->send_message_bytes_read == calld->send_message_caching_stream->length()) { break; } } return GRPC_ERROR_NONE; } // Async callback for ByteStream::Next(). static void on_send_message_next_done(void* arg, grpc_error_handle error) { grpc_call_element* elem = static_cast<grpc_call_element*>(arg); call_data* calld = static_cast<call_data*>(elem->call_data); if (error != GRPC_ERROR_NONE) { grpc_transport_stream_op_batch_finish_with_failure( calld->send_message_batch, error, calld->call_combiner); return; } error = pull_slice_from_send_message(calld); if (error != GRPC_ERROR_NONE) { grpc_transport_stream_op_batch_finish_with_failure( calld->send_message_batch, error, calld->call_combiner); return; } // There may or may not be more to read, but we don't care. If we got // here, then we know that all of the data was not available // synchronously, so we were not able to do a cached call. Instead, // we just reset the byte stream and then send down the batch as-is. calld->send_message_caching_stream->Reset(); grpc_call_next_op(elem, calld->send_message_batch); } static char* slice_buffer_to_string(grpc_slice_buffer* slice_buffer) { char* payload_bytes = static_cast<char*>(gpr_malloc(slice_buffer->length + 1)); size_t offset = 0; for (size_t i = 0; i < slice_buffer->count; ++i) { memcpy(payload_bytes + offset, GRPC_SLICE_START_PTR(slice_buffer->slices[i]), GRPC_SLICE_LENGTH(slice_buffer->slices[i])); offset += GRPC_SLICE_LENGTH(slice_buffer->slices[i]); } *(payload_bytes + offset) = '\0'; return payload_bytes; } // Modifies the path entry in the batch's send_initial_metadata to // append the base64-encoded query for a GET request. static grpc_error_handle update_path_for_get( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { call_data* calld = static_cast<call_data*>(elem->call_data); grpc_slice path_slice = GRPC_MDVALUE(batch->payload->send_initial_metadata.send_initial_metadata ->legacy_index() ->named.path->md); /* sum up individual component's lengths and allocate enough memory to * hold combined path+query */ size_t estimated_len = GRPC_SLICE_LENGTH(path_slice); estimated_len++; /* for the '?' */ estimated_len += grpc_base64_estimate_encoded_size( batch->payload->send_message.send_message->length(), false /* multi_line */); grpc_core::UnmanagedMemorySlice path_with_query_slice(estimated_len); /* memcopy individual pieces into this slice */ char* write_ptr = reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice); char* original_path = reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_slice); memcpy(write_ptr, original_path, GRPC_SLICE_LENGTH(path_slice)); write_ptr += GRPC_SLICE_LENGTH(path_slice); *write_ptr++ = '?'; char* payload_bytes = slice_buffer_to_string(calld->send_message_cache->cache_buffer()); grpc_base64_encode_core(write_ptr, payload_bytes, batch->payload->send_message.send_message->length(), true /* url_safe */, false /* multi_line */); gpr_free(payload_bytes); /* remove trailing unused memory and add trailing 0 to terminate string */ char* t = reinterpret_cast<char*> GRPC_SLICE_START_PTR(path_with_query_slice); /* safe to use strlen since base64_encode will always add '\0' */ path_with_query_slice = grpc_slice_sub_no_ref(path_with_query_slice, 0, strlen(t)); /* substitute previous path with the new path+query */ grpc_mdelem mdelem_path_and_query = grpc_mdelem_from_slices(GRPC_MDSTR_PATH, path_with_query_slice); grpc_metadata_batch* b = batch->payload->send_initial_metadata.send_initial_metadata; return b->Substitute(b->legacy_index()->named.path, mdelem_path_and_query); } static void remove_if_present(grpc_metadata_batch* batch, grpc_metadata_batch_callouts_index idx) { batch->Remove(idx); } static void http_client_start_transport_stream_op_batch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { call_data* calld = static_cast<call_data*>(elem->call_data); channel_data* channeld = static_cast<channel_data*>(elem->channel_data); GPR_TIMER_SCOPE("http_client_start_transport_stream_op_batch", 0); if (batch->recv_initial_metadata) { /* substitute our callback for the higher callback */ calld->recv_initial_metadata = batch->payload->recv_initial_metadata.recv_initial_metadata; calld->original_recv_initial_metadata_ready = batch->payload->recv_initial_metadata.recv_initial_metadata_ready; batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &calld->recv_initial_metadata_ready; } if (batch->recv_trailing_metadata) { /* substitute our callback for the higher callback */ calld->recv_trailing_metadata = batch->payload->recv_trailing_metadata.recv_trailing_metadata; calld->original_recv_trailing_metadata_ready = batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &calld->recv_trailing_metadata_ready; } grpc_error_handle error = GRPC_ERROR_NONE; bool batch_will_be_handled_asynchronously = false; if (batch->send_initial_metadata) { // Decide which HTTP VERB to use. We use GET if the request is marked // cacheable, and the operation contains both initial metadata and send // message, and the payload is below the size threshold, and all the data // for this request is immediately available. grpc_mdelem method = GRPC_MDELEM_METHOD_POST; if (batch->send_message && (batch->payload->send_initial_metadata.send_initial_metadata_flags & GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) && batch->payload->send_message.send_message->length() < channeld->max_payload_size_for_get) { calld->send_message_bytes_read = 0; calld->send_message_cache.Init( std::move(batch->payload->send_message.send_message)); calld->send_message_caching_stream.Init(calld->send_message_cache.get()); batch->payload->send_message.send_message.reset( calld->send_message_caching_stream.get()); calld->original_send_message_on_complete = batch->on_complete; batch->on_complete = &calld->send_message_on_complete; calld->send_message_batch = batch; error = read_all_available_send_message_data(calld); if (error != GRPC_ERROR_NONE) goto done; // If all the data has been read, then we can use GET. if (calld->send_message_bytes_read == calld->send_message_caching_stream->length()) { method = GRPC_MDELEM_METHOD_GET; error = update_path_for_get(elem, batch); if (error != GRPC_ERROR_NONE) goto done; batch->send_message = false; calld->send_message_caching_stream->Orphan(); } else { // Not all data is available. The batch will be sent down // asynchronously in on_send_message_next_done(). batch_will_be_handled_asynchronously = true; // Fall back to POST. gpr_log(GPR_DEBUG, "Request is marked Cacheable but not all data is available. " "Falling back to POST"); } } else if (batch->payload->send_initial_metadata .send_initial_metadata_flags & GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST) { method = GRPC_MDELEM_METHOD_PUT; } remove_if_present( batch->payload->send_initial_metadata.send_initial_metadata, GRPC_BATCH_METHOD); remove_if_present( batch->payload->send_initial_metadata.send_initial_metadata, GRPC_BATCH_SCHEME); remove_if_present( batch->payload->send_initial_metadata.send_initial_metadata, GRPC_BATCH_TE); remove_if_present( batch->payload->send_initial_metadata.send_initial_metadata, GRPC_BATCH_CONTENT_TYPE); remove_if_present( batch->payload->send_initial_metadata.send_initial_metadata, GRPC_BATCH_USER_AGENT); /* Send : prefixed headers, which have to be before any application layer headers. */ error = grpc_metadata_batch_add_head( batch->payload->send_initial_metadata.send_initial_metadata, &calld->method, method, GRPC_BATCH_METHOD); if (error != GRPC_ERROR_NONE) goto done; error = grpc_metadata_batch_add_head( batch->payload->send_initial_metadata.send_initial_metadata, &calld->scheme, channeld->static_scheme, GRPC_BATCH_SCHEME); if (error != GRPC_ERROR_NONE) goto done; error = grpc_metadata_batch_add_tail( batch->payload->send_initial_metadata.send_initial_metadata, &calld->te_trailers, GRPC_MDELEM_TE_TRAILERS, GRPC_BATCH_TE); if (error != GRPC_ERROR_NONE) goto done; error = grpc_metadata_batch_add_tail( batch->payload->send_initial_metadata.send_initial_metadata, &calld->content_type, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, GRPC_BATCH_CONTENT_TYPE); if (error != GRPC_ERROR_NONE) goto done; error = grpc_metadata_batch_add_tail( batch->payload->send_initial_metadata.send_initial_metadata, &calld->user_agent, GRPC_MDELEM_REF(channeld->user_agent), GRPC_BATCH_USER_AGENT); if (error != GRPC_ERROR_NONE) goto done; } done: if (error != GRPC_ERROR_NONE) { grpc_transport_stream_op_batch_finish_with_failure(batch, error, calld->call_combiner); } else if (!batch_will_be_handled_asynchronously) { grpc_call_next_op(elem, batch); } } /* Constructor for call_data */ static grpc_error_handle http_client_init_call_elem( grpc_call_element* elem, const grpc_call_element_args* args) { new (elem->call_data) call_data(elem, *args); return GRPC_ERROR_NONE; } /* Destructor for call_data */ static void http_client_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { call_data* calld = static_cast<call_data*>(elem->call_data); calld->~call_data(); } static grpc_mdelem scheme_from_args(const grpc_channel_args* args) { unsigned i; size_t j; grpc_mdelem valid_schemes[] = {GRPC_MDELEM_SCHEME_HTTP, GRPC_MDELEM_SCHEME_HTTPS}; if (args != nullptr) { for (i = 0; i < args->num_args; ++i) { if (args->args[i].type == GRPC_ARG_STRING && strcmp(args->args[i].key, GRPC_ARG_HTTP2_SCHEME) == 0) { for (j = 0; j < GPR_ARRAY_SIZE(valid_schemes); j++) { if (0 == grpc_slice_str_cmp(GRPC_MDVALUE(valid_schemes[j]), args->args[i].value.string)) { return valid_schemes[j]; } } } } } return GRPC_MDELEM_SCHEME_HTTP; } static size_t max_payload_size_from_args(const grpc_channel_args* args) { if (args != nullptr) { for (size_t i = 0; i < args->num_args; ++i) { if (0 == strcmp(args->args[i].key, GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET)) { if (args->args[i].type != GRPC_ARG_INTEGER) { gpr_log(GPR_ERROR, "%s: must be an integer", GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET); } else { return static_cast<size_t>(args->args[i].value.integer); } } } } return kMaxPayloadSizeForGet; } static grpc_core::ManagedMemorySlice user_agent_from_args( const grpc_channel_args* args, const char* transport_name) { std::vector<std::string> user_agent_fields; for (size_t i = 0; args && i < args->num_args; i++) { if (0 == strcmp(args->args[i].key, GRPC_ARG_PRIMARY_USER_AGENT_STRING)) { if (args->args[i].type != GRPC_ARG_STRING) { gpr_log(GPR_ERROR, "Channel argument '%s' should be a string", GRPC_ARG_PRIMARY_USER_AGENT_STRING); } else { user_agent_fields.push_back(args->args[i].value.string); } } } user_agent_fields.push_back( absl::StrFormat("grpc-c/%s (%s; %s)", grpc_version_string(), GPR_PLATFORM_STRING, transport_name)); for (size_t i = 0; args && i < args->num_args; i++) { if (0 == strcmp(args->args[i].key, GRPC_ARG_SECONDARY_USER_AGENT_STRING)) { if (args->args[i].type != GRPC_ARG_STRING) { gpr_log(GPR_ERROR, "Channel argument '%s' should be a string", GRPC_ARG_SECONDARY_USER_AGENT_STRING); } else { user_agent_fields.push_back(args->args[i].value.string); } } } std::string user_agent_string = absl::StrJoin(user_agent_fields, " "); return grpc_core::ManagedMemorySlice(user_agent_string.c_str()); } /* Constructor for channel_data */ static grpc_error_handle http_client_init_channel_elem( grpc_channel_element* elem, grpc_channel_element_args* args) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); GPR_ASSERT(!args->is_last); GPR_ASSERT(args->optional_transport != nullptr); chand->static_scheme = scheme_from_args(args->channel_args); chand->max_payload_size_for_get = max_payload_size_from_args(args->channel_args); chand->user_agent = grpc_mdelem_from_slices( GRPC_MDSTR_USER_AGENT, user_agent_from_args(args->channel_args, args->optional_transport->vtable->name)); return GRPC_ERROR_NONE; } /* Destructor for channel data */ static void http_client_destroy_channel_elem(grpc_channel_element* elem) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); GRPC_MDELEM_UNREF(chand->user_agent); } const grpc_channel_filter grpc_http_client_filter = { http_client_start_transport_stream_op_batch, grpc_channel_next_op, sizeof(call_data), http_client_init_call_elem, grpc_call_stack_ignore_set_pollset_or_pollset_set, http_client_destroy_call_elem, sizeof(channel_data), http_client_init_channel_elem, http_client_destroy_channel_elem, grpc_channel_next_get_info, "http-client"};
42.02459
80
0.71024
swami-raj
29c49e2aa28cb26f20e30f4fc1289eeb738ed83a
571
cpp
C++
C++/Polymorphism/Shape.cpp
Allenjonesing/tutorials
c729fdd655130b021ec7ca9b619e147ae636cfa5
[ "MIT" ]
367
2015-01-12T22:43:04.000Z
2022-03-31T02:03:27.000Z
C++/Polymorphism/Shape.cpp
uag515/tutorials
c729fdd655130b021ec7ca9b619e147ae636cfa5
[ "MIT" ]
3
2016-04-17T06:02:01.000Z
2019-01-20T16:07:53.000Z
C++/Polymorphism/Shape.cpp
uag515/tutorials
c729fdd655130b021ec7ca9b619e147ae636cfa5
[ "MIT" ]
212
2015-01-14T14:13:34.000Z
2022-03-04T01:08:41.000Z
#include "Shape.h" // You'll notice the implementation of these classes is just like usual, // no "virtual" keywords or anything like that. // Doesn't do a thing! void CShape::draw() { return; } // The CTriangle draw method draws an ASCII triangle void CTriangle::draw() { cout << " * " << endl; cout << " * * " << endl; cout << "*****" << endl; cout << endl; } // The CSquare draw method draws an ASCII square void CSquare::draw() { cout << "******" << endl; cout << "* *" << endl; cout << "* *" << endl; cout << "******" << endl; cout << endl; }
19.689655
72
0.565674
Allenjonesing
29c4c425d12f80e3b43cedd39e21009bdc4c93c3
2,731
cpp
C++
test/select_if_test.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
24
2015-01-20T16:15:46.000Z
2019-09-16T07:53:54.000Z
test/select_if_test.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
8
2015-01-30T07:27:00.000Z
2017-07-11T21:37:17.000Z
test/select_if_test.cpp
audiohacked/gamgee
772a095c5f0725c410e7c23e88f79d8b76e098a8
[ "MIT" ]
15
2015-01-11T05:28:26.000Z
2022-01-18T08:47:10.000Z
#include <boost/test/unit_test.hpp> #include <boost/dynamic_bitset.hpp> #include "variant/variant_reader.h" #include "variant/variant.h" using namespace std; using namespace gamgee; using namespace boost; constexpr auto GQ_THRESH = 35; BOOST_AUTO_TEST_CASE( select_if_individual_fields ) { const auto actual_gq_selects = vector<dynamic_bitset<>>{ dynamic_bitset<>(string("111")), //Beware that in setting dynamic_bitset that way dynamic_bitset<>(string("110")), //the bit order is inversed: Here it is actually 011 dynamic_bitset<>(string("100")), dynamic_bitset<>(string("010")), dynamic_bitset<>(string("011"))}; const auto actual_pl_selects = vector<dynamic_bitset<>>{ dynamic_bitset<>(string("010")), dynamic_bitset<>(string("000")), dynamic_bitset<>(string("001")), dynamic_bitset<>(string("111")), dynamic_bitset<>(string("100"))}; for (const auto& filename : {"testdata/test_variants_02.vcf"}) { const auto reader = SingleVariantReader{filename}; auto record_idx = 0u; for (const auto& record : SingleVariantReader{filename}) { const auto g_quals = record.integer_individual_field("GQ"); const auto p_likes = record.integer_individual_field("PL"); const auto high_gq = [](const IndividualFieldValue<int32_t>& x) { return x[0] >= GQ_THRESH; }; const auto hom_ref = [](const IndividualFieldValue<int32_t>& x) { return x[0] == 0; }; const auto comput_gq_select = Variant::select_if(g_quals.begin(), g_quals.end(), high_gq); const auto comput_pl_select = Variant::select_if(p_likes.begin(), p_likes.end(), hom_ref); BOOST_CHECK_EQUAL(comput_gq_select.size(), 3u); BOOST_CHECK_EQUAL(comput_pl_select.size(), 3u); const auto actual_gq_select = actual_gq_selects[record_idx]; const auto actual_pl_select = actual_pl_selects[record_idx]; BOOST_CHECK(comput_pl_select == actual_pl_select); ++record_idx; } BOOST_CHECK_EQUAL(record_idx, 5u); } } BOOST_AUTO_TEST_CASE( select_if_shared_field ) { const auto truth_an_counts = std::vector<uint32_t>{1,1,1,1,1,1,1}; const auto truth_af_counts = std::vector<uint32_t>{0,0,0,0,1,0,1}; auto truth_index = 0u; for (const auto& record : SingleVariantReader{"testdata/test_variants.vcf"}) { const auto an = record.integer_shared_field("AN"); const auto r1 = Variant::select_if(an.begin(), an.end(), [](const auto& v) { return v == 6; }); BOOST_CHECK_EQUAL(r1.count(), truth_an_counts[truth_index]); const auto af = record.float_shared_field("AF"); const auto r2 = Variant::select_if(af.begin(), af.end(), [](const auto& v) { return v < 0.5; }); BOOST_CHECK_EQUAL(r2.count(), truth_af_counts[truth_index++]); } }
45.516667
100
0.702307
audiohacked
29c5d7386046e9152e1605bb2875b42d1b8c0b61
20,601
cc
C++
MELA/src/MELANCSpline_3D_fast.cc
mostafa1993/JHUGenMELA
a28f39043d98319f1f27493cf899a13646221eda
[ "Apache-2.0" ]
null
null
null
MELA/src/MELANCSpline_3D_fast.cc
mostafa1993/JHUGenMELA
a28f39043d98319f1f27493cf899a13646221eda
[ "Apache-2.0" ]
8
2020-10-02T20:02:44.000Z
2022-01-19T15:41:05.000Z
MELA/src/MELANCSpline_3D_fast.cc
mostafa1993/JHUGenMELA
a28f39043d98319f1f27493cf899a13646221eda
[ "Apache-2.0" ]
11
2020-10-07T17:15:30.000Z
2022-03-19T10:41:52.000Z
#include "MELANCSpline_3D_fast.h" #include <cmath> #include "TMath.h" #include "Riostream.h" #include "RooAbsReal.h" using namespace TMath; using namespace RooFit; using namespace std; using namespace TNumericUtil; ClassImp(MELANCSpline_3D_fast) MELANCSpline_3D_fast::MELANCSpline_3D_fast() : MELANCSplineCore(), rangeYmin(1), rangeYmax(-1), rangeZmin(1), rangeZmax(-1), bcBeginX(MELANCSplineCore::bcNaturalSpline), bcEndX(MELANCSplineCore::bcNaturalSpline), bcBeginY(MELANCSplineCore::bcNaturalSpline), bcEndY(MELANCSplineCore::bcNaturalSpline), bcBeginZ(MELANCSplineCore::bcNaturalSpline), bcEndZ(MELANCSplineCore::bcNaturalSpline), theYVar("theYVar", "theYVar", this), theZVar("theZVar", "theZVar", this) {} MELANCSpline_3D_fast::MELANCSpline_3D_fast( const char* name, const char* title ) : MELANCSplineCore(name, title), rangeYmin(1), rangeYmax(-1), rangeZmin(1), rangeZmax(-1), bcBeginX(MELANCSplineCore::bcNaturalSpline), bcEndX(MELANCSplineCore::bcNaturalSpline), bcBeginY(MELANCSplineCore::bcNaturalSpline), bcEndY(MELANCSplineCore::bcNaturalSpline), bcBeginZ(MELANCSplineCore::bcNaturalSpline), bcEndZ(MELANCSplineCore::bcNaturalSpline), theYVar("theYVar", "theYVar", this), theZVar("theZVar", "theZVar", this) {} MELANCSpline_3D_fast::MELANCSpline_3D_fast( const char* name, const char* title, RooAbsReal& inXVar, RooAbsReal& inYVar, RooAbsReal& inZVar, const std::vector<T>& inXList, const std::vector<T>& inYList, const std::vector<T>& inZList, const std::vector<std::vector<std::vector<T>>>& inFcnList, MELANCSplineCore::BoundaryCondition const bcBeginX_, MELANCSplineCore::BoundaryCondition const bcEndX_, MELANCSplineCore::BoundaryCondition const bcBeginY_, MELANCSplineCore::BoundaryCondition const bcEndY_, MELANCSplineCore::BoundaryCondition const bcBeginZ_, MELANCSplineCore::BoundaryCondition const bcEndZ_, Bool_t inUseFloor, T inFloorEval, T inFloorInt ) : MELANCSplineCore(name, title, inXVar, inXList, inUseFloor, inFloorEval, inFloorInt), rangeYmin(1), rangeYmax(-1), rangeZmin(1), rangeZmax(-1), bcBeginX(bcBeginX_), bcEndX(bcEndX_), bcBeginY(bcBeginY_), bcEndY(bcEndY_), bcBeginZ(bcBeginZ_), bcEndZ(bcEndZ_), theYVar("theYVar", "theYVar", this, inYVar), theZVar("theZVar", "theZVar", this, inZVar), YList(inYList), ZList(inZList), FcnList(inFcnList) { if (npointsX()>1 && npointsY()>1 && npointsZ()>1){ // Prepare A and kappa arrays for x, y and z coordinates int npoints; Double_t det; vector<vector<MELANCSplineCore::T>> xA; getKappas(kappaX, 0); getAArray(kappaX, xA, bcBeginX, bcEndX); npoints=kappaX.size(); TMatrix_t xAtrans(npoints, npoints); for (int i=0; i<npoints; i++){ for (int j=0; j<npoints; j++){ xAtrans[i][j]=xA.at(i).at(j); } } det=0; TMatrix_t xAinv = xAtrans.Invert(&det); if (det==0.){ coutE(InputArguments) << "MELANCSpline_3D_fast::interpolateFcn: Matrix xA could not be inverted. Something is wrong with the x coordinates of points!" << endl; assert(0); } vector<vector<MELANCSplineCore::T>> yA; getKappas(kappaY, 1); getAArray(kappaY, yA, bcBeginY, bcEndY); npoints=kappaY.size(); TMatrix_t yAtrans(npoints, npoints); for (int i=0; i<npoints; i++){ for (int j=0; j<npoints; j++){ yAtrans[i][j]=yA.at(i).at(j); } } det=0; TMatrix_t yAinv = yAtrans.Invert(&det); if (det==0.){ coutE(InputArguments) << "MELANCSpline_3D_fast::interpolateFcn: Matrix yA could not be inverted. Something is wrong with the y coordinates of points!" << endl; assert(0); } vector<vector<MELANCSplineCore::T>> zA; getKappas(kappaZ, 2); getAArray(kappaZ, zA, bcBeginZ, bcEndZ); npoints=kappaZ.size(); TMatrix_t zAtrans(npoints, npoints); for (int i=0; i<npoints; i++){ for (int j=0; j<npoints; j++){ zAtrans[i][j]=zA.at(i).at(j); } } det=0; TMatrix_t zAinv = zAtrans.Invert(&det); if (det==0.){ coutE(InputArguments) << "MELANCSpline_3D_fast::interpolateFcn: Matrix zA could not be inverted. Something is wrong with the z coordinates of points!" << endl; assert(0); } //cout << "MELANCSpline_3D_fast::MELANCSpline_3D_fast: Initial kappa arrays are set up" << endl; // Get the grid of coefficients int nxpoldim=0; int nxbins=0; int nybins=0; int nypoldim=0; std::vector< std::vector<std::vector< std::vector<std::vector<MELANCSplineCore::T>> >> > coefsAlongZ; // [ix][A_x,B_x,C_x,D_x][iy][A_x_y,B_x_y,C_x_y,D_x_y][z_k] at each z_k for (unsigned int k=0; k<npointsZ(); k++){ //cout << "Finding coefficients along z line " << k << endl; std::vector<std::vector< std::vector<std::vector<MELANCSplineCore::T>> >> coefficients_perZ; // [ix][A_x,B_x,C_x,D_x][iy][A_x_y,B_x_y,C_x_y,D_x_y] at each z_k vector<vector<vector<MELANCSplineCore::T>>> coefsAlongY; // [xbin][Ax(y),Bx(y),Cx(y),Dx(y)][ybin] in each z for (unsigned int j=0; j<npointsY(); j++){ vector<vector<MELANCSplineCore::T>> xcoefsAtYjZk = getCoefficientsPerYPerZ(kappaX, xAinv, j, k, bcBeginX, bcEndX, -1); // [ix][Ax,Bx,Cx,Dx] at each y_j z_k //cout << "\tCoefficients in y line " << j << " are found" << endl; if (j==0){ if (k==0){ nxbins=xcoefsAtYjZk.size(); nxpoldim=xcoefsAtYjZk.at(0).size(); } for (int ix=0; ix<nxbins; ix++){ vector<vector<MELANCSplineCore::T>> dum_xycoefarray; for (int icx=0; icx<nxpoldim; icx++){ vector<MELANCSplineCore::T> dum_ycoefarray; dum_xycoefarray.push_back(dum_ycoefarray); } coefsAlongY.push_back(dum_xycoefarray); } } if (nxbins!=(int)xcoefsAtYjZk.size() || nxpoldim!=(int)xcoefsAtYjZk.at(0).size()){ coutE(InputArguments) << "MELANCSpline_3D_fast::interpolateFcn: nxbins!=(int)xcoefsAtYjZk.size() || nxpoldim!=(int)xcoefsAtYjZk.at(0).size()!" << endl; assert(0); } for (int ix=0; ix<nxbins; ix++){ for (int icx=0; icx<nxpoldim; icx++) coefsAlongY.at(ix).at(icx).push_back(xcoefsAtYjZk.at(ix).at(icx)); } } //cout << "\tCoefficients in each y line are found" << endl; for (int ix=0; ix<nxbins; ix++){ // Get the x coefficients interpolated across y vector<vector<vector<MELANCSplineCore::T>>> xCoefs; for (int icx=0; icx<nxpoldim; icx++){ vector<vector<MELANCSplineCore::T>> yCoefs = getCoefficientsAlongDirection(kappaY, yAinv, coefsAlongY.at(ix).at(icx), bcBeginY, bcEndY, -1); // [iy][A,B,C,D] xCoefs.push_back(yCoefs); } coefficients_perZ.push_back(xCoefs); } if (k==0){ nybins = coefficients_perZ.at(0).at(0).size(); nypoldim = coefficients_perZ.at(0).at(0).at(0).size(); for (int ix=0; ix<nxbins; ix++){ vector<vector<vector<vector<MELANCSplineCore::T>>>> xCoefs; for (int icx=0; icx<nxpoldim; icx++){ vector<vector<vector<MELANCSplineCore::T>>> xCoefsAlongY; for (int iy=0; iy<nybins; iy++){ vector<vector<MELANCSplineCore::T>> yCoefs; for (int icy=0; icy<nypoldim; icy++){ vector<MELANCSplineCore::T> yCoefAtZj; yCoefs.push_back(yCoefAtZj); } xCoefsAlongY.push_back(yCoefs); } xCoefs.push_back(xCoefsAlongY); } coefsAlongZ.push_back(xCoefs); } } for (int ix=0; ix<nxbins; ix++){ for (int icx=0; icx<nxpoldim; icx++){ for (int iy=0; iy<nybins; iy++){ for (int icy=0; icy<nypoldim; icy++){ coefsAlongZ.at(ix).at(icx).at(iy).at(icy).push_back(coefficients_perZ.at(ix).at(icx).at(iy).at(icy)); } } } } } //cout << "Finding the final coefficients" << endl; for (int ix=0; ix<nxbins; ix++){ vector<vector<vector<vector<vector<MELANCSplineCore::T>>>>> xCoefs; for (int icx=0; icx<nxpoldim; icx++){ vector<vector<vector<vector<MELANCSplineCore::T>>>> xCoefsAlongY; for (int iy=0; iy<nybins; iy++){ vector<vector<vector<MELANCSplineCore::T>>> yCoefs; for (int icy=0; icy<nypoldim; icy++){ vector<vector<MELANCSplineCore::T>> yCoefsAlongZ = getCoefficientsAlongDirection(kappaZ, zAinv, coefsAlongZ.at(ix).at(icx).at(iy).at(icy), bcBeginZ, bcEndZ, -1); // [iz][A,B,C,D] yCoefs.push_back(yCoefsAlongZ); } xCoefsAlongY.push_back(yCoefs); } xCoefs.push_back(xCoefsAlongY); } coefficients.push_back(xCoefs); } } else assert(0); RooArgSet leafset; getLeafDependents(theXVar, leafset); getLeafDependents(theYVar, leafset); getLeafDependents(theZVar, leafset); addLeafDependents(leafset); emptyFcnList(); } MELANCSpline_3D_fast::MELANCSpline_3D_fast( const MELANCSpline_3D_fast& other, const char* name ) : MELANCSplineCore(other, name), rangeYmin(other.rangeYmin), rangeYmax(other.rangeYmax), rangeZmin(other.rangeZmin), rangeZmax(other.rangeZmax), bcBeginX(other.bcBeginX), bcEndX(other.bcEndX), bcBeginY(other.bcBeginY), bcEndY(other.bcEndY), bcBeginZ(other.bcBeginZ), bcEndZ(other.bcEndZ), theYVar("theYVar", this, other.theYVar), theZVar("theZVar", this, other.theZVar), YList(other.YList), ZList(other.ZList), FcnList(other.FcnList), kappaX(other.kappaX), kappaY(other.kappaY), kappaZ(other.kappaZ), coefficients(other.coefficients) {} MELANCSplineCore::T MELANCSpline_3D_fast::interpolateFcn(Int_t code, const char* rangeName)const{ DefaultAccumulator<MELANCSplineCore::T> res; if (verbosity==MELANCSplineCore::kVerbose) cout << "MELANCSpline_3D_fast(" << GetName() << ")::interpolateFcn begin with code: " << code << endl; // Get bins vector<Int_t> varprime; varprime.push_back(2); varprime.push_back(3); varprime.push_back(5); const Int_t ndims=(const Int_t)varprime.size(); vector<Int_t> varbin; vector<Int_t> varbinmin; vector<Int_t> varbinmax; vector<MELANCSplineCore::T> tvar; vector<MELANCSplineCore::T> tvarmin; vector<MELANCSplineCore::T> tvarmax; vector<const vector<MELANCSplineCore::T>*> varkappa; varkappa.push_back(&kappaX); varkappa.push_back(&kappaY); varkappa.push_back(&kappaZ); vector<const RooRealProxy*> varcoord; varcoord.push_back(&theXVar); varcoord.push_back(&theYVar); varcoord.push_back(&theZVar); for (Int_t idim=0; idim<ndims; idim++){ Int_t binval=-1; Int_t binmin=-1; Int_t binmax=-1; MELANCSplineCore::T tval=0; MELANCSplineCore::T tmin=0; MELANCSplineCore::T tmax=0; if (code==0 || code%varprime.at(idim)!=0){ if (!testRangeValidity(*(varcoord.at(idim)), idim)) return 0; binval = getWhichBin(*(varcoord.at(idim)), idim); tval = getTVar(*(varkappa.at(idim)), *(varcoord.at(idim)), binval, idim); } else{ MELANCSplineCore::T coordmin = varcoord.at(idim)->min(rangeName); cropValueForRange(coordmin, idim); MELANCSplineCore::T coordmax = varcoord.at(idim)->max(rangeName); cropValueForRange(coordmax, idim); const std::vector<MELANCSplineCore::T>& kappadim = *(varkappa.at(idim)); binmin = getWhichBin(coordmin, idim); tmin = getTVar(kappadim, coordmin, binmin, idim); binmax = getWhichBin(coordmax, idim); tmax = getTVar(kappadim, coordmax, binmax, idim); } varbin.push_back(binval); varbinmin.push_back(binmin); varbinmax.push_back(binmax); tvar.push_back(tval); tvarmin.push_back(tmin); tvarmax.push_back(tmax); } for (int ix=0; ix<(int)coefficients.size(); ix++){ if ( (varbin[0]>=0 && ix!=varbin[0]) || (varbinmin[0]>=0 && varbinmax[0]>=varbinmin[0] && !(varbinmin[0]<=ix && ix<=varbinmax[0])) ) continue; MELANCSplineCore::T txlow=0, txhigh=1; if (code>0 && code%varprime[0]==0){ if (ix==varbinmin[0]) txlow=tvarmin[0]; if (ix==varbinmax[0]) txhigh=tvarmax[0]; } else txhigh=tvar[0]; // Get the x coefficients interpolated across y vector<MELANCSplineCore::T> xCoefs; for (int icx=0; icx<(int)coefficients.at(ix).size(); icx++){ DefaultAccumulator<MELANCSplineCore::T> theXCoef; for (int iy=0; iy<(int)coefficients.at(ix).at(icx).size(); iy++){ if ( (varbin[1]>=0 && iy!=varbin[1]) || (varbinmin[1]>=0 && varbinmax[1]>=varbinmin[1] && !(varbinmin[1]<=iy && iy<=varbinmax[1])) ) continue; MELANCSplineCore::T tylow=0, tyhigh=1; if (code>0 && code%varprime[1]==0){ if (iy==varbinmin[1]) tylow=tvarmin[1]; if (iy==varbinmax[1]) tyhigh=tvarmax[1]; } else tyhigh=tvar[1]; // Get the y coefficients interpolated across z vector<MELANCSplineCore::T> yCoefs; for (int icy=0; icy<(int)coefficients.at(ix).at(icx).at(iy).size(); icy++){ DefaultAccumulator<MELANCSplineCore::T> theYCoef; for (int iz=0; iz<(int)coefficients.at(ix).at(icx).at(iy).at(icy).size(); iz++){ if ( (varbin[2]>=0 && iz!=varbin[2]) || (varbinmin[2]>=0 && varbinmax[2]>=varbinmin[2] && !(varbinmin[2]<=iz && iz<=varbinmax[2])) ) continue; MELANCSplineCore::T tzlow=0, tzhigh=1; if (code>0 && code%varprime[2]==0){ if (iz==varbinmin[2]) tzlow=tvarmin[2]; if (iz==varbinmax[2]) tzhigh=tvarmax[2]; } else tzhigh=tvar[2]; theYCoef += evalSplineSegment(coefficients.at(ix).at(icx).at(iy).at(icy).at(iz), varkappa[2]->at(iz), tzhigh, tzlow, (code>0 && code%varprime[2]==0)); } yCoefs.push_back(theYCoef); } theXCoef += evalSplineSegment(yCoefs, varkappa[1]->at(iy), tyhigh, tylow, (code>0 && code%varprime[1]==0)); } xCoefs.push_back(theXCoef); } // Evaluate value of spline at x with coefficients evaluated at y res += evalSplineSegment(xCoefs, varkappa[0]->at(ix), txhigh, txlow, (code>0 && code%varprime[0]==0)); } return res; } void MELANCSpline_3D_fast::getKappas(vector<MELANCSplineCore::T>& kappas, const Int_t whichDirection){ kappas.clear(); MELANCSplineCore::T kappa=1; Int_t npoints; vector<MELANCSplineCore::T> const* coord; if (whichDirection==0){ npoints=npointsX(); coord=&XList; } else if (whichDirection==1){ npoints=npointsY(); coord=&YList; } else{ npoints=npointsZ(); coord=&ZList; } for (Int_t j=0; j<npoints-1; j++){ MELANCSplineCore::T val_j = coord->at(j); MELANCSplineCore::T val_jpo = coord->at(j+1); MELANCSplineCore::T val_diff = (val_jpo-val_j); if (fabs(val_diff)>MELANCSplineCore::T(0)) kappa = 1./val_diff; else kappa = 0; kappas.push_back(kappa); } kappas.push_back(kappa); // Push the same kappa_(N-1)=kappa_(N-2) at the end point } Int_t MELANCSpline_3D_fast::getWhichBin(const MELANCSplineCore::T& val, const Int_t whichDirection)const{ Int_t bin=-1; MELANCSplineCore::T valj, valjpo; Int_t npoints; vector<MELANCSplineCore::T> const* coord; if (whichDirection==0){ npoints=npointsX(); coord=&XList; } else if (whichDirection==1){ npoints=npointsY(); coord=&YList; } else{ npoints=npointsZ(); coord=&ZList; } if (npoints<=1) bin=0; else{ valjpo = coord->at(0); for (Int_t j=0; j<npoints-1; j++){ valj = coord->at(j); valjpo = coord->at(j+1); if (val<valjpo && val>=valj){ bin=j; break; } } if (bin==-1 && val>=valjpo) bin=npoints-2; else if (bin==-1) bin=0; } return bin; } MELANCSplineCore::T MELANCSpline_3D_fast::getTVar(const vector<MELANCSplineCore::T>& kappas, const MELANCSplineCore::T& val, const Int_t& bin, const Int_t whichDirection)const{ const MELANCSplineCore::T& K=kappas.at(bin); vector<MELANCSplineCore::T> const* coord; if (whichDirection==0) coord=&XList; else if (whichDirection==1) coord=&YList; else coord=&ZList; return (val-coord->at(bin))*K; } vector<vector<MELANCSplineCore::T>> MELANCSpline_3D_fast::getCoefficientsPerYPerZ( const std::vector<MELANCSplineCore::T>& kappaX, const TMatrix_t& xAinv, const Int_t& ybin, const Int_t& zbin, MELANCSplineCore::BoundaryCondition const& bcBegin, MELANCSplineCore::BoundaryCondition const& bcEnd, const Int_t xbin )const{ vector<MELANCSplineCore::T> fcnList; for (unsigned int bin=0; bin<npointsX(); bin++){ fcnList.push_back(FcnList.at(zbin).at(ybin).at(bin)); } vector<vector<MELANCSplineCore::T>> coefs = getCoefficientsAlongDirection(kappaX, xAinv, fcnList, bcBegin, bcEnd, xbin); return coefs; } Double_t MELANCSpline_3D_fast::evaluate() const{ Double_t value = interpolateFcn(0); if (useFloor && value<floorEval){ if (verbosity>=MELANCSplineCore::kError) coutE(Eval) << "MELANCSpline_3D_fast ERROR::MELANCSpline_3D_fast(" << GetName() << ") evaluation returned " << value << " at (x, y, z) = (" << theXVar << ", " << theYVar << ", " << theZVar << ")" << endl; value = floorEval; } if (verbosity==MELANCSplineCore::kVerbose){ cout << "MELANCSpline_3D_fast(" << GetName() << ")::evaluate = " << value << " at (x, y, z) = (" << theXVar << ", " << theYVar << ", " << theZVar << ")" << endl; } return value; } Int_t MELANCSpline_3D_fast::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const{ if (_forceNumInt) return 0; Int_t code=1; RooArgSet Xdeps, Ydeps, Zdeps; RooRealVar* rrv_x = dynamic_cast<RooRealVar*>(theXVar.absArg()); RooRealVar* rrv_y = dynamic_cast<RooRealVar*>(theYVar.absArg()); RooRealVar* rrv_z = dynamic_cast<RooRealVar*>(theZVar.absArg()); if (rrv_x==0) theXVar.absArg()->leafNodeServerList(&Xdeps, 0, true); if (rrv_y==0) theYVar.absArg()->leafNodeServerList(&Ydeps, 0, true); if (rrv_z==0) theZVar.absArg()->leafNodeServerList(&Zdeps, 0, true); if (rrv_x!=0){ if ( (Ydeps.find(*rrv_x)==0 || rrv_y!=0) && (Zdeps.find(*rrv_x)==0 || rrv_z!=0) ){ if (matchArgs(allVars, analVars, theXVar)) code*=2; } } if (rrv_y!=0){ if ( (Xdeps.find(*rrv_y)==0 || rrv_x!=0) && (Zdeps.find(*rrv_y)==0 || rrv_z!=0) ){ if (matchArgs(allVars, analVars, theYVar)) code*=3; } } if (rrv_z!=0){ if ( (Xdeps.find(*rrv_z)==0 || rrv_x!=0) && (Ydeps.find(*rrv_z)==0 || rrv_y!=0) ){ if (matchArgs(allVars, analVars, theZVar)) code*=5; } } if (code==1) code=0; return code; } Double_t MELANCSpline_3D_fast::analyticalIntegral(Int_t code, const char* rangeName) const{ Double_t value = interpolateFcn(code, rangeName); if (useFloor && value<floorInt){ if (verbosity>=MELANCSplineCore::kError) coutE(Integration) << "MELANCSpline_3D_fast ERROR::MELANCSpline_3D_fast(" << GetName() << ") integration returned " << value << " for code = " << code << endl; value = floorInt; } if (verbosity==MELANCSplineCore::kVerbose){ cout << "MELANCSpline_3D_fast(" << GetName() << ")::analyticalIntegral = " << value << " for code = " << code << endl; } return value; } Bool_t MELANCSpline_3D_fast::testRangeValidity(const T& val, const Int_t whichDirection) const{ const T* range[2]; if (whichDirection==0){ range[0] = &rangeXmin; range[1] = &rangeXmax; } else if (whichDirection==1){ range[0] = &rangeYmin; range[1] = &rangeYmax; } else{ range[0] = &rangeZmin; range[1] = &rangeZmax; } return (*(range[0])>*(range[1]) || (val>=*(range[0]) && val<=*(range[1]))); } void MELANCSpline_3D_fast::setRangeValidity(const T valmin, const T valmax, const Int_t whichDirection){ T* range[2]; if (whichDirection==0){ range[0] = &rangeXmin; range[1] = &rangeXmax; } else if (whichDirection==1){ range[0] = &rangeYmin; range[1] = &rangeYmax; } else{ range[0] = &rangeZmin; range[1] = &rangeZmax; } *(range[0])=valmin; *(range[1])=valmax; } void MELANCSpline_3D_fast::cropValueForRange(T& val, const Int_t whichDirection)const{ if (testRangeValidity(val, whichDirection)) return; const T* range[2]; if (whichDirection==0){ range[0] = &rangeXmin; range[1] = &rangeXmax; } else if (whichDirection==1){ range[0] = &rangeYmin; range[1] = &rangeYmax; } else{ range[0] = &rangeZmin; range[1] = &rangeZmax; } if (val<*(range[0])) val = *(range[0]); if (val>*(range[1])) val = *(range[1]); }
37.320652
249
0.640794
mostafa1993
29c74e3f2cb6c7464f17d654f431b6729d8dc157
3,604
cpp
C++
sockets/Socket.cpp
allmanaj/emojicode
44b66adf7b50c80600a4397ccd70df6528d01aae
[ "Artistic-2.0" ]
null
null
null
sockets/Socket.cpp
allmanaj/emojicode
44b66adf7b50c80600a4397ccd70df6528d01aae
[ "Artistic-2.0" ]
null
null
null
sockets/Socket.cpp
allmanaj/emojicode
44b66adf7b50c80600a4397ccd70df6528d01aae
[ "Artistic-2.0" ]
null
null
null
// // Created by Theo Weidmann on 26.03.18. // #include "../runtime/Runtime.h" #include "../s/Data.h" #include "../s/String.h" #include "../s/Error.h" #include <arpa/inet.h> #include <cerrno> #include <csignal> #include <cstring> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> using s::String; using s::Data; namespace sockets { class Socket : public runtime::Object<Socket> { public: int socket_; }; class Server : public runtime::Object<Server> { public: int socket_; }; extern "C" Socket* socketsSocketNewHost(String *host, runtime::Integer port, runtime::Raiser *raiser) { struct hostent *server = gethostbyname(host->stdString().c_str()); if (server == nullptr) { EJC_RAISE(raiser, s::IOError::init()); } struct sockaddr_in address{}; std::memset(&address, 0, sizeof(address)); std::memcpy(&address.sin_addr.s_addr, server->h_addr_list[0], server->h_length); address.sin_family = PF_INET; address.sin_port = htons(port); int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0); if (socketDescriptor == -1 || connect(socketDescriptor, reinterpret_cast<struct sockaddr *>(&address), sizeof(address)) == -1) { EJC_RAISE(raiser, s::IOError::init()); } auto socket = Socket::init(); socket->socket_ = socketDescriptor; return socket; } extern "C" void socketsSocketClose(Socket *socket) { close(socket->socket_); } extern "C" void socketsSocketSend(Socket *socket, Data *data, runtime::Raiser *raiser) { EJC_COND_RAISE_IO_VOID(send(socket->socket_, data->data.get(), data->count, 0) != -1, raiser); } extern "C" Data* socketsSocketRead(Socket *socket, runtime::Integer count, runtime::Raiser *raiser) { auto bytes = runtime::allocate<runtime::Byte>(count); auto read = recv(socket->socket_, bytes.get(), count, 0); if (read == -1) { EJC_RAISE(raiser, s::IOError::init()); } auto data = Data::init(); data->count = read; data->data = bytes; return data; } extern "C" void socketsServerClose(Server *server) { close(server->socket_); } extern "C" Server* socketsServerNewPort(runtime::Integer port, runtime::Raiser *raiser) { int listenerDescriptor = socket(PF_INET, SOCK_STREAM, 0); if (listenerDescriptor == -1) { EJC_RAISE(raiser, s::IOError::init()); } struct sockaddr_in name{}; name.sin_family = PF_INET; name.sin_port = htons(port); name.sin_addr.s_addr = htonl(INADDR_ANY); int reuse = 1; if (setsockopt(listenerDescriptor, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&reuse), sizeof(int)) == -1 || bind(listenerDescriptor, reinterpret_cast<struct sockaddr *>(&name), sizeof(name)) == -1 || listen(listenerDescriptor, 10) == -1) { EJC_RAISE(raiser, s::IOError::init()); } auto server = Server::init(); server->socket_ = listenerDescriptor; return server; } extern "C" Socket* socketsServerAccept(Server *server, runtime::Raiser *raiser) { std::signal(SIGPIPE, SIG_IGN); struct sockaddr_storage clientAddress{}; unsigned int addressSize = sizeof(clientAddress); int connectionAddress = accept(server->socket_, reinterpret_cast<struct sockaddr *>(&clientAddress), &addressSize); if (connectionAddress == -1) { EJC_RAISE(raiser, s::IOError::init()); } auto socket = Socket::init(); socket->socket_ = connectionAddress; return socket; } } // namespace sockets SET_INFO_FOR(sockets::Socket, sockets, 1f4de) SET_INFO_FOR(sockets::Server, sockets, 1f3c4)
29.064516
120
0.662042
allmanaj
29ca5633050c63589f7e31e31dd7dd8f8c51a47a
4,033
cpp
C++
test/tree/tree.cpp
ho-ri1991/genetic-programming
06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0
[ "MIT" ]
null
null
null
test/tree/tree.cpp
ho-ri1991/genetic-programming
06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0
[ "MIT" ]
null
null
null
test/tree/tree.cpp
ho-ri1991/genetic-programming
06d0c1f0719f4d2ddcf9c066d9de1d0bb67772b0
[ "MIT" ]
null
null
null
#define BOOST_TEST_NO_LIB #define BOOST_TEST_MAIN #include <gp/node/node.hpp> #include <gp/tree/tree.hpp> #include <boost/test/unit_test.hpp> using namespace gp; BOOST_AUTO_TEST_SUITE(tree_test) BOOST_AUTO_TEST_CASE(tree_test) { auto var0 = node::NodeInterface::createInstance<node::LocalVariableNode<int>>(0); auto arg1 = node::NodeInterface::createInstance<node::ArgumentNode<int, 1>>(); auto add1 = node::NodeInterface::createInstance<node::AddNode<int>>(); add1->setChild(0, std::move(arg1)); add1->setChild(1, std::move(var0)); auto c1 = node::NodeInterface::createInstance<node::ConstNode<int>>(10); auto add2 = node::NodeInterface::createInstance<node::AddNode<int>>(); add2->setChild(0, std::move(c1)); add2->setChild(1, std::move(add1)); auto lvar0 = node::NodeInterface::createInstance<node::LocalVariableNode<utility::LeftHandValue<int>>>(0); auto arg0 = node::NodeInterface::createInstance<node::ArgumentNode<int, 0>>(); auto subst = node::NodeInterface::createInstance<node::SubstitutionNode<int>>(); subst->setChild(0, std::move(lvar0)); subst->setChild(1, std::move(arg0)); auto progn = node::NodeInterface::createInstance<node::PrognNode<int, 2>>(); progn->setChild(0, std::move(subst)); progn->setChild(1, std::move(add2)); auto treeProperty = tree::TreeProperty{&utility::typeInfo<int>(), {&utility::typeInfo<int>(), &utility::typeInfo<int>()}, {&utility::typeInfo<int>()}, "TestTree"}; tree::Tree tree(std::move(treeProperty), std::move(progn)); for(int i = -10; i < 10; ++i) { int a0 = i; int a1 = 2 * i; auto ans = tree.evaluate(std::make_tuple(a0, a1)); BOOST_CHECK_EQUAL(static_cast<int>(ans.getEvaluationStatus()), static_cast<int>(utility::EvaluationStatus::ValueReturned)); BOOST_CHECK_EQUAL(std::any_cast<int>(ans.getReturnValue()), 10 + a0 + a1); } tree::Tree copyTree = tree; BOOST_CHECK_EQUAL(copyTree.getArgumentNum(), tree.getArgumentNum()); BOOST_CHECK_EQUAL(copyTree.getLocalVariableNum(), tree.getLocalVariableNum()); BOOST_CHECK(tree.getReturnType() == copyTree.getReturnType()); for(int i = 0; i < tree.getArgumentNum(); ++i) { BOOST_CHECK(tree.getArgumentType(i) == copyTree.getArgumentType(i)); } for(int i = 0; i < tree.getLocalVariableNum(); ++i) { BOOST_CHECK(tree.getLocalVariableType(i) == copyTree.getLocalVariableType(i)); } for(int i = -10; i < 10; ++i) { int a0 = i; int a1 = 2 * i; auto ans = copyTree.evaluate(std::make_tuple(a0, a1)); BOOST_CHECK_EQUAL(static_cast<int>(ans.getEvaluationStatus()), static_cast<int>(utility::EvaluationStatus::ValueReturned)); BOOST_CHECK_EQUAL(std::any_cast<int>(ans.getReturnValue()), 10 + a0 + a1); } copyTree.getRootNode().getChild(1).getChild(0).setNodePropertyByAny(5); for(int i = -10; i < 10; ++i) { int a0 = i; int a1 = 2 * i; auto ans = tree.evaluate(std::make_tuple(a0, a1)); BOOST_CHECK_EQUAL(static_cast<int>(ans.getEvaluationStatus()), static_cast<int>(utility::EvaluationStatus::ValueReturned)); BOOST_CHECK_EQUAL(std::any_cast<int>(ans.getReturnValue()), 10 + a0 + a1); } for(int i = -10; i < 10; ++i) { int a0 = i; int a1 = 2 * i; auto ans = copyTree.evaluate(std::make_tuple(a0, a1)); BOOST_CHECK_EQUAL(static_cast<int>(ans.getEvaluationStatus()), static_cast<int>(utility::EvaluationStatus::ValueReturned)); BOOST_CHECK_EQUAL(std::any_cast<int>(ans.getReturnValue()), 5 + a0 + a1); } } BOOST_AUTO_TEST_SUITE_END()
45.829545
135
0.601537
ho-ri1991
29cab57d32aa22883e6804362b41524283bc8416
8,709
cpp
C++
tests/tdd/test_rsa.cpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
40
2016-04-01T15:20:24.000Z
2022-03-24T08:38:12.000Z
tests/tdd/test_rsa.cpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
4
2017-12-12T09:04:38.000Z
2021-01-30T04:19:05.000Z
tests/tdd/test_rsa.cpp
tjahn/mbedcrypto
23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425
[ "MIT" ]
15
2016-07-22T02:46:23.000Z
2020-12-23T15:57:37.000Z
#include <catch2/catch.hpp> #include "mbedcrypto/hash.hpp" #include "pk_common.hpp" #include "mbedtls/bignum.h" #include "mbedtls/rsa.h" #include <iostream> /////////////////////////////////////////////////////////////////////////////// namespace { using namespace mbedcrypto; /////////////////////////////////////////////////////////////////////////////// void mpi_checker(const char*, const mpi& mpi) { REQUIRE(mpi == true); REQUIRE(mpi.size() > 0); REQUIRE(mpi.bitlen() <= (mpi.size() << 3)); auto bin = mpi.dump(); REQUIRE(bin.size() == mpi.size()); auto str = mpi.to_string(16); REQUIRE(str.size() == (mpi.size() << 1)); REQUIRE(from_hex(str) == bin); // dumper(name, mpi); } /////////////////////////////////////////////////////////////////////////////// } // namespace anon /////////////////////////////////////////////////////////////////////////////// TEST_CASE("rsa type checks", "[types][pk]") { using namespace mbedcrypto; SECTION("creation") { rsa my_empty; REQUIRE(test::icompare(my_empty.name(), "RSA")); REQUIRE(my_empty.can_do(pk_t::rsa)); REQUIRE(!my_empty.can_do(pk_t::rsa_alt)); REQUIRE(!my_empty.can_do(pk_t::ecdsa)); REQUIRE(!my_empty.has_private_key()); auto af = my_empty.what_can_do(); // empty instance, all members must be false REQUIRE_FALSE((af.encrypt || af.decrypt || af.sign || af.verify)); REQUIRE_THROWS(my_empty.reset_as(pk_t::none)); REQUIRE_THROWS(my_empty.reset_as(pk_t::eckey)); REQUIRE_THROWS(my_empty.reset_as(pk_t::eckey_dh)); REQUIRE_THROWS(my_empty.reset_as(pk_t::ecdsa)); REQUIRE_NOTHROW(my_empty.reset_as(pk_t::rsa)); if (supports(pk_t::rsa_alt)) { REQUIRE_NOTHROW(my_empty.reset_as(pk_t::rsa_alt)); } if (supports(pk_t::rsassa_pss)) { REQUIRE_NOTHROW(my_empty.reset_as(pk_t::rsassa_pss)); } rsa my_pri; REQUIRE_NOTHROW(my_pri.import_key(test::rsa_private_key())); REQUIRE(test::icompare(my_pri.name(), "RSA")); REQUIRE(my_pri.has_private_key()); REQUIRE(my_pri.can_do(pk_t::rsa)); REQUIRE(!my_pri.can_do(pk_t::rsa_alt)); REQUIRE(my_pri.key_bitlen() == 2048); af = my_pri.what_can_do(); // private key, can do all of the tasks REQUIRE((af.encrypt && af.decrypt && af.sign && af.verify)); rsa my_key; REQUIRE_NOTHROW(my_key.import_public_key(test::rsa_public_key())); REQUIRE(test::icompare(my_key.name(), "RSA")); REQUIRE(!my_key.has_private_key()); REQUIRE(my_key.can_do(pk_t::rsa)); REQUIRE(!my_key.can_do(pk_t::rsa_alt)); REQUIRE(my_key.key_bitlen() == 2048); af = my_key.what_can_do(); // public key can both encrypt or verify REQUIRE((af.encrypt && af.verify)); // public key can not decrypt nor sign REQUIRE_FALSE((af.decrypt | af.sign)); // check key pair REQUIRE(!check_pair(my_empty, my_key)); // my_empty is uninitialized REQUIRE(!check_pair(my_key, my_empty)); // my_empty is uninitialized REQUIRE(check_pair(my_key, my_pri) == true); // reuse of my_key REQUIRE_NOTHROW(my_key.import_key( test::rsa_private_key_password(), "mbedcrypto1234" // password )); REQUIRE(test::icompare(my_key.name(), "RSA")); REQUIRE(my_key.has_private_key()); REQUIRE(my_key.can_do(pk_t::rsa)); REQUIRE(my_key.key_bitlen() == 2048); // my_key is still the same key (with or without password) REQUIRE(check_pair(my_pri, my_key) == true); } } TEST_CASE("rsa cryptography", "[pk]") { using namespace mbedcrypto; SECTION("cryptography max size") { rsa my_pri; my_pri.import_key(test::rsa_private_key()); REQUIRE(my_pri.max_crypt_size() == (my_pri.key_length() - 11)); rsa my_pub; my_pub.import_public_key(test::rsa_public_key()); REQUIRE(my_pub.max_crypt_size() == (my_pub.key_length() - 11)); } SECTION("sign and verify") { // message is 455 bytes long > 2048 bits std::string message{test::long_text()}; constexpr auto hash_type = hash_t::sha1; rsa my_pri; my_pri.import_key(test::rsa_private_key()); // invalid hash value size REQUIRE_THROWS(my_pri.sign(message, hash_type)); // sign by message auto sig_m = my_pri.sign_message(message, hash_type); REQUIRE((sig_m == test::long_text_signature())); // sign by hash auto hvalue = to_sha1(message); auto sig_h = my_pri.sign(hvalue, hash_type); REQUIRE((sig_h == sig_m)); // verify by private key, a private key contains the public REQUIRE(my_pri.verify_message(sig_m, message, hash_type)); REQUIRE(my_pri.verify(sig_m, hvalue, hash_type)); rsa my_pub; my_pub.import_public_key(test::rsa_public_key()); REQUIRE(my_pub.verify_message(sig_m, message, hash_type)); REQUIRE(my_pub.verify(sig_m, hvalue, hash_type)); } SECTION("encrypt and decrypt") { const std::string message(test::long_text()); const auto hvalue = hash::make(hash_t::sha256, message); rsa my_pub; my_pub.import_public_key(test::rsa_public_key()); // message size is invalid REQUIRE_THROWS(my_pub.encrypt(message)); auto encv = my_pub.encrypt(hvalue); rsa my_pri; my_pri.import_key(test::rsa_private_key()); REQUIRE_THROWS(my_pri.decrypt(message)); auto decv = my_pri.decrypt(encv); REQUIRE(decv == hvalue); } } TEST_CASE("rsa key tests", "[pk]") { using namespace mbedcrypto; if (supports(features::rsa_keygen)) { rsa my_pri; // my_pri is not defined as rsa REQUIRE_NOTHROW(my_pri.generate_key(1024)); REQUIRE(my_pri.has_private_key()); REQUIRE(my_pri.type() == pk_t::rsa); // reuse REQUIRE_NOTHROW(my_pri.generate_key(1024)); REQUIRE(my_pri.has_private_key()); REQUIRE_NOTHROW(my_pri.generate_key(2048, 3)); REQUIRE(my_pri.has_private_key()); } if (supports(features::pk_export)) { std::string message{test::long_text()}; rsa my_gen; my_gen.import_key(test::rsa_private_key()); const auto signature = my_gen.sign_message(message, hash_t::sha256); // test pem public rsa my_pub; my_pub.import_public_key(my_gen.export_public_key(pk::pem_format)); REQUIRE(my_pub.verify_message(signature, message, hash_t::sha256)); REQUIRE(check_pair(my_pub, my_gen) == true); // test pem private rsa my_pri; my_pri.import_key(my_gen.export_key(pk::pem_format)); REQUIRE((signature == my_pri.sign_message(message, hash_t::sha256))); REQUIRE(check_pair(my_pub, my_pri) == true); // test der public my_pub.import_public_key(my_gen.export_public_key(pk::der_format)); REQUIRE(my_pub.verify_message(signature, message, hash_t::sha256)); REQUIRE(check_pair(my_pub, my_gen) == true); // test der private my_pri.import_key(my_gen.export_key(pk::der_format)); REQUIRE((signature == my_pri.sign_message(message, hash_t::sha256))); REQUIRE(check_pair(my_pub, my_pri) == true); } } TEST_CASE("rsa key params", "[pk]") { using namespace mbedcrypto; auto dumper = [](const char* name, const mpi& mpi) { std::cout << name << ": (size = " << mpi.size() << " , " << mpi.bitlen() << ")\n" << mpi.to_string(16) << "\n" << to_hex(mpi.dump()) << std::endl; }; SECTION("private checks") { rsa pri_key; pri_key.import_key(test::rsa_private_key()); auto ki = pri_key.key_info(); mpi_checker("N", ki.N); mpi_checker("E", ki.E); mpi_checker("D", ki.D); mpi_checker("P", ki.P); mpi_checker("Q", ki.Q); mpi_checker("DP", ki.DP); mpi_checker("DQ", ki.DQ); mpi_checker("QP", ki.QP); } SECTION("public checks") { rsa pub_key; pub_key.import_public_key(test::rsa_public_key()); auto ki = pub_key.key_info(); mpi_checker("N", ki.N); mpi_checker("E", ki.E); // private parts must be empty REQUIRE(ki.D == false); REQUIRE(ki.P == false); REQUIRE(ki.Q == false); REQUIRE(ki.DP == false); REQUIRE(ki.DQ == false); REQUIRE(ki.QP == false); } }
34.019531
80
0.582501
tjahn
29cc08022c891ead7f796ff870b2f64c5357bfb4
8,409
cpp
C++
grid-test/export/macos/obj/src/lime/graphics/opengl/ext/OES_compressed_paletted_texture.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/lime/graphics/opengl/ext/OES_compressed_paletted_texture.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/lime/graphics/opengl/ext/OES_compressed_paletted_texture.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.4 #include <hxcpp.h> #ifndef INCLUDED_lime_graphics_opengl_ext_OES_compressed_paletted_texture #include <lime/graphics/opengl/ext/OES_compressed_paletted_texture.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_169dd139fd8d75fb_4_new,"lime.graphics.opengl.ext.OES_compressed_paletted_texture","new",0x4e71e5b1,"lime.graphics.opengl.ext.OES_compressed_paletted_texture.new","lime/graphics/opengl/ext/OES_compressed_paletted_texture.hx",4,0x52203801) namespace lime{ namespace graphics{ namespace opengl{ namespace ext{ void OES_compressed_paletted_texture_obj::__construct(){ HX_STACKFRAME(&_hx_pos_169dd139fd8d75fb_4_new) HXLINE( 15) this->PALETTE8_RGB5_A1_OES = 35737; HXLINE( 14) this->PALETTE8_RGBA4_OES = 35736; HXLINE( 13) this->PALETTE8_R5_G6_B5_OES = 35735; HXLINE( 12) this->PALETTE8_RGBA8_OES = 35734; HXLINE( 11) this->PALETTE8_RGB8_OES = 35733; HXLINE( 10) this->PALETTE4_RGB5_A1_OES = 35732; HXLINE( 9) this->PALETTE4_RGBA4_OES = 35731; HXLINE( 8) this->PALETTE4_R5_G6_B5_OES = 35730; HXLINE( 7) this->PALETTE4_RGBA8_OES = 35729; HXLINE( 6) this->PALETTE4_RGB8_OES = 35728; } Dynamic OES_compressed_paletted_texture_obj::__CreateEmpty() { return new OES_compressed_paletted_texture_obj; } void *OES_compressed_paletted_texture_obj::_hx_vtable = 0; Dynamic OES_compressed_paletted_texture_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< OES_compressed_paletted_texture_obj > _hx_result = new OES_compressed_paletted_texture_obj(); _hx_result->__construct(); return _hx_result; } bool OES_compressed_paletted_texture_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6506bab7; } OES_compressed_paletted_texture_obj::OES_compressed_paletted_texture_obj() { } ::hx::Val OES_compressed_paletted_texture_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 17: if (HX_FIELD_EQ(inName,"PALETTE4_RGB8_OES") ) { return ::hx::Val( PALETTE4_RGB8_OES ); } if (HX_FIELD_EQ(inName,"PALETTE8_RGB8_OES") ) { return ::hx::Val( PALETTE8_RGB8_OES ); } break; case 18: if (HX_FIELD_EQ(inName,"PALETTE4_RGBA8_OES") ) { return ::hx::Val( PALETTE4_RGBA8_OES ); } if (HX_FIELD_EQ(inName,"PALETTE4_RGBA4_OES") ) { return ::hx::Val( PALETTE4_RGBA4_OES ); } if (HX_FIELD_EQ(inName,"PALETTE8_RGBA8_OES") ) { return ::hx::Val( PALETTE8_RGBA8_OES ); } if (HX_FIELD_EQ(inName,"PALETTE8_RGBA4_OES") ) { return ::hx::Val( PALETTE8_RGBA4_OES ); } break; case 20: if (HX_FIELD_EQ(inName,"PALETTE4_RGB5_A1_OES") ) { return ::hx::Val( PALETTE4_RGB5_A1_OES ); } if (HX_FIELD_EQ(inName,"PALETTE8_RGB5_A1_OES") ) { return ::hx::Val( PALETTE8_RGB5_A1_OES ); } break; case 21: if (HX_FIELD_EQ(inName,"PALETTE4_R5_G6_B5_OES") ) { return ::hx::Val( PALETTE4_R5_G6_B5_OES ); } if (HX_FIELD_EQ(inName,"PALETTE8_R5_G6_B5_OES") ) { return ::hx::Val( PALETTE8_R5_G6_B5_OES ); } } return super::__Field(inName,inCallProp); } ::hx::Val OES_compressed_paletted_texture_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 17: if (HX_FIELD_EQ(inName,"PALETTE4_RGB8_OES") ) { PALETTE4_RGB8_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE8_RGB8_OES") ) { PALETTE8_RGB8_OES=inValue.Cast< int >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"PALETTE4_RGBA8_OES") ) { PALETTE4_RGBA8_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE4_RGBA4_OES") ) { PALETTE4_RGBA4_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE8_RGBA8_OES") ) { PALETTE8_RGBA8_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE8_RGBA4_OES") ) { PALETTE8_RGBA4_OES=inValue.Cast< int >(); return inValue; } break; case 20: if (HX_FIELD_EQ(inName,"PALETTE4_RGB5_A1_OES") ) { PALETTE4_RGB5_A1_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE8_RGB5_A1_OES") ) { PALETTE8_RGB5_A1_OES=inValue.Cast< int >(); return inValue; } break; case 21: if (HX_FIELD_EQ(inName,"PALETTE4_R5_G6_B5_OES") ) { PALETTE4_R5_G6_B5_OES=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"PALETTE8_R5_G6_B5_OES") ) { PALETTE8_R5_G6_B5_OES=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void OES_compressed_paletted_texture_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("PALETTE4_RGB8_OES",6f,94,1b,77)); outFields->push(HX_("PALETTE4_RGBA8_OES",fc,e0,36,f0)); outFields->push(HX_("PALETTE4_R5_G6_B5_OES",0b,45,14,23)); outFields->push(HX_("PALETTE4_RGBA4_OES",f8,8e,9c,a2)); outFields->push(HX_("PALETTE4_RGB5_A1_OES",3f,5b,48,08)); outFields->push(HX_("PALETTE8_RGB8_OES",eb,73,45,78)); outFields->push(HX_("PALETTE8_RGBA8_OES",00,8e,b0,f3)); outFields->push(HX_("PALETTE8_R5_G6_B5_OES",87,92,c9,2d)); outFields->push(HX_("PALETTE8_RGBA4_OES",fc,3b,16,a6)); outFields->push(HX_("PALETTE8_RGB5_A1_OES",43,51,4a,1f)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo OES_compressed_paletted_texture_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE4_RGB8_OES),HX_("PALETTE4_RGB8_OES",6f,94,1b,77)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE4_RGBA8_OES),HX_("PALETTE4_RGBA8_OES",fc,e0,36,f0)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE4_R5_G6_B5_OES),HX_("PALETTE4_R5_G6_B5_OES",0b,45,14,23)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE4_RGBA4_OES),HX_("PALETTE4_RGBA4_OES",f8,8e,9c,a2)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE4_RGB5_A1_OES),HX_("PALETTE4_RGB5_A1_OES",3f,5b,48,08)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE8_RGB8_OES),HX_("PALETTE8_RGB8_OES",eb,73,45,78)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE8_RGBA8_OES),HX_("PALETTE8_RGBA8_OES",00,8e,b0,f3)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE8_R5_G6_B5_OES),HX_("PALETTE8_R5_G6_B5_OES",87,92,c9,2d)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE8_RGBA4_OES),HX_("PALETTE8_RGBA4_OES",fc,3b,16,a6)}, {::hx::fsInt,(int)offsetof(OES_compressed_paletted_texture_obj,PALETTE8_RGB5_A1_OES),HX_("PALETTE8_RGB5_A1_OES",43,51,4a,1f)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *OES_compressed_paletted_texture_obj_sStaticStorageInfo = 0; #endif static ::String OES_compressed_paletted_texture_obj_sMemberFields[] = { HX_("PALETTE4_RGB8_OES",6f,94,1b,77), HX_("PALETTE4_RGBA8_OES",fc,e0,36,f0), HX_("PALETTE4_R5_G6_B5_OES",0b,45,14,23), HX_("PALETTE4_RGBA4_OES",f8,8e,9c,a2), HX_("PALETTE4_RGB5_A1_OES",3f,5b,48,08), HX_("PALETTE8_RGB8_OES",eb,73,45,78), HX_("PALETTE8_RGBA8_OES",00,8e,b0,f3), HX_("PALETTE8_R5_G6_B5_OES",87,92,c9,2d), HX_("PALETTE8_RGBA4_OES",fc,3b,16,a6), HX_("PALETTE8_RGB5_A1_OES",43,51,4a,1f), ::String(null()) }; ::hx::Class OES_compressed_paletted_texture_obj::__mClass; void OES_compressed_paletted_texture_obj::__register() { OES_compressed_paletted_texture_obj _hx_dummy; OES_compressed_paletted_texture_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("lime.graphics.opengl.ext.OES_compressed_paletted_texture",3f,39,e7,12); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(OES_compressed_paletted_texture_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< OES_compressed_paletted_texture_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = OES_compressed_paletted_texture_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = OES_compressed_paletted_texture_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace graphics } // end namespace opengl } // end namespace ext
49.464706
267
0.769414
VehpuS
29cd2e6611a04cb22090920d11b904d14c592074
5,004
cpp
C++
windows/radiobuttons.cpp
LeeDark/libui
244c837fc510fdbaa4427be6d6a4b48e58aa000f
[ "MIT" ]
9
2016-06-15T17:40:01.000Z
2021-05-24T08:28:40.000Z
windows/radiobuttons.cpp
LeeDark/libui
244c837fc510fdbaa4427be6d6a4b48e58aa000f
[ "MIT" ]
1
2018-07-17T07:09:17.000Z
2018-07-17T07:09:17.000Z
windows/radiobuttons.cpp
LeeDark/libui
244c837fc510fdbaa4427be6d6a4b48e58aa000f
[ "MIT" ]
2
2017-03-25T20:44:40.000Z
2018-02-05T22:37:20.000Z
// 20 may 2015 #include "uipriv_windows.hpp" // desired behavior: // - tab moves between the radio buttons and the adjacent controls // - arrow keys navigate between radio buttons // - arrow keys do not leave the radio buttons (this is done in control.c) // - arrow keys wrap around bare groups (if the previous control has WS_GROUP but the first radio button doesn't, then it doesn't; since our radio buttons are all in their own child window we can't do that) // - clicking on a radio button draws a focus rect (TODO) struct uiRadioButtons { uiWindowsControl c; HWND hwnd; // of the container std::vector<HWND> *hwnds; // of the buttons void (*onSelected)(uiRadioButtons *, void *); void *onSelectedData; }; static BOOL onWM_COMMAND(uiControl *c, HWND clicked, WORD code, LRESULT *lResult) { uiRadioButtons *r = uiRadioButtons(c); WPARAM check; if (code != BN_CLICKED) return FALSE; for (const HWND &hwnd : *(r->hwnds)) { check = BST_UNCHECKED; if (clicked == hwnd) check = BST_CHECKED; SendMessage(hwnd, BM_SETCHECK, check, 0); } (*(r->onSelected))(r, r->onSelectedData); *lResult = 0; return TRUE; } static void defaultOnSelected(uiRadioButtons *r, void *data) { // do nothing } static void uiRadioButtonsDestroy(uiControl *c) { uiRadioButtons *r = uiRadioButtons(c); for (const HWND &hwnd : *(r->hwnds)) { uiWindowsUnregisterWM_COMMANDHandler(hwnd); uiWindowsEnsureDestroyWindow(hwnd); } delete r->hwnds; uiWindowsEnsureDestroyWindow(r->hwnd); uiFreeControl(uiControl(r)); } // TODO SyncEnableState uiWindowsControlAllDefaultsExceptDestroy(uiRadioButtons) // from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing #define radiobuttonHeight 10 // from http://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx #define radiobuttonXFromLeftOfBoxToLeftOfLabel 12 static void uiRadioButtonsMinimumSize(uiWindowsControl *c, int *width, int *height) { uiRadioButtons *r = uiRadioButtons(c); int wid, maxwid; uiWindowsSizing sizing; int x, y; if (r->hwnds->size() == 0) { *width = 0; *height = 0; return; } maxwid = 0; for (const HWND &hwnd : *(r->hwnds)) { wid = uiWindowsWindowTextWidth(hwnd); if (maxwid < wid) maxwid = wid; } x = radiobuttonXFromLeftOfBoxToLeftOfLabel; y = radiobuttonHeight; uiWindowsGetSizing((*(r->hwnds))[0], &sizing); uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y); *width = x + maxwid; *height = y * r->hwnds->size(); } static void radiobuttonsRelayout(uiRadioButtons *r) { RECT client; int x, y, width, height; int height1; uiWindowsSizing sizing; if (r->hwnds->size() == 0) return; uiWindowsEnsureGetClientRect(r->hwnd, &client); x = client.left; y = client.top; width = client.right - client.left; height1 = radiobuttonHeight; uiWindowsGetSizing((*(r->hwnds))[0], &sizing); uiWindowsSizingDlgUnitsToPixels(&sizing, NULL, &height1); height = height1; for (const HWND &hwnd : *(r->hwnds)) { uiWindowsEnsureMoveWindowDuringResize(hwnd, x, y, width, height); y += height; } } static void radiobuttonsArrangeChildren(uiRadioButtons *r) { LONG_PTR controlID; HWND insertAfter; controlID = 100; insertAfter = NULL; for (const HWND &hwnd : *(r->hwnds)) uiWindowsEnsureAssignControlIDZOrder(hwnd, &controlID, &insertAfter); } void uiRadioButtonsAppend(uiRadioButtons *r, const char *text) { HWND hwnd; WCHAR *wtext; DWORD groupTabStop; // the first radio button gets both WS_GROUP and WS_TABSTOP // successive radio buttons get *neither* groupTabStop = 0; if (r->hwnds->size() == 0) groupTabStop = WS_GROUP | WS_TABSTOP; wtext = toUTF16(text); hwnd = uiWindowsEnsureCreateControlHWND(0, L"button", wtext, BS_RADIOBUTTON | groupTabStop, hInstance, NULL, TRUE); uiFree(wtext); uiWindowsEnsureSetParentHWND(hwnd, r->hwnd); uiWindowsRegisterWM_COMMANDHandler(hwnd, onWM_COMMAND, uiControl(r)); r->hwnds->push_back(hwnd); radiobuttonsArrangeChildren(r); uiWindowsControlMinimumSizeChanged(uiWindowsControl(r)); } int uiRadioButtonsSelected(uiRadioButtons *r) { size_t i; for (i = 0; i < r->hwnds->size(); i++) if (SendMessage((*(r->hwnds))[i], BM_GETCHECK, 0, 0) == BST_CHECKED) return i; return -1; } void uiRadioButtonsSetSelected(uiRadioButtons *r, int n) { int m; m = uiRadioButtonsSelected(r); if (m != -1) SendMessage((*(r->hwnds))[m], BM_SETCHECK, BST_UNCHECKED, 0); if (n != -1) SendMessage((*(r->hwnds))[n], BM_SETCHECK, BST_CHECKED, 0); } void uiRadioButtonsOnSelected(uiRadioButtons *r, void (*f)(uiRadioButtons *, void *), void *data) { r->onSelected = f; r->onSelectedData = data; } static void onResize(uiWindowsControl *c) { radiobuttonsRelayout(uiRadioButtons(c)); } uiRadioButtons *uiNewRadioButtons(void) { uiRadioButtons *r; uiWindowsNewControl(uiRadioButtons, r); r->hwnd = uiWindowsMakeContainer(uiWindowsControl(r), onResize); r->hwnds = new std::vector<HWND>; uiRadioButtonsOnSelected(r, defaultOnSelected, NULL); return r; }
25.401015
206
0.721023
LeeDark
29d02ac4c75905e2181f65d6566b6b064b820556
15,434
cc
C++
nurandom/RandomUtils/NuRandomService.cc
NuSoftHEP/nurandom
9e02e51dd273d20cfd5940295a34cf82fc8707a9
[ "Apache-2.0" ]
null
null
null
nurandom/RandomUtils/NuRandomService.cc
NuSoftHEP/nurandom
9e02e51dd273d20cfd5940295a34cf82fc8707a9
[ "Apache-2.0" ]
null
null
null
nurandom/RandomUtils/NuRandomService.cc
NuSoftHEP/nurandom
9e02e51dd273d20cfd5940295a34cf82fc8707a9
[ "Apache-2.0" ]
null
null
null
/** * @file NuRandomService_service.cc * @brief Assists in the distribution of guaranteed unique seeds to all engines within a job. * @author Rob Kutschke (kutschke@fnal.gov) * @see `nurandom/RandomUtils/NuRandomService.h` * `nurandom/RandomUtils/Providers/SeedMaster.h` */ // NuRandomService header #include "nurandom/RandomUtils/NuRandomService.h" // Art include files #include "canvas/Utilities/Exception.h" #include "art/Framework/Core/detail/EngineCreator.h" #include "art/Framework/Principal/Run.h" #include "art/Framework/Principal/SubRun.h" #include "art/Framework/Services/Registry/ActivityRegistry.h" #include "art/Persistency/Provenance/ModuleContext.h" #include "art/Persistency/Provenance/ModuleDescription.h" #include "canvas/Persistency/Provenance/EventID.h" // Supporting library include files #include "messagefacility/MessageLogger/MessageLogger.h" // CLHEP libraries #include "CLHEP/Random/RandomEngine.h" // CLHEP::HepRandomEngine // C++ include files #include <iostream> #include <iomanip> namespace rndm { //---------------------------------------------------------------------------- NuRandomService::NuRandomService (fhicl::ParameterSet const& paramSet, art::ActivityRegistry& iRegistry) : seeds(paramSet) , state() , verbosity(paramSet.get<int>("verbosity", 0)) , bPrintEndOfJobSummary(paramSet.get<bool>("endOfJobSummary",false)) { state.transit_to(NuRandomServiceHelper::ArtState::inServiceConstructor); // Register callbacks. iRegistry.sPreModuleConstruction.watch (this, &NuRandomService::preModuleConstruction ); iRegistry.sPostModuleConstruction.watch (this, &NuRandomService::postModuleConstruction ); iRegistry.sPreModuleBeginRun.watch (this, &NuRandomService::preModuleBeginRun ); iRegistry.sPostModuleBeginRun.watch (this, &NuRandomService::postModuleBeginRun ); iRegistry.sPreProcessEvent.watch (this, &NuRandomService::preProcessEvent ); iRegistry.sPreModule.watch (this, &NuRandomService::preModule ); iRegistry.sPostModule.watch (this, &NuRandomService::postModule ); iRegistry.sPostProcessEvent.watch (this, &NuRandomService::postProcessEvent ); iRegistry.sPreModuleEndJob.watch (this, &NuRandomService::preModuleEndJob ); iRegistry.sPostModuleEndJob.watch (this, &NuRandomService::postModuleEndJob ); iRegistry.sPostEndJob.watch (this, &NuRandomService::postEndJob ); } // NuRandomService::NuRandomService() //---------------------------------------------------------------------------- NuRandomService::EngineId NuRandomService::qualify_engine_label (std::string moduleLabel, std::string instanceName) const { return { moduleLabel, instanceName }; } NuRandomService::EngineId NuRandomService::qualify_engine_label (std::string instanceName /* = "" */) const { return qualify_engine_label( state.moduleLabel(), instanceName); } //---------------------------------------------------------------------------- auto NuRandomService::getSeed (std::string instanceName /* = "" */) -> seed_t { return getSeed(qualify_engine_label(instanceName)); } // NuRandomService::getSeed(string) //---------------------------------------------------------------------------- auto NuRandomService::getSeed (std::string const& moduleLabel, std::string const& instanceName) -> seed_t { return getSeed(qualify_engine_label(moduleLabel, instanceName)); } //---------------------------------------------------------------------------- auto NuRandomService::getGlobalSeed(std::string instanceName) -> seed_t { EngineId ID(instanceName, EngineId::global); MF_LOG_DEBUG("NuRandomService") << "NuRandomService::getGlobalSeed(\"" << instanceName << "\")"; return getSeed(ID); } // NuRandomService::getGlobalSeed() //---------------------------------------------------------------------------- NuRandomService::seed_t NuRandomService::getSeed(EngineId const& id) { // We require an engine to have been registered before we yield seeds; // this should minimise unexpected conflicts. if (hasEngine(id)) return querySeed(id); // ask the seed to seed master // if it hasn't been declared, we declare it now // (this is for backward compatibility with the previous behaviour). // registerEngineID() will eventually call this function again to get the // seed... so we return it directly. // Also note that this effectively "freezes" the engine since no seeder // is specified. return registerEngineID(id); } // NuRandomService::getSeed(EngineId) NuRandomService::seed_t NuRandomService::querySeed(EngineId const& id) { return seeds.getSeed(id); // ask the seed to seed master } // NuRandomService::querySeed() auto NuRandomService::extractSeed (EngineId const& id, std::optional<seed_t> seed) -> std::pair<seed_t, bool> { // if we got a valid seed, use it as frozen if (seed && (seed.value() != InvalidSeed)) return { seed.value(), true }; // seed was not good enough; get the seed from the master return { querySeed(id), false }; } // NuRandomService::extractSeed() NuRandomService::seed_t NuRandomService::registerEngine( SeedMaster_t::Seeder_t seeder, std::string const instance /* = "" */, std::optional<seed_t> const seed /* = std::nullopt */ ) { EngineId id = qualify_engine_label(instance); registerEngineAndSeeder(id, seeder); auto const [ seedValue, frozen ] = extractSeed(id, seed); seedEngine(id); // seed it before freezing if (frozen) freezeSeed(id, seedValue); return seedValue; } // NuRandomService::registerEngine(Seeder_t, string, ParameterSet, init list) NuRandomService::seed_t NuRandomService::registerEngine( SeedMaster_t::Seeder_t seeder, std::string instance, fhicl::ParameterSet const& pset, std::initializer_list<std::string> pnames ) { return registerEngine(seeder, instance, readSeedParameter(pset, pnames)); } // NuRandomService::registerEngine(Seeder_t, string, ParameterSet, init list) NuRandomService::seed_t NuRandomService::registerEngine( SeedMaster_t::Seeder_t seeder, std::string instance, SeedAtom const& seedParam ) { return registerEngine(seeder, instance, readSeedParameter(seedParam)); } // NuRandomService::registerEngine(Seeder_t, string, ParameterSet, init list) NuRandomService::seed_t NuRandomService::declareEngine(std::string instance) { return registerEngine(SeedMaster_t::Seeder_t(), instance); } // NuRandomService::declareEngine(string) NuRandomService::seed_t NuRandomService::declareEngine( std::string instance, fhicl::ParameterSet const& pset, std::initializer_list<std::string> pnames ) { return registerEngine(SeedMaster_t::Seeder_t(), instance, pset, pnames); } // NuRandomService::declareEngine(string, ParameterSet, init list) NuRandomService::seed_t NuRandomService::defineEngine (SeedMaster_t::Seeder_t seeder, std::string instance /* = {} */) { return defineEngineID(qualify_engine_label(instance), seeder); } // NuRandomService::defineEngine(string, Seeder_t) //---------------------------------------------------------------------------- NuRandomService::seed_t NuRandomService::registerEngineID( EngineId const& id, SeedMaster_t::Seeder_t seeder /* = SeedMaster_t::Seeder_t() */ ) { prepareEngine(id, seeder); return seedEngine(id); } // NuRandomService::registerEngineID() NuRandomService::seed_t NuRandomService::defineEngineID (EngineId const& id, SeedMaster_t::Seeder_t seeder) { if (!hasEngine(id)) { throw art::Exception(art::errors::LogicError) << "Attempted to define engine '" << id.artName() << "', that was not declared\n"; } if (seeds.hasSeeder(id)) { throw art::Exception(art::errors::LogicError) << "Attempted to redefine engine '" << id.artName() << "', that has already been defined\n"; } ensureValidState(); seeds.registerSeeder(id, seeder); seed_t const seed = seedEngine(id); return seed; } // NuRandomService::defineEngineID() //---------------------------------------------------------------------------- void NuRandomService::ensureValidState(bool bGlobal /* = false */) const { if (bGlobal) { // registering engines may only happen in a service c'tor // In all other cases, throw. if ( (state.state() != NuRandomServiceHelper::ArtState::inServiceConstructor)) { throw art::Exception(art::errors::LogicError) << "NuRandomService: not in a service constructor." << " May not register \"global\" engines.\n"; } } else { // context-aware engine // registering engines may only happen in a c'tor // (disabling the ability to do that or from a beginRun method) // In all other cases, throw. if ( (state.state() != NuRandomServiceHelper::ArtState::inModuleConstructor) // && (state.state() != NuRandomServiceHelper::ArtState::inModuleBeginRun) ) { throw art::Exception(art::errors::LogicError) << "NuRandomService: not in a module constructor." << " May not register engines.\n"; } } // if } // NuRandomService::ensureValidState() //---------------------------------------------------------------------------- NuRandomService::seed_t NuRandomService::reseedInstance(EngineId const& id) { // get all the information on the current process, event and module from // ArtState: SeedMaster_t::EventData_t const data(state.getEventSeedInputData()); seed_t const seed = seeds.reseedEvent(id, data); if (seed == InvalidSeed) { mf::LogDebug("NuRandomService") << "No random seed specific to this event for engine '" << id << "'"; } else { mf::LogInfo("NuRandomService") << "Random seed for this event, engine '" << id << "': " << seed; } return seed; } // NuRandomService::reseedInstance() void NuRandomService::reseedModule(std::string currentModule) { for (EngineId const& ID: seeds.engineIDsRange()) { if (ID.moduleLabel != currentModule) continue; // not our module? neeext!! reseedInstance(ID); } // for } // NuRandomService::reseedModule(string) void NuRandomService::reseedModule() { reseedModule(state.moduleLabel()); } void NuRandomService::reseedGlobal() { for (EngineId const& ID: seeds.engineIDsRange()) { if (!ID.isGlobal()) continue; // not global? neeext!! reseedInstance(ID); } // for } // NuRandomService::reseedGlobal() //---------------------------------------------------------------------------- void NuRandomService::registerEngineAndSeeder (EngineId const& id, SeedMaster_t::Seeder_t seeder) { // Are we being called from the right place? ensureValidState(id.isGlobal()); if (hasEngine(id)) { throw art::Exception(art::errors::LogicError) << "NuRandomService: an engine with ID '" << id.artName() << "' has already been created!\n"; } seeds.registerNewSeeder(id, seeder); } // NuRandomService::registerEngineAndSeeder() //---------------------------------------------------------------------------- void NuRandomService::freezeSeed(EngineId const& id, seed_t frozen_seed) { seeds.freezeSeed(id, frozen_seed); } //---------------------------------------------------------------------------- NuRandomService::seed_t NuRandomService::prepareEngine (EngineId const& id, SeedMaster_t::Seeder_t seeder) { registerEngineAndSeeder(id, seeder); return querySeed(id); } // NuRandomService::prepareEngine() //---------------------------------------------------------------------------- std::optional<seed_t> NuRandomService::readSeedParameter( fhicl::ParameterSet const& pset, std::initializer_list<std::string> pnames ) { seed_t seed; for (std::string const& key: pnames) if (pset.get_if_present(key, seed)) return { seed }; return std::nullopt; } // NuRandomService::readSeedParameter(ParameterSet, strings) //---------------------------------------------------------------------------- std::optional<seed_t> NuRandomService::readSeedParameter (SeedAtom const& param) { seed_t seed; return param(seed)? std::make_optional(seed): std::nullopt; } // NuRandomService::readSeedParameter(SeedAtom) //---------------------------------------------------------------------------- // Callbacks called by art. Used to maintain information about state. void NuRandomService::preModuleConstruction(art::ModuleDescription const& md) { state.transit_to(NuRandomServiceHelper::ArtState::inModuleConstructor); state.set_module(md); } // NuRandomService::preModuleConstruction() void NuRandomService::postModuleConstruction(art::ModuleDescription const&) { state.reset_state(); } // NuRandomService::postModuleConstruction() void NuRandomService::preModuleBeginRun(art::ModuleContext const& mc) { state.transit_to(NuRandomServiceHelper::ArtState::inModuleBeginRun); state.set_module(mc.moduleDescription()); } // NuRandomService::preModuleBeginRun() void NuRandomService::postModuleBeginRun(art::ModuleContext const&) { state.reset_state(); } // NuRandomService::postModuleBeginRun() void NuRandomService::preProcessEvent(art::Event const& evt, art::ScheduleContext) { state.transit_to(NuRandomServiceHelper::ArtState::inEvent); state.set_event(evt); seeds.onNewEvent(); // inform the seed master that a new event has come MF_LOG_DEBUG("NuRandomService") << "preProcessEvent(): will reseed global engines"; reseedGlobal(); // why don't we do them all?!? } // NuRandomService::preProcessEvent() void NuRandomService::preModule(art::ModuleContext const& mc) { state.transit_to(NuRandomServiceHelper::ArtState::inModuleEvent); state.set_module(mc.moduleDescription()); // Reseed all the engine of this module... maybe // (that is, if the current policy alows it). MF_LOG_DEBUG("NuRandomService") << "preModule(): will reseed engines for module '" << mc.moduleLabel() << "'"; reseedModule(mc.moduleLabel()); } // NuRandomService::preModule() void NuRandomService::postModule(art::ModuleContext const&) { state.reset_module(); state.reset_state(); } // NuRandomService::postModule() void NuRandomService::postProcessEvent(art::Event const&, art::ScheduleContext) { state.reset_event(); state.reset_state(); } // NuRandomService::postProcessEvent() void NuRandomService::preModuleEndJob(art::ModuleDescription const& md) { state.transit_to(NuRandomServiceHelper::ArtState::inEndJob); state.set_module(md); } // NuRandomService::preModuleBeginRun() void NuRandomService::postModuleEndJob(art::ModuleDescription const&) { state.reset_state(); } // NuRandomService::preModuleBeginRun() void NuRandomService::postEndJob() { if ((verbosity > 0) || bPrintEndOfJobSummary) print(); // framework logger decides whether and where it shows up } // NuRandomService::postEndJob() //---------------------------------------------------------------------------- } // end namespace rndm
38.974747
94
0.643773
NuSoftHEP
29d27708d7907287819fd576685433bf6dbc6a0a
13,178
cpp
C++
gdal/gcore/gdaldefaultasync.cpp
dtusk/gdal1
30dcdc1eccbca2331674f6421f1c5013807da609
[ "MIT" ]
3
2017-01-12T10:18:56.000Z
2020-03-21T16:42:55.000Z
gdal/gcore/gdaldefaultasync.cpp
ShinNoNoir/gdal-1.11.5-vs2015
5d544e176a4c11f9bcd12a0fe66f97fd157824e6
[ "MIT" ]
null
null
null
gdal/gcore/gdaldefaultasync.cpp
ShinNoNoir/gdal-1.11.5-vs2015
5d544e176a4c11f9bcd12a0fe66f97fd157824e6
[ "MIT" ]
null
null
null
/****************************************************************************** * $Id: gdaldataset.cpp 16796 2009-04-17 23:35:04Z normanb $ * * Project: GDAL Core * Purpose: Implementation of GDALDefaultAsyncReader and the * GDALAsyncReader base class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2010, Frank Warmerdam * * 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 "gdal_priv.h" CPL_CVSID("$Id: gdaldataset.cpp 16796 2009-04-17 23:35:04Z normanb $"); CPL_C_START GDALAsyncReader * GDALGetDefaultAsyncReader( GDALDataset* poDS, int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions ); CPL_C_END /************************************************************************/ /* ==================================================================== */ /* GDALAsyncReader */ /* ==================================================================== */ /************************************************************************/ /************************************************************************/ /* GDALAsyncReader() */ /************************************************************************/ GDALAsyncReader::GDALAsyncReader() { } /************************************************************************/ /* ~GDALAsyncReader() */ /************************************************************************/ GDALAsyncReader::~GDALAsyncReader() { } /************************************************************************/ /* GetNextUpdatedRegion() */ /************************************************************************/ /** * \fn GDALAsyncStatusType GDALAsyncReader::GetNextUpdatedRegion( double dfTimeout, int* pnBufXOff, int* pnBufYOff, int* pnBufXSize, int* pnBufXSize) = 0; * * \brief Get async IO update * * Provide an opportunity for an asynchronous IO request to update the * image buffer and return an indication of the area of the buffer that * has been updated. * * The dfTimeout parameter can be used to wait for additional data to * become available. The timeout does not limit the amount * of time this method may spend actually processing available data. * * The following return status are possible. * - GARIO_PENDING: No imagery was altered in the buffer, but there is still * activity pending, and the application should continue to call * GetNextUpdatedRegion() as time permits. * - GARIO_UPDATE: Some of the imagery has been updated, but there is still * activity pending. * - GARIO_ERROR: Something has gone wrong. The asynchronous request should * be ended. * - GARIO_COMPLETE: An update has occured and there is no more pending work * on this request. The request should be ended and the buffer used. * * @param dfTimeout the number of seconds to wait for additional updates. Use * -1 to wait indefinately, or zero to not wait at all if there is no data * available. * @param pnBufXOff location to return the X offset of the area of the * request buffer that has been updated. * @param pnBufYOff location to return the Y offset of the area of the * request buffer that has been updated. * @param pnBufXSize location to return the X size of the area of the * request buffer that has been updated. * @param pnBufYSize location to return the Y size of the area of the * request buffer that has been updated. * * @return GARIO_ status, details described above. */ /************************************************************************/ /* GDALARGetNextUpdatedRegion() */ /************************************************************************/ GDALAsyncStatusType CPL_STDCALL GDALARGetNextUpdatedRegion(GDALAsyncReaderH hARIO, double timeout, int* pnxbufoff, int* pnybufoff, int* pnxbufsize, int* pnybufsize) { VALIDATE_POINTER1(hARIO, "GDALARGetNextUpdatedRegion", GARIO_ERROR); return ((GDALAsyncReader *)hARIO)->GetNextUpdatedRegion( timeout, pnxbufoff, pnybufoff, pnxbufsize, pnybufsize); } /************************************************************************/ /* LockBuffer() */ /************************************************************************/ /** * \brief Lock image buffer. * * Locks the image buffer passed into GDALDataset::BeginAsyncReader(). * This is useful to ensure the image buffer is not being modified while * it is being used by the application. UnlockBuffer() should be used * to release this lock when it is no longer needed. * * @param dfTimeout the time in seconds to wait attempting to lock the buffer. * -1.0 to wait indefinately and 0 to not wait at all if it can't be * acquired immediately. Default is -1.0 (infinite wait). * * @return TRUE if successful, or FALSE on an error. */ int GDALAsyncReader::LockBuffer( CPL_UNUSED double dfTimeout ) { return TRUE; } /************************************************************************/ /* GDALARLockBuffer() */ /************************************************************************/ int CPL_STDCALL GDALARLockBuffer(GDALAsyncReaderH hARIO, double dfTimeout ) { VALIDATE_POINTER1(hARIO, "GDALARLockBuffer",FALSE); return ((GDALAsyncReader *)hARIO)->LockBuffer( dfTimeout ); } /************************************************************************/ /* UnlockBuffer() */ /************************************************************************/ /** * \brief Unlock image buffer. * * Releases a lock on the image buffer previously taken with LockBuffer(). */ void GDALAsyncReader::UnlockBuffer() { } /************************************************************************/ /* GDALARUnlockBuffer() */ /************************************************************************/ void CPL_STDCALL GDALARUnlockBuffer(GDALAsyncReaderH hARIO) { VALIDATE_POINTER0(hARIO, "GDALARUnlockBuffer"); ((GDALAsyncReader *)hARIO)->UnlockBuffer(); } /************************************************************************/ /* ==================================================================== */ /* GDALDefaultAsyncReader */ /* ==================================================================== */ /************************************************************************/ class GDALDefaultAsyncReader : public GDALAsyncReader { private: char ** papszOptions; public: GDALDefaultAsyncReader(GDALDataset* poDS, int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions); ~GDALDefaultAsyncReader(); virtual GDALAsyncStatusType GetNextUpdatedRegion(double dfTimeout, int* pnBufXOff, int* pnBufYOff, int* pnBufXSize, int* pnBufYSize); }; /************************************************************************/ /* GDALGetDefaultAsyncReader() */ /************************************************************************/ GDALAsyncReader * GDALGetDefaultAsyncReader( GDALDataset* poDS, int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions) { return new GDALDefaultAsyncReader( poDS, nXOff, nYOff, nXSize, nYSize, pBuf, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace, papszOptions ); } /************************************************************************/ /* GDALDefaultAsyncReader() */ /************************************************************************/ GDALDefaultAsyncReader:: GDALDefaultAsyncReader( GDALDataset* poDS, int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int* panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions) { this->poDS = poDS; this->nXOff = nXOff; this->nYOff = nYOff; this->nXSize = nXSize; this->nYSize = nYSize; this->pBuf = pBuf; this->nBufXSize = nBufXSize; this->nBufYSize = nBufYSize; this->eBufType = eBufType; this->nBandCount = nBandCount; this->panBandMap = (int *) CPLMalloc(sizeof(int)*nBandCount); if( panBandMap != NULL ) memcpy( this->panBandMap, panBandMap, sizeof(int)*nBandCount ); else { for( int i = 0; i < nBandCount; i++ ) this->panBandMap[i] = i+1; } this->nPixelSpace = nPixelSpace; this->nLineSpace = nLineSpace; this->nBandSpace = nBandSpace; this->papszOptions = CSLDuplicate(papszOptions); } /************************************************************************/ /* ~GDALDefaultAsyncReader() */ /************************************************************************/ GDALDefaultAsyncReader::~GDALDefaultAsyncReader() { CPLFree( panBandMap ); CSLDestroy( papszOptions ); } /************************************************************************/ /* GetNextUpdatedRegion() */ /************************************************************************/ GDALAsyncStatusType GDALDefaultAsyncReader::GetNextUpdatedRegion(CPL_UNUSED double dfTimeout, int* pnBufXOff, int* pnBufYOff, int* pnBufXSize, int* pnBufYSize ) { CPLErr eErr; eErr = poDS->RasterIO( GF_Read, nXOff, nYOff, nXSize, nYSize, pBuf, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace ); *pnBufXOff = 0; *pnBufYOff = 0; *pnBufXSize = nBufXSize; *pnBufYSize = nBufYSize; if( eErr == CE_None ) return GARIO_COMPLETE; else return GARIO_ERROR; }
41.18125
154
0.46183
dtusk
29d88bed151491adda2d93677ad7a2a8b32f853b
7,640
cpp
C++
MavLinkCom/src/MavLinkMessageBase.cpp
JaganathSahu/Microsoft-Open-Source-Code
bf5cc70395da78f03d7af8592fad466088f9d84e
[ "MIT" ]
2
2019-11-25T18:53:58.000Z
2020-02-17T01:43:49.000Z
MavLinkCom/src/MavLinkMessageBase.cpp
spkdroid/AirSim
bf5cc70395da78f03d7af8592fad466088f9d84e
[ "MIT" ]
null
null
null
MavLinkCom/src/MavLinkMessageBase.cpp
spkdroid/AirSim
bf5cc70395da78f03d7af8592fad466088f9d84e
[ "MIT" ]
2
2017-02-16T01:19:25.000Z
2017-04-21T17:50:43.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "MavLinkMessageBase.hpp" #include "MavLinkConnection.hpp" #include "Utils.hpp" using namespace common_utils; STRICT_MODE_OFF #define MAVLINK_PACKED #include "../mavlink/common/mavlink.h" #include "../mavlink/mavlink_types.h" #include "../mavlink/mavlink_helpers.h" STRICT_MODE_ON using namespace mavlinkcom; void MavLinkMessageBase::decode(const MavLinkMessage& msg) { // unpack the message... this->msgid = msg.msgid; unpack(reinterpret_cast<const char*>(msg.payload64)); } void MavLinkMessageBase::pack_uint8_t(char* buffer, const uint8_t* field, int offset) const { buffer[offset] = *reinterpret_cast<const char*>(field); } void MavLinkMessageBase::pack_int8_t(char* buffer, const int8_t* field, int offset) const { buffer[offset] = *reinterpret_cast<const char*>(field); } void MavLinkMessageBase::pack_int16_t(char* buffer, const int16_t* field, int offset) const { _mav_put_int16_t(buffer, offset, *field); } void MavLinkMessageBase::pack_uint16_t(char* buffer, const uint16_t* field, int offset) const { _mav_put_uint16_t(buffer, offset, *field); } void MavLinkMessageBase::pack_uint32_t(char* buffer, const uint32_t* field, int offset) const { _mav_put_uint32_t(buffer, offset, *field); } void MavLinkMessageBase::pack_int32_t(char* buffer, const int32_t* field, int offset) const { _mav_put_int32_t(buffer, offset, *field); } void MavLinkMessageBase::pack_uint64_t(char* buffer, const uint64_t* field, int offset) const { _mav_put_uint64_t(buffer, offset, *field); } void MavLinkMessageBase::pack_int64_t(char* buffer, const int64_t* field, int offset) const { _mav_put_int64_t(buffer, offset, *field); } void MavLinkMessageBase::pack_float(char* buffer, const float* field, int offset) const { _mav_put_float(buffer, offset, *field); } void MavLinkMessageBase::pack_char_array(int len, char* buffer, const char* field, int offset) const { _mav_put_char_array(buffer, offset, field, len); } void MavLinkMessageBase::pack_uint8_t_array(int len, char* buffer, const uint8_t* field, int offset) const { _mav_put_uint8_t_array(buffer, offset, field, len); } void MavLinkMessageBase::pack_int8_t_array(int len, char* buffer, const int8_t* field, int offset) const { _mav_put_int8_t_array(buffer, offset, field, len); } void MavLinkMessageBase::pack_uint16_t_array(int len, char* buffer, const uint16_t* field, int offset) const { _mav_put_uint16_t_array(buffer, offset, field, len); } void MavLinkMessageBase::pack_int16_t_array(int len, char* buffer, const int16_t* field, int offset) const { _mav_put_int16_t_array(buffer, offset, field, len); } void MavLinkMessageBase::pack_float_array(int len, char* buffer, const float* field, int offset) const { _mav_put_float_array(buffer, offset, field, len); } #if MAVLINK_NEED_BYTE_SWAP #define _mav_get_uint16_t(buf, wire_offset, b) byte_swap_2((const char *)b,&buf[wire_offset], ) #define _mav_get_int16_t(buf, wire_offset, b) byte_swap_2((const char *)b,&buf[wire_offset], ) #define _mav_get_uint32_t(buf, wire_offset, b) byte_swap_4((const char *)b,&buf[wire_offset], ) #define _mav_get_int32_t(buf, wire_offset, b) byte_swap_4((const char *)b,&buf[wire_offset], ) #define _mav_get_uint64_t(buf, wire_offset, b) byte_swap_8((const char *)b,&buf[wire_offset], ) #define _mav_get_int64_t(buf, wire_offset, b) byte_swap_8((const char *)b,&buf[wire_offset], ) #define _mav_get_float(buf, wire_offset, b) byte_swap_4((const char *)b,&buf[wire_offset], ) #define _mav_get_double(buf, wire_offset, b) byte_swap_8((const char *)b,&buf[wire_offset], ) #elif !MAVLINK_ALIGNED_FIELDS #define _mav_get_uint16_t(buf, wire_offset, b) byte_copy_2((const char *)b,&buf[wire_offset], ) #define _mav_get_int16_t(buf, wire_offset, b) byte_copy_2((const char *)b,&buf[wire_offset], ) #define _mav_get_uint32_t(buf, wire_offset, b) byte_copy_4((const char *)b,&buf[wire_offset], ) #define _mav_get_int32_t(buf, wire_offset, b) byte_copy_4((const char *)b,&buf[wire_offset], ) #define _mav_get_uint64_t(buf, wire_offset, b) byte_copy_8((const char *)b,&buf[wire_offset], ) #define _mav_get_int64_t(buf, wire_offset, b) byte_copy_8((const char *)b,&buf[wire_offset], ) #define _mav_get_float(buf, wire_offset, b) byte_copy_4((const char *)b,&buf[wire_offset], ) #define _mav_get_double(buf, wire_offset, b) byte_copy_8((const char *)b,&buf[wire_offset], ) #else #define _mav_get_uint16_t(buf, wire_offset, b) *b = *(uint16_t *)&buf[wire_offset] #define _mav_get_int16_t(buf, wire_offset, b) *b = *(int16_t *)&buf[wire_offset] #define _mav_get_uint32_t(buf, wire_offset, b) *b = *(uint32_t *)&buf[wire_offset] #define _mav_get_int32_t(buf, wire_offset, b) *b = *(int32_t *)&buf[wire_offset] #define _mav_get_uint64_t(buf, wire_offset, b) *b = *(uint64_t *)&buf[wire_offset] #define _mav_get_int64_t(buf, wire_offset, b) *b = *(int64_t *)&buf[wire_offset] #define _mav_get_float(buf, wire_offset, b) *b = *(float *)&buf[wire_offset] #define _mav_get_double(buf, wire_offset, b) *b = *(double *)&buf[wire_offset] #endif void MavLinkMessageBase::unpack_uint8_t(const char* buffer, uint8_t* field, int offset) { *reinterpret_cast<char*>(field) = buffer[offset]; } void MavLinkMessageBase::unpack_int8_t(const char* buffer, int8_t* field, int offset) { *reinterpret_cast<char*>(field) = buffer[offset]; } void MavLinkMessageBase::unpack_int16_t(const char* buffer, int16_t* field, int offset) { _mav_get_int16_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint16_t(const char* buffer, uint16_t* field, int offset) { _mav_get_uint16_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint32_t(const char* buffer, uint32_t* field, int offset) { _mav_get_uint32_t(buffer, offset, field); } void MavLinkMessageBase::unpack_int32_t(const char* buffer, int32_t* field, int offset) { _mav_get_int32_t(buffer, offset, field); } void MavLinkMessageBase::unpack_uint64_t(const char* buffer, uint64_t* field, int offset) { _mav_get_uint64_t(buffer, offset, field); } void MavLinkMessageBase::unpack_int64_t(const char* buffer, int64_t* field, int offset) { _mav_get_int64_t(buffer, offset, field); } void MavLinkMessageBase::unpack_float(const char* buffer, float* field, int offset) { _mav_get_float(buffer, offset, field); } void MavLinkMessageBase::unpack_char_array(int len, const char* buffer, char* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_uint8_t_array(int len, const char* buffer, uint8_t* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_int8_t_array(int len, const char* buffer, int8_t* field, int offset) { memcpy(field, &buffer[offset], len); } void MavLinkMessageBase::unpack_uint16_t_array(int len, const char* buffer, uint16_t* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_uint16_t(buffer, offset, field); offset += sizeof(uint16_t); field++; } } void MavLinkMessageBase::unpack_int16_t_array(int len, const char* buffer, int16_t* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_int16_t(buffer, offset, field); offset += sizeof(int16_t); field++; } } void MavLinkMessageBase::unpack_float_array(int len, const char* buffer, float* field, int offset) { for (int i = 0; i < len; i++) { _mav_get_float(buffer, offset, field); offset += sizeof(float); field++; } }
39.381443
109
0.735733
JaganathSahu
29d8f61edd6b0945e14100e52f4fed417cb9c36a
3,140
cpp
C++
source/perlin3d.cpp
max-pasichnyk/procedural_world
e197bf275f07043b688e68bdf07c9cb708386215
[ "Apache-2.0" ]
null
null
null
source/perlin3d.cpp
max-pasichnyk/procedural_world
e197bf275f07043b688e68bdf07c9cb708386215
[ "Apache-2.0" ]
null
null
null
source/perlin3d.cpp
max-pasichnyk/procedural_world
e197bf275f07043b688e68bdf07c9cb708386215
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Maxim Pasichnyk 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 "perlin3d.h" double perlin3d::noise(const glm::vec3 &point) { double x = point.x; double y = point.y; double z = point.z; // Find unit grid cell containing point int X = fastfloor(x); int Y = fastfloor(y); int Z = fastfloor(z); // Get relative xyz coordinates of point within that cell x = x - X; y = y - Y; z = z - Z; // Wrap the integer cells at 255 (smaller integer period can be introduced here) X = X & 255; Y = Y & 255; Z = Z & 255; // Calculate a set of eight hashed gradient indices int gi000 = perm[X + perm[Y + perm[Z]]] % 12; int gi001 = perm[X + perm[Y + perm[Z + 1]]] % 12; int gi010 = perm[X + perm[Y + 1 + perm[Z]]] % 12; int gi011 = perm[X + perm[Y + 1 + perm[Z + 1]]] % 12; int gi100 = perm[X + 1 + perm[Y + perm[Z]]] % 12; int gi101 = perm[X + 1 + perm[Y + perm[Z + 1]]] % 12; int gi110 = perm[X + 1 + perm[Y + 1 + perm[Z]]] % 12; int gi111 = perm[X + 1 + perm[Y + 1 + perm[Z + 1]]] % 12; // The gradients of each corner are now: // g000 = grad3[gi000]; // g001 = grad3[gi001]; // g010 = grad3[gi010]; // g011 = grad3[gi011]; // g100 = grad3[gi100]; // g101 = grad3[gi101]; // g110 = grad3[gi110]; // g111 = grad3[gi111]; // Calculate noise contributions from each of the eight corners double n000 = dot(grad3[gi000], x, y, z); double n100 = dot(grad3[gi100], x - 1, y, z); double n010 = dot(grad3[gi010], x, y - 1, z); double n110 = dot(grad3[gi110], x - 1, y - 1, z); double n001 = dot(grad3[gi001], x, y, z - 1); double n101 = dot(grad3[gi101], x - 1, y, z - 1); double n011 = dot(grad3[gi011], x, y - 1, z - 1); double n111 = dot(grad3[gi111], x - 1, y - 1, z - 1); // Compute the fade curve value for each of x, y, z double u = fade(x); double v = fade(y); double w = fade(z); // Interpolate along x the contributions from each of the corners double nx00 = mix(n000, n100, u); double nx01 = mix(n001, n101, u); double nx10 = mix(n010, n110, u); double nx11 = mix(n011, n111, u); // Interpolate the four results along y double nxy0 = mix(nx00, nx10, v); double nxy1 = mix(nx01, nx11, v); // Interpolate the two last results along z double nxyz = mix(nxy0, nxy1, w); return nxyz; } double perlin3d::noise(const glm::vec3 &point, int octaves, float persistence) { double x = point.x; double y = point.y; double z = point.z; double amplitude = 1; double max = 0; double result = 0; while (octaves-- > 0) { max += amplitude; result += noise({(float)x, (float)y, (float)z}) * amplitude; amplitude *= persistence; x *= 2; y *= 2; z *= 2; } return result / max; }
29.904762
81
0.638535
max-pasichnyk
29df169b06b1aa1a45b2ec77d2def7bab35e7b79
684
cpp
C++
Entregas/ACM_Tarea10/P02/HW10P02.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
Entregas/ACM_Tarea10/P02/HW10P02.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
Entregas/ACM_Tarea10/P02/HW10P02.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
/*------------------------------------------------------------ PROGRAMACIÓN AVANZADA I HW10P02 César Magaña cesar@cimat.mx --------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; int tata(double &x); //float tata(const string &s,const double &x); //float tata(double &x); int tata(const string &s, const double &x); int tata(const string &s, unsigned int k); int tata(const double &x); //------------------------------------------------------------ int main (int argc, char * const argv[]) { std::cout << "Hello, World!\n"; return 0; } //------------------------------------------------------------
28.5
64
0.426901
cesar-magana
29e180475781f6dbae00a274d67b6111cdc36177
3,564
cpp
C++
source/blender/compositor/operations/COM_ChromaMatteOperation.cpp
Scoan/blender
9314d73d753750d5e20bb2ee1fa6ec3646bd25dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
33
2019-06-10T22:59:54.000Z
2022-03-24T09:16:01.000Z
source/blender/compositor/operations/COM_ChromaMatteOperation.cpp
Scoan/blender
9314d73d753750d5e20bb2ee1fa6ec3646bd25dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
5
2019-06-21T21:06:34.000Z
2021-06-26T21:58:45.000Z
source/blender/compositor/operations/COM_ChromaMatteOperation.cpp
Scoan/blender
9314d73d753750d5e20bb2ee1fa6ec3646bd25dc
[ "Naumen", "Condor-1.1", "MS-PL" ]
14
2019-06-21T12:14:23.000Z
2021-08-25T14:57:06.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright 2011, Blender Foundation. */ #include "COM_ChromaMatteOperation.h" #include "BLI_math.h" ChromaMatteOperation::ChromaMatteOperation() { addInputSocket(COM_DT_COLOR); addInputSocket(COM_DT_COLOR); addOutputSocket(COM_DT_VALUE); this->m_inputImageProgram = nullptr; this->m_inputKeyProgram = nullptr; } void ChromaMatteOperation::initExecution() { this->m_inputImageProgram = this->getInputSocketReader(0); this->m_inputKeyProgram = this->getInputSocketReader(1); } void ChromaMatteOperation::deinitExecution() { this->m_inputImageProgram = nullptr; this->m_inputKeyProgram = nullptr; } void ChromaMatteOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler) { float inKey[4]; float inImage[4]; const float acceptance = this->m_settings->t1; /* in radians */ const float cutoff = this->m_settings->t2; /* in radians */ const float gain = this->m_settings->fstrength; float x_angle, z_angle, alpha; float theta, beta; float kfg; this->m_inputKeyProgram->readSampled(inKey, x, y, sampler); this->m_inputImageProgram->readSampled(inImage, x, y, sampler); /* Store matte(alpha) value in [0] to go with * COM_SetAlphaMultiplyOperation and the Value output. */ /* Algorithm from book "Video Demistified," does not include the spill reduction part */ /* find theta, the angle that the color space should be rotated based on key */ /* rescale to -1.0..1.0 */ // inImage[0] = (inImage[0] * 2.0f) - 1.0f; // UNUSED inImage[1] = (inImage[1] * 2.0f) - 1.0f; inImage[2] = (inImage[2] * 2.0f) - 1.0f; // inKey[0] = (inKey[0] * 2.0f) - 1.0f; // UNUSED inKey[1] = (inKey[1] * 2.0f) - 1.0f; inKey[2] = (inKey[2] * 2.0f) - 1.0f; theta = atan2(inKey[2], inKey[1]); /*rotate the cb and cr into x/z space */ x_angle = inImage[1] * cosf(theta) + inImage[2] * sinf(theta); z_angle = inImage[2] * cosf(theta) - inImage[1] * sinf(theta); /*if within the acceptance angle */ /* if kfg is <0 then the pixel is outside of the key color */ kfg = x_angle - (fabsf(z_angle) / tanf(acceptance / 2.0f)); if (kfg > 0.0f) { /* found a pixel that is within key color */ alpha = 1.0f - (kfg / gain); beta = atan2(z_angle, x_angle); /* if beta is within the cutoff angle */ if (fabsf(beta) < (cutoff / 2.0f)) { alpha = 0.0f; } /* don't make something that was more transparent less transparent */ if (alpha < inImage[3]) { output[0] = alpha; } else { output[0] = inImage[3]; } } else { /*pixel is outside key color */ output[0] = inImage[3]; /* make pixel just as transparent as it was before */ } }
32.108108
90
0.645623
Scoan
29e2f6d1b3379c8f43a65510f199ac6ad76ef976
287
hpp
C++
sensact_firmware_stm32/lib/core/error.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2021-02-09T16:17:43.000Z
2021-08-09T04:02:44.000Z
sensact_firmware_stm32/lib/core/error.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
2
2016-05-17T20:45:10.000Z
2020-03-10T07:03:39.000Z
sensact_firmware_stm32/lib/core/error.hpp
klaus-liebler/sensact
b8fc05eff67f23cf58c4fdf53e0026aab0966f6b
[ "Apache-2.0" ]
1
2020-05-24T13:37:55.000Z
2020-05-24T13:37:55.000Z
#pragma once namespace sensactcore { enum Error { OK, UNSPECIFIED_ERROR, I2C_DeviceNotFound, I2C_BusError, CAN_BusError, OneWireDeviceNotFound, UNKNOWN_IO, NOT_YET_IMPLEMENTED, NO_MESSAGE_AVAILABLE, }; }
17.9375
30
0.592334
klaus-liebler
29e3ddb1b4bad5dbb1ffa2caa1087360a55d4bf5
5,753
hpp
C++
code/FIReader.hpp
PkXwmpgN/assimp
bb77f2b4e4c786000177f80fc3372606c882551f
[ "BSD-3-Clause" ]
596
2019-07-30T03:07:57.000Z
2022-03-31T07:45:20.000Z
external/assimp/code/FIReader.hpp
Guangehhhh/VulkanDemos
d3b9cc113aa3657689a0e7828892fb754f73361f
[ "MIT" ]
9
2019-07-28T08:48:41.000Z
2022-03-31T07:53:50.000Z
external/assimp/code/FIReader.hpp
Guangehhhh/VulkanDemos
d3b9cc113aa3657689a0e7828892fb754f73361f
[ "MIT" ]
79
2019-08-05T03:05:01.000Z
2022-03-31T07:45:22.000Z
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2019, assimp team 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: * 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /// \file FIReader.hpp /// \brief Reader for Fast Infoset encoded binary XML files. /// \date 2017 /// \author Patrick Daehne #ifndef INCLUDED_AI_FI_READER_H #define INCLUDED_AI_FI_READER_H #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER //#include <wchar.h> #include <string> #include <memory> #include <cerrno> #include <cwchar> #include <vector> //#include <stdio.h> //#include <cstdint> #include <irrXML.h> namespace Assimp { struct FIValue { virtual const std::string &toString() const = 0; virtual ~FIValue() {} }; struct FIStringValue: public FIValue { std::string value; static std::shared_ptr<FIStringValue> create(std::string &&value); }; struct FIByteValue: public FIValue { std::vector<uint8_t> value; }; struct FIHexValue: public FIByteValue { static std::shared_ptr<FIHexValue> create(std::vector<uint8_t> &&value); }; struct FIBase64Value: public FIByteValue { static std::shared_ptr<FIBase64Value> create(std::vector<uint8_t> &&value); }; struct FIShortValue: public FIValue { std::vector<int16_t> value; static std::shared_ptr<FIShortValue> create(std::vector<int16_t> &&value); }; struct FIIntValue: public FIValue { std::vector<int32_t> value; static std::shared_ptr<FIIntValue> create(std::vector<int32_t> &&value); }; struct FILongValue: public FIValue { std::vector<int64_t> value; static std::shared_ptr<FILongValue> create(std::vector<int64_t> &&value); }; struct FIBoolValue: public FIValue { std::vector<bool> value; static std::shared_ptr<FIBoolValue> create(std::vector<bool> &&value); }; struct FIFloatValue: public FIValue { std::vector<float> value; static std::shared_ptr<FIFloatValue> create(std::vector<float> &&value); }; struct FIDoubleValue: public FIValue { std::vector<double> value; static std::shared_ptr<FIDoubleValue> create(std::vector<double> &&value); }; struct FIUUIDValue: public FIByteValue { static std::shared_ptr<FIUUIDValue> create(std::vector<uint8_t> &&value); }; struct FICDATAValue: public FIStringValue { static std::shared_ptr<FICDATAValue> create(std::string &&value); }; struct FIDecoder { virtual std::shared_ptr<const FIValue> decode(const uint8_t *data, size_t len) = 0; virtual ~FIDecoder() {} }; struct FIQName { const char *name; const char *prefix; const char *uri; }; struct FIVocabulary { const char **restrictedAlphabetTable; size_t restrictedAlphabetTableSize; const char **encodingAlgorithmTable; size_t encodingAlgorithmTableSize; const char **prefixTable; size_t prefixTableSize; const char **namespaceNameTable; size_t namespaceNameTableSize; const char **localNameTable; size_t localNameTableSize; const char **otherNCNameTable; size_t otherNCNameTableSize; const char **otherURITable; size_t otherURITableSize; const std::shared_ptr<const FIValue> *attributeValueTable; size_t attributeValueTableSize; const std::shared_ptr<const FIValue> *charactersTable; size_t charactersTableSize; const std::shared_ptr<const FIValue> *otherStringTable; size_t otherStringTableSize; const FIQName *elementNameTable; size_t elementNameTableSize; const FIQName *attributeNameTable; size_t attributeNameTableSize; }; class IOStream; class FIReader: public irr::io::IIrrXMLReader<char, irr::io::IXMLBase> { public: virtual ~FIReader(); virtual std::shared_ptr<const FIValue> getAttributeEncodedValue(int idx) const = 0; virtual std::shared_ptr<const FIValue> getAttributeEncodedValue(const char *name) const = 0; virtual void registerDecoder(const std::string &algorithmUri, std::unique_ptr<FIDecoder> decoder) = 0; virtual void registerVocabulary(const std::string &vocabularyUri, const FIVocabulary *vocabulary) = 0; static std::unique_ptr<FIReader> create(IOStream *stream); };// class IFIReader inline FIReader::~FIReader() { // empty } }// namespace Assimp #endif // #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER #endif // INCLUDED_AI_FI_READER_H
30.439153
106
0.734399
PkXwmpgN
29ec4fd265c3fd1dad92e449ec37b6e90761ebb0
2,700
cpp
C++
FSE/Application.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
17
2017-04-02T00:17:47.000Z
2021-11-23T21:42:48.000Z
FSE/Application.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
null
null
null
FSE/Application.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
5
2017-08-06T12:47:18.000Z
2020-08-14T14:16:22.000Z
#include "Application.h" #include <imgui.h> #include <imgui-SFML.h> #include "FSEObject/FSEObject.h" #include "FSEChaiLib.h" #ifdef ANDROID #include <android/log.h> #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__)) #endif namespace fse { Application::Application() : root_scene_(this) { input_.init(); base_chai_state_ = chai_.get_state(); base_chai_locals_ = chai_.get_locals(); } Application::~Application() { if (render_window_ != nullptr) ImGui::SFML::Shutdown(); } void Application::update() { if (render_window_ != nullptr) { sf::Event event; while (render_window_->pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { render_window_->close(); return; } #ifdef ANDROID if (event.type == sf::Event::MouseEntered) { LOGI("MOUSE_ENTERED"); isActive_ = true; } if (event.type == sf::Event::MouseLeft) { LOGI("MOUSE_LEFT"); isActive_ = false; return; } #endif if (event.type == sf::Event::Resized) { on_window_resized_(); } input_.updateEvents(event); } #ifdef ANDROID if (!isActive_) return; #endif sf::Time time = application_clock_.restart(); ImGui::SFML::Update(*render_window_, time); render_window_->clear(); root_scene_.update(time.asSeconds()); root_scene_.draw(); ImGui::SFML::Render(*render_window_); render_window_->display(); } else { root_scene_.update(application_clock_.restart().asSeconds()); } network_handler_.updateSignals(); } void Application::initChai() { resetChai(); priv::FSEChaiLib::Init(chai_); on_chaiscript_init_(chai_); } void Application::setWindow(sf::RenderWindow * window) { render_window_ = window; root_scene_.setRenderTarget(render_window_); ImGui::SFML::Init(*window); } void Application::setServerClientType(int type) { if (type == 1) is_server_ = true; } void Application::init() { initChai(); } bool Application::isServer() const { return is_server_; } sf::RenderWindow* Application::getWindow() const { return render_window_; } Input* Application::getInput() { return &input_; } NetworkHandler* Application::getNetworkHandler() { return &network_handler_; } fse::AssetLoader& Application::getAssetLoader() { return asset_loader_; } chaiscript::ChaiScript* Application::getChai() { return &chai_; } void Application::resetChai() { chai_.set_state(base_chai_state_); chai_.set_locals(base_chai_locals_); } }
17.532468
95
0.671852
Alia5
29ed044763b5cd754a97459ea4d914fc63c87e15
81,897
cpp
C++
cstrike15_src/engine/host_cmd.cpp
5R33CH4/-5R33CH4-CSGO-Source-Code
dafb3cafa88f37cd405df3a9ffbbcdcb1dba8f63
[ "MIT" ]
4
2020-11-25T11:45:10.000Z
2021-03-17T15:22:01.000Z
cstrike15_src/engine/host_cmd.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
null
null
null
cstrike15_src/engine/host_cmd.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
7
2021-08-22T11:29:02.000Z
2022-03-29T11:59:15.000Z
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// // HACKHACK fix this include #if defined( _WIN32 ) && !defined( _X360 ) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include "tier0/vprof.h" #include "server.h" #include "host_cmd.h" #include "keys.h" #include "screen.h" #include "vengineserver_impl.h" #include "host_saverestore.h" #include "sv_filter.h" #include "gl_matsysiface.h" #include "pr_edict.h" #include "world.h" #include "checksum_engine.h" #include "const.h" #include "sv_main.h" #include "host.h" #include "demo.h" #include "cdll_int.h" #include "networkstringtableserver.h" #include "networkstringtableclient.h" #include "host_state.h" #include "string_t.h" #include "tier0/dbg.h" #include "testscriptmgr.h" #include "r_local.h" #include "PlayerState.h" #include "enginesingleuserfilter.h" #include "profile.h" #include "protocol.h" #include "cl_main.h" #include "sv_steamauth.h" #include "zone.h" #include "GameEventManager.h" #include "datacache/idatacache.h" #include "sys_dll.h" #include "cmd.h" #include "tier0/icommandline.h" #include "filesystem.h" #include "filesystem_engine.h" #include "icliententitylist.h" #include "icliententity.h" #include "hltvserver.h" #if defined( REPLAY_ENABLED ) #include "replayserver.h" #endif #include "cdll_engine_int.h" #include "cl_steamauth.h" #include "cl_splitscreen.h" #ifndef DEDICATED #include "vgui_baseui_interface.h" #endif #include "sound.h" #include "voice.h" #include "sv_rcon.h" #if defined( _X360 ) #include "xbox/xbox_console.h" #include "xbox/xbox_launch.h" #elif defined( _PS3 ) #include "ps3/ps3_console.h" #include "tls_ps3.h" #endif #include "filesystem/IQueuedLoader.h" #include "filesystem/IXboxInstaller.h" #include "toolframework/itoolframework.h" #include "fmtstr.h" #include "tier3/tier3.h" #include "matchmaking/imatchframework.h" #include "tier2/tier2.h" #include "shaderapi/gpumemorystats.h" #include "snd_audio_source.h" #include "netconsole.h" #include "tier2/fileutils.h" #if POSIX #include <sys/types.h> #include <sys/wait.h> #include <sys/syscall.h> #include <sys/stat.h> #include <fcntl.h> #endif #include "ixboxsystem.h" extern IXboxSystem *g_pXboxSystem; extern IVEngineClient *engineClient; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define STEAM_PREFIX "STEAM_" #ifndef DEDICATED bool g_bInEditMode = false; bool g_bInCommentaryMode = false; #endif KeyValues *g_pLaunchOptions = NULL; void PerformKick( cmd_source_t commandSource, int iSearchIndex, char* szSearchString, bool bForceKick, const char* pszMessage ); ConVar host_name_store( "host_name_store", "1", FCVAR_RELEASE, "Whether hostname is recorded in game events and GOTV." ); ConVar host_players_show( "host_players_show", "1", FCVAR_RELEASE, "How players are disclosed in server queries: 0 - query disabled, 1 - show only max players count, 2 - show all players" ); ConVar host_info_show( "host_info_show", "1", FCVAR_RELEASE, "How server info gets disclosed in server queries: 0 - query disabled, 1 - show only general info, 2 - show full info" ); ConVar host_rules_show( "host_rules_show", "1", FCVAR_RELEASE, "How server rules get disclosed in server queries: 0 - query disabled, 1 - query enabled" ); static void HostnameChanged( IConVar *pConVar, const char *pOldValue, float flOldValue ) { Steam3Server().NotifyOfServerNameChange(); if ( sv.IsActive() && host_name_store.GetBool() ) { // look up the descriptor first to avoid a DevMsg for HL2 and mods that don't define a // hostname_change event CGameEventDescriptor *descriptor = g_GameEventManager.GetEventDescriptor( "hostname_changed" ); if ( descriptor ) { IGameEvent *event = g_GameEventManager.CreateEvent( "hostname_changed" ); if ( event ) { ConVarRef var( pConVar ); event->SetString( "hostname", var.GetString() ); g_GameEventManager.FireEvent( event ); } } } } ConVar host_name( "hostname", "", FCVAR_RELEASE, "Hostname for server.", false, 0.0f, false, 0.0f, HostnameChanged ); ConVar host_map( "host_map", "", FCVAR_RELEASE, "Current map name." ); bool CanShowHostTvStatus() { if ( !serverGameDLL ) return true; if ( serverGameDLL->IsValveDS() ) { // By default OFFICIAL server will NOT print TV information in "status" output // Running with -display_tv_status will reveal GOTV information static bool s_bCanShowHostTvStatusOFFICIAL = !!CommandLine()->FindParm( "-display_tv_status" ); return s_bCanShowHostTvStatusOFFICIAL; } else { // By default COMMUNITY server will print TV information in "status" output // Running with -disable_tv_status will conceal GOTV information static bool s_bCanShowHostTvStatusCOMMUNITY = !CommandLine()->FindParm( "-disable_tv_status" ); return s_bCanShowHostTvStatusCOMMUNITY; } } #ifdef _PS3 ConVar ps3_host_quit_graceperiod( "ps3_host_quit_graceperiod", "7", FCVAR_DEVELOPMENTONLY, "Time granted for save operations to finish" ); ConVar ps3_host_quit_debugpause( "ps3_host_quit_debugpause", "0", FCVAR_DEVELOPMENTONLY, "Time to stall quit for debug purposes" ); #endif ConVar voice_recordtofile("voice_recordtofile", "0", FCVAR_RELEASE, "Record mic data and decompressed voice data into 'voice_micdata.wav' and 'voice_decompressed.wav'"); ConVar voice_inputfromfile("voice_inputfromfile", "0",FCVAR_RELEASE, "Get voice input from 'voice_input.wav' rather than from the microphone."); uint GetSteamAppID() { #ifndef DEDICATED if ( Steam3Client().SteamUtils() ) return Steam3Client().SteamUtils()->GetAppID(); #endif if ( Steam3Server().SteamGameServerUtils() ) return Steam3Server().SteamGameServerUtils()->GetAppID(); return 215; // defaults to Source SDK Base (215) if no steam.inf can be found. } EUniverse GetSteamUniverse() { #ifndef DEDICATED if ( Steam3Client().SteamUtils() ) return Steam3Client().SteamUtils()->GetConnectedUniverse(); #endif if ( Steam3Server().SteamGameServerUtils() ) return Steam3Server().SteamGameServerUtils()->GetConnectedUniverse(); return k_EUniverseInvalid; } // Globals int gHostSpawnCount = 0; // If any quit handlers balk, then aborts quit sequence bool EngineTool_CheckQuitHandlers(); #if defined( _GAMECONSOLE ) void Host_Quit_f (void); void PS3_sysutil_callback_forwarder( uint64 uiStatus, uint64 uiParam ); void Quit_gameconsole_f( bool bWarmRestart, bool bUnused ) { #if defined( _DEMO ) if ( Host_IsDemoExiting() ) { // for safety, only want to play this under demo exit conditions // which guaranteed us a safe exiting context game->PlayVideoListAndWait( "media/DemoUpsellVids.txt" ); } #endif #if defined( _X360 ) && defined( _DEMO ) // demo version has to support variants of the launch structures // demo version must reply with exact demo launch structure if provided unsigned int launchID; int launchSize; void *pLaunchData; bool bValid = XboxLaunch()->GetLaunchData( &launchID, &pLaunchData, &launchSize ); if ( bValid && Host_IsDemoHostedFromShell() ) { XboxLaunch()->SetLaunchData( pLaunchData, launchSize, LF_UNKNOWNDATA ); g_pMaterialSystem->PersistDisplay(); XBX_DisconnectConsoleMonitor(); const char *pImageName = XLAUNCH_KEYWORD_DEFAULT_APP; if ( launchID == LAUNCH_DATA_DEMO_ID ) { pImageName = ((LD_DEMO*)pLaunchData)->szLauncherXEX; } XboxLaunch()->Launch( pImageName ); return; } #endif #ifdef _X360 // must be first, will cause a reset of the launch if we have never been re-launched // all further XboxLaunch() operations MUST be writes, otherwise reset int launchFlags = LF_EXITFROMGAME; // block until the installer stops g_pXboxInstaller->IsStopped( true ); if ( g_pXboxInstaller->IsFullyInstalled() ) { launchFlags |= LF_INSTALLEDTOCACHE; } // allocate the full payload int nPayloadSize = XboxLaunch()->MaxPayloadSize(); byte *pPayload = (byte *)stackalloc( nPayloadSize ); V_memset( pPayload, 0, sizeof( nPayloadSize ) ); // payload is at least the command line // any user data needed must be placed AFTER the command line const char *pCmdLine = CommandLine()->GetCmdLine(); int nCmdLineLength = (int)strlen( pCmdLine ) + 1; V_memcpy( pPayload, pCmdLine, min( nPayloadSize, nCmdLineLength ) ); // add any other data here to payload, after the command line // ... // Collect settings to preserve across restarts int numGameUsers = XBX_GetNumGameUsers(); char slot2ctrlr[4]; char slot2guest[4]; int ctrlr2storage[4]; for ( int k = 0; k < 4; ++ k ) { slot2ctrlr[k] = (char) XBX_GetUserId( k ); slot2guest[k] = (char) XBX_GetUserIsGuest( k ); ctrlr2storage[k] = XBX_GetStorageDeviceId( k ); } // storage device may have changed since previous launch XboxLaunch()->SetStorageID( ctrlr2storage ); // Close the storage devices g_pXboxSystem->CloseAllContainers(); DWORD nUserID = XBX_GetPrimaryUserId(); XboxLaunch()->SetUserID( nUserID ); XboxLaunch()->SetSlotUsers( numGameUsers, slot2ctrlr, slot2guest ); if ( bWarmRestart ) { // a restart is an attempt at a hidden reboot-in-place launchFlags |= LF_WARMRESTART; } // set our own data and relaunch self bool bLaunch = XboxLaunch()->SetLaunchData( pPayload, nPayloadSize, launchFlags ); #if defined( _DEMO ) bLaunch = true; #endif if ( bLaunch ) { // Can't send anything to VXConsole; about to abandon connection // VXConsole tries to respond but can't and throws the timeout crash // COM_TimestampedLog( "Launching: \"%s\" Flags: 0x%8.8x", pCmdLine, XboxLaunch()->GetLaunchFlags() ); g_pMaterialSystem->PersistDisplay(); XBX_DisconnectConsoleMonitor(); #if defined( CSTRIKE15 ) XboxLaunch()->SetLaunchData( NULL, 0, 0 ); XboxLaunch()->Launch( XLAUNCH_KEYWORD_DASH_ARCADE ); #else XboxLaunch()->Launch(); #endif // defined( CSTRIKE15 ) } #elif defined( _PS3 ) // TODO: preserve when a "restart" is requested! Assert( !bWarmRestart ); Assert( !bUnused ); if ( bWarmRestart ) { DevWarning( "TODO: PS3 quit_x360 restart is not implemented yet!\n" ); } // Prevent re-entry static bool s_bQuitPreventReentry = false; if ( s_bQuitPreventReentry ) return; s_bQuitPreventReentry = true; // We must go into single-threaded rendering Host_AllowQueuedMaterialSystem( false ); // Make sure everybody received the EXITGAME callback, might happen multiple times now float const flTimeStampStart = Plat_FloatTime(); float flGracePeriod = ps3_host_quit_graceperiod.GetFloat(); flGracePeriod = MIN( 7, flGracePeriod ); flGracePeriod = MAX( 0, flGracePeriod ); float const flTimeStampForceShutdown = flTimeStampStart + flGracePeriod; uint64 uiLastCountdownNotificationSent = 0; for ( ; ; ) { enum ShutdownSystemsWait_t { kSysSaveRestore, kSysSaveUtilV2, kSysSteamClient, kSysDebugPause, kSysShutdownSystemsCount }; char const *szSystems[kSysShutdownSystemsCount] = {0}; char const *szSystemsRequiredState[kSysShutdownSystemsCount] = {0}; // Poll systems whether they are ready to shutdown if ( saverestore && saverestore->IsSaveInProgress() ) szSystems[kSysSaveRestore] = "saverestore"; extern bool SaveUtilV2_CanShutdown(); if ( !SaveUtilV2_CanShutdown() ) szSystems[kSysSaveUtilV2] = "SaveUtilV2"; if ( Steam3Client().SteamUtils() && !Steam3Client().SteamUtils()->BIsReadyToShutdown() ) szSystems[kSysSteamClient] = "steamclient"; if ( ( ps3_host_quit_debugpause.GetFloat() > 0 ) && ( Plat_FloatTime() < flTimeStampStart + ps3_host_quit_debugpause.GetFloat() ) ) szSystems[kSysDebugPause] = "debugpause"; if ( !Q_memcmp( szSystemsRequiredState, szSystems, sizeof( szSystemsRequiredState ) ) ) { DevMsg( "PS3 shutdown procedure: all systems ready (%.2f sec elapsed)\n", ( Plat_FloatTime() - flTimeStampStart ) ); break; } uint64 uiCountdownNotification = 1 + ( flTimeStampForceShutdown - Plat_FloatTime() ); if ( uiCountdownNotification != uiLastCountdownNotificationSent ) { uiLastCountdownNotificationSent = uiCountdownNotification; PS3_sysutil_callback_forwarder( CELL_SYSUTIL_REQUEST_EXITGAME, uiCountdownNotification ); DevWarning( "PS3 shutdown procedure: %.2f sec elapsed...\n", ( Plat_FloatTime() - flTimeStampStart ) ); int nNotReadySystemsCount = 0; for ( int jj = 0; jj < ARRAYSIZE( szSystems ); ++ jj ) { if ( szSystems[jj] ) { DevWarning( " system not ready : %s\n", szSystems[jj] ); ++ nNotReadySystemsCount; } } DevWarning( "PS3 shutdown procedure: waiting for %d systems to be ready for shutdown (%.2f sec remaining)...\n", nNotReadySystemsCount, ( flTimeStampForceShutdown - Plat_FloatTime() ) ); } if ( Plat_FloatTime() >= flTimeStampForceShutdown ) { DevWarning( "FORCING PS3 SHUTDOWN PROCEDURE: NOT ALL SYSTEMS READY (%.2f sec elapsed)...\n", ( Plat_FloatTime() - flTimeStampStart ) ); break; } // Perform blank vsync'ed flips static ConVarRef mat_vsync( "mat_vsync" ); mat_vsync.SetValue( true ); g_pMaterialSystem->SetFlipPresentFrequency( 1 ); // let it flip every VSYNC, we let interrupt handler throttle this loop to conform with TCR#R092 [no more than 60 fps] // Dummy frame g_pMaterialSystem->BeginFrame( 1.0f/60.0f ); CMatRenderContextPtr pRenderContext; pRenderContext.GetFrom( g_pMaterialSystem ); pRenderContext->ClearColor4ub( 0, 0, 0, 255 ); pRenderContext->ClearBuffers( true, true, true ); pRenderContext.SafeRelease(); g_pMaterialSystem->EndFrame(); g_pMaterialSystem->SwapBuffers(); // Pump system event queue XBX_ProcessEvents(); XBX_DispatchEventsQueue(); } // QUIT Warning( "[PS3 SYSTEM] REQUEST EXITGAME INITIATING QUIT @ %.3f\n", Plat_FloatTime() ); Host_Quit_f(); #else Assert( 0 ); #error #endif } CON_COMMAND( quit_gameconsole, "" ) { Quit_gameconsole_f( args.FindArg( "restart" ) != NULL, args.FindArg( "invite" ) != NULL ); } #endif // store arbitrary launch arguments in KeyValues to avoid having to add code for every new // launch parameter (like edit mode, commentary mode, background, etc. do) void SetLaunchOptions( const CCommand &args ) { if ( g_pLaunchOptions ) { g_pLaunchOptions->deleteThis(); } g_pLaunchOptions = new KeyValues( "LaunchOptions" ); for ( int i = 0 ; i < args.ArgC() ; i++ ) { g_pLaunchOptions->SetString( va("Arg%d", i), args[i] ); } } /* ================== Host_Quit_f ================== */ void Host_Quit_f (void) { #if !defined(DEDICATED) if ( !EngineTool_CheckQuitHandlers() ) { return; } #endif HostState_Shutdown(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( _restart, "Shutdown and restart the engine." ) { /* // FIXME: How to handle restarts? #ifndef DEDICATED if ( !EngineTool_CheckQuitHandlers() ) { return; } #endif */ HostState_Restart(); } #ifndef DEDICATED //----------------------------------------------------------------------------- // A console command to spew out driver information //----------------------------------------------------------------------------- void Host_LightCrosshair (void); static ConCommand light_crosshair( "light_crosshair", Host_LightCrosshair, "Show texture color at crosshair", FCVAR_CHEAT ); void Host_LightCrosshair (void) { Vector endPoint; Vector lightmapColor; // max_range * sqrt(3) VectorMA( MainViewOrigin(), COORD_EXTENT * 1.74f, MainViewForward(), endPoint ); R_LightVec( MainViewOrigin(), endPoint, true, lightmapColor ); int r = LinearToTexture( lightmapColor.x ); int g = LinearToTexture( lightmapColor.y ); int b = LinearToTexture( lightmapColor.z ); ConMsg( "Luxel Value: %d %d %d\n", r, g, b ); } #endif /* ================== Host_Status_PrintClient Print client info to console ================== */ void Host_Status_PrintClient( IClient *client, bool bShowAddress, void (*print) (const char *fmt, ...) ) { INetChannelInfo *nci = client->GetNetChannel(); const char *state = "challenging"; if ( client->IsActive() ) state = "active"; else if ( client->IsSpawned() ) state = "spawning"; else if ( client->IsConnected() ) state = "connecting"; if ( nci != NULL ) { print( "# %2i %i \"%s\" %s %s %i %i %s %d", client->GetUserID(), client->GetPlayerSlot() + 1, client->GetClientName(), client->GetNetworkIDString(), COM_FormatSeconds( nci->GetTimeConnected() ), (int)(1000.0f*nci->GetAvgLatency( FLOW_OUTGOING )), (int)(100.0f*nci->GetAvgLoss(FLOW_INCOMING)), state, (int)nci->GetDataRate() ); if ( bShowAddress ) { print( " %s", nci->GetAddress() ); } } else { print( "#%2i \"%s\" %s %s %.0f", client->GetUserID(), client->GetClientName(), client->GetNetworkIDString(), state, client->GetUpdateRate() ); } print( "\n" ); } typedef void ( *FnPrintf_t )(const char *fmt, ...); void Host_Client_Printf(const char *fmt, ...) { va_list argptr; char string[1024]; va_start (argptr,fmt); Q_vsnprintf (string, sizeof( string ), fmt,argptr); va_end (argptr); host_client->ClientPrintf( "%s", string ); } static void Host_Client_PrintfStub(const char *fmt, ...) { } void Host_PrintStatus( cmd_source_t commandSource, void ( *print )(const char *fmt, ...), bool bShort ) { bool bWithAddresses = ( ( commandSource != kCommandSrcNetClient ) && ( commandSource != kCommandSrcNetServer ) && ( print == ConMsg ) ); // guarantee to never print for remote IClient *client; int j; if ( !print ) { return; } // ============================================================ // Server status information. print( "hostname: %s\n", host_name.GetString() ); const char *pchSecureReasonString = ""; const char *pchUniverse = ""; bool bGSSecure = Steam3Server().BSecure(); if ( !bGSSecure && Steam3Server().BWantsSecure() ) { if ( Steam3Server().BLoggedOn() ) { pchSecureReasonString = "(secure mode enabled, connected to Steam3)"; } else { pchSecureReasonString = "(secure mode enabled, disconnected from Steam3)"; } } switch ( GetSteamUniverse() ) { case k_EUniversePublic: pchUniverse = ""; break; case k_EUniverseBeta: pchUniverse = "(beta)"; break; case k_EUniverseInternal: pchUniverse = "(internal)"; break; case k_EUniverseDev: pchUniverse = "(dev)"; break; /* no such universe anymore case k_EUniverseRC: pchUniverse = "(rc)"; break; */ default: pchUniverse = "(unknown)"; break; } if ( bWithAddresses ) { print( "version : %s/%d %d/%d %s %s %s %s\n", Sys_GetVersionString(), GetHostVersion(), GetServerVersion(), build_number(), bGSSecure ? "secure" : "insecure", pchSecureReasonString, Steam3Server().GetGSSteamID().IsValid() ? Steam3Server().GetGSSteamID().Render() : "[INVALID_STEAMID]", pchUniverse ); } else { print( "version : %s %s\n", Sys_GetVersionString(), bGSSecure ? "secure" : "insecure" ); } if ( NET_IsMultiplayer() ) { CUtlString sPublicIPInfo; if ( !Steam3Server().BLanOnly() ) { uint32 unPublicIP = Steam3Server().GetPublicIP(); if ( ( unPublicIP != 0 ) && bWithAddresses && sv.IsDedicated() ) { netadr_t addr; addr.SetIP( unPublicIP ); sPublicIPInfo.Format(" (public ip: %s)", addr.ToString( true ) ); } } print( "udp/ip : %s:%i%s\n", net_local_adr.ToString(true), sv.GetUDPPort(), sPublicIPInfo.String() ); static ConVarRef sv_steamdatagramtransport_port( "sv_steamdatagramtransport_port" ); if ( bWithAddresses && sv_steamdatagramtransport_port.GetInt() > 0 ) { print( "sdt : =%s on port %d\n", Steam3Server().GetGSSteamID().Render(), sv_steamdatagramtransport_port.GetInt() ); } const char *osType = #if defined( WIN32 ) "Windows"; #elif defined( _LINUX ) "Linux"; #elif defined( PLATFORM_OSX ) "OSX"; #else "Unknown"; #endif print( "os : %s\n", osType ); char const *serverType = sv.IsHLTV() ? "hltv" : ( sv.IsDedicated() ? ( serverGameDLL->IsValveDS() ? "official dedicated" : "community dedicated" ) : "listen" ); print( "type : %s\n", serverType ); } #ifndef DEDICATED // no client on dedicated server if ( !sv.IsDedicated() && GetBaseLocalClient().IsConnected() ) { print( "map : %s at: %d x, %d y, %d z\n", sv.GetMapName(), (int)MainViewOrigin()[0], (int)MainViewOrigin()[1], (int)MainViewOrigin()[2]); } #else { print( "map : %s\n", sv.GetMapName() ); } #endif if ( CanShowHostTvStatus() ) { for ( CActiveHltvServerIterator hltv; hltv; hltv.Next() ) { print( "gotv[%i]: port %i, delay %.1fs, rate %.1f\n", hltv.GetIndex(), hltv->GetUDPPort(), hltv->GetDirector() ? hltv->GetDirector()->GetDelay() : 0.0f, hltv->GetSnapshotRate() ); } } #if defined( REPLAY_ENABLED ) if ( replay && replay->IsActive() ) { print( "replay: port %i, delay %.1fs\n", replay->GetUDPPort(), replay->GetDirector()->GetDelay() ); } #endif int nHumans; int nMaxHumans; int nBots; sv.GetMasterServerPlayerCounts( nHumans, nMaxHumans, nBots ); print( "players : %i humans, %i bots (%i/%i max) (%s)\n\n", nHumans, nBots, nMaxHumans, sv.GetNumGameSlots(), sv.IsHibernating() ? "hibernating" : "not hibernating" ); // ============================================================ #if SUPPORT_NET_CONSOLE if ( g_pNetConsoleMgr && g_pNetConsoleMgr->IsActive() && bWithAddresses ) { print( "netcon : %s:%i\n", net_local_adr.ToString( true), g_pNetConsoleMgr->GetAddress().GetPort() ); } #endif // Early exit for this server. if ( bShort ) { for ( j=0 ; j < sv.GetClientCount() ; j++ ) { client = sv.GetClient( j ); if ( !client->IsActive() ) continue; if ( !bWithAddresses && !CanShowHostTvStatus() && client->IsHLTV() ) continue; print( "#%i - %s\n" , j + 1, client->GetClientName() ); } return; } // the header for the status rows print( "# userid name uniqueid connected ping loss state rate" ); if ( bWithAddresses ) { print( " adr" ); } print( "\n" ); for ( j=0 ; j < sv.GetClientCount() ; j++ ) { client = sv.GetClient( j ); if ( !client->IsConnected() ) continue; // not connected yet, maybe challenging if ( !CanShowHostTvStatus() && client->IsHLTV() ) continue; Host_Status_PrintClient( client, bWithAddresses, print ); } print( "#end\n" ); } //----------------------------------------------------------------------------- // Host_Status_f //----------------------------------------------------------------------------- CON_COMMAND( status, "Display map and connection status." ) { void (*print) (const char *fmt, ...) = Host_Client_PrintfStub; if ( args.Source() != kCommandSrcNetClient ) { if ( !sv.IsActive() ) { Cmd_ForwardToServer( args ); return; } #ifndef DBGFLAG_STRINGS_STRIP print = ConMsg; #endif } else { print = Host_Client_Printf; } bool bShort = false; if ( args.ArgC() == 2 ) { if ( !Q_stricmp( args[1], "short" ) ) { bShort = true; } } Host_PrintStatus( args.Source(), print, bShort ); } CON_COMMAND( hltv_replay_status, "Show Killer Replay status and some statistics, works on listen or dedicated server." ) { HltvReplayStats_t hltvStats; for ( int j = 0; j < sv.GetClientCount(); j++ ) { IClient *client = sv.GetClient( j ); if ( !client->IsConnected() ) continue; // not connected yet, maybe challenging if ( !CanShowHostTvStatus() && client->IsHLTV() ) continue; INetChannelInfo *nci = client->GetNetChannel(); const char *state = "challenging"; if ( client->IsActive() ) state = "active"; else if ( client->IsSpawned() ) state = "spawning"; else if ( client->IsConnected() ) state = "connecting"; if ( nci != NULL ) { ConMsg( "# %2i %i \"%s\" %s %s %s %s", client->GetUserID(), client->GetPlayerSlot() + 1, client->GetClientName(), client->GetNetworkIDString(), COM_FormatSeconds( nci->GetTimeConnected() ), state, client->GetHltvReplayStatus() ); if ( client->GetHltvReplayDelay() ) ConMsg( ", in replay NOW" ); } else { ConMsg( "#%2i \"%s\" %s %s %s", client->GetUserID(), client->GetClientName(), client->GetNetworkIDString(), state, client->GetHltvReplayStatus() ); } if ( CGameClient *pClient = dynamic_cast< CGameClient * >( client ) ) { if ( pClient->m_HltvReplayStats.nStartRequests ) hltvStats += pClient->m_HltvReplayStats; if ( pClient->m_nForceWaitForTick > 0 ) { ConMsg( ", force-waiting for tick %d - server tick %d, current frame %d", pClient->m_nForceWaitForTick, sv.GetTick(), pClient->m_pCurrentFrame ? pClient->m_pCurrentFrame->tick_count : 0 ); } } ConMsg( "\n" ); } extern HltvReplayStats_t m_DisconnectedClientsHltvReplayStats; if ( m_DisconnectedClientsHltvReplayStats.nClients > 1 ) ConMsg( "%u disconnected clients: %s\n", m_DisconnectedClientsHltvReplayStats.nClients - 1, m_DisconnectedClientsHltvReplayStats.AsString() ); if ( hltvStats.nClients > 0 ) { ConMsg( "%u current clients: %s\n", hltvStats.nClients, hltvStats.AsString() ); } } #if defined( _X360 ) CON_COMMAND( vx_mapinfo, "" ) { Vector org; QAngle ang; const char *pName; if ( GetBaseLocalClient().IsActive() ) { pName = GetBaseLocalClient().m_szLevelNameShort; org = MainViewOrigin(); VectorAngles( MainViewForward(), ang ); IClientEntity *localPlayer = entitylist->GetClientEntity( GetBaseLocalClient().m_nPlayerSlot + 1 ); if ( localPlayer ) { org = localPlayer->GetAbsOrigin(); } } else { pName = ""; org.Init(); ang.Init(); } // HACK: This is only relevant for portal2. Msg( "BUG REPORT PORTAL POSITIONS:\n" ); Cbuf_AddText( Cbuf_GetCurrentPlayer(), "portal_report\n" ); // send to vxconsole xMapInfo_t mapInfo; mapInfo.position[0] = org[0]; mapInfo.position[1] = org[1]; mapInfo.position[2] = org[2]; mapInfo.angle[0] = ang[0]; mapInfo.angle[1] = ang[1]; mapInfo.angle[2] = ang[2]; mapInfo.build = build_number(); mapInfo.skill = skill.GetInt(); // generate the qualified path where .sav files are expected to be written char savePath[MAX_PATH]; V_snprintf( savePath, sizeof( savePath ), "%s", saverestore->GetSaveDir() ); V_StripTrailingSlash( savePath ); g_pFileSystem->RelativePathToFullPath( savePath, "MOD", mapInfo.savePath, sizeof( mapInfo.savePath ) ); V_FixSlashes( mapInfo.savePath ); if ( pName[0] ) { // generate the qualified path from where the map was loaded char mapPath[MAX_PATH]; V_snprintf( mapPath, sizeof( mapPath ), "maps/%s" PLATFORM_EXT ".bsp", pName ); g_pFileSystem->GetLocalPath( mapPath, mapInfo.mapPath, sizeof( mapInfo.mapPath ) ); V_FixSlashes( mapInfo.mapPath ); } else { mapInfo.mapPath[0] = '\0'; } mapInfo.details[0] = '\0'; ConVarRef host_thread_mode( "host_thread_mode" ); ConVarRef mat_queue_mode( "mat_queue_mode" ); ConVarRef snd_surround_speakers( "snd_surround_speakers" ); V_strncat( mapInfo.details, CFmtStr( "Build: %d\n", build_number() ), sizeof( mapInfo.details ) ); XVIDEO_MODE videoMode; XGetVideoMode( &videoMode ); V_strncat( mapInfo.details, CFmtStr( "Display: %dx%d (%s)\n", videoMode.dwDisplayWidth, videoMode.dwDisplayHeight, videoMode.fIsWideScreen ? "widescreen" : "normal" ), sizeof( mapInfo.details ) ); int backbufferWidth, backbufferHeight; materials->GetBackBufferDimensions( backbufferWidth, backbufferHeight ); V_strncat( mapInfo.details, CFmtStr( "BackBuffer: %dx%d\n", backbufferWidth, backbufferHeight ), sizeof( mapInfo.details ) ); // audio info const char *pAudioInfo = "Unknown"; switch ( snd_surround_speakers.GetInt() ) { case 2: pAudioInfo = "Stereo"; break; case 5: pAudioInfo = "5.1 Digital Surround"; break; } V_strncat( mapInfo.details, CFmtStr( "Audio: %s\n", pAudioInfo ), sizeof( mapInfo.details ) ); // ui language V_strncat( mapInfo.details, CFmtStr( "UI: %s\n", cl_language.GetString() ), sizeof( mapInfo.details ) ); // cvars V_strncat( mapInfo.details, CFmtStr( "host_thread_mode: %d\n", host_thread_mode.GetInt() ), sizeof( mapInfo.details ) ); V_strncat( mapInfo.details, CFmtStr( "mat_queue_mode: %d\n", mat_queue_mode.GetInt() ), sizeof( mapInfo.details ) ); XBX_rMapInfo( &mapInfo ); } #elif defined( _PS3 ) #include "ps3/ps3_sn.h" CON_COMMAND( vx_mapinfo, "" ) { Vector org; QAngle ang; const char *pName; if ( GetBaseLocalClient().IsActive() ) { pName = GetBaseLocalClient().m_szLevelNameShort; org = MainViewOrigin(); VectorAngles( MainViewForward(), ang ); IClientEntity *localPlayer = entitylist->GetClientEntity( GetBaseLocalClient().m_nPlayerSlot + 1 ); if ( localPlayer ) { org = localPlayer->GetAbsOrigin(); } } else { pName = ""; org.Init(); ang.Init(); } // HACK: This is only relevant for portal2. Msg( "BUG REPORT PORTAL POSITIONS:\n" ); Cbuf_AddText( Cbuf_GetCurrentPlayer(), "portal_report\n" ); // send to vxconsole xMapInfo_t mapInfo; mapInfo.position[0] = org[0]; mapInfo.position[1] = org[1]; mapInfo.position[2] = org[2]; mapInfo.angle[0] = ang[0]; mapInfo.angle[1] = ang[1]; mapInfo.angle[2] = ang[2]; mapInfo.build = build_number(); mapInfo.skill = skill.GetInt(); // generate the qualified path where .sav files are expected to be written char savePath[MAX_PATH]; V_snprintf( savePath, sizeof( savePath ), "%s", saverestore->GetSaveDir() ); V_StripTrailingSlash( savePath ); g_pFileSystem->RelativePathToFullPath( savePath, "MOD", mapInfo.savePath, sizeof( mapInfo.savePath ) ); V_FixSlashes( mapInfo.savePath ); if ( pName[0] ) { // generate the qualified path from where the map was loaded char mapPath[MAX_PATH]; V_snprintf( mapPath, sizeof( mapPath ), "maps/%s" PLATFORM_EXT ".bsp", pName ); g_pFileSystem->GetLocalPath( mapPath, mapInfo.mapPath, sizeof( mapInfo.mapPath ) ); V_FixSlashes( mapInfo.mapPath ); } else { mapInfo.mapPath[0] = '\0'; } mapInfo.details[0] = '\0'; ConVarRef host_thread_mode( "host_thread_mode" ); ConVarRef mat_queue_mode( "mat_queue_mode" ); ConVarRef snd_surround_speakers( "snd_surround_speakers" ); V_strncat( mapInfo.details, CFmtStr( "Build: %d\n", build_number() ), sizeof( mapInfo.details ) ); /* XVIDEO_MODE videoMode; XGetVideoMode( &videoMode ); V_strncat( mapInfo.details, CFmtStr( "Display: %dx%d (%s)\n", videoMode.dwDisplayWidth, videoMode.dwDisplayHeight, videoMode.fIsWideScreen ? "widescreen" : "normal" ), sizeof( mapInfo.details ) ); int backbufferWidth, backbufferHeight; materials->GetBackBufferDimensions( backbufferWidth, backbufferHeight ); V_strncat( mapInfo.details, CFmtStr( "BackBuffer: %dx%d\n", backbufferWidth, backbufferHeight ), sizeof( mapInfo.details ) ); */ // audio info const char *pAudioInfo = "Unknown"; switch ( snd_surround_speakers.GetInt() ) { case 2: pAudioInfo = "Stereo"; break; case 5: pAudioInfo = "5.1 Digital Surround"; break; } V_strncat( mapInfo.details, CFmtStr( "Audio: %s\n", pAudioInfo ), sizeof( mapInfo.details ) ); // ui language V_strncat( mapInfo.details, CFmtStr( "UI: %s\n", cl_language.GetString() ), sizeof( mapInfo.details ) ); // cvars V_strncat( mapInfo.details, CFmtStr( "host_thread_mode: %d\n", host_thread_mode.GetInt() ), sizeof( mapInfo.details ) ); V_strncat( mapInfo.details, CFmtStr( "mat_queue_mode: %d\n", mat_queue_mode.GetInt() ), sizeof( mapInfo.details ) ); XBX_rMapInfo( &mapInfo ); } CON_COMMAND( vx_screenshot, "" ) { #if 1 g_pMaterialSystem->TransmitScreenshotToVX( ); #else // COMPILE_TIME_ASSERT( sizeof(g_pfnSwapBufferMarker) == 8); union FunctionPointerIsReallyADescriptor { void (*pFunc_t)(); struct { uint32 funcaddress; int32 iToc; } fn8; }; FunctionPointerIsReallyADescriptor *pBreakpoint = (FunctionPointerIsReallyADescriptor *)g_pfnSwapBufferMarker; // breakpoint.pFunc_t = g_pfnSwapBufferMarker; uint64 uBPAddress; /// Address of a pointer that points to the image in memory char * pFrameBuffer; /// Width of image uint32 uWidth; /// Height of image uint32 uHeight; /// Image pitch (as described in CellGCMSurface) - in bytes uint32 uPitch; /// Image colour settings (0 = X8R8G8B8, 1 = X8B8G8R8, 2 = R16G16B16X16) IMaterialSystem::VRAMScreenShotInfoColor_t colour ; // get one of the screen buffers. Since we breakpoint the game anyway I don't think // it really matters if we're two out of date. (For this test, anyway.) g_pMaterialSystem->GetVRAMScreenShotInfo( &pFrameBuffer, &uWidth, &uHeight, &uPitch, &colour ); g_pValvePS3Console->VRAMDumpingInfo( (uint64)pBreakpoint->fn8.funcaddress, (uint64)pFrameBuffer, uWidth, uHeight, uPitch, colour ); #endif } #endif //----------------------------------------------------------------------------- // Host_Ping_f //----------------------------------------------------------------------------- CON_COMMAND( ping, "Display ping to server." ) { if ( args.Source() != kCommandSrcNetClient ) { Cmd_ForwardToServer( args ); return; } host_client->ClientPrintf( "Client ping times:\n" ); for ( int i=0; i< sv.GetClientCount(); i++ ) { IClient *client = sv.GetClient(i); if ( !client->IsConnected() || client->IsFakeClient() ) continue; host_client->ClientPrintf ("%4.0f ms : %s\n", 1000.0f * client->GetNetChannel()->GetAvgLatency( FLOW_OUTGOING ), client->GetClientName() ); } } //----------------------------------------------------------------------------- // Purpose: // Input : editmode - //----------------------------------------------------------------------------- extern void GetPlatformMapPath( const char *pMapPath, char *pPlatformMapPath, int maxLength ); bool CL_HL2Demo_MapCheck( const char *name ) { if ( IsPC() && CL_IsHL2Demo() && !sv.IsDedicated() ) { if ( !Q_stricmp( name, "d1_trainstation_01" ) || !Q_stricmp( name, "d1_trainstation_02" ) || !Q_stricmp( name, "d1_town_01" ) || !Q_stricmp( name, "d1_town_01a" ) || !Q_stricmp( name, "d1_town_02" ) || !Q_stricmp( name, "d1_town_03" ) || !Q_stricmp( name, "background01" ) || !Q_stricmp( name, "background03" ) ) { return true; } return false; } return true; } bool CL_PortalDemo_MapCheck( const char *name ) { if ( IsPC() && CL_IsPortalDemo() && !sv.IsDedicated() ) { if ( !Q_stricmp( name, "testchmb_a_00" ) || !Q_stricmp( name, "testchmb_a_01" ) || !Q_stricmp( name, "testchmb_a_02" ) || !Q_stricmp( name, "testchmb_a_03" ) || !Q_stricmp( name, "testchmb_a_04" ) || !Q_stricmp( name, "testchmb_a_05" ) || !Q_stricmp( name, "testchmb_a_06" ) || !Q_stricmp( name, "background1" ) ) { return true; } return false; } return true; } enum EMapFlags { EMAP_NONE = 0, EMAP_EDIT_MODE = (1<<0), EMAP_BACKGROUND = (1<<1), EMAP_COMMENTARY = (1<<2), EMAP_SPLITSCREEN = (1<<3) }; int _Host_Map_f_CompletionFunc( char const *cmdname, char const *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] ); // Note, leaves name alone if no match possible static bool Host_Map_Helper_FuzzyName( const CCommand &args, char *name, size_t bufsize ) { char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ]; CUtlString argv0; argv0 = args.Arg( 0 ); argv0 += " "; if ( _Host_Map_f_CompletionFunc( argv0, args[1], commands ) > 0 ) { Q_strncpy( name, &commands[ 0 ][ argv0.Length() ], bufsize ); return true; } return false; } void Host_Changelevel_f( const CCommand &args ); void Host_Map_Helper( const CCommand &args, EMapFlags flags ) { char name[MAX_QPATH]; if (args.ArgC() < 2) { Warning("No map specified\n"); return; } if ( ( sv.IsActive() && !sv.IsSinglePlayerGame() && !sv.IsLevelMainMenuBackground() ) || ( sv.IsActive() && sv.IsDedicated() ) ) { // Using the 'map' command while in a map disconnects all players. // Ease the pain of this common error by forwarding to the correct command. Host_Changelevel_f( args ); return; } bool bBackground = ( flags & EMAP_BACKGROUND ) != 0; bool bSplitScreenConnect = ( flags & EMAP_SPLITSCREEN ) != 0; char ppath[ MAX_QPATH ]; // If there is a .bsp on the end, strip it off! Q_StripExtension( args[ 1 ], ppath, sizeof( ppath ) ); // Call with quiet flag for initial search if ( !modelloader->Map_IsValid( ppath, true ) ) { Host_Map_Helper_FuzzyName( args, ppath, sizeof( ppath ) ); if ( !modelloader->Map_IsValid( ppath ) ) { Warning( "map load failed: %s not found or invalid\n", ppath ); return; } } GetPlatformMapPath( ppath, name, sizeof( name ) ); // If I was in edit mode reload config file // to overwrite WC edit key bindings #if !defined(DEDICATED) bool bCommentary = ( flags & EMAP_COMMENTARY ) != 0; bool bEditmode = ( flags & EMAP_EDIT_MODE ) != 0; if ( !bEditmode ) { if ( g_bInEditMode ) { // Re-read config from disk Host_ReadConfiguration( -1, false ); g_bInEditMode = false; } } else { g_bInEditMode = true; } g_bInCommentaryMode = bCommentary; #endif SetLaunchOptions( args ); if ( !CL_HL2Demo_MapCheck( name ) ) { Warning( "map load failed: %s not found or invalid\n", name ); return; } if ( !CL_PortalDemo_MapCheck( name ) ) { Warning( "map load failed: %s not found or invalid\n", name ); return; } #ifdef DEDICATED if ( sv.IsDedicated() ) #else // Stop demo loop GetBaseLocalClient().demonum = -1; if ( GetBaseLocalClient().m_nMaxClients == 0 || sv.IsDedicated() ) #endif { Host_Disconnect( false ); // stop old game HostState_NewGame( name, false, bBackground, bSplitScreenConnect ); } if (args.ArgC() == 10) { if (Q_stricmp(args[2], "setpos") == 0 && Q_stricmp(args[6], "setang") == 0) { Vector newpos; newpos.x = atof( args[3] ); newpos.y = atof( args[4] ); newpos.z = atof( args[5] ); QAngle newangle; newangle.x = atof( args[7] ); newangle.y = atof( args[8] ); newangle.z = atof( args[9] ); HostState_SetSpawnPoint(newpos, newangle); } } } // Handle a map command from the console. Active clients are kicked off. void Host_Map_f( const CCommand &args ) { Host_Map_Helper( args, (EMapFlags)0 ); } // Handle a map group command from the console void Host_MapGroup_f( const CCommand &args ) { if ( args.ArgC() < 2 ) { Warning( "Host_MapGroup_f: No mapgroup specified\n" ); return; } Msg( "Setting mapgroup to '%s'\n", args[1] ); HostState_SetMapGroupName( args[1] ); } // Handle smap command to connect multiple splitscreen users at once void Host_SplitScreen_Map_f( const CCommand &args ) { #ifndef _DEMO Host_Map_Helper( args, EMAP_SPLITSCREEN ); #endif } //----------------------------------------------------------------------------- // handle a map_edit <servername> command from the console. // Active clients are kicked off. // UNDONE: protect this from use if not in dev. mode //----------------------------------------------------------------------------- #ifndef DEDICATED CON_COMMAND( map_edit, "" ) { Host_Map_Helper( args, EMAP_EDIT_MODE ); } #endif //----------------------------------------------------------------------------- // Purpose: Runs a map as the background //----------------------------------------------------------------------------- void Host_Map_Background_f( const CCommand &args ) { Host_Map_Helper( args, EMAP_BACKGROUND ); } //----------------------------------------------------------------------------- // Purpose: Runs a map in commentary mode //----------------------------------------------------------------------------- void Host_Map_Commentary_f( const CCommand &args ) { Host_Map_Helper( args, EMAP_COMMENTARY ); } //----------------------------------------------------------------------------- // Restarts the current server for a dead player //----------------------------------------------------------------------------- CON_COMMAND( restart, "Restart the game on the same level (add setpos to jump to current view position on restart)." ) { if ( #if !defined(DEDICATED) demoplayer->IsPlayingBack() || #endif !sv.IsActive() ) return; if ( sv.IsMultiplayer() ) return; bool bRememberLocation = ( args.ArgC() == 2 && !Q_stricmp( args[1], "setpos" ) ); bool bSplitScreenConnect = GET_NUM_SPLIT_SCREEN_PLAYERS() == 2 ; Host_Disconnect(false); // stop old game if ( !CL_HL2Demo_MapCheck( sv.GetMapName() ) ) { Warning( "map load failed: %s not found or invalid\n", sv.GetMapName() ); return; } if ( !CL_PortalDemo_MapCheck( sv.GetMapName() ) ) { Warning( "map load failed: %s not found or invalid\n", sv.GetMapName() ); return; } HostState_NewGame( sv.GetMapName(), bRememberLocation, false, bSplitScreenConnect ); } //----------------------------------------------------------------------------- // Restarts the current server for a dead player //----------------------------------------------------------------------------- CON_COMMAND( reload, "Reload the most recent saved game (add setpos to jump to current view position on reload).") { #ifndef DEDICATED const char *pSaveName; char name[MAX_OSPATH]; #endif if ( #if !defined(DEDICATED) demoplayer->IsPlayingBack() || #endif !sv.IsActive() ) return; if ( sv.IsMultiplayer() ) return; if ( !serverGameDLL->SupportsSaveRestore() ) return; bool remember_location = false; if ( args.ArgC() == 2 && !Q_stricmp( args[1], "setpos" ) ) { remember_location = true; } // See if there is a most recently saved game // Restart that game if there is // Otherwise, restart the starting game map #ifndef DEDICATED pSaveName = saverestore->FindRecentSave( name, sizeof( name ) ); // Put up loading plaque SCR_BeginLoadingPlaque(); { // Prepare the offline session for server reload KeyValues *pEvent = new KeyValues( "OnEngineClientSignonStatePrepareChange" ); pEvent->SetString( "reason", "reload" ); g_pMatchFramework->GetEventsSubscription()->BroadcastEvent( pEvent ); } Host_Disconnect( false ); // stop old game if ( pSaveName && saverestore->SaveFileExists( pSaveName ) ) { HostState_LoadGame( pSaveName, remember_location, false ); } else #endif { if ( !CL_HL2Demo_MapCheck( host_map.GetString() ) ) { Warning( "map load failed: %s not found or invalid\n", host_map.GetString() ); return; } if ( !CL_PortalDemo_MapCheck( host_map.GetString() ) ) { Warning( "map load failed: %s not found or invalid\n", host_map.GetString() ); return; } #if !defined( DEDICATED ) if ( pSaveName && pSaveName[0] ) { Warning( "SAVERESTORE PROBLEM: %s not found! Starting new game in %s\n", pSaveName, host_map.GetString() ); } #endif HostState_NewGame( host_map.GetString(), remember_location, false, false ); } } //----------------------------------------------------------------------------- // Purpose: Goes to a new map, taking all clients along // Output : void Host_Changelevel_f //----------------------------------------------------------------------------- void Host_Changelevel_f( const CCommand &args ) { if ( args.ArgC() < 2 ) { ConMsg( "changelevel <levelname> : continue game on a new level\n" ); return; } if ( !sv.IsActive() ) { ConMsg( "Can't changelevel, not running server\n" ); return; } char mapname[MAX_PATH]; Q_StripExtension( args[ 1 ], mapname, sizeof( mapname ) ); bool bMapMustExist = true; static ConVarRef sv_workshop_allow_other_maps( "sv_workshop_allow_other_maps" ); if ( StringHasPrefix( mapname, "workshop" ) && ( ( mapname[8] == '/' ) || ( mapname[8] == '\\' ) ) && sv_workshop_allow_other_maps.GetBool() ) bMapMustExist = false; if ( bMapMustExist && !modelloader->Map_IsValid( mapname, true ) ) { Host_Map_Helper_FuzzyName( args, mapname, sizeof( mapname ) ); if ( !modelloader->Map_IsValid( mapname ) ) { Warning( "changelevel failed: %s not found\n", mapname ); return; } } if ( !CL_HL2Demo_MapCheck( mapname ) ) { Warning( "changelevel failed: %s not found\n", mapname ); return; } if ( !CL_PortalDemo_MapCheck( mapname ) ) { Warning( "changelevel failed: %s not found\n", mapname ); return; } SetLaunchOptions( args ); HostState_ChangeLevelMP( mapname, args[2] ); } //----------------------------------------------------------------------------- // Purpose: Changing levels within a unit, uses save/restore //----------------------------------------------------------------------------- void Host_Changelevel2_f( const CCommand &args ) { if ( args.ArgC() < 2 ) { ConMsg ("changelevel2 <levelname> : continue game on a new level in the unit\n"); return; } if ( !sv.IsActive() ) { ConMsg( "Can't changelevel2, not in a map\n" ); return; } if ( !g_pVEngineServer->IsMapValid( args[1] ) ) { if ( !CL_IsHL2Demo() || (CL_IsHL2Demo() && !(!Q_stricmp( args[1], "d1_trainstation_03" ) || !Q_stricmp( args[1], "d1_town_02a" ))) ) { Warning( "changelevel2 failed: %s not found\n", args[1] ); return; } } #if !defined(DEDICATED) // needs to be before CL_HL2Demo_MapCheck() check as d1_trainstation_03 isn't a valid map if ( IsPC() && CL_IsHL2Demo() && !sv.IsDedicated() && !Q_stricmp( args[1], "d1_trainstation_03" ) ) { void CL_DemoTransitionFromTrainstation(); CL_DemoTransitionFromTrainstation(); return; } // needs to be before CL_HL2Demo_MapCheck() check as d1_trainstation_03 isn't a valid map if ( IsPC() && CL_IsHL2Demo() && !sv.IsDedicated() && !Q_stricmp( args[1], "d1_town_02a" ) && !Q_stricmp( args[2], "d1_town_02_02a" )) { void CL_DemoTransitionFromRavenholm(); CL_DemoTransitionFromRavenholm(); return; } if ( IsPC() && CL_IsPortalDemo() && !sv.IsDedicated() && !Q_stricmp( args[1], "testchmb_a_07" ) ) { void CL_DemoTransitionFromTestChmb(); CL_DemoTransitionFromTestChmb(); return; } #endif // allow a level transition to d1_trainstation_03 so the Host_Changelevel() can act on it if ( !CL_HL2Demo_MapCheck( args[1] ) ) { Warning( "changelevel failed: %s not found\n", args[1] ); return; } SetLaunchOptions( args ); HostState_ChangeLevelSP( args[1], args[2] ); } // On PS/3, due to Matchmaking framework event architecture, Host_Disconnect is called recursively on quit. // Bad things happen. Since it's not really necessary to disconnect recursively, we'll track and prevent it on PS/3 during shutdown. int g_nHostDisconnectReentrancyCounter = 0; class CDisconnectReentrancyCounter { public: CDisconnectReentrancyCounter() { g_nHostDisconnectReentrancyCounter++ ;} ~CDisconnectReentrancyCounter() { g_nHostDisconnectReentrancyCounter-- ;} }; //----------------------------------------------------------------------------- // Purpose: Shut down client connection and any server //----------------------------------------------------------------------------- void Host_Disconnect( bool bShowMainMenu ) { #ifdef _PS3 if ( GetTLSGlobals()->bNormalQuitRequested ) { if ( g_nHostDisconnectReentrancyCounter != 0 ) { return; // do not disconnect recursively on QUIT } } #endif IGameEvent *disconnectEvent = g_GameEventManager.CreateEvent( "cs_game_disconnected" ); if ( disconnectEvent ) g_GameEventManager.FireEventClientSide( disconnectEvent ); CDisconnectReentrancyCounter autoReentrancyCounter; #if !defined( DEDICATED ) if ( bShowMainMenu ) { // exiting game // ensure commentary state gets cleared g_bInCommentaryMode = false; } #endif if ( IsGameConsole() ) { g_pQueuedLoader->EndMapLoading( false ); } // Switch to single-threaded rendering during shutdown to // avoid synchronization issues between destructed objects // and the renderer Host_AllowQueuedMaterialSystem( false ); #ifndef DEDICATED if ( !sv.IsDedicated() ) { FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh ) { ACTIVE_SPLITSCREEN_PLAYER_GUARD( hh ); GetLocalClient().Disconnect( bShowMainMenu ); } } #endif #if !defined( DEDICATED ) if ( g_ClientDLL && bShowMainMenu ) { // forcefully stop any of the full screen video panels used for loading or whatever // this is a safety precaution to ensure we don't orpan any of the hacky global video panels g_ClientDLL->ShutdownMovies(); } #endif HostState_GameShutdown(); #ifndef DEDICATED if ( !sv.IsDedicated() ) { if ( bShowMainMenu && !engineClient->IsDrawingLoadingImage() && ( GetBaseLocalClient().demonum == -1 ) ) { if ( IsGameConsole() ) { // Reset larger configuration material system memory (for map) back down for ui work // This must be BEFORE ui gets-rectivated below materials->ResetTempHWMemory( true ); } #ifdef _PS3 if ( GetTLSGlobals()->bNormalQuitRequested ) { return; // do not disconnect recursively on QUIT } #endif EngineVGui()->ActivateGameUI(); } } #endif } //----------------------------------------------------------------------------- // Kill the client and any local server. //----------------------------------------------------------------------------- CON_COMMAND_F( disconnect, "Disconnect game from server.", FCVAR_SERVER_CAN_EXECUTE ) { #ifndef DEDICATED GetBaseLocalClient().demonum = -1; #endif if ( args.ArgC() > 1 ) { COM_ExplainDisconnection( false, "%s", args[ 1 ] ); } Host_Disconnect(true); } CON_COMMAND( version, "Print version info string." ) { ConMsg( "Protocol version %i [%i/%i]\nExe version %s (%s)\n", GetHostVersion(), GetServerVersion(), GetClientVersion(), Sys_GetVersionString(), Sys_GetProductString() ); ConMsg( "Exe build: " __TIME__ " " __DATE__ " (%i) (%i)\n", build_number(), GetSteamAppID() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( pause, "Toggle the server pause state." ) { #if !defined( CLIENT_DLL ) #ifndef DEDICATED if ( !sv.IsDedicated() ) { if ( !GetBaseLocalClient().m_szLevelName[ 0 ] ) return; } #endif if ( !sv.IsPausable() ) return; // toggle paused state sv.SetPaused( !sv.IsPaused() ); // send text message who paused the game if ( host_client ) sv.BroadcastPrintf( "%s %s the game\n", host_client->GetClientName(), sv.IsPaused() ? "paused" : "unpaused" ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( setpause, "Set the pause state of the server." ) { #if !defined( CLIENT_DLL ) #ifndef DEDICATED if ( !sv.IsDedicated() ) { if ( !GetBaseLocalClient().m_szLevelName[ 0 ] ) return; } #endif if ( !sv.IsPausable() ) return; sv.SetPaused( true ); if ( !args.FindArg( "nomsg" ) ) { // send text message who paused the game if ( host_client ) sv.BroadcastPrintf( "%s paused the game\n", host_client->GetClientName() ); } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( unpause, "Unpause the game." ) { #if !defined( CLIENT_DLL ) #ifndef DEDICATED if ( !sv.IsDedicated() ) { if ( !GetBaseLocalClient().m_szLevelName[ 0 ] ) return; } #endif if ( !sv.IsPaused() ) return; sv.SetPaused( false ); if ( !args.FindArg( "nomsg" ) ) { // send text messaage who unpaused the game if ( host_client ) sv.BroadcastPrintf( "%s unpaused the game\n", host_client->GetClientName() ); } #endif } //----------------------------------------------------------------------------- // Kicks a user off of the server using their userid or uniqueid //----------------------------------------------------------------------------- CON_COMMAND( kickid_ex, "Kick a player by userid or uniqueid, provide a force-the-kick flag and also assign a message." ) { const char *pszArg1 = NULL, *pszMessage = NULL; int iSearchIndex = -1; char szSearchString[128]; int argsStartNum = 1; bool bSteamID = false; bool bForce = false; if ( args.ArgC() <= 1 ) { ConMsg( "Usage: kickid_ex < userid | uniqueid > < force ( 0 / 1 ) > { message }\n" ); return; } // get the first argument pszArg1 = args[1]; // if the first letter is a charcter then // we're searching for a uniqueid ( e.g. STEAM_ ) if ( *pszArg1 < '0' || *pszArg1 > '9' ) { // SteamID (need to reassemble it) if ( StringHasPrefix( pszArg1, STEAM_PREFIX ) && Q_strstr( args[2], ":" ) ) { Q_snprintf( szSearchString, sizeof( szSearchString ), "%s:%s:%s", pszArg1, args[3], args[5] ); argsStartNum = 5; bSteamID = true; } // some other ID (e.g. "UNKNOWN", "STEAM_ID_PENDING", "STEAM_ID_LAN") // NOTE: assumed to be one argument else { Q_snprintf( szSearchString, sizeof( szSearchString ), "%s", pszArg1 ); } } // this is a userid else { iSearchIndex = Q_atoi( pszArg1 ); } // check for game type and game mode if ( args.ArgC() > argsStartNum ) { if ( atoi( args[ argsStartNum + 1 ] ) == 1 ) { bForce = true; } argsStartNum++; } // check for a message if ( args.ArgC() > argsStartNum ) { int j; int dataLen = 0; pszMessage = args.ArgS(); for ( j = 1; j <= argsStartNum; j++ ) { dataLen += Q_strlen( args[j] ) + 1; // +1 for the space between args } if ( bSteamID ) { dataLen -= 5; // SteamIDs don't have spaces between the args[) values } if ( dataLen > Q_strlen( pszMessage ) ) // saftey check { pszMessage = NULL; } else { pszMessage += dataLen; } } PerformKick( args.Source(), iSearchIndex, szSearchString, bForce, pszMessage ); } //----------------------------------------------------------------------------- // Kicks a user off of the server using their userid or uniqueid //----------------------------------------------------------------------------- CON_COMMAND( kickid, "Kick a player by userid or uniqueid, with a message." ) { const char *pszArg1 = NULL, *pszMessage = NULL; int iSearchIndex = -1; char szSearchString[128]; int argsStartNum = 1; bool bSteamID = false; if ( args.ArgC() <= 1 ) { ConMsg( "Usage: kickid < userid | uniqueid > { message }\n" ); return; } // get the first argument pszArg1 = args[1]; // if the first letter is a charcter then // we're searching for a uniqueid ( e.g. STEAM_ ) if ( *pszArg1 < '0' || *pszArg1 > '9' ) { // SteamID (need to reassemble it) if ( StringHasPrefix( pszArg1, STEAM_PREFIX ) && Q_strstr( args[2], ":" ) ) { Q_snprintf( szSearchString, sizeof( szSearchString ), "%s:%s:%s", pszArg1, args[3], args[5] ); argsStartNum = 5; bSteamID = true; } // some other ID (e.g. "UNKNOWN", "STEAM_ID_PENDING", "STEAM_ID_LAN") // NOTE: assumed to be one argument else { Q_snprintf( szSearchString, sizeof( szSearchString ), "%s", pszArg1 ); } } // this is a userid else { iSearchIndex = Q_atoi( pszArg1 ); } // check for a message if ( args.ArgC() > argsStartNum ) { int j; int dataLen = 0; pszMessage = args.ArgS(); for ( j = 1; j <= argsStartNum; j++ ) { dataLen += Q_strlen( args[j] ) + 1; // +1 for the space between args } if ( bSteamID ) { dataLen -= 5; // SteamIDs don't have spaces between the args[) values } if ( dataLen > Q_strlen( pszMessage ) ) // saftey check { pszMessage = NULL; } else { pszMessage += dataLen; } } PerformKick( args.Source(), iSearchIndex, szSearchString, false, pszMessage ); } void PerformKick( cmd_source_t commandSource, int iSearchIndex, char* szSearchString, bool bForceKick, const char* pszMessage ) { IClient *client = NULL; char *who = "Console"; // find this client int i; for ( i = 0; i < sv.GetClientCount(); i++ ) { client = sv.GetClient( i ); if ( !client->IsConnected() ) { continue; } // searching by UserID if ( iSearchIndex != -1 ) { if ( client->GetUserID() == iSearchIndex ) { // found! break; } } // searching by UniqueID else { if ( Q_stricmp( client->GetNetworkIDString(), szSearchString ) == 0 ) { // found! break; } } } // now kick them if ( i < sv.GetClientCount() ) { if ( client->IsSplitScreenUser() && client->GetSplitScreenOwner() ) { client = client->GetSplitScreenOwner(); } if ( commandSource == kCommandSrcNetClient ) { who = host_client->m_Name; } if ( host_client == client && !sv.IsDedicated() && !bForceKick ) { // can't kick yourself! return; } if ( iSearchIndex != -1 || !client->IsFakeClient() ) { if ( pszMessage ) { client->Disconnect( CFmtStr( "Kicked by %s : %s", who, pszMessage ) ); } else { client->Disconnect( CFmtStr( "Kicked by %s", who ) ); } } } else { if ( iSearchIndex != -1 ) { ConMsg( "userid \"%d\" not found\n", iSearchIndex ); } else { ConMsg( "uniqueid \"%s\" not found\n", szSearchString ); } } } /* ================== Host_Kick_f Kicks a user off of the server using their name ================== */ CON_COMMAND( kick, "Kick a player by name." ) { char *who = "Console"; char *pszName = NULL; IClient *client = NULL; int i = 0; char name[64]; if ( args.ArgC() <= 1 ) { ConMsg( "Usage: kick < name >\n" ); return; } // copy the name to a local buffer memset( name, 0, sizeof(name) ); Q_strncpy( name, args.ArgS(), sizeof(name) ); pszName = name; // safety check if ( pszName && pszName[0] != 0 ) { //HACK-HACK // check for the name surrounded by quotes (comes in this way from rcon) int len = Q_strlen( pszName ) - 1; // (minus one since we start at 0) if ( pszName[0] == '"' && pszName[len] == '"' ) { // get rid of the quotes at the beginning and end pszName[len] = 0; pszName++; } for ( i = 0; i < sv.GetClientCount(); i++ ) { client = sv.GetClient(i); if ( !client->IsConnected() ) continue; // found! if ( Q_strcasecmp( client->GetClientName(), pszName ) == 0 ) break; } // now kick them if ( i < sv.GetClientCount() ) { if ( client->IsSplitScreenUser() && client->GetSplitScreenOwner() ) { client = client->GetSplitScreenOwner(); } if ( args.Source() == kCommandSrcNetClient ) { who = host_client->m_Name; } // can't kick yourself! if ( host_client == client && !sv.IsDedicated() ) return; client->Disconnect( CFmtStr( "Kicked by %s", who ) ); } else { ConMsg( "Can't kick \"%s\", name not found\n", pszName ); } } } /* =============================================================================== DEBUGGING TOOLS =============================================================================== */ void Host_PrintMemoryStatus( const char *mapname ) { const float MB = 1.0f / ( 1024*1024 ); Assert( mapname ); #ifdef PLATFORM_LINUX struct mallinfo memstats = mallinfo( ); Msg( "[MEMORYSTATUS] [%s] Operating system reports sbrk size: %.2f MB, Used: %.2f MB, #mallocs = %d\n", mapname, MB*memstats.arena, MB*memstats.uordblks, memstats.hblks ); #elif defined(PLATFORM_OSX) struct mstats stats = mstats(); Msg( "[MEMORYSTATUS] [%s] Operating system reports Used: %.2f MB, Free: %.2f Total: %.2f\n", mapname, MB*stats.bytes_used, MB*stats.bytes_free, MB*stats.bytes_total ); #elif defined( _PS3 ) // NOTE: for PS3 nFreeMemory can be negative (on a devkit, we can use more memory than a retail kit has) int nUsedMemory, nFreeMemory, nAvailable; g_pMemAlloc->GlobalMemoryStatus( (size_t *)&nUsedMemory, (size_t *)&nFreeMemory ); nAvailable = nUsedMemory + nFreeMemory; Msg( "[MEMORYSTATUS] [%s] Operating system reports Available: %.2f MB, Used: %.2f MB, Free: %.2f MB\n", mapname, MB*nAvailable, MB*nUsedMemory, MB*nFreeMemory ); #elif defined(PLATFORM_WINDOWS) MEMORYSTATUSEX statex; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx( &statex ); Msg( "[MEMORYSTATUSEX] [%s] Operating system reports Physical Available: %.2f MB, Physical Used: %.2f MB, Physical Free: %.2f MB\n Virtual Size: %.2f, Virtual Free: %.2f MB, PageFile Size: %.2f, PageFile Free: %.2f MB\n", mapname, MB*statex.ullTotalPhys, MB*( statex.ullTotalPhys - statex.ullAvailPhys ), MB*statex.ullAvailPhys, MB*statex.ullTotalVirtual, MB*statex.ullAvailVirtual, MB*statex.ullTotalPageFile, MB*statex.ullAvailPageFile ); #endif if ( IsPS3() ) { // Include stats on GPU memory usage GPUMemoryStats stats; materials->GetGPUMemoryStats( stats ); g_pMemAlloc->SetStatsExtraInfo( mapname, CFmtStr( "%d %d %d %d %d %d %d", stats.nGPUMemSize, stats.nGPUMemFree, stats.nTextureSize, stats.nRTSize, stats.nVBSize, stats.nIBSize, stats.nUnknown ) ); Msg( "[MEMORYSTATUS] [%s] RSX memory: total %.1fkb, free %.1fkb, textures %.1fkb, render targets %.1fkb, vertex buffers %.1fkb, index buffers %.1fkb, unknown %.1fkb\n", mapname, stats.nGPUMemSize/1024.0f, stats.nGPUMemFree/1024.0f, stats.nTextureSize/1024.0f, stats.nRTSize/1024.0f, stats.nVBSize/1024.0f, stats.nIBSize/1024.0f, stats.nUnknown/1024.0f ); } else { g_pMemAlloc->SetStatsExtraInfo( mapname, "" ); } int nTotal = g_pMemAlloc->GetSize( 0 ); if (nTotal == -1) { Msg( "Internal heap corrupted!\n" ); } else { Msg( "Internal heap reports: %5.2f MB (%d bytes)\n", nTotal/(1024.0f*1024.0f), nTotal ); } Msg( "\nHunk Memory Used:\n" ); Hunk_Print(); Msg( "\nDatacache reports:\n" ); g_pDataCache->OutputReport( DC_SUMMARY_REPORT, NULL ); } //----------------------------------------------------------------------------- // Dump memory stats //----------------------------------------------------------------------------- CON_COMMAND( memory, "Print memory stats." ) { ConMsg( "Heap Used:\n" ); int nTotal = g_pMemAlloc->GetSize( 0 ); if (nTotal == -1) { ConMsg( "Corrupted!\n" ); } else { ConMsg( "%5.2f MB (%d bytes)\n", nTotal/(1024.0f*1024.0f), nTotal ); } #ifdef VPROF_ENABLED ConMsg("\nVideo Memory Used:\n"); CVProfile *pProf = &g_VProfCurrentProfile; int prefixLen = V_strlen( "TexGroup_Global_" ); float total = 0.0f; for ( int i=0; i < pProf->GetNumCounters(); i++ ) { if ( pProf->GetCounterGroup( i ) == COUNTER_GROUP_TEXTURE_GLOBAL ) { float value = pProf->GetCounterValue( i ) * (1.0f/(1024.0f*1024.0f) ); total += value; const char *pName = pProf->GetCounterName( i ); if ( StringHasPrefix( pName, "TexGroup_Global_" ) ) { pName += prefixLen; } ConMsg( "%5.2f MB: %s\n", value, pName ); } } ConMsg("------------------\n"); ConMsg( "%5.2f MB: total\n", total ); #endif ConMsg( "\nHunk Memory Used:\n" ); Hunk_Print(); } /* =============================================================================== DEMO LOOP CONTROL =============================================================================== */ #ifndef DEDICATED //MOTODO move all demo commands to demoplayer //----------------------------------------------------------------------------- // Purpose: Gets number of valid demo names // Output : int //----------------------------------------------------------------------------- int Host_GetNumDemos() { int c = 0; #ifndef DEDICATED for ( int i = 0; i < MAX_DEMOS; ++i ) { const char *demoname = GetBaseLocalClient().demos[ i ]; if ( !demoname[ 0 ] ) break; ++c; } #endif return c; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void Host_PrintDemoList() { int count = Host_GetNumDemos(); #ifndef DEDICATED int next = GetBaseLocalClient().demonum; if ( next >= count || next < 0 ) { next = 0; } for ( int i = 0; i < MAX_DEMOS; ++i ) { const char *demoname = GetBaseLocalClient().demos[ i ]; if ( !demoname[ 0 ] ) break; bool isnextdemo = next == i ? true : false; DevMsg( "%3s % 2i : %20s\n", isnextdemo ? "-->" : " ", i, GetBaseLocalClient().demos[ i ] ); } #endif if ( !count ) { DevMsg( "No demos in list, use startdemos <demoname> <demoname2> to specify\n" ); } } #ifndef DEDICATED //----------------------------------------------------------------------------- // // Con commands related to demos, not available on dedicated servers // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Purpose: Specify list of demos for the "demos" command //----------------------------------------------------------------------------- CON_COMMAND( startdemos, "Play demos in demo sequence." ) { int c = args.ArgC() - 1; if (c > MAX_DEMOS) { Msg ("Max %i demos in demoloop\n", MAX_DEMOS); c = MAX_DEMOS; } Msg ("%i demo(s) in loop\n", c); for ( int i=1 ; i<c+1 ; i++ ) { Q_strncpy( GetBaseLocalClient().demos[i-1], args[i], sizeof(GetBaseLocalClient().demos[0]) ); } GetBaseLocalClient().demonum = 0; Host_PrintDemoList(); if ( !sv.IsActive() && !demoplayer->IsPlayingBack() ) { CL_NextDemo (); } else { GetBaseLocalClient().demonum = -1; } } //----------------------------------------------------------------------------- // Purpose: Return to looping demos, optional resume demo index //----------------------------------------------------------------------------- CON_COMMAND( demos, "Demo demo file sequence." ) { CClientState &cl = GetBaseLocalClient(); int oldn = cl.demonum; cl.demonum = -1; Host_Disconnect(false); cl.demonum = oldn; if (cl.demonum == -1) cl.demonum = 0; if ( args.ArgC() == 2 ) { int numdemos = Host_GetNumDemos(); if ( numdemos >= 1 ) { cl.demonum = clamp( Q_atoi( args[1] ), 0, numdemos - 1 ); DevMsg( "Jumping to %s\n", cl.demos[ cl.demonum ] ); } } Host_PrintDemoList(); CL_NextDemo (); } //----------------------------------------------------------------------------- // Purpose: Stop current demo //----------------------------------------------------------------------------- CON_COMMAND_F( stopdemo, "Stop playing back a demo.", FCVAR_DONTRECORD ) { if ( !demoplayer->IsPlayingBack() ) return; Host_Disconnect (true); } //----------------------------------------------------------------------------- // Purpose: Skip to next demo //----------------------------------------------------------------------------- CON_COMMAND( nextdemo, "Play next demo in sequence." ) { if ( args.ArgC() == 2 ) { int numdemos = Host_GetNumDemos(); if ( numdemos >= 1 ) { GetBaseLocalClient().demonum = clamp( Q_atoi( args[1] ), 0, numdemos - 1 ); DevMsg( "Jumping to %s\n", GetBaseLocalClient().demos[ GetBaseLocalClient().demonum ] ); } } Host_EndGame( false, "Moving to next demo..." ); } //----------------------------------------------------------------------------- // Purpose: Print out the current demo play order //----------------------------------------------------------------------------- CON_COMMAND( demolist, "Print demo sequence list." ) { Host_PrintDemoList(); } //----------------------------------------------------------------------------- // Purpose: Host_Soundfade_f //----------------------------------------------------------------------------- CON_COMMAND_F( soundfade, "Fade client volume.", FCVAR_SERVER_CAN_EXECUTE ) { float percent; float inTime, holdTime, outTime; if (args.ArgC() != 3 && args.ArgC() != 5) { Msg("soundfade <percent> <hold> [<out> <int>]\n"); return; } percent = clamp( atof(args[1]), 0.0f, 100.0f ); holdTime = MAX( 0.0f, atof(args[2]) ); inTime = 0.0f; outTime = 0.0f; if (args.ArgC() == 5) { outTime = MAX( 0.0f, atof(args[3]) ); inTime = MAX( 0.0f, atof( args[4]) ); } S_SoundFade( percent, holdTime, outTime, inTime ); } #endif // !DEDICATED #endif //----------------------------------------------------------------------------- // Shutdown the server //----------------------------------------------------------------------------- CON_COMMAND( killserver, "Shutdown the server." ) { Host_Disconnect(true); if ( !sv.IsDedicated() ) { // close network sockets and reopen if multiplayer game NET_SetMultiplayer( false ); NET_SetMultiplayer( !!( g_pMatchFramework->GetMatchTitle()->GetTitleSettingsFlags() & MATCHTITLE_SETTING_MULTIPLAYER ) ); } } // [hpe:jason] Enable ENGINE_VOICE for Cstrike 1.5, all platforms #if defined( CSTRIKE15 ) ConVar voice_vox( "voice_vox", "false", FCVAR_DEVELOPMENTONLY ); // Controls open microphone (no push to talk) settings #undef NO_ENGINE_VOICE #else #define NO_ENGINE_VOICE #endif #ifdef NO_ENGINE_VOICE ConVar voice_ptt( "voice_ptt", "-1.0", FCVAR_DEVELOPMENTONLY ); // Time when ptt key was released, 0 means to keep transmitting voice #endif #if !defined(DEDICATED) void Host_VoiceRecordStart_f(void) { #ifdef NO_ENGINE_VOICE voice_ptt.SetValue( 0 ); #else ConVarRef voice_vox( "voice_vox" ); if ( voice_vox.GetBool() == true ) return; int iSsSlot = GET_ACTIVE_SPLITSCREEN_SLOT(); if ( GetLocalClient( iSsSlot ).IsActive() ) { const char *pUncompressedFile = NULL; const char *pDecompressedFile = NULL; const char *pInputFile = NULL; if (voice_recordtofile.GetInt()) { pUncompressedFile = "voice_micdata.wav"; pDecompressedFile = "voice_decompressed.wav"; } if (voice_inputfromfile.GetInt()) { pInputFile = "voice_input.wav"; } #if !defined( NO_VOICE ) if (Voice_RecordStart(pUncompressedFile, pDecompressedFile, pInputFile)) { } #endif } #endif // #ifndef NO_ENGINE_VOICE } void Host_VoiceRecordStop_f( const CCommand &args ) { #ifdef NO_ENGINE_VOICE voice_ptt.SetValue( (float) Plat_FloatTime() ); #else ConVarRef voice_vox( "voice_vox" ); if ( voice_vox.GetBool() == true ) return; int iSsSlot = GET_ACTIVE_SPLITSCREEN_SLOT(); if ( GetLocalClient( iSsSlot ).IsActive() ) { #if !defined( NO_VOICE ) if (Voice_IsRecording()) { CL_SendVoicePacket(true); Voice_RecordStop(); } if ( args.ArgC() == 2 && V_strcasecmp( args[1], "force" ) == 0 ) { // do nothing } else { voice_vox.SetValue( 0 ); } #endif } #endif // #ifndef NO_ENGINE_VOICE } #endif // TERROR: adding a toggle for voice void Host_VoiceToggle_f( const CCommand &args ) { #ifdef NO_ENGINE_VOICE voice_ptt.SetValue( (float) ( voice_ptt.GetFloat() ? 0.0f : Plat_FloatTime() ) ); #endif #if !defined( DEDICATED ) && !defined( NO_ENGINE_VOICE ) #if !defined( NO_VOICE ) if ( GetBaseLocalClient().IsActive() ) { bool bToggle = false; if ( args.ArgC() == 2 && V_strcasecmp( args[1], "on" ) == 0 ) { bToggle = true; } if ( Voice_IsRecording() && bToggle == false ) { CL_SendVoicePacket(true); Voice_RecordStop(); } else if ( bToggle == true && Voice_IsRecording() == false ) { const char *pUncompressedFile = NULL; const char *pDecompressedFile = NULL; const char *pInputFile = NULL; if (voice_recordtofile.GetInt()) { pUncompressedFile = "voice_micdata.wav"; pDecompressedFile = "voice_decompressed.wav"; } if (voice_inputfromfile.GetInt()) { pInputFile = "voice_input.wav"; } Voice_RecordStart( pUncompressedFile, pDecompressedFile, pInputFile ); } } #endif #endif } //----------------------------------------------------------------------------- // Purpose: Wrapper for modelloader->Print() function call //----------------------------------------------------------------------------- CON_COMMAND( listmodels, "List loaded models." ) { modelloader->Print(); } /* ================== Host_IncrementCVar ================== */ CON_COMMAND_F( incrementvar, "Increment specified convar value.", FCVAR_DONTRECORD ) { if( args.ArgC() != 5 ) { Warning( "Usage: incrementvar varName minValue maxValue delta\n" ); return; } const char *varName = args[ 1 ]; if( !varName ) { ConDMsg( "Host_IncrementCVar_f without a varname\n" ); return; } ConVar *var = ( ConVar * )g_pCVar->FindVar( varName ); if( !var ) { ConDMsg( "cvar \"%s\" not found\n", varName ); return; } float currentValue = var->GetFloat(); float startValue = atof( args[ 2 ] ); float endValue = atof( args[ 3 ] ); float delta = atof( args[ 4 ] ); float newValue = currentValue + delta; if( newValue > endValue ) { newValue = startValue; } else if ( newValue < startValue ) { newValue = endValue; } // Conver incrementvar command to direct sets to avoid any problems with state in a demo loop. Cbuf_AddText( Cbuf_GetCurrentPlayer(), va("%s %f", varName, newValue) ); ConDMsg( "%s = %f\n", var->GetName(), newValue ); } //----------------------------------------------------------------------------- // Host_MultiplyCVar_f //----------------------------------------------------------------------------- CON_COMMAND_F( multvar, "Multiply specified convar value.", FCVAR_DONTRECORD ) { if (( args.ArgC() != 5 )) { Warning( "Usage: multvar varName minValue maxValue factor\n" ); return; } const char *varName = args[ 1 ]; if( !varName ) { ConDMsg( "multvar without a varname\n" ); return; } ConVar *var = ( ConVar * )g_pCVar->FindVar( varName ); if( !var ) { ConDMsg( "cvar \"%s\" not found\n", varName ); return; } float currentValue = var->GetFloat(); float startValue = atof( args[ 2 ] ); float endValue = atof( args[ 3 ] ); float factor = atof( args[ 4 ] ); float newValue = currentValue * factor; if( newValue > endValue ) { newValue = endValue; } else if ( newValue < startValue ) { newValue = startValue; } // Conver incrementvar command to direct sets to avoid any problems with state in a demo loop. Cbuf_AddText( Cbuf_GetCurrentPlayer(), va("%s %f", varName, newValue) ); ConDMsg( "%s = %f\n", var->GetName(), newValue ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CON_COMMAND( dumpstringtables, "Print string tables to console." ) { SV_PrintStringTables(); #ifndef DEDICATED CL_PrintStringTables(); #endif } CON_COMMAND( stringtabledictionary, "Create dictionary for current strings." ) { if ( !sv.IsActive() ) { Warning( "stringtabledictionary: only valid when running a map\n" ); return; } SV_CreateDictionary( sv.GetMapName() ); } // Register shared commands CON_COMMAND_F( quit, "Exit the engine.", FCVAR_NONE ) { if ( args.ArgC() > 1 && V_strcmp( args[ 1 ], "prompt" ) == 0 ) { Cbuf_AddText( Cbuf_GetCurrentPlayer(), "quit_prompt" ); return; } Host_Quit_f(); } static ConCommand cmd_exit("exit", Host_Quit_f, "Exit the engine."); #ifndef DEDICATED #ifdef VOICE_OVER_IP static ConCommand startvoicerecord("+voicerecord", Host_VoiceRecordStart_f); static ConCommand endvoicerecord("-voicerecord", Host_VoiceRecordStop_f); static ConCommand togglevoicerecord("voicerecord_toggle", Host_VoiceToggle_f); #endif // VOICE_OVER_IP #endif //----------------------------------------------------------------------------- // Purpose: Force a null pointer crash. useful for testing minidumps //----------------------------------------------------------------------------- CON_COMMAND_F( crash, "Cause the engine to crash (Debug!!)", FCVAR_CHEAT ) { Msg( "forcing crash\n" ); #if defined( _X360 ) DmCrashDump( FALSE ); #else char *p = 0; *p = 0; #endif } CON_COMMAND_F( spincycle, "Cause the engine to spincycle (Debug!!)", FCVAR_CHEAT ) { if ( args.ArgC() > 1 ) { const char *pParam = args.Arg( 1 ); if ( pParam && *pParam && pParam[ V_strlen( pParam ) - 1 ] == 's' ) { float flSeconds = V_atof( pParam ); if ( flSeconds > 0 ) { Msg( "Sleeping for %.3f seconds\n", flSeconds ); ThreadSleep( flSeconds * 1000 ); return; } } } int numCycles = ( args.ArgC() > 1 ) ? Q_atoi( args.Arg(1) ) : 10; Msg( "forcing spincycle for %d cycles\n", numCycles ); for( int k = 0; k < numCycles; ++ k ) { ( void ) RandomInt( 0, numCycles ); } } #if POSIX CON_COMMAND_F( forktest, "Cause the engine to fork and wait for child PID, parameter can be passed for requested exit code (Debug!!)", FCVAR_CHEAT ) { EndWatchdogTimer(); // End the watchdog in case child takes too long int nExitCodeRequested = ( args.ArgC() > 1 ) ? Q_atoi( args.Arg(1) ) : 0; pid_t pID = fork(); Msg( "forktest: Forked, pID = %d\n", (int) pID ); if ( pID == 0 ) // are we the forked child? { // // Enumerate all open file descriptors that are not #0 (stdin), #1 (stdout), #2 (stderr) // and close them all. // This will close all sockets and file handles that can result in process hanging // when network events occur on the machine and make NFS handles go bad. // if ( !CommandLine()->FindParm( "-forkfdskeepall" ) ) { FileFindHandle_t hFind = NULL; CUtlVector< int > arrHandlesToClose; for ( char const *szFileName = g_pFullFileSystem->FindFirst( "/proc/self/fd/*", &hFind ); szFileName && *szFileName; szFileName = g_pFullFileSystem->FindNext( hFind ) ) { int iFdHandle = Q_atoi( szFileName ); if ( ( iFdHandle > 2 ) && ( arrHandlesToClose.Find( iFdHandle ) == arrHandlesToClose.InvalidIndex() ) ) arrHandlesToClose.AddToTail( iFdHandle ); } g_pFullFileSystem->FindClose( hFind ); FOR_EACH_VEC( arrHandlesToClose, idxFd ) { ::close( arrHandlesToClose[idxFd] ); } if ( !CommandLine()->FindParm( "-forkfdskeepstd" ) ) { // Explicitly close #0 (stdin), #1 (stdout), #2 (stderr) and reopen them to /dev/null to consume 0-1-2 FDs (Posix spec requires to return lowest FDs first) ::close( 0 ); ::close( 1 ); ::close( 2 ); ::open("/dev/null", O_RDONLY); ::open("/dev/null", O_RDWR); ::open("/dev/null", O_RDWR); } } Msg( "Child finished successfully!\n" ); syscall( SYS_exit, nExitCodeRequested ); // don't do a normal c++ exit, don't want to call destructors, etc. Warning( "Forked child just called SYS_exit.\n" ); } else { int nRet = -1; int nWait = waitpid( pID, &nRet, 0 ); Msg( "Parent finished wait: %d, ret: %d, exit: %d, code: %d\n", nWait, nRet, WIFEXITED( nRet ), WEXITSTATUS( nRet ) ); } } #endif CON_COMMAND_F( flush, "Flush unlocked cache memory.", FCVAR_CHEAT ) { #if !defined( DEDICATED ) g_ClientDLL->InvalidateMdlCache(); #endif // DEDICATED serverGameDLL->InvalidateMdlCache(); g_pDataCache->Flush( true ); #if !defined( DEDICATED ) wavedatacache->Flush(); #endif } CON_COMMAND_F( flush_locked, "Flush unlocked and locked cache memory.", FCVAR_CHEAT ) { #if !defined( DEDICATED ) g_ClientDLL->InvalidateMdlCache(); #endif // DEDICATED serverGameDLL->InvalidateMdlCache(); g_pDataCache->Flush( false ); #if !defined( DEDICATED ) wavedatacache->Flush(); #endif } CON_COMMAND( cache_print, "cache_print [section]\nPrint out contents of cache memory." ) { const char *pszSection = NULL; if ( args.ArgC() == 2 ) { pszSection = args[ 1 ]; } g_pDataCache->OutputReport( DC_DETAIL_REPORT, pszSection ); } CON_COMMAND( cache_print_lru, "cache_print_lru [section]\nPrint out contents of cache memory." ) { const char *pszSection = NULL; if ( args.ArgC() == 2 ) { pszSection = args[ 1 ]; } g_pDataCache->OutputReport( DC_DETAIL_REPORT_LRU, pszSection ); } CON_COMMAND( cache_print_summary, "cache_print_summary [section]\nPrint out a summary contents of cache memory." ) { const char *pszSection = NULL; if ( args.ArgC() == 2 ) { pszSection = args[ 1 ]; } g_pDataCache->OutputReport( DC_SUMMARY_REPORT, pszSection ); } #if defined( _X360 ) CON_COMMAND( vx_datacache_list, "vx_datacache_list" ) { g_pDataCache->OutputReport( DC_DETAIL_REPORT_VXCONSOLE, NULL ); } #endif #ifndef _DEMO #ifndef DEDICATED // NOTE: As of shipping the 360 version of L4D, this command will not work correctly. See changelist 612757 (terror src) for why. CON_COMMAND_F( ss_connect, "If connected with available split screen slots, connects a split screen player to this machine.", FCVAR_DEVELOPMENTONLY ) { if ( host_state.max_splitscreen_players == 1 ) { if ( toolframework->InToolMode() ) { Msg( "Can't ss_connect, split screen not supported when running -tools mode.\n" ); } else { Msg( "Can't ss_connect, game does not support split screen.\n" ); } return; } if ( !GetBaseLocalClient().IsConnected() ) { Msg( "Can't ss_connect, not connected to game.\n" ); return; } int nSlot = 1; #ifndef DEDICATED while ( splitscreen->IsValidSplitScreenSlot( nSlot ) ) { ++nSlot; } #endif if ( nSlot >= host_state.max_splitscreen_players ) { Msg( "Can't ss_connect, no more split screen player slots!\n" ); return; } // Grab convars for next available slot CCLCMsg_SplitPlayerConnect_t msg; Host_BuildUserInfoUpdateMessage( nSlot, msg.mutable_convars(), false ); GetBaseLocalClient().m_NetChannel->SendNetMsg( msg ); } CON_COMMAND_F( ss_disconnect, "If connected with available split screen slots, connects a split screen player to this machine.", FCVAR_DEVELOPMENTONLY ) { if ( args.Source() == kCommandSrcNetClient ) { #ifndef DEDICATED host_client->SplitScreenDisconnect( args ); #endif return; } // Get the first valid slot int nSlot = -1; for ( int i = 1; i < host_state.max_splitscreen_players; ++i ) { if ( IS_VALID_SPLIT_SCREEN_SLOT( i ) ) { nSlot = i; break; } } if ( args.ArgC() > 1 ) { int cmdslot = Q_atoi( args.Arg( 1 ) ); if ( IS_VALID_SPLIT_SCREEN_SLOT( cmdslot ) ) { nSlot = cmdslot; } else { Msg( "Can't ss_disconnect, slot %d not active\n", cmdslot ); return; } } if ( ! IS_VALID_SPLIT_SCREEN_SLOT( nSlot ) ) { Msg( "Can't ss_disconnect, no split screen users active\n" ); return; } char buf[ 256 ]; Q_snprintf( buf, sizeof( buf ), "ss_disconnect %d\n", nSlot ); CCommand argsClient; argsClient.Tokenize( buf, kCommandSrcCode ); Cmd_ForwardToServer( argsClient ); #ifndef DEDICATED splitscreen->SetDisconnecting( nSlot, true ); #endif } #endif #endif #if 0 CON_COMMAND_F( infinite_loop, "Hang server with an infinite loop to test crash recovery.", FCVAR_CHEAT ) { for(;;) { ThreadSleep( 500 ); } } CON_COMMAND_F( null_ptr_references, "Produce a null ptr reference.", FCVAR_CHEAT ) { *((int *) 0 ) = 77; } #endif
26.816306
223
0.62857
5R33CH4
29ed430f7a00a248465bbbbea5676f293488c6f9
16,491
cpp
C++
libraries/entities/src/UpdateEntityOperator.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/entities/src/UpdateEntityOperator.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/entities/src/UpdateEntityOperator.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // UpdateEntityOperator.cpp // libraries/entities/src // // Created by Brad Hefta-Gaub on 8/11/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "EntityItem.h" #include "EntityTree.h" #include "EntityTreeElement.h" #include "UpdateEntityOperator.h" UpdateEntityOperator::UpdateEntityOperator(EntityTree* tree, EntityTreeElement* containingElement, EntityItem* existingEntity, const EntityItemProperties& properties) : _tree(tree), _existingEntity(existingEntity), _containingElement(containingElement), _containingElementCube(containingElement->getAACube()), _properties(properties), _entityItemID(existingEntity->getEntityItemID()), _foundOld(false), _foundNew(false), _removeOld(false), _dontMove(false), // assume we'll be moving _changeTime(usecTimestampNow()), _oldEntityCube(), _newEntityCube(), _wantDebug(false) { // caller must have verified existence of containingElement and oldEntity assert(_containingElement && _existingEntity); if (_wantDebug) { qDebug() << "UpdateEntityOperator::UpdateEntityOperator() -----------------------------"; } // Here we have a choice to make, do we want to "tight fit" the actual minimum for the // entity into the the element, or do we want to use the entities "relaxed" bounds // which can handle all potential rotations? // the getMaximumAACube is the relaxed form. _oldEntityCube = _existingEntity->getMaximumAACube(); _oldEntityBox = _oldEntityCube.clamp(0.0f, 1.0f); // clamp to domain bounds // If the old properties doesn't contain the properties required to calculate a bounding box, // get them from the existing entity. Registration point is required to correctly calculate // the bounding box. if (!_properties.registrationPointChanged()) { _properties.setRegistrationPoint(_existingEntity->getRegistrationPoint()); } // If the new properties has position OR dimension changes, but not both, we need to // get the old property value and set it in our properties in order for our bounds // calculations to work. if (_properties.containsPositionChange() && !_properties.containsDimensionsChange()) { glm::vec3 oldDimensionsInMeters = _existingEntity->getDimensions() * (float)TREE_SCALE; _properties.setDimensions(oldDimensionsInMeters); if (_wantDebug) { qDebug() << " ** setting properties dimensions - had position change, no dimension change **"; } } if (!_properties.containsPositionChange() && _properties.containsDimensionsChange()) { glm::vec3 oldPositionInMeters = _existingEntity->getPosition() * (float)TREE_SCALE; _properties.setPosition(oldPositionInMeters); if (_wantDebug) { qDebug() << " ** setting properties position - had dimensions change, no position change **"; } } // If our new properties don't have bounds details (no change to position, etc) or if this containing element would // be the best fit for our new properties, then just do the new portion of the store pass, since the change path will // be the same for both parts of the update bool oldElementBestFit = _containingElement->bestFitBounds(_properties); // if we don't have bounds properties, then use our old clamped box to determine best fit if (!_properties.containsBoundsProperties()) { oldElementBestFit = _containingElement->bestFitBounds(_oldEntityBox); if (_wantDebug) { qDebug() << " ** old Element best fit - no dimensions change, no position change **"; } } // For some reason we've seen a case where the original containing element isn't a best fit for the old properties // in this case we want to move it, even if the properties haven't changed. if (!_properties.containsBoundsProperties() && !oldElementBestFit) { _newEntityCube = _oldEntityCube; _removeOld = true; // our properties are going to move us, so remember this for later processing if (_wantDebug) { qDebug() << " **** UNUSUAL CASE **** no changes, but not best fit... consider it a move.... **"; } } else if (!_properties.containsBoundsProperties() || oldElementBestFit) { _foundOld = true; _newEntityCube = _oldEntityCube; _dontMove = true; if (_wantDebug) { qDebug() << " **** TYPICAL NO MOVE CASE ****"; qDebug() << " _properties.containsBoundsProperties():" << _properties.containsBoundsProperties(); qDebug() << " oldElementBestFit:" << oldElementBestFit; } } else { _newEntityCube = _properties.getMaximumAACubeInTreeUnits(); _removeOld = true; // our properties are going to move us, so remember this for later processing if (_wantDebug) { qDebug() << " **** TYPICAL MOVE CASE ****"; } } _newEntityBox = _newEntityCube.clamp(0.0f, 1.0f); // clamp to domain bounds if (_wantDebug) { qDebug() << " _entityItemID:" << _entityItemID; qDebug() << " _containingElementCube:" << _containingElementCube; qDebug() << " _oldEntityCube:" << _oldEntityCube; qDebug() << " _oldEntityBox:" << _oldEntityBox; qDebug() << " _newEntityCube:" << _newEntityCube; qDebug() << " _newEntityBox:" << _newEntityBox; qDebug() << "--------------------------------------------------------------------------"; } } UpdateEntityOperator::~UpdateEntityOperator() { } // does this entity tree element contain the old entity bool UpdateEntityOperator::subTreeContainsOldEntity(OctreeElement* element) { // We've found cases where the old entity might be placed in an element that is not actually the best fit // so when we're searching the tree for the old element, we use the known cube for the known containing element bool elementContainsOldBox = element->getAACube().contains(_containingElementCube); if (_wantDebug) { bool elementContainsOldCube = element->getAACube().contains(_oldEntityCube); qDebug() << "UpdateEntityOperator::subTreeContainsOldEntity()...."; qDebug() << " element->getAACube()=" << element->getAACube(); qDebug() << " _oldEntityCube=" << _oldEntityCube; qDebug() << " _oldEntityBox=" << _oldEntityBox; qDebug() << " elementContainsOldCube=" << elementContainsOldCube; qDebug() << " elementContainsOldBox=" << elementContainsOldBox; } return elementContainsOldBox; } bool UpdateEntityOperator::subTreeContainsNewEntity(OctreeElement* element) { bool elementContainsNewBox = element->getAACube().contains(_newEntityBox); if (_wantDebug) { bool elementContainsNewCube = element->getAACube().contains(_newEntityCube); qDebug() << "UpdateEntityOperator::subTreeContainsNewEntity()...."; qDebug() << " element->getAACube()=" << element->getAACube(); qDebug() << " _newEntityCube=" << _newEntityCube; qDebug() << " _newEntityBox=" << _newEntityBox; qDebug() << " elementContainsNewCube=" << elementContainsNewCube; qDebug() << " elementContainsNewBox=" << elementContainsNewBox; } return elementContainsNewBox; } bool UpdateEntityOperator::preRecursion(OctreeElement* element) { EntityTreeElement* entityTreeElement = static_cast<EntityTreeElement*>(element); // In Pre-recursion, we're generally deciding whether or not we want to recurse this // path of the tree. For this operation, we want to recurse the branch of the tree if // and of the following are true: // * We have not yet found the old entity, and this branch contains our old entity // * We have not yet found the new entity, and this branch contains our new entity // // Note: it's often the case that the branch in question contains both the old entity // and the new entity. bool keepSearching = false; // assume we don't need to search any more bool subtreeContainsOld = subTreeContainsOldEntity(element); bool subtreeContainsNew = subTreeContainsNewEntity(element); if (_wantDebug) { qDebug() << "---- UpdateEntityOperator::preRecursion().... ----"; qDebug() << " element=" << element->getAACube(); qDebug() << " subtreeContainsOld=" << subtreeContainsOld; qDebug() << " subtreeContainsNew=" << subtreeContainsNew; qDebug() << " _foundOld=" << _foundOld; qDebug() << " _foundNew=" << _foundNew; } // If we haven't yet found the old entity, and this subTreeContains our old // entity, then we need to keep searching. if (!_foundOld && subtreeContainsOld) { if (_wantDebug) { qDebug() << " OLD TREE CASE...."; qDebug() << " entityTreeElement=" << entityTreeElement; qDebug() << " _containingElement=" << _containingElement; } // If this is the element we're looking for, then ask it to remove the old entity // and we can stop searching. if (entityTreeElement == _containingElement) { if (_wantDebug) { qDebug() << " *** it's the OLD ELEMENT! ***"; } // If the containgElement IS NOT the best fit for the new entity properties // then we need to remove it, and the updateEntity below will store it in the // correct element. if (_removeOld) { if (_wantDebug) { qDebug() << " *** REMOVING from ELEMENT ***"; } // the entity knows what element it's in, so we remove it from that one // NOTE: we know we haven't yet added it to its new element because _removeOld is true EntityTreeElement* oldElement = _existingEntity->getElement(); oldElement->removeEntityItem(_existingEntity); _tree->setContainingElement(_entityItemID, NULL); if (oldElement != _containingElement) { qDebug() << "WARNING entity moved during UpdateEntityOperator recursion"; _containingElement->removeEntityItem(_existingEntity); } if (_wantDebug) { qDebug() << " *** REMOVING from MAP ***"; } } _foundOld = true; } else { // if this isn't the element we're looking for, then keep searching keepSearching = true; } } // If we haven't yet found the new entity, and this subTreeContains our new // entity, then we need to keep searching. if (!_foundNew && subtreeContainsNew) { if (_wantDebug) { qDebug() << " NEW TREE CASE...."; qDebug() << " entityTreeElement=" << entityTreeElement; qDebug() << " _containingElement=" << _containingElement; qDebug() << " entityTreeElement->bestFitBounds(_newEntityBox)=" << entityTreeElement->bestFitBounds(_newEntityBox); } // If this element is the best fit for the new entity properties, then add/or update it if (entityTreeElement->bestFitBounds(_newEntityBox)) { if (_wantDebug) { qDebug() << " *** THIS ELEMENT IS BEST FIT ***"; } EntityTreeElement* oldElement = _existingEntity->getElement(); // if we are the existing containing element, then we can just do the update of the entity properties if (entityTreeElement == oldElement) { if (_wantDebug) { qDebug() << " *** This is the same OLD ELEMENT ***"; } // set the entity properties and mark our element as changed. _existingEntity->setProperties(_properties); if (_wantDebug) { qDebug() << " *** set properties ***"; } } else { // otherwise, this is an add case. if (oldElement) { oldElement->removeEntityItem(_existingEntity); if (oldElement != _containingElement) { qDebug() << "WARNING entity moved during UpdateEntityOperator recursion"; } } entityTreeElement->addEntityItem(_existingEntity); _tree->setContainingElement(_entityItemID, entityTreeElement); _existingEntity->setProperties(_properties); // still need to update the properties! if (_wantDebug) { qDebug() << " *** ADDING ENTITY to ELEMENT and MAP and SETTING PROPERTIES ***"; } } _foundNew = true; // we found the new element _removeOld = false; // and it has already been removed from the old } else { keepSearching = true; } } if (_wantDebug) { qDebug() << " FINAL --- keepSearching=" << keepSearching; qDebug() << "--------------------------------------------------"; } return keepSearching; // if we haven't yet found it, keep looking } bool UpdateEntityOperator::postRecursion(OctreeElement* element) { // Post-recursion is the unwinding process. For this operation, while we // unwind we want to mark the path as being dirty if we changed it below. // We might have two paths, one for the old entity and one for the new entity. bool keepSearching = !_foundOld || !_foundNew; bool subtreeContainsOld = subTreeContainsOldEntity(element); bool subtreeContainsNew = subTreeContainsNewEntity(element); // As we unwind, if we're in either of these two paths, we mark our element // as dirty. if ((_foundOld && subtreeContainsOld) || (_foundNew && subtreeContainsNew)) { element->markWithChangedTime(); } // It's not OK to prune if we have the potential of deleting the original containig element. // because if we prune the containing element then new might end up reallocating the same memory later // and that will confuse our logic. // // it's ok to prune if: // 1) we're not removing the old // 2) we are removing the old, but this subtree doesn't contain the old // 3) we are removing the old, this subtree contains the old, but this element isn't a direct parent of _containingElement if (!_removeOld || !subtreeContainsOld || !element->isParentOf(_containingElement)) { EntityTreeElement* entityTreeElement = static_cast<EntityTreeElement*>(element); entityTreeElement->pruneChildren(); // take this opportunity to prune any empty leaves } return keepSearching; // if we haven't yet found it, keep looking } OctreeElement* UpdateEntityOperator::possiblyCreateChildAt(OctreeElement* element, int childIndex) { // If we're getting called, it's because there was no child element at this index while recursing. // We only care if this happens while still searching for the new entity location. // Check to see if if (!_foundNew) { float childElementScale = element->getScale() / 2.0f; // all of our children will be half our scale // Note: because the entity's bounds might have been clamped to the domain. We want to check if the // bounds of the clamped box would fit in our child elements. It may be the case that the actual // bounds of the element would hang outside of the child elements cells. bool entityWouldFitInChild = _newEntityBox.getLargestDimension() <= childElementScale; // if the scale of our desired cube is smaller than our children, then consider making a child if (entityWouldFitInChild) { int indexOfChildContainingNewEntity = element->getMyChildContaining(_newEntityBox); if (childIndex == indexOfChildContainingNewEntity) { return element->addChildAtIndex(childIndex);; } } } return NULL; }
44.093583
130
0.626281
ey6es
29ee6d4fa9ecc554257daf6e1755099f03259d47
4,950
cpp
C++
source/unittest/vmessageunit.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
2
2019-01-09T19:09:45.000Z
2019-04-02T17:53:49.000Z
source/unittest/vmessageunit.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
17
2015-01-07T02:05:04.000Z
2019-08-30T16:57:42.000Z
source/unittest/vmessageunit.cpp
xvela/code-vault
780dad2d2855e28d802a64baf781927b7edd9ed9
[ "MIT" ]
3
2016-04-06T19:01:11.000Z
2017-09-20T09:28:00.000Z
/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ /** @file */ #include "vmessageunit.h" #include "vmessage.h" #include "vcompactingdeque.h" class TestMessage; typedef VSharedPtr<TestMessage> TestMessagePtr; class TestMessage : public VMessage { public: static TestMessagePtr factory(); static TestMessagePtr factory(VMessageID messageID); virtual ~TestMessage(); virtual void send(const VString& /*sessionLabel*/, VBinaryIOStream& /*out*/) {} virtual void receive(const VString& /*sessionLabel*/, VBinaryIOStream& /*in*/) {} static int getNumMessagesConstructed() { return gNumMessagesConstructed; } static int getNumMessagesDestructed() { return gNumMessagesDestructed; } static void resetCounters() { gNumMessagesConstructed = 0; gNumMessagesDestructed = 0; } protected: TestMessage(); TestMessage(VMessageID messageID); private: static int gNextMessageUniqueID; static int gNumMessagesConstructed; static int gNumMessagesDestructed; int mUniqueID; }; int TestMessage::gNextMessageUniqueID = 1; int TestMessage::gNumMessagesConstructed = 0; int TestMessage::gNumMessagesDestructed = 0; // static TestMessagePtr TestMessage::factory() { return TestMessagePtr(new TestMessage()); } // static TestMessagePtr TestMessage::factory(VMessageID messageID) { return TestMessagePtr(new TestMessage(messageID)); } TestMessage::TestMessage() : VMessage(), mUniqueID(TestMessage::gNextMessageUniqueID++) { ++gNumMessagesConstructed; } TestMessage::TestMessage(VMessageID messageID) : VMessage(messageID), mUniqueID(TestMessage::gNextMessageUniqueID++) { ++gNumMessagesConstructed; } TestMessage::~TestMessage() { ++gNumMessagesDestructed; } class TestMessageFactory : public VMessageFactory { public: TestMessageFactory() {} virtual ~TestMessageFactory() {} /** Must be implemented by subclass, to simply instantiate a new VMessage object of a concrete VMessage subclass type. @return pointer to a new message object */ virtual VMessagePtr instantiateNewMessage(VMessageID messageID) const { return TestMessage::factory(messageID); } }; VMessageUnit::VMessageUnit(bool logOnSuccess, bool throwOnError) : VUnit("VMessageUnit", logOnSuccess, throwOnError) { } void VMessageUnit::run() { // Basic tests of VCompactingDeque, which is used only by VMessageQueue at this time. const size_t HWM = 10; const size_t LWM = 2; VCompactingDeque<int> q(HWM, LWM); q.push_back(10); q.push_back(20); q.push_back(30); q.push_back(40); q.push_back(50); q.push_back(60); q.push_back(70); q.push_back(80); q.push_back(90); q.push_back(100); q.push_back(110); q.push_back(120); VUNIT_ASSERT_EQUAL(q.front(), 10); VUNIT_ASSERT_EQUAL(q.back(), 120); VUNIT_ASSERT_EQUAL(q.size(), (size_t) 12); VUNIT_ASSERT_EQUAL(q.mHighWaterMark, (size_t) 0); // <- not a requirement but verifies expected internal behavior; mHighWaterMark only updated on pop VUNIT_ASSERT_EQUAL(q.mHighWaterMarkRequired, HWM); VUNIT_ASSERT_EQUAL(q.mLowWaterMarkRequired, LWM); q.pop_front(); q.pop_front(); q.pop_front(); VUNIT_ASSERT_EQUAL(q.front(), 40); VUNIT_ASSERT_EQUAL(q.back(), 120); VUNIT_ASSERT_EQUAL(q.size(), (size_t) 9); VUNIT_ASSERT_EQUAL(q.mHighWaterMark, (size_t) 12); VUNIT_ASSERT_EQUAL(q.mHighWaterMarkRequired, HWM); VUNIT_ASSERT_EQUAL(q.mLowWaterMarkRequired, LWM); q.pop_back(); q.pop_back(); q.pop_back(); VUNIT_ASSERT_EQUAL(q.front(), 40); VUNIT_ASSERT_EQUAL(q.back(), 90); VUNIT_ASSERT_EQUAL(q.size(), (size_t) 6); VUNIT_ASSERT_EQUAL(q.mHighWaterMark, (size_t) 12); VUNIT_ASSERT_EQUAL(q.mHighWaterMarkRequired, HWM); VUNIT_ASSERT_EQUAL(q.mLowWaterMarkRequired, LWM); q.pop_back(); q.pop_back(); q.pop_front(); q.pop_front(); VUNIT_ASSERT_EQUAL(q.front(), 60); VUNIT_ASSERT_EQUAL(q.back(), 70); VUNIT_ASSERT_EQUAL(q.size(), (size_t) 2); VUNIT_ASSERT_EQUAL(q.mHighWaterMark, (size_t) 0); // <- verifies that we triggered compaction at LWM == size == 2 VUNIT_ASSERT_EQUAL(q.mHighWaterMarkRequired, HWM); VUNIT_ASSERT_EQUAL(q.mLowWaterMarkRequired, LWM); q.push_front(42); q.push_back(43); q.pop_back(); VUNIT_ASSERT_EQUAL(q.front(), 42); VUNIT_ASSERT_EQUAL(q.back(), 70); VUNIT_ASSERT_EQUAL(q.size(), (size_t) 3); VUNIT_ASSERT_EQUAL(q.mHighWaterMark, (size_t) 4); // <- verifies that pop_back updated mHighWaterMark to max before pop VUNIT_ASSERT_EQUAL(q.mHighWaterMarkRequired, HWM); VUNIT_ASSERT_EQUAL(q.mLowWaterMarkRequired, LWM); }
30.745342
153
0.701818
xvela
29ef393e915a62bbb2a9ff1b232eae700508d2a0
2,162
cpp
C++
tests/System/ContextTests.cpp
GRIF-IT/Investcoin-CLI
975be82e79b3b253bbb9aca9179fc63cee9d25c0
[ "BSD-3-Clause" ]
2
2018-12-18T13:14:21.000Z
2019-03-11T17:16:40.000Z
tests/System/ContextTests.cpp
GRIF-IT/Investcoin-CLI
975be82e79b3b253bbb9aca9179fc63cee9d25c0
[ "BSD-3-Clause" ]
null
null
null
tests/System/ContextTests.cpp
GRIF-IT/Investcoin-CLI
975be82e79b3b253bbb9aca9179fc63cee9d25c0
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2018-2020, The Investcoin Project, GRIF-IT #include <System/Context.h> #include <System/Dispatcher.h> #include <System/Event.h> #include <System/InterruptedException.h> #include <System/Timer.h> #include <gtest/gtest.h> using namespace System; TEST(ContextTests, getReturnsResult) { Dispatcher dispatcher; Context<int> context(dispatcher, [&] { return 2; }); ASSERT_EQ(2, context.get()); } TEST(ContextTests, getRethrowsException) { Dispatcher dispatcher; Context<> context(dispatcher, [&] { throw std::string("Hi there!"); }); ASSERT_THROW(context.get(), std::string); } TEST(ContextTests, destructorIgnoresException) { Dispatcher dispatcher; ASSERT_NO_THROW(Context<>(dispatcher, [&] { throw std::string("Hi there!"); })); } TEST(ContextTests, interruptIsInterrupting) { Dispatcher dispatcher; Context<> context(dispatcher, [&] { if (dispatcher.interrupted()) { throw InterruptedException(); } }); context.interrupt(); ASSERT_THROW(context.get(), InterruptedException); } TEST(ContextTests, getChecksInterruption) { Dispatcher dispatcher; Event event(dispatcher); Context<int> context1(dispatcher, [&] { event.wait(); if (dispatcher.interrupted()) { return 11; } return 10; }); Context<int> context2(dispatcher, [&] { event.set(); return context1.get(); }); context2.interrupt(); ASSERT_EQ(11, context2.get()); } TEST(ContextTests, getIsInterruptible) { Dispatcher dispatcher; Event event1(dispatcher); Event event2(dispatcher); Context<int> context1(dispatcher, [&] { event2.wait(); if (dispatcher.interrupted()) { return 11; } return 10; }); Context<int> context2(dispatcher, [&] { event1.set(); return context1.get(); }); event1.wait(); context2.interrupt(); event2.set(); ASSERT_EQ(11, context2.get()); } TEST(ContextTests, destructorInterrupts) { Dispatcher dispatcher; bool interrupted = false; { Context<> context(dispatcher, [&] { if (dispatcher.interrupted()) { interrupted = true; } }); } ASSERT_TRUE(interrupted); }
20.205607
59
0.661887
GRIF-IT
29f0a2519c7598675d56ee178d8f7949131edfea
570
cpp
C++
Tea Bubble Edition/Tea Bubble Edition Project/CupDispenser.cpp
Skyway666/Tea-Bubble-Edition
3cffe55fa686ae34135e518bbc030de4040e13f7
[ "MIT" ]
null
null
null
Tea Bubble Edition/Tea Bubble Edition Project/CupDispenser.cpp
Skyway666/Tea-Bubble-Edition
3cffe55fa686ae34135e518bbc030de4040e13f7
[ "MIT" ]
null
null
null
Tea Bubble Edition/Tea Bubble Edition Project/CupDispenser.cpp
Skyway666/Tea-Bubble-Edition
3cffe55fa686ae34135e518bbc030de4040e13f7
[ "MIT" ]
null
null
null
#include "CupDispenser.h" #include "j1Entities.h" CupDispenser::CupDispenser(iPoint position): StaticEntity(position) { collider.x = position.x; collider.y = position.y; collider.w = 200; collider.h = 400; type = CUP_DISPENSER; // Static entity: Inicialization idle.PushBack({ 0,0, 200, 400 }); current_animation = &idle; // Given object: Inicialization empty_cup.current_animation.PushBack({ 0,0, 200, 300 }); empty_cup.type = EMPTY_CUP; } CupDispenser::~CupDispenser() { } void CupDispenser::Take(Player * player) { player->object = empty_cup; }
18.387097
69
0.712281
Skyway666
29f1474526e479ca91f2c6d82ff9006fb7936daa
1,767
cc
C++
benchmark/packet_source_benchmark.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
benchmark/packet_source_benchmark.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
benchmark/packet_source_benchmark.cc
epgdatacapbon/mirakc-arib
f50851ac1869599e95dcbefe115624b95e8274de
[ "Apache-2.0", "MIT" ]
null
null
null
#include <algorithm> #include <memory> #include <benchmark/benchmark.h> #include "packet_source.hh" namespace { class BenchmarkFile final : public File { public: static constexpr size_t kNumPackets = 10000; BenchmarkFile() { for (size_t i = 0; i < kBufSize; i += ts::PKT_SIZE) { ts::NullPacket.copyTo(reinterpret_cast<void*>(&buf_[i])); } } ~BenchmarkFile() override {} const std::string& path() const override { return path_; } ssize_t Read(uint8_t* buf, size_t len) override { auto remaining = kNumPackets - nread_; if (remaining == 0) { return 0; } auto ncopy = std::min(len, remaining); std::memcpy(buf, &buf_[nread_], ncopy); nread_ += ncopy; return static_cast<ssize_t>(ncopy); } ssize_t Write(uint8_t*, size_t) override { return 0; } bool Sync() override { return true; } bool Trunc(int64_t) override { return true; } int64_t Seek(int64_t, SeekMode) override { return 0; } private: static constexpr size_t kBufSize = ts::PKT_SIZE * kNumPackets; std::string path_ = "<benchmark>"; size_t nread_ = 0; uint8_t buf_[kBufSize]; }; class BenchmarkSink final : public PacketSink { public: BenchmarkSink() = default; ~BenchmarkSink() override = default; bool HandlePacket(const ts::TSPacket&) override { return true; } }; void BM_FileSource(benchmark::State& state) { auto file = std::make_unique<BenchmarkFile>(); auto sink = std::make_unique<BenchmarkSink>(); FileSource src(std::move(file)); src.Connect(std::move(sink)); for (auto _ : state) { src.FeedPackets(); } state.SetItemsProcessed( BenchmarkFile::kNumPackets * static_cast<int64_t>(state.iterations())); } } // namespace BENCHMARK(BM_FileSource);
21.54878
77
0.665535
epgdatacapbon
29f2c065c8d24f143156cf9da4a592bf00c6cc27
3,083
cpp
C++
ares/component/processor/v30mz/instructions-group.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/component/processor/v30mz/instructions-group.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/component/processor/v30mz/instructions-group.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
template<u32 size> auto V30MZ::instructionGroup1MemImm(bool sign) -> void { wait(1); modRM(); auto mem = getMemory<size>(); n16 imm = 0; if(sign) imm = (i8)fetch<Byte>(); else if(size == Byte) imm = fetch<Byte>(); else imm = fetch<Word>(); switch(modrm.reg) { case 0: setMemory<size>(ADD<size>(mem, imm)); break; case 1: setMemory<size>(OR <size>(mem, imm)); break; case 2: setMemory<size>(ADC<size>(mem, imm)); break; case 3: setMemory<size>(SBB<size>(mem, imm)); break; case 4: setMemory<size>(AND<size>(mem, imm)); break; case 5: setMemory<size>(SUB<size>(mem, imm)); break; case 6: setMemory<size>(XOR<size>(mem, imm)); break; case 7: (SUB<size>(mem, imm)); break; } } template<u32 size> auto V30MZ::instructionGroup2MemImm(u8 clocks, maybe<u8> imm) -> void { wait(clocks); modRM(); auto mem = getMemory<size>(); if(!imm) imm = fetch<Byte>(); switch(modrm.reg) { case 0: setMemory<size>(ROL<size>(mem, *imm)); break; case 1: setMemory<size>(ROR<size>(mem, *imm)); break; case 2: setMemory<size>(RCL<size>(mem, *imm)); break; case 3: setMemory<size>(RCR<size>(mem, *imm)); break; case 4: setMemory<size>(SHL<size>(mem, *imm)); break; case 5: setMemory<size>(SHR<size>(mem, *imm)); break; case 6: setMemory<size>(SAL<size>(mem, *imm)); break; case 7: setMemory<size>(SAR<size>(mem, *imm)); break; } } template<u32 size> auto V30MZ::instructionGroup3MemImm() -> void { modRM(); auto mem = getMemory<size>(); switch(modrm.reg) { case 0: wait(1); AND<size>(mem, fetch<size>()); break; //TEST case 1: wait(1); AND<size>(mem, fetch<size>()); break; //TEST (undocumented mirror) case 2: wait(1); setMemory<size>(NOT<size>(mem)); break; case 3: wait(1); setMemory<size>(NEG<size>(mem)); break; case 4: wait(3); setAccumulator<size * 2>(MULU<size>(getAccumulator<size>(), mem)); break; case 5: wait(3); setAccumulator<size * 2>(MULI<size>(getAccumulator<size>(), mem)); break; break; case 6: wait(size == Byte ? 15 : 23); setAccumulator<size * 2>(DIVU<size>(getAccumulator<size * 2>(), mem)); break; case 7: wait(size == Byte ? 17 : 24); setAccumulator<size * 2>(DIVI<size>(getAccumulator<size * 2>(), mem)); break; } } template<u32 size> auto V30MZ::instructionGroup4MemImm() -> void { modRM(); switch(modrm.reg) { case 0: //INC wait(1); setMemory<size>(INC<size>(getMemory<size>())); break; case 1: //DEC wait(1); setMemory<size>(DEC<size>(getMemory<size>())); break; case 2: //CALL wait(5); push(PC); PC = getMemory<Word>(); flush(); break; case 3: //CALLF wait(11); push(PS); push(PC); PC = getMemory<Word>(0); PS = getMemory<Word>(2); flush(); break; case 4: //JMP wait(4); PC = getMemory<Word>(); flush(); break; case 5: //JMPF wait(9); PC = getMemory<Word>(0); PS = getMemory<Word>(2); flush(); break; case 6: //PUSH push(getMemory<Word>()); break; case 7: //PUSH (undocumented mirror) push(getMemory<Word>()); break; } }
31.783505
117
0.606876
CasualPokePlayer
29f2c61daa34cae38e496e88d1eab93b6c9a8b10
8,619
cc
C++
rnacore/interval_map.cc
Shao-Group/meta-scallop
3c546900060e9544541e865604e235f49366803b
[ "BSD-3-Clause" ]
null
null
null
rnacore/interval_map.cc
Shao-Group/meta-scallop
3c546900060e9544541e865604e235f49366803b
[ "BSD-3-Clause" ]
2
2021-11-28T17:19:43.000Z
2022-01-17T09:02:55.000Z
rnacore/interval_map.cc
Shao-Group/meta-scallop
3c546900060e9544541e865604e235f49366803b
[ "BSD-3-Clause" ]
1
2020-06-22T12:31:00.000Z
2020-06-22T12:31:00.000Z
/* Part of Scallop Transcript Assembler (c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University. See LICENSE for licensing. */ #include "interval_map.h" int create_split(split_interval_map &imap, int32_t p) { SIMI it = imap.find(p); if(it == imap.end()) return 0; int32_t l = lower(it->first); int32_t r = upper(it->first); int32_t w = it->second; assert(l <= p); assert(r >= p); if(l == p || r == p) return 0; imap -= make_pair(ROI(l, r), w); imap += make_pair(ROI(l, p), w); imap += make_pair(ROI(p, r), w); return 0; } int compute_overlap(const split_interval_map &imap, int32_t p) { SIMI it = imap.find(p); if(it == imap.end()) return 0; return it->second; } SIMI locate_right_iterator(const split_interval_map &imap, int32_t x) { return imap.upper_bound(ROI(x - 1, x)); } ISMI locate_right_iterator(const interval_set_map &ism, int32_t x) { return ism.upper_bound(interval32(x - 1, x)); } SIMI locate_left_iterator(const split_interval_map &imap, int32_t x) { SIMI it = imap.lower_bound(ROI(x - 1, x)); if(it == imap.end() && it == imap.begin()) return it; if(it == imap.end()) it--; while(upper(it->first) > x) { if(it == imap.begin()) return imap.end(); it--; } return it; } ISMI locate_left_iterator(const interval_set_map &ism, int32_t x) { ISMI it = ism.lower_bound(interval32(x - 1, x)); if(it == ism.end() && it == ism.begin()) return it; if(it == ism.end()) it--; while(upper(it->first) > x) { if(it == ism.begin()) return ism.end(); it--; } return it; } PSIMI locate_boundary_iterators(const split_interval_map &imap, int32_t x, int32_t y) { SIMI lit, rit; lit = locate_right_iterator(imap, x); if(lit == imap.end() || upper(lit->first) > y) lit = imap.end(); rit = locate_left_iterator(imap, y); if(rit == imap.end() || lower(rit->first) < x) rit = imap.end(); if(lit == imap.end()) assert(rit == imap.end()); if(rit == imap.end() && lit != imap.end()) { //printf("x = %d, y = %d, lit = [%d, %d)\n", x, y, lower(lit->first), upper(lit->first)); assert(lit == imap.end()); } return PSIMI(lit, rit); } PISMI locate_boundary_iterators(const interval_set_map &ism, int32_t x, int32_t y) { ISMI lit, rit; lit = locate_right_iterator(ism, x); if(lit == ism.end() || upper(lit->first) > y) lit = ism.end(); rit = locate_left_iterator(ism, y); if(rit == ism.end() || lower(rit->first) < x) rit = ism.end(); if(lit == ism.end()) assert(rit == ism.end()); if(rit == ism.end() && lit != ism.end()) { //printf("x = %d, y = %d, lit = [%d, %d)\n", x, y, lower(lit->first), upper(lit->first)); assert(lit == ism.end()); } return PISMI(lit, rit); } int32_t compute_max_overlap(const split_interval_map &imap, SIMI &p, SIMI &q) { if(p == imap.end()) return 0; int32_t s = 0; for(SIMI it = p; it != q; it++) { int32_t x = it->second; if(x > s) s = x; } if(q != imap.end()) { int32_t x = q->second; if(x > s) s = x; } return s; } int32_t compute_sum_overlap(const split_interval_map &imap, SIMI &p, SIMI &q) { if(p == imap.end()) return 0; int32_t s = 0; for(SIMI it = p; it != q; it++) { int l = lower(it->first); int u = upper(it->first); assert(u > l); //printf(" AA add [%d, %d) : %d\n", lower(it->first), upper(it->first), it->second); s += (u - l) * it->second; } if(q != imap.end()) { //printf(" BB add [%d, %d) : %d\n", lower(q->first), upper(q->first), q->second); s += (upper(q->first) - lower(q->first)) * q->second; } return s; } int32_t compute_coverage(const split_interval_map &imap, SIMI &p, SIMI &q) { if(p == imap.end()) return 0; int32_t s = 0; for(SIMI it = p; it != q; it++) { s += upper(it->first) - lower(it->first); } if(q != imap.end()) s += upper(q->first) - lower(q->first); return s; } int evaluate_rectangle(const split_interval_map &imap, int ll, int rr, double &ave, double &dev, double &max) { ave = 0; dev = 1; max = 0; PSIMI pei = locate_boundary_iterators(imap, ll, rr); SIMI lit = pei.first, rit = pei.second; if(lit == imap.end()) return 0; if(rit == imap.end()) return 0; max = 1.0 * compute_max_overlap(imap, lit, rit); ave = 1.0 * compute_sum_overlap(imap, lit, rit) / (rr - ll); //printf("compute average %d-%d = %.2lf\n", ll, rr, ave); double var = 0; for(SIMI it = lit; ; it++) { assert(upper(it->first) > lower(it->first)); var += (it->second - ave) * (it->second - ave) * (upper(it->first) - lower(it->first)); if(it == rit) break; } dev = sqrt(var / (rr - ll)); //if(dev < 1.0) dev = 1.0; return 0; } int evaluate_triangle(const split_interval_map &imap, int ll, int rr, double &ave, double &dev) { ave = 0; dev = 1.0; PSIMI pei = locate_boundary_iterators(imap, ll, rr); SIMI lit = pei.first, rit = pei.second; if(lit == imap.end()) return 0; if(rit == imap.end()) return 0; vector<double> xv; vector<double> yv; double xm = 0; double ym = 0; for(SIMI it = lit; ; it++) { assert(upper(it->first) > lower(it->first)); double xi = (lower(it->first) + upper(it->first)) / 2.0; double yi = it->second; xv.push_back(xi); yv.push_back(yi); xm += xi; ym += yi; if(it == rit) break; } xm /= xv.size(); ym /= yv.size(); double f1 = 0; double f2 = 0; for(int i = 0; i < xv.size(); i++) { f1 += (xv[i] - xm) * (yv[i] - ym); f2 += (xv[i] - xm) * (xv[i] - xm); } double b1 = f1 / f2; double b0 = ym - b1 * xm; double a1 = b1 * rr + b0; double a0 = b1 * ll + b0; ave = (a1 > a0) ? a1 : a0; double var = 0; for(SIMI it = lit; ; it++) { assert(upper(it->first) > lower(it->first)); double xi = (upper(it->first) + lower(it->first)) / 2.0; double yi = b1 * xi + b0; var += (it->second - yi) * (it->second - yi) * (upper(it->first) - lower(it->first)); if(it == rit) break; } dev = sqrt(var / (rr - ll)); if(dev < 1.0) dev = 1.0; return 0; } set<int> get_overlapped_set(const interval_set_map &ism, int32_t x, int32_t y) { PISMI pei = locate_boundary_iterators(ism, x, y); ISMI lit = pei.first, rit = pei.second; set<int> s; if(lit == ism.end()) return s; if(rit == ism.end()) return s; for(ISMI it = lit; ; it++) { assert(upper(it->first) > lower(it->first)); s.insert((it->second).begin(), (it->second).end()); if(it == rit) break; } return s; } int test_split_interval_map() { split_interval_map imap; imap += make_pair(ROI(6, 7), 3); imap += make_pair(ROI(1, 3), 3); imap += make_pair(ROI(1, 2), 1); imap += make_pair(ROI(2, 5), 2); create_split(imap, 4); SIMI it; for(it = imap.begin(); it != imap.end(); it++) { printf("interval: [%d,%d) -> %d\n", lower(it->first), upper(it->first), it->second); } for(int i = 1; i <= 7; i++) { it = imap.find(i); if(it == imap.end()) { printf("find %d: does not exist\n", i); } else { printf("find %d: [%d,%d) -> %d\n", i, lower(it->first), upper(it->first), it->second); } } for(int i = 1; i <= 7; i++) { it = imap.lower_bound(ROI(i, i + 1)); if(it == imap.end()) { printf("lower bound %d: does not exist\n", i); } else { printf("lower bound %d: [%d,%d) -> %d\n", i, lower(it->first), upper(it->first), it->second); } } for(int i = 1; i <= 7; i++) { it = imap.upper_bound(ROI(i, i + 1)); if(it == imap.end()) { printf("upper bound %d: does not exist\n", i); } else { printf("upper bound %d: [%d,%d) -> %d\n", i, lower(it->first), upper(it->first), it->second); } } for(int i = 0; i <= 8; i++) { for(int j = i; j <= 8; j++) { pair<SIMI, SIMI> p = locate_boundary_iterators(imap, i, j); int s = compute_coverage(imap, p.first, p.second); printf("coverage [%d,%d) = %d\n", i, j, s); } } return 0; } int test_interval_set_map() { interval_set_map ism; int v1[] = {1, 2}; int v2[] = {1, 2, 3}; int v3[] = {3, 4}; set<int> s1(v1, v1 + 2); set<int> s2(v2, v2 + 3); set<int> s3(v3, v3 + 2); ism += make_pair(interval32(1, 2), s1); ism += make_pair(interval32(2, 3), s2); ism += make_pair(interval32(1, 5), s3); for(ISMI it = ism.begin(); it != ism.end(); it++) { interval32 iv = it->first; set<int> s = it->second; printf("[%d, %d) -> ", lower(iv), upper(iv)); for(set<int>::iterator x = s.begin(); x != s.end(); x++) { printf("%d ", *x); } printf("\n"); } return 0; } int print_interval_set_map(const interval_set_map &ism) { for(ISMI it = ism.begin(); it != ism.end(); it++) { const interval32 &iv = it->first; const set<int> &s = it->second; printf("[%d, %d) -> ", lower(iv), upper(iv)); for(set<int>::const_iterator x = s.begin(); x != s.end(); x++) { printf("%d ", *x); } printf("\n"); } return 0; }
22.1
109
0.576053
Shao-Group
29f32cf47cdbccbe32468f05bfb1a9c3bbafd409
3,987
hpp
C++
include/boost/beast/core/close_socket.hpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
include/boost/beast/core/close_socket.hpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
include/boost/beast/core/close_socket.hpp
bebuch/beast
2454d671653844d8435f4f066946a7751a758db7
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2018 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_CLOSE_SOCKET_HPP #define BOOST_BEAST_CLOSE_SOCKET_HPP #include <boost/beast/core/detail/config.hpp> #include <boost/beast/core/detail/static_const.hpp> #include <boost/asio/basic_socket.hpp> namespace boost { namespace beast { /** Default socket close function. This function is not meant to be called directly. Instead, it is called automatically when using @ref close_socket. To enable closure of user-defined types or classes derived from a particular user-defined type, this function should be overloaded in the corresponding namespace for the type in question. @see close_socket */ template<class Protocol BOOST_ASIO_SVC_TPARAM> void beast_close_socket( net::basic_socket<Protocol BOOST_ASIO_SVC_TPARAM>& sock) { boost::system::error_code ec; sock.close(ec); } namespace detail { struct close_socket_impl { template<class T> void operator()(T& t) const { using beast::beast_close_socket; beast_close_socket(t); } }; } // detail /** Close a socket or socket-like object. This function attempts to close an object representing a socket. In this context, a socket is an object for which an unqualified call to the function `void beast_close_socket(Socket&)` is well-defined. The function `beast_close_socket` is a <em>customization point</em>, allowing user-defined types to provide an algorithm for performing the close operation by overloading this function for the type in question. Since the customization point is a function call, the normal rules for finding the correct overload are applied including the rules for argument-dependent lookup ("ADL"). This permits classes derived from a type for which a customization is provided to inherit the customization point. An overload for the networking class template `net::basic_socket` is provided, which implements the close algorithm for all socket-like objects (hence the name of this customization point). When used in conjunction with @ref get_lowest_layer, a generic algorithm operating on a layered stream can perform a closure of the underlying socket without knowing the exact list of concrete types. @par Example 1 The following generic function synchronously sends a message on the stream, then closes the socket. @code template <class WriteStream> void hello_and_close (WriteStream& stream) { net::write(stream, net::const_buffer("Hello, world!", 13)); close_socket(get_lowest_layer(stream)); } @endcode To enable closure of user defined types, it is necessary to provide an overload of the function `beast_close_socket` for the type. @par Example 2 The following code declares a user-defined type which contains a private socket, and provides an overload of the customization point which closes the private socket. @code class my_socket { net::ip::tcp::socket sock_; public: my_socket(net::io_context& ioc) : sock_(ioc) { } friend void beast_close_socket(my_socket& s) { error_code ec; s.sock_.close(ec); // ignore the error } }; @endcode @param sock The socket to close. If the customization point is not defined for the type of this object, or one of its base classes, then a compiler error results. @see beast_close_socket */ #if BOOST_BEAST_DOXYGEN template<class Socket> void close_socket(Socket& sock); #else BOOST_BEAST_INLINE_VARIABLE(close_socket, detail::close_socket_impl) #endif } // beast } // boost #endif
29.753731
79
0.717081
bebuch
29f3635c8893e4558c5adf85872d9210a3912b6f
314
hpp
C++
template/for-function/main/hello-greet.hpp
research-note/deep-learning-from-scratch-using-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
2
2021-08-15T12:38:41.000Z
2021-08-15T12:38:51.000Z
template/for-function/main/hello-greet.hpp
research-note/deep-learning-from-scratch-using-modern-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
null
null
null
template/for-function/main/hello-greet.hpp
research-note/deep-learning-from-scratch-using-modern-cpp
5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1
[ "MIT" ]
null
null
null
/* * Build obj linking with cc_library file example. * * Copyright Bazel organization * */ #ifndef CPP_TUTORIAL_STAGE3_MAIN_HELLO_GREET_H_ #define CPP_TUTORIAL_STAGE3_MAIN_HELLO_GREET_H_ #include <string> std::string get_greet(const std::string &thing); #endif // CPP_TUTORIAL_STAGE3_MAIN_HELLO_GREET_H_
19.625
50
0.796178
research-note
29f56e4cb49d77ea4773b13f0548b0e9cfb8b5e1
1,224
cpp
C++
lab21/3 - istream.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-01-24T14:04:45.000Z
2019-01-24T14:04:45.000Z
lab21/3 - istream.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-01-24T18:32:45.000Z
2019-01-28T04:10:28.000Z
lab21/3 - istream.cpp
uiowa-cs-3210-0001/cs3210-labs
d6263d719a45257ba056a1ead7cc3dd428d377f3
[ "MIT" ]
1
2019-02-07T00:28:20.000Z
2019-02-07T00:28:20.000Z
#include <iostream> using namespace std; template< typename T > T read( std::istream& in ) { T x; in >> x; return x; } int main() { // auto c = read<char>( std::cin ); // std::cout << "Read: " << c << endl; // std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); // auto c2 = read<char>( std::cin ); // std::cout << "Read: " << c2 << endl; // auto s = read<string>( std::cin ); // std::cout << "Read: " << s << endl; // std::string line; // std::getline( std::cin, line ); // std::cout << "Read: " << line << endl; // auto p = read<Point>( std::cin ); // std::cout << "Read: " << p << endl; } // struct Point { int x, y; }; // std::istream& operator>>( std::istream& in, Point& result ) // { // char lparen, comma, rparen; // Point p; // if ( !( in >> lparen >> p.x >> comma >> p.y >> rparen ) // || lparen != '(' || comma != ',' || rparen != ')' // ) // throw std::runtime_error( "Error reading Point from stream" ); // result = p; // return in; // } // std::ostream& operator<<( std::ostream& out, Point const& p ) // { // return out << '(' << p.x << ',' << p.y << ')'; // }
23.09434
76
0.46732
uiowa-cs-3210-0001
29f92b44d2d20829231a22dff4e7f6c31aabd4f6
4,941
cpp
C++
test/trie.cpp
DldFw/ethereum
d45dc929b594add85d527236830037f01da0e8a3
[ "MIT" ]
null
null
null
test/trie.cpp
DldFw/ethereum
d45dc929b594add85d527236830037f01da0e8a3
[ "MIT" ]
null
null
null
test/trie.cpp
DldFw/ethereum
d45dc929b594add85d527236830037f01da0e8a3
[ "MIT" ]
null
null
null
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ /** @file trie.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 * Trie test functions. */ #include <random> #include <TrieHash.h> #include <TrieDB.h> #include <MemTrie.h> using namespace std; using namespace eth; int trieTest() { { BasicMap m; GenericTrieDB<BasicMap> t(&m); t.init(); // initialise as empty tree. cout << t; cout << m; cout << t.root() << endl; cout << hash256(StringMap()) << endl; t.insert(string("tesz"), string("test")); cout << t; cout << m; cout << t.root() << endl; StringMap test1; test1["test"] = "test"; //cout << hash256({{"test", "test"}}) << endl; cout << hash256(test1) << endl; t.insert(string("tesa"), string("testy")); cout << t; cout << m; cout << t.root() << endl; StringMap test2; test2["test"] = "test"; test2["te"] = "testy"; cout << hash256(test2) << endl; //cout << hash256({{"test", "test"}, {"te", "testy"}}) << endl; cout << t.at(string("test")) << endl; cout << t.at(string("te")) << endl; cout << t.at(string("t")) << endl; t.remove(string("te")); cout << m; cout << t.root() << endl; StringMap test3; test3["test"] = "test"; cout << hash256(test3) << endl; t.remove(string("test")); cout << m; cout << t.root() << endl; cout << hash256(StringMap()) << endl; } { BasicMap m; GenericTrieDB<BasicMap> t(&m); t.init(); // initialise as empty tree. t.insert(string("a"), string("A")); t.insert(string("b"), string("B")); cout << t; cout << m; cout << t.root() << endl; StringMap test; test["b"] = "B"; test["a"] = "A"; cout << hash256(test) << endl; cout << RLP(rlp256({{"b", "B"}, {"a", "A"}})) << endl; } { MemTrie t; t.insert("dog", "puppy"); cout << hex << t.hash256() << endl; cout << RLP(t.rlp()) << endl; } { MemTrie t; t.insert("bed", "d"); t.insert("be", "e"); cout << hex << t.hash256() << endl; cout << RLP(t.rlp()) << endl; } { StringMap test; test["dog"] = "puppy"; test["doe"] = "reindeer"; cout << hex << hash256(test) << endl; //cout << hex << hash256({{"dog", "puppy"}, {"doe", "reindeer"}}) << endl; MemTrie t; t.insert("dog", "puppy"); t.insert("doe", "reindeer"); cout << hex << t.hash256() << endl; cout << RLP(t.rlp()) << endl; cout << asHex(t.rlp()) << endl; } { BasicMap m; GenericTrieDB<BasicMap> d(&m); d.init(); // initialise as empty tree. MemTrie t; StringMap s; auto add = [&](char const* a, char const* b) { d.insert(string(a), string(b)); t.insert(a, b); s[a] = b; cout << endl << "-------------------------------" << endl; cout << a << " -> " << b << endl; cout << d; cout << m; cout << d.root() << endl; cout << hash256(s) << endl; assert(t.hash256() == hash256(s)); assert(d.root() == hash256(s)); for (auto const& i: s) { (void)i; assert(t.at(i.first) == i.second); assert(d.at(i.first) == i.second); } }; auto remove = [&](char const* a) { s.erase(a); t.remove(a); d.remove(string(a)); cout << endl << "-------------------------------" << endl; cout << "X " << a << endl; cout << d; cout << m; cout << d.root() << endl; cout << hash256(s) << endl; assert(t.at(a).empty()); assert(d.at(string(a)).empty()); assert(t.hash256() == hash256(s)); assert(d.root() == hash256(s)); for (auto const& i: s) { (void)i; assert(t.at(i.first) == i.second); assert(d.at(i.first) == i.second); } }; add("dogglesworth", "cat"); add("doe", "reindeer"); remove("dogglesworth"); add("horse", "stallion"); add("do", "verb"); add("doge", "coin"); remove("horse"); remove("do"); remove("doge"); remove("doe"); for (int a = 0; a < 20; ++a) { StringMap m; for (int i = 0; i < 20; ++i) { auto k = randomWord(); auto v = toString(i); m.insert(make_pair(k, v)); t.insert(k, v); d.insert(k, v); assert(hash256(m) == t.hash256()); assert(hash256(m) == d.root()); } while (!m.empty()) { auto k = m.begin()->first; d.remove(k); t.remove(k); m.erase(k); assert(hash256(m) == t.hash256()); assert(hash256(m) == d.root()); } } } return 0; }
23.641148
76
0.534305
DldFw
29fac8aa4a0c3a20a2793ed67843be19f73c7680
3,585
cpp
C++
EU4toV2/Source/Mappers/ProvinceMappings/ProvinceMapper.cpp
ParadoxGameConverters/EU4toVic2
17a61d5662da02abcb976403cb50da365ef7061d
[ "MIT" ]
42
2018-12-22T03:59:43.000Z
2022-02-03T10:45:42.000Z
EU4toV2/Source/Mappers/ProvinceMappings/ProvinceMapper.cpp
DrDudelsack/EU4toVic2
06da665b3eaa6e14d240f65f02caf9ffb7085b5b
[ "MIT" ]
336
2018-12-22T17:15:27.000Z
2022-03-02T11:19:32.000Z
EU4toV2/Source/Mappers/ProvinceMappings/ProvinceMapper.cpp
klorpa/EU4toVic2
e3068eb2aa459f884c1929f162d0047a4cb5f4d4
[ "MIT" ]
56
2018-12-22T19:13:23.000Z
2022-01-01T23:08:53.000Z
#include "ProvinceMapper.h" #include "Configuration.h" #include "GameVersion.h" #include "Log.h" #include "ParserHelpers.h" #include "ProvinceMappingsVersion.h" #include <filesystem> #include <fstream> #include <stdexcept> namespace fs = std::filesystem; #include "CommonRegexes.h" mappers::ProvinceMapper::ProvinceMapper(): colonialRegionsMapper(std::make_unique<EU4::ColonialRegions>()) { Log(LogLevel::Info) << "Parsing province mappings"; registerKeys(); if (theConfiguration.isVN()) parseFile("configurables/vn_province_mappings.txt"); else if (theConfiguration.isHpmEnabled()) parseFile("configurables/HPM/province_mappings.txt"); else parseFile("configurables/province_mappings.txt"); clearRegisteredKeywords(); const auto& mappings = getBestMappingsVersion(theConfiguration.getEU4Version()); createMappings(mappings); } mappers::ProvinceMapper::ProvinceMapper(std::istream& mainStream, std::istream& colonialStream, const Configuration& testConfiguration): colonialRegionsMapper(std::make_unique<EU4::ColonialRegions>(colonialStream)) { registerKeys(); parseStream(mainStream); clearRegisteredKeywords(); const auto& mappings = getBestMappingsVersion(testConfiguration.getEU4Version()); createMappings(mappings); } void mappers::ProvinceMapper::registerKeys() { registerRegex(R"([\d.]+)", [this](const std::string& versionString, std::istream& theStream) { ProvinceMappingsVersion mappingVersion(versionString, theStream); mappingVersions.insert(std::make_pair(mappingVersion.getVersion(), mappingVersion)); }); registerRegex(commonItems::catchallRegex, commonItems::ignoreItem); } std::optional<std::string> mappers::ProvinceMapper::getColonialRegionForProvince(int province) const { return colonialRegionsMapper->getColonialRegionForProvince(province); } mappers::ProvinceMappingsVersion mappers::ProvinceMapper::getBestMappingsVersion(const GameVersion& usedEU4Version) const { for (auto mappingVersion = mappingVersions.rbegin(); mappingVersion != mappingVersions.rend(); ++mappingVersion) { if (usedEU4Version >= mappingVersion->first) { Log(LogLevel::Info) << "\t-> Using version " << mappingVersion->first << " mappings"; return mappingVersion->second; } } throw std::range_error("Could not find matching province mappings for EU4 version"); } void mappers::ProvinceMapper::createMappings(const ProvinceMappingsVersion& provinceMappingsVersion) { for (const auto& mapping: provinceMappingsVersion.getMappings()) { // ignore deliberate errors where we leave mappings without keys (asian wasteland comes to mind): if (mapping.getVic2Provinces().empty()) continue; if (mapping.getEU4Provinces().empty()) continue; for (const auto& vic2Number: mapping.getVic2Provinces()) { if (vic2Number) vic2ToEU4ProvinceMap.insert(std::make_pair(vic2Number, mapping.getEU4Provinces())); } for (const auto& eu4Number: mapping.getEU4Provinces()) { if (eu4Number) eu4ToVic2ProvinceMap.insert(std::make_pair(eu4Number, mapping.getVic2Provinces())); } } } std::set<int> mappers::ProvinceMapper::getVic2ProvinceNumbers(const int eu4ProvinceNumber) const { const auto& mapping = eu4ToVic2ProvinceMap.find(eu4ProvinceNumber); if (mapping != eu4ToVic2ProvinceMap.end()) return mapping->second; else return std::set<int>(); } std::set<int> mappers::ProvinceMapper::getEU4ProvinceNumbers(int vic2ProvinceNumber) const { const auto& mapping = vic2ToEU4ProvinceMap.find(vic2ProvinceNumber); if (mapping != vic2ToEU4ProvinceMap.end()) return mapping->second; else return std::set<int>(); }
33.504673
136
0.772106
ParadoxGameConverters
29ffd6be90971a18707ad2d2fc2940dc3bd78f52
2,514
cpp
C++
samples/Random/src/RandomSample.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
50
2015-06-01T19:23:24.000Z
2021-12-22T02:14:23.000Z
samples/Random/src/RandomSample.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
109
2015-07-20T07:43:03.000Z
2021-01-31T21:52:36.000Z
samples/Random/src/RandomSample.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
9
2015-07-02T21:36:20.000Z
2019-10-19T04:18:02.000Z
// Oak Nut include #include <onut/PrimitiveBatch.h> #include <onut/Random.h> #include <onut/Renderer.h> #include <onut/Settings.h> #include <onut/SpriteBatch.h> void initSettings() { oSettings->setGameName("Random Sample"); oSettings->setIsRetroMode(true); // So we can see the points bigger oSettings->setRetroResolution({200, 200}); } void init() { } void shutdown() { } void update() { } void render() { oRenderer->clear({0, 0, 0, 1}); oPrimitiveBatch->begin(OPrimitivePointList); if (ORandBool()) oPrimitiveBatch->draw(Vector2(10, 25), Color(0, 1, 0, 1)); // 50% if (ORandBool(.25f)) oPrimitiveBatch->draw(Vector2(20, 25), Color(0, 1, 0, 1)); // 25% for (int i = 0; i < 100; ++i) { oPrimitiveBatch->draw(Vector2(ORandInt(10) * 10, 5), Color(1, 1, 0, 1)); oPrimitiveBatch->draw(Vector2(ORandInt(5, 10) * 10, 10), Color(1, 1, 0, 1)); oPrimitiveBatch->draw(Vector2(ORandInt(100), 15), Color(0, 1, 1, 1)); oPrimitiveBatch->draw(Vector2(ORandInt(50, 100), 20), Color(0, 1, 1, 1)); oPrimitiveBatch->draw(ORandVector2(Vector2(25, 25)) + Vector2(0, 30), Color(1, 0, 1, 1)); oPrimitiveBatch->draw(ORandVector2(Vector2(10, 10), Vector2(25, 25)) + Vector2(30, 30), Color(1, 0, 1, 1)); oPrimitiveBatch->draw(onut::randCircle(Vector2(50, 100), 25), Color(1, 1, 1, 1)); oPrimitiveBatch->draw(onut::randCircleEdge(Vector2(150, 100), 25), Color(1, 1, 1, 1)); } oPrimitiveBatch->end(); oSpriteBatch->begin(); oSpriteBatch->drawRect(nullptr, Rect(0, 150, 20, 12), ORandColor()); oSpriteBatch->drawRect(nullptr, Rect(21, 150, 20, 12), ORandColor(.5f)); oSpriteBatch->drawRect(nullptr, Rect(42, 150, 20, 12), ORandColor(Color(1, 0, 1))); oSpriteBatch->drawRect(nullptr, Rect(63, 150, 20, 12), ORandColor(Color(0, 1, 0), Color(1, 0, 0))); oSpriteBatch->drawRect(nullptr, Rect(63, 150, 20, 12), ORandColor(Color(0, 1, 0), Color(1, 0, 0))); onut::Palette palette = { OColorHex(43A08E), OColorHex(B3E0CB), OColorHex(EE5351), OColorHex(D19A8E), OColorHex(DBC9A3) }; float x = 0; for (auto c : palette) { oSpriteBatch->drawRect(nullptr, Rect(x, 170, 20, 12), c); x += 21; } oSpriteBatch->drawRect(nullptr, Rect(0, 183, 20, 12), ORandColor(palette)); oSpriteBatch->drawRect(nullptr, Rect(21, 183, 20, 12), ORandColor(palette, .5f)); oSpriteBatch->end(); } void postRender() { } void renderUI() { }
29.928571
115
0.619332
Daivuk
4b002a793f6d29e1a1c42b1fa3cbb5c643f5d2f2
724
cpp
C++
spoj0/contest-116/balanse.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
spoj0/contest-116/balanse.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
spoj0/contest-116/balanse.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_oi_optimizations() { ios_base::sync_with_stdio(false); cin.tie(NULL); } int main() { use_oi_optimizations(); unsigned int test_cases; cin >> test_cases; for (unsigned int i = 0; i < test_cases; ++i) { unsigned long long coins; unsigned int counterfeit; cin >> coins >> counterfeit; if (coins == 1) { cout << "1\n"; continue; } unsigned long long min_measurements = 0; while (coins >= 2) { ++min_measurements; coins = (coins + 2) / 3; } cout << min_measurements << '\n'; } return 0; }
16.454545
49
0.515193
Rkhoiwal
4b035d6ed2fcd81fdca32ebdc8f78cb0df942877
4,328
cc
C++
test/common/stream_info/utility_test.cc
kh-chang/envoy
dde79aea0ee6e069530a85c0fa43dcb977fd1c6f
[ "Apache-2.0" ]
1
2018-12-18T06:58:00.000Z
2018-12-18T06:58:00.000Z
test/common/stream_info/utility_test.cc
kh-chang/envoy
dde79aea0ee6e069530a85c0fa43dcb977fd1c6f
[ "Apache-2.0" ]
null
null
null
test/common/stream_info/utility_test.cc
kh-chang/envoy
dde79aea0ee6e069530a85c0fa43dcb977fd1c6f
[ "Apache-2.0" ]
1
2018-12-18T07:03:38.000Z
2018-12-18T07:03:38.000Z
#include "common/network/address_impl.h" #include "common/stream_info/utility.h" #include "test/mocks/stream_info/mocks.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::NiceMock; using testing::Return; namespace Envoy { namespace StreamInfo { TEST(ResponseFlagUtilsTest, toShortStringConversion) { static_assert(ResponseFlag::LastFlag == 0x4000, "A flag has been added. Fix this code."); std::vector<std::pair<ResponseFlag, std::string>> expected = { std::make_pair(ResponseFlag::FailedLocalHealthCheck, "LH"), std::make_pair(ResponseFlag::NoHealthyUpstream, "UH"), std::make_pair(ResponseFlag::UpstreamRequestTimeout, "UT"), std::make_pair(ResponseFlag::LocalReset, "LR"), std::make_pair(ResponseFlag::UpstreamRemoteReset, "UR"), std::make_pair(ResponseFlag::UpstreamConnectionFailure, "UF"), std::make_pair(ResponseFlag::UpstreamConnectionTermination, "UC"), std::make_pair(ResponseFlag::UpstreamOverflow, "UO"), std::make_pair(ResponseFlag::NoRouteFound, "NR"), std::make_pair(ResponseFlag::DelayInjected, "DI"), std::make_pair(ResponseFlag::FaultInjected, "FI"), std::make_pair(ResponseFlag::RateLimited, "RL"), std::make_pair(ResponseFlag::UnauthorizedExternalService, "UAEX"), std::make_pair(ResponseFlag::RateLimitServiceError, "RLSE"), std::make_pair(ResponseFlag::DownstreamConnectionTermination, "DC"), }; for (const auto& test_case : expected) { NiceMock<MockStreamInfo> stream_info; ON_CALL(stream_info, hasResponseFlag(test_case.first)).WillByDefault(Return(true)); EXPECT_EQ(test_case.second, ResponseFlagUtils::toShortString(stream_info)); } // No flag is set. { NiceMock<MockStreamInfo> stream_info; ON_CALL(stream_info, hasResponseFlag(_)).WillByDefault(Return(false)); EXPECT_EQ("-", ResponseFlagUtils::toShortString(stream_info)); } // Test combinations. // These are not real use cases, but are used to cover multiple response flags case. { NiceMock<MockStreamInfo> stream_info; ON_CALL(stream_info, hasResponseFlag(ResponseFlag::DelayInjected)).WillByDefault(Return(true)); ON_CALL(stream_info, hasResponseFlag(ResponseFlag::FaultInjected)).WillByDefault(Return(true)); ON_CALL(stream_info, hasResponseFlag(ResponseFlag::UpstreamRequestTimeout)) .WillByDefault(Return(true)); EXPECT_EQ("UT,DI,FI", ResponseFlagUtils::toShortString(stream_info)); } } TEST(ResponseFlagsUtilsTest, toResponseFlagConversion) { static_assert(ResponseFlag::LastFlag == 0x4000, "A flag has been added. Fix this code."); std::vector<std::pair<std::string, ResponseFlag>> expected = { std::make_pair("LH", ResponseFlag::FailedLocalHealthCheck), std::make_pair("UH", ResponseFlag::NoHealthyUpstream), std::make_pair("UT", ResponseFlag::UpstreamRequestTimeout), std::make_pair("LR", ResponseFlag::LocalReset), std::make_pair("UR", ResponseFlag::UpstreamRemoteReset), std::make_pair("UF", ResponseFlag::UpstreamConnectionFailure), std::make_pair("UC", ResponseFlag::UpstreamConnectionTermination), std::make_pair("UO", ResponseFlag::UpstreamOverflow), std::make_pair("NR", ResponseFlag::NoRouteFound), std::make_pair("DI", ResponseFlag::DelayInjected), std::make_pair("FI", ResponseFlag::FaultInjected), std::make_pair("RL", ResponseFlag::RateLimited), std::make_pair("UAEX", ResponseFlag::UnauthorizedExternalService), std::make_pair("RLSE", ResponseFlag::RateLimitServiceError), std::make_pair("DC", ResponseFlag::DownstreamConnectionTermination), }; EXPECT_FALSE(ResponseFlagUtils::toResponseFlag("NonExistentFlag").has_value()); for (const auto& test_case : expected) { absl::optional<ResponseFlag> response_flag = ResponseFlagUtils::toResponseFlag(test_case.first); EXPECT_TRUE(response_flag.has_value()); EXPECT_EQ(test_case.second, response_flag.value()); } } TEST(UtilityTest, formatDownstreamAddressNoPort) { EXPECT_EQ("1.2.3.4", Utility::formatDownstreamAddressNoPort(Network::Address::Ipv4Instance("1.2.3.4"))); EXPECT_EQ("/hello", Utility::formatDownstreamAddressNoPort(Network::Address::PipeInstance("/hello"))); } } // namespace StreamInfo } // namespace Envoy
42.851485
100
0.731285
kh-chang
4b04c2f2eb18e2341618c7a4e4f7101d2c90f8b9
1,267
cpp
C++
UVA00256.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
17
2015-12-08T18:50:03.000Z
2022-03-16T01:23:20.000Z
UVA00256.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
null
null
null
UVA00256.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
6
2017-04-04T18:16:23.000Z
2020-06-28T11:07:22.000Z
#include <cstdio> using namespace std; int main() { /*for (int i = 0; i <= 10000; i++) { int sqrt = i*i; if (sqrt < 100) { int aux = sqrt%10 + sqrt/10; aux *= aux; if (aux == sqrt) printf("%d\n", sqrt); } else if (sqrt < 10000) { int aux = sqrt%100 + sqrt/100; aux *= aux; if (aux == sqrt) printf("%d\n", sqrt); } else if (sqrt < 1000000) { int aux = sqrt%1000 + sqrt/1000; aux *= aux; if (aux == sqrt) printf("%d\n", sqrt); } else if (sqrt < 100000000) { int aux = sqrt%10000 + sqrt/10000; aux *= aux; if (aux == sqrt) printf("%d\n", sqrt); } }*/ char* s2 = "00\n01\n81\n"; // 0 and 1 appear in all outputs char* s4 = "0000\n0001\n2025\n3025\n9801\n"; char* s6 = "000000\n000001\n088209\n494209\n998001\n"; char* s8 = "00000000\n00000001\n04941729\n07441984\n24502500\n25502500\n52881984\n60481729\n99980001\n"; int n; while (scanf("%d", &n) != EOF) { if (n == 2) printf("%s", s2); else if (n == 4) printf("%s", s4); else if (n == 6) printf("%s", s6); else if (n == 8) printf("%s", s8); } return 0; }
33.342105
108
0.47356
MaSteve
4b05c2b9b5fabd42fb4b8a8f354c05b209504907
6,787
cpp
C++
src/Entities/Pickup.cpp
skpub/cuberite
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
[ "Apache-2.0" ]
1
2021-01-08T05:30:14.000Z
2021-01-08T05:30:14.000Z
src/Entities/Pickup.cpp
skpub/cuberite
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
[ "Apache-2.0" ]
null
null
null
src/Entities/Pickup.cpp
skpub/cuberite
c2f8ceb554982a33bcd4a1e168f6c4e26d0b85dd
[ "Apache-2.0" ]
null
null
null
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #ifndef _WIN32 #include <cstdlib> #endif #include "Pickup.h" #include "Player.h" #include "../ClientHandle.h" #include "../World.h" #include "../Server.h" #include "../Bindings/PluginManager.h" #include "../Root.h" #include "../Chunk.h" class cPickupCombiningCallback { public: cPickupCombiningCallback(Vector3d a_Position, cPickup * a_Pickup) : m_FoundMatchingPickup(false), m_Position(a_Position), m_Pickup(a_Pickup) { } bool operator () (cEntity & a_Entity) { ASSERT(a_Entity.IsTicking()); if (!a_Entity.IsPickup() || (a_Entity.GetUniqueID() <= m_Pickup->GetUniqueID()) || !a_Entity.IsOnGround()) { return false; } Vector3d EntityPos = a_Entity.GetPosition(); double Distance = (EntityPos - m_Position).Length(); auto & OtherPickup = static_cast<cPickup &>(a_Entity); cItem & Item = OtherPickup.GetItem(); if ((Distance < 1.2) && Item.IsEqual(m_Pickup->GetItem()) && OtherPickup.CanCombine()) { short CombineCount = Item.m_ItemCount; if ((CombineCount + m_Pickup->GetItem().m_ItemCount) > Item.GetMaxStackSize()) { CombineCount = Item.GetMaxStackSize() - m_Pickup->GetItem().m_ItemCount; } if (CombineCount <= 0) { return false; } m_Pickup->GetItem().AddCount(static_cast<char>(CombineCount)); Item.m_ItemCount -= CombineCount; if (Item.m_ItemCount <= 0) { a_Entity.GetWorld()->BroadcastCollectEntity(a_Entity, *m_Pickup, static_cast<unsigned>(CombineCount)); a_Entity.Destroy(); // Reset the timer m_Pickup->SetAge(0); } else { a_Entity.GetWorld()->BroadcastEntityMetadata(a_Entity); } m_FoundMatchingPickup = true; } return false; } inline bool FoundMatchingPickup() { return m_FoundMatchingPickup; } protected: bool m_FoundMatchingPickup; Vector3d m_Position; cPickup * m_Pickup; }; //////////////////////////////////////////////////////////////////////////////// // cPickup: cPickup::cPickup(Vector3d a_Pos, const cItem & a_Item, bool IsPlayerCreated, Vector3f a_Speed, int a_LifetimeTicks, bool a_CanCombine): Super(etPickup, a_Pos, 0.2, 0.2), m_Timer(0), m_Item(a_Item), m_bCollected(false), m_bIsPlayerCreated(IsPlayerCreated), m_bCanCombine(a_CanCombine), m_Lifetime(cTickTime(a_LifetimeTicks)) { SetGravity(-16.0f); SetAirDrag(0.02f); SetMaxHealth(5); SetHealth(5); SetSpeed(a_Speed); } void cPickup::SpawnOn(cClientHandle & a_Client) { a_Client.SendSpawnEntity(*this); a_Client.SendEntityMetadata(*this); } void cPickup::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) { Super::Tick(a_Dt, a_Chunk); if (!IsTicking()) { // The base class tick destroyed us return; } BroadcastMovementUpdate(); // Notify clients of position m_Timer += a_Dt; if (!m_bCollected) { int BlockY = POSY_TOINT; int BlockX = POSX_TOINT; int BlockZ = POSZ_TOINT; if ((BlockY >= 0) && (BlockY < cChunkDef::Height)) // Don't do anything except for falling when outside the world { // Position might have changed due to physics. So we have to make sure we have the correct chunk. GET_AND_VERIFY_CURRENT_CHUNK(CurrentChunk, BlockX, BlockZ); // Destroy the pickup if it is on fire: if (IsOnFire()) { m_bCollected = true; m_Timer = std::chrono::milliseconds(0); // We have to reset the timer. m_Timer += a_Dt; // In case we have to destroy the pickup in the same tick. if (m_Timer > std::chrono::milliseconds(500)) { Destroy(); return; } } // Try to combine the pickup with adjacent same-item pickups: if ((m_Item.m_ItemCount < m_Item.GetMaxStackSize()) && IsOnGround() && CanCombine()) // Don't combine if already full or not on ground { // By using a_Chunk's ForEachEntity() instead of cWorld's, pickups don't combine across chunk boundaries. // That is a small price to pay for not having to traverse the entire world for each entity. // The speedup in the tick thread is quite considerable. cPickupCombiningCallback PickupCombiningCallback(GetPosition(), this); a_Chunk.ForEachEntity(PickupCombiningCallback); if (PickupCombiningCallback.FoundMatchingPickup()) { m_World->BroadcastEntityMetadata(*this); } } } } else { if (m_Timer > std::chrono::milliseconds(500)) // 0.5 second { Destroy(); return; } } if (m_Timer > m_Lifetime) { Destroy(); return; } } bool cPickup::DoTakeDamage(TakeDamageInfo & a_TDI) { if (a_TDI.DamageType == dtCactusContact) { Destroy(); return true; } return Super::DoTakeDamage(a_TDI); } bool cPickup::CollectedBy(cPlayer & a_Dest) { if (m_bCollected) { // LOG("Pickup %d cannot be collected by \"%s\", because it has already been collected.", m_UniqueID, a_Dest->GetName().c_str()); return false; // It's already collected! } // Two seconds if player created the pickup (vomiting), half a second if anything else if (m_Timer < (m_bIsPlayerCreated ? std::chrono::seconds(2) : std::chrono::milliseconds(500))) { // LOG("Pickup %d cannot be collected by \"%s\", because it is not old enough.", m_UniqueID, a_Dest->GetName().c_str()); return false; // Not old enough } // If the player is a spectator, he cannot collect anything if (a_Dest.IsGameModeSpectator()) { return false; } if (cRoot::Get()->GetPluginManager()->CallHookCollectingPickup(a_Dest, *this)) { // LOG("Pickup %d cannot be collected by \"%s\", because a plugin has said no.", m_UniqueID, a_Dest->GetName().c_str()); return false; } int NumAdded = a_Dest.GetInventory().AddItem(m_Item); if (NumAdded > 0) { // Check achievements switch (m_Item.m_ItemType) { case E_BLOCK_LOG: a_Dest.AwardAchievement(Statistic::AchMineWood); break; case E_ITEM_LEATHER: a_Dest.AwardAchievement(Statistic::AchKillCow); break; case E_ITEM_DIAMOND: a_Dest.AwardAchievement(Statistic::AchDiamonds); break; case E_ITEM_BLAZE_ROD: a_Dest.AwardAchievement(Statistic::AchBlazeRod); break; default: break; } m_Item.m_ItemCount -= NumAdded; m_World->BroadcastCollectEntity(*this, a_Dest, static_cast<unsigned>(NumAdded)); // Also send the "pop" sound effect with a somewhat random pitch (fast-random using EntityID ;) m_World->BroadcastSoundEffect("entity.item.pickup", GetPosition(), 0.3f, (1.2f + (static_cast<float>((GetUniqueID() * 23) % 32)) / 64)); if (m_Item.m_ItemCount <= 0) { // All of the pickup has been collected, schedule the pickup for destroying m_bCollected = true; } m_Timer = std::chrono::milliseconds(0); return true; } // LOG("Pickup %d cannot be collected by \"%s\", because there's no space in the inventory.", a_Dest->GetName().c_str(), m_UniqueID); return false; }
25.230483
138
0.685281
skpub
4b06a69d9beeccdb46427de28cba0328dce0e321
2,248
cpp
C++
runtime/utilities/linux/timer_util.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
runtime/utilities/linux/timer_util.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
runtime/utilities/linux/timer_util.cpp
PTS93/compute-runtime
0655045c7962d551e29008547a802e398b646c6e
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017-2018 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include <chrono> #include "runtime/utilities/timer_util.h" namespace OCLRT { class Timer::TimerImpl { public: TimerImpl() { } ~TimerImpl() { } void start() { *((std::chrono::high_resolution_clock::time_point *)&m_startTime) = std::chrono::high_resolution_clock::now(); } void end() { *((std::chrono::high_resolution_clock::time_point *)&m_endTime) = std::chrono::high_resolution_clock::now(); } long long int get() { long long int nanosecondTime = 0; std::chrono::duration<double> diffTime = std::chrono::duration_cast<std::chrono::duration<double>>(*(reinterpret_cast<std::chrono::high_resolution_clock::time_point *>(&m_endTime)) - *(reinterpret_cast<std::chrono::high_resolution_clock::time_point *>(&m_startTime))); nanosecondTime = (long long int)(diffTime.count() * (double)1000000000.0); return nanosecondTime; } long long getStart() { long long ret = (long long)(reinterpret_cast<std::chrono::high_resolution_clock::time_point *>(&m_startTime)->time_since_epoch().count()); return ret; } long long getEnd() { long long ret = (long long)(reinterpret_cast<std::chrono::high_resolution_clock::time_point *>(&m_endTime)->time_since_epoch().count()); return ret; } TimerImpl &operator=(const TimerImpl &t) { m_startTime = t.m_startTime; return *this; } static void setFreq() { } private: std::chrono::high_resolution_clock::time_point m_startTime; std::chrono::high_resolution_clock::time_point m_endTime; }; Timer::Timer() { timerImpl = new TimerImpl(); } Timer::~Timer() { delete timerImpl; } void Timer::start() { timerImpl->start(); } void Timer::end() { timerImpl->end(); } long long int Timer::get() { return timerImpl->get(); } long long Timer::getStart() { return timerImpl->getStart(); } long long Timer::getEnd() { return timerImpl->getEnd(); } Timer &Timer::operator=(const Timer &t) { *timerImpl = *(t.timerImpl); return *this; } void Timer::setFreq() { TimerImpl::setFreq(); } }; // namespace OCLRT
23.175258
276
0.644573
PTS93
4b0deaa8c83cca315c67e6c842cb71a34a4e0fc2
1,635
hpp
C++
include/IBL.hpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
include/IBL.hpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
include/IBL.hpp
akoylasar/PBR
17e6197fb5357220e2f1454898a18f8890844d4d
[ "MIT" ]
null
null
null
/* * Copyright (c) Fouad Valadbeigi (akoylasar@gmail.com) */ #pragma once #include <atomic> #include "ShaderProgram.hpp" #include "Mesh.hpp" #include "Camera.hpp" namespace Akoylasar { class IBLScene { private: struct ImageData { int width, height; float* image; }; public: void initialise(); void render(double deltaTime, const Camera& camera); void shutdown(); void loadAssets(); void steupResources(ImageData* image); void setupBackgroundTexture(ImageData* image); void setupIrradianceMap(); void setupPrefilterEnvMap(); void setupBrdLUT(); void drawUI(double deltaTime); static void renderToCubeMap(GLuint inputTexture, bool isCubeMap, GLuint outputTexture, unsigned int width, unsigned int height, const ShaderProgram& program, const GpuMesh& cubeMesh, int mip); private: GLuint mEnvironmentTexture; std::unique_ptr<ShaderProgram> mBackgroundProgram; std::unique_ptr<ShaderProgram> mPrefilterEnvProgram; std::unique_ptr<ShaderProgram> mPbrProgram; GpuMesh mCubeMesh; GpuMesh mSphereMesh; std::atomic<ImageData*> mImage = nullptr; GLuint mIrradianceMap; GLuint mPrefilterMap; GLuint mBrdfLUT; Neon::Vec3f mAlbedo = Neon::Vec3f(0.98, 0.96, 0.99); float mMetallic = 0.5f; float mRoughness = 0.3f; float mAo = 1.0f; bool mInitialised = false; }; }
27.25
61
0.598165
akoylasar
4b0fa520e169bb57eabe192ad4ed5047ba25b9de
13,411
hpp
C++
hpx/components/dataflow/server/detail/preprocessed/apply_helper_15.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/components/dataflow/server/detail/preprocessed/apply_helper_15.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
hpx/components/dataflow/server/detail/preprocessed/apply_helper_15.hpp
Titzi90/hpx
150fb0de1cfe40c26a722918097199147957b45c
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2012-2013 Thomas Heller // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This file has been automatically generated using the Boost.Wave tool. // Do not edit manually. template <typename Action> struct apply_helper<1, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) ); } }; template <typename Action> struct apply_helper<2, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) ); } }; template <typename Action> struct apply_helper<3, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) ); } }; template <typename Action> struct apply_helper<4, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) ); } }; template <typename Action> struct apply_helper<5, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) ); } }; template <typename Action> struct apply_helper<6, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) ); } }; template <typename Action> struct apply_helper<7, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) ); } }; template <typename Action> struct apply_helper<8, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) ); } }; template <typename Action> struct apply_helper<9, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) ); } }; template <typename Action> struct apply_helper<10, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) ); } }; template <typename Action> struct apply_helper<11, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) , std::move(boost::fusion::at_c< 10>(args)) ); } }; template <typename Action> struct apply_helper<12, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) , std::move(boost::fusion::at_c< 10>(args)) , std::move(boost::fusion::at_c< 11>(args)) ); } }; template <typename Action> struct apply_helper<13, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) , std::move(boost::fusion::at_c< 10>(args)) , std::move(boost::fusion::at_c< 11>(args)) , std::move(boost::fusion::at_c< 12>(args)) ); } }; template <typename Action> struct apply_helper<14, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) , std::move(boost::fusion::at_c< 10>(args)) , std::move(boost::fusion::at_c< 11>(args)) , std::move(boost::fusion::at_c< 12>(args)) , std::move(boost::fusion::at_c< 13>(args)) ); } }; template <typename Action> struct apply_helper<15, Action> { template <typename Vector> void operator()( naming::id_type const & cont , naming::id_type const & id , Vector & args ) const { LLCO_(info) << "dataflow apply action " << hpx::actions::detail::get_action_name<Action>(); hpx::apply_c<Action>( cont , id , std::move(boost::fusion::at_c< 0>(args)) , std::move(boost::fusion::at_c< 1>(args)) , std::move(boost::fusion::at_c< 2>(args)) , std::move(boost::fusion::at_c< 3>(args)) , std::move(boost::fusion::at_c< 4>(args)) , std::move(boost::fusion::at_c< 5>(args)) , std::move(boost::fusion::at_c< 6>(args)) , std::move(boost::fusion::at_c< 7>(args)) , std::move(boost::fusion::at_c< 8>(args)) , std::move(boost::fusion::at_c< 9>(args)) , std::move(boost::fusion::at_c< 10>(args)) , std::move(boost::fusion::at_c< 11>(args)) , std::move(boost::fusion::at_c< 12>(args)) , std::move(boost::fusion::at_c< 13>(args)) , std::move(boost::fusion::at_c< 14>(args)) ); } };
41.138037
663
0.513757
Titzi90
4b114167c43fdfb8fc70dc66e81bbed3244fbfe7
31,984
cc
C++
test/cpp/microbenchmarks/bm_call_create.cc
galihputera/grpc
36cbed1ef53bbd4374acb646005cefedbb4f180e
[ "Apache-2.0" ]
3
2020-11-30T15:35:37.000Z
2022-01-06T14:17:18.000Z
test/cpp/microbenchmarks/bm_call_create.cc
galihputera/grpc
36cbed1ef53bbd4374acb646005cefedbb4f180e
[ "Apache-2.0" ]
54
2020-06-23T17:34:04.000Z
2022-03-31T02:04:06.000Z
test/cpp/microbenchmarks/bm_call_create.cc
galihputera/grpc
36cbed1ef53bbd4374acb646005cefedbb4f180e
[ "Apache-2.0" ]
12
2020-07-14T23:59:57.000Z
2022-03-22T09:59:18.000Z
/* * * Copyright 2017 gRPC authors. * * 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. * */ /* This benchmark exists to ensure that the benchmark integration is * working */ #include <benchmark/benchmark.h> #include <string.h> #include <sstream> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> #include <grpcpp/channel.h> #include <grpcpp/support/channel_arguments.h> #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/deadline/deadline_filter.h" #include "src/core/ext/filters/http/client/http_client_filter.h" #include "src/core/ext/filters/http/message_compress/message_compress_filter.h" #include "src/core/ext/filters/http/server/http_server_filter.h" #include "src/core/ext/filters/message_size/message_size_filter.h" #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/connected_channel.h" #include "src/core/lib/iomgr/call_combiner.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/transport_impl.h" #include "src/cpp/client/create_channel_internal.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/core/util/test_config.h" #include "test/cpp/microbenchmarks/helpers.h" #include "test/cpp/util/test_config.h" void BM_Zalloc(benchmark::State& state) { // speed of light for call creation is zalloc, so benchmark a few interesting // sizes TrackCounters track_counters; size_t sz = state.range(0); for (auto _ : state) { gpr_free(gpr_zalloc(sz)); } track_counters.Finish(state); } BENCHMARK(BM_Zalloc) ->Arg(64) ->Arg(128) ->Arg(256) ->Arg(512) ->Arg(1024) ->Arg(1536) ->Arg(2048) ->Arg(3072) ->Arg(4096) ->Arg(5120) ->Arg(6144) ->Arg(7168); //////////////////////////////////////////////////////////////////////////////// // Benchmarks creating full stacks class BaseChannelFixture { public: BaseChannelFixture(grpc_channel* channel) : channel_(channel) {} ~BaseChannelFixture() { grpc_channel_destroy(channel_); } grpc_channel* channel() const { return channel_; } private: grpc_channel* const channel_; }; class InsecureChannel : public BaseChannelFixture { public: InsecureChannel() : BaseChannelFixture( grpc_insecure_channel_create("localhost:1234", nullptr, nullptr)) {} }; class LameChannel : public BaseChannelFixture { public: LameChannel() : BaseChannelFixture(grpc_lame_client_channel_create( "localhost:1234", GRPC_STATUS_UNAUTHENTICATED, "blah")) {} }; template <class Fixture> static void BM_CallCreateDestroy(benchmark::State& state) { TrackCounters track_counters; Fixture fixture; grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr); gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); void* method_hdl = grpc_channel_register_call(fixture.channel(), "/foo/bar", nullptr, nullptr); for (auto _ : state) { grpc_call_unref(grpc_channel_create_registered_call( fixture.channel(), nullptr, GRPC_PROPAGATE_DEFAULTS, cq, method_hdl, deadline, nullptr)); } grpc_completion_queue_destroy(cq); track_counters.Finish(state); } BENCHMARK_TEMPLATE(BM_CallCreateDestroy, InsecureChannel); BENCHMARK_TEMPLATE(BM_CallCreateDestroy, LameChannel); //////////////////////////////////////////////////////////////////////////////// // Benchmarks isolating individual filters static void* tag(int i) { return reinterpret_cast<void*>(static_cast<intptr_t>(i)); } static void BM_LameChannelCallCreateCpp(benchmark::State& state) { TrackCounters track_counters; auto stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannelInternal( "", grpc_lame_client_channel_create("localhost:1234", GRPC_STATUS_UNAUTHENTICATED, "blah"), std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>>())); grpc::CompletionQueue cq; grpc::testing::EchoRequest send_request; grpc::testing::EchoResponse recv_response; grpc::Status recv_status; for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc::ClientContext cli_ctx; auto reader = stub->AsyncEcho(&cli_ctx, send_request, &cq); reader->Finish(&recv_response, &recv_status, tag(0)); void* t; bool ok; GPR_ASSERT(cq.Next(&t, &ok)); GPR_ASSERT(ok); } track_counters.Finish(state); } BENCHMARK(BM_LameChannelCallCreateCpp); static void do_nothing(void* /*ignored*/) {} static void BM_LameChannelCallCreateCore(benchmark::State& state) { TrackCounters track_counters; grpc_channel* channel; grpc_completion_queue* cq; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_byte_buffer* response_payload_recv = nullptr; grpc_status_code status; grpc_slice details; grpc::testing::EchoRequest send_request; grpc_slice send_request_slice = grpc_slice_new(&send_request, sizeof(send_request), do_nothing); channel = grpc_lame_client_channel_create( "localhost:1234", GRPC_STATUS_UNAUTHENTICATED, "blah"); cq = grpc_completion_queue_create_for_next(nullptr); void* rc = grpc_channel_register_call( channel, "/grpc.testing.EchoTestService/Echo", nullptr, nullptr); for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc_call* call = grpc_channel_create_registered_call( channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq, rc, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_byte_buffer* request_payload_send = grpc_raw_byte_buffer_create(&send_request_slice, 1); // Fill in call ops grpc_op ops[6]; memset(ops, 0, sizeof(ops)); grpc_op* op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = request_payload_send; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op++; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call, ops, (size_t)(op - ops), (void*)1, nullptr)); grpc_event ev = grpc_completion_queue_next( cq, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); GPR_ASSERT(ev.type != GRPC_QUEUE_SHUTDOWN); GPR_ASSERT(ev.success != 0); grpc_call_unref(call); grpc_byte_buffer_destroy(request_payload_send); grpc_byte_buffer_destroy(response_payload_recv); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); } grpc_channel_destroy(channel); grpc_completion_queue_destroy(cq); grpc_slice_unref(send_request_slice); track_counters.Finish(state); } BENCHMARK(BM_LameChannelCallCreateCore); static void BM_LameChannelCallCreateCoreSeparateBatch(benchmark::State& state) { TrackCounters track_counters; grpc_channel* channel; grpc_completion_queue* cq; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_byte_buffer* response_payload_recv = nullptr; grpc_status_code status; grpc_slice details; grpc::testing::EchoRequest send_request; grpc_slice send_request_slice = grpc_slice_new(&send_request, sizeof(send_request), do_nothing); channel = grpc_lame_client_channel_create( "localhost:1234", GRPC_STATUS_UNAUTHENTICATED, "blah"); cq = grpc_completion_queue_create_for_next(nullptr); void* rc = grpc_channel_register_call( channel, "/grpc.testing.EchoTestService/Echo", nullptr, nullptr); for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc_call* call = grpc_channel_create_registered_call( channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq, rc, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_byte_buffer* request_payload_send = grpc_raw_byte_buffer_create(&send_request_slice, 1); // Fill in call ops grpc_op ops[3]; memset(ops, 0, sizeof(ops)); grpc_op* op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = request_payload_send; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call, ops, (size_t)(op - ops), (void*)nullptr, nullptr)); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload_recv; op++; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call, ops, (size_t)(op - ops), (void*)1, nullptr)); grpc_event ev = grpc_completion_queue_next( cq, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); GPR_ASSERT(ev.type != GRPC_QUEUE_SHUTDOWN); GPR_ASSERT(ev.success == 0); ev = grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); GPR_ASSERT(ev.type != GRPC_QUEUE_SHUTDOWN); GPR_ASSERT(ev.success != 0); grpc_call_unref(call); grpc_byte_buffer_destroy(request_payload_send); grpc_byte_buffer_destroy(response_payload_recv); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); } grpc_channel_destroy(channel); grpc_completion_queue_destroy(cq); grpc_slice_unref(send_request_slice); track_counters.Finish(state); } BENCHMARK(BM_LameChannelCallCreateCoreSeparateBatch); static void FilterDestroy(void* arg, grpc_error* /*error*/) { gpr_free(arg); } static void DoNothing(void* /*arg*/, grpc_error* /*error*/) {} class FakeClientChannelFactory : public grpc_core::ClientChannelFactory { public: grpc_core::Subchannel* CreateSubchannel( const grpc_channel_args* /*args*/) override { return nullptr; } }; static grpc_arg StringArg(const char* key, const char* value) { grpc_arg a; a.type = GRPC_ARG_STRING; a.key = const_cast<char*>(key); a.value.string = const_cast<char*>(value); return a; } enum FixtureFlags : uint32_t { CHECKS_NOT_LAST = 1, REQUIRES_TRANSPORT = 2, }; template <const grpc_channel_filter* kFilter, uint32_t kFlags> struct Fixture { const grpc_channel_filter* filter = kFilter; const uint32_t flags = kFlags; }; namespace dummy_filter { static void StartTransportStreamOp(grpc_call_element* /*elem*/, grpc_transport_stream_op_batch* /*op*/) {} static void StartTransportOp(grpc_channel_element* /*elem*/, grpc_transport_op* /*op*/) {} static grpc_error* InitCallElem(grpc_call_element* /*elem*/, const grpc_call_element_args* /*args*/) { return GRPC_ERROR_NONE; } static void SetPollsetOrPollsetSet(grpc_call_element* /*elem*/, grpc_polling_entity* /*pollent*/) {} static void DestroyCallElem(grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/, grpc_closure* /*then_sched_closure*/) {} grpc_error* InitChannelElem(grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DestroyChannelElem(grpc_channel_element* /*elem*/) {} void GetChannelInfo(grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {} static const grpc_channel_filter dummy_filter = {StartTransportStreamOp, StartTransportOp, 0, InitCallElem, SetPollsetOrPollsetSet, DestroyCallElem, 0, InitChannelElem, DestroyChannelElem, GetChannelInfo, "dummy_filter"}; } // namespace dummy_filter namespace dummy_transport { /* Memory required for a single stream element - this is allocated by upper layers and initialized by the transport */ size_t sizeof_stream; /* = sizeof(transport stream) */ /* name of this transport implementation */ const char* name; /* implementation of grpc_transport_init_stream */ int InitStream(grpc_transport* /*self*/, grpc_stream* /*stream*/, grpc_stream_refcount* /*refcount*/, const void* /*server_data*/, grpc_core::Arena* /*arena*/) { return 0; } /* implementation of grpc_transport_set_pollset */ void SetPollset(grpc_transport* /*self*/, grpc_stream* /*stream*/, grpc_pollset* /*pollset*/) {} /* implementation of grpc_transport_set_pollset */ void SetPollsetSet(grpc_transport* /*self*/, grpc_stream* /*stream*/, grpc_pollset_set* /*pollset_set*/) {} /* implementation of grpc_transport_perform_stream_op */ void PerformStreamOp(grpc_transport* /*self*/, grpc_stream* /*stream*/, grpc_transport_stream_op_batch* op) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_complete, GRPC_ERROR_NONE); } /* implementation of grpc_transport_perform_op */ void PerformOp(grpc_transport* /*self*/, grpc_transport_op* /*op*/) {} /* implementation of grpc_transport_destroy_stream */ void DestroyStream(grpc_transport* /*self*/, grpc_stream* /*stream*/, grpc_closure* /*then_sched_closure*/) {} /* implementation of grpc_transport_destroy */ void Destroy(grpc_transport* /*self*/) {} /* implementation of grpc_transport_get_endpoint */ grpc_endpoint* GetEndpoint(grpc_transport* /*self*/) { return nullptr; } static const grpc_transport_vtable dummy_transport_vtable = { 0, "dummy_http2", InitStream, SetPollset, SetPollsetSet, PerformStreamOp, PerformOp, DestroyStream, Destroy, GetEndpoint}; static grpc_transport dummy_transport = {&dummy_transport_vtable}; } // namespace dummy_transport class NoOp { public: class Op { public: Op(NoOp* /*p*/, grpc_call_stack* /*s*/) {} void Finish() {} }; }; class SendEmptyMetadata { public: SendEmptyMetadata() : op_payload_(nullptr) { op_ = {}; op_.on_complete = GRPC_CLOSURE_INIT(&closure_, DoNothing, nullptr, grpc_schedule_on_exec_ctx); op_.send_initial_metadata = true; op_.payload = &op_payload_; } class Op { public: Op(SendEmptyMetadata* p, grpc_call_stack* /*s*/) { grpc_metadata_batch_init(&batch_); p->op_payload_.send_initial_metadata.send_initial_metadata = &batch_; } void Finish() { grpc_metadata_batch_destroy(&batch_); } private: grpc_metadata_batch batch_; }; private: const gpr_timespec deadline_ = gpr_inf_future(GPR_CLOCK_MONOTONIC); const gpr_timespec start_time_ = gpr_now(GPR_CLOCK_MONOTONIC); const grpc_slice method_ = grpc_slice_from_static_string("/foo/bar"); grpc_transport_stream_op_batch op_; grpc_transport_stream_op_batch_payload op_payload_; grpc_closure closure_; }; // Test a filter in isolation. Fixture specifies the filter under test (use the // Fixture<> template to specify this), and TestOp defines some unit of work to // perform on said filter. template <class Fixture, class TestOp> static void BM_IsolatedFilter(benchmark::State& state) { TrackCounters track_counters; Fixture fixture; std::ostringstream label; FakeClientChannelFactory fake_client_channel_factory; std::vector<grpc_arg> args = { grpc_core::ClientChannelFactory::CreateChannelArg( &fake_client_channel_factory), StringArg(GRPC_ARG_SERVER_URI, "localhost"), }; grpc_channel_args channel_args = {args.size(), &args[0]}; std::vector<const grpc_channel_filter*> filters; if (fixture.filter != nullptr) { filters.push_back(fixture.filter); } if (fixture.flags & CHECKS_NOT_LAST) { filters.push_back(&dummy_filter::dummy_filter); label << " #has_dummy_filter"; } grpc_core::ExecCtx exec_ctx; size_t channel_size = grpc_channel_stack_size( filters.empty() ? nullptr : &filters[0], filters.size()); grpc_channel_stack* channel_stack = static_cast<grpc_channel_stack*>(gpr_zalloc(channel_size)); GPR_ASSERT(GRPC_LOG_IF_ERROR( "channel_stack_init", grpc_channel_stack_init(1, FilterDestroy, channel_stack, filters.empty() ? nullptr : &filters[0], filters.size(), &channel_args, fixture.flags & REQUIRES_TRANSPORT ? &dummy_transport::dummy_transport : nullptr, "CHANNEL", channel_stack))); grpc_core::ExecCtx::Get()->Flush(); grpc_call_stack* call_stack = static_cast<grpc_call_stack*>(gpr_zalloc(channel_stack->call_stack_size)); grpc_millis deadline = GRPC_MILLIS_INF_FUTURE; gpr_cycle_counter start_time = gpr_get_cycle_counter(); grpc_slice method = grpc_slice_from_static_string("/foo/bar"); grpc_call_final_info final_info; TestOp test_op_data; const int kArenaSize = 4096; grpc_call_context_element context[GRPC_CONTEXT_COUNT] = {}; grpc_call_element_args call_args{call_stack, nullptr, context, method, start_time, deadline, grpc_core::Arena::Create(kArenaSize), nullptr}; while (state.KeepRunning()) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); GRPC_ERROR_UNREF( grpc_call_stack_init(channel_stack, 1, DoNothing, nullptr, &call_args)); typename TestOp::Op op(&test_op_data, call_stack); grpc_call_stack_destroy(call_stack, &final_info, nullptr); op.Finish(); grpc_core::ExecCtx::Get()->Flush(); // recreate arena every 64k iterations to avoid oom if (0 == (state.iterations() & 0xffff)) { call_args.arena->Destroy(); call_args.arena = grpc_core::Arena::Create(kArenaSize); } } call_args.arena->Destroy(); grpc_channel_stack_destroy(channel_stack); grpc_core::ExecCtx::Get()->Flush(); gpr_free(channel_stack); gpr_free(call_stack); state.SetLabel(label.str()); track_counters.Finish(state); } typedef Fixture<nullptr, 0> NoFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, NoFilter, NoOp); typedef Fixture<&dummy_filter::dummy_filter, 0> DummyFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, DummyFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, DummyFilter, SendEmptyMetadata); typedef Fixture<&grpc_client_channel_filter, 0> ClientChannelFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, ClientChannelFilter, NoOp); typedef Fixture<&grpc_message_compress_filter, CHECKS_NOT_LAST> CompressFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, CompressFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, CompressFilter, SendEmptyMetadata); typedef Fixture<&grpc_client_deadline_filter, CHECKS_NOT_LAST> ClientDeadlineFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, ClientDeadlineFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, ClientDeadlineFilter, SendEmptyMetadata); typedef Fixture<&grpc_server_deadline_filter, CHECKS_NOT_LAST> ServerDeadlineFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, ServerDeadlineFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, ServerDeadlineFilter, SendEmptyMetadata); typedef Fixture<&grpc_http_client_filter, CHECKS_NOT_LAST | REQUIRES_TRANSPORT> HttpClientFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, HttpClientFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, HttpClientFilter, SendEmptyMetadata); typedef Fixture<&grpc_http_server_filter, CHECKS_NOT_LAST> HttpServerFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, HttpServerFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, HttpServerFilter, SendEmptyMetadata); typedef Fixture<&grpc_message_size_filter, CHECKS_NOT_LAST> MessageSizeFilter; BENCHMARK_TEMPLATE(BM_IsolatedFilter, MessageSizeFilter, NoOp); BENCHMARK_TEMPLATE(BM_IsolatedFilter, MessageSizeFilter, SendEmptyMetadata); // This cmake target is disabled for now because it depends on OpenCensus, which // is Bazel-only. // typedef Fixture<&grpc_server_load_reporting_filter, CHECKS_NOT_LAST> // LoadReportingFilter; // BENCHMARK_TEMPLATE(BM_IsolatedFilter, LoadReportingFilter, NoOp); // BENCHMARK_TEMPLATE(BM_IsolatedFilter, LoadReportingFilter, // SendEmptyMetadata); //////////////////////////////////////////////////////////////////////////////// // Benchmarks isolating grpc_call namespace isolated_call_filter { typedef struct { grpc_core::CallCombiner* call_combiner; } call_data; static void StartTransportStreamOp(grpc_call_element* elem, grpc_transport_stream_op_batch* op) { call_data* calld = static_cast<call_data*>(elem->call_data); // Construct list of closures to return. grpc_core::CallCombinerClosureList closures; if (op->recv_initial_metadata) { closures.Add(op->payload->recv_initial_metadata.recv_initial_metadata_ready, GRPC_ERROR_NONE, "recv_initial_metadata"); } if (op->recv_message) { closures.Add(op->payload->recv_message.recv_message_ready, GRPC_ERROR_NONE, "recv_message"); } if (op->recv_trailing_metadata) { closures.Add( op->payload->recv_trailing_metadata.recv_trailing_metadata_ready, GRPC_ERROR_NONE, "recv_trailing_metadata"); } if (op->on_complete != nullptr) { closures.Add(op->on_complete, GRPC_ERROR_NONE, "on_complete"); } // Execute closures. closures.RunClosures(calld->call_combiner); } static void StartTransportOp(grpc_channel_element* /*elem*/, grpc_transport_op* op) { if (op->disconnect_with_error != GRPC_ERROR_NONE) { GRPC_ERROR_UNREF(op->disconnect_with_error); } grpc_core::ExecCtx::Run(DEBUG_LOCATION, op->on_consumed, GRPC_ERROR_NONE); } static grpc_error* InitCallElem(grpc_call_element* elem, const grpc_call_element_args* args) { call_data* calld = static_cast<call_data*>(elem->call_data); calld->call_combiner = args->call_combiner; return GRPC_ERROR_NONE; } static void SetPollsetOrPollsetSet(grpc_call_element* /*elem*/, grpc_polling_entity* /*pollent*/) {} static void DestroyCallElem(grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/, grpc_closure* then_sched_closure) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, then_sched_closure, GRPC_ERROR_NONE); } grpc_error* InitChannelElem(grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { return GRPC_ERROR_NONE; } void DestroyChannelElem(grpc_channel_element* /*elem*/) {} void GetChannelInfo(grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {} static const grpc_channel_filter isolated_call_filter = { StartTransportStreamOp, StartTransportOp, sizeof(call_data), InitCallElem, SetPollsetOrPollsetSet, DestroyCallElem, 0, InitChannelElem, DestroyChannelElem, GetChannelInfo, "isolated_call_filter"}; } // namespace isolated_call_filter class IsolatedCallFixture : public TrackCounters { public: IsolatedCallFixture() { // We are calling grpc_channel_stack_builder_create() instead of // grpc_channel_create() here, which means we're not getting the // grpc_init() called by grpc_channel_create(), but we are getting // the grpc_shutdown() run by grpc_channel_destroy(). So we need to // call grpc_init() manually here to balance things out. grpc_init(); grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create(); grpc_channel_stack_builder_set_name(builder, "dummy"); grpc_channel_stack_builder_set_target(builder, "dummy_target"); GPR_ASSERT(grpc_channel_stack_builder_append_filter( builder, &isolated_call_filter::isolated_call_filter, nullptr, nullptr)); { grpc_core::ExecCtx exec_ctx; channel_ = grpc_channel_create_with_builder(builder, GRPC_CLIENT_CHANNEL); } cq_ = grpc_completion_queue_create_for_next(nullptr); } void Finish(benchmark::State& state) override { grpc_completion_queue_destroy(cq_); grpc_channel_destroy(channel_); TrackCounters::Finish(state); } grpc_channel* channel() const { return channel_; } grpc_completion_queue* cq() const { return cq_; } private: grpc_completion_queue* cq_; grpc_channel* channel_; }; static void BM_IsolatedCall_NoOp(benchmark::State& state) { IsolatedCallFixture fixture; gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); void* method_hdl = grpc_channel_register_call(fixture.channel(), "/foo/bar", nullptr, nullptr); for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc_call_unref(grpc_channel_create_registered_call( fixture.channel(), nullptr, GRPC_PROPAGATE_DEFAULTS, fixture.cq(), method_hdl, deadline, nullptr)); } fixture.Finish(state); } BENCHMARK(BM_IsolatedCall_NoOp); static void BM_IsolatedCall_Unary(benchmark::State& state) { IsolatedCallFixture fixture; gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); void* method_hdl = grpc_channel_register_call(fixture.channel(), "/foo/bar", nullptr, nullptr); grpc_slice slice = grpc_slice_from_static_string("hello world"); grpc_byte_buffer* send_message = grpc_raw_byte_buffer_create(&slice, 1); grpc_byte_buffer* recv_message = nullptr; grpc_status_code status_code; grpc_slice status_details = grpc_empty_slice(); grpc_metadata_array recv_initial_metadata; grpc_metadata_array_init(&recv_initial_metadata); grpc_metadata_array recv_trailing_metadata; grpc_metadata_array_init(&recv_trailing_metadata); grpc_op ops[6]; memset(ops, 0, sizeof(ops)); ops[0].op = GRPC_OP_SEND_INITIAL_METADATA; ops[1].op = GRPC_OP_SEND_MESSAGE; ops[1].data.send_message.send_message = send_message; ops[2].op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; ops[3].op = GRPC_OP_RECV_INITIAL_METADATA; ops[3].data.recv_initial_metadata.recv_initial_metadata = &recv_initial_metadata; ops[4].op = GRPC_OP_RECV_MESSAGE; ops[4].data.recv_message.recv_message = &recv_message; ops[5].op = GRPC_OP_RECV_STATUS_ON_CLIENT; ops[5].data.recv_status_on_client.status = &status_code; ops[5].data.recv_status_on_client.status_details = &status_details; ops[5].data.recv_status_on_client.trailing_metadata = &recv_trailing_metadata; for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc_call* call = grpc_channel_create_registered_call( fixture.channel(), nullptr, GRPC_PROPAGATE_DEFAULTS, fixture.cq(), method_hdl, deadline, nullptr); grpc_call_start_batch(call, ops, 6, tag(1), nullptr); grpc_completion_queue_next(fixture.cq(), gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr); grpc_call_unref(call); } fixture.Finish(state); grpc_metadata_array_destroy(&recv_initial_metadata); grpc_metadata_array_destroy(&recv_trailing_metadata); grpc_byte_buffer_destroy(send_message); } BENCHMARK(BM_IsolatedCall_Unary); static void BM_IsolatedCall_StreamingSend(benchmark::State& state) { IsolatedCallFixture fixture; gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); void* method_hdl = grpc_channel_register_call(fixture.channel(), "/foo/bar", nullptr, nullptr); grpc_slice slice = grpc_slice_from_static_string("hello world"); grpc_byte_buffer* send_message = grpc_raw_byte_buffer_create(&slice, 1); grpc_metadata_array recv_initial_metadata; grpc_metadata_array_init(&recv_initial_metadata); grpc_metadata_array recv_trailing_metadata; grpc_metadata_array_init(&recv_trailing_metadata); grpc_op ops[2]; memset(ops, 0, sizeof(ops)); ops[0].op = GRPC_OP_SEND_INITIAL_METADATA; ops[1].op = GRPC_OP_RECV_INITIAL_METADATA; ops[1].data.recv_initial_metadata.recv_initial_metadata = &recv_initial_metadata; grpc_call* call = grpc_channel_create_registered_call( fixture.channel(), nullptr, GRPC_PROPAGATE_DEFAULTS, fixture.cq(), method_hdl, deadline, nullptr); grpc_call_start_batch(call, ops, 2, tag(1), nullptr); grpc_completion_queue_next(fixture.cq(), gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr); memset(ops, 0, sizeof(ops)); ops[0].op = GRPC_OP_SEND_MESSAGE; ops[0].data.send_message.send_message = send_message; for (auto _ : state) { GPR_TIMER_SCOPE("BenchmarkCycle", 0); grpc_call_start_batch(call, ops, 1, tag(2), nullptr); grpc_completion_queue_next(fixture.cq(), gpr_inf_future(GPR_CLOCK_MONOTONIC), nullptr); } grpc_call_unref(call); fixture.Finish(state); grpc_metadata_array_destroy(&recv_initial_metadata); grpc_metadata_array_destroy(&recv_trailing_metadata); grpc_byte_buffer_destroy(send_message); } BENCHMARK(BM_IsolatedCall_StreamingSend); // Some distros have RunSpecifiedBenchmarks under the benchmark namespace, // and others do not. This allows us to support both modes. namespace benchmark { void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); } } // namespace benchmark int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); LibraryInitializer libInit; ::benchmark::Initialize(&argc, argv); ::grpc::testing::InitTest(&argc, &argv, false); benchmark::RunTheBenchmarksNamespaced(); return 0; }
38.304192
80
0.701507
galihputera
4b15ce21d680717ea38a9fd013db35301e26d0dd
3,889
cpp
C++
src/ofxMSATFVizUtils.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
481
2016-01-28T22:05:07.000Z
2022-03-07T23:29:10.000Z
src/ofxMSATFVizUtils.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
37
2016-01-29T02:18:33.000Z
2020-03-24T17:36:05.000Z
src/ofxMSATFVizUtils.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
110
2016-01-29T14:00:39.000Z
2020-11-22T14:20:56.000Z
#include "ofxMSATFVizUtils.h" namespace msa { namespace tf { //-------------------------------------------------------------- void draw_probs(const vector<float>& probs, const ofRectangle& rect, const ofColor& lo_color, const ofColor& hi_color) { if(probs.size() == 0) return; ofPushStyle(); ofFill(); ofRectangle r(rect); r.width = rect.width / probs.size(); for(int i=0; i<probs.size(); i++) { float p = probs[i]; r.height = p * rect.height; r.y = rect.getBottom() - r.height; r.x += r.width; ofSetColor(lo_color + (hi_color - lo_color)* p); ofDrawRectangle(r); } ofPopStyle(); } //-------------------------------------------------------------- // visualise bivariate gaussian distribution as an ellipse // rotate unit circle by matrix of normalised eigenvectors and scale by sqrt eigenvalues (tip from @colormotor) // eigen decomposition from on http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html // also see nice visualisation at http://demonstrations.wolfram.com/TheBivariateNormalDistribution/ void draw_bi_gaussian(float mu1, // mean 1 float mu2, // mean 2 float sigma1, // sigma 1 float sigma2, // sigma 2 float rho, // correlation float scale // arbitrary scale ) { // Correlation Matrix Sigma [[a b], [c d]] double a = sigma1*sigma1; double b = rho*sigma1*sigma2; double c = b; double d = sigma2*sigma2; double T = a+d; // trace double D = (a*d)-(b*c); // determinant // eigenvalues double l1 = T/2. + T*sqrt( 1./(4.-D) ); double l2 = T/2. - T*sqrt( 1./(4.-D) ); ofVec2f v1 ( ofVec2f(b, l1-a).normalized() ); ofVec2f v2 ( ofVec2f(b, l2-a).normalized() ); // create 4x4 transformation matrix // eigenvectors in upper left corner for rotation around z // scale diagonal by eigenvalues ofMatrix4x4 m44; m44.ofMatrix4x4::makeIdentityMatrix(); m44.getPtr()[0] = v1.x * sqrtf(fabsf(l1)) * scale; m44.getPtr()[4] = v1.y; m44.getPtr()[1] = v2.x; m44.getPtr()[5] = v2.y * sqrtf(fabsf(l2)) * scale; m44.setTranslation(mu1, mu2, 0); ofPushMatrix(); ofMultMatrix(m44); ofDrawCircle(0, 0, 1); ofPopMatrix(); // trying raw opengl commands instead of ofXXX to make sure column and row order stuff is done as I want :S // glPushMatrix(); // glMultMatrixf(m44.getPtr()); // ofDrawCircle(0, 0, 1); // glPopMatrix(); } //-------------------------------------------------------------- // visualise bivariate gaussian mixture model void draw_bi_gmm(const vector<float>& o_pi, // vector of mixture weights const vector<float>& o_mu1, // means 1 const vector<float>& o_mu2, // means 2 const vector<float>& o_sigma1, // sigmas 1 const vector<float>& o_sigma2, // sigmas 2 const vector<float>& o_corr, // correlations const ofVec2f& offset, float draw_scale, float gaussian_scale, ofColor color_min, ofColor color_max ) { int k = o_pi.size(); if(k == 0 || o_mu1.size() != k || o_mu2.size() != k || o_sigma1.size() != k || o_sigma2.size() != k || o_corr.size() != k) { ofLogWarning("ofxMSATensorFlow") << " draw_bi_gmm vector size mismatch "; return; } ofPushMatrix(); ofTranslate(offset); ofScale(draw_scale, draw_scale); for(int i=0; i<k; i++) { ofColor c(color_min); c.lerp(color_max, o_pi[i]); ofSetColor(c); draw_bi_gaussian(o_mu1[i], o_mu2[i], o_sigma1[i], o_sigma2[i], o_corr[i], gaussian_scale); } ofPopMatrix(); } } }
33.525862
128
0.550527
marcel303
4b175e77903ba8ceaba5b44085d747c6b8ab0d18
16,189
cpp
C++
core_test/file_test.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
null
null
null
core_test/file_test.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
null
null
null
core_test/file_test.cpp
granitepenguin/wwiv
30669b21f45c5f534014a251f55568c86904f87e
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)2014-2021, WWIV Software Services */ /* */ /* 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 "core/file.h" #include "core/stl.h" #include "core/strings.h" #include "file_helper.h" #include "fmt/format-inl.h" #include "gtest/gtest.h" #include <iostream> #include <string> using namespace wwiv::core; using namespace wwiv::strings; TEST(FileTest, DoesNotExist) { FileHelper file; auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); const auto fn = FilePath(tmp, "doesnotexist"); ASSERT_FALSE(File::Exists(fn)); } TEST(FileTest, DoesNotExist_Static) { FileHelper file; auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); File dne(FilePath(tmp, "doesnotexist")); ASSERT_FALSE(File::Exists(dne.path())); } TEST(FileTest, Exists) { FileHelper file; const auto tmp{file.TempDir()}; GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); const auto f{FilePath(tmp, "newdir")}; ASSERT_TRUE(File::Exists(f)) << f; } TEST(FileTest, ExistsWildCard) { FileHelper helper; const auto path = helper.CreateTempFile("msg00000.001", "msg00000.001"); ASSERT_TRUE(File::Exists(path)); auto wildcard_path = FilePath(helper.TempDir(), "msg*"); ASSERT_TRUE(File::ExistsWildcard(wildcard_path)) << path << "; w: " << wildcard_path; wildcard_path = FilePath(helper.TempDir(), "msg*.*"); EXPECT_TRUE(File::ExistsWildcard(wildcard_path)) << path << "; w: " << wildcard_path; wildcard_path = FilePath(helper.TempDir(), "msg*.???"); EXPECT_TRUE(File::ExistsWildcard(wildcard_path)) << path << "; w: " << wildcard_path; } TEST(FileTest, ExistsWildCard_Extension) { FileHelper helper; const auto path = helper.CreateTempFile("msg00000.001", "msg00000.001"); ASSERT_TRUE(File::Exists(path)); auto wildcard_path = FilePath(helper.TempDir(), "msg*.001").string(); ASSERT_TRUE(File::ExistsWildcard(wildcard_path)) << path << "; w: " << wildcard_path; wildcard_path = FilePath(helper.TempDir(), "msg*.??1").string(); ASSERT_TRUE(File::ExistsWildcard(wildcard_path)) << path << "; w: " << wildcard_path; } TEST(FileTest, Exists_Static) { FileHelper file{}; const auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); const File dne(FilePath(tmp, "newdir")); ASSERT_TRUE(File::Exists(dne.path())) << dne.path(); } TEST(FileTest, Exists_TrailingSlash) { FileHelper file; const auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); File dne(FilePath(tmp, "newdir")); const auto path = File::EnsureTrailingSlash(dne.full_pathname()); ASSERT_TRUE(File::Exists(path)) << path; ASSERT_EQ(File::pathSeparatorChar, path.back()); } TEST(FileTest, Length_Open) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); ASSERT_EQ(static_cast<long>(kHelloWorld.size()), file.length()); } TEST(FileTest, Length_NotOpen) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_EQ(static_cast<long>(kHelloWorld.size()), file.length()); } TEST(FileTest, IsDirectory_NotOpen) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); std::error_code ec; ASSERT_FALSE(std::filesystem::is_directory(path, ec)); ASSERT_TRUE(std::filesystem::is_regular_file(path, ec)); } TEST(FileTest, IsDirectory_Open) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; const auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); std::error_code ec; ASSERT_FALSE(std::filesystem::is_directory(path, ec)); ASSERT_TRUE(std::filesystem::is_regular_file(path, ec)); } TEST(FileTest, LastWriteTime_NotOpen) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; const auto now = time(nullptr); const auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_LE(now, file.last_write_time()); } TEST(FileTest, LastWriteTime_Open) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; time_t now = time(nullptr); auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); ASSERT_LE(now, file.last_write_time()); } TEST(FileTest, Read) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); char buf[255]; ASSERT_EQ(static_cast<int>(kHelloWorld.length()), file.Read(buf, kHelloWorld.length())); buf[11] = 0; ASSERT_STREQ(kHelloWorld.c_str(), buf); } TEST(FileTest, GetName) { static const std::string kFileName = test_info_->name(); FileHelper helper; const auto path = helper.CreateTempFile(kFileName, "Hello World"); File file{path}; ASSERT_EQ(kFileName, file.path().filename().string()); } TEST(FileTest, EnsureTrailingSlash) { const auto single_slash = fmt::format("temp{}", File::pathSeparatorChar); const auto double_slash = fmt::format("temp{}{}", File::pathSeparatorChar, File::pathSeparatorChar); const std::string no_slash = "temp"; EXPECT_EQ(single_slash, File::EnsureTrailingSlash(single_slash)); EXPECT_EQ(double_slash, File::EnsureTrailingSlash(double_slash)); EXPECT_EQ(single_slash, File::EnsureTrailingSlash(no_slash)); } TEST(FileTest, CurrentDirectory) { char buf[MAX_PATH]; char* expected = getcwd(buf, MAX_PATH); const auto actual = File::current_directory().string(); EXPECT_STREQ(expected, actual.c_str()); } TEST(FileTest, SetCurrentDirectory) { char buf[MAX_PATH]; char* expected = getcwd(buf, MAX_PATH); const auto original_dir = File::current_directory().string(); ASSERT_STREQ(expected, original_dir.c_str()); FileHelper helper; File::set_current_directory(helper.TempDir()); EXPECT_EQ(helper.TempDir(), File::current_directory().string()); File::set_current_directory(original_dir); } TEST(FileTest, MakeAbsolutePath_Relative) { static const std::string kFileName{test_info_->name()}; FileHelper helper; const auto path = helper.CreateTempFile(kFileName, "Hello World"); const auto relative = File::absolute(helper.TempDir().string(), kFileName); EXPECT_EQ(path, relative); } TEST(FileTest, MakeAbsolutePath_AlreadyAbsolute) { static const std::string kFileName = test_info_->name(); FileHelper helper; const auto expected = helper.CreateTempFile(kFileName, "Hello World"); const auto path = File::absolute(helper.TempDir().string(), expected.string()); EXPECT_EQ(expected, path); } TEST(FileTest, MakeAbsolutePath_AlreadyAbsolute_Returning) { static const std::string kFileName = test_info_->name(); FileHelper helper; const auto expected = helper.CreateTempFile(kFileName, "Hello World"); const auto path = File::absolute(helper.TempDir().string(), expected.string()); EXPECT_EQ(expected, path); } TEST(FileTest, RealPath_Same) { static const std::string kFileName = test_info_->name(); FileHelper helper; const auto path = helper.CreateTempFile(kFileName, "Hello World"); const auto c = std::filesystem::canonical(path); EXPECT_EQ(path, c); } TEST(FileTest, RealPath_Different) { static const std::string kFileName{test_info_->name()}; FileHelper helper; const auto path = helper.CreateTempFile(kFileName, "Hello World"); // Add an extra ./ into the path. const auto suffix = FilePath(".", kFileName).string(); const auto full = FilePath(helper.TempDir(), suffix).string(); const auto canonical = File::canonical(full); EXPECT_EQ(path, canonical); } TEST(FileTest, mkdir) { const FileHelper helper{}; const auto path = FilePath(helper.TempDir(), "a"); const auto l = FilePath("b", "c").string(); const auto path_missing_middle = FilePath(path, l); ASSERT_FALSE(File::Exists(path)); ASSERT_TRUE(File::mkdir(path)); ASSERT_TRUE(File::mkdir(path)); // 2nd time should still return true. EXPECT_FALSE(File::mkdir(path_missing_middle)); // Can't create missing path elements. ASSERT_TRUE(File::Exists(path)); } TEST(FileTest, mkdirs) { FileHelper helper; const auto f = FilePath(helper.TempDir(), "a"); const auto l = FilePath("b", "c"); const auto path = FilePath(f, l.string()); ASSERT_FALSE(File::Exists(path)); ASSERT_TRUE(File::mkdirs(path)); ASSERT_TRUE(File::mkdirs(path)); ASSERT_TRUE(File::Exists(path)); } TEST(FileTest, Stream) { FileHelper file{}; File f(FilePath(file.TempDir(), "newdir")); std::stringstream s; s << f; ASSERT_EQ(f.full_pathname(), s.str()); } TEST(FileTest, IsOpen_Open) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; const auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); EXPECT_TRUE(file.IsOpen()); EXPECT_TRUE(static_cast<bool>(file)); } TEST(FileTest, IsOpen_NotOpen) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File file(path.concat("DNE")); EXPECT_FALSE(file.IsOpen()); EXPECT_FALSE(file); } TEST(FileTest, Seek) { static const std::string kContents = "0123456789"; FileHelper helper; const auto path = helper.CreateTempFile(test_info_->name(), kContents); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); EXPECT_EQ(0, file.Seek(0, File::Whence::begin)); char c{}; file.Read(&c, 1); EXPECT_EQ('0', c); EXPECT_EQ(3, file.Seek(2, File::Whence::current)); file.Read(&c, 1); EXPECT_EQ('3', c); EXPECT_EQ(static_cast<File::size_type>(kContents.size()), file.Seek(0, File::Whence::end)); EXPECT_EQ(0, file.Read(&c, 1)); } TEST(FileTest, CurrentPosition) { static const std::string kContents = "0123456789"; FileHelper helper; const auto path = helper.CreateTempFile(test_info_->name(), kContents); File file(path); ASSERT_TRUE(file.Open(File::modeBinary | File::modeReadOnly)); EXPECT_EQ(3, file.Seek(3, File::Whence::begin)); EXPECT_EQ(3, file.current_position()); EXPECT_EQ(static_cast<int>(kContents.size()), file.Seek(0, File::Whence::end)); EXPECT_EQ(static_cast<int>(kContents.size()), file.current_position()); } TEST(FileTest, FsCopyFile) { FileHelper file; auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); auto from = FilePath(tmp, "f1"); File f(from); f.Open(File::modeWriteOnly | File::modeCreateFile); f.Write("ok"); f.Close(); ASSERT_TRUE(File::Exists(f.path())) << f.full_pathname(); auto to = FilePath(tmp, "f2"); std::error_code ec; EXPECT_FALSE(File::Exists(to.string())); copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec); EXPECT_TRUE(File::Exists(to.string())); } TEST(FileTest, CopyFile) { FileHelper file; auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); auto f1 = FilePath(tmp, "f1"); File f(f1); f.Open(File::modeWriteOnly | File::modeCreateFile); f.Write("ok"); f.Close(); ASSERT_TRUE(File::Exists(f.path())) << f.full_pathname(); auto f2 = FilePath(tmp, "f2"); EXPECT_FALSE(File::Exists(f2)); File::Copy(f1, f2); EXPECT_TRUE(File::Exists(f2)); } TEST(FileTest, MoveFile) { FileHelper file; auto tmp = file.TempDir(); GTEST_ASSERT_NE("", tmp); ASSERT_TRUE(file.Mkdir("newdir")); auto f1 = FilePath(tmp, "f1"); File f(f1); f.Open(File::modeWriteOnly | File::modeCreateFile); f.Write("ok"); f.Close(); ASSERT_TRUE(File::Exists(f.path())) << f.full_pathname(); auto f2 = FilePath(tmp, "f2"); EXPECT_TRUE(File::Exists(f1)) << f1; EXPECT_FALSE(File::Exists(f2)); File::Move(f1, f2); EXPECT_TRUE(File::Exists(f2)); EXPECT_FALSE(File::Exists(f1)); } TEST(FileTest, Remove_String) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); ASSERT_TRUE(File::Exists(path)); File::Remove(path.string()); EXPECT_FALSE(File::Exists(path)); } TEST(FileTest, Remove_Path) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; const auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); ASSERT_TRUE(File::Exists(path)); File::Remove(path); EXPECT_FALSE(File::Exists(path)); } TEST(FileTest, Free) { const FileHelper file; const auto& tmp = file.TempDir(); const auto fs = File::freespace_for_path(tmp); EXPECT_GT(fs, 0); } TEST(FileTest, Move_Ctor) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File f(path); ASSERT_TRUE(f.Open(File::modeReadOnly)); ASSERT_TRUE(f.IsOpen()); ASSERT_NE(-1, f.handle()); auto f2(std::move(f)); ASSERT_TRUE(f2.IsOpen()); ASSERT_NE(-1, f2.handle()); ASSERT_FALSE(f.IsOpen()); // NOLINT ASSERT_EQ(-1, f.handle()); } TEST(FileTest, Move_Operator) { static const std::string kHelloWorld = "Hello World"; FileHelper helper; auto path = helper.CreateTempFile(test_info_->name(), kHelloWorld); File f(path); ASSERT_TRUE(f.Open(File::modeReadOnly)); ASSERT_TRUE(f.IsOpen()); ASSERT_NE(-1, f.handle()); File f2(path); f2 = std::move(f); ASSERT_TRUE(f2.IsOpen()); ASSERT_NE(-1, f2.handle()); ASSERT_FALSE(f.IsOpen()); // NOLINT ASSERT_EQ(-1, f.handle()); } TEST(FileSystemTest, Empty) { const std::filesystem::path p{""}; ASSERT_TRUE(p.empty()); } TEST(FileSystemTest, Path_IsDir) { const FileHelper file; const auto& tmp = file.TempDir(); auto p{tmp}; std::cerr << p << std::endl; ASSERT_TRUE(std::filesystem::is_directory(p)); } TEST(FileSystemTest, Path_WithoutDir) { std::filesystem::path p{"hello.txt"}; EXPECT_FALSE(wwiv::stl::contains(p.string(), File::pathSeparatorChar)) << "p: " << p.string(); } TEST(FileSystemTest, Path_WithWildCard) { std::filesystem::path p{"hello.*"}; EXPECT_FALSE(wwiv::stl::contains(p.string(), File::pathSeparatorChar)) << "p: " << p.string(); EXPECT_TRUE(wwiv::strings::ends_with(p.string(), "hello.*")) << "p: " << p.string(); } TEST(FileSystemTest, PathFilePath_Nested) { auto p = FilePath("foo", FilePath("bar", "baz")); auto expected = StrCat("foo", File::pathSeparatorChar, "bar", File::pathSeparatorChar, "baz"); EXPECT_EQ(expected, p.string()); }
32.313373
96
0.67132
granitepenguin
4b19207b80c7c3b104d61c04d0349239dc12b74f
16,732
cpp
C++
obs-studio/UI/api-interface.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/api-interface.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
obs-studio/UI/api-interface.cpp
noelemahcz/libobspp
029472b973e5a1985f883242f249848385df83a3
[ "MIT" ]
null
null
null
#include <obs-frontend-internal.hpp> #include "obs-app.hpp" #include "qt-wrappers.hpp" #include "window-basic-main.hpp" #include "window-basic-main-outputs.hpp" #include <functional> using namespace std; Q_DECLARE_METATYPE(OBSScene); Q_DECLARE_METATYPE(OBSSource); template<typename T> static T GetOBSRef(QListWidgetItem *item) { return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>(); } void EnumProfiles(function<bool(const char *, const char *)> &&cb); void EnumSceneCollections(function<bool(const char *, const char *)> &&cb); extern volatile bool streaming_active; extern volatile bool recording_active; extern volatile bool recording_paused; extern volatile bool replaybuf_active; extern volatile bool virtualcam_active; /* ------------------------------------------------------------------------- */ template<typename T> struct OBSStudioCallback { T callback; void *private_data; inline OBSStudioCallback(T cb, void *p) : callback(cb), private_data(p) { } }; template<typename T> inline size_t GetCallbackIdx(vector<OBSStudioCallback<T>> &callbacks, T callback, void *private_data) { for (size_t i = 0; i < callbacks.size(); i++) { OBSStudioCallback<T> curCB = callbacks[i]; if (curCB.callback == callback && curCB.private_data == private_data) return i; } return (size_t)-1; } struct OBSStudioAPI : obs_frontend_callbacks { OBSBasic *main; vector<OBSStudioCallback<obs_frontend_event_cb>> callbacks; vector<OBSStudioCallback<obs_frontend_save_cb>> saveCallbacks; vector<OBSStudioCallback<obs_frontend_save_cb>> preloadCallbacks; inline OBSStudioAPI(OBSBasic *main_) : main(main_) {} void *obs_frontend_get_main_window(void) override { return (void *)main; } void *obs_frontend_get_main_window_handle(void) override { return (void *)main->winId(); } void *obs_frontend_get_system_tray(void) override { return (void *)main->trayIcon.data(); } void obs_frontend_get_scenes( struct obs_frontend_source_list *sources) override { for (int i = 0; i < main->ui->scenes->count(); i++) { QListWidgetItem *item = main->ui->scenes->item(i); OBSScene scene = GetOBSRef<OBSScene>(item); obs_source_t *source = obs_scene_get_source(scene); if (obs_source_get_ref(source) != nullptr) da_push_back(sources->sources, &source); } } obs_source_t *obs_frontend_get_current_scene(void) override { if (main->IsPreviewProgramMode()) { return obs_weak_source_get_source(main->programScene); } else { OBSSource source = main->GetCurrentSceneSource(); return obs_source_get_ref(source); } } void obs_frontend_set_current_scene(obs_source_t *scene) override { if (main->IsPreviewProgramMode()) { QMetaObject::invokeMethod( main, "TransitionToScene", WaitConnection(), Q_ARG(OBSSource, OBSSource(scene))); } else { QMetaObject::invokeMethod( main, "SetCurrentScene", WaitConnection(), Q_ARG(OBSSource, OBSSource(scene)), Q_ARG(bool, false)); } } void obs_frontend_get_transitions( struct obs_frontend_source_list *sources) override { for (int i = 0; i < main->ui->transitions->count(); i++) { obs_source_t *tr = main->ui->transitions->itemData(i) .value<OBSSource>(); if (!tr) continue; if (obs_source_get_ref(tr) != nullptr) da_push_back(sources->sources, &tr); } } obs_source_t *obs_frontend_get_current_transition(void) override { OBSSource tr = main->GetCurrentTransition(); return obs_source_get_ref(tr); } void obs_frontend_set_current_transition(obs_source_t *transition) override { QMetaObject::invokeMethod(main, "SetTransition", Q_ARG(OBSSource, OBSSource(transition))); } int obs_frontend_get_transition_duration(void) override { return main->ui->transitionDuration->value(); } void obs_frontend_set_transition_duration(int duration) override { QMetaObject::invokeMethod(main->ui->transitionDuration, "setValue", Q_ARG(int, duration)); } void obs_frontend_release_tbar(void) override { QMetaObject::invokeMethod(main, "TBarReleased"); } void obs_frontend_set_tbar_position(int position) override { QMetaObject::invokeMethod(main, "TBarChanged", Q_ARG(int, position)); } int obs_frontend_get_tbar_position(void) override { return main->tBar->value(); } void obs_frontend_get_scene_collections( std::vector<std::string> &strings) override { auto addCollection = [&](const char *name, const char *) { strings.emplace_back(name); return true; }; EnumSceneCollections(addCollection); } char *obs_frontend_get_current_scene_collection(void) override { const char *cur_name = config_get_string( App()->GlobalConfig(), "Basic", "SceneCollection"); return bstrdup(cur_name); } void obs_frontend_set_current_scene_collection( const char *collection) override { QList<QAction *> menuActions = main->ui->sceneCollectionMenu->actions(); QString qstrCollection = QT_UTF8(collection); for (int i = 0; i < menuActions.count(); i++) { QAction *action = menuActions[i]; QVariant v = action->property("file_name"); if (v.typeName() != nullptr) { if (action->text() == qstrCollection) { action->trigger(); break; } } } } bool obs_frontend_add_scene_collection(const char *name) override { bool success = false; QMetaObject::invokeMethod(main, "AddSceneCollection", WaitConnection(), Q_RETURN_ARG(bool, success), Q_ARG(bool, true), Q_ARG(QString, QT_UTF8(name))); return success; } void obs_frontend_get_profiles(std::vector<std::string> &strings) override { auto addProfile = [&](const char *name, const char *) { strings.emplace_back(name); return true; }; EnumProfiles(addProfile); } char *obs_frontend_get_current_profile(void) override { const char *name = config_get_string(App()->GlobalConfig(), "Basic", "Profile"); return bstrdup(name); } char *obs_frontend_get_current_profile_path(void) override { char profilePath[512]; int ret = GetProfilePath(profilePath, sizeof(profilePath), ""); if (ret <= 0) return nullptr; return bstrdup(profilePath); } void obs_frontend_set_current_profile(const char *profile) override { QList<QAction *> menuActions = main->ui->profileMenu->actions(); QString qstrProfile = QT_UTF8(profile); for (int i = 0; i < menuActions.count(); i++) { QAction *action = menuActions[i]; QVariant v = action->property("file_name"); if (v.typeName() != nullptr) { if (action->text() == qstrProfile) { action->trigger(); break; } } } } void obs_frontend_create_profile(const char *name) override { QMetaObject::invokeMethod(main, "NewProfile", Q_ARG(QString, name)); } void obs_frontend_duplicate_profile(const char *name) override { QMetaObject::invokeMethod(main, "DuplicateProfile", Q_ARG(QString, name)); } void obs_frontend_delete_profile(const char *profile) override { QMetaObject::invokeMethod(main, "DeleteProfile", Q_ARG(QString, profile)); } void obs_frontend_streaming_start(void) override { QMetaObject::invokeMethod(main, "StartStreaming"); } void obs_frontend_streaming_stop(void) override { QMetaObject::invokeMethod(main, "StopStreaming"); } bool obs_frontend_streaming_active(void) override { return os_atomic_load_bool(&streaming_active); } void obs_frontend_recording_start(void) override { QMetaObject::invokeMethod(main, "StartRecording"); } void obs_frontend_recording_stop(void) override { QMetaObject::invokeMethod(main, "StopRecording"); } bool obs_frontend_recording_active(void) override { return os_atomic_load_bool(&recording_active); } void obs_frontend_recording_pause(bool pause) override { QMetaObject::invokeMethod(main, pause ? "PauseRecording" : "UnpauseRecording"); } bool obs_frontend_recording_paused(void) override { return os_atomic_load_bool(&recording_paused); } void obs_frontend_replay_buffer_start(void) override { QMetaObject::invokeMethod(main, "StartReplayBuffer"); } void obs_frontend_replay_buffer_save(void) override { QMetaObject::invokeMethod(main, "ReplayBufferSave"); } void obs_frontend_replay_buffer_stop(void) override { QMetaObject::invokeMethod(main, "StopReplayBuffer"); } bool obs_frontend_replay_buffer_active(void) override { return os_atomic_load_bool(&replaybuf_active); } void *obs_frontend_add_tools_menu_qaction(const char *name) override { main->ui->menuTools->setEnabled(true); return (void *)main->ui->menuTools->addAction(QT_UTF8(name)); } void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data) override { main->ui->menuTools->setEnabled(true); auto func = [private_data, callback]() { callback(private_data); }; QAction *action = main->ui->menuTools->addAction(QT_UTF8(name)); QObject::connect(action, &QAction::triggered, func); } void *obs_frontend_add_dock(void *dock) override { return (void *)main->AddDockWidget((QDockWidget *)dock); } void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(callbacks, callback, private_data); if (idx == (size_t)-1) callbacks.emplace_back(callback, private_data); } void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(callbacks, callback, private_data); if (idx == (size_t)-1) return; callbacks.erase(callbacks.begin() + idx); } obs_output_t *obs_frontend_get_streaming_output(void) override { OBSOutput output = main->outputHandler->streamOutput.Get(); return obs_output_get_ref(output); } obs_output_t *obs_frontend_get_recording_output(void) override { OBSOutput out = main->outputHandler->fileOutput.Get(); return obs_output_get_ref(out); } obs_output_t *obs_frontend_get_replay_buffer_output(void) override { OBSOutput out = main->outputHandler->replayBuffer.Get(); return obs_output_get_ref(out); } config_t *obs_frontend_get_profile_config(void) override { return main->basicConfig; } config_t *obs_frontend_get_global_config(void) override { return App()->GlobalConfig(); } void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name) override { SavedProjectorInfo proj = { ProjectorType::Preview, monitor, geometry ? geometry : "", name ? name : "", }; if (type) { if (astrcmpi(type, "Source") == 0) proj.type = ProjectorType::Source; else if (astrcmpi(type, "Scene") == 0) proj.type = ProjectorType::Scene; else if (astrcmpi(type, "StudioProgram") == 0) proj.type = ProjectorType::StudioProgram; else if (astrcmpi(type, "Multiview") == 0) proj.type = ProjectorType::Multiview; } QMetaObject::invokeMethod(main, "OpenSavedProjector", WaitConnection(), Q_ARG(SavedProjectorInfo *, &proj)); } void obs_frontend_save(void) override { main->SaveProject(); } void obs_frontend_defer_save_begin(void) override { QMetaObject::invokeMethod(main, "DeferSaveBegin"); } void obs_frontend_defer_save_end(void) override { QMetaObject::invokeMethod(main, "DeferSaveEnd"); } void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); if (idx == (size_t)-1) saveCallbacks.emplace_back(callback, private_data); } void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); if (idx == (size_t)-1) return; saveCallbacks.erase(saveCallbacks.begin() + idx); } void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); if (idx == (size_t)-1) preloadCallbacks.emplace_back(callback, private_data); } void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); if (idx == (size_t)-1) return; preloadCallbacks.erase(preloadCallbacks.begin() + idx); } void obs_frontend_push_ui_translation( obs_frontend_translate_ui_cb translate) override { App()->PushUITranslation(translate); } void obs_frontend_pop_ui_translation(void) override { App()->PopUITranslation(); } void obs_frontend_set_streaming_service(obs_service_t *service) override { main->SetService(service); } obs_service_t *obs_frontend_get_streaming_service(void) override { return main->GetService(); } void obs_frontend_save_streaming_service(void) override { main->SaveService(); } bool obs_frontend_preview_program_mode_active(void) override { return main->IsPreviewProgramMode(); } void obs_frontend_set_preview_program_mode(bool enable) override { main->SetPreviewProgramMode(enable); } void obs_frontend_preview_program_trigger_transition(void) override { QMetaObject::invokeMethod(main, "TransitionClicked"); } bool obs_frontend_preview_enabled(void) override { return main->previewEnabled; } void obs_frontend_set_preview_enabled(bool enable) override { if (main->previewEnabled != enable) main->EnablePreviewDisplay(enable); } obs_source_t *obs_frontend_get_current_preview_scene(void) override { if (main->IsPreviewProgramMode()) { OBSSource source = main->GetCurrentSceneSource(); return obs_source_get_ref(source); } return nullptr; } void obs_frontend_set_current_preview_scene(obs_source_t *scene) override { if (main->IsPreviewProgramMode()) { QMetaObject::invokeMethod(main, "SetCurrentScene", Q_ARG(OBSSource, OBSSource(scene)), Q_ARG(bool, false)); } } void obs_frontend_take_screenshot(void) override { QMetaObject::invokeMethod(main, "Screenshot"); } void obs_frontend_take_source_screenshot(obs_source_t *source) override { QMetaObject::invokeMethod(main, "Screenshot", Q_ARG(OBSSource, OBSSource(source))); } obs_output_t *obs_frontend_get_virtualcam_output(void) override { OBSOutput output = main->outputHandler->virtualCam.Get(); return obs_output_get_ref(output); } void obs_frontend_start_virtualcam(void) override { QMetaObject::invokeMethod(main, "StartVirtualCam"); } void obs_frontend_stop_virtualcam(void) override { QMetaObject::invokeMethod(main, "StopVirtualCam"); } bool obs_frontend_virtualcam_active(void) override { return os_atomic_load_bool(&virtualcam_active); } void obs_frontend_reset_video(void) override { main->ResetVideo(); } void obs_frontend_open_source_properties(obs_source_t *source) override { QMetaObject::invokeMethod(main, "OpenProperties", Q_ARG(OBSSource, OBSSource(source))); } void obs_frontend_open_source_filters(obs_source_t *source) override { QMetaObject::invokeMethod(main, "OpenFilters", Q_ARG(OBSSource, OBSSource(source))); } void obs_frontend_open_source_interaction(obs_source_t *source) override { QMetaObject::invokeMethod(main, "OpenInteraction", Q_ARG(OBSSource, OBSSource(source))); } char *obs_frontend_get_current_record_output_path(void) override { const char *recordOutputPath = main->GetCurrentOutputPath(); return bstrdup(recordOutputPath); } void on_load(obs_data_t *settings) override { for (size_t i = saveCallbacks.size(); i > 0; i--) { auto cb = saveCallbacks[i - 1]; cb.callback(settings, false, cb.private_data); } } void on_preload(obs_data_t *settings) override { for (size_t i = preloadCallbacks.size(); i > 0; i--) { auto cb = preloadCallbacks[i - 1]; cb.callback(settings, false, cb.private_data); } } void on_save(obs_data_t *settings) override { for (size_t i = saveCallbacks.size(); i > 0; i--) { auto cb = saveCallbacks[i - 1]; cb.callback(settings, true, cb.private_data); } } void on_event(enum obs_frontend_event event) override { if (main->disableSaving && event != OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP && event != OBS_FRONTEND_EVENT_EXIT) return; for (size_t i = callbacks.size(); i > 0; i--) { auto cb = callbacks[i - 1]; cb.callback(event, cb.private_data); } } }; obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main) { obs_frontend_callbacks *api = new OBSStudioAPI(main); obs_frontend_set_callbacks_internal(api); return api; }
25.085457
79
0.725795
noelemahcz
4b1bcd262ffccd0c65e429860aedd84411df8637
6,881
hpp
C++
hot/lib/hot/rowex/include/hot/rowex/HOTRowexInsertStack.hpp
jyizheng/hydralist
910dad17eab4815057e3ea3e46b02f6ce45d7e46
[ "Apache-2.0" ]
99
2018-03-23T11:08:48.000Z
2022-03-03T10:03:35.000Z
libs/hot/rowex/include/hot/rowex/HOTRowexInsertStack.hpp
SheldonZhong/hot
ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0
[ "ISC" ]
3
2018-12-18T19:00:04.000Z
2021-09-07T13:05:36.000Z
libs/hot/rowex/include/hot/rowex/HOTRowexInsertStack.hpp
SheldonZhong/hot
ec29331ecb4b0d5381b90d5b45ce2319b7cfeff0
[ "ISC" ]
29
2018-06-03T07:56:35.000Z
2022-03-04T07:31:50.000Z
#ifndef __HOT__ROWEX__INSERT_STACK__ #define __HOT__ROWEX__INSERT_STACK__ #include <stdio.h> #include <execinfo.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <hot/commons/InsertInformation.hpp> #include <hot/commons/DiscriminativeBit.hpp> #include <idx/contenthelpers/OptionalValue.hpp> #include <idx/contenthelpers/TidConverters.hpp> #include <idx/contenthelpers/KeyUtilities.hpp> #include "hot/rowex/HOTRowexChildPointer.hpp" #include "hot/rowex/HOTRowexFirstInsertLevel.hpp" namespace hot { namespace rowex { template<typename ValueType, template<typename> typename KeyExtractor, typename InsertStackEntry> struct HOTRowexInsertStack { static KeyExtractor<ValueType> extractKey; using KeyType = decltype(extractKey(std::declval<ValueType>())); using EntryType = InsertStackEntry; char mRawStack[64 * sizeof(EntryType)]; EntryType* mLeafEntry; EntryType const * getRawStack() const { return reinterpret_cast<EntryType const*>(mRawStack); } EntryType* getRawStack() { return reinterpret_cast<EntryType*>(mRawStack); } //do not initialize, for performance Reasons HOTRowexInsertStack(HOTRowexChildPointer currentRoot, HOTRowexChildPointer* rootPointer, uint8_t const *newKeyBytes) : mLeafEntry(reinterpret_cast<EntryType*>(mRawStack)) { HOTRowexChildPointer* currentPointerLocation = rootPointer; HOTRowexChildPointer currentPointer = currentRoot; while (!currentPointer.isLeaf()) { mLeafEntry->initNode(currentPointerLocation, currentPointer); currentPointerLocation = currentPointer.executeForSpecificNodeType(true, [&,this](auto &node) { return node.searchForInsert(mLeafEntry->mSearchResultForInsert, newKeyBytes); }); currentPointer = *currentPointerLocation; ++mLeafEntry; } mLeafEntry->initLeaf(currentPointerLocation, currentPointer); } bool isConsistent(EntryType* firstLockedEntry, unsigned int numberLockedEntries) { bool isConsistent = true; //start at minus one to check that the considered entry in the firstLockedEntry is still the same (not already replaced or leaf node pushdown or similar) for(int i=-1; i < static_cast<int>(numberLockedEntries); ++i) { isConsistent &= (firstLockedEntry - i)->isConsistent(); } return isConsistent; } /*** * * @param newDiscriminativeBit * @param insertDepth * * @return the number entries locked or 0 it the lock could not be aquired */ inline unsigned int tryLock(HOTRowexChildPointer* mRoot, HOTRowexFirstInsertLevel<EntryType> const & insertLevel) { EntryType* firstInsertStackEntry = insertLevel.mFirstEntry; EntryType* insertStackEntry = firstInsertStackEntry; HOTRowexChildPointer currentNode = insertStackEntry->getChildPointer(); int numberLockedEntries = 0; bool lockedSuccessfully = insertStackEntry->tryLock(); numberLockedEntries += static_cast<unsigned int>(lockedSuccessfully); if(lockedSuccessfully & (!insertLevel.mIsLeafNodePushdown) & (insertStackEntry > getRawStack())) { EntryType* parentStackEntry = insertStackEntry - 1; lockedSuccessfully = parentStackEntry->tryLock(); numberLockedEntries += static_cast<unsigned int>(lockedSuccessfully); while ((lockedSuccessfully & (parentStackEntry > getRawStack())) && ((currentNode.getNode()->isFull()) & ((currentNode.getHeight() + 1) == parentStackEntry->getChildPointer().getHeight()))) { currentNode = parentStackEntry->getChildPointer(); lockedSuccessfully = (--parentStackEntry)->tryLock(); numberLockedEntries += static_cast<unsigned int>(lockedSuccessfully); } } if(!lockedSuccessfully || !isConsistent(insertStackEntry, numberLockedEntries)) { for(int i=numberLockedEntries - 1; i >= 0; --i) { (firstInsertStackEntry - i)->unlock(); } numberLockedEntries = 0; } assert([&]() -> bool { EntryType *lastLockedEntry = firstInsertStackEntry + numberLockedEntries - 1; return (numberLockedEntries == 0 || lastLockedEntry != getRawStack() || *mRoot == lastLockedEntry->getChildPointer()); }()); return numberLockedEntries; } HOTRowexFirstInsertLevel<EntryType> determineInsertLevel(hot::commons::DiscriminativeBit const & mismatchingBit) { EntryType* nextInsertStackEntry = getRawStack() + 1u; //searches for the node to insert the new value into., typename InsertStackEntry //Be aware that this can result in a false positive. Therefor in case only a single entry is affected and it has a child node it must be inserted into the child node //this is an alternative approach to using getLeastSignificantDiscriminativeBitForEntry while ((mismatchingBit.mAbsoluteBitIndex > nextInsertStackEntry->mSearchResultForInsert.mMostSignificantBitIndex) & (nextInsertStackEntry < mLeafEntry)) { ++nextInsertStackEntry; } EntryType* possibleInsertStackEntry = nextInsertStackEntry - 1u; //this is ensured because mMostSignificantDiscriminativeBitIndex is set to MAX_INT16 for the leaf entry assert(possibleInsertStackEntry < mLeafEntry); hot::commons::InsertInformation const &insertInformation = possibleInsertStackEntry->getInsertInformation(mismatchingBit); bool isSingleEntry = possibleInsertStackEntry->isSingleEntryAffected(insertInformation); bool isLeafEntry = (nextInsertStackEntry == mLeafEntry); bool isBoundaryNode = isSingleEntry & (!isLeafEntry); return (isBoundaryNode) //in this case the single entry is a boundary entry -> insert the value into the child partition //As the insert results in a new partition root, no prefix bits are set and all entries in the partition are affected ? HOTRowexFirstInsertLevel<EntryType> { nextInsertStackEntry , {0, 0, static_cast<uint32_t>(nextInsertStackEntry->getChildPointer().getNode()->getNumberEntries()), mismatchingBit}, false } : HOTRowexFirstInsertLevel<EntryType> { possibleInsertStackEntry, insertInformation, isSingleEntry & isLeafEntry & (possibleInsertStackEntry->getChildPointer().getHeight() > 1) }; } idx::contenthelpers::OptionalValue<hot::commons::DiscriminativeBit> getMismatchingBit(uint8_t const *newKeyBytes) const { intptr_t tid = mLeafEntry->getChildPointer().getTid(); ValueType const &existingValue = idx::contenthelpers::tidToValue<ValueType>(tid); KeyType const &existingKey = extractKey(existingValue); auto const &existingFixedSizeKey = idx::contenthelpers::toFixSizedKey( idx::contenthelpers::toBigEndianByteOrder(existingKey)); uint8_t const *existingKeyBytes = idx::contenthelpers::interpretAsByteArray(existingFixedSizeKey); return hot::commons::getMismatchingBit(existingKeyBytes, newKeyBytes, static_cast<uint16_t>(idx::contenthelpers::getMaxKeyLength<KeyType>())); } }; template<typename ValueType, template <typename> typename KeyExtractor, typename InsertStackEntry> KeyExtractor<ValueType> HOTRowexInsertStack<ValueType, KeyExtractor, InsertStackEntry>::extractKey; }} #endif
44.108974
198
0.775323
jyizheng