From 07ba428806d4e8a1a608193e875f0e765bf61d95 Mon Sep 17 00:00:00 2001 From: Denis Koronchik Date: Thu, 29 Jul 2021 01:17:44 +0200 Subject: [PATCH 1/5] [cmake][sc-memory] Support arm64 on OSX --- CMakeLists.txt | 21 ++++++++++++++----- cmake/FindLibClang.cmake | 1 + sc-memory/sc-core/sc-store/sc_element.h | 2 +- .../sc-store/sc_event/sc_event_private.h | 2 -- .../sc-store/sc_event/sc_event_queue.c | 2 -- .../tests/sc-memory/performance/main.cpp | 12 ++++++++++- sc-network/sctp_client/sctpClient.hpp | 3 --- 7 files changed, 29 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a900dc65..2998cfb22 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,22 +2,34 @@ project (sc-machine) site_name (www.ostis.net) cmake_minimum_required (VERSION 2.8) -include(CTest) +include (CTest) +include (CheckCCompilerFlag) -set(SC_BIN_PATH "${CMAKE_CURRENT_LIST_DIR}/bin") +set (SC_BIN_PATH "${CMAKE_CURRENT_LIST_DIR}/bin") -set(SC_MACHINE_ROOT ${CMAKE_CURRENT_LIST_DIR}) -set(SC_MACHINE_THIRDPARTY_PATH "${SC_MACHINE_ROOT}/thirdparty") +set (SC_MACHINE_ROOT ${CMAKE_CURRENT_LIST_DIR}) +set (SC_MACHINE_THIRDPARTY_PATH "${SC_MACHINE_ROOT}/thirdparty") option (SC_AUTO_TEST "Flag to build for automation testing" OFF) option (SC_KPM_SCP "Flag to build SCP module" OFF) option (SC_BUILD_SCTP "Flag to turn on/off sctp protocol support" OFF) +option (SC_BUILD_ARM64 "Flag to build arm64" OFF) set(SC_USE_SANITIZER "none" CACHE STRING "Build with specified sanitizer") set_property(CACHE SC_USE_SANITIZER PROPERTY STRINGS none address memory) message ("Sanitizer: ${SC_USE_SANITIZER}") +if (${SC_BUILD_ARM64}) + check_c_compiler_flag("-arch arm64" IS_ARM64_SUPPORTED) + if (${IS_ARM64_SUPPORTED}) + set (CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "Used architecture" FORCE) + message ("-- Architecture: arm64") + else() + message (FATAL_ERROR "Arm64 platform is not supported by compiler") + endif() +endif() + # codegen if (${UNIX}) set(SC_CODEGEN_TOOL "${SC_BIN_PATH}/sc-code-generator") @@ -91,7 +103,6 @@ if (${APPLE}) set (GLIB2_LIBRARIES ${GLIB_LDFLAGS} ${GLIB2_MODULE_LDFLAGS}) - set (LIBCLANG_LLVM_CONFIG_EXECUTABLE "/usr/local/opt/llvm/bin/llvm-config") if (NOT DEFINED LIBCLANG_LIBRARIES OR NOT DEFINED LIBCLANG_CXXFLAGS OR NOT DEFINED LIBCLANG_LIBDIR) find_package(LibClang REQUIRED) endif () diff --git a/cmake/FindLibClang.cmake b/cmake/FindLibClang.cmake index 0b26df825..17fbb144c 100644 --- a/cmake/FindLibClang.cmake +++ b/cmake/FindLibClang.cmake @@ -48,6 +48,7 @@ if (NOT LIBCLANG_LLVM_CONFIG_EXECUTABLE) set(llvm_config_names llvm-config) foreach(minor RANGE 9 0) list(APPEND llvm_config_names + "llvm-config" "llvm-config-7" "llvm-config-6.${minor}" "llvm-config-5.${minor}" diff --git a/sc-memory/sc-core/sc-store/sc_element.h b/sc-memory/sc-core/sc-store/sc_element.h index 41e58196e..11f4235d8 100644 --- a/sc-memory/sc-core/sc-store/sc_element.h +++ b/sc-memory/sc-core/sc-store/sc_element.h @@ -21,7 +21,7 @@ struct _sc_arc_info }; -#define SC_CHECKSUM_LEN 32//(sizeof(sc_arc_info) - sizeof(sc_uint32)) +#define SC_CHECKSUM_LEN 32 //(sizeof(sc_arc_info) - sizeof(sc_uint32)) /*! Structure to store content information * Data field store checksum for data, that stores in specified sc-link. diff --git a/sc-memory/sc-core/sc-store/sc_event/sc_event_private.h b/sc-memory/sc-core/sc-store/sc_event/sc_event_private.h index 431e87fcf..e2b7904c0 100644 --- a/sc-memory/sc-core/sc-store/sc_event/sc_event_private.h +++ b/sc-memory/sc-core/sc-store/sc_event/sc_event_private.h @@ -20,7 +20,6 @@ #define SC_EVENT_REQUEST_DESTROY (1 << 31) #define SC_EVENT_REF_COUNT_MASK (~SC_EVENT_REQUEST_DESTROY) -#pragma pack(push, 1) /*! Structure that contains information about event */ struct _sc_event @@ -45,7 +44,6 @@ struct _sc_event sc_access_levels access_levels; }; -#pragma pack(pop) //! Function to initialize sc-events module diff --git a/sc-memory/sc-core/sc-store/sc_event/sc_event_queue.c b/sc-memory/sc-core/sc-store/sc_event/sc_event_queue.c index a4513341c..d9e583baa 100644 --- a/sc-memory/sc-core/sc-store/sc_event/sc_event_queue.c +++ b/sc-memory/sc-core/sc-store/sc_event/sc_event_queue.c @@ -11,14 +11,12 @@ #include "../../sc_memory_private.h" #include "../../sc_memory.h" -#pragma pack(push, 1) typedef struct { sc_event * evt; sc_addr edge_addr; sc_addr other_addr; } sc_event_pool_worker_data; -#pragma pack(pop) sc_event_pool_worker_data * sc_event_pool_worker_data_new(sc_event * evt, sc_addr edge_addr, sc_addr other_addr) { diff --git a/sc-memory/tests/sc-memory/performance/main.cpp b/sc-memory/tests/sc-memory/performance/main.cpp index ed94616f6..6b1921e63 100644 --- a/sc-memory/tests/sc-memory/performance/main.cpp +++ b/sc-memory/tests/sc-memory/performance/main.cpp @@ -52,6 +52,11 @@ void BM_MemoryThreaded(benchmark::State & state) int constexpr kNodeIters = 10000000; +BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) + ->Threads(1) + ->Iterations(kNodeIters) + ->Unit(benchmark::TimeUnit::kMicrosecond); + BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) ->Threads(2) ->Iterations(kNodeIters / 2) @@ -72,7 +77,12 @@ BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) ->Iterations(kNodeIters / 16) ->Unit(benchmark::TimeUnit::kMicrosecond); -int constexpr kLinkIters = 25000; +int constexpr kLinkIters = 2500; + +BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) + ->Threads(1) + ->Iterations(kLinkIters) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) ->Threads(2) diff --git a/sc-network/sctp_client/sctpClient.hpp b/sc-network/sctp_client/sctpClient.hpp index e2d9e2117..3c35762bc 100644 --- a/sc-network/sctp_client/sctpClient.hpp +++ b/sc-network/sctp_client/sctpClient.hpp @@ -20,7 +20,6 @@ namespace sctp #define SCTP_ADDR_SIZE (sizeof(ScRealAddr)) -#pragma pack(push,1) struct RequestHeader { sc_uint8 commandType; @@ -76,8 +75,6 @@ struct ResultHeader }; -#pragma pack(pop) - class Iterator { friend class Client; From 6ba5a912e32eba3fb5ef09da2d747d01327049cd Mon Sep 17 00:00:00 2001 From: Denis Koronchik Date: Thu, 29 Jul 2021 01:22:22 +0200 Subject: [PATCH 2/5] [changelog] Update changelog --- docs/changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/changelog.md b/docs/changelog.md index a5896e1b7..bd99434af 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,7 @@ - **Build system**: - Set project binaries path to root (#352) + - Support arm64 build - **Core**: - Fix issue with erasing empty sc-link From d147e9732296e3fc6cc7992dfc5a6ac3618e1d7a Mon Sep 17 00:00:00 2001 From: Denis Koronchik Date: Thu, 29 Jul 2021 01:28:01 +0200 Subject: [PATCH 3/5] [ci] Fix CI build --- scripts/ci/install-deps.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci/install-deps.sh b/scripts/ci/install-deps.sh index 885c6b13d..c6ace65e3 100755 --- a/scripts/ci/install-deps.sh +++ b/scripts/ci/install-deps.sh @@ -15,4 +15,5 @@ packagelist=( python3-pip python3-setuptools ) +sudo apt-get update sudo apt-get install ${packagelist[@]} From d99ae77984b112692ad9299080d378d7dc9f0ab5 Mon Sep 17 00:00:00 2001 From: Denis Koronchik Date: Fri, 30 Jul 2021 00:08:06 +0200 Subject: [PATCH 4/5] [git] Add clang code formatting --- .clang-format | 162 +++++++++++++++++++++++++++++++++ .github/workflows/main.yml | 13 +++ scripts/ci/check-formatting.sh | 13 +++ scripts/ci/install-deps.sh | 2 +- scripts/format-code.sh | 10 ++ scripts/tools/format-code.py | 133 +++++++++++++++++++++++++++ 6 files changed, 332 insertions(+), 1 deletion(-) create mode 100644 .clang-format create mode 100755 scripts/ci/check-formatting.sh create mode 100755 scripts/format-code.sh create mode 100644 scripts/tools/format-code.py diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..7da9b431a --- /dev/null +++ b/.clang-format @@ -0,0 +1,162 @@ +Language: Cpp +# BasedOnStyle: Google +AccessModifierOffset: -2 +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: DontAlign +AlignOperands: true +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortLambdasOnASingleLine: Empty +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: true + BeforeWhile: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true + +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: true +BreakInheritanceList: BeforeComma +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^\s*(\*)?\s*\\.+' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +# EmptyLineBeforeAccessModifier: Always +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^<(gtest|gmock)/.*' + Priority: 1 + + - Regex: '^ bool: + files = self.collect_files(search_paths) + + final_result = True + non_formatted_files = [] + + for f in files: + print('Check {}'.format(f), end='') + cmd = "{} --output-replacements-xml {}".format(Formatter.Executable, f) + + process = subprocess.Popen(cmd, shell=True, cwd=os.getcwd(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + rc = process.wait() + output = process.communicate()[0] + + passed = False + + if rc == 0: + + passed = True + # check if there are any replacements + s = output.decode("utf-8") + if len(s) > 0: + root = ET.fromstring(s) + replacements = root.findall("replacement") + + if len(replacements) > 0: + passed = False + + if not passed: + final_result = False + non_formatted_files.append(f) + + print (" - {}".format("ok" if passed else "fail")) + + return (final_result, non_formatted_files) + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser(description="Process some integers.") + parser.add_argument( + "files", + nargs="*", + help= + "List of input files or folders (relative to the working directory)", + ) + parser.add_argument("--check", action="store_true") + + args = parser.parse_args() + + c = Formatter() + if args.check: + passed, files = c.check(args.files) + if not passed: + if len(files) > 0: + print ("-" * 10) + print("Files that need formatting:") + for f in files: + print(" {}".format(f)) + else: + print ("-" * 10) + print ("All checks passed") + + sys.exit(0 if passed else 1) + else: + c.format(args.files) \ No newline at end of file From 71a9ec9faf3d2be97abd6a06450ce5b18c705ea4 Mon Sep 17 00:00:00 2001 From: Denis Koronchik Date: Fri, 30 Jul 2021 00:56:44 +0200 Subject: [PATCH 5/5] [format] Format code with clang --- .clang-format | 22 +- .github/workflows/main.yml | 2 +- docs/dev/pr.md | 1 + .../translators/uiSc2SCgJsonTranslator.cpp | 11 +- .../translators/uiSc2SCnJsonTranslator.cpp | 94 +- .../translators/uiSc2ScsJsonTranslator.cpp | 40 +- .../sc-ui/translators/uiTranslatorFromSc.cpp | 19 +- sc-kpm/sc-ui/ui.cpp | 5 +- sc-kpm/sc-ui/uiCommands.cpp | 241 +-- sc-kpm/sc-ui/uiKeynodes.cpp | 16 +- sc-kpm/sc-ui/uiTranslators.cpp | 65 +- sc-kpm/sc-ui/uiTypes.cpp | 9 +- sc-kpm/sc-ui/uiUtils.cpp | 3 +- .../scp_system_operators/sc_system_gen.cpp | 156 +- .../sc_system_operators.cpp | 485 +++--- .../scp_system_operators/sc_system_search.cpp | 1389 +++++++++-------- .../scp_system_operators/scp_sys_gen.cpp | 116 +- .../scp_system_operators/scp_sys_search.cpp | 245 +-- sc-memory/sc-core/sc-store/sc_fm_engine.cpp | 40 +- sc-memory/sc-memory/http/sc_http_request.cpp | 20 +- sc-memory/sc-memory/http/sc_http_request.hpp | 6 +- sc-memory/sc-memory/http/sc_http_response.hpp | 2 +- sc-memory/sc-memory/kpm/sc_agent.cpp | 66 +- sc-memory/sc-memory/kpm/sc_agent.hpp | 43 +- sc-memory/sc-memory/sc_addr.cpp | 6 +- sc-memory/sc-memory/sc_addr.hpp | 30 +- sc-memory/sc-memory/sc_common_templ.cpp | 19 +- sc-memory/sc-memory/sc_common_templ.hpp | 19 +- sc-memory/sc-memory/sc_debug.cpp | 43 +- sc-memory/sc-memory/sc_debug.hpp | 233 +-- sc-memory/sc-memory/sc_defines.hpp | 56 +- sc-memory/sc-memory/sc_event.cpp | 25 +- sc-memory/sc-memory/sc_event.hpp | 11 +- sc-memory/sc-memory/sc_iterator.cpp | 153 +- sc-memory/sc-memory/sc_iterator.hpp | 37 +- sc-memory/sc-memory/sc_keynodes.cpp | 14 +- sc-memory/sc-memory/sc_link.cpp | 18 +- sc-memory/sc-memory/sc_link.hpp | 119 +- sc-memory/sc-memory/sc_memory.cpp | 54 +- sc-memory/sc-memory/sc_memory.hpp | 88 +- sc-memory/sc-memory/sc_memory_headers.hpp | 2 +- sc-memory/sc-memory/sc_module.cpp | 2 - sc-memory/sc-memory/sc_module.hpp | 3 +- sc-memory/sc-memory/sc_object.cpp | 5 +- sc-memory/sc-memory/sc_object.hpp | 7 +- sc-memory/sc-memory/sc_platform.hpp | 1 - sc-memory/sc-memory/sc_scs_helper.cpp | 58 +- sc-memory/sc-memory/sc_stream.cpp | 6 +- sc-memory/sc-memory/sc_stream.hpp | 68 +- sc-memory/sc-memory/sc_struct.cpp | 7 +- sc-memory/sc-memory/sc_struct.hpp | 9 +- sc-memory/sc-memory/sc_template.cpp | 9 +- sc-memory/sc-memory/sc_template.hpp | 8 +- sc-memory/sc-memory/sc_template_arg.hpp | 8 +- sc-memory/sc-memory/sc_template_builder.cpp | 21 +- sc-memory/sc-memory/sc_template_builder.hpp | 18 +- .../sc-memory/sc_template_builder_impl.cpp | 18 +- .../sc-memory/sc_template_builder_impl.hpp | 22 +- sc-memory/sc-memory/sc_template_data.hpp | 36 +- sc-memory/sc-memory/sc_template_generate.cpp | 16 +- .../sc-memory/sc_template_named_struct.cpp | 13 +- .../sc-memory/sc_template_named_struct.hpp | 5 +- sc-memory/sc-memory/sc_template_params.cpp | 6 +- sc-memory/sc-memory/sc_template_params.hpp | 17 +- .../sc-memory/sc_template_scs_builder.cpp | 5 +- sc-memory/sc-memory/sc_template_search.cpp | 150 +- sc-memory/sc-memory/sc_template_search.hpp | 33 +- .../sc-memory/sc_template_struct_builder.cpp | 132 +- sc-memory/sc-memory/sc_timer.cpp | 9 +- sc-memory/sc-memory/sc_timer.hpp | 8 +- sc-memory/sc-memory/sc_type.cpp | 9 +- sc-memory/sc-memory/sc_type.hpp | 144 +- sc-memory/sc-memory/sc_utils.cpp | 71 +- sc-memory/sc-memory/sc_utils.hpp | 128 +- sc-memory/sc-memory/sc_wait.cpp | 2 +- sc-memory/sc-memory/sc_wait.hpp | 43 +- sc-memory/sc-memory/scs/scs_parser.cpp | 109 +- sc-memory/sc-memory/scs/scs_parser.hpp | 60 +- sc-memory/sc-memory/scs/scs_types.cpp | 138 +- sc-memory/sc-memory/scs/scs_types.hpp | 3 +- sc-memory/sc-memory/utils/sc_base64.cpp | 25 +- sc-memory/sc-memory/utils/sc_base64.hpp | 7 +- sc-memory/sc-memory/utils/sc_boost.hpp | 59 +- sc-memory/sc-memory/utils/sc_cache.hpp | 29 +- sc-memory/sc-memory/utils/sc_console.cpp | 280 ++-- sc-memory/sc-memory/utils/sc_console.hpp | 112 +- .../sc-memory/utils/sc_keynode_cache.cpp | 12 +- .../sc-memory/utils/sc_keynode_cache.hpp | 17 +- sc-memory/sc-memory/utils/sc_lock.cpp | 11 +- sc-memory/sc-memory/utils/sc_lock.hpp | 22 +- sc-memory/sc-memory/utils/sc_log.cpp | 33 +- sc-memory/sc-memory/utils/sc_log.hpp | 70 +- sc-memory/sc-memory/utils/sc_message.cpp | 1 + sc-memory/sc-memory/utils/sc_message.hpp | 73 +- sc-memory/sc-memory/utils/sc_progress.cpp | 6 +- sc-memory/sc-memory/utils/sc_progress.hpp | 11 +- .../sc-memory/utils/sc_signal_handler.cpp | 61 +- .../sc-memory/utils/sc_signal_handler.hpp | 11 +- .../sc-memory/_test/dummy_file_interface.hpp | 4 +- .../sc-memory/agents/sc-agent-actions.cpp | 18 +- .../sc-memory/agents/sc-agent-result.cpp | 22 +- sc-memory/tests/sc-memory/agents/sc-agent.cpp | 8 +- .../tests/sc-memory/agents/test_sc_agent.hpp | 10 +- .../sc-memory/agents/test_sc_agent_result.hpp | 2 +- sc-memory/tests/sc-memory/codegen/codegen.cpp | 3 +- .../sc-memory/codegen/test_sc_object.cpp | 5 +- .../sc-memory/codegen/test_sc_object.hpp | 10 +- .../sc-memory/common/sc-common-templ.cpp | 30 +- .../tests/sc-memory/common/sc-elements.cpp | 3 +- .../tests/sc-memory/common/sc-iterator3.cpp | 5 +- .../tests/sc-memory/common/sc-iterator5.cpp | 46 +- .../tests/sc-memory/common/sc-keynodes.cpp | 30 +- sc-memory/tests/sc-memory/common/sc-link.cpp | 9 +- .../tests/sc-memory/common/sc-memory.cpp | 5 +- .../tests/sc-memory/common/sc-stream.cpp | 7 +- .../tests/sc-memory/common/sc-struct.cpp | 12 +- sc-memory/tests/sc-memory/common/sc-type.cpp | 3 +- sc-memory/tests/sc-memory/common/sc-utils.cpp | 1 - .../sc-memory/events/sc-event-threading.cpp | 44 +- sc-memory/tests/sc-memory/events/sc-event.cpp | 103 +- sc-memory/tests/sc-memory/events/sc-wait.cpp | 63 +- .../tests/sc-memory/performance/main.cpp | 140 +- .../performance/memory_create_edge.hpp | 5 +- .../performance/memory_create_link.hpp | 1 - .../sc-memory/performance/memory_test.hpp | 4 +- .../performance/sc_code_base_vs_extend.hpp | 61 +- .../performance/template_search_complex.hpp | 31 +- .../performance/template_search_smoke.hpp | 7 +- sc-memory/tests/sc-memory/scs/scs-helper.cpp | 134 +- .../tests/sc-memory/scs/scs-regression.cpp | 30 +- .../tests/sc-memory/scs/scs_test_utils.hpp | 4 +- .../templates/sc-templates-build.cpp | 25 +- .../templates/sc-templates-common.cpp | 196 +-- .../sc-memory/templates/sc-templates-data.cpp | 32 +- .../templates/sc-templates-params.cpp | 11 +- .../templates/sc-templates-regression.cpp | 195 +-- .../sc-memory/templates/sc-templates-scs.cpp | 24 +- .../templates/sc-templates-search.cpp | 167 +- .../templates/sc-templates-struct.cpp | 32 +- .../templates/template_test_utils.hpp | 18 +- sc-memory/tests/scs/units/test_scs_common.cpp | 38 +- .../tests/scs/units/test_scs_level_1.cpp | 1 - .../tests/scs/units/test_scs_level_2.cpp | 87 +- .../tests/scs/units/test_scs_level_3.cpp | 97 +- .../tests/scs/units/test_scs_level_4.cpp | 76 +- .../tests/scs/units/test_scs_level_5.cpp | 35 +- .../tests/scs/units/test_scs_level_6.cpp | 69 +- .../tests/scs/units/test_scs_regression.cpp | 2 +- sc-memory/tests/scs/units/test_scs_utils.hpp | 24 +- sc-network/sctp_client/sctpClient.cpp | 8 +- sc-network/sctp_client/sctpClient.hpp | 182 ++- sc-network/sctp_client/sctpISocket.hpp | 11 +- sc-network/sctp_client/sctpTypes.hpp | 72 +- sc-network/sctp_client/sockets/glibSocket.cpp | 6 +- sc-network/sctp_client/sockets/glibSocket.hpp | 18 +- sc-network/sctp_client/sockets/winSocket.cpp | 111 +- sc-network/sctp_client/sockets/winSocket.hpp | 45 +- sc-network/sctp_client/test/test_client.cpp | 281 ++-- sc-network/sctp_server/main.cpp | 10 +- sc-network/sctp_server/sctpClient.cpp | 9 +- sc-network/sctp_server/sctpCommand.cpp | 343 ++-- sc-network/sctp_server/sctpEventManager.cpp | 24 +- sc-network/sctp_server/sctpServer.cpp | 34 +- sc-network/sctp_server/sctpStatistic.cpp | 51 +- sc-server/src/main.cpp | 29 +- tools/builder/src/base64/base64.cpp | 150 +- tools/builder/src/builder.cpp | 61 +- tools/builder/src/builder.hpp | 8 +- tools/builder/src/exception.hpp | 5 +- tools/builder/src/gwf_translator.cpp | 38 +- tools/builder/src/gwf_translator.hpp | 2 - tools/builder/src/main.cpp | 29 +- tools/builder/src/scs_translator.cpp | 10 +- tools/builder/src/scs_translator.hpp | 1 - tools/builder/src/translator.cpp | 37 +- tools/builder/src/translator.hpp | 4 +- tools/builder/src/utils.hpp | 7 +- tools/builder/tests/units/builder_test.hpp | 1 - tools/builder/tests/units/test_base.cpp | 11 +- tools/builder/tests/units/test_clean.cpp | 17 +- tools/builder/tests/units/test_contents.cpp | 3 +- tools/builder/tests/units/test_visibility.cpp | 53 +- tools/codegen/Parser/Cache.cpp | 7 +- tools/codegen/Parser/Cache.hpp | 1 + tools/codegen/Parser/Cursor.cpp | 5 +- tools/codegen/Parser/Cursor.hpp | 6 +- tools/codegen/Parser/CursorType.cpp | 5 +- tools/codegen/Parser/CursorType.hpp | 3 +- tools/codegen/Parser/LanguageTypes/Class.cpp | 63 +- tools/codegen/Parser/LanguageTypes/Class.hpp | 7 +- .../Parser/LanguageTypes/Constructor.cpp | 6 +- .../Parser/LanguageTypes/Constructor.hpp | 6 +- tools/codegen/Parser/LanguageTypes/Field.cpp | 14 +- tools/codegen/Parser/LanguageTypes/Field.hpp | 7 +- .../codegen/Parser/LanguageTypes/Function.cpp | 6 +- .../codegen/Parser/LanguageTypes/Function.hpp | 6 +- tools/codegen/Parser/LanguageTypes/Global.cpp | 16 +- tools/codegen/Parser/LanguageTypes/Global.hpp | 2 - .../Parser/LanguageTypes/Invokable.cpp | 4 +- .../Parser/LanguageTypes/LanguageType.cpp | 2 +- tools/codegen/Parser/LanguageTypes/Method.cpp | 2 +- tools/codegen/Parser/LanguageTypes/Method.hpp | 6 +- tools/codegen/Parser/MacrosManager.cpp | 10 +- tools/codegen/Parser/MacrosManager.hpp | 23 +- tools/codegen/Parser/Main.cpp | 82 +- tools/codegen/Parser/MetaDataManager.cpp | 54 +- tools/codegen/Parser/MetaDataManager.hpp | 1 - tools/codegen/Parser/MetaUtils.cpp | 13 +- tools/codegen/Parser/MetaUtils.hpp | 6 +- tools/codegen/Parser/ReflectionParser.cpp | 50 +- tools/codegen/Parser/ReflectionParser.hpp | 12 +- tools/codegen/Parser/ReservedTypes.hpp | 9 +- tools/codegen/Parser/Sha256.cpp | 70 +- tools/codegen/Parser/Sha256.hpp | 139 +- tools/codegen/Parser/Types.hpp | 17 +- 215 files changed, 5389 insertions(+), 5201 deletions(-) diff --git a/.clang-format b/.clang-format index 7da9b431a..7f7e31ebd 100644 --- a/.clang-format +++ b/.clang-format @@ -72,14 +72,30 @@ IncludeCategories: - Regex: '^<(gtest|gmock)/.*' Priority: 1 - - Regex: '^mElementInfo == mElementInfo->target) ? mElementInfo->source : mElementInfo->target; + sScElementInfo * el = (mParent->mElementInfo == mElementInfo->target) ? mElementInfo->source : mElementInfo->target; assert(el); - uiSCnSentenceNode *child = new uiSCnSentenceNode(); + uiSCnSentenceNode * child = new uiSCnSentenceNode(); child->mType = ST_NODE; child->mElementInfo = el; _appendChildNode(child); @@ -71,12 +70,10 @@ void uiSCnSentenceNode::buildTree() void uiSCnSentenceNode::balance() { - } -const String& uiSCnSentenceNode::json() +const String & uiSCnSentenceNode::json() { - StringStream ss; ss << "{"; @@ -90,7 +87,8 @@ const String& uiSCnSentenceNode::json() { assert(mChildSentences.size() == 1); ss << ", \"SCNode\" : " << (*mChildSentences.begin())->json(); - } else + } + else { ss << ", \"SCArcs\": ["; @@ -98,7 +96,7 @@ const String& uiSCnSentenceNode::json() tSentenceNodeList::iterator it, itEnd = mChildSentences.end(); for (it = mChildSentences.begin(); it != itEnd; ++it) { - uiSCnSentenceNode *sentence = *it; + uiSCnSentenceNode * sentence = *it; assert(sentence->mType == ST_PREDICATE); if (it != mChildSentences.begin()) @@ -115,9 +113,9 @@ const String& uiSCnSentenceNode::json() return mJSONData; } -uiSCnSentenceNode* uiSCnSentenceNode::createChildNode(uiSCnSentenceNode::eSentenceNodeType type) +uiSCnSentenceNode * uiSCnSentenceNode::createChildNode(uiSCnSentenceNode::eSentenceNodeType type) { - uiSCnSentenceNode *child = new uiSCnSentenceNode(); + uiSCnSentenceNode * child = new uiSCnSentenceNode(); child->mType = type; _appendChildNode(child); return child; @@ -132,7 +130,7 @@ void uiSCnSentenceNode::destroyChilds() delete *it; } -void uiSCnSentenceNode::_removeChildNode(uiSCnSentenceNode *child) +void uiSCnSentenceNode::_removeChildNode(uiSCnSentenceNode * child) { assert(child->mParent == this); child->mParent = 0; @@ -147,7 +145,7 @@ void uiSCnSentenceNode::_removeChildNode(uiSCnSentenceNode *child) } } -void uiSCnSentenceNode::_appendChildNode(uiSCnSentenceNode *child) +void uiSCnSentenceNode::_appendChildNode(uiSCnSentenceNode * child) { assert(child->mParent != this); @@ -158,7 +156,7 @@ void uiSCnSentenceNode::_appendChildNode(uiSCnSentenceNode *child) mChildSentences.push_back(child); } -bool uiSCnSentenceNode::_hasChildNode(uiSCnSentenceNode *child) const +bool uiSCnSentenceNode::_hasChildNode(uiSCnSentenceNode * child) const { tSentenceNodeList::const_iterator it, itEnd = mChildSentences.end(); for (it = mChildSentences.begin(); it != itEnd; ++it) @@ -170,17 +168,14 @@ bool uiSCnSentenceNode::_hasChildNode(uiSCnSentenceNode *child) const return false; } -void uiSCnSentenceNode::_createChildPredicate(sScElementInfo *arc) +void uiSCnSentenceNode::_createChildPredicate(sScElementInfo * arc) { assert(arc->type & sc_type_arc_mask); - uiSCnSentenceNode *child = createChildNode(ST_PREDICATE); + uiSCnSentenceNode * child = createChildNode(ST_PREDICATE); child->mElementInfo = arc; } - - - // --------------------------------------------------------------------------------------------------- uiSc2SCnJsonTranslator::uiSc2SCnJsonTranslator() : mScElementsInfoPool(0) @@ -190,24 +185,23 @@ uiSc2SCnJsonTranslator::uiSc2SCnJsonTranslator() uiSc2SCnJsonTranslator::~uiSc2SCnJsonTranslator() { if (mScElementsInfoPool) - delete []mScElementsInfoPool; + delete[] mScElementsInfoPool; } void uiSc2SCnJsonTranslator::runImpl() { // get command arguments - sc_iterator5 *it5 = sc_iterator5_a_a_f_a_f_new(s_default_ctx, - sc_type_node | sc_type_const, - sc_type_arc_common | sc_type_const, - mInputConstructionAddr, - sc_type_arc_pos_const_perm, - keynode_question_nrel_answer); + sc_iterator5 * it5 = sc_iterator5_a_a_f_a_f_new( + s_default_ctx, + sc_type_node | sc_type_const, + sc_type_arc_common | sc_type_const, + mInputConstructionAddr, + sc_type_arc_pos_const_perm, + keynode_question_nrel_answer); if (sc_iterator5_next(it5) == SC_TRUE) { - sc_iterator3 *it3 = sc_iterator3_f_a_a_new(s_default_ctx, - sc_iterator5_value(it5, 0), - sc_type_arc_pos_const_perm, - 0); + sc_iterator3 * it3 = + sc_iterator3_f_a_a_new(s_default_ctx, sc_iterator5_value(it5, 0), sc_type_arc_pos_const_perm, 0); while (sc_iterator3_next(it3) == SC_TRUE) mKeywordsList.push_back(sc_iterator3_value(it3, 2)); sc_iterator3_free(it3); @@ -216,14 +210,12 @@ void uiSc2SCnJsonTranslator::runImpl() collectScElementsInfo(); - - mOutputData = "["; tScAddrList::iterator it, itEnd = mKeywordsList.end(); for (it = mKeywordsList.begin(); it != itEnd; ++it) { - uiSCnSentenceNode *sentence = new uiSCnSentenceNode(mScElementsInfo[*it]); + uiSCnSentenceNode * sentence = new uiSCnSentenceNode(mScElementsInfo[*it]); mRootSentences.push_back(sentence); } @@ -251,31 +243,25 @@ void uiSc2SCnJsonTranslator::runImpl() mRootSentences.clear(); mOutputData += "]"; - //qDebug() << "Result: " << QString().fromStdString(mOutputData); + // qDebug() << "Result: " << QString().fromStdString(mOutputData); } String uiSc2SCnJsonTranslator::translateElement(sc_addr addr, bool isKeyword) { - return ""; } bool uiSc2SCnJsonTranslator::isInOutputConstruction(sc_addr addr) const { - sc_iterator3 *it3 = sc_iterator3_f_a_f_new(s_default_ctx, - mInputConstructionAddr, - sc_type_arc_pos_const_perm, - addr); + sc_iterator3 * it3 = sc_iterator3_f_a_f_new(s_default_ctx, mInputConstructionAddr, sc_type_arc_pos_const_perm, addr); bool result = (sc_iterator3_next(it3) == SC_TRUE); sc_iterator3_free(it3); return result; } - - void uiSc2SCnJsonTranslator::collectScElementsInfo() { - sc_uint32 elementsCount =(sc_uint32) mObjects.size(); + sc_uint32 elementsCount = (sc_uint32)mObjects.size(); mScElementsInfoPool = new sScElementInfo[elementsCount]; sc_uint32 poolUsed = 0; @@ -300,7 +286,7 @@ void uiSc2SCnJsonTranslator::collectScElementsInfo() arcAddr = it->first; elType = it->second; - sScElementInfo *elInfo = mScElementsInfo[arcAddr]; + sScElementInfo * elInfo = mScElementsInfo[arcAddr]; elInfo->isInSentenceTree = false; elInfo->visualType = sScElementInfo::VT_NODE; @@ -310,16 +296,15 @@ void uiSc2SCnJsonTranslator::collectScElementsInfo() // get begin/end addrs if (sc_memory_get_arc_begin(s_default_ctx, arcAddr, &begAddr) != SC_RESULT_OK) - continue; // @todo process errors + continue; // @todo process errors if (sc_memory_get_arc_end(s_default_ctx, arcAddr, &endAddr) != SC_RESULT_OK) - continue; // @todo process errors - + continue; // @todo process errors elInfo->srcAddr = begAddr; elInfo->trgAddr = endAddr; - sScElementInfo *begInfo = mScElementsInfo[begAddr]; - sScElementInfo *endInfo = mScElementsInfo[endAddr]; + sScElementInfo * begInfo = mScElementsInfo[begAddr]; + sScElementInfo * endInfo = mScElementsInfo[endAddr]; elInfo->source = begInfo; elInfo->target = endInfo; @@ -335,7 +320,7 @@ void uiSc2SCnJsonTranslator::collectScElementsInfo() tScElemetsInfoMap::iterator itInfo, itInfoEnd = mScElementsInfo.begin(); for (itInfo = mScElementsInfo.begin(); itInfo != itInfoEnd; ++itInfo) { - sScElementInfo *el = itInfo->second; + sScElementInfo * el = itInfo->second; // possible sc-lement can be visualized as set if (el->type & sc_type_node_tuple) @@ -346,17 +331,14 @@ void uiSc2SCnJsonTranslator::collectScElementsInfo() // possible sc-element can be visualized as contour if (el->type & sc_type_node_struct) { - } - } // construct tree of sentences - } // ------------------------------------- -sc_result uiSc2SCnJsonTranslator::ui_translate_sc2scn(const sc_event *event, sc_addr arg) +sc_result uiSc2SCnJsonTranslator::ui_translate_sc2scn(const sc_event * event, sc_addr arg) { sc_addr cmd_addr, input_addr, format_addr; @@ -377,5 +359,3 @@ sc_result uiSc2SCnJsonTranslator::ui_translate_sc2scn(const sc_event *event, sc_ return SC_RESULT_OK; } - - diff --git a/sc-kpm/sc-ui/translators/uiSc2ScsJsonTranslator.cpp b/sc-kpm/sc-ui/translators/uiSc2ScsJsonTranslator.cpp index 51ae6f00c..cd37088e1 100644 --- a/sc-kpm/sc-ui/translators/uiSc2ScsJsonTranslator.cpp +++ b/sc-kpm/sc-ui/translators/uiSc2ScsJsonTranslator.cpp @@ -4,11 +4,11 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiSc2ScsJsonTranslator.h" -#include "uiTranslators.h" #include "uiKeynodes.h" +#include "uiPrecompiled.h" +#include "uiTranslators.h" #include "uiUtils.h" // -------------------- @@ -18,7 +18,6 @@ uiSc2ScsTranslator::uiSc2ScsTranslator() uiSc2ScsTranslator::~uiSc2ScsTranslator() { - } void uiSc2ScsTranslator::runImpl() @@ -29,18 +28,17 @@ void uiSc2ScsTranslator::runImpl() bool first = true; // get command arguments (keywords) - sc_iterator5 *it5 = sc_iterator5_a_a_f_a_f_new(s_default_ctx, - sc_type_node | sc_type_const, - sc_type_arc_common | sc_type_const, - mInputConstructionAddr, - sc_type_arc_pos_const_perm, - keynode_question_nrel_answer); + sc_iterator5 * it5 = sc_iterator5_a_a_f_a_f_new( + s_default_ctx, + sc_type_node | sc_type_const, + sc_type_arc_common | sc_type_const, + mInputConstructionAddr, + sc_type_arc_pos_const_perm, + keynode_question_nrel_answer); if (sc_iterator5_next(it5) == SC_TRUE) { - sc_iterator3 *it3 = sc_iterator3_f_a_a_new(s_default_ctx, - sc_iterator5_value(it5, 0), - sc_type_arc_pos_const_perm, - 0); + sc_iterator3 * it3 = + sc_iterator3_f_a_a_new(s_default_ctx, sc_iterator5_value(it5, 0), sc_type_arc_pos_const_perm, 0); while (sc_iterator3_next(it3) == SC_TRUE) { sc_addr addr = sc_iterator3_value(it3, 2); @@ -69,7 +67,7 @@ void uiSc2ScsTranslator::runImpl() tScAddrToScTypeMap::iterator it, itEnd = mObjects.end(); for (it = mObjects.begin(); it != itEnd; ++it) { - const sc_addr &arc_addr = it->first; + const sc_addr & arc_addr = it->first; sc_type arc_type = it->second; // skip non arc objects @@ -79,16 +77,16 @@ void uiSc2ScsTranslator::runImpl() sc_addr arc_beg, arc_end; // get begin and end arc elements if (sc_memory_get_arc_begin(s_default_ctx, arc_addr, &arc_beg) != SC_RESULT_OK) - continue; //! TODO logging + continue; //! TODO logging if (isNeedToTranslate(arc_beg) == false) - continue; //! TODO logging + continue; //! TODO logging if (sc_memory_get_arc_end(s_default_ctx, arc_addr, &arc_end) != SC_RESULT_OK) - continue; //! TODO logging + continue; //! TODO logging if (isNeedToTranslate(arc_end) == false) - continue; //! TODO logging + continue; //! TODO logging sc_type beg_type, end_type; tScAddrToScTypeMap::iterator itTmp = mObjects.find(arc_beg); @@ -110,14 +108,13 @@ void uiSc2ScsTranslator::runImpl() ss << "[{ \"addr\": \"" << buildId(arc_beg) << "\", \"type\": " << beg_type << "}, "; ss << "{ \"addr\": \"" << buildId(arc_addr) << "\", \"type\": " << arc_type << "}, "; ss << "{ \"addr\": \"" << buildId(arc_end) << "\", \"type\": " << end_type << "}]"; - } ss << "]}"; mOutputData = ss.str(); } -void uiSc2ScsTranslator::resolveSystemIdentifier(const sc_addr &addr, String &idtf) +void uiSc2ScsTranslator::resolveSystemIdentifier(const sc_addr & addr, String & idtf) { tSystemIdentifiersMap::iterator it = mSystemIdentifiers.find(addr); if (it != mSystemIdentifiers.end()) @@ -130,9 +127,8 @@ void uiSc2ScsTranslator::resolveSystemIdentifier(const sc_addr &addr, String &id mSystemIdentifiers[addr] = idtf; } - // ------------------------------------------------------- -sc_result uiSc2ScsTranslator::ui_translate_sc2scs(const sc_event *event, sc_addr arg) +sc_result uiSc2ScsTranslator::ui_translate_sc2scs(const sc_event * event, sc_addr arg) { sc_addr cmd_addr, input_addr, format_addr; diff --git a/sc-kpm/sc-ui/translators/uiTranslatorFromSc.cpp b/sc-kpm/sc-ui/translators/uiTranslatorFromSc.cpp index 04bb6fd7e..22886ac15 100644 --- a/sc-kpm/sc-ui/translators/uiTranslatorFromSc.cpp +++ b/sc-kpm/sc-ui/translators/uiTranslatorFromSc.cpp @@ -4,21 +4,20 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiTranslatorFromSc.h" + #include "uiKeynodes.h" +#include "uiPrecompiled.h" uiTranslateFromSc::uiTranslateFromSc() { - } uiTranslateFromSc::~uiTranslateFromSc() { - } -void uiTranslateFromSc::translate(const sc_addr &input_addr, const sc_addr &format_addr) +void uiTranslateFromSc::translate(const sc_addr & input_addr, const sc_addr & format_addr) { mInputConstructionAddr = input_addr; mOutputFormatAddr = format_addr; @@ -28,8 +27,9 @@ void uiTranslateFromSc::translate(const sc_addr &input_addr, const sc_addr &form runImpl(); // write into sc-link - sc_stream *result_data_stream = 0; - result_data_stream = sc_stream_memory_new(mOutputData.c_str(), (sc_uint)mOutputData.size(), SC_STREAM_FLAG_READ, SC_FALSE); + sc_stream * result_data_stream = 0; + result_data_stream = + sc_stream_memory_new(mOutputData.c_str(), (sc_uint)mOutputData.size(), SC_STREAM_FLAG_READ, SC_FALSE); sc_addr result_addr = sc_memory_link_new(s_default_ctx); sc_memory_set_link_content(s_default_ctx, result_addr, result_data_stream); @@ -47,7 +47,7 @@ void uiTranslateFromSc::translate(const sc_addr &input_addr, const sc_addr &form void uiTranslateFromSc::collectObjects() { - sc_iterator3 *it = sc_iterator3_f_a_a_new(s_default_ctx, mInputConstructionAddr, sc_type_arc_pos_const_perm, 0); + sc_iterator3 * it = sc_iterator3_f_a_a_new(s_default_ctx, mInputConstructionAddr, sc_type_arc_pos_const_perm, 0); while (sc_iterator3_next(it) == SC_TRUE) { sc_type el_type = 0; @@ -58,17 +58,16 @@ void uiTranslateFromSc::collectObjects() continue; mObjects[addr] = el_type; - } sc_iterator3_free(it); } -bool uiTranslateFromSc::isNeedToTranslate(const sc_addr &addr) const +bool uiTranslateFromSc::isNeedToTranslate(const sc_addr & addr) const { return mObjects.find(addr) != mObjects.end(); } -String uiTranslateFromSc::buildId(const sc_addr &addr) +String uiTranslateFromSc::buildId(const sc_addr & addr) { uint32_t v = addr.seg | (addr.offset << 16); StringStream ss; diff --git a/sc-kpm/sc-ui/ui.cpp b/sc-kpm/sc-ui/ui.cpp index 4ecde9d09..bf27c5d7e 100644 --- a/sc-kpm/sc-ui/ui.cpp +++ b/sc-kpm/sc-ui/ui.cpp @@ -4,12 +4,12 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "ui.h" -#include "uiTranslators.h" #include "uiCommands.h" #include "uiKeynodes.h" +#include "uiPrecompiled.h" +#include "uiTranslators.h" extern "C" { @@ -38,7 +38,6 @@ _SC_EXT_EXTERN sc_result sc_module_initialize() _SC_EXT_EXTERN sc_result sc_module_shutdown() { - ui_shutdown_translators(); ui_shutdown_commands(); diff --git a/sc-kpm/sc-ui/uiCommands.cpp b/sc-kpm/sc-ui/uiCommands.cpp index 64b61867e..328692bd0 100644 --- a/sc-kpm/sc-ui/uiCommands.cpp +++ b/sc-kpm/sc-ui/uiCommands.cpp @@ -4,17 +4,18 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiCommands.h" -#include "uiKeynodes.h" + #include "uiDefines.h" +#include "uiKeynodes.h" +#include "uiPrecompiled.h" #include // -------------------- Events ---------------------- -sc_event *event_ui_start_answer_translation = 0; -sc_event *event_ui_command_generate_instance = 0; -sc_event *event_ui_remove_displayed_answer = 0; +sc_event * event_ui_start_answer_translation = 0; +sc_event * event_ui_command_generate_instance = 0; +sc_event * event_ui_remove_displayed_answer = 0; struct sTemplateArcInfo { @@ -29,31 +30,31 @@ struct sTemplateArcInfo , end_addr(_end) , self_type(_type) { - } }; -typedef std::list < sTemplateArcInfo > tTemplArcsList; -typedef std::list < sc_addr > tElementsList; +typedef std::list tTemplArcsList; +typedef std::list tElementsList; // -------------------- Event handlers -------------- -sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) +sc_result ui_command_generate_instance(const sc_event * event, sc_addr arg) { sc_addr command_addr; sc_addr args_addr; - sc_iterator5 *it5 = (sc_iterator5*)null_ptr; - sc_iterator3 *it3 = (sc_iterator3*)null_ptr; + sc_iterator5 * it5 = (sc_iterator5 *)null_ptr; + sc_iterator3 * it3 = (sc_iterator3 *)null_ptr; if (sc_memory_get_arc_end(s_default_ctx, arg, &command_addr) != SC_RESULT_OK) return SC_RESULT_ERROR; // first of all we need to find command arguments - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - command_addr, - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_rrel_command_arguments); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + command_addr, + sc_type_arc_pos_const_perm, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_rrel_command_arguments); if (sc_iterator5_next(it5) != SC_TRUE) { @@ -64,7 +65,6 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) args_addr = sc_iterator5_value(it5, 2); sc_iterator5_free(it5); - int idx = 0; bool found = true; tScAddrVector arguments; @@ -72,12 +72,13 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) { found = false; // iterate arguments and append them into vector - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - args_addr, - sc_type_arc_pos_const_perm, - 0, - sc_type_arc_pos_const_perm, - ui_keynode_rrel_order[idx]); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + args_addr, + sc_type_arc_pos_const_perm, + 0, + sc_type_arc_pos_const_perm, + ui_keynode_rrel_order[idx]); if (sc_iterator5_next(it5) == SC_TRUE) { @@ -89,12 +90,13 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) } // get command class - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - command_addr, - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_rrel_command); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + command_addr, + sc_type_arc_pos_const_perm, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_rrel_command); if (sc_iterator5_next(it5) != SC_TRUE) { @@ -107,12 +109,13 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) sc_iterator5_free(it5); // get command template - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - new_command_class_addr, - sc_type_arc_common | sc_type_const, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_nrel_command_template); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + new_command_class_addr, + sc_type_arc_common | sc_type_const, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_nrel_command_template); if (sc_iterator5_next(it5) != SC_TRUE) { @@ -132,10 +135,7 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) tElementsList created_nodes; tTemplArcsList templ_arcs; bool isValid = true; - it3 = sc_iterator3_f_a_a_new(s_default_ctx, - new_command_templ_addr, - sc_type_arc_pos_const_perm, - 0); + it3 = sc_iterator3_f_a_a_new(s_default_ctx, new_command_templ_addr, sc_type_arc_pos_const_perm, 0); while (sc_iterator3_next(it3) == SC_TRUE && isValid) { templ_item_addr = sc_iterator3_value(it3, 2); @@ -203,7 +203,8 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) // append to set of failed commands sc_memory_element_free(s_default_ctx, arg); - sc_addr arc_addr = sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, keynode_command_failed, command_addr); + sc_addr arc_addr = + sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, keynode_command_failed, command_addr); SYSTEM_ELEMENT(arc_addr); return SC_RESULT_ERROR_INVALID_PARAMS; @@ -227,7 +228,6 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) arc_end_addr = (*it).end_addr; arc_type = (*it).self_type; - it_arc_beg = templ_to_inst.find(arc_beg_addr); it_arc_end = templ_to_inst.find(arc_end_addr); @@ -235,7 +235,8 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) if (it_arc_beg != templ_to_inst.end() && it_arc_end != templ_to_inst.end()) { created = true; - new_arc_addr = sc_memory_arc_new(s_default_ctx, (arc_type & ~sc_type_var) | sc_type_const, (*it_arc_beg).second, (*it_arc_end).second); + new_arc_addr = sc_memory_arc_new( + s_default_ctx, (arc_type & ~sc_type_var) | sc_type_const, (*it_arc_beg).second, (*it_arc_end).second); templ_to_inst[arc_addr] = new_arc_addr; it = templ_arcs.erase(it); @@ -272,7 +273,7 @@ sc_result ui_command_generate_instance(const sc_event *event, sc_addr arg) return SC_RESULT_OK; } -sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) +sc_result ui_start_answer_translation(sc_event * event, sc_addr arg) { sc_addr question_addr; sc_addr answer_addr; @@ -281,19 +282,19 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) sc_addr format_addr; sc_addr trans_command_addr; sc_addr arc_addr; - sc_iterator5 *it5 = (sc_iterator5*)null_ptr; - sc_iterator3 *it3 = (sc_iterator3*)null_ptr; - + sc_iterator5 * it5 = (sc_iterator5 *)null_ptr; + sc_iterator3 * it3 = (sc_iterator3 *)null_ptr; if (sc_memory_get_arc_end(s_default_ctx, arg, &question_addr) != SC_RESULT_OK) return SC_RESULT_ERROR; - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - question_addr, - sc_type_arc_common | sc_type_const, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_question_nrel_answer); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + question_addr, + sc_type_arc_common | sc_type_const, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_question_nrel_answer); if (sc_iterator5_next(it5) == SC_FALSE) { sc_iterator5_free(it5); @@ -303,12 +304,13 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) answer_addr = sc_iterator5_value(it5, 2); // find author of this question - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - question_addr, - sc_type_arc_common | sc_type_const, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_nrel_authors); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + question_addr, + sc_type_arc_common | sc_type_const, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_nrel_authors); if (it5 == null_ptr) return SC_RESULT_ERROR; @@ -321,12 +323,13 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) if (sc_helper_check_arc(s_default_ctx, keynode_user, author_addr, sc_type_arc_pos_const_perm) == SC_TRUE) { // get answer output formats - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - question_addr, - sc_type_arc_common | sc_type_const, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_nrel_user_answer_formats); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + question_addr, + sc_type_arc_common | sc_type_const, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_nrel_user_answer_formats); if (it5 == null_ptr) return SC_RESULT_ERROR; @@ -336,10 +339,8 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) sc_iterator5_free(it5); // list all output formats and initialize translation - it3 = sc_iterator3_f_a_a_new(s_default_ctx, - output_formats_addr, - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const); + it3 = sc_iterator3_f_a_a_new( + s_default_ctx, output_formats_addr, sc_type_arc_pos_const_perm, sc_type_node | sc_type_const); if (it3 == null_ptr) return SC_RESULT_ERROR; @@ -353,7 +354,8 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) arc_addr = sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, trans_command_addr, answer_addr); SYSTEM_ELEMENT(arc_addr); - arc_addr = sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, keynode_rrel_source_sc_construction, arc_addr); + arc_addr = sc_memory_arc_new( + s_default_ctx, sc_type_arc_pos_const_perm, keynode_rrel_source_sc_construction, arc_addr); SYSTEM_ELEMENT(arc_addr); arc_addr = sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, trans_command_addr, format_addr); @@ -362,80 +364,80 @@ sc_result ui_start_answer_translation(sc_event *event, sc_addr arg) SYSTEM_ELEMENT(arc_addr); // add into translation command set - arc_addr = sc_memory_arc_new(s_default_ctx, sc_type_arc_pos_const_perm, keynode_command_translate_from_sc, trans_command_addr); + arc_addr = sc_memory_arc_new( + s_default_ctx, sc_type_arc_pos_const_perm, keynode_command_translate_from_sc, trans_command_addr); SYSTEM_ELEMENT(arc_addr); } sc_iterator3_free(it3); - - }else + } + else sc_iterator5_free(it5); - } - }else + } + else sc_iterator5_free(it5); - // get answer node return SC_RESULT_OK; } -sc_result ui_remove_displayed_answer(sc_event *event, sc_addr arg) +sc_result ui_remove_displayed_answer(sc_event * event, sc_addr arg) { sc_addr answer_addr; - sc_iterator5 *it5 = 0; - sc_iterator5 *it5Res = 0; - sc_iterator5 *it5Args = 0; + sc_iterator5 * it5 = 0; + sc_iterator5 * it5Res = 0; + sc_iterator5 * it5Args = 0; if (sc_memory_get_arc_end(s_default_ctx, arg, &answer_addr) != SC_RESULT_OK) return SC_RESULT_ERROR; // first of all delete translation command - it5 = sc_iterator5_a_a_f_a_f_new(s_default_ctx, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - answer_addr, - sc_type_arc_pos_const_perm, - keynode_rrel_source_sc_construction); + it5 = sc_iterator5_a_a_f_a_f_new( + s_default_ctx, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + answer_addr, + sc_type_arc_pos_const_perm, + keynode_rrel_source_sc_construction); if (sc_iterator5_next(it5) == SC_TRUE) sc_memory_element_free(s_default_ctx, sc_iterator5_value(it5, 0)); sc_iterator5_free(it5); // remove translation result - it5 = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - answer_addr, - sc_type_arc_common | sc_type_const, - sc_type_link, - sc_type_arc_pos_const_perm, - keynode_nrel_translation); + it5 = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + answer_addr, + sc_type_arc_common | sc_type_const, + sc_type_link, + sc_type_arc_pos_const_perm, + keynode_nrel_translation); if (sc_iterator5_next(it5) == SC_TRUE) sc_memory_element_free(s_default_ctx, sc_iterator5_value(it5, 2)); sc_iterator5_free(it5); // find question, and remove all connected information - it5 = sc_iterator5_a_a_f_a_f_new(s_default_ctx, - sc_type_node | sc_type_const, - sc_type_arc_common | sc_type_const, - answer_addr, - sc_type_arc_pos_const_perm, - keynode_question_nrel_answer); + it5 = sc_iterator5_a_a_f_a_f_new( + s_default_ctx, + sc_type_node | sc_type_const, + sc_type_arc_common | sc_type_const, + answer_addr, + sc_type_arc_pos_const_perm, + keynode_question_nrel_answer); if (sc_iterator5_next(it5) == SC_TRUE) { - it5Res = sc_iterator5_a_a_f_a_f_new(s_default_ctx, - 0, - 0, - sc_iterator5_value(it5, 0), - 0, - keynode_nrel_command_result); + it5Res = + sc_iterator5_a_a_f_a_f_new(s_default_ctx, 0, 0, sc_iterator5_value(it5, 0), 0, keynode_nrel_command_result); if (sc_iterator5_next(it5Res) == SC_TRUE) { - it5Args = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - sc_iterator5_value(it5Res, 0), - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_rrel_command_arguments); + it5Args = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + sc_iterator5_value(it5Res, 0), + sc_type_arc_pos_const_perm, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_rrel_command_arguments); if (sc_iterator5_next(it5Args) == SC_TRUE) sc_memory_element_free(s_default_ctx, sc_iterator5_value(it5Args, 2)); sc_iterator5_free(it5Args); @@ -457,17 +459,16 @@ sc_result ui_remove_displayed_answer(sc_event *event, sc_addr arg) // -------------------- Module ---------------------- sc_result ui_initialize_commands() { - /*event_ui_start_answer_translation = sc_event_new(keynode_question_finished, SC_EVENT_ADD_OUTPUT_ARC, 0, ui_start_answer_translation, 0); - if (event_ui_start_answer_translation == null) - return SC_RESULT_ERROR;*/ + /*event_ui_start_answer_translation = sc_event_new(keynode_question_finished, SC_EVENT_ADD_OUTPUT_ARC, 0, + ui_start_answer_translation, 0); if (event_ui_start_answer_translation == null) return SC_RESULT_ERROR;*/ - event_ui_command_generate_instance = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, ui_command_generate_instance, 0); + event_ui_command_generate_instance = sc_event_new( + s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, ui_command_generate_instance, 0); if (event_ui_command_generate_instance == null_ptr) return SC_RESULT_ERROR; - /*event_ui_remove_displayed_answer = sc_event_new(keynode_displayed_answer, SC_EVENT_ADD_OUTPUT_ARC, 0, ui_remove_displayed_answer, 0); - if (event_ui_remove_displayed_answer == null) - return SC_RESULT_ERROR;*/ + /*event_ui_remove_displayed_answer = sc_event_new(keynode_displayed_answer, SC_EVENT_ADD_OUTPUT_ARC, 0, + ui_remove_displayed_answer, 0); if (event_ui_remove_displayed_answer == null) return SC_RESULT_ERROR;*/ return SC_RESULT_OK; } @@ -476,13 +477,13 @@ void ui_shutdown_commands() { if (event_ui_start_answer_translation) sc_event_destroy(event_ui_start_answer_translation); - event_ui_start_answer_translation = (sc_event*)null_ptr; + event_ui_start_answer_translation = (sc_event *)null_ptr; if (event_ui_command_generate_instance) sc_event_destroy(event_ui_command_generate_instance); - event_ui_command_generate_instance = (sc_event*)null_ptr; + event_ui_command_generate_instance = (sc_event *)null_ptr; if (event_ui_remove_displayed_answer) sc_event_destroy(event_ui_remove_displayed_answer); - event_ui_remove_displayed_answer = (sc_event*)null_ptr; + event_ui_remove_displayed_answer = (sc_event *)null_ptr; } diff --git a/sc-kpm/sc-ui/uiKeynodes.cpp b/sc-kpm/sc-ui/uiKeynodes.cpp index 0e4552dc6..7ac891c9f 100644 --- a/sc-kpm/sc-ui/uiKeynodes.cpp +++ b/sc-kpm/sc-ui/uiKeynodes.cpp @@ -4,16 +4,17 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiKeynodes.h" +#include "uiPrecompiled.h" + extern "C" { #include "../sc-common/sc_keynodes.h" + #include } - // ------------- Keynodes ---------------------- const char keynode_user_str[] = "ui_user"; const char keynode_command_translate_from_sc_str[] = "ui_command_translate_from_sc"; @@ -21,14 +22,12 @@ const char keynode_nrel_user_answer_formats_str[] = "ui_nrel_user_answer_formats const char keynode_rrel_source_sc_construction_str[] = "ui_rrel_source_sc_construction"; const char keynode_rrel_output_format_str[] = "ui_rrel_output_format"; - const char keynode_question_nrel_answer_str[] = "nrel_answer"; const char keynode_question_finished_str[] = "question_finished"; const char keynode_nrel_authors_str[] = "nrel_authors"; const char keynode_nrel_translation_str[] = "nrel_translation"; const char keynode_nrel_format_str[] = "nrel_format"; - const char keynode_command_generate_instance_str[] = "ui_command_generate_instance"; const char keynode_command_initiated_str[] = "ui_command_initiated"; const char keynode_command_finished_str[] = "ui_command_finished"; @@ -45,7 +44,6 @@ const char keynode_format_scn_json_str[] = "format_scn_json"; const char keynode_system_element_str[] = "system_element"; - sc_addr keynode_user; sc_addr keynode_command_translate_from_sc; sc_addr keynode_nrel_user_answer_formats; @@ -77,7 +75,6 @@ sc_addr keynode_system_element; sc_addr ui_keynode_rrel_order[RREL_ORDER_COUNT]; sc_addr ui_keynode_arg[UI_ARG_COUNT]; - // ------------------------------------------------- sc_bool initialize_keynodes() { @@ -115,7 +112,8 @@ sc_bool initialize_keynodes() if (sc_helper_resolve_system_identifier(s_default_ctx, ss.str().c_str(), &(ui_keynode_rrel_order[i])) == SC_FALSE) { ui_keynode_rrel_order[i] = sc_memory_node_new(s_default_ctx, 0); - if (sc_helper_set_system_identifier(s_default_ctx, ui_keynode_rrel_order[i], ss.str().c_str(), (sc_uint32)ss.str().size()) != SC_RESULT_OK) + if (sc_helper_set_system_identifier( + s_default_ctx, ui_keynode_rrel_order[i], ss.str().c_str(), (sc_uint32)ss.str().size()) != SC_RESULT_OK) return SC_FALSE; } } @@ -127,11 +125,11 @@ sc_bool initialize_keynodes() if (sc_helper_resolve_system_identifier(s_default_ctx, ss.str().c_str(), &(ui_keynode_arg[i])) == SC_FALSE) { ui_keynode_rrel_order[i] = sc_memory_node_new(s_default_ctx, 0); - if (sc_helper_set_system_identifier(s_default_ctx, ui_keynode_rrel_order[i], ss.str().c_str(), (sc_uint32)ss.str().size()) != SC_RESULT_OK) + if (sc_helper_set_system_identifier( + s_default_ctx, ui_keynode_rrel_order[i], ss.str().c_str(), (sc_uint32)ss.str().size()) != SC_RESULT_OK) return SC_FALSE; } } return SC_TRUE; } - diff --git a/sc-kpm/sc-ui/uiTranslators.cpp b/sc-kpm/sc-ui/uiTranslators.cpp index 0c716c3ae..696c76c03 100644 --- a/sc-kpm/sc-ui/uiTranslators.cpp +++ b/sc-kpm/sc-ui/uiTranslators.cpp @@ -4,23 +4,36 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiTranslators.h" -#include "uiKeynodes.h" -#include "translators/uiSc2ScsJsonTranslator.h" #include "translators/uiSc2SCgJsonTranslator.h" #include "translators/uiSc2SCnJsonTranslator.h" +#include "translators/uiSc2ScsJsonTranslator.h" +#include "uiKeynodes.h" +#include "uiPrecompiled.h" -sc_event *ui_translator_sc2scs_event = (sc_event*)null_ptr; -sc_event *ui_translator_sc2scg_json_event = (sc_event*)null_ptr; -sc_event *ui_translator_sc2scn_json_event = (sc_event*)null_ptr; +sc_event * ui_translator_sc2scs_event = (sc_event *)null_ptr; +sc_event * ui_translator_sc2scg_json_event = (sc_event *)null_ptr; +sc_event * ui_translator_sc2scn_json_event = (sc_event *)null_ptr; void ui_initialize_translators() { - ui_translator_sc2scs_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2ScsTranslator::ui_translate_sc2scs, 0); - ui_translator_sc2scg_json_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2SCgJsonTranslator::ui_translate_sc2scg_json, 0); - ui_translator_sc2scn_json_event = sc_event_new(s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2SCnJsonTranslator::ui_translate_sc2scn, 0); + ui_translator_sc2scs_event = sc_event_new( + s_default_ctx, keynode_command_initiated, SC_EVENT_ADD_OUTPUT_ARC, 0, uiSc2ScsTranslator::ui_translate_sc2scs, 0); + ui_translator_sc2scg_json_event = sc_event_new( + s_default_ctx, + keynode_command_initiated, + SC_EVENT_ADD_OUTPUT_ARC, + 0, + uiSc2SCgJsonTranslator::ui_translate_sc2scg_json, + 0); + ui_translator_sc2scn_json_event = sc_event_new( + s_default_ctx, + keynode_command_initiated, + SC_EVENT_ADD_OUTPUT_ARC, + 0, + uiSc2SCnJsonTranslator::ui_translate_sc2scn, + 0); } void ui_shutdown_translators() @@ -33,19 +46,20 @@ void ui_shutdown_translators() sc_event_destroy(ui_translator_sc2scn_json_event); } -sc_result ui_translate_command_resolve_arguments(sc_addr cmd_addr, sc_addr *output_fmt_addr, sc_addr *source_addr) +sc_result ui_translate_command_resolve_arguments(sc_addr cmd_addr, sc_addr * output_fmt_addr, sc_addr * source_addr) { - sc_iterator5 *it = (sc_iterator5*)null_ptr; + sc_iterator5 * it = (sc_iterator5 *)null_ptr; sc_bool fmt_found = SC_FALSE; sc_bool source_found = SC_FALSE; // resolve output format - it = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - cmd_addr, - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_rrel_output_format); + it = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + cmd_addr, + sc_type_arc_pos_const_perm, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_rrel_output_format); while (sc_iterator5_next(it) == SC_TRUE) { @@ -59,12 +73,13 @@ sc_result ui_translate_command_resolve_arguments(sc_addr cmd_addr, sc_addr *outp return SC_RESULT_ERROR; // resolve input construction - it = sc_iterator5_f_a_a_a_f_new(s_default_ctx, - cmd_addr, - sc_type_arc_pos_const_perm, - sc_type_node | sc_type_const, - sc_type_arc_pos_const_perm, - keynode_rrel_source_sc_construction); + it = sc_iterator5_f_a_a_a_f_new( + s_default_ctx, + cmd_addr, + sc_type_arc_pos_const_perm, + sc_type_node | sc_type_const, + sc_type_arc_pos_const_perm, + keynode_rrel_source_sc_construction); while (sc_iterator5_next(it) == SC_TRUE) { @@ -80,10 +95,10 @@ sc_result ui_translate_command_resolve_arguments(sc_addr cmd_addr, sc_addr *outp return SC_RESULT_OK; } -sc_bool ui_translate_resolve_system_identifier(sc_addr el, String &sys_idtf) +sc_bool ui_translate_resolve_system_identifier(sc_addr el, String & sys_idtf) { sc_addr sys_idtf_addr; - sc_stream *idtf_stream = 0; + sc_stream * idtf_stream = 0; sc_uint32 idtf_length = 0; sc_uint32 read_bytes = 0; sc_bool result = SC_FALSE; diff --git a/sc-kpm/sc-ui/uiTypes.cpp b/sc-kpm/sc-ui/uiTypes.cpp index e173e5417..3bf6556f1 100644 --- a/sc-kpm/sc-ui/uiTypes.cpp +++ b/sc-kpm/sc-ui/uiTypes.cpp @@ -4,10 +4,11 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiTypes.h" -bool operator < (const sc_addr &addr1, const sc_addr &addr2) +#include "uiPrecompiled.h" + +bool operator<(const sc_addr & addr1, const sc_addr & addr2) { if (addr1.seg != addr2.seg) return addr1.seg < addr2.seg; @@ -15,12 +16,12 @@ bool operator < (const sc_addr &addr1, const sc_addr &addr2) return addr1.offset < addr2.offset; } -bool operator == (const sc_addr &addr1, const sc_addr &addr2) +bool operator==(const sc_addr & addr1, const sc_addr & addr2) { return (addr1.seg == addr2.seg) && (addr1.offset == addr2.offset); } -bool operator != (const sc_addr &addr1, const sc_addr &addr2) +bool operator!=(const sc_addr & addr1, const sc_addr & addr2) { return (addr1.seg != addr2.seg) || (addr1.offset != addr2.offset); } diff --git a/sc-kpm/sc-ui/uiUtils.cpp b/sc-kpm/sc-ui/uiUtils.cpp index 85df7a984..e5d550c04 100644 --- a/sc-kpm/sc-ui/uiUtils.cpp +++ b/sc-kpm/sc-ui/uiUtils.cpp @@ -4,9 +4,10 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include "uiPrecompiled.h" #include "uiUtils.h" +#include "uiPrecompiled.h" + sc_result ui_check_cmd_type(sc_addr cmd_addr, sc_addr cmd_class) { if (sc_helper_check_arc(s_default_ctx, cmd_class, cmd_addr, sc_type_arc_pos_const_perm) == SC_TRUE) diff --git a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_gen.cpp b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_gen.cpp index a46650090..caae12aa0 100644 --- a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_gen.cpp +++ b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_gen.cpp @@ -25,87 +25,95 @@ extern "C" } #include "sc_system_gen.h" -#include #include +#include - -sc_addr gen_correspondence_for_var(sc_memory_context *context, sc_addr var_elem, sc_type_result *params, sc_type_result *result) +sc_addr gen_correspondence_for_var( + sc_memory_context * context, + sc_addr var_elem, + sc_type_result * params, + sc_type_result * result) { - sc_type_result::iterator pos = params->find(var_elem); - if (pos != params->end()) - { - return (*pos).second; - } - sc_type var_type; - sc_memory_get_element_type(context, var_elem, &var_type); - sc_type const_type = ((~sc_type_var & var_type) | sc_type_const); - sc_addr const_elem; - if ((sc_type_node & var_type) == sc_type_node) - { - const_elem = sc_memory_node_new(context, const_type); - } - else - { - sc_addr var_begin, var_end; - sc_memory_get_arc_begin(context, var_elem, &var_begin); - sc_memory_get_arc_end(context, var_elem, &var_end); - sc_addr const_begin = gen_correspondence_for_var(context, var_begin, params, result); - sc_addr const_end = gen_correspondence_for_var(context, var_end, params, result); - const_elem = sc_memory_arc_new(context, const_type, const_begin, const_end); - } - params->insert(sc_addr_pair(var_elem, const_elem)); - result->insert(sc_addr_pair(var_elem, const_elem)); - return const_elem; + sc_type_result::iterator pos = params->find(var_elem); + if (pos != params->end()) + { + return (*pos).second; + } + sc_type var_type; + sc_memory_get_element_type(context, var_elem, &var_type); + sc_type const_type = ((~sc_type_var & var_type) | sc_type_const); + sc_addr const_elem; + if ((sc_type_node & var_type) == sc_type_node) + { + const_elem = sc_memory_node_new(context, const_type); + } + else + { + sc_addr var_begin, var_end; + sc_memory_get_arc_begin(context, var_elem, &var_begin); + sc_memory_get_arc_end(context, var_elem, &var_end); + sc_addr const_begin = gen_correspondence_for_var(context, var_begin, params, result); + sc_addr const_end = gen_correspondence_for_var(context, var_end, params, result); + const_elem = sc_memory_arc_new(context, const_type, const_begin, const_end); + } + params->insert(sc_addr_pair(var_elem, const_elem)); + result->insert(sc_addr_pair(var_elem, const_elem)); + return const_elem; } -sc_result system_sys_gen(sc_memory_context *context, sc_addr pattern, sc_type_result params, sc_type_result *result) +sc_result system_sys_gen(sc_memory_context * context, sc_addr pattern, sc_type_result params, sc_type_result * result) { - sc_type_result all_pairs; - all_pairs.insert(params.begin(), params.end()); - sc_iterator3 *it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_node | sc_type_const); - while (SC_TRUE == sc_iterator3_next(it)) - { - sc_addr node = sc_iterator3_value(it, 2); - all_pairs.insert(sc_addr_pair(node, node)); - } - sc_iterator3_free(it); - - it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_var); - while (SC_TRUE == sc_iterator3_next(it)) - { - sc_addr node = sc_iterator3_value(it, 2); - gen_correspondence_for_var(context, node, &all_pairs, result); - } - sc_iterator3_free(it); - - //print_result(*result); - - return SC_RESULT_OK; + sc_type_result all_pairs; + all_pairs.insert(params.begin(), params.end()); + sc_iterator3 * it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_node | sc_type_const); + while (SC_TRUE == sc_iterator3_next(it)) + { + sc_addr node = sc_iterator3_value(it, 2); + all_pairs.insert(sc_addr_pair(node, node)); + } + sc_iterator3_free(it); + + it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_var); + while (SC_TRUE == sc_iterator3_next(it)) + { + sc_addr node = sc_iterator3_value(it, 2); + gen_correspondence_for_var(context, node, &all_pairs, result); + } + sc_iterator3_free(it); + + // print_result(*result); + + return SC_RESULT_OK; } -sc_result system_sys_gen_for_variables(sc_memory_context *context, sc_addr pattern, sc_type_result params, sc_addr_vector requested_values, sc_type_result *result) +sc_result system_sys_gen_for_variables( + sc_memory_context * context, + sc_addr pattern, + sc_type_result params, + sc_addr_vector requested_values, + sc_type_result * result) { - sc_type_result all_pairs; - all_pairs.insert(params.begin(), params.end()); - sc_iterator3 *it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_node | sc_type_const); - while (SC_TRUE == sc_iterator3_next(it)) - { - sc_addr node = sc_iterator3_value(it, 2); - all_pairs.insert(sc_addr_pair(node, node)); - } - sc_iterator3_free(it); - - it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_var); - while (SC_TRUE == sc_iterator3_next(it)) - { - sc_addr node = sc_iterator3_value(it, 2); - gen_correspondence_for_var(context, node, &all_pairs, result); - } - sc_iterator3_free(it); - - filter_result_by_variables(result, &requested_values); - - //print_result(*result); - - return SC_RESULT_OK; + sc_type_result all_pairs; + all_pairs.insert(params.begin(), params.end()); + sc_iterator3 * it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_node | sc_type_const); + while (SC_TRUE == sc_iterator3_next(it)) + { + sc_addr node = sc_iterator3_value(it, 2); + all_pairs.insert(sc_addr_pair(node, node)); + } + sc_iterator3_free(it); + + it = sc_iterator3_f_a_a_new(context, pattern, 0, sc_type_var); + while (SC_TRUE == sc_iterator3_next(it)) + { + sc_addr node = sc_iterator3_value(it, 2); + gen_correspondence_for_var(context, node, &all_pairs, result); + } + sc_iterator3_free(it); + + filter_result_by_variables(result, &requested_values); + + // print_result(*result); + + return SC_RESULT_OK; } diff --git a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_operators.cpp b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_operators.cpp index 8b43643d3..afa8ec911 100644 --- a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_operators.cpp +++ b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_operators.cpp @@ -21,325 +21,356 @@ along with OSTIS. If not, see . */ extern "C" { -#include "sc_memory_headers.h" #include "sc_helper.h" +#include "sc_memory_headers.h" } #include "sc_system_operators.h" -#include +#include #include #include -#include +#include -void printIdtf(sc_memory_context *context, sc_addr element) +void printIdtf(sc_memory_context * context, sc_addr element) { - sc_addr idtf; - sc_type type; - sc_memory_get_element_type(context, element, &type); + sc_addr idtf; + sc_type type; + sc_memory_get_element_type(context, element, &type); - if ((sc_type_node & type) == sc_type_node || (sc_type_link & type) == sc_type_link ) + if ((sc_type_node & type) == sc_type_node || (sc_type_link & type) == sc_type_link) + { + if (SC_RESULT_OK == sc_helper_get_system_identifier_link(context, element, &idtf)) { - - if (SC_RESULT_OK == sc_helper_get_system_identifier_link(context, element, &idtf)) - { - sc_stream *stream; - sc_uint32 length = 0, read_length = 0; - sc_char *data; - sc_memory_get_link_content(context, idtf, &stream); - sc_stream_get_length(stream, &length); - data = (sc_char *)calloc(length + 1, sizeof(sc_char)); - sc_stream_read_data(stream, data, length, &read_length); - data[length] = '\0'; - printf("%s", data); - sc_stream_free(stream); - free(data); - } - else - { - printf("%u|%u", element.seg, element.offset); - } + sc_stream * stream; + sc_uint32 length = 0, read_length = 0; + sc_char * data; + sc_memory_get_link_content(context, idtf, &stream); + sc_stream_get_length(stream, &length); + data = (sc_char *)calloc(length + 1, sizeof(sc_char)); + sc_stream_read_data(stream, data, length, &read_length); + data[length] = '\0'; + printf("%s", data); + sc_stream_free(stream); + free(data); } else { - sc_addr elem1, elem2; - sc_memory_get_arc_begin(context, element, &elem1); - sc_memory_get_arc_end(context, element, &elem2); - printf("("); - printIdtf(context, elem1); - printf(" -> "); - printIdtf(context, elem2); - printf(")"); + printf("%u|%u", element.seg, element.offset); } + } + else + { + sc_addr elem1, elem2; + sc_memory_get_arc_begin(context, element, &elem1); + sc_memory_get_arc_end(context, element, &elem2); + printf("("); + printIdtf(context, elem1); + printf(" -> "); + printIdtf(context, elem2); + printf(")"); + } } -bool sc_result_comparator(sc_type_result *s1, sc_type_result *s2) +bool sc_result_comparator(sc_type_result * s1, sc_type_result * s2) { - return (s1->size() > s2->size()); + return (s1->size() > s2->size()); } void print_hash(sc_type_hash table) { - sc_type_hash::iterator it; - printf("HASHMAP:\n"); - for (it = table.begin() ; it != table.end(); it++) - { - sc_addr addr = (*it).second; - std::cout << addr.seg << "|" << addr.offset << std::endl; - } + sc_type_hash::iterator it; + printf("HASHMAP:\n"); + for (it = table.begin(); it != table.end(); it++) + { + sc_addr addr = (*it).second; + std::cout << addr.seg << "|" << addr.offset << std::endl; + } } -void print_result(sc_memory_context *context, sc_type_result table) +void print_result(sc_memory_context * context, sc_type_result table) { - sc_type_result::iterator it; - printf("RESULT (%d):\n", (int)table.size()); - for (it = table.begin() ; it != table.end(); it++) - { - sc_addr addr1 = (*it).first; - sc_addr addr2 = (*it).second; - printIdtf(context, addr1); - std::cout << " => "; - printIdtf(context, addr2); - std::cout << std::endl; - //std::cout << addr1.seg << "|" << addr1.offset << "=>" << addr2.seg << "|" << addr2.offset << std::endl; - } + sc_type_result::iterator it; + printf("RESULT (%d):\n", (int)table.size()); + for (it = table.begin(); it != table.end(); it++) + { + sc_addr addr1 = (*it).first; + sc_addr addr2 = (*it).second; + printIdtf(context, addr1); + std::cout << " => "; + printIdtf(context, addr2); + std::cout << std::endl; + // std::cout << addr1.seg << "|" << addr1.offset << "=>" << addr2.seg << "|" << addr2.offset << std::endl; + } } -void print_result_set(sc_memory_context *context, sc_type_result_vector *table) +void print_result_set(sc_memory_context * context, sc_type_result_vector * table) { - printf("RESULT COUNT:%d\n", (int)table->size()); - for (sc_uint i = 0; i < table->size(); i++) - { - print_result(context, *((*table)[i])); - } + printf("RESULT COUNT:%d\n", (int)table->size()); + for (sc_uint i = 0; i < table->size(); i++) + { + print_result(context, *((*table)[i])); + } } -sc_bool copy_set_into_hash(sc_memory_context *context, sc_addr set, sc_type arc_type, sc_type end_type, sc_type_hash *table, sc_uint *var_count) +sc_bool copy_set_into_hash( + sc_memory_context * context, + sc_addr set, + sc_type arc_type, + sc_type end_type, + sc_type_hash * table, + sc_uint * var_count) { - sc_addr addr3; - sc_iterator3 *it = sc_iterator3_f_a_a_new(context, set, arc_type, end_type); - if (it == 0) + sc_addr addr3; + sc_iterator3 * it = sc_iterator3_f_a_a_new(context, set, arc_type, end_type); + if (it == 0) + { + return SC_FALSE; + } + while (SC_TRUE == sc_iterator3_next(it)) + { + addr3 = sc_iterator3_value(it, 2); + table->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(addr3), addr3)); + + sc_type element_type; + if (sc_memory_get_element_type(context, addr3, &element_type) != SC_RESULT_OK) { - return SC_FALSE; + continue; } - while (SC_TRUE == sc_iterator3_next(it)) + if ((sc_type_var & element_type) == sc_type_var) { - addr3 = sc_iterator3_value(it, 2); - table->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(addr3), addr3)); - - sc_type element_type; - if (sc_memory_get_element_type(context, addr3, &element_type) != SC_RESULT_OK) {continue;} - if ((sc_type_var & element_type) == sc_type_var) - { - (*var_count)++; - } + (*var_count)++; } - sc_iterator3_free(it); - return SC_TRUE; + } + sc_iterator3_free(it); + return SC_TRUE; } -sc_bool find_result_pair_for_var(sc_type_result *set, sc_addr var_element, sc_addr *result) +sc_bool find_result_pair_for_var(sc_type_result * set, sc_addr var_element, sc_addr * result) { - sc_type_result::iterator it = set->find(var_element); - if (it == set->end()) - { - return SC_FALSE; - } - else - { - *result = (*it).second; - return SC_TRUE; - } + sc_type_result::iterator it = set->find(var_element); + if (it == set->end()) + { + return SC_FALSE; + } + else + { + *result = (*it).second; + return SC_TRUE; + } } -sc_bool find_result_pair_for_const(sc_type_result *set, sc_addr const_element, sc_addr *result) +sc_bool find_result_pair_for_const(sc_type_result * set, sc_addr const_element, sc_addr * result) { - sc_type_result::iterator it; - for (it = set->begin() ; it != set->end(); it++) + sc_type_result::iterator it; + for (it = set->begin(); it != set->end(); it++) + { + sc_addr var = (*it).first; + sc_addr cnst = (*it).second; + if (SC_ADDR_IS_EQUAL(cnst, const_element)) { - sc_addr var = (*it).first; - sc_addr cnst = (*it).second; - if (SC_ADDR_IS_EQUAL(cnst, const_element)) - { - *result = var; - return SC_TRUE; - } + *result = var; + return SC_TRUE; } - return SC_FALSE; + } + return SC_FALSE; } -void cantorize_result_vector(sc_type_result_vector *result) +void cantorize_result_vector(sc_type_result_vector * result) { - std::set myset(result->begin(), result->end()); - result->clear(); - result->insert(result->begin(), myset.begin(), myset.end()); + std::set myset(result->begin(), result->end()); + result->clear(); + result->insert(result->begin(), myset.begin(), myset.end()); } -void remove_all_elements(sc_type_result_vector *pattern, sc_type_result_vector *source) +void remove_all_elements(sc_type_result_vector * pattern, sc_type_result_vector * source) { - for (sc_uint i = 0; i < pattern->size(); i++) - { - source->erase(std::remove(source->begin(), source->end(), (*pattern)[i]), source->end()); - } + for (sc_uint i = 0; i < pattern->size(); i++) + { + source->erase(std::remove(source->begin(), source->end(), (*pattern)[i]), source->end()); + } } -sc_bool check_coherence(sc_memory_context *context, sc_addr element, sc_addr sc_pattern, sc_addr checked_arc, sc_bool output, sc_type_result *result, sc_type_result *inp_result) +sc_bool check_coherence( + sc_memory_context * context, + sc_addr element, + sc_addr sc_pattern, + sc_addr checked_arc, + sc_bool output, + sc_type_result * result, + sc_type_result * inp_result) { - sc_addr addr1, addr2, temp; + sc_addr addr1, addr2, temp; - sc_iterator3 *it_pattern_arc = sc_iterator3_f_a_a_new(context, element, 0, 0); - if (it_pattern_arc == null_ptr) {return SC_FALSE;} - while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + sc_iterator3 * it_pattern_arc = sc_iterator3_f_a_a_new(context, element, 0, 0); + if (it_pattern_arc == null_ptr) + { + return SC_FALSE; + } + while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + { + addr2 = sc_iterator3_value(it_pattern_arc, 1); + if (SC_TRUE == sc_helper_check_arc(context, sc_pattern, addr2, sc_type_arc_pos_const_perm)) { - addr2 = sc_iterator3_value(it_pattern_arc, 1); - if (SC_TRUE == sc_helper_check_arc(context, sc_pattern, addr2, sc_type_arc_pos_const_perm)) - { - if (SC_TRUE == output && SC_ADDR_IS_EQUAL(checked_arc, addr2)) - { - continue; - } - - if (SC_TRUE == find_result_pair_for_var(result, addr2, &temp) && - SC_FALSE == find_result_pair_for_var(inp_result, addr2, &temp)) - { - sc_iterator3_free(it_pattern_arc); - return SC_FALSE; - } - } + if (SC_TRUE == output && SC_ADDR_IS_EQUAL(checked_arc, addr2)) + { + continue; + } + + if (SC_TRUE == find_result_pair_for_var(result, addr2, &temp) && + SC_FALSE == find_result_pair_for_var(inp_result, addr2, &temp)) + { + sc_iterator3_free(it_pattern_arc); + return SC_FALSE; + } } - sc_iterator3_free(it_pattern_arc); + } + sc_iterator3_free(it_pattern_arc); - it_pattern_arc = sc_iterator3_a_a_f_new(context, 0, 0, element); - if (it_pattern_arc == null_ptr) {return SC_FALSE;} - while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + it_pattern_arc = sc_iterator3_a_a_f_new(context, 0, 0, element); + if (it_pattern_arc == null_ptr) + { + return SC_FALSE; + } + while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + { + addr1 = sc_iterator3_value(it_pattern_arc, 0); + if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) + continue; + addr2 = sc_iterator3_value(it_pattern_arc, 1); + if (SC_TRUE == sc_helper_check_arc(context, sc_pattern, addr2, sc_type_arc_pos_const_perm)) { - addr1 = sc_iterator3_value(it_pattern_arc, 0); - if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) continue; - addr2 = sc_iterator3_value(it_pattern_arc, 1); - if (SC_TRUE == sc_helper_check_arc(context, sc_pattern, addr2, sc_type_arc_pos_const_perm)) - { - if (SC_FALSE == output && SC_ADDR_IS_EQUAL(checked_arc, addr2)) - { - continue; - } - - if (SC_TRUE == find_result_pair_for_var(result, addr2, &temp) && - SC_FALSE == find_result_pair_for_var(inp_result, addr2, &temp)) - { - sc_iterator3_free(it_pattern_arc); - return SC_FALSE; - } - } + if (SC_FALSE == output && SC_ADDR_IS_EQUAL(checked_arc, addr2)) + { + continue; + } + + if (SC_TRUE == find_result_pair_for_var(result, addr2, &temp) && + SC_FALSE == find_result_pair_for_var(inp_result, addr2, &temp)) + { + sc_iterator3_free(it_pattern_arc); + return SC_FALSE; + } } - sc_iterator3_free(it_pattern_arc); + } + sc_iterator3_free(it_pattern_arc); - sc_type element_type; + sc_type element_type; - if (SC_RESULT_OK != sc_memory_get_element_type(context, element, &element_type)) {return SC_FALSE;} - if ((sc_type_node & element_type) != sc_type_node) + if (SC_RESULT_OK != sc_memory_get_element_type(context, element, &element_type)) + { + return SC_FALSE; + } + if ((sc_type_node & element_type) != sc_type_node) + { + sc_addr end, begin; + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, element, &begin)) { - sc_addr end, begin; - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, element, &begin)) {return SC_FALSE;} - if (SC_RESULT_OK != sc_memory_get_arc_end(context, element, &end)) {return SC_FALSE;} - - if (SC_TRUE == check_coherence(context, begin, sc_pattern, element, SC_TRUE, result, inp_result) && - SC_TRUE == check_coherence(context, end, sc_pattern, element, SC_FALSE, result, inp_result)) - return SC_TRUE; - else - return SC_FALSE; + return SC_FALSE; } - return SC_TRUE; + if (SC_RESULT_OK != sc_memory_get_arc_end(context, element, &end)) + { + return SC_FALSE; + } + + if (SC_TRUE == check_coherence(context, begin, sc_pattern, element, SC_TRUE, result, inp_result) && + SC_TRUE == check_coherence(context, end, sc_pattern, element, SC_FALSE, result, inp_result)) + return SC_TRUE; + else + return SC_FALSE; + } + return SC_TRUE; } -void free_single_result(sc_type_result *result) +void free_single_result(sc_type_result * result) { - delete result; - //class_count--; + delete result; + // class_count--; } -void free_result_vector(sc_type_result_vector *result) +void free_result_vector(sc_type_result_vector * result) { - for (sc_uint i = 0; i < result->size(); i++) - { - free_single_result((*result)[i]); - } - result->clear(); + for (sc_uint i = 0; i < result->size(); i++) + { + free_single_result((*result)[i]); + } + result->clear(); } -void sort_result_vector(sc_type_result_vector *data) +void sort_result_vector(sc_type_result_vector * data) { - std::sort(data->begin(), data->end(), sc_result_comparator); + std::sort(data->begin(), data->end(), sc_result_comparator); } -sc_bool remove_result_vector_short_results(sc_type_result_vector *data) +sc_bool remove_result_vector_short_results(sc_type_result_vector * data) { - sc_type_result_vector::iterator it; - for (it = data->begin() + 1 ; it != data->end(); it++) + sc_type_result_vector::iterator it; + for (it = data->begin() + 1; it != data->end(); it++) + { + if (sc_result_comparator(*(it - 1), *it)) { - if (sc_result_comparator(*(it - 1), *it)) - { - sc_type_result_vector clear_data(it, data->end()); - data->erase(it, data->end()); - free_result_vector(&clear_data); - return SC_TRUE; - } + sc_type_result_vector clear_data(it, data->end()); + data->erase(it, data->end()); + free_result_vector(&clear_data); + return SC_TRUE; } - return SC_FALSE; + } + return SC_FALSE; } -sc_bool remove_result_vector_short_results(sc_type_result_vector *data, sc_uint size) +sc_bool remove_result_vector_short_results(sc_type_result_vector * data, sc_uint size) { - sc_type_result_vector::iterator it; - for (it = data->begin() ; it != data->end(); it++) + sc_type_result_vector::iterator it; + for (it = data->begin(); it != data->end(); it++) + { + if ((*it)->size() < size) { - if ((*it)->size() < size) - { - sc_type_result_vector clear_data(it, data->end()); - data->erase(it, data->end()); - free_result_vector(&clear_data); - return SC_TRUE; - } + sc_type_result_vector clear_data(it, data->end()); + data->erase(it, data->end()); + free_result_vector(&clear_data); + return SC_TRUE; } - return SC_FALSE; + } + return SC_FALSE; } -sc_bool sc_addr_vector_contains(sc_addr addr, sc_addr_vector *requested_values) +sc_bool sc_addr_vector_contains(sc_addr addr, sc_addr_vector * requested_values) { - for (sc_uint i = 0; i < requested_values->size(); i++) - { - sc_addr addr1 = (*requested_values)[i]; - if (SC_ADDR_IS_EQUAL(addr, addr1)) - return SC_TRUE; - } - return SC_FALSE; + for (sc_uint i = 0; i < requested_values->size(); i++) + { + sc_addr addr1 = (*requested_values)[i]; + if (SC_ADDR_IS_EQUAL(addr, addr1)) + return SC_TRUE; + } + return SC_FALSE; } -void filter_result_vector_by_variables(sc_type_result_vector *data, sc_addr_vector *requested_values) +void filter_result_vector_by_variables(sc_type_result_vector * data, sc_addr_vector * requested_values) { - sc_type_result_vector::iterator it; - sc_type_result::iterator it1; + sc_type_result_vector::iterator it; + sc_type_result::iterator it1; - for (it = data->begin() ; it != data->end(); it++) + for (it = data->begin(); it != data->end(); it++) + { + for (it1 = (*it)->begin(); it1 != (*it)->end(); it1++) { - for (it1 = (*it)->begin() ; it1 != (*it)->end(); it1++) - { - sc_addr key = (*it1).first; - if (SC_FALSE == sc_addr_vector_contains(key, requested_values)) - { - (*it)->erase(key); - } - } + sc_addr key = (*it1).first; + if (SC_FALSE == sc_addr_vector_contains(key, requested_values)) + { + (*it)->erase(key); + } } + } } -void filter_result_by_variables(sc_type_result *data, sc_addr_vector *requested_values) +void filter_result_by_variables(sc_type_result * data, sc_addr_vector * requested_values) { - sc_type_result::iterator it; - for (it = data->begin() ; it != data->end(); it++) + sc_type_result::iterator it; + for (it = data->begin(); it != data->end(); it++) + { + sc_addr key = (*it).first; + if (SC_FALSE == sc_addr_vector_contains(key, requested_values)) { - sc_addr key = (*it).first; - if (SC_FALSE == sc_addr_vector_contains(key, requested_values)) - { - data->erase(key); - } + data->erase(key); } + } } diff --git a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_search.cpp b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_search.cpp index 862402c57..9e0a7d179 100644 --- a/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_search.cpp +++ b/sc-kpm/scp/scp_lib/scp_system_operators/sc_system_search.cpp @@ -21,790 +21,873 @@ along with OSTIS. If not, see . */ extern "C" { -#include "sc_memory_headers.h" #include "sc_helper.h" +#include "sc_memory_headers.h" } #include "sc_system_search.h" -#include #include +#include void print_tab(int level) { - printf("\n"); - for (int i = 0; i < level; i++) - { - printf("\t"); - } + printf("\n"); + for (int i = 0; i < level; i++) + { + printf("\t"); + } } -sc_bool system_sys_search_recurse(sc_memory_context *context, sc_addr sc_pattern, sc_type_hash *pattern, sc_addr curr_const_element, sc_addr curr_pattern_element, sc_type_result *inp_result, sc_type_result_vector *out_common_result, int level) +sc_bool system_sys_search_recurse( + sc_memory_context * context, + sc_addr sc_pattern, + sc_type_hash * pattern, + sc_addr curr_const_element, + sc_addr curr_pattern_element, + sc_type_result * inp_result, + sc_type_result_vector * out_common_result, + int level) { - sc_addr addr1, addr2, temp, temp1; - int out_arc_count = 0; + sc_addr addr1, addr2, temp, temp1; + int out_arc_count = 0; - sc_type_result_vector common_result; - sc_type_result_vector del_result; - sc_type_result inp_result_copy = *inp_result; - common_result.push_back(inp_result); + sc_type_result_vector common_result; + sc_type_result_vector del_result; + sc_type_result inp_result_copy = *inp_result; + common_result.push_back(inp_result); - //Pattern arcs list - sc_addr_vector pattern_arc_set; + // Pattern arcs list + sc_addr_vector pattern_arc_set; - sc_iterator3 *it_pattern_arc = sc_iterator3_f_a_a_new(context, curr_pattern_element, 0, 0); - if (it_pattern_arc == null_ptr) {return SC_FALSE;} - while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + sc_iterator3 * it_pattern_arc = sc_iterator3_f_a_a_new(context, curr_pattern_element, 0, 0); + if (it_pattern_arc == null_ptr) + { + return SC_FALSE; + } + while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + { + addr2 = sc_iterator3_value(it_pattern_arc, 1); + if (pattern->find(SC_ADDR_LOCAL_TO_INT(addr2)) != pattern->end()) + { + out_arc_count++; + pattern_arc_set.push_back(addr2); + } + } + sc_iterator3_free(it_pattern_arc); + + it_pattern_arc = sc_iterator3_a_a_f_new(context, 0, 0, curr_pattern_element); + if (it_pattern_arc == null_ptr) + { + return SC_FALSE; + } + while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + { + addr1 = sc_iterator3_value(it_pattern_arc, 0); + if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) + continue; + addr2 = sc_iterator3_value(it_pattern_arc, 1); + if (pattern->find(SC_ADDR_LOCAL_TO_INT(addr2)) != pattern->end()) { - addr2 = sc_iterator3_value(it_pattern_arc, 1); - if (pattern->find(SC_ADDR_LOCAL_TO_INT(addr2)) != pattern->end()) + pattern_arc_set.push_back(addr2); + } + } + sc_iterator3_free(it_pattern_arc); + + sc_addr pattern_arc; + sc_addr const_arc; + sc_addr next_pattern_element; + sc_addr next_const_element; + sc_addr next_pattern_element_begin, next_pattern_element_end; + sc_addr next_const_element_begin, next_const_element_end; + sc_bool out_arc_flag = SC_TRUE; + sc_type_result_vector new_common_result; + sc_type_result_vector next_common_result; + sc_type_result_vector next_common_result_arc; + sc_type_result_vector next_common_result_begin; + sc_type_result_vector next_common_result_end; + sc_type_result_vector next_common_result_element; + + sc_bool next_pattern_element_is_node = SC_FALSE; + sc_type next_pattern_element_type; + sc_type next_pattern_element_begin_type; + sc_type next_pattern_element_end_type; + + sc_bool pattern_arc_is_const_or_has_value = SC_FALSE; + sc_bool pattern_is_const_or_has_value = SC_FALSE; + sc_bool pattern_begin_is_const_or_has_value = SC_FALSE; + sc_bool pattern_end_is_const_or_has_value = SC_FALSE; + + // Pattern arcs loop + for (sc_uint i = 0; i < pattern_arc_set.size(); i++) + { + pattern_arc = pattern_arc_set[i]; + out_arc_flag = SC_TRUE; + + //! check pattern_arc type + sc_type pattern_arc_type; + if (sc_memory_get_element_type(context, pattern_arc, &pattern_arc_type) != SC_RESULT_OK) + continue; + if ((sc_type_const & pattern_arc_type) == sc_type_const) + continue; + + pattern_arc_is_const_or_has_value = SC_FALSE; + pattern_is_const_or_has_value = SC_FALSE; + + if (out_arc_count > 0) + { + if (SC_RESULT_OK != sc_memory_get_arc_end(context, pattern_arc, &next_pattern_element)) + continue; + out_arc_count--; + } + else + { + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, pattern_arc, &next_pattern_element)) + continue; + out_arc_flag = SC_FALSE; + } + + if (sc_memory_get_element_type(context, next_pattern_element, &next_pattern_element_type) != SC_RESULT_OK) + { + continue; + } + if ((sc_type_node & next_pattern_element_type) == sc_type_node) + { + next_pattern_element_is_node = SC_TRUE; + } + else + { + next_pattern_element_is_node = SC_FALSE; + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_pattern_element, &next_pattern_element_begin)) + { + continue; + } + if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_pattern_element, &next_pattern_element_end)) + { + continue; + } + } + + if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element)) == pattern->end()) + { + continue; + } + if (next_pattern_element_is_node == SC_FALSE) + { + if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin)) == pattern->end()) + { + continue; + } + if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end)) == pattern->end()) + { + continue; + } + } + + sc_type_result::iterator arc_it = inp_result_copy.find(pattern_arc); + if (arc_it != inp_result_copy.end()) + { + const_arc = (*arc_it).second; + pattern_arc_is_const_or_has_value = SC_TRUE; + if (out_arc_flag == SC_TRUE) + { + if (SC_RESULT_OK != sc_memory_get_arc_end(context, const_arc, &next_const_element)) + continue; + } + else + { + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, const_arc, &next_const_element)) + continue; + } + } + + //! check next_pattern_element type + if ((sc_type_const & next_pattern_element_type) == sc_type_const) + { + if (pattern_arc_is_const_or_has_value == SC_TRUE) + { + if (!SC_ADDR_IS_EQUAL(next_const_element, next_pattern_element)) { - out_arc_count++; - pattern_arc_set.push_back(addr2); + continue; } + } + else + { + next_const_element = next_pattern_element; + } + pattern_is_const_or_has_value = SC_TRUE; } - sc_iterator3_free(it_pattern_arc); - - it_pattern_arc = sc_iterator3_a_a_f_new(context, 0, 0, curr_pattern_element); - if (it_pattern_arc == null_ptr) {return SC_FALSE;} - while (SC_TRUE == sc_iterator3_next(it_pattern_arc)) + else { - addr1 = sc_iterator3_value(it_pattern_arc, 0); - if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) continue; - addr2 = sc_iterator3_value(it_pattern_arc, 1); - if (pattern->find(SC_ADDR_LOCAL_TO_INT(addr2)) != pattern->end()) + sc_type_result::iterator it = inp_result_copy.find(next_pattern_element); + if (it != inp_result_copy.end()) + { + if (pattern_arc_is_const_or_has_value == SC_TRUE) { - pattern_arc_set.push_back(addr2); + if (!SC_ADDR_IS_EQUAL(next_const_element, (*it).second)) + { + continue; + } } + else + { + next_const_element = (*it).second; + } + pattern_is_const_or_has_value = SC_TRUE; + } } - sc_iterator3_free(it_pattern_arc); - - sc_addr pattern_arc; - sc_addr const_arc; - sc_addr next_pattern_element; - sc_addr next_const_element; - sc_addr next_pattern_element_begin, next_pattern_element_end; - sc_addr next_const_element_begin, next_const_element_end; - sc_bool out_arc_flag = SC_TRUE; - sc_type_result_vector new_common_result; - sc_type_result_vector next_common_result; - sc_type_result_vector next_common_result_arc; - sc_type_result_vector next_common_result_begin; - sc_type_result_vector next_common_result_end; - sc_type_result_vector next_common_result_element; - - sc_bool next_pattern_element_is_node = SC_FALSE; - sc_type next_pattern_element_type; - sc_type next_pattern_element_begin_type; - sc_type next_pattern_element_end_type; - - sc_bool pattern_arc_is_const_or_has_value = SC_FALSE; - sc_bool pattern_is_const_or_has_value = SC_FALSE; - sc_bool pattern_begin_is_const_or_has_value = SC_FALSE; - sc_bool pattern_end_is_const_or_has_value = SC_FALSE; - - //Pattern arcs loop - for (sc_uint i = 0; i < pattern_arc_set.size(); i++) + + if (next_pattern_element_is_node == SC_FALSE) { - pattern_arc = pattern_arc_set[i]; - out_arc_flag = SC_TRUE; + pattern_begin_is_const_or_has_value = SC_FALSE; + pattern_end_is_const_or_has_value = SC_FALSE; + if (sc_memory_get_element_type(context, next_pattern_element_begin, &next_pattern_element_begin_type) != + SC_RESULT_OK) + { + continue; + } + if (sc_memory_get_element_type(context, next_pattern_element_end, &next_pattern_element_end_type) != SC_RESULT_OK) + { + continue; + } + + if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + { + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_const_element, &next_const_element_begin)) + { + continue; + } + if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_const_element, &next_const_element_end)) + { + continue; + } + } - //!check pattern_arc type - sc_type pattern_arc_type; - if (sc_memory_get_element_type(context, pattern_arc, &pattern_arc_type) != SC_RESULT_OK) + //! check next_pattern_element_begin type + if ((sc_type_const & next_pattern_element_begin_type) == sc_type_const) + { + if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + { + if (!SC_ADDR_IS_EQUAL(next_const_element_begin, next_pattern_element_begin)) + { continue; - if ((sc_type_const & pattern_arc_type) == sc_type_const) + } + } + else + { + next_const_element_begin = next_pattern_element_begin; + } + pattern_begin_is_const_or_has_value = SC_TRUE; + } + else + { + sc_type_result::iterator it = inp_result_copy.find(next_pattern_element_begin); + if (it != inp_result_copy.end()) + { + if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + { + if (!SC_ADDR_IS_EQUAL(next_const_element_begin, (*it).second)) + { + continue; + } + } + else + { + next_const_element_begin = (*it).second; + } + pattern_begin_is_const_or_has_value = SC_TRUE; + } + } + + //! check next_pattern_element_end type + if ((sc_type_const & next_pattern_element_end_type) == sc_type_const) + { + if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + { + if (!SC_ADDR_IS_EQUAL(next_const_element_end, next_pattern_element_end)) + { continue; + } + } + else + { + next_const_element_end = next_pattern_element_end; + } + pattern_end_is_const_or_has_value = SC_TRUE; + } + else + { + sc_type_result::iterator it = inp_result_copy.find(next_pattern_element_end); + if (it != inp_result_copy.end()) + { + if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + { + if (!SC_ADDR_IS_EQUAL(next_const_element_end, (*it).second)) + { + continue; + } + } + else + { + next_const_element_end = (*it).second; + } + pattern_end_is_const_or_has_value = SC_TRUE; + } + } + } - pattern_arc_is_const_or_has_value = SC_FALSE; - pattern_is_const_or_has_value = SC_FALSE; + //! const arc loop + sc_addr_vector const_arc_set; - if (out_arc_count > 0) + if (pattern_arc_is_const_or_has_value == SC_FALSE) + { + sc_iterator3 * it_const_arc; + sc_type const_arc_type = ((~sc_type_var & pattern_arc_type) | sc_type_const); + if (out_arc_flag == SC_TRUE) + { + if (pattern_is_const_or_has_value == SC_TRUE) { - if (SC_RESULT_OK != sc_memory_get_arc_end(context, pattern_arc, &next_pattern_element)) - continue; - out_arc_count--; + it_const_arc = sc_iterator3_f_a_f_new(context, curr_const_element, const_arc_type, next_const_element); } else { - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, pattern_arc, &next_pattern_element)) - continue; - out_arc_flag = SC_FALSE; + sc_type next_const_element_type = ((~sc_type_var & next_pattern_element_type) | sc_type_const); + if ((sc_type_node & next_pattern_element_type) == sc_type_node) + { + next_const_element_type = next_const_element_type & sc_type_link; + } + it_const_arc = sc_iterator3_f_a_a_new(context, curr_const_element, const_arc_type, next_const_element_type); } - - if (sc_memory_get_element_type(context, next_pattern_element, &next_pattern_element_type) != SC_RESULT_OK) {continue;} - if ((sc_type_node & next_pattern_element_type) == sc_type_node) + } + else + { + if (pattern_is_const_or_has_value == SC_TRUE) { - next_pattern_element_is_node = SC_TRUE; + it_const_arc = sc_iterator3_f_a_f_new(context, next_const_element, const_arc_type, curr_const_element); } else { - next_pattern_element_is_node = SC_FALSE; - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_pattern_element, &next_pattern_element_begin)) {continue;} - if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_pattern_element, &next_pattern_element_end)) {continue;} + sc_type next_const_element_type = ((~sc_type_var & next_pattern_element_type) | sc_type_const); + if ((sc_type_node & next_pattern_element_type) == sc_type_node) + { + next_const_element_type = next_const_element_type & sc_type_link; + } + it_const_arc = sc_iterator3_a_a_f_new(context, next_const_element_type, const_arc_type, curr_const_element); + } + } + while (SC_TRUE == sc_iterator3_next(it_const_arc)) + { + if (out_arc_flag == SC_FALSE) + { + addr1 = sc_iterator3_value(it_const_arc, 0); + if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) + continue; } + addr2 = sc_iterator3_value(it_const_arc, 1); + const_arc_set.push_back(addr2); + } + sc_iterator3_free(it_const_arc); + } + else + { + const_arc_set.push_back(const_arc); + } + + for (sc_uint j = 0; j < const_arc_set.size(); j++) + { + const_arc = const_arc_set[j]; - if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element)) == pattern->end()) + if (pattern_arc_is_const_or_has_value == SC_FALSE) + { + if (out_arc_flag == SC_TRUE) { + if (SC_RESULT_OK != sc_memory_get_arc_end(context, const_arc, &next_const_element)) continue; } - if (next_pattern_element_is_node == SC_FALSE) + else { - if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin)) == pattern->end()) - { - continue; - } - if (pattern->find(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end)) == pattern->end()) - { - continue; - } + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, const_arc, &next_const_element)) + continue; } + } - sc_type_result::iterator arc_it = inp_result_copy.find(pattern_arc); - if (arc_it != inp_result_copy.end()) + //! TODO Optimize + if (SC_FALSE == next_pattern_element_is_node) + { + sc_addr next_const_element_begin1, next_const_element_end1; + if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_const_element, &next_const_element_begin1)) { - const_arc = (*arc_it).second; - pattern_arc_is_const_or_has_value = SC_TRUE; - if (out_arc_flag == SC_TRUE) - { - if (SC_RESULT_OK != sc_memory_get_arc_end(context, const_arc, &next_const_element)) - continue; - } - else - { - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, const_arc, &next_const_element)) - continue; - } + continue; + } + if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_const_element, &next_const_element_end1)) + { + continue; + } + if (SC_TRUE == pattern_begin_is_const_or_has_value && + SC_ADDR_IS_NOT_EQUAL(next_const_element_begin, next_const_element_begin1)) + { + continue; + } + if (SC_TRUE == pattern_end_is_const_or_has_value && + SC_ADDR_IS_NOT_EQUAL(next_const_element_end, next_const_element_end1)) + { + continue; } + next_const_element_begin = next_const_element_begin1; + next_const_element_end = next_const_element_end1; + } - //!check next_pattern_element type - if ((sc_type_const & next_pattern_element_type) == sc_type_const) + //! Results loop + for (sc_uint k = 0; k < common_result.size(); k++) + { + sc_type_result * result = common_result[k]; + + if (pattern_arc_is_const_or_has_value == SC_FALSE) { - if (pattern_arc_is_const_or_has_value == SC_TRUE) + if (SC_TRUE == find_result_pair_for_const(result, const_arc, &temp)) + continue; + + if (SC_FALSE == pattern_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element)) + { + continue; + } + if (SC_FALSE == next_pattern_element_is_node) + { + if (SC_FALSE == pattern_begin_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element_begin, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_begin)) { - if (!SC_ADDR_IS_EQUAL(next_const_element, next_pattern_element)) - { - continue; - } + continue; } - else + if (SC_FALSE == pattern_end_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element_end, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_end)) { - next_const_element = next_pattern_element; + continue; } - pattern_is_const_or_has_value = SC_TRUE; - } - else - { - sc_type_result::iterator it = inp_result_copy.find(next_pattern_element); - if (it != inp_result_copy.end()) + } + + if (SC_TRUE == find_result_pair_for_var(result, pattern_arc, &temp)) + { + //! Gen new result + + if (SC_FALSE == + check_coherence( + context, next_pattern_element, sc_pattern, pattern_arc, !out_arc_flag, result, &inp_result_copy)) { - if (pattern_arc_is_const_or_has_value == SC_TRUE) - { - if (!SC_ADDR_IS_EQUAL(next_const_element, (*it).second)) - { - continue; - } - } - else - { - next_const_element = (*it).second; - } - pattern_is_const_or_has_value = SC_TRUE; + continue; } - } - if (next_pattern_element_is_node == SC_FALSE) - { - pattern_begin_is_const_or_has_value = SC_FALSE; - pattern_end_is_const_or_has_value = SC_FALSE; - if (sc_memory_get_element_type(context, next_pattern_element_begin, &next_pattern_element_begin_type) != SC_RESULT_OK) {continue;} - if (sc_memory_get_element_type(context, next_pattern_element_end, &next_pattern_element_end_type) != SC_RESULT_OK) {continue;} + sc_type_result * new_result = new sc_type_result(); - if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) + (*new_result) = (*result); + new_common_result.push_back(new_result); + result = new_result; + result->erase(pattern_arc); + if (pattern_is_const_or_has_value == SC_FALSE) { - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_const_element, &next_const_element_begin)) {continue;} - if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_const_element, &next_const_element_end)) {continue;} + result->erase(next_pattern_element); } - - //!check next_pattern_element_begin type - if ((sc_type_const & next_pattern_element_begin_type) == sc_type_const) + if (SC_FALSE == next_pattern_element_is_node) + { + if (pattern_begin_is_const_or_has_value == SC_FALSE) + { + result->erase(next_pattern_element_begin); + } + if (pattern_end_is_const_or_has_value == SC_FALSE) + { + result->erase(next_pattern_element_end); + } + } + } + else + { + //! TODO Add flags to not add already existing elements + if (SC_FALSE == pattern_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element)) { - if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) - { - if (!SC_ADDR_IS_EQUAL(next_const_element_begin, next_pattern_element_begin)) - { - continue; - } - } - else - { - next_const_element_begin = next_pattern_element_begin; - } - pattern_begin_is_const_or_has_value = SC_TRUE; + continue; } - else + if (SC_FALSE == next_pattern_element_is_node) { - sc_type_result::iterator it = inp_result_copy.find(next_pattern_element_begin); - if (it != inp_result_copy.end()) - { - if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) - { - if (!SC_ADDR_IS_EQUAL(next_const_element_begin, (*it).second)) - { - continue; - } - } - else - { - next_const_element_begin = (*it).second; - } - pattern_begin_is_const_or_has_value = SC_TRUE; - } + if (SC_FALSE == pattern_begin_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element_begin, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_begin)) + { + continue; + } + if (SC_FALSE == pattern_end_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element_end, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_end)) + { + continue; + } } + } - //!check next_pattern_element_end type - if ((sc_type_const & next_pattern_element_end_type) == sc_type_const) + //! Genering pair for 2nd element + result->insert(sc_addr_pair(pattern_arc, const_arc)); + + //! Genering pair for 3rd element + if (pattern_is_const_or_has_value == SC_FALSE) + { + result->insert(sc_addr_pair(next_pattern_element, next_const_element)); + } + + //! Generating pair for next pattern element begin and end + if (SC_FALSE == next_pattern_element_is_node) + { + if (pattern_begin_is_const_or_has_value == SC_FALSE) { - if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) - { - if (!SC_ADDR_IS_EQUAL(next_const_element_end, next_pattern_element_end)) - { - continue; - } - } - else - { - next_const_element_end = next_pattern_element_end; - } - pattern_end_is_const_or_has_value = SC_TRUE; + result->insert(sc_addr_pair(next_pattern_element_begin, next_const_element_begin)); } - else + if (pattern_end_is_const_or_has_value == SC_FALSE) { - sc_type_result::iterator it = inp_result_copy.find(next_pattern_element_end); - if (it != inp_result_copy.end()) - { - if (SC_TRUE == pattern_arc_is_const_or_has_value || SC_TRUE == pattern_is_const_or_has_value) - { - if (!SC_ADDR_IS_EQUAL(next_const_element_end, (*it).second)) - { - continue; - } - } - else - { - next_const_element_end = (*it).second; - } - pattern_end_is_const_or_has_value = SC_TRUE; - } + result->insert(sc_addr_pair(next_pattern_element_end, next_const_element_end)); } + } } - - //!const arc loop - sc_addr_vector const_arc_set; - - if (pattern_arc_is_const_or_has_value == SC_FALSE) + else { - sc_iterator3 *it_const_arc; - sc_type const_arc_type = ((~sc_type_var & pattern_arc_type) | sc_type_const); - if (out_arc_flag == SC_TRUE) + if (SC_TRUE == find_result_pair_for_const(result, const_arc, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, pattern_arc)) + { + continue; + } + if (SC_TRUE == find_result_pair_for_var(result, pattern_arc, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, const_arc)) + { + continue; + } + if (SC_FALSE == pattern_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element)) + { + continue; + } + if (SC_FALSE == next_pattern_element_is_node) + { + if (SC_FALSE == pattern_begin_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element_begin, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_begin)) + { + continue; + } + if (SC_FALSE == pattern_end_is_const_or_has_value && + SC_TRUE == find_result_pair_for_const(result, next_const_element_end, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_end)) + { + continue; + } + } + if (SC_FALSE == pattern_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element)) + { + continue; + } + if (SC_FALSE == next_pattern_element_is_node) + { + if (SC_FALSE == pattern_begin_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element_begin, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_begin)) + { + continue; + } + if (SC_FALSE == pattern_end_is_const_or_has_value && + SC_TRUE == find_result_pair_for_var(result, next_pattern_element_end, &temp1) && + SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_end)) { - if (pattern_is_const_or_has_value == SC_TRUE) - { - it_const_arc = sc_iterator3_f_a_f_new(context, curr_const_element, const_arc_type, next_const_element); - } - else - { - sc_type next_const_element_type = ((~sc_type_var & next_pattern_element_type) | sc_type_const); - if ((sc_type_node & next_pattern_element_type) == sc_type_node) - { - next_const_element_type = next_const_element_type & sc_type_link; - } - it_const_arc = sc_iterator3_f_a_a_new(context, curr_const_element, const_arc_type, next_const_element_type); - } + continue; } - else + } + //! Genering pair for 3rd element + if (pattern_is_const_or_has_value == SC_FALSE) + { + result->insert(sc_addr_pair(next_pattern_element, next_const_element)); + } + + //! Generating pair for next pattern element begin and end + if (SC_FALSE == next_pattern_element_is_node) + { + if (pattern_begin_is_const_or_has_value == SC_FALSE) { - if (pattern_is_const_or_has_value == SC_TRUE) - { - it_const_arc = sc_iterator3_f_a_f_new(context, next_const_element, const_arc_type, curr_const_element); - } - else - { - sc_type next_const_element_type = ((~sc_type_var & next_pattern_element_type) | sc_type_const); - if ((sc_type_node & next_pattern_element_type) == sc_type_node) - { - next_const_element_type = next_const_element_type & sc_type_link; - } - it_const_arc = sc_iterator3_a_a_f_new(context, next_const_element_type, const_arc_type, curr_const_element); - } + result->insert(sc_addr_pair(next_pattern_element_begin, next_const_element_begin)); } - while (SC_TRUE == sc_iterator3_next(it_const_arc)) + if (pattern_end_is_const_or_has_value == SC_FALSE) { - if (out_arc_flag == SC_FALSE) - { - addr1 = sc_iterator3_value(it_const_arc, 0); - if (SC_ADDR_IS_EQUAL(addr1, sc_pattern)) - continue; - } - addr2 = sc_iterator3_value(it_const_arc, 1); - const_arc_set.push_back(addr2); + result->insert(sc_addr_pair(next_pattern_element_end, next_const_element_end)); } - sc_iterator3_free(it_const_arc); + } } - else + + sc_type_result * arc_result = new sc_type_result(); + (*arc_result) = (*result); + del_result.push_back(result); + + pattern->erase(SC_ADDR_LOCAL_TO_INT(pattern_arc)); + pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element)); + if (next_pattern_element_is_node == SC_FALSE) { - const_arc_set.push_back(const_arc); + pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin)); + pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end)); } - for (sc_uint j = 0; j < const_arc_set.size(); j++) - { - const_arc = const_arc_set[j]; + system_sys_search_recurse( + context, sc_pattern, pattern, const_arc, pattern_arc, arc_result, &next_common_result_arc, level + 1); - if (pattern_arc_is_const_or_has_value == SC_FALSE) + for (sc_uint kk = 0; kk < next_common_result_arc.size(); kk++) + { + sc_type_result * element_result = next_common_result_arc[kk]; + system_sys_search_recurse( + context, + sc_pattern, + pattern, + next_const_element, + next_pattern_element, + element_result, + &next_common_result_element, + level + 1); + + if (SC_FALSE == next_pattern_element_is_node) + { + //! Recurse for begin element + for (sc_uint kk_begin = 0; kk_begin < next_common_result_element.size(); kk_begin++) { - if (out_arc_flag == SC_TRUE) - { - if (SC_RESULT_OK != sc_memory_get_arc_end(context, const_arc, &next_const_element)) - continue; - } - else - { - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, const_arc, &next_const_element)) - continue; - } + sc_type_result * begin_result = next_common_result_element[kk_begin]; + system_sys_search_recurse( + context, + sc_pattern, + pattern, + next_const_element_begin, + next_pattern_element_begin, + begin_result, + &next_common_result_begin, + level + 1); + + //! Recurse for end element + for (sc_uint kk_end = 0; kk_end < next_common_result_begin.size(); kk_end++) + { + sc_type_result * end_result = next_common_result_begin[kk_end]; + system_sys_search_recurse( + context, + sc_pattern, + pattern, + next_const_element_end, + next_pattern_element_end, + end_result, + &next_common_result_end, + level + 1); + + next_common_result.insert( + next_common_result.end(), next_common_result_end.begin(), next_common_result_end.end()); + next_common_result_end.clear(); + } + + next_common_result_begin.clear(); } + next_common_result_element.clear(); + } + else + { + next_common_result.insert( + next_common_result.end(), next_common_result_element.begin(), next_common_result_element.end()); + next_common_result_element.clear(); + } + } - //!TODO Optimize - if (SC_FALSE == next_pattern_element_is_node) - { - sc_addr next_const_element_begin1, next_const_element_end1; - if (SC_RESULT_OK != sc_memory_get_arc_begin(context, next_const_element, &next_const_element_begin1)) {continue;} - if (SC_RESULT_OK != sc_memory_get_arc_end(context, next_const_element, &next_const_element_end1)) {continue;} - if (SC_TRUE == pattern_begin_is_const_or_has_value && SC_ADDR_IS_NOT_EQUAL(next_const_element_begin, next_const_element_begin1)) - { - continue; - } - if (SC_TRUE == pattern_end_is_const_or_has_value && SC_ADDR_IS_NOT_EQUAL(next_const_element_end, next_const_element_end1)) - { - continue; - } - next_const_element_begin = next_const_element_begin1; - next_const_element_end = next_const_element_end1; - } + pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(pattern_arc), pattern_arc)); + pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element), next_pattern_element)); + if (next_pattern_element_is_node == SC_FALSE) + { + pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin), next_pattern_element_begin)); + pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end), next_pattern_element_end)); + } - //!Results loop - for (sc_uint k = 0; k < common_result.size(); k++) - { - sc_type_result *result = common_result[k]; - - if (pattern_arc_is_const_or_has_value == SC_FALSE) - { - if (SC_TRUE == find_result_pair_for_const(result, const_arc, &temp)) - continue; - - - if (SC_FALSE == pattern_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element)) - { - continue; - } - if (SC_FALSE == next_pattern_element_is_node) - { - if (SC_FALSE == pattern_begin_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element_begin, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_begin)) - { - continue; - } - if (SC_FALSE == pattern_end_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element_end, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_end)) - { - continue; - } - } - - if (SC_TRUE == find_result_pair_for_var(result, pattern_arc, &temp)) - { - //!Gen new result - - if (SC_FALSE == check_coherence(context, next_pattern_element, sc_pattern, pattern_arc, !out_arc_flag, result, &inp_result_copy)) - { - continue; - } - - sc_type_result *new_result = new sc_type_result(); - - (*new_result) = (*result); - new_common_result.push_back(new_result); - result = new_result; - result->erase(pattern_arc); - if (pattern_is_const_or_has_value == SC_FALSE) - { - result->erase(next_pattern_element); - } - if (SC_FALSE == next_pattern_element_is_node) - { - if (pattern_begin_is_const_or_has_value == SC_FALSE) - { - result->erase(next_pattern_element_begin); - } - if (pattern_end_is_const_or_has_value == SC_FALSE) - { - result->erase(next_pattern_element_end); - } - } - } - else - { - //! TODO Add flags to not add already existing elements - if (SC_FALSE == pattern_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element)) - { - continue; - } - if (SC_FALSE == next_pattern_element_is_node) - { - if (SC_FALSE == pattern_begin_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element_begin, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_begin)) - { - continue; - } - if (SC_FALSE == pattern_end_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element_end, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_end)) - { - continue; - } - } - } - - //!Genering pair for 2nd element - result->insert(sc_addr_pair(pattern_arc, const_arc)); - - //!Genering pair for 3rd element - if (pattern_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element, next_const_element)); - } - - //! Generating pair for next pattern element begin and end - if (SC_FALSE == next_pattern_element_is_node) - { - if (pattern_begin_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element_begin, next_const_element_begin)); - } - if (pattern_end_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element_end, next_const_element_end)); - } - } - } - else - { - if (SC_TRUE == find_result_pair_for_const(result, const_arc, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, pattern_arc)) - { - continue; - } - if (SC_TRUE == find_result_pair_for_var(result, pattern_arc, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, const_arc)) - { - continue; - } - if (SC_FALSE == pattern_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element)) - { - continue; - } - if (SC_FALSE == next_pattern_element_is_node) - { - if (SC_FALSE == pattern_begin_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element_begin, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_begin)) - { - continue; - } - if (SC_FALSE == pattern_end_is_const_or_has_value - && SC_TRUE == find_result_pair_for_const(result, next_const_element_end, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_pattern_element_end)) - { - continue; - } - } - if (SC_FALSE == pattern_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element)) - { - continue; - } - if (SC_FALSE == next_pattern_element_is_node) - { - if (SC_FALSE == pattern_begin_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element_begin, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_begin)) - { - continue; - } - if (SC_FALSE == pattern_end_is_const_or_has_value - && SC_TRUE == find_result_pair_for_var(result, next_pattern_element_end, &temp1) - && SC_ADDR_IS_NOT_EQUAL(temp1, next_const_element_end)) - { - continue; - } - } - //!Genering pair for 3rd element - if (pattern_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element, next_const_element)); - } - - //! Generating pair for next pattern element begin and end - if (SC_FALSE == next_pattern_element_is_node) - { - if (pattern_begin_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element_begin, next_const_element_begin)); - } - if (pattern_end_is_const_or_has_value == SC_FALSE) - { - result->insert(sc_addr_pair(next_pattern_element_end, next_const_element_end)); - } - } - } - - sc_type_result *arc_result = new sc_type_result(); - (*arc_result) = (*result); - del_result.push_back(result); - - pattern->erase(SC_ADDR_LOCAL_TO_INT(pattern_arc)); - pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element)); - if (next_pattern_element_is_node == SC_FALSE) - { - pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin)); - pattern->erase(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end)); - } - - system_sys_search_recurse(context, sc_pattern, pattern, const_arc, pattern_arc, - arc_result, &next_common_result_arc, level + 1); - - for (sc_uint kk = 0; kk < next_common_result_arc.size(); kk++) - { - sc_type_result *element_result = next_common_result_arc[kk]; - system_sys_search_recurse(context, sc_pattern, pattern, next_const_element, next_pattern_element, - element_result, &next_common_result_element, level + 1); - - if (SC_FALSE == next_pattern_element_is_node) - { - //! Recurse for begin element - for (sc_uint kk_begin = 0; kk_begin < next_common_result_element.size(); kk_begin++) - { - sc_type_result *begin_result = next_common_result_element[kk_begin]; - system_sys_search_recurse(context, sc_pattern, pattern, next_const_element_begin, next_pattern_element_begin, - begin_result, &next_common_result_begin, level + 1); - - //! Recurse for end element - for (sc_uint kk_end = 0; kk_end < next_common_result_begin.size(); kk_end++) - { - sc_type_result *end_result = next_common_result_begin[kk_end]; - system_sys_search_recurse(context, sc_pattern, pattern, next_const_element_end, next_pattern_element_end, - end_result, &next_common_result_end, level + 1); - - next_common_result.insert(next_common_result.end(), - next_common_result_end.begin(), next_common_result_end.end()); - next_common_result_end.clear(); - } - - next_common_result_begin.clear(); - } - next_common_result_element.clear(); - } - else - { - next_common_result.insert(next_common_result.end(), - next_common_result_element.begin(), next_common_result_element.end()); - next_common_result_element.clear(); - } - } - - pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(pattern_arc), pattern_arc)); - pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element), next_pattern_element)); - if (next_pattern_element_is_node == SC_FALSE) - { - pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element_begin), next_pattern_element_begin)); - pattern->insert(sc_hash_pair(SC_ADDR_LOCAL_TO_INT(next_pattern_element_end), next_pattern_element_end)); - } - - out_common_result->insert(out_common_result->end(), next_common_result.begin(), next_common_result.end()); - new_common_result.insert(new_common_result.end(), next_common_result.begin(), next_common_result.end()); - next_common_result.clear(); - next_common_result_arc.clear(); - } - }//const loop + out_common_result->insert(out_common_result->end(), next_common_result.begin(), next_common_result.end()); + new_common_result.insert(new_common_result.end(), next_common_result.begin(), next_common_result.end()); + next_common_result.clear(); + next_common_result_arc.clear(); + } + } // const loop - common_result.insert(common_result.begin(), new_common_result.begin(), new_common_result.end()); + common_result.insert(common_result.begin(), new_common_result.begin(), new_common_result.end()); - new_common_result.clear(); - remove_all_elements(&del_result, &common_result); - remove_all_elements(&del_result, out_common_result); - free_result_vector(&del_result); - }//pattern loop + new_common_result.clear(); + remove_all_elements(&del_result, &common_result); + remove_all_elements(&del_result, out_common_result); + free_result_vector(&del_result); + } // pattern loop - out_common_result->insert(out_common_result->end(), common_result.begin(), common_result.end()); - common_result.clear(); - cantorize_result_vector(out_common_result); + out_common_result->insert(out_common_result->end(), common_result.begin(), common_result.end()); + common_result.clear(); + cantorize_result_vector(out_common_result); - return SC_TRUE; + return SC_TRUE; } /* * returns SC_FALSE if element can't be found otherwise SC_TRUE -*/ -sc_bool get_const_element(sc_memory_context *context, sc_addr pattern, sc_addr *result) + */ +sc_bool get_const_element(sc_memory_context * context, sc_addr pattern, sc_addr * result) { - sc_iterator3 *it = sc_iterator3_f_a_a_new(context, pattern, sc_type_arc_pos_const_perm, sc_type_const); - if (SC_TRUE == sc_iterator3_next(it)) - { - *result = sc_iterator3_value(it, 2); - sc_iterator3_free(it); - return SC_TRUE; - } + sc_iterator3 * it = sc_iterator3_f_a_a_new(context, pattern, sc_type_arc_pos_const_perm, sc_type_const); + if (SC_TRUE == sc_iterator3_next(it)) + { + *result = sc_iterator3_value(it, 2); sc_iterator3_free(it); - return SC_FALSE; + return SC_TRUE; + } + sc_iterator3_free(it); + return SC_FALSE; } -sc_result system_sys_search_only_full(sc_memory_context *context, sc_addr pattern, sc_type_result params, sc_type_result_vector *search_result) +sc_result system_sys_search_only_full( + sc_memory_context * context, + sc_addr pattern, + sc_type_result params, + sc_type_result_vector * search_result) { - sc_addr start_pattern_node, start_const_node; + sc_addr start_pattern_node, start_const_node; - if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + { + if (params.empty()) { - if (params.empty()) - { - std::cout << "ERROR: need const element to start search!" << std::endl; - return SC_RESULT_ERROR_INVALID_PARAMS; - } - else - { - sc_type_result::iterator it = params.begin(); - start_pattern_node = (*it).first; - start_const_node = (*it).second; - } + std::cout << "ERROR: need const element to start search!" << std::endl; + return SC_RESULT_ERROR_INVALID_PARAMS; } else { - start_const_node = start_pattern_node; + sc_type_result::iterator it = params.begin(); + start_pattern_node = (*it).first; + start_const_node = (*it).second; } - sc_type_result *result = new sc_type_result(); - *result = params; + } + else + { + start_const_node = start_pattern_node; + } + sc_type_result * result = new sc_type_result(); + *result = params; - sc_uint var_count = 0; - sc_type_hash pattern_hash; + sc_uint var_count = 0; + sc_type_hash pattern_hash; - /*sc_helper_resolve_system_identifier(context, "aaa123", &start_pattern_node); - sc_helper_resolve_system_identifier(context, "aaa123", &start_const_node); + /*sc_helper_resolve_system_identifier(context, "aaa123", &start_pattern_node); + sc_helper_resolve_system_identifier(context, "aaa123", &start_const_node); - printf("START ELEMENT\n"); - printIdtf(context, start_pattern_node); - printf("\n");*/ + printf("START ELEMENT\n"); + printIdtf(context, start_pattern_node); + printf("\n");*/ - copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); - pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); - system_sys_search_recurse(context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 0); + copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); + pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); + system_sys_search_recurse( + context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 0); - sort_result_vector(search_result); - remove_result_vector_short_results(search_result, var_count); + sort_result_vector(search_result); + remove_result_vector_short_results(search_result, var_count); - //print_result_set(context, search_result); + // print_result_set(context, search_result); - return SC_RESULT_OK; + return SC_RESULT_OK; } -sc_result system_sys_search_for_variables(sc_memory_context *context, sc_addr pattern, sc_type_result params, sc_addr_vector requested_values, sc_type_result_vector *search_result) +sc_result system_sys_search_for_variables( + sc_memory_context * context, + sc_addr pattern, + sc_type_result params, + sc_addr_vector requested_values, + sc_type_result_vector * search_result) { - sc_addr start_pattern_node, start_const_node; + sc_addr start_pattern_node, start_const_node; - if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + { + if (params.empty()) { - if (params.empty()) - { - std::cout << "ERROR: need const element to start search!" << std::endl; - return SC_RESULT_ERROR_INVALID_PARAMS; - } - else - { - sc_type_result::iterator it = params.begin(); - start_pattern_node = (*it).first; - start_const_node = (*it).second; - } + std::cout << "ERROR: need const element to start search!" << std::endl; + return SC_RESULT_ERROR_INVALID_PARAMS; } else { - start_const_node = start_pattern_node; - } - - sc_type_result *result = new sc_type_result(); - *result = params; - - sc_uint var_count = 0; - sc_type_hash pattern_hash; - - /*printf("START ELEMENT\n"); - printIdtf(context, start_pattern_node); - printf("\n");*/ - - copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); - pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); - system_sys_search_recurse(context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 2); - - sort_result_vector(search_result); - remove_result_vector_short_results(search_result, var_count); - if (!requested_values.empty()) - { - filter_result_vector_by_variables(search_result, &requested_values); + sc_type_result::iterator it = params.begin(); + start_pattern_node = (*it).first; + start_const_node = (*it).second; } - - return SC_RESULT_OK; + } + else + { + start_const_node = start_pattern_node; + } + + sc_type_result * result = new sc_type_result(); + *result = params; + + sc_uint var_count = 0; + sc_type_hash pattern_hash; + + /*printf("START ELEMENT\n"); + printIdtf(context, start_pattern_node); + printf("\n");*/ + + copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); + pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); + system_sys_search_recurse( + context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 2); + + sort_result_vector(search_result); + remove_result_vector_short_results(search_result, var_count); + if (!requested_values.empty()) + { + filter_result_vector_by_variables(search_result, &requested_values); + } + + return SC_RESULT_OK; } -sc_result system_sys_search(sc_memory_context *context, sc_addr pattern, sc_type_result params, sc_type_result_vector *search_result) +sc_result system_sys_search( + sc_memory_context * context, + sc_addr pattern, + sc_type_result params, + sc_type_result_vector * search_result) { - sc_addr start_pattern_node, start_const_node; - if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + sc_addr start_pattern_node, start_const_node; + if (SC_FALSE == get_const_element(context, pattern, &start_pattern_node)) + { + if (params.empty()) { - if (params.empty()) - { - std::cout << "ERROR: need const element to start search!" << std::endl; - return SC_RESULT_ERROR_INVALID_PARAMS; - } - else - { - sc_type_result::iterator it = params.begin(); - start_pattern_node = (*it).first; - start_const_node = (*it).second; - } + std::cout << "ERROR: need const element to start search!" << std::endl; + return SC_RESULT_ERROR_INVALID_PARAMS; } else { - start_const_node = start_pattern_node; + sc_type_result::iterator it = params.begin(); + start_pattern_node = (*it).first; + start_const_node = (*it).second; } + } + else + { + start_const_node = start_pattern_node; + } - sc_type_result *result = new sc_type_result(); - *result = params; + sc_type_result * result = new sc_type_result(); + *result = params; - sc_uint var_count = 0; - sc_type_hash pattern_hash; + sc_uint var_count = 0; + sc_type_hash pattern_hash; - copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); - pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); - system_sys_search_recurse(context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 2); + copy_set_into_hash(context, pattern, sc_type_arc_pos_const_perm, 0, &pattern_hash, &var_count); + pattern_hash.erase(SC_ADDR_LOCAL_TO_INT(start_pattern_node)); + system_sys_search_recurse( + context, pattern, &pattern_hash, start_const_node, start_pattern_node, result, search_result, 2); - sort_result_vector(search_result); - remove_result_vector_short_results(search_result); + sort_result_vector(search_result); + remove_result_vector_short_results(search_result); - return SC_RESULT_OK; + return SC_RESULT_OK; } diff --git a/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_gen.cpp b/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_gen.cpp index 4d16796f8..8f2830a0b 100644 --- a/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_gen.cpp +++ b/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_gen.cpp @@ -26,68 +26,82 @@ extern "C" { #include "sc_memory_headers.h" -#include "scp_sys_gen.h" #include "../scp_types.h" + +#include "scp_sys_gen.h" } -extern "C" scp_result sys_gen(sc_memory_context *context, scp_operand *param1, scp_operand *param2, scp_operand_pair *parameters, sc_uint32 param_count, scp_operand *param4) +extern "C" scp_result sys_gen( + sc_memory_context * context, + scp_operand * param1, + scp_operand * param2, + scp_operand_pair * parameters, + sc_uint32 param_count, + scp_operand * param4) { - sc_type_result params; - sc_addr addr1, addr2, arc; - sc_type_result result; - sc_type_result::iterator it; - sc_uint i; - - for (i = 0; i < param_count; i++) + sc_type_result params; + sc_addr addr1, addr2, arc; + sc_type_result result; + sc_type_result::iterator it; + sc_uint i; + + for (i = 0; i < param_count; i++) + { + params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + } + system_sys_gen(context, param1->addr, params, &result); + + for (it = result.begin(); it != result.end(); it++) + { + addr1 = (*it).first; + addr2 = (*it).second; + arc = sc_memory_arc_new(context, sc_type_arc_common | sc_type_const, addr1, addr2); + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param2->addr, arc); + if (param4 != null_ptr) { - params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr2); } - system_sys_gen(context, param1->addr, params, &result); + } - for (it = result.begin() ; it != result.end(); it++) - { - addr1 = (*it).first; - addr2 = (*it).second; - arc = sc_memory_arc_new(context, sc_type_arc_common | sc_type_const, addr1, addr2); - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param2->addr, arc); - if (param4 != null_ptr) - { - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr2); - } - } - - return SCP_RESULT_TRUE; + return SCP_RESULT_TRUE; } -extern "C" scp_result sys_gen_for_variables(sc_memory_context *context, scp_operand *param1, scp_operand_pair *variables, sc_uint32 var_count, scp_operand_pair *parameters, sc_uint32 param_count, scp_operand *param4) +extern "C" scp_result sys_gen_for_variables( + sc_memory_context * context, + scp_operand * param1, + scp_operand_pair * variables, + sc_uint32 var_count, + scp_operand_pair * parameters, + sc_uint32 param_count, + scp_operand * param4) { - sc_type_result params; - sc_type_result result; - sc_addr_vector vars; - sc_uint i; - - for (i = 0; i < param_count; i++) - { - params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); - } - - for (i = 0; i < var_count; i++) - { - vars.push_back(variables[i].operand1->addr); - } - - system_sys_gen_for_variables(context, param1->addr, params, vars, &result); - - for (i = 0; i < var_count; i++) + sc_type_result params; + sc_type_result result; + sc_addr_vector vars; + sc_uint i; + + for (i = 0; i < param_count; i++) + { + params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + } + + for (i = 0; i < var_count; i++) + { + vars.push_back(variables[i].operand1->addr); + } + + system_sys_gen_for_variables(context, param1->addr, params, vars, &result); + + for (i = 0; i < var_count; i++) + { + scp_operand * op1 = variables[i].operand1; + scp_operand * op2 = variables[i].operand2; + find_result_pair_for_var(&result, op1->addr, &(op2->addr)); + if (param4 != null_ptr) { - scp_operand *op1 = variables[i].operand1; - scp_operand *op2 = variables[i].operand2; - find_result_pair_for_var(&result, op1->addr, &(op2->addr)); - if (param4 != null_ptr) - { - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, op2->addr); - } + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, op2->addr); } + } - return SCP_RESULT_TRUE; + return SCP_RESULT_TRUE; } diff --git a/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_search.cpp b/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_search.cpp index 5e9d397b2..ace1ecd96 100644 --- a/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_search.cpp +++ b/sc-kpm/scp/scp_lib/scp_system_operators/scp_sys_search.cpp @@ -21,152 +21,167 @@ along with OSTIS. If not, see . */ #include "sc_system_search.h" + #include extern "C" { #include "sc_memory_headers.h" -#include "scp_sys_search.h" #include "../scp_types.h" + +#include "scp_sys_search.h" } -extern "C" scp_result sys_search_for_variables(sc_memory_context *context, scp_operand *param1, scp_operand_pair *variables, sc_uint32 var_count, scp_operand_pair *parameters, sc_uint32 param_count, scp_operand *param4) +extern "C" scp_result sys_search_for_variables( + sc_memory_context * context, + scp_operand * param1, + scp_operand_pair * variables, + sc_uint32 var_count, + scp_operand_pair * parameters, + sc_uint32 param_count, + scp_operand * param4) { - sc_type_result params; - sc_addr addr1; - sc_addr_vector vars; - sc_type_result_vector result; - sc_uint i, j; - scp_result res = SCP_RESULT_FALSE; - GHashTable *table; + sc_type_result params; + sc_addr addr1; + sc_addr_vector vars; + sc_type_result_vector result; + sc_uint i, j; + scp_result res = SCP_RESULT_FALSE; + GHashTable * table; - for (i = 0; i < param_count; i++) - { - params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); - } - for (i = 0; i < var_count; i++) - { - vars.push_back(variables[i].operand1->addr); - } + for (i = 0; i < param_count; i++) + { + params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + } + for (i = 0; i < var_count; i++) + { + vars.push_back(variables[i].operand1->addr); + } - if (SC_RESULT_OK != system_sys_search_for_variables(context, param1->addr, params, vars, &result)) - { - return SCP_RESULT_ERROR; - } - if (result.size() > 0) + if (SC_RESULT_OK != system_sys_search_for_variables(context, param1->addr, params, vars, &result)) + { + return SCP_RESULT_ERROR; + } + if (result.size() > 0) + { + res = SCP_RESULT_TRUE; + } + else + { + return SCP_RESULT_FALSE; + } + for (i = 0; i < var_count; i++) + { + scp_operand * op1 = variables[i].operand1; + scp_operand * op2 = variables[i].operand2; + if (op2->set == SCP_TRUE) { - res = SCP_RESULT_TRUE; + for (j = 0; j < result.size(); j++) + { + find_result_pair_for_var(result[j], op1->addr, &addr1); + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, op2->addr, addr1); + } } else { - return SCP_RESULT_FALSE; + find_result_pair_for_var(result[i], op1->addr, &(op2->addr)); } - for (i = 0; i < var_count; i++) - { - scp_operand *op1 = variables[i].operand1; - scp_operand *op2 = variables[i].operand2; - if (op2->set == SCP_TRUE) - { - for (j = 0; j < result.size(); j++) - { - find_result_pair_for_var(result[j], op1->addr, &addr1); - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, op2->addr, addr1); - } - } - else - { - find_result_pair_for_var(result[i], op1->addr, &(op2->addr)); - } - } - if (param4 != null_ptr) + } + if (param4 != null_ptr) + { + table = g_hash_table_new(NULL, NULL); + sc_type_result::iterator it; + for (i = 0; i < result.size(); i++) { - table = g_hash_table_new(NULL, NULL); - sc_type_result::iterator it; - for (i = 0; i < result.size(); i++) + for (it = result[i]->begin(); it != result[i]->end(); it++) + { + addr1 = (*it).second; + if (FALSE == g_hash_table_contains(table, MAKE_SC_ADDR_HASH(addr1))) { - for (it = result[i]->begin() ; it != result[i]->end(); it++) - { - addr1 = (*it).second; - if (FALSE == g_hash_table_contains(table, MAKE_SC_ADDR_HASH(addr1))) - { - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr1); - g_hash_table_add(table, MAKE_SC_ADDR_HASH(addr1)); - } - } + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr1); + g_hash_table_add(table, MAKE_SC_ADDR_HASH(addr1)); } - g_hash_table_destroy(table); + } } - free_result_vector(&result); - return res; + g_hash_table_destroy(table); + } + free_result_vector(&result); + return res; } -extern "C" scp_result sys_search(sc_memory_context *context, scp_operand *param1, scp_operand *param2, scp_operand_pair *parameters, sc_uint32 param_count, scp_operand *param4, scp_bool full_only) +extern "C" scp_result sys_search( + sc_memory_context * context, + scp_operand * param1, + scp_operand * param2, + scp_operand_pair * parameters, + sc_uint32 param_count, + scp_operand * param4, + scp_bool full_only) { - sc_type_result params; - sc_addr curr_result_node, addr1, addr2, arc; - sc_type_result_vector result; - sc_type_result::iterator it; - sc_uint i; - scp_result res = SCP_RESULT_FALSE; - GHashTable *table; + sc_type_result params; + sc_addr curr_result_node, addr1, addr2, arc; + sc_type_result_vector result; + sc_type_result::iterator it; + sc_uint i; + scp_result res = SCP_RESULT_FALSE; + GHashTable * table; - for (i = 0; i < param_count; i++) + for (i = 0; i < param_count; i++) + { + params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + } + if (SCP_TRUE == full_only) + { + if (SC_RESULT_OK != system_sys_search_only_full(context, param1->addr, params, &result)) { - params.insert(sc_addr_pair(parameters[i].operand1->addr, parameters[i].operand2->addr)); + return SCP_RESULT_ERROR; } - if (SCP_TRUE == full_only) + } + else + { + if (SC_RESULT_OK != system_sys_search(context, param1->addr, params, &result)) { - if (SC_RESULT_OK != system_sys_search_only_full(context, param1->addr, params, &result)) - { - return SCP_RESULT_ERROR; - } - } - else - { - if (SC_RESULT_OK != system_sys_search(context, param1->addr, params, &result)) - { - return SCP_RESULT_ERROR; - } - } - if (result.size() > 0) - { - res = SCP_RESULT_TRUE; - } - else - { - free_result_vector(&result); - return SCP_RESULT_FALSE; + return SCP_RESULT_ERROR; } - if (param4 != null_ptr) - { - table = g_hash_table_new(NULL, NULL); - } - for (i = 0; i < result.size(); i++) + } + if (result.size() > 0) + { + res = SCP_RESULT_TRUE; + } + else + { + free_result_vector(&result); + return SCP_RESULT_FALSE; + } + if (param4 != null_ptr) + { + table = g_hash_table_new(NULL, NULL); + } + for (i = 0; i < result.size(); i++) + { + curr_result_node = sc_memory_node_new(context, sc_type_const); + for (it = result[i]->begin(); it != result[i]->end(); it++) { - curr_result_node = sc_memory_node_new(context, sc_type_const); - for (it = result[i]->begin() ; it != result[i]->end(); it++) + addr1 = (*it).first; + addr2 = (*it).second; + arc = sc_memory_arc_new(context, sc_type_arc_common | sc_type_const, addr1, addr2); + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, curr_result_node, arc); + if (param4 != null_ptr) + { + if (FALSE == g_hash_table_contains(table, MAKE_SC_ADDR_HASH(addr2))) { - addr1 = (*it).first; - addr2 = (*it).second; - arc = sc_memory_arc_new(context, sc_type_arc_common | sc_type_const, addr1, addr2); - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, curr_result_node, arc); - if (param4 != null_ptr) - { - if (FALSE == g_hash_table_contains(table, MAKE_SC_ADDR_HASH(addr2))) - { - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr2); - g_hash_table_add(table, MAKE_SC_ADDR_HASH(addr2)); - } - - } + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param4->addr, addr2); + g_hash_table_add(table, MAKE_SC_ADDR_HASH(addr2)); } - sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param2->addr, curr_result_node); - } - free_result_vector(&result); - if (param4 != null_ptr) - { - g_hash_table_destroy(table); + } } - return res; + sc_memory_arc_new(context, sc_type_arc_pos_const_perm, param2->addr, curr_result_node); + } + free_result_vector(&result); + if (param4 != null_ptr) + { + g_hash_table_destroy(table); + } + return res; } diff --git a/sc-memory/sc-core/sc-store/sc_fm_engine.cpp b/sc-memory/sc-core/sc-store/sc_fm_engine.cpp index 6812e7989..a230081c5 100644 --- a/sc-memory/sc-core/sc-store/sc_fm_engine.cpp +++ b/sc-memory/sc-core/sc-store/sc_fm_engine.cpp @@ -7,6 +7,7 @@ extern "C" { #include "sc_fm_engine.h" + #include "sc_stream_memory.h" } @@ -30,14 +31,13 @@ using MutexGuard = std::lock_guard; namespace { - bool CreateDBInstance() { rocksdb::Options options; options.create_if_missing = true; -// options.error_if_exists = true; + // options.error_if_exists = true; -// _sc_fm_remove_dir(gInstancePath.c_str()); + // _sc_fm_remove_dir(gInstancePath.c_str()); _sc_fs_mkdirs(gInstancePath.c_str()); rocksdb::Status status = rocksdb::DB::Open(options, gInstancePath, &gDBInstance); if (!status.ok()) @@ -50,7 +50,7 @@ void DestroyDBInstance() { assert(gDBInstance); gDBInstance->SyncWAL(); -// gDBInstance->Close(); + // gDBInstance->Close(); delete gDBInstance; gDBInstance = nullptr; @@ -77,8 +77,7 @@ std::string DataToStringBuffer(AddrsVector const & addrs) uint8_t const * pSize = (uint8_t const *)(&size); uint8_t const * pData = (uint8_t const *)(addrs.data()); - return std::string(pSize, pSize + sizeof(size)) + - std::string(pData, pData + sizeof(sc_addr) * size); + return std::string(pSize, pSize + sizeof(size)) + std::string(pData, pData + sizeof(sc_addr) * size); } AddrsVector StringBufferToData(std::string const & data) @@ -97,12 +96,12 @@ AddrsVector StringBufferToData(std::string const & data) #define SC_RES(expr) (expr) ? SC_RESULT_OK : SC_RESULT_ERROR; -} +} // namespace sc_result sc_fm_init(const sc_char * repo_path) { MutexGuard lock(gMutex); - gInstancePath = std::string (repo_path) + "/file_memory"; + gInstancePath = std::string(repo_path) + "/file_memory"; return SC_RES(CreateDBInstance()); } @@ -124,7 +123,7 @@ sc_stream * sc_fm_read_stream_new(const sc_check_sum * check_sum) if (status.ok()) { - sc_char * data = (sc_char*)malloc(value.size()); + sc_char * data = (sc_char *)malloc(value.size()); if (data == nullptr) return nullptr; @@ -148,8 +147,7 @@ sc_result sc_fm_write_stream(const sc_check_sum * check_sum, const sc_stream * s if (res != SC_RESULT_OK) return SC_RESULT_ERROR_IO; - - + sc_char buffer[1024]; std::string data; @@ -164,20 +162,20 @@ sc_result sc_fm_write_stream(const sc_check_sum * check_sum, const sc_stream * s assert(gDBInstance); rocksdb::WriteOptions options; -// options.sync = true; + // options.sync = true; rocksdb::Status status = gDBInstance->Put(options, MakeContentKey(check_sum), data); return SC_RES(status.ok()); } -sc_result sc_fm_addr_ref_append(sc_addr addr, const sc_check_sum *check_sum) +sc_result sc_fm_addr_ref_append(sc_addr addr, const sc_check_sum * check_sum) { MutexGuard lock(gMutex); assert(gDBInstance); std::string const key = MakeAddrsKey(check_sum); - std::string value; + std::string value; rocksdb::ReadOptions readOptions; rocksdb::Status status = gDBInstance->Get(readOptions, key, &value); @@ -195,14 +193,14 @@ sc_result sc_fm_addr_ref_append(sc_addr addr, const sc_check_sum *check_sum) return SC_RES(status.ok()); } -sc_result sc_fm_addr_ref_remove(sc_addr addr, const sc_check_sum *check_sum) +sc_result sc_fm_addr_ref_remove(sc_addr addr, const sc_check_sum * check_sum) { MutexGuard lock(gMutex); assert(gDBInstance); std::string const key = MakeAddrsKey(check_sum); - std::string value; + std::string value; rocksdb::ReadOptions readOptions; rocksdb::Status status = gDBInstance->Get(readOptions, key, &value); @@ -235,14 +233,14 @@ sc_result sc_fm_addr_ref_remove(sc_addr addr, const sc_check_sum *check_sum) return SC_RES(status.ok()); } -sc_result sc_fm_find(const sc_check_sum *check_sum, sc_addr **result, sc_uint32 *result_count) +sc_result sc_fm_find(const sc_check_sum * check_sum, sc_addr ** result, sc_uint32 * result_count) { MutexGuard lock(gMutex); assert(gDBInstance); - + std::string const key = MakeAddrsKey(check_sum); - std::string value; + std::string value; rocksdb::ReadOptions readOptions; rocksdb::Status status = gDBInstance->Get(readOptions, key, &value); @@ -255,7 +253,7 @@ sc_result sc_fm_find(const sc_check_sum *check_sum, sc_addr **result, sc_uint32 *result_count = sc_uint32(addrs.size()); size_t const resultBytes = sizeof(sc_addr) * addrs.size(); - *result = (sc_addr*)malloc(resultBytes); + *result = (sc_addr *)malloc(resultBytes); memcpy(*result, addrs.data(), resultBytes); return SC_RESULT_OK; @@ -281,7 +279,7 @@ sc_result sc_fm_save() assert(gDBInstance); rocksdb::FlushOptions options; options.wait = true; - + rocksdb::Status status = gDBInstance->Flush(options); return SC_RES(status.ok()); } diff --git a/sc-memory/sc-memory/http/sc_http_request.cpp b/sc-memory/sc-memory/http/sc_http_request.cpp index 765176399..4468eb960 100644 --- a/sc-memory/sc-memory/http/sc_http_request.cpp +++ b/sc-memory/sc-memory/http/sc_http_request.cpp @@ -6,8 +6,7 @@ namespace { - -size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmemb, std::string * s) +size_t CurlWrite_CallbackFunc_StdString(void * contents, size_t size, size_t nmemb, std::string * s) { size_t newLength = size * nmemb; size_t oldLength = s->size(); @@ -17,35 +16,34 @@ size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmem } catch (std::bad_alloc &) { - //handle memory problem + // handle memory problem return 0; } - std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength); + std::copy((char *)contents, (char *)contents + newLength, s->begin() + oldLength); return size * nmemb; } -} // namespace - +} // namespace ScHttpRequest::ScHttpRequest(std::string const & url) : m_handle(nullptr) , m_type(Type::GET) { - m_handle = (void*)curl_easy_init(); + m_handle = (void *)curl_easy_init(); if (!url.empty()) SetURL(url); } ScHttpRequest::~ScHttpRequest() { - curl_easy_cleanup((CURL*)m_handle); + curl_easy_cleanup((CURL *)m_handle); } void ScHttpRequest::Perform() { - CURL * curl = (CURL*)m_handle; - + CURL * curl = (CURL *)m_handle; + if (m_type == Type::POST) { curl_easy_setopt(curl, CURLOPT_POST, 1L); @@ -78,7 +76,7 @@ void ScHttpRequest::Perform() void ScHttpRequest::SetURL(std::string const & url) { - CURLcode const r = curl_easy_setopt((CURL*)m_handle, CURLOPT_URL, url.c_str()); + CURLcode const r = curl_easy_setopt((CURL *)m_handle, CURLOPT_URL, url.c_str()); SC_ASSERT(r == CURLE_OK, ()); } diff --git a/sc-memory/sc-memory/http/sc_http_request.hpp b/sc-memory/sc-memory/http/sc_http_request.hpp index bd21a95d6..8431126c3 100644 --- a/sc-memory/sc-memory/http/sc_http_request.hpp +++ b/sc-memory/sc-memory/http/sc_http_request.hpp @@ -1,15 +1,15 @@ #pragma once -#include "../sc_defines.hpp" #include "sc_http_response.hpp" +#include "../sc_defines.hpp" + #include #include -class ScHttpRequest +class ScHttpRequest { public: - enum class Type : uint8_t { GET, diff --git a/sc-memory/sc-memory/http/sc_http_response.hpp b/sc-memory/sc-memory/http/sc_http_response.hpp index 93b347524..fcac24ece 100644 --- a/sc-memory/sc-memory/http/sc_http_response.hpp +++ b/sc-memory/sc-memory/http/sc_http_response.hpp @@ -16,7 +16,7 @@ class ScHttpResponse public: _SC_EXTERN std::string const & GetData() const; _SC_EXTERN std::string GetResultCodeString() const; - + _SC_EXTERN bool IsSuccess() const; private: diff --git a/sc-memory/sc-memory/kpm/sc_agent.cpp b/sc-memory/sc-memory/kpm/sc_agent.cpp index ce295ee4f..7c9725694 100644 --- a/sc-memory/sc-memory/kpm/sc_agent.cpp +++ b/sc-memory/sc-memory/kpm/sc_agent.cpp @@ -1,18 +1,16 @@ #include "sc_agent.hpp" #include "../sc_debug.hpp" -#include "../sc_wait.hpp" - #include "../sc_template_builder.hpp" #include "../sc_template_search.hpp" +#include "../sc_wait.hpp" namespace { - bool gInitializeResult = false; bool gIsInitialized = false; -} // namespace +} // namespace bool ScAgentInit(bool force /* = false */) { @@ -25,7 +23,6 @@ bool ScAgentInit(bool force /* = false */) return gInitializeResult; } - ScAgent::ScAgent(char const * name, sc_uint8 accessLvl) : m_memoryCtx(accessLvl, name) { @@ -35,7 +32,6 @@ ScAgent::~ScAgent() { } - // --------------------------- ScAgentAction::ScAgentAction(ScAddr const & cmdClassAddr, char const * name, sc_uint8 accessLvl) : ScAgent(name, accessLvl) @@ -58,7 +54,8 @@ sc_result ScAgentAction::Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, if (m_memoryCtx.HelperCheckEdge(m_cmdClassAddr, cmdAddr, ScType::EdgeAccessConstPosPerm)) { m_memoryCtx.EraseElement(edgeAddr); - ScAddr progressAddr = m_memoryCtx.CreateEdge(ScType::EdgeAccessConstPosTemp, ScKeynodes::kCommandProgressdAddr, cmdAddr); + ScAddr progressAddr = + m_memoryCtx.CreateEdge(ScType::EdgeAccessConstPosTemp, ScKeynodes::kCommandProgressdAddr, cmdAddr); assert(progressAddr.IsValid()); ScAddr resultAddr = m_memoryCtx.CreateNode(ScType::NodeConstStruct); assert(resultAddr.IsValid()); @@ -82,11 +79,8 @@ sc_result ScAgentAction::Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr ScAgentAction::GetParam(ScAddr const & cmdAddr, ScAddr const & relationAddr, ScType const & paramType) const { - ScIterator5Ptr iter = m_memoryCtx.Iterator5(cmdAddr, - ScType::EdgeAccessConstPosPerm, - paramType, - ScType::EdgeAccessConstPosPerm, - relationAddr); + ScIterator5Ptr iter = m_memoryCtx.Iterator5( + cmdAddr, ScType::EdgeAccessConstPosPerm, paramType, ScType::EdgeAccessConstPosPerm, relationAddr); if (!iter->Next()) return ScAddr(); @@ -117,7 +111,9 @@ ScAddr const & ScAgentAction::GetNrelResultAddr() ScAddr ScAgentAction::CreateCommand(ScMemoryContext & ctx, ScAddr const & cmdClassAddr, ScAddrVector const & params) { if (params.size() >= ScKeynodes::GetRrelIndexNum()) - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "You should use <= " + std::to_string(ScKeynodes::GetRrelIndexNum()) + " params"); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, + "You should use <= " + std::to_string(ScKeynodes::GetRrelIndexNum()) + " params"); SC_ASSERT(cmdClassAddr.IsValid(), ()); @@ -149,24 +145,28 @@ bool ScAgentAction::InitiateCommand(ScMemoryContext & ctx, ScAddr const & cmdAdd return ctx.CreateEdge(ScType::EdgeAccessConstPosTemp, ScKeynodes::kCommandInitiatedAddr, cmdAddr).IsValid(); } -bool ScAgentAction::InitiateCommandWait(ScMemoryContext & ctx, ScAddr const & cmdAddr, uint32_t waitTimeOutMS/* = 5000 */) +bool ScAgentAction::InitiateCommandWait( + ScMemoryContext & ctx, + ScAddr const & cmdAddr, + uint32_t waitTimeOutMS /* = 5000 */) { ScWaitActionFinished waiter(ctx, cmdAddr); - waiter.SetOnWaitStartDelegate([&]() - { - ScAgentAction::InitiateCommand(ctx, cmdAddr); - }); + waiter.SetOnWaitStartDelegate( + [&]() + { + ScAgentAction::InitiateCommand(ctx, cmdAddr); + }); return waiter.Wait(waitTimeOutMS); } ScAddr ScAgentAction::GetCommandResultAddr(ScMemoryContext & ctx, ScAddr const & cmdAddr) { ScIterator5Ptr it = ctx.Iterator5( - cmdAddr, - ScType::EdgeDCommonConst, - ScType::NodeConstStruct, - ScType::EdgeAccessConstPosPerm, - ScKeynodes::kNrelResult); + cmdAddr, + ScType::EdgeDCommonConst, + ScType::NodeConstStruct, + ScType::EdgeAccessConstPosPerm, + ScKeynodes::kNrelResult); if (it->Next()) return it->Get(2); @@ -186,16 +186,11 @@ ScAddr ScAgentAction::GetCommandResultCodeAddr(ScMemoryContext & ctx, ScAddr con if (!resultAddr.IsValid()) return ScAddr(); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - ScKeynodes::kScResult, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarClass >> "result_class") - .Triple( - "result_class", - ScType::EdgeAccessVarPosPerm, - resultAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple(ScKeynodes::kScResult, ScType::EdgeAccessVarPosPerm, ScType::NodeVarClass >> "result_class") + .Triple("result_class", ScType::EdgeAccessVarPosPerm, resultAddr) + .Make(); ScTemplateSearch search(ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -209,10 +204,7 @@ ScAddr ScAgentAction::GetCommandResultCodeAddr(ScMemoryContext & ctx, ScAddr con ScAgentAction::State ScAgentAction::GetCommandState(ScMemoryContext & ctx, ScAddr const & cmdAddr) { - ScIterator3Ptr it = ctx.Iterator3( - ScType::NodeConstClass, - ScType::EdgeAccessConstPosTemp, - cmdAddr); + ScIterator3Ptr it = ctx.Iterator3(ScType::NodeConstClass, ScType::EdgeAccessConstPosTemp, cmdAddr); ScAddr stateAddr; while (it->Next()) diff --git a/sc-memory/sc-memory/kpm/sc_agent.hpp b/sc-memory/sc-memory/kpm/sc_agent.hpp index 7deacd540..f3d3fb3f9 100644 --- a/sc-memory/sc-memory/kpm/sc_agent.hpp +++ b/sc-memory/sc-memory/kpm/sc_agent.hpp @@ -1,20 +1,18 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once -#include "../sc_object.hpp" -#include "../sc_memory.hpp" #include "../sc_keynodes.hpp" - +#include "../sc_memory.hpp" +#include "../sc_object.hpp" #include "../utils/sc_log.hpp" #include "../generated/sc_agent.generated.hpp" - /* Call this function before agent module usage. * If module initialized, then returns true; otherwise returns false */ @@ -44,7 +42,6 @@ class ScAgentAction : public ScAgent SC_GENERATED_BODY() public: - enum class State : uint8_t { Unknown = 0, @@ -53,11 +50,15 @@ class ScAgentAction : public ScAgent Finished }; - _SC_EXTERN explicit ScAgentAction(ScAddr const & cmdClassAddr, char const * name, sc_uint8 accessLvl = sc_access_lvl_make_max); + _SC_EXTERN explicit ScAgentAction( + ScAddr const & cmdClassAddr, + char const * name, + sc_uint8 accessLvl = sc_access_lvl_make_max); _SC_EXTERN virtual ~ScAgentAction(); protected: - _SC_EXTERN virtual sc_result Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) override; + _SC_EXTERN virtual sc_result Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) + override; _SC_EXTERN ScAddr GetParam(ScAddr const & cmdAddr, ScAddr const & relationAddr, ScType const & paramType) const; /* This funtion returns parameter by index. It's equal to call @@ -80,7 +81,8 @@ class ScAgentAction : public ScAgent * Returns ScAddr of created command instance. If addr is not valid, then * command doesn't created */ - static _SC_EXTERN ScAddr CreateCommand(ScMemoryContext & ctx, ScAddr const & cmdClassAddr, ScAddrVector const & params); + static _SC_EXTERN ScAddr + CreateCommand(ScMemoryContext & ctx, ScAddr const & cmdClassAddr, ScAddrVector const & params); /* Init specified command. * cmdAddr - ScAddr of command instance @@ -93,7 +95,10 @@ class ScAgentAction : public ScAgent * waitTimeOutMS - timeout for a waiting (milliseconds) * Returns true, if command initiated and finished; otherwise returns false (wait timeout) */ - static _SC_EXTERN bool InitiateCommandWait(ScMemoryContext & ctx, ScAddr const & cmdAddr, uint32_t waitTimeOutMS = 5000); + static _SC_EXTERN bool InitiateCommandWait( + ScMemoryContext & ctx, + ScAddr const & cmdAddr, + uint32_t waitTimeOutMS = 5000); /* Returns ScAddr of result structure of specified command */ @@ -120,24 +125,22 @@ class ScAgentAction : public ScAgent static _SC_EXTERN bool IsCommandFishined(ScMemoryContext & ctx, ScAddr const & cmdAddr); /* Reutrns true, if specified command included into set of initiated commands - */ + */ static _SC_EXTERN bool IsCommandInitiated(ScMemoryContext & ctx, ScAddr const & cmdAddr); /* Reutrns true, if specified command included into set of in-progress commands - */ + */ static _SC_EXTERN bool IsCommandInProgress(ScMemoryContext & ctx, ScAddr const & cmdAddr); private: ScAddr m_cmdClassAddr; private: - }; #define AGENT_NAME_TYPE(__Name__) __Name__##Type #define AGENT_NAME_CLASS(__Name__) __Name__##_Agent -#define AGENT_NAME_INST(__Name__) __Name__/*##(__LINE__)##(__FILE__)*/ - +#define AGENT_NAME_INST(__Name__) __Name__ /*##(__LINE__)##(__FILE__)*/ #define SC_AGENT_IMPLEMENTATION(__AgentName__) \ SC_COMBINE(ScFileID, _, __AgentName__, _impl) \ @@ -147,10 +150,8 @@ class ScAgentAction : public ScAgent SC_COMBINE(ScFileID, _, __AgentName__, _impl) \ sc_result __AgentName__::RunImpl(ScAddr const & requestAddr, ScAddr const & resultAddr) - - #define SC_AGENT_REGISTER(__AgentName__) \ SC_OBJECT_INIT_GLOBAL_CALL(__AgentName__) \ __AgentName__::RegisterHandler(); -#define SC_AGENT_UNREGISTER(__AgentName__) __AgentName__::UnregisterHandler(); +#define SC_AGENT_UNREGISTER(__AgentName__) __AgentName__::UnregisterHandler(); diff --git a/sc-memory/sc-memory/sc_addr.cpp b/sc-memory/sc-memory/sc_addr.cpp index cb91e8033..db30c73ae 100644 --- a/sc-memory/sc-memory/sc_addr.cpp +++ b/sc-memory/sc-memory/sc_addr.cpp @@ -44,17 +44,17 @@ ScAddr::HashType ScAddr::Hash() const return ((m_realAddr.seg << 16) | m_realAddr.offset); } -bool ScAddr::operator == (ScAddr const & other) const +bool ScAddr::operator==(ScAddr const & other) const { return SC_ADDR_IS_EQUAL(m_realAddr, other.m_realAddr); } -bool ScAddr::operator != (ScAddr const & other) const +bool ScAddr::operator!=(ScAddr const & other) const { return SC_ADDR_IS_NOT_EQUAL(m_realAddr, other.m_realAddr); } -ScRealAddr const & ScAddr::operator * () const +ScRealAddr const & ScAddr::operator*() const { return m_realAddr; } diff --git a/sc-memory/sc-memory/sc_addr.hpp b/sc-memory/sc-memory/sc_addr.hpp index 594e08247..23953e935 100644 --- a/sc-memory/sc-memory/sc_addr.hpp +++ b/sc-memory/sc-memory/sc_addr.hpp @@ -22,8 +22,10 @@ class _SC_EXTERN ScAddr { friend class ScMemoryContext; - template friend class TIterator3; - template friend class TIterator5; + template + friend class TIterator3; + template + friend class TIterator5; public: using HashType = uint64_t; @@ -36,13 +38,13 @@ class _SC_EXTERN ScAddr bool IsValid() const; //! Bool operator wraps IsValid method - explicit operator bool () const; + explicit operator bool() const; void Reset(); - bool operator == (ScAddr const & other) const; - bool operator != (ScAddr const & other) const; - ScRealAddr const & operator * () const; + bool operator==(ScAddr const & other) const; + bool operator!=(ScAddr const & other) const; + ScRealAddr const & operator*() const; HashType Hash() const; std::string ToString() const; @@ -55,7 +57,7 @@ using ScAddrVector = std::vector; struct RealAddrLessFunc { - bool operator () (ScRealAddr const & a, ScRealAddr const & b) const + bool operator()(ScRealAddr const & a, ScRealAddr const & b) const { if (a.seg < b.seg) return true; @@ -69,7 +71,7 @@ struct RealAddrLessFunc struct ScAddLessFunc { - bool operator () (ScAddr const & a, ScAddr const & b) const + bool operator()(ScAddr const & a, ScAddr const & b) const { return RealAddrLessFunc()(*a, *b); } @@ -79,20 +81,22 @@ struct ScAddLessFunc template struct ScAddrHashFunc { - HashType operator () (ScAddr const & addr); + HashType operator()(ScAddr const & addr); }; -template <> struct ScAddrHashFunc < uint32_t > +template <> +struct ScAddrHashFunc { - uint32_t operator() (ScAddr const & addr) const + uint32_t operator()(ScAddr const & addr) const { return SC_ADDR_LOCAL_TO_INT(*addr); } }; -template <> struct ScAddrHashFunc < uint64_t > +template <> +struct ScAddrHashFunc { - uint64_t operator() (ScAddr const & addr) const + uint64_t operator()(ScAddr const & addr) const { return addr.Hash(); } diff --git a/sc-memory/sc-memory/sc_common_templ.cpp b/sc-memory/sc-memory/sc_common_templ.cpp index 191e5f1ba..6fb4b6166 100644 --- a/sc-memory/sc-memory/sc_common_templ.cpp +++ b/sc-memory/sc-memory/sc_common_templ.cpp @@ -2,17 +2,13 @@ namespace sc { - ScAddr ResolveRelationTuple(ScMemoryContext & ctx, ScAddr const & elAddr, ScAddr const & relAddr) { - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::NodeVarTuple >> "_tuple", - ScType::EdgeDCommonVar, - elAddr, - ScType::EdgeAccessVarPosPerm, - relAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + ScType::NodeVarTuple >> "_tuple", ScType::EdgeDCommonVar, elAddr, ScType::EdgeAccessVarPosPerm, relAddr) + .Make(); ScTemplateSearch search(ctx, *templ); ScTemplateSearch::Iterator it = search.begin(); @@ -27,11 +23,10 @@ ScAddr ResolveRelationTuple(ScMemoryContext & ctx, ScAddr const & elAddr, ScAddr ScTemplateGenerate::Result const generated = generator.Do(); if (!generated) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, - "Can't create tuple"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't create tuple"); } return (*generated)["_tuple"]; } -} // namespace sc +} // namespace sc diff --git a/sc-memory/sc-memory/sc_common_templ.hpp b/sc-memory/sc-memory/sc_common_templ.hpp index 37b8119b6..e8ea5680b 100644 --- a/sc-memory/sc-memory/sc_common_templ.hpp +++ b/sc-memory/sc-memory/sc_common_templ.hpp @@ -9,7 +9,6 @@ namespace sc { - /* Create construction: * elAddr <= relAddr: {};; * If construction exist, then returns exist tuple addr; otherwise create new one. @@ -25,14 +24,11 @@ _SC_EXTERN ScAddr ResolveRelationTuple(ScMemoryContext & ctx, ScAddr const & elA template ScAddr SetRelationValue(ScMemoryContext & ctx, ScAddr const & elAddr, ScAddr const & relAddr, ValueType const & value) { - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - elAddr, - ScType::EdgeDCommonVar, - ScType::LinkVar >> "_link", - ScType::EdgeAccessVarPosPerm, - relAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + elAddr, ScType::EdgeDCommonVar, ScType::LinkVar >> "_link", ScType::EdgeAccessVarPosPerm, relAddr) + .Make(); ScAddr linkAddr; ScTemplateSearch search(ctx, *templ); @@ -49,8 +45,7 @@ ScAddr SetRelationValue(ScMemoryContext & ctx, ScAddr const & elAddr, ScAddr con if (!linkAddr.IsValid()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, - "Can't create value relation"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't create value relation"); } } @@ -60,4 +55,4 @@ ScAddr SetRelationValue(ScMemoryContext & ctx, ScAddr const & elAddr, ScAddr con return linkAddr; } -} // namespace sc +} // namespace sc diff --git a/sc-memory/sc-memory/sc_debug.cpp b/sc-memory/sc-memory/sc_debug.cpp index c6e29b992..75d0098b2 100644 --- a/sc-memory/sc-memory/sc_debug.cpp +++ b/sc-memory/sc-memory/sc_debug.cpp @@ -1,32 +1,31 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_debug.hpp" namespace utils { +ScException::ScException(std::string const & description, std::string const & msg) + : m_description(description) + , m_msg(msg) +{ +} - ScException::ScException(std::string const & description, std::string const & msg) - : m_description(description) - , m_msg(msg) - { - } - - ScException::~ScException() throw() - { - } +ScException::~ScException() throw() +{ +} - const char * ScException::Description() const throw() - { - return m_description.c_str(); - } +const char * ScException::Description() const throw() +{ + return m_description.c_str(); +} - const char * ScException::Message() const throw() - { - return m_msg.c_str(); - } +const char * ScException::Message() const throw() +{ + return m_msg.c_str(); +} -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/sc_debug.hpp b/sc-memory/sc-memory/sc_debug.hpp index 2d7dd24b9..ed2056576 100644 --- a/sc-memory/sc-memory/sc_debug.hpp +++ b/sc-memory/sc-memory/sc_debug.hpp @@ -1,18 +1,17 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once +#include "utils/sc_console.hpp" #include "utils/sc_log.hpp" #include "utils/sc_message.hpp" -#include "utils/sc_console.hpp" namespace utils { - /// ----------------------- class ScException : public std::exception @@ -32,158 +31,218 @@ class ScException : public std::exception class ExceptionAssert final : public ScException { public: - ExceptionAssert(std::string const & description, std::string const & msg) : ScException("Assert: " + description, msg) {} + ExceptionAssert(std::string const & description, std::string const & msg) + : ScException("Assert: " + description, msg) + { + } }; class ExceptionCritical final : public ScException { public: - ExceptionCritical(std::string const & description, std::string const & msg) : ScException("Critical: " + description, msg) {} + ExceptionCritical(std::string const & description, std::string const & msg) + : ScException("Critical: " + description, msg) + { + } }; class ExceptionInvalidParams final : public ScException { public: - ExceptionInvalidParams(std::string const & description, std::string const & msg) : ScException("InvalidParams: " + description, msg) {} + ExceptionInvalidParams(std::string const & description, std::string const & msg) + : ScException("InvalidParams: " + description, msg) + { + } }; class ExceptionInvalidState final : public ScException { public: - ExceptionInvalidState(std::string const & description, std::string const & msg) : ScException("InvalidState: " + description, msg) {} + ExceptionInvalidState(std::string const & description, std::string const & msg) + : ScException("InvalidState: " + description, msg) + { + } }; class ExceptionItemNotFound final : public ScException { public: - ExceptionItemNotFound(std::string const & description, std::string const & msg) : ScException("ItemNotFound: " + description, msg) {} + ExceptionItemNotFound(std::string const & description, std::string const & msg) + : ScException("ItemNotFound: " + description, msg) + { + } }; class ExceptionParseError final : public ScException { public: - ExceptionParseError(std::string const & description, std::string const & msg) : ScException("ParseError: " + description, msg) {} + ExceptionParseError(std::string const & description, std::string const & msg) + : ScException("ParseError: " + description, msg) + { + } }; class ExceptionNotImplemented final : public ScException { public: - ExceptionNotImplemented(std::string const & description, std::string const & msg) : ScException("NotImplemented: " + description, msg) {} + ExceptionNotImplemented(std::string const & description, std::string const & msg) + : ScException("NotImplemented: " + description, msg) + { + } }; class ExceptionInvalidType final : public ScException { public: - explicit ExceptionInvalidType(std::string const & description, std::string const & msg) : ScException("InvalidType: " + description, msg) {} + explicit ExceptionInvalidType(std::string const & description, std::string const & msg) + : ScException("InvalidType: " + description, msg) + { + } }; -#define error(__str) { throw ScException(__str); } -#define error_invalid_params(__str) { throw ScExceptionInvalidParams(__str); } - // Asserts #define THROW_EXCEPTION(_exception_class, _msg, _file, _line) \ -{ \ - std::stringstream _str_message; \ - _str_message << _msg; \ - std::string _msg_raw = _str_message.str(); \ - _str_message << std::endl << "File: " << _file << std::endl << "Line:" << _line << std::endl; \ - throw _exception_class(_str_message.str(), _msg_raw); \ -} + { \ + std::stringstream _str_message; \ + _str_message << _msg; \ + std::string _msg_raw = _str_message.str(); \ + _str_message << std::endl << "File: " << _file << std::endl << "Line:" << _line << std::endl; \ + throw _exception_class(_str_message.str(), _msg_raw); \ + } #define SC_THROW_EXCEPTION(_exception_class, _msg) THROW_EXCEPTION(_exception_class, _msg, __FILE__, __LINE__) #define SC_NOT_IMPLEMENTED(_msg) SC_THROW_EXCEPTION(utils::ExceptionNotImplemented, _msg) #define _ASSERT_IMPL(_expr, _msg, _file, _line) \ -{ \ - if (!(_expr)) \ -{ \ - std::string _message = ::utils::impl::Message("SC_ASSERT("#_expr")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, _file, _line); \ -} \ -} + { \ + if (!(_expr)) \ + { \ + std::string _message = ::utils::impl::Message("SC_ASSERT(" #_expr ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, _file, _line); \ + } \ + } #if SC_DEBUG_MODE -# define SC_ASSERT(_expr, _msg) { _ASSERT_IMPL( _expr, _msg, __FILE__, __LINE__ ); } +# define SC_ASSERT(_expr, _msg) \ + { \ + _ASSERT_IMPL(_expr, _msg, __FILE__, __LINE__); \ + } // will be removed use SC_ASSERT instead -# define ASSERT(_expr, _msg) { _ASSERT_IMPL(_expr, _msg, __FILE__, __LINE__); } +# define ASSERT(_expr, _msg) \ + { \ + _ASSERT_IMPL(_expr, _msg, __FILE__, __LINE__); \ + } #else -# define SC_ASSERT(_expr, _msg) ((void)0) +# define SC_ASSERT(_expr, _msg) ((void)0) // will be removed use SC_ASSERT instead -# define ASSERT(_expr, _msg) ((void)0) +# define ASSERT(_expr, _msg) ((void)0) #endif #define _CHECK_IMPL(_expr, _msg, _name) \ do \ -{ \ - if (_expr) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string(_name) + "("#_expr")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if (_expr) \ + { \ + } \ + else \ + { \ + std::string _message = ::utils::impl::Message(std::string(_name) + "(" #_expr ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK(_expr, _msg) _CHECK_IMPL(_expr, _msg, "CHECK") #define SC_CHECK_NOT(_expr, _msg) _CHECK_IMPL(!_expr, _msg, "CHECK_NOT") #define SC_CHECK_EQUAL(_a, _b, _msg) \ do \ -{ \ - if ((_a) == (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_EQUAL") + "("#_a" == "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if ((_a) == (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = \ + ::utils::impl::Message(std::string("SC_CHECK_EQUAL") + "(" #_a " == " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK_NOT_EQUAL(_a, _b, _msg) \ do \ -{ \ - if ((_a) != (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_NOT_EQUAL") + "("#_a" != "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if ((_a) != (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = ::utils::impl::Message( \ + std::string("SC_CHECK_NOT_EQUAL") + "(" #_a " != " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK_GREAT(_a, _b, _msg) \ do \ -{ \ - if ((_a) > (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_GREAT") + "("#_a" > "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if ((_a) > (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = \ + ::utils::impl::Message(std::string("SC_CHECK_GREAT") + "(" #_a " > " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK_GREAT_EQ(_a, _b, _msg) \ do \ -{ \ - if ((_a) >= (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_GREAT_EQ") + "("#_a" >= "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if ((_a) >= (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = ::utils::impl::Message( \ + std::string("SC_CHECK_GREAT_EQ") + "(" #_a " >= " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK_LESS(_a, _b, _msg) \ do \ -{ \ - if ((_a) < (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_LESS") + "("#_a" < "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime + { \ + if ((_a) < (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = \ + ::utils::impl::Message(std::string("SC_CHECK_LESS") + "(" #_a " < " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime #define SC_CHECK_LESS_EQ(_a, _b, _msg) \ do \ -{ \ - if ((_a) <= (_b)) {} else \ -{ \ - std::string _message = ::utils::impl::Message(std::string("SC_CHECK_LESS_EQ") + "("#_a" <= "#_b")", ::utils::impl::Message _msg); \ - THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ -} \ -} while (false); // stop runtime - - -} // namespace utils + { \ + if ((_a) <= (_b)) \ + { \ + } \ + else \ + { \ + std::string _message = ::utils::impl::Message( \ + std::string("SC_CHECK_LESS_EQ") + "(" #_a " <= " #_b ")", ::utils::impl::Message _msg); \ + THROW_EXCEPTION(::utils::ExceptionAssert, _message, __FILE__, __LINE__); \ + } \ + } \ + while (false); // stop runtime + +} // namespace utils diff --git a/sc-memory/sc-memory/sc_defines.hpp b/sc-memory/sc-memory/sc_defines.hpp index 37ebec3ed..f090e2840 100644 --- a/sc-memory/sc-memory/sc_defines.hpp +++ b/sc-memory/sc-memory/sc_defines.hpp @@ -12,38 +12,46 @@ #define SC_COMBINE(v1, v2, v3, v4) SC_COMBINE_INTERNAL(v1, v2, v3, v4) #ifdef __SC_REFLECTION_PARSER__ -#define SC_BODY_INTERNAL(...) __attribute__((annotate(#__VA_ARGS__))) void __null_body() {} -#define SC_CLASS_INTERNAL(...) __attribute__((annotate(#__VA_ARGS__))) void __null_meta() {} - -#define SC_CLASS(...) SC_CLASS_INTERNAL(__VA_ARGS__) -#define SC_GENERATED_BODY(...) SC_BODY_INTERNAL(GenBody()) -#define SC_PROPERTY(...) __attribute__((annotate(#__VA_ARGS__))) +# define SC_BODY_INTERNAL(...) \ + __attribute__((annotate(#__VA_ARGS__))) void __null_body() \ + { \ + } +# define SC_CLASS_INTERNAL(...) \ + __attribute__((annotate(#__VA_ARGS__))) void __null_meta() \ + { \ + } + +# define SC_CLASS(...) SC_CLASS_INTERNAL(__VA_ARGS__) +# define SC_GENERATED_BODY(...) SC_BODY_INTERNAL(GenBody()) +# define SC_PROPERTY(...) __attribute__((annotate(# __VA_ARGS__))) #else -#define SC_GENERATED_BODY_ITEMS(v) SC_COMBINE(ScFileID, _, __LINE__, v) -#define SC_GENERATED_BODY_INIT() \ +# define SC_GENERATED_BODY_ITEMS(v) SC_COMBINE(ScFileID, _, __LINE__, v) +# define SC_GENERATED_BODY_INIT() \ public: \ - static bool InitGlobal() { return _InitStaticInternal(); } \ + static bool InitGlobal() \ + { \ + return _InitStaticInternal(); \ + } \ +\ private: \ - SC_GENERATED_BODY_ITEMS(_init) \ - SC_GENERATED_BODY_ITEMS(_initStatic) \ - SC_GENERATED_BODY_ITEMS(_decl) - + SC_GENERATED_BODY_ITEMS(_init) \ + SC_GENERATED_BODY_ITEMS(_initStatic) \ + SC_GENERATED_BODY_ITEMS(_decl) -#define SC_CLASS(...) -#define SC_GENERATED_BODY(...) SC_GENERATED_BODY_INIT() -#define SC_PROPERTY(...) +# define SC_CLASS(...) +# define SC_GENERATED_BODY(...) SC_GENERATED_BODY_INIT() +# define SC_PROPERTY(...) -#define SC_OBJECT_INIT_GLOBAL_CALL(__class) __class::InitGlobal(); +# define SC_OBJECT_INIT_GLOBAL_CALL(__class) __class::InitGlobal(); // for autocompletion -#define Keynode(__X) -#define ForceCreate(__X) -#define CmdClass -#define Agent +# define Keynode(__X) +# define ForceCreate(__X) +# define CmdClass +# define Agent // utils -#define SC_UNUSED(__X) (void)__X - -#endif // __SC_REFLECTION_PARSER__ +# define SC_UNUSED(__X) (void)__X +#endif // __SC_REFLECTION_PARSER__ diff --git a/sc-memory/sc-memory/sc_event.cpp b/sc-memory/sc-memory/sc_event.cpp index acb629310..6bc0e7ef4 100644 --- a/sc-memory/sc-memory/sc_event.cpp +++ b/sc-memory/sc-memory/sc_event.cpp @@ -5,9 +5,10 @@ */ #include "sc_event.hpp" -#include "sc_utils.hpp" + #include "sc_addr.hpp" #include "sc_memory.hpp" +#include "sc_utils.hpp" #include "utils/sc_log.hpp" @@ -15,7 +16,6 @@ namespace { - sc_event_type ConvertEventType(ScEvent::Type type) { switch (type) @@ -39,17 +39,21 @@ sc_event_type ConvertEventType(ScEvent::Type type) return SC_EVENT_CONTENT_CHANGED; } - SC_THROW_EXCEPTION(utils::ExceptionNotImplemented, - "Unsupported event type " + std::to_string(int(type))); + SC_THROW_EXCEPTION(utils::ExceptionNotImplemented, "Unsupported event type " + std::to_string(int(type))); return SC_EVENT_UNKNOWN; } -} +} // namespace -ScEvent::ScEvent(const ScMemoryContext & ctx, const ScAddr & addr, Type eventType, ScEvent::DelegateFunc func /*= DelegateFunc()*/) +ScEvent::ScEvent( + const ScMemoryContext & ctx, + const ScAddr & addr, + Type eventType, + ScEvent::DelegateFunc func /*= DelegateFunc()*/) { m_delegate = func; - m_event = sc_event_new_ex(*ctx, *addr, ConvertEventType(eventType), (sc_pointer)this, &ScEvent::Handler, &ScEvent::HandlerDelete); + m_event = sc_event_new_ex( + *ctx, *addr, ConvertEventType(eventType), (sc_pointer)this, &ScEvent::Handler, &ScEvent::HandlerDelete); } ScEvent::~ScEvent() @@ -65,12 +69,13 @@ void ScEvent::RemoveDelegate() sc_result ScEvent::Handler(sc_event const * evt, sc_addr edge, sc_addr other_el) { - ScEvent * eventObj = (ScEvent*)sc_event_get_data(evt); + ScEvent * eventObj = (ScEvent *)sc_event_get_data(evt); SC_ASSERT(eventObj != nullptr, ()); if (eventObj->m_delegate) { - return eventObj->m_delegate(ScAddr(sc_event_get_element(evt)), ScAddr(edge), ScAddr(other_el)) ? SC_RESULT_OK : SC_RESULT_ERROR; + return eventObj->m_delegate(ScAddr(sc_event_get_element(evt)), ScAddr(edge), ScAddr(other_el)) ? SC_RESULT_OK + : SC_RESULT_ERROR; } return SC_RESULT_ERROR; @@ -78,7 +83,7 @@ sc_result ScEvent::Handler(sc_event const * evt, sc_addr edge, sc_addr other_el) sc_result ScEvent::HandlerDelete(sc_event const * evt) { - ScEvent * eventObj = (ScEvent*)sc_event_get_data(evt); + ScEvent * eventObj = (ScEvent *)sc_event_get_data(evt); SC_ASSERT(eventObj != nullptr, ()); utils::ScLockScope(eventObj->m_lock); diff --git a/sc-memory/sc-memory/sc_event.hpp b/sc-memory/sc-memory/sc_event.hpp index fd77e3d20..c7fb67fd3 100644 --- a/sc-memory/sc-memory/sc_event.hpp +++ b/sc-memory/sc-memory/sc_event.hpp @@ -30,7 +30,11 @@ class ScEvent ContentChanged }; - explicit _SC_EXTERN ScEvent(class ScMemoryContext const & ctx, const ScAddr & addr, Type eventType, DelegateFunc func = DelegateFunc()); + explicit _SC_EXTERN ScEvent( + class ScMemoryContext const & ctx, + const ScAddr & addr, + Type eventType, + DelegateFunc func = DelegateFunc()); virtual _SC_EXTERN ~ScEvent(); // Don't allow copying of events @@ -71,6 +75,7 @@ class ScEventAddOutputEdge final : public ScEvent class ScEventAddInputEdge final : public ScEvent { friend class ScMemoryContext; + public: _SC_EXTERN ScEventAddInputEdge(const ScMemoryContext & ctx, const ScAddr & addr, ScEvent::DelegateFunc func) : ScEvent(ctx, addr, ScEvent::Type::AddInputEdge, func) @@ -81,6 +86,7 @@ class ScEventAddInputEdge final : public ScEvent class ScEventRemoveOutputEdge final : public ScEvent { friend class ScMemoryContext; + public: _SC_EXTERN ScEventRemoveOutputEdge(const ScMemoryContext & ctx, const ScAddr & addr, ScEvent::DelegateFunc func) : ScEvent(ctx, addr, ScEvent::Type::RemoveOutputEdge, func) @@ -91,6 +97,7 @@ class ScEventRemoveOutputEdge final : public ScEvent class ScEventRemoveInputEdge final : public ScEvent { friend class ScMemoryContext; + public: _SC_EXTERN ScEventRemoveInputEdge(const ScMemoryContext & ctx, const ScAddr & addr, ScEvent::DelegateFunc func) : ScEvent(ctx, addr, ScEvent::Type::RemoveInputEdge, func) @@ -101,6 +108,7 @@ class ScEventRemoveInputEdge final : public ScEvent class ScEventEraseElement final : public ScEvent { friend class ScMemoryContext; + public: _SC_EXTERN ScEventEraseElement(const ScMemoryContext & ctx, const ScAddr & addr, ScEvent::DelegateFunc func) : ScEvent(ctx, addr, ScEvent::Type::EraseElement, func) @@ -111,6 +119,7 @@ class ScEventEraseElement final : public ScEvent class ScEventContentChanged final : public ScEvent { friend class ScMemoryContext; + public: _SC_EXTERN ScEventContentChanged(const ScMemoryContext & ctx, const ScAddr & addr, ScEvent::DelegateFunc func) : ScEvent(ctx, addr, ScEvent::Type::ContentChanged, func) diff --git a/sc-memory/sc-memory/sc_iterator.cpp b/sc-memory/sc-memory/sc_iterator.cpp index acecbf7e4..6550f66a3 100644 --- a/sc-memory/sc-memory/sc_iterator.cpp +++ b/sc-memory/sc-memory/sc_iterator.cpp @@ -5,59 +5,81 @@ */ #include "sc_iterator.hpp" -#include "sc_memory.hpp" +#include "sc_memory.hpp" -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScAddr const & p1, sc_type const & p2, ScAddr const & p3) + ScAddr const & p1, + sc_type const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_f_a_f_new(*context, *p1, p2, *p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScAddr const & p1, sc_type const & p2, sc_type const & p3) + ScAddr const & p1, + sc_type const & p2, + sc_type const & p3) { m_iterator = sc_iterator3_f_a_a_new(*context, *p1, p2, p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - sc_type const & p1, sc_type const & p2, ScAddr const & p3) + sc_type const & p1, + sc_type const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_a_a_f_new(*context, p1, p2, *p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - sc_type const & p1, ScAddr const & p2, sc_type const & p3) + sc_type const & p1, + ScAddr const & p2, + sc_type const & p3) { m_iterator = sc_iterator3_a_f_a_new(*context, p1, *p2, p3); } -template<> TIterator3::TIterator3( - ScMemoryContext const & context, - ScAddr const & p1, ScAddr const & p2, sc_type const & p3) +template <> +TIterator3::TIterator3( + ScMemoryContext const & context, + ScAddr const & p1, + ScAddr const & p2, + sc_type const & p3) { m_iterator = sc_iterator3_f_f_a_new(*context, *p1, *p2, p3); } -template<> TIterator3::TIterator3( - ScMemoryContext const & context, - sc_type const & p1, ScAddr const & p2, ScAddr const & p3) +template <> +TIterator3::TIterator3( + ScMemoryContext const & context, + sc_type const & p1, + ScAddr const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_a_f_f_new(*context, p1, *p2, *p3); } -template<> TIterator3::TIterator3( - ScMemoryContext const & context, - ScAddr const & p1, ScAddr const & p2, ScAddr const & p3) +template <> +TIterator3::TIterator3( + ScMemoryContext const & context, + ScAddr const & p1, + ScAddr const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_f_f_f_new(*context, *p1, *p2, *p3); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, sc_type const & p2, @@ -68,7 +90,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_a_a_f_new(*context, *p1, p2, p3, p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, sc_type const & p1, sc_type const & p2, @@ -79,7 +102,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_a_a_f_a_f_new(*context, p1, p2, *p3, p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, sc_type const & p2, @@ -90,7 +114,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_f_a_f_new(*context, *p1, p2, *p3, p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, sc_type const & p2, @@ -101,7 +126,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_f_a_a_new(*context, *p1, p2, *p3, p4, p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, sc_type const & p2, @@ -112,7 +138,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_a_a_a_new(*context, *p1, p2, p3, p4, p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, sc_type const & p1, sc_type const & p2, @@ -123,62 +150,81 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_a_a_f_a_a_new(*context, p1, p2, *p3, p4, p5); } - - // ----------- -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScAddr const & p1, ScType const & p2, ScAddr const & p3) + ScAddr const & p1, + ScType const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_f_a_f_new(*context, *p1, *p2, *p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScAddr const & p1, ScType const & p2, ScType const & p3) + ScAddr const & p1, + ScType const & p2, + ScType const & p3) { m_iterator = sc_iterator3_f_a_a_new(*context, *p1, *p2, *p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScType const & p1, ScType const & p2, ScAddr const & p3) + ScType const & p1, + ScType const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_a_a_f_new(*context, *p1, *p2, *p3); } -template<> TIterator3::TIterator3( +template <> +TIterator3::TIterator3( ScMemoryContext const & context, - ScType const & p1, ScAddr const & p2, ScType const & p3) + ScType const & p1, + ScAddr const & p2, + ScType const & p3) { m_iterator = sc_iterator3_a_f_a_new(*context, *p1, *p2, *p3); } -template<> TIterator3::TIterator3( - ScMemoryContext const & context, - ScAddr const & p1, ScAddr const & p2, ScType const & p3) +template <> +TIterator3::TIterator3( + ScMemoryContext const & context, + ScAddr const & p1, + ScAddr const & p2, + ScType const & p3) { m_iterator = sc_iterator3_f_f_a_new(*context, *p1, *p2, *p3); } -template<> TIterator3::TIterator3( - ScMemoryContext const & context, - ScType const & p1, ScAddr const & p2, ScAddr const & p3) +template <> +TIterator3::TIterator3( + ScMemoryContext const & context, + ScType const & p1, + ScAddr const & p2, + ScAddr const & p3) { m_iterator = sc_iterator3_a_f_f_new(*context, *p1, *p2, *p3); } -template<> TIterator5::TIterator5(ScMemoryContext const & context, - ScAddr const & p1, - ScType const & p2, - ScType const & p3, - ScType const & p4, - ScAddr const & p5) +template <> +TIterator5::TIterator5( + ScMemoryContext const & context, + ScAddr const & p1, + ScType const & p2, + ScType const & p3, + ScType const & p4, + ScAddr const & p5) { m_iterator = sc_iterator5_f_a_a_a_f_new(*context, *p1, *p2, *p3, *p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScType const & p1, ScType const & p2, @@ -189,7 +235,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_a_a_f_a_f_new(*context, *p1, *p2, *p3, *p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, ScType const & p2, @@ -200,7 +247,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_f_a_f_new(*context, *p1, *p2, *p3, *p4, *p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, ScType const & p2, @@ -211,7 +259,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_f_a_a_new(*context, *p1, p2, *p3, p4, p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScAddr const & p1, ScType const & p2, @@ -222,7 +271,8 @@ template<> TIterator5::TIterator5( m_iterator = sc_iterator5_f_a_a_a_a_new(*context, *p1, p2, p3, p4, p5); } -template<> TIterator5::TIterator5( +template <> +TIterator5::TIterator5( ScMemoryContext const & context, ScType const & p1, ScType const & p2, @@ -232,4 +282,3 @@ template<> TIterator5::TIterator5( { m_iterator = sc_iterator5_a_a_f_a_a_new(*context, p1, p2, *p3, p4, p5); } - diff --git a/sc-memory/sc-memory/sc_iterator.hpp b/sc-memory/sc-memory/sc_iterator.hpp index 417981027..f901d2db7 100644 --- a/sc-memory/sc-memory/sc_iterator.hpp +++ b/sc-memory/sc-memory/sc_iterator.hpp @@ -14,15 +14,15 @@ extern "C" #include "sc-core/sc_memory_headers.h" } - class ScMemoryContext; template class TIteratorBase { public: - - virtual ~TIteratorBase() {} + virtual ~TIteratorBase() + { + } inline bool IsValid() const { @@ -34,22 +34,28 @@ class TIteratorBase //! Returns sc-addr of specified element in iterator result _SC_EXTERN virtual ScAddr Get(sc_uint8 idx) const = 0; - + //! Short form of Get - inline ScAddr operator [] (sc_uint8 idx) const { return Get(idx); } + inline ScAddr operator[](sc_uint8 idx) const + { + return Get(idx); + } protected: IterType * m_iterator; }; - template class TIterator3 : public TIteratorBase { friend class ScMemoryContext; protected: - _SC_EXTERN TIterator3(ScMemoryContext const & context, ParamType1 const & p1, ParamType2 const & p2, ParamType3 const & p3); + _SC_EXTERN TIterator3( + ScMemoryContext const & context, + ParamType1 const & p1, + ParamType2 const & p2, + ParamType3 const & p3); public: _SC_EXTERN virtual ~TIterator3() @@ -59,10 +65,9 @@ class TIterator3 : public TIteratorBase TIterator3(TIterator3 const & other) { - } - TIterator3 & operator = (TIterator3 const & other) + TIterator3 & operator=(TIterator3 const & other) { TakeOwnership(other); return *this; @@ -98,7 +103,13 @@ class TIterator5 : public TIteratorBase friend class ScMemoryContext; protected: - _SC_EXTERN TIterator5(ScMemoryContext const & context, ParamType1 const & p1, ParamType2 const & p2, ParamType3 const & p3, ParamType4 const & p4, ParamType5 const & p5); + _SC_EXTERN TIterator5( + ScMemoryContext const & context, + ParamType1 const & p1, + ParamType2 const & p2, + ParamType3 const & p3, + ParamType4 const & p4, + ParamType5 const & p5); public: _SC_EXTERN virtual ~TIterator5() @@ -127,12 +138,10 @@ class TIterator5 : public TIteratorBase SC_ASSERT(IsValid(), ()); return ScAddr(sc_iterator5_value(m_iterator, idx)); } - }; typedef TIteratorBase ScIterator3Type; typedef TIteratorBase ScIterator5Type; -typedef std::shared_ptr< ScIterator3Type > ScIterator3Ptr; -typedef std::shared_ptr< ScIterator5Type > ScIterator5Ptr; - +typedef std::shared_ptr ScIterator3Ptr; +typedef std::shared_ptr ScIterator5Ptr; diff --git a/sc-memory/sc-memory/sc_keynodes.cpp b/sc-memory/sc-memory/sc_keynodes.cpp index bf188d9e0..4ee815096 100644 --- a/sc-memory/sc-memory/sc_keynodes.cpp +++ b/sc-memory/sc-memory/sc_keynodes.cpp @@ -5,6 +5,7 @@ */ #include "sc_keynodes.hpp" + #include "sc_struct.hpp" size_t const kKeynodeRrelListNum = 20; @@ -78,7 +79,7 @@ bool ScKeynodes::Init(bool force) } // command states - ScAddr states[] = { kCommandFinishedAddr, kCommandInitiatedAddr, kCommandProgressdAddr }; + ScAddr states[] = {kCommandFinishedAddr, kCommandInitiatedAddr, kCommandProgressdAddr}; for (auto const & a : states) { if (!ctx.CreateEdge(ScType::EdgeAccessConstPosPerm, kCommandStateAddr, a).IsValid()) @@ -88,10 +89,8 @@ bool ScKeynodes::Init(bool force) // binary types { ScSet set(ctx, kBinaryType); - set << kBinaryDouble << kBinaryFloat << kBinaryString - << kBinaryInt8 << kBinaryInt16 << kBinaryInt32 << kBinaryInt64 - << kBinaryUInt8 << kBinaryUInt16 << kBinaryUInt32 << kBinaryUInt64 - << kBinaryCustom; + set << kBinaryDouble << kBinaryFloat << kBinaryString << kBinaryInt8 << kBinaryInt16 << kBinaryInt32 << kBinaryInt64 + << kBinaryUInt8 << kBinaryUInt16 << kBinaryUInt32 << kBinaryUInt64 << kBinaryCustom; } ms_isInitialized = true; @@ -167,13 +166,12 @@ sc_result ScKeynodes::GetResultCodeByAddr(ScAddr const & resultClassAddr) return SC_RESULT_UNKNOWN; } - ScAddr const & ScKeynodes::GetRrelIndex(size_t idx) { if (idx >= kKeynodeRrelListNum) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "You should use index in range[0; " + std::to_string(kKeynodeRrelListNum) + "]"); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "You should use index in range[0; " + std::to_string(kKeynodeRrelListNum) + "]"); } return kKeynodeRrelList[idx]; diff --git a/sc-memory/sc-memory/sc_link.cpp b/sc-memory/sc-memory/sc_link.cpp index 79e995db5..76c1c17ff 100644 --- a/sc-memory/sc-memory/sc_link.cpp +++ b/sc-memory/sc-memory/sc_link.cpp @@ -1,4 +1,5 @@ #include "sc_link.hpp" + #include "sc_template_builder.hpp" #include "sc_template_search.hpp" @@ -109,20 +110,14 @@ std::string ScLink::GetAsString() const return ""; } - bool ScLink::_DetermineTypeEdgeImpl(ScAddr & outEdge, ScAddr & outType) const { // set type - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - ScKeynodes::kBinaryType, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarClass >> "_type") - .Triple( - "_type", - ScType::EdgeAccessVarPosTemp >> "_edge", - m_addr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple(ScKeynodes::kBinaryType, ScType::EdgeAccessVarPosPerm, ScType::NodeVarClass >> "_type") + .Triple("_type", ScType::EdgeAccessVarPosTemp >> "_edge", m_addr) + .Make(); ScTemplateSearch search(m_ctx, *templ); auto it = search.begin(); @@ -136,4 +131,3 @@ bool ScLink::_DetermineTypeEdgeImpl(ScAddr & outEdge, ScAddr & outType) const return false; } - diff --git a/sc-memory/sc-memory/sc_link.hpp b/sc-memory/sc-memory/sc_link.hpp index ddb4102c6..d65768644 100644 --- a/sc-memory/sc-memory/sc_link.hpp +++ b/sc-memory/sc-memory/sc_link.hpp @@ -6,9 +6,9 @@ #pragma once +#include "sc_keynodes.hpp" #include "sc_memory.hpp" #include "sc_stream.hpp" -#include "sc_keynodes.hpp" #include "sc_template.hpp" /* This class wraps specified sc-link and provide functionality @@ -39,33 +39,36 @@ class ScLink // Check if this class has reference to sc-link element bool IsValid() const; - template inline ScAddr const & Type2Addr() const; - template inline void Value2Stream(Type const & value, ScStreamPtr & stream) const + template + inline ScAddr const & Type2Addr() const; + template + inline void Value2Stream(Type const & value, ScStreamPtr & stream) const { - stream.reset(new ScStream((sc_char*)(&value), sizeof(value), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); + stream.reset(new ScStream((sc_char *)(&value), sizeof(value), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); } - template inline bool Stream2Value(ScStreamPtr const & stream, Type & outValue) const + template + inline bool Stream2Value(ScStreamPtr const & stream, Type & outValue) const { if (stream->Size() != sizeof(Type)) return false; size_t readBytes = 0; - stream->Read((sc_char*)(&outValue), sizeof(Type), readBytes); + stream->Read((sc_char *)(&outValue), sizeof(Type), readBytes); if (sizeof(Type) != readBytes) return false; return true; } - template inline - bool IsType() const + template + inline bool IsType() const { return m_ctx.HelperCheckEdge(Type2Addr(), m_addr, ScType::EdgeAccessConstPosTemp); } - template inline - bool Set(Type const & value) + template + inline bool Set(Type const & value) { ScStreamPtr stream; Value2Stream(value, stream); @@ -94,14 +97,12 @@ class ScLink return true; } - template Type Get() const { if (!IsType()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidType, - "You've used incorrect type. Use IsType<>() to check it"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidType, "You've used incorrect type. Use IsType<>() to check it"); } ScStreamPtr const stream = m_ctx.GetLinkContent(m_addr); @@ -112,8 +113,7 @@ class ScLink Type result; if (!Stream2Value(stream, result)) { - SC_THROW_EXCEPTION(utils::ExceptionCritical, - "Failed to get the value of " + std::to_string(m_addr.Hash())); + SC_THROW_EXCEPTION(utils::ExceptionCritical, "Failed to get the value of " + std::to_string(m_addr.Hash())); } return result; @@ -124,39 +124,91 @@ class ScLink protected: _SC_EXTERN bool _DetermineTypeEdgeImpl(ScAddr & outEdge, ScAddr & outType) const; + private: ScMemoryContext & m_ctx; ScAddr m_addr; }; -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryString; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryFloat; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryDouble; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryInt8; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryInt16; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryInt32; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryInt64; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryUInt8; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryUInt16; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryUInt32; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryUInt64; } -template <> inline ScAddr const & ScLink::Type2Addr() const { return ScKeynodes::kBinaryCustom; } +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryString; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryFloat; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryDouble; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryInt8; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryInt16; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryInt32; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryInt64; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryUInt8; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryUInt16; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryUInt32; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryUInt64; +} +template <> +inline ScAddr const & ScLink::Type2Addr() const +{ + return ScKeynodes::kBinaryCustom; +} -template <> inline void ScLink::Value2Stream(std::string const & value, ScStreamPtr & stream) const +template <> +inline void ScLink::Value2Stream(std::string const & value, ScStreamPtr & stream) const { - stream.reset(new ScStream((sc_char*)value.c_str(), value.size(), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); + stream.reset(new ScStream((sc_char *)value.c_str(), value.size(), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); } -template <> inline void ScLink::Value2Stream(ScStreamPtr const & value, ScStreamPtr & stream) const +template <> +inline void ScLink::Value2Stream(ScStreamPtr const & value, ScStreamPtr & stream) const { stream = value; } -template <> inline bool ScLink::Stream2Value(ScStreamPtr const & stream, std::string & outValue) const +template <> +inline bool ScLink::Stream2Value(ScStreamPtr const & stream, std::string & outValue) const { std::vector buff(stream->Size()); size_t readBytes = 0; - stream->Read((sc_char*)buff.data(), buff.size(), readBytes); + stream->Read((sc_char *)buff.data(), buff.size(), readBytes); if (readBytes != buff.size()) return false; @@ -164,7 +216,8 @@ template <> inline bool ScLink::Stream2Value(ScStreamPtr const & st return true; } -template <> inline bool ScLink::Stream2Value(ScStreamPtr const & stream, ScStreamPtr & outValue) const +template <> +inline bool ScLink::Stream2Value(ScStreamPtr const & stream, ScStreamPtr & outValue) const { outValue = stream; return true; diff --git a/sc-memory/sc-memory/sc_memory.cpp b/sc-memory/sc-memory/sc_memory.cpp index 8f2bdca3d..fb39d9eb4 100644 --- a/sc-memory/sc-memory/sc_memory.cpp +++ b/sc-memory/sc-memory/sc_memory.cpp @@ -5,14 +5,13 @@ */ #include "sc_memory.hpp" + #include "sc_keynodes.hpp" -#include "sc_utils.hpp" #include "sc_stream.hpp" - -#include "kpm/sc_agent.hpp" +#include "sc_utils.hpp" #include "http/sc_http.hpp" - +#include "kpm/sc_agent.hpp" #include "utils/sc_log.hpp" #include @@ -30,18 +29,26 @@ extern "C" namespace { - GMutex gContextMutex; struct ContextMutexLock { - ContextMutexLock() { g_mutex_lock(&gContextMutex); } - ~ContextMutexLock() { g_mutex_unlock(&gContextMutex); } + ContextMutexLock() + { + g_mutex_lock(&gContextMutex); + } + ~ContextMutexLock() + { + g_mutex_unlock(&gContextMutex); + } }; bool gIsLogMuted = false; -void _logPrintHandler(gchar const * /* log_domain */, GLogLevelFlags log_level, - gchar const * message, gpointer /* user_data */) +void _logPrintHandler( + gchar const * /* log_domain */, + GLogLevelFlags log_level, + gchar const * message, + gpointer /* user_data */) { if (gIsLogMuted) return; @@ -69,9 +76,9 @@ void _logPrintHandler(gchar const * /* log_domain */, GLogLevelFlags log_level, }; } -std::atomic_int gContextCounter = { 0 }; +std::atomic_int gContextCounter = {0}; -} // namespace +} // namespace // ------------------ @@ -246,7 +253,7 @@ ScAddr ScMemoryContext::CreateNode(ScType const & type) return ScAddr(sc_memory_node_new(m_context, *type)); } -ScAddr ScMemoryContext::CreateLink(ScType const & type/* = ScType::LinkConst */) +ScAddr ScMemoryContext::CreateLink(ScType const & type /* = ScType::LinkConst */) { SC_ASSERT(type == ScType::LinkConst || type == ScType::LinkVar, ()); SC_ASSERT(IsValid(), ()); @@ -300,7 +307,8 @@ ScAddr ScMemoryContext::GetEdgeTarget(ScAddr const & edgeAddr) const bool ScMemoryContext::GetEdgeInfo(ScAddr const & edgeAddr, ScAddr & outSourceAddr, ScAddr & outTargetAddr) const { SC_ASSERT(IsValid(), ()); - if (sc_memory_get_arc_info(m_context, *edgeAddr, &outSourceAddr.m_realAddr, &outTargetAddr.m_realAddr) != SC_RESULT_OK) + if (sc_memory_get_arc_info(m_context, *edgeAddr, &outSourceAddr.m_realAddr, &outTargetAddr.m_realAddr) != + SC_RESULT_OK) { outSourceAddr.Reset(); outTargetAddr.Reset(); @@ -371,13 +379,16 @@ bool ScMemoryContext::Save() return (sc_memory_save(m_context) == SC_RESULT_OK); } -bool ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScAddr & outAddr, ScType const & type/* = ScType()*/) +bool ScMemoryContext::HelperResolveSystemIdtf( + std::string const & sysIdtf, + ScAddr & outAddr, + ScType const & type /* = ScType()*/) { outAddr = HelperResolveSystemIdtf(sysIdtf, type); return outAddr.IsValid(); } -ScAddr ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScType const & type/* = ScType()*/) +ScAddr ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScType const & type /* = ScType()*/) { SC_ASSERT(IsValid(), ()); ScAddr resultAddr = HelperFindBySystemIdtf(sysIdtf); @@ -385,8 +396,7 @@ ScAddr ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScT { if (!type.IsNode()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "You should provide any of ScType::Node... value as a type"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "You should provide any of ScType::Node... value as a type"); } resultAddr = CreateNode(type); @@ -399,7 +409,8 @@ ScAddr ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScT bool ScMemoryContext::HelperSetSystemIdtf(std::string const & sysIdtf, ScAddr const & addr) { SC_ASSERT(IsValid(), ()); - return (sc_helper_set_system_identifier(m_context, *addr, sysIdtf.c_str(), (sc_uint32)sysIdtf.size()) == SC_RESULT_OK); + return ( + sc_helper_set_system_identifier(m_context, *addr, sysIdtf.c_str(), (sc_uint32)sysIdtf.size()) == SC_RESULT_OK); } std::string ScMemoryContext::HelperGetSystemIdtf(ScAddr const & addr) @@ -437,14 +448,17 @@ bool ScMemoryContext::HelperCheckEdge(ScAddr const & begin, ScAddr end, ScType c bool ScMemoryContext::HelperFindBySystemIdtf(std::string const & sysIdtf, ScAddr & outAddr) { SC_ASSERT(IsValid(), ()); - return (sc_helper_find_element_by_system_identifier(m_context, sysIdtf.c_str(), (sc_uint32)sysIdtf.size(), &outAddr.m_realAddr) == SC_RESULT_OK); + return ( + sc_helper_find_element_by_system_identifier( + m_context, sysIdtf.c_str(), (sc_uint32)sysIdtf.size(), &outAddr.m_realAddr) == SC_RESULT_OK); } ScAddr ScMemoryContext::HelperFindBySystemIdtf(std::string const & sysIdtf) { ScAddr result; SC_ASSERT(IsValid(), ()); - sc_helper_find_element_by_system_identifier(m_context, sysIdtf.c_str(), (sc_uint32)sysIdtf.size(), &result.m_realAddr); + sc_helper_find_element_by_system_identifier( + m_context, sysIdtf.c_str(), (sc_uint32)sysIdtf.size(), &result.m_realAddr); return result; } diff --git a/sc-memory/sc-memory/sc_memory.hpp b/sc-memory/sc-memory/sc_memory.hpp index 6e790c645..0c6b6a94c 100644 --- a/sc-memory/sc-memory/sc_memory.hpp +++ b/sc-memory/sc-memory/sc_memory.hpp @@ -8,8 +8,8 @@ extern "C" { -#include "sc-core/sc_memory_headers.h" #include "sc-core/sc_helper.h" +#include "sc-core/sc_memory_headers.h" } #include "sc_addr.hpp" @@ -35,10 +35,11 @@ class ScMemory _SC_EXTERN static void LogMute(); _SC_EXTERN static void LogUnmute(); -protected: +protected: static void RegisterContext(ScMemoryContext const * ctx); static void UnregisterContext(ScMemoryContext const * ctx); + private: static bool HasMemoryContext(ScMemoryContext const * ctx); @@ -72,10 +73,16 @@ class ScMemoryContext // Disable object copying ScMemoryContext(ScMemoryContext const & other) = delete; - ScMemoryContext & operator = (ScMemoryContext const & other) = delete; + ScMemoryContext & operator=(ScMemoryContext const & other) = delete; - sc_memory_context const * operator * () const { return m_context; } - sc_memory_context const * GetRealContext() const { return m_context; } + sc_memory_context const * operator*() const + { + return m_context; + } + sc_memory_context const * GetRealContext() const + { + return m_context; + } //! Call this function, when you request to destroy real memory context, before destructor calls for this object _SC_EXTERN void Destroy(); @@ -86,7 +93,10 @@ class ScMemoryContext //! End events pending mode void EndEventsPending(); - std::string const & GetName() const { return m_name; } + std::string const & GetName() const + { + return m_name; + } _SC_EXTERN bool IsValid() const; @@ -107,8 +117,8 @@ class ScMemoryContext _SC_EXTERN ScType GetElementType(ScAddr const & addr) const; /*! Change subtype of sc-element. - * Return true, if there are no any errors; otherwise return false. - */ + * Return true, if there are no any errors; otherwise return false. + */ _SC_EXTERN bool SetElementSubtype(ScAddr const & addr, sc_type subtype); _SC_EXTERN ScAddr GetEdgeSource(ScAddr const & edgeAddr) const; @@ -127,7 +137,8 @@ class ScMemoryContext SC_DEPRECATED(0.6.0, "Use `ScAddrList FindLinksByContent(ScStreamPtr const & stream)` instead.") _SC_EXTERN bool FindLinksByContent(ScStreamPtr const & stream, ScAddrVector & found); _SC_EXTERN ScAddrVector FindLinksByContent(ScStreamPtr const & stream); - template ScAddrVector FindLinksByContent(TContentType const & value) + template + ScAddrVector FindLinksByContent(TContentType const & value) { return FindLinksByContent(ScStreamMakeRead(value)); } @@ -136,33 +147,33 @@ class ScMemoryContext _SC_EXTERN bool Save(); template - std::shared_ptr> Iterator5(ParamType1 const & param1, - ParamType2 const & param2, - ParamType3 const & param3, - ParamType4 const & param4, - ParamType5 const & param5) + std::shared_ptr> Iterator5( + ParamType1 const & param1, + ParamType2 const & param2, + ParamType3 const & param3, + ParamType4 const & param4, + ParamType5 const & param5) { return std::shared_ptr>( - new TIterator5(*this, param1, param2, param3, param4, param5)); + new TIterator5( + *this, param1, param2, param3, param4, param5)); } template - std::shared_ptr> Iterator3(ParamType1 const & param1, - ParamType2 const & param2, - ParamType3 const & param3) + std::shared_ptr> Iterator3( + ParamType1 const & param1, + ParamType2 const & param2, + ParamType3 const & param3) { return std::shared_ptr>( - new TIterator3(*this, param1, param2, param3)); + new TIterator3(*this, param1, param2, param3)); } /* Make iteration by triples, and call fn function for each result. * fn function should have 3 parameters (ScAddr const & source, ScAddr const & edge, ScAddr const & target) */ template - void ForEachIter3(ParamType1 const & param1, - ParamType2 const & param2, - ParamType3 const & param3, - FnT && fn) + void ForEachIter3(ParamType1 const & param1, ParamType2 const & param2, ParamType3 const & param3, FnT && fn) { ScIterator3Ptr it = Iterator3(param1, param2, param3); while (it->Next()) @@ -173,13 +184,20 @@ class ScMemoryContext * fn function should have 5 parameters * (ScAddr const & source, ScAddr const & edge, ScAddr const & target, ScAddr const & attrEdge, ScAddr const & attr) */ - template - void ForEachIter5(ParamType1 const & param1, - ParamType2 const & param2, - ParamType3 const & param3, - ParamType4 const & param4, - ParamType5 const & param5, - FnT && fn) + template < + typename ParamType1, + typename ParamType2, + typename ParamType3, + typename ParamType4, + typename ParamType5, + typename FnT> + void ForEachIter5( + ParamType1 const & param1, + ParamType2 const & param2, + ParamType3 const & param3, + ParamType4 const & param4, + ParamType5 const & param5, + FnT && fn) { ScIterator5Ptr it = Iterator5(param1, param2, param3, param4, param5); while (it->Next()) @@ -191,8 +209,13 @@ class ScMemoryContext * Look at type parameter as ForceCreate flag, that contains type. * Important: Type should be any of ScType::Node... */ - SC_DEPRECATED(0.4.0, "Use should use ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScType const & type)") - _SC_EXTERN bool HelperResolveSystemIdtf(std::string const & sysIdtf, ScAddr & outAddr, ScType const & type = ScType()); + SC_DEPRECATED( + 0.4.0, + "Use should use ScMemoryContext::HelperResolveSystemIdtf(std::string const & sysIdtf, ScType const & type)") + _SC_EXTERN bool HelperResolveSystemIdtf( + std::string const & sysIdtf, + ScAddr & outAddr, + ScType const & type = ScType()); _SC_EXTERN ScAddr HelperResolveSystemIdtf(std::string const & sysIdtf, ScType const & type = ScType()); _SC_EXTERN bool HelperSetSystemIdtf(std::string const & sysIdtf, ScAddr const & addr); @@ -230,4 +253,3 @@ class ScMemoryContextEventsPendingGuard private: ScMemoryContext & m_ctx; }; - diff --git a/sc-memory/sc-memory/sc_memory_headers.hpp b/sc-memory/sc-memory/sc_memory_headers.hpp index 0a2ed2730..9ff8e2771 100644 --- a/sc-memory/sc-memory/sc_memory_headers.hpp +++ b/sc-memory/sc-memory/sc_memory_headers.hpp @@ -8,5 +8,5 @@ #include "sc_memory.hpp" #include "sc_stream.hpp" -#include "sc_template.hpp" #include "sc_struct.hpp" +#include "sc_template.hpp" diff --git a/sc-memory/sc-memory/sc_module.cpp b/sc-memory/sc-memory/sc_module.cpp index 31b7f63a5..071bad1b8 100644 --- a/sc-memory/sc-memory/sc_module.cpp +++ b/sc-memory/sc-memory/sc_module.cpp @@ -5,5 +5,3 @@ */ #include "sc_module.hpp" - - diff --git a/sc-memory/sc-memory/sc_module.hpp b/sc-memory/sc-memory/sc_module.hpp index 7da8ab73a..75654b180 100644 --- a/sc-memory/sc-memory/sc_module.hpp +++ b/sc-memory/sc-memory/sc_module.hpp @@ -6,8 +6,9 @@ #pragma once -#include "sc_object.hpp" #include "sc_addr.hpp" +#include "sc_object.hpp" + #include "kpm/sc_agent.hpp" #include "generated/sc_module.generated.hpp" diff --git a/sc-memory/sc-memory/sc_object.cpp b/sc-memory/sc-memory/sc_object.cpp index 39155ecc7..3dda6413e 100644 --- a/sc-memory/sc-memory/sc_object.cpp +++ b/sc-memory/sc-memory/sc_object.cpp @@ -6,7 +6,6 @@ #include "sc_object.hpp" - ScObject::ScObject() : m_isInitialized(false) , m_initResult(false) @@ -15,15 +14,13 @@ ScObject::ScObject() ScObject::~ScObject() { - } ScObject::ScObject(ScObject const & other) { - } -ScObject & ScObject::operator = (ScObject const & other) +ScObject & ScObject::operator=(ScObject const & other) { return *this; } diff --git a/sc-memory/sc-memory/sc_object.hpp b/sc-memory/sc-memory/sc_object.hpp index 45dced837..f4e0932f2 100644 --- a/sc-memory/sc-memory/sc_object.hpp +++ b/sc-memory/sc-memory/sc_object.hpp @@ -15,13 +15,12 @@ */ class _SC_EXTERN ScObject { - protected: explicit ScObject(); virtual ~ScObject(); ScObject(ScObject const & other); - ScObject & operator = (ScObject const & other); + ScObject & operator=(ScObject const & other); public: /// TODO: Need mechanism to call that function automaticaly after object construction @@ -29,8 +28,8 @@ class _SC_EXTERN ScObject private: /** This method override genarates by code generator, and initialize all - * meta data for this object. It calls from ScObject constructors - */ + * meta data for this object. It calls from ScObject constructors + */ virtual bool _InitInternal() = 0; private: diff --git a/sc-memory/sc-memory/sc_platform.hpp b/sc-memory/sc-memory/sc_platform.hpp index 7b4a9cd85..78a50bf2f 100644 --- a/sc-memory/sc-memory/sc_platform.hpp +++ b/sc-memory/sc-memory/sc_platform.hpp @@ -7,4 +7,3 @@ #pragma once #include "sc-core/sc-store/sc_platform.h" - diff --git a/sc-memory/sc-memory/sc_scs_helper.cpp b/sc-memory/sc-memory/sc_scs_helper.cpp index d925a40a4..568e44665 100644 --- a/sc-memory/sc-memory/sc_scs_helper.cpp +++ b/sc-memory/sc-memory/sc_scs_helper.cpp @@ -17,7 +17,6 @@ namespace impl { - class StructGenerator { friend class ::SCsHelper; @@ -31,7 +30,7 @@ class StructGenerator SC_ASSERT(m_kNrelSCsGlobalIdtf.IsValid(), ()); } - void operator() (scs::Parser const & parser) + void operator()(scs::Parser const & parser) { // generate aliases auto const & aliases = parser.GetAliases(); @@ -56,8 +55,7 @@ class StructGenerator SC_ASSERT(srcAddr.IsValid() && trgAddr.IsValid(), ()); if (!edge.GetType().IsEdge()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidType, - "Edge in triple has incorrect type"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidType, "Edge in triple has incorrect type"); } ScAddr const edgeAddr = m_ctx.CreateEdge(edge.GetType(), srcAddr, trgAddr); @@ -65,19 +63,18 @@ class StructGenerator m_idtfCache.insert(std::make_pair(edge.GetIdtf(), edgeAddr)); } - parser.ForEachParsedElement([this](scs::ParsedElement const & el) - { - if (m_idtfCache.find(el.GetIdtf()) == m_idtfCache.end() && - !el.GetType().IsEdge() && - !scs::TypeResolver::IsKeynodeType(el.GetIdtf())) - { - ResolveElement(el); - } - }); + parser.ForEachParsedElement( + [this](scs::ParsedElement const & el) + { + if (m_idtfCache.find(el.GetIdtf()) == m_idtfCache.end() && !el.GetType().IsEdge() && + !scs::TypeResolver::IsKeynodeType(el.GetIdtf())) + { + ResolveElement(el); + } + }); } private: - void SetSCsGlobalIdtf(std::string const & idtf, ScAddr const & addr) { SC_ASSERT(m_kNrelSCsGlobalIdtf.IsValid(), ()); @@ -102,13 +99,13 @@ class StructGenerator for (ScAddr const & addr : links) { ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::Unknown >> "_el", - ScType::EdgeDCommonVar, - addr, - ScType::EdgeAccessVarPosPerm, - m_kNrelSCsGlobalIdtf) - .Make(); + .TripleWithRelation( + ScType::Unknown >> "_el", + ScType::EdgeDCommonVar, + addr, + ScType::EdgeAccessVarPosPerm, + m_kNrelSCsGlobalIdtf) + .Make(); ScTemplateSearch search(m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -117,8 +114,8 @@ class StructGenerator ScAddr const foundAddr = found["_el"]; if (result.IsValid() || (++found != search.end())) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, - "There are more then 1 element with global identifier: " << idtf); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidState, "There are more then 1 element with global identifier: " << idtf); } result = foundAddr; @@ -176,7 +173,6 @@ class StructGenerator { SetSCsGlobalIdtf(el.GetIdtf(), result); } - } SC_ASSERT(result.IsValid(), ()); @@ -188,7 +184,8 @@ class StructGenerator return result; } - template bool SetLinkContentT(ScAddr const & linkAddr, std::string const & value) + template + bool SetLinkContentT(ScAddr const & linkAddr, std::string const & value) { T number; auto const result = utils::StringUtils::ParseNumber(value, number); @@ -217,7 +214,8 @@ class StructGenerator else { // chekc if it's a number format - std::regex const rNumber("^\\^\"(int8|int16|int32|int64|uint8|uint16|uint32|uint64|float|double)\\s*:\\s*([0-9]+|[0-9]+[.][0-9]+)\"$"); + std::regex const rNumber( + "^\\^\"(int8|int16|int32|int64|uint8|uint16|uint32|uint64|float|double)\\s*:\\s*([0-9]+|[0-9]+[.][0-9]+)\"$"); std::smatch result; if (std::regex_match(el.GetValue(), result, rNumber)) { @@ -249,14 +247,12 @@ class StructGenerator result = SetLinkContentT(linkAddr, value); else { - SC_THROW_EXCEPTION(utils::ExceptionInvalidType, - "Unsupported link binary type: " + type); + SC_THROW_EXCEPTION(utils::ExceptionInvalidType, "Unsupported link binary type: " + type); } if (!result) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, - "Can't parse value from: " + el.GetValue()); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't parse value from: " + el.GetValue()); } } else @@ -275,7 +271,7 @@ class StructGenerator ScAddr m_kNrelSCsGlobalIdtf; }; -} // namespace impl +} // namespace impl SCsHelper::SCsHelper(ScMemoryContext & ctx, SCsFileInterfacePtr const & fileInterface) : m_ctx(ctx) diff --git a/sc-memory/sc-memory/sc_stream.cpp b/sc-memory/sc-memory/sc_stream.cpp index fb21cdb0f..fc20c9fb9 100644 --- a/sc-memory/sc-memory/sc_stream.cpp +++ b/sc-memory/sc-memory/sc_stream.cpp @@ -6,7 +6,6 @@ #include "sc_stream.hpp" - ScStream::ScStream() : m_stream(0) { @@ -108,7 +107,7 @@ bool ScStream::HasFlag(sc_uint8 flag) // --------------- ScStreamMemory::ScStreamMemory(MemoryBufferPtr const & buff) - : ScStream (static_cast(buff->Data()), sc_uint(buff->Size()), SC_STREAM_FLAG_READ) + : ScStream(static_cast(buff->Data()), sc_uint(buff->Size()), SC_STREAM_FLAG_READ) , m_buffer(buff) { } @@ -129,10 +128,9 @@ bool ScStreamConverter::StreamToString(ScStreamPtr const & stream, std::string & if (stream->Read(data, bytesCount, readBytes) && (readBytes == bytesCount)) outString.assign(data, data + bytesCount); - delete []data; + delete[] data; return true; - } ScStreamPtr ScStreamConverter::StreamFromString(std::string const & str) diff --git a/sc-memory/sc-memory/sc_stream.hpp b/sc-memory/sc-memory/sc_stream.hpp index 1f452a4ba..307d15592 100644 --- a/sc-memory/sc-memory/sc_stream.hpp +++ b/sc-memory/sc-memory/sc_stream.hpp @@ -20,7 +20,7 @@ class ScStream friend class ScMemoryContext; ScStream(ScStream const & other) = delete; - ScStream & operator = (ScStream const & other) = delete; + ScStream & operator=(ScStream const & other) = delete; public: _SC_EXTERN explicit ScStream(); @@ -53,7 +53,7 @@ class ScStream bool ReadType(Type & value) { size_t readBytes = 0; - return Read((sc_char*)&value, sizeof(Type), readBytes) && (readBytes == sizeof(Type)); + return Read((sc_char *)&value, sizeof(Type), readBytes) && (readBytes == sizeof(Type)); } protected: @@ -72,11 +72,9 @@ class ScStreamMemory : public ScStream MemoryBufferPtr m_buffer; }; - class ScStreamConverter { - public: - +public: static _SC_EXTERN bool StreamToString(ScStreamPtr const & stream, std::string & outString); static _SC_EXTERN ScStreamPtr StreamFromString(std::string const & str); }; @@ -84,19 +82,53 @@ class ScStreamConverter template inline ScStreamPtr ScStreamMakeReadT(T const & value) { - static_assert (std::is_arithmetic::value, "Just simple arithmetic types are supported"); - return std::make_shared((sc_char*)&value, sizeof(T), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK | SC_STREAM_FLAG_TELL); + static_assert(std::is_arithmetic::value, "Just simple arithmetic types are supported"); + return std::make_shared( + (sc_char *)&value, sizeof(T), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK | SC_STREAM_FLAG_TELL); } // TODO: implement with enable_if -inline ScStreamPtr ScStreamMakeRead(std::string const & value) { return ScStreamConverter::StreamFromString(value); } -inline ScStreamPtr ScStreamMakeRead(uint8_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(uint16_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(uint32_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(uint64_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(int8_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(int16_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(int32_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(int64_t const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(float const & value) { return ScStreamMakeReadT(value); } -inline ScStreamPtr ScStreamMakeRead(double const & value) { return ScStreamMakeReadT(value); } +inline ScStreamPtr ScStreamMakeRead(std::string const & value) +{ + return ScStreamConverter::StreamFromString(value); +} +inline ScStreamPtr ScStreamMakeRead(uint8_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(uint16_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(uint32_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(uint64_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(int8_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(int16_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(int32_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(int64_t const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(float const & value) +{ + return ScStreamMakeReadT(value); +} +inline ScStreamPtr ScStreamMakeRead(double const & value) +{ + return ScStreamMakeReadT(value); +} diff --git a/sc-memory/sc-memory/sc_struct.cpp b/sc-memory/sc-memory/sc_struct.cpp index a0d8dbe07..b69eab022 100644 --- a/sc-memory/sc-memory/sc_struct.cpp +++ b/sc-memory/sc-memory/sc_struct.cpp @@ -5,6 +5,7 @@ */ #include "sc_struct.hpp" + #include "sc_memory.hpp" #include "sc_template.hpp" @@ -59,19 +60,19 @@ bool ScSet::HasElement(ScAddr const & elAddr) const return m_context.HelperCheckEdge(m_addr, elAddr, ScType::EdgeAccessConstPosPerm); } -ScSet & ScSet::operator << (ScAddr const & elAddr) +ScSet & ScSet::operator<<(ScAddr const & elAddr) { Append(elAddr); return *this; } -ScSet & ScSet::operator >> (ScAddr const & elAddr) +ScSet & ScSet::operator>>(ScAddr const & elAddr) { Remove(elAddr); return *this; } -ScAddr const & ScSet::operator * () const +ScAddr const & ScSet::operator*() const { return m_addr; } diff --git a/sc-memory/sc-memory/sc_struct.hpp b/sc-memory/sc-memory/sc_struct.hpp index 3775c7630..136f44c49 100644 --- a/sc-memory/sc-memory/sc_struct.hpp +++ b/sc-memory/sc-memory/sc_struct.hpp @@ -8,7 +8,8 @@ class ScSet public: _SC_EXTERN ScSet(class ScMemoryContext & ctx, ScAddr const & setAddr); - /* Append element into sc-set. If element already exist, then doesn't append it and return false; otherwise returns true. */ + /* Append element into sc-set. If element already exist, then doesn't append it and return false; otherwise returns + * true. */ _SC_EXTERN bool Append(ScAddr const & elAddr); _SC_EXTERN bool Append(ScAddr const & elAddr, ScAddr const & attrAddr); @@ -16,15 +17,15 @@ class ScSet _SC_EXTERN bool Remove(ScAddr const & elAddr); /* Operator equal to append */ - _SC_EXTERN ScSet & operator << (ScAddr const & elAddr); + _SC_EXTERN ScSet & operator<<(ScAddr const & elAddr); /* Operator equal to remove */ - _SC_EXTERN ScSet & operator >> (ScAddr const & elAddr); + _SC_EXTERN ScSet & operator>>(ScAddr const & elAddr); /* Check if specified element exist in set */ _SC_EXTERN bool HasElement(ScAddr const & elAddr) const; - _SC_EXTERN ScAddr const & operator * () const; + _SC_EXTERN ScAddr const & operator*() const; /* Check if set has no elements */ _SC_EXTERN bool IsEmpty() const; diff --git a/sc-memory/sc-memory/sc_template.cpp b/sc-memory/sc-memory/sc_template.cpp index a1698fa1b..48c8fe867 100644 --- a/sc-memory/sc-memory/sc_template.cpp +++ b/sc-memory/sc-memory/sc_template.cpp @@ -5,26 +5,27 @@ */ #include "sc_template.hpp" + #include "sc_memory.hpp" #include -ScTemplateArg operator >> (ScAddr const & value, char const * replName) +ScTemplateArg operator>>(ScAddr const & value, char const * replName) { return ScTemplateArg(value, replName); } -ScTemplateArg operator >> (ScAddr const & value, std::string const & replName) +ScTemplateArg operator>>(ScAddr const & value, std::string const & replName) { return ScTemplateArg(value, replName.c_str()); } -ScTemplateArg operator >> (ScType const & value, char const * replName) +ScTemplateArg operator>>(ScType const & value, char const * replName) { return ScTemplateArg(value, replName); } -ScTemplateArg operator >> (ScType const & value, std::string const & replName) +ScTemplateArg operator>>(ScType const & value, std::string const & replName) { return ScTemplateArg(value, replName.c_str()); } diff --git a/sc-memory/sc-memory/sc_template.hpp b/sc-memory/sc-memory/sc_template.hpp index ce90eedf7..e23ff4fd7 100644 --- a/sc-memory/sc-memory/sc_template.hpp +++ b/sc-memory/sc-memory/sc_template.hpp @@ -6,8 +6,6 @@ #include #include - - class ScTemplate final { friend class ScTemplateBuilderImpl; @@ -19,7 +17,7 @@ class ScTemplate final explicit ScTemplate(Data && data); ScTemplate(ScTemplate const & other) = delete; - ScTemplate & operator = (ScTemplate const & other) = delete; + ScTemplate & operator=(ScTemplate const & other) = delete; _SC_EXTERN ScTemplate() = default; _SC_EXTERN bool IsEmpty() const; @@ -33,8 +31,8 @@ class ScTemplate final using ScTemplatePtr = std::unique_ptr; -template -ScTemplatePtr ScTemplatePtrMake(_Args&&... args) +template +ScTemplatePtr ScTemplatePtrMake(_Args &&... args) { return std::make_unique(std::forward<_Args>(args)...); } diff --git a/sc-memory/sc-memory/sc_template_arg.hpp b/sc-memory/sc-memory/sc_template_arg.hpp index db2b19d30..1e0126789 100644 --- a/sc-memory/sc-memory/sc_template_arg.hpp +++ b/sc-memory/sc-memory/sc_template_arg.hpp @@ -120,7 +120,7 @@ struct ScTemplateArg std::string m_replacementName; }; -_SC_EXTERN ScTemplateArg operator >> (ScAddr const & value, char const * replName); -_SC_EXTERN ScTemplateArg operator >> (ScAddr const & value, std::string const & replName); -_SC_EXTERN ScTemplateArg operator >> (ScType const & value, char const * replName); -_SC_EXTERN ScTemplateArg operator >> (ScType const & value, std::string const & replName); +_SC_EXTERN ScTemplateArg operator>>(ScAddr const & value, char const * replName); +_SC_EXTERN ScTemplateArg operator>>(ScAddr const & value, std::string const & replName); +_SC_EXTERN ScTemplateArg operator>>(ScType const & value, char const * replName); +_SC_EXTERN ScTemplateArg operator>>(ScType const & value, std::string const & replName); diff --git a/sc-memory/sc-memory/sc_template_builder.cpp b/sc-memory/sc-memory/sc_template_builder.cpp index 5155e228a..ff002f879 100644 --- a/sc-memory/sc-memory/sc_template_builder.cpp +++ b/sc-memory/sc-memory/sc_template_builder.cpp @@ -1,4 +1,5 @@ #include "sc_template_builder.hpp" + #include "sc_template_builder_impl.hpp" ScTemplateBuilder::ScTemplateBuilder() @@ -11,19 +12,21 @@ ScTemplateBuilder::~ScTemplateBuilder() // need to use forward declaration for std::unique_ptr } -ScTemplateBuilder & ScTemplateBuilder::Triple(ScTemplateArg const & source, - ScTemplateArg const & edge, - ScTemplateArg const & target) +ScTemplateBuilder & ScTemplateBuilder::Triple( + ScTemplateArg const & source, + ScTemplateArg const & edge, + ScTemplateArg const & target) { m_impl->Triple(source, edge, target); return *this; } -ScTemplateBuilder & ScTemplateBuilder::TripleWithRelation(ScTemplateArg const & source, - ScTemplateArg const & edge, - ScTemplateArg const & target, - ScTemplateArg const & attrEdge, - ScTemplateArg const & attr) +ScTemplateBuilder & ScTemplateBuilder::TripleWithRelation( + ScTemplateArg const & source, + ScTemplateArg const & edge, + ScTemplateArg const & target, + ScTemplateArg const & attrEdge, + ScTemplateArg const & attr) { m_impl->TripleWithRelation(source, edge, target, attrEdge, attr); return *this; @@ -33,5 +36,3 @@ ScTemplatePtr ScTemplateBuilder::Make() { return m_impl->Make(); } - - diff --git a/sc-memory/sc-memory/sc_template_builder.hpp b/sc-memory/sc-memory/sc_template_builder.hpp index 2e303b8b6..7309d6c02 100644 --- a/sc-memory/sc-memory/sc_template_builder.hpp +++ b/sc-memory/sc-memory/sc_template_builder.hpp @@ -15,9 +15,10 @@ class _SC_EXTERN ScTemplateBuilder final * \param edge Edge element definition * \param target Target element definition */ - _SC_EXTERN ScTemplateBuilder & Triple(ScTemplateArg const & source, - ScTemplateArg const & edge, - ScTemplateArg const & target); + _SC_EXTERN ScTemplateBuilder & Triple( + ScTemplateArg const & source, + ScTemplateArg const & edge, + ScTemplateArg const & target); /*! \brief Adds 5-element construction into template. * This is equal to `Triple` function calls: @@ -36,11 +37,12 @@ class _SC_EXTERN ScTemplateBuilder final * \param attrEdge Definition of edge that goes from attribute * \param attr Definition of attribute */ - _SC_EXTERN ScTemplateBuilder & TripleWithRelation(ScTemplateArg const & source, - ScTemplateArg const & edge, - ScTemplateArg const & target, - ScTemplateArg const & attrEdge, - ScTemplateArg const & attr); + _SC_EXTERN ScTemplateBuilder & TripleWithRelation( + ScTemplateArg const & source, + ScTemplateArg const & edge, + ScTemplateArg const & target, + ScTemplateArg const & attrEdge, + ScTemplateArg const & attr); /*! \brief Makes template based on appended triples * \return Returns pointer to created template diff --git a/sc-memory/sc-memory/sc_template_builder_impl.cpp b/sc-memory/sc-memory/sc_template_builder_impl.cpp index 03c704583..738958b0b 100644 --- a/sc-memory/sc-memory/sc_template_builder_impl.cpp +++ b/sc-memory/sc-memory/sc_template_builder_impl.cpp @@ -5,20 +5,22 @@ ScTemplateBuilderImpl::ScTemplateBuilderImpl() m_templ.Reserve(4); } -ScTemplateBuilderImpl & ScTemplateBuilderImpl::Triple(ScTemplateArg const & param1, - ScTemplateArg const & param2, - ScTemplateArg const & param3) +ScTemplateBuilderImpl & ScTemplateBuilderImpl::Triple( + ScTemplateArg const & param1, + ScTemplateArg const & param2, + ScTemplateArg const & param3) { SC_ASSERT(!m_isDone, ("Call method after Make() is not allowed")); m_templ.AddTriple(param1, param2, param3); return *this; } -ScTemplateBuilderImpl & ScTemplateBuilderImpl::TripleWithRelation(ScTemplateArg const & param1, - ScTemplateArg const & param2, - ScTemplateArg const & param3, - ScTemplateArg const & param4, - ScTemplateArg const & param5) +ScTemplateBuilderImpl & ScTemplateBuilderImpl::TripleWithRelation( + ScTemplateArg const & param1, + ScTemplateArg const & param2, + ScTemplateArg const & param3, + ScTemplateArg const & param4, + ScTemplateArg const & param5) { SC_ASSERT(!m_isDone, ("Call method after Make() is not allowed")); diff --git a/sc-memory/sc-memory/sc_template_builder_impl.hpp b/sc-memory/sc-memory/sc_template_builder_impl.hpp index 30ffbc503..c75fc01d3 100644 --- a/sc-memory/sc-memory/sc_template_builder_impl.hpp +++ b/sc-memory/sc-memory/sc_template_builder_impl.hpp @@ -11,9 +11,10 @@ class ScTemplateBuilderImpl final * param2 * param1 ----------> param3 */ - ScTemplateBuilderImpl & Triple(ScTemplateArg const & param1, - ScTemplateArg const & param2, - ScTemplateArg const & param3); + ScTemplateBuilderImpl & Triple( + ScTemplateArg const & param1, + ScTemplateArg const & param2, + ScTemplateArg const & param3); /** Adds construction: * param2 @@ -26,15 +27,16 @@ class ScTemplateBuilderImpl final * Equal to two calls of triple, so this template add 6 items to result (NOT 5), to minimize * possible abuse, use result name mapping, and get result by names */ - ScTemplateBuilderImpl & TripleWithRelation(ScTemplateArg const & param1, - ScTemplateArg const & param2, - ScTemplateArg const & param3, - ScTemplateArg const & param4, - ScTemplateArg const & param5); + ScTemplateBuilderImpl & TripleWithRelation( + ScTemplateArg const & param1, + ScTemplateArg const & param2, + ScTemplateArg const & param3, + ScTemplateArg const & param4, + ScTemplateArg const & param5); /*! Returns pointer to created template - * \remarks Do not use builder after this method call. - */ + * \remarks Do not use builder after this method call. + */ ScTemplatePtr Make(); //! Check if replacement with specified idtf exists diff --git a/sc-memory/sc-memory/sc_template_data.hpp b/sc-memory/sc-memory/sc_template_data.hpp index 29be64605..7b1cc81ca 100644 --- a/sc-memory/sc-memory/sc_template_data.hpp +++ b/sc-memory/sc-memory/sc_template_data.hpp @@ -1,7 +1,7 @@ #pragma once -#include "sc_template_arg.hpp" #include "sc_debug.hpp" +#include "sc_template_arg.hpp" class ScTemplateData { @@ -71,16 +71,14 @@ class ScTemplateData auto const it = m_repl.find(replName); if (it != m_repl.end()) { - m_repl.insert({ newAlias, it->second }); + m_repl.insert({newAlias, it->second}); return true; } return false; } - inline void AddTriple(ScTemplateArg const & src, - ScTemplateArg const & edge, - ScTemplateArg const & trg) + inline void AddTriple(ScTemplateArg const & src, ScTemplateArg const & edge, ScTemplateArg const & trg) { if (!edge.m_replacementName.empty() && (edge.m_replacementName == src.m_replacementName || edge.m_replacementName == trg.m_replacementName)) @@ -89,20 +87,18 @@ class ScTemplateData } std::array triple; - std::array elements = { &src, &edge, &trg }; + std::array elements = {&src, &edge, &trg}; for (size_t i = 0; i < elements.size(); ++i) { size_t & tripleIndex = triple[i]; ScTemplateArg const & value = *(elements[i]); - if (value.m_kind == ScTemplateArg::Kind::Type && - value.m_typeValue.IsConst()) + if (value.m_kind == ScTemplateArg::Kind::Type && value.m_typeValue.IsConst()) { SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "Using of constant types in template is restricted"); } - if (value.m_kind == ScTemplateArg::Kind::Addr && - !value.m_addrValue.IsValid()) + if (value.m_kind == ScTemplateArg::Kind::Addr && !value.m_addrValue.IsValid()) { SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "ScAddr is empty"); } @@ -111,8 +107,8 @@ class ScTemplateData { if (m_repl.find(value.m_replacementName) != m_repl.end()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "Replacement " << value.m_replacementName << " already exists"); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "Replacement " << value.m_replacementName << " already exists"); } } @@ -123,9 +119,9 @@ class ScTemplateData if (it == m_repl.end()) { tripleIndex = m_elements.size(); - m_repl.insert({ sAddr, tripleIndex }); + m_repl.insert({sAddr, tripleIndex}); if (value.HasReplacementName()) - m_repl.insert({ value.m_replacementName, tripleIndex }); + m_repl.insert({value.m_replacementName, tripleIndex}); m_elements.emplace_back(value); } @@ -138,7 +134,7 @@ class ScTemplateData { tripleIndex = m_elements.size(); if (value.HasReplacementName()) - m_repl.insert({ value.m_replacementName, tripleIndex }); + m_repl.insert({value.m_replacementName, tripleIndex}); m_elements.emplace_back(value); } @@ -147,15 +143,15 @@ class ScTemplateData auto const it = m_repl.find(value.m_replacementName); if (it == m_repl.end()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "There are no parameter with name " << value.m_replacementName); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "There are no parameter with name " << value.m_replacementName); } else { tripleIndex = it->second; } } - } // for + } // for m_triples.emplace_back(std::move(triple)); } @@ -169,9 +165,7 @@ class ScTemplateData SC_ASSERT(indecies[1] < m_elements.size(), ()); SC_ASSERT(indecies[2] < m_elements.size(), ()); - return { m_elements[indecies[0]], - m_elements[indecies[1]], - m_elements[indecies[2]] }; + return {m_elements[indecies[0]], m_elements[indecies[1]], m_elements[indecies[2]]}; } ReplacementsMap const & Replacements() const diff --git a/sc-memory/sc-memory/sc_template_generate.cpp b/sc-memory/sc-memory/sc_template_generate.cpp index 9964489b5..6d96864b9 100644 --- a/sc-memory/sc-memory/sc_template_generate.cpp +++ b/sc-memory/sc-memory/sc_template_generate.cpp @@ -7,8 +7,7 @@ class ScTemplateGenerateImpl { public: - ScTemplateGenerateImpl(ScMemoryContext & ctx, - ScTemplate::Data const & templ) + ScTemplateGenerateImpl(ScMemoryContext & ctx, ScTemplate::Data const & templ) : m_ctx(ctx) , m_templ(templ) { @@ -26,7 +25,8 @@ class ScTemplateGenerateImpl { ScTemplate::Data::Triple const & triple = m_templ.GetTriple(i); if (triple.edge.IsFixed()) - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "You can't use fixed value for edge in triple for template generation"); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "You can't use fixed value for edge in triple for template generation"); } if (!CheckParams(params)) @@ -38,7 +38,7 @@ class ScTemplateGenerateImpl auto const AddResult = [&resultBuilder, &result](ScAddr const & addr, std::string const & name) { if (name.empty()) - return; // do nothing + return; // do nothing if (!result.Has(name)) resultBuilder.Add(name, addr); @@ -107,9 +107,10 @@ class ScTemplateGenerateImpl return addr; } - ScAddr ResolveAddr(ScTemplateArg const & itemValue, - ScTemplateParams const & params, - ScTemplateNamedStruct const & result) + ScAddr ResolveAddr( + ScTemplateArg const & itemValue, + ScTemplateParams const & params, + ScTemplateNamedStruct const & result) { /// TODO: improve speed, because not all time we need to replace by params // replace by value from params @@ -187,7 +188,6 @@ class ScTemplateGenerateImpl ScAddrVector m_createdElements; }; - ScTemplateGenerate::ScTemplateGenerate(ScMemoryContext & ctx, ScTemplate const & templ) { m_impl = std::make_unique(ctx, templ.GetData()); diff --git a/sc-memory/sc-memory/sc_template_named_struct.cpp b/sc-memory/sc-memory/sc_template_named_struct.cpp index ad04d9b66..9fc98ff6c 100644 --- a/sc-memory/sc-memory/sc_template_named_struct.cpp +++ b/sc-memory/sc-memory/sc_template_named_struct.cpp @@ -15,7 +15,7 @@ bool ScTemplateNamedStruct::Has(std::string const & name) const return (m_names.find(name) != m_names.end()); } -ScAddr const & ScTemplateNamedStruct::operator [] (std::string const & name) const +ScAddr const & ScTemplateNamedStruct::operator[](std::string const & name) const { auto const it = m_names.find(name); if (it != m_names.end()) @@ -55,7 +55,7 @@ void ScTemplateNamedStruct::Builder::Add(ScAddr const & addr) uint64_t const hash = addr.Hash(); if (m_addrs.find(hash) == m_addrs.end()) { - m_addrs.insert({ hash, m_struct.m_elements.size() }); + m_addrs.insert({hash, m_struct.m_elements.size()}); m_struct.m_elements.push_back(addr); } } @@ -64,20 +64,19 @@ void ScTemplateNamedStruct::Builder::Add(std::string const & name, ScAddr const { if (m_struct.m_names.find(name) != m_struct.m_names.end()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, - "Name " << name << " already exists"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Name " << name << " already exists"); } uint64_t const hash = addr.Hash(); auto const it = m_addrs.find(hash); if (it == m_addrs.end()) { - m_struct.m_names.insert({ name, m_struct.m_elements.size() }); - m_addrs.insert({ hash, m_struct.m_elements.size() }); + m_struct.m_names.insert({name, m_struct.m_elements.size()}); + m_addrs.insert({hash, m_struct.m_elements.size()}); m_struct.m_elements.push_back(addr); } else { - m_struct.m_names.insert({ name, it->second }); + m_struct.m_names.insert({name, it->second}); } } diff --git a/sc-memory/sc-memory/sc_template_named_struct.hpp b/sc-memory/sc-memory/sc_template_named_struct.hpp index b4bed45b5..f5af0f713 100644 --- a/sc-memory/sc-memory/sc_template_named_struct.hpp +++ b/sc-memory/sc-memory/sc_template_named_struct.hpp @@ -3,8 +3,8 @@ #include "sc_addr.hpp" #include "sc_defines.hpp" -#include #include +#include #include class ScTemplateNamedStruct @@ -29,7 +29,7 @@ class ScTemplateNamedStruct _SC_EXTERN ScTemplateNamedStruct(NamesMap && names, ScAddrVector && elements); _SC_EXTERN bool Has(std::string const & name) const; - _SC_EXTERN ScAddr const & operator [] (std::string const & name) const; + _SC_EXTERN ScAddr const & operator[](std::string const & name) const; _SC_EXTERN bool IsEmpty() const; _SC_EXTERN void Clear(); @@ -40,4 +40,3 @@ class ScTemplateNamedStruct NamesMap m_names; ScAddrVector m_elements; }; - diff --git a/sc-memory/sc-memory/sc_template_params.cpp b/sc-memory/sc-memory/sc_template_params.cpp index 5aa7734ee..7a4672fc6 100644 --- a/sc-memory/sc-memory/sc_template_params.cpp +++ b/sc-memory/sc-memory/sc_template_params.cpp @@ -26,7 +26,7 @@ ScAddr ScTemplateParams::TryGet(std::string const & name) const { auto const it = m_values.find(name); if (it != m_values.end()) - return it->second; + return it->second; return {}; } @@ -36,12 +36,12 @@ ScAddr ScTemplateParams::TryGet(ScAddr const & addr) const return TryGet(addr.ToString()); } -ScAddr ScTemplateParams::operator [] (std::string const & name) const +ScAddr ScTemplateParams::operator[](std::string const & name) const { return TryGet(name); } -ScAddr ScTemplateParams::operator [] (ScAddr const & addr) const +ScAddr ScTemplateParams::operator[](ScAddr const & addr) const { return TryGet(addr); } diff --git a/sc-memory/sc-memory/sc_template_params.hpp b/sc-memory/sc-memory/sc_template_params.hpp index 5e7001bb7..8435c97da 100644 --- a/sc-memory/sc-memory/sc_template_params.hpp +++ b/sc-memory/sc-memory/sc_template_params.hpp @@ -3,20 +3,25 @@ #include "sc_addr.hpp" #include "sc_type.hpp" -#include #include +#include class ScTemplateParams { public: - using ContainerType = std::unordered_map; _SC_EXTERN ScTemplateParams & Add(std::string const & key, ScAddr const & value); _SC_EXTERN ScTemplateParams & Add(ScAddr const & key, ScAddr const & value); - _SC_EXTERN ContainerType::const_iterator begin() const { return m_values.begin(); } - _SC_EXTERN ContainerType::const_iterator end() const { return m_values.end(); } + _SC_EXTERN ContainerType::const_iterator begin() const + { + return m_values.begin(); + } + _SC_EXTERN ContainerType::const_iterator end() const + { + return m_values.end(); + } //! Check if parameters are empty _SC_EXTERN bool IsEmpty() const; @@ -32,8 +37,8 @@ class ScTemplateParams _SC_EXTERN ScAddr TryGet(ScAddr const & addr) const; /// Operators that wrap TryGet methods - _SC_EXTERN ScAddr operator [] (std::string const & name) const; - _SC_EXTERN ScAddr operator [] (ScAddr const & addr) const; + _SC_EXTERN ScAddr operator[](std::string const & name) const; + _SC_EXTERN ScAddr operator[](ScAddr const & addr) const; /*! Check if template element with type `varType` can be replaced with * parameter that have type `paramType` diff --git a/sc-memory/sc-memory/sc_template_scs_builder.cpp b/sc-memory/sc-memory/sc_template_scs_builder.cpp index 1beb7fd42..8fb33082b 100644 --- a/sc-memory/sc-memory/sc_template_scs_builder.cpp +++ b/sc-memory/sc-memory/sc_template_scs_builder.cpp @@ -4,7 +4,6 @@ #include "sc_template_builder_impl.hpp" #include "scs/scs_parser.hpp" - #include "utils/sc_keynode_cache.hpp" ScTemplateSCsBuilder::ScTemplateSCsBuilder(ScMemoryContext & ctx) @@ -74,9 +73,7 @@ ScTemplatePtr ScTemplateSCsBuilder::Make(std::string const & scsText) ScTemplateArg srcItem, edgeItem, trgItem; - if (!MakeTemplItem(src, srcItem) || - !MakeTemplItem(edge, edgeItem) || - !MakeTemplItem(trg, trgItem)) + if (!MakeTemplItem(src, srcItem) || !MakeTemplItem(edge, edgeItem) || !MakeTemplItem(trg, trgItem)) { return {}; } diff --git a/sc-memory/sc-memory/sc_template_search.cpp b/sc-memory/sc-memory/sc_template_search.cpp index 9636414f3..d4c8dabd8 100644 --- a/sc-memory/sc-memory/sc_template_search.cpp +++ b/sc-memory/sc-memory/sc_template_search.cpp @@ -9,10 +9,11 @@ class ScTemplateSearchImpl { public: - ScTemplateSearchImpl(ScTemplate::Data const & templ, - ScMemoryContext & context, - ScAddr const & scStruct, - ScTemplateNamedStruct & result) + ScTemplateSearchImpl( + ScTemplate::Data const & templ, + ScMemoryContext & context, + ScAddr const & scStruct, + ScTemplateNamedStruct & result) : m_templ(templ) , m_context(context) , m_struct(scStruct) @@ -48,9 +49,9 @@ class ScTemplateSearchImpl static const size_t kScoreOther = 1; /** First of all we need to calculate scores for all triples - * (more scores - should be search first). - * Also need to store all replacements that need to be resolved - */ + * (more scores - should be search first). + * Also need to store all replacements that need to be resolved + */ std::vector tripleScores(m_templ.TriplesNum()); std::unordered_map> replDependMap; for (size_t i = 0; i < m_templ.TriplesNum(); ++i) @@ -62,7 +63,7 @@ class ScTemplateSearchImpl if (constr.edge.IsAddr() && constr.source.IsAssign() && constr.target.IsAssign()) score += kScoreEdge; else if (constr.source.IsAddr() && constr.edge.IsAssign() && constr.target.IsAddr()) - score += kScoreOther * 2; // should be a sum of (f_a_a and a_a_f) + score += kScoreOther * 2; // should be a sum of (f_a_a and a_a_f) else if (constr.source.IsAddr() || constr.target.IsAddr()) score += kScoreOther; @@ -85,10 +86,13 @@ class ScTemplateSearchImpl } // sort by scores - std::sort(preCache.begin(), preCache.end(), [&](size_t a, size_t b) - { - return (tripleScores[a] > tripleScores[b]); - }); + std::sort( + preCache.begin(), + preCache.end(), + [&](size_t a, size_t b) + { + return (tripleScores[a] > tripleScores[b]); + }); // now we need to append triples, in order, when previous resolve replacement for a next one std::vector & cache = m_state.processOrder; @@ -109,7 +113,7 @@ class ScTemplateSearchImpl // get resolved replacements by the last triple std::vector resolvedReplacements; resolvedReplacements.reserve(3); - for (auto const & value : { triple.source, triple.edge, triple.target }) + for (auto const & value : {triple.source, triple.edge, triple.target}) { if (!value.m_replacementName.empty()) resolvedReplacements.emplace_back(value.m_replacementName); @@ -217,66 +221,48 @@ class ScTemplateSearchImpl { if (!edgeAddr.IsValid()) { - if (targetAddr.IsValid()) // F_A_F + if (targetAddr.IsValid()) // F_A_F { - return m_context.Iterator3( - sourceAddr, - PrepareType(triple.edge.m_typeValue), - targetAddr); + return m_context.Iterator3(sourceAddr, PrepareType(triple.edge.m_typeValue), targetAddr); } - else // F_A_A + else // F_A_A { return m_context.Iterator3( - sourceAddr, - PrepareType(triple.edge.m_typeValue), - PrepareType(triple.target.m_typeValue)); + sourceAddr, PrepareType(triple.edge.m_typeValue), PrepareType(triple.target.m_typeValue)); } } else { - if (targetAddr.IsValid()) // F_F_F + if (targetAddr.IsValid()) // F_F_F { - return m_context.Iterator3( - sourceAddr, - edgeAddr, - targetAddr); + return m_context.Iterator3(sourceAddr, edgeAddr, targetAddr); } - else // F_F_A + else // F_F_A { - return m_context.Iterator3( - sourceAddr, - edgeAddr, - PrepareType(triple.target.m_typeValue)); + return m_context.Iterator3(sourceAddr, edgeAddr, PrepareType(triple.target.m_typeValue)); } } } else if (targetAddr.IsValid()) { - if (edgeAddr.IsValid()) // A_F_F + if (edgeAddr.IsValid()) // A_F_F { - return m_context.Iterator3( - PrepareType(triple.source.m_typeValue), - edgeAddr, - targetAddr); + return m_context.Iterator3(PrepareType(triple.source.m_typeValue), edgeAddr, targetAddr); } - else // A_A_F + else // A_A_F { return m_context.Iterator3( - PrepareType(triple.source.m_typeValue), - PrepareType(triple.edge.m_typeValue), - targetAddr); + PrepareType(triple.source.m_typeValue), PrepareType(triple.edge.m_typeValue), targetAddr); } } - else if (edgeAddr.IsValid() && !targetAddr.IsValid()) // A_F_A + else if (edgeAddr.IsValid() && !targetAddr.IsValid()) // A_F_A { return m_context.Iterator3( - PrepareType(triple.source.m_typeValue), - edgeAddr, - PrepareType(triple.target.m_typeValue)); + PrepareType(triple.source.m_typeValue), edgeAddr, PrepareType(triple.target.m_typeValue)); } //// unknown iterator type - //SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Unknown iterator type"); + // SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Unknown iterator type"); return ScIterator3Ptr(); } @@ -321,7 +307,7 @@ class ScTemplateSearchImpl auto it = m_repls.find(item.m_replacementName); if (it == m_repls.end()) { - m_repls[item.m_replacementName] = { addr, 1 }; + m_repls[item.m_replacementName] = {addr, 1}; } else { @@ -333,7 +319,7 @@ class ScTemplateSearchImpl bool DoIter() { if (m_state.isFinished) - return false; // do nothing + return false; // do nothing bool found = false; do @@ -376,16 +362,13 @@ class ScTemplateSearchImpl ScAddr const addr3 = it->Get(2); // check if search in structure - if (m_struct.IsValid() && - (!CheckInStruct(addr1) || - !CheckInStruct(addr2) || - !CheckInStruct(addr3))) + if (m_struct.IsValid() && (!CheckInStruct(addr1) || !CheckInStruct(addr2) || !CheckInStruct(addr3))) { - continue; + continue; } auto const res = m_usedEdges.insert(addr2); - if (!res.second) // don't iterate the same edge twicely + if (!res.second) // don't iterate the same edge twicely continue; m_state.edges[orderIndex] = addr2; @@ -415,17 +398,18 @@ class ScTemplateSearchImpl break; } - if (isFinished) // finish iterator + if (isFinished) // finish iterator { m_state.iterators.pop(); m_state.newIteration = false; } } - else // special checks and search + else // special checks and search { SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Invalid state during template search"); } - } while (!found && !m_state.iterators.empty()); + } + while (!found && !m_state.iterators.empty()); if (m_state.iterators.empty()) m_state.isFinished = true; @@ -461,29 +445,26 @@ class ScTemplateSearchImpl }; std::unordered_map m_repls; - - InternalState m_state; ScTemplateNamedStruct & m_result; }; - -bool ScTemplateSearch::Iterator::operator == (Iterator const & other) const +bool ScTemplateSearch::Iterator::operator==(Iterator const & other) const { return (m_index == other.m_index); } -bool ScTemplateSearch::Iterator::operator != (Iterator const & other) const +bool ScTemplateSearch::Iterator::operator!=(Iterator const & other) const { return !(*this == other); } -ScTemplateSearch::Iterator & ScTemplateSearch::Iterator::operator ++ () +ScTemplateSearch::Iterator & ScTemplateSearch::Iterator::operator++() { auto const result = m_search.DoIter(); if (result) { - m_index = (m_index + 1) % kEndIndex; // don't use maximum index + m_index = (m_index + 1) % kEndIndex; // don't use maximum index } else { @@ -494,7 +475,7 @@ ScTemplateSearch::Iterator & ScTemplateSearch::Iterator::operator ++ () return *this; } -ScTemplateNamedStruct const & ScTemplateSearch::Iterator::operator * () const +ScTemplateNamedStruct const & ScTemplateSearch::Iterator::operator*() const { return m_struct; } @@ -511,10 +492,11 @@ ScAddr ScTemplateSearch::Iterator::operator[](ScAddr const & addr) const // -------------------------------------- -ScTemplateSearch::ScTemplateSearch(ScMemoryContext & ctx, - ScTemplate const & templ, - ScTemplateParams const & params /* = {} */, - ScAddr const & structAddr /* = ScAddr::Empty */) +ScTemplateSearch::ScTemplateSearch( + ScMemoryContext & ctx, + ScTemplate const & templ, + ScTemplateParams const & params /* = {} */, + ScAddr const & structAddr /* = ScAddr::Empty */) : m_ctx(ctx) , m_template(templ) , m_structAddr(structAddr) @@ -533,10 +515,7 @@ ScTemplateSearch::Iterator ScTemplateSearch::begin() ApplyParameters(); m_impl = std::make_unique( - m_templateWithParams ? m_templateWithParams->GetData() : m_template.GetData(), - m_ctx, - m_structAddr, - m_result); + m_templateWithParams ? m_templateWithParams->GetData() : m_template.GetData(), m_ctx, m_structAddr, m_result); m_impl->Reset(); if (m_impl->DoIter()) @@ -552,13 +531,13 @@ ScTemplateSearch::Iterator ScTemplateSearch::end() std::pair ScTemplateSearch::DoStep() { - return { m_result, m_impl->DoIter() }; + return {m_result, m_impl->DoIter()}; } void ScTemplateSearch::ApplyParameters() { if (m_params.IsEmpty()) - return; // do nothing + return; // do nothing // Create new template ScTemplate::Data newData = m_template.GetData(); @@ -571,27 +550,27 @@ void ScTemplateSearch::ApplyParameters() { if (!item->IsType()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "Please assign values just only to type items of template. Parameter: " << param.first); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, + "Please assign values just only to type items of template. Parameter: " << param.first); } - else if (!item->m_typeValue.IsVar()) // this case is impossible because of template builder checks + else if (!item->m_typeValue.IsVar()) // this case is impossible because of template builder checks { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "Can't assign value to non variable item. Parameter: " << param.first); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "Can't assign value to non variable item. Parameter: " << param.first); } // check types compatibility ScType const paramType = m_ctx.GetElementType(param.second); if (paramType.IsVar()) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "Do not use variable as parameter value. Parameter: " << param.first); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidParams, "Do not use variable as parameter value. Parameter: " << param.first); } if (!ScTemplateParams::CanAssignParam(item->m_typeValue, paramType)) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, - "Type of " << param.first << " is not compatible"); + SC_THROW_EXCEPTION(utils::ExceptionInvalidParams, "Type of " << param.first << " is not compatible"); } item->m_kind = ScTemplateArg::Kind::Addr; @@ -600,8 +579,7 @@ void ScTemplateSearch::ApplyParameters() } else { - SC_THROW_EXCEPTION(utils::ExceptionItemNotFound, - "Can't find replacement for the parameter " << param.first); + SC_THROW_EXCEPTION(utils::ExceptionItemNotFound, "Can't find replacement for the parameter " << param.first); } } diff --git a/sc-memory/sc-memory/sc_template_search.hpp b/sc-memory/sc-memory/sc_template_search.hpp index f709ee42b..2bd7823b7 100644 --- a/sc-memory/sc-memory/sc_template_search.hpp +++ b/sc-memory/sc-memory/sc_template_search.hpp @@ -7,7 +7,6 @@ #include #include - class ScTemplateSearchImpl; /*! @@ -16,28 +15,25 @@ class ScTemplateSearchImpl; class ScTemplateSearch final { public: - class Iterator - { + class Iterator + { friend class ScTemplateSearch; protected: static size_t const kEndIndex = std::numeric_limits::max(); - Iterator(ScTemplateSearchImpl & search, - ScTemplateNamedStruct & namedStruct, - size_t idx = kEndIndex) - : m_search(search) - , m_struct(namedStruct) - , m_index(idx) + Iterator(ScTemplateSearchImpl & search, ScTemplateNamedStruct & namedStruct, size_t idx = kEndIndex) + : m_search(search) + , m_struct(namedStruct) + , m_index(idx) { } public: - - bool operator == (Iterator const & other) const; - bool operator != (Iterator const & other) const; - Iterator & operator ++ (); - ScTemplateNamedStruct const & operator * () const; + bool operator==(Iterator const & other) const; + bool operator!=(Iterator const & other) const; + Iterator & operator++(); + ScTemplateNamedStruct const & operator*() const; ScAddr operator[](std::string const & name) const; ScAddr operator[](ScAddr const & addr) const; @@ -49,10 +45,11 @@ class ScTemplateSearch final size_t m_index = std::numeric_limits::max(); }; - ScTemplateSearch(ScMemoryContext & ctx, - ScTemplate const & templ, - ScTemplateParams const & params = {}, - ScAddr const & structAddr = ScAddr::Empty); + ScTemplateSearch( + ScMemoryContext & ctx, + ScTemplate const & templ, + ScTemplateParams const & params = {}, + ScAddr const & structAddr = ScAddr::Empty); ~ScTemplateSearch(); Iterator begin(); diff --git a/sc-memory/sc-memory/sc_template_struct_builder.cpp b/sc-memory/sc-memory/sc_template_struct_builder.cpp index be728208a..1887d9c3b 100644 --- a/sc-memory/sc-memory/sc_template_struct_builder.cpp +++ b/sc-memory/sc-memory/sc_template_struct_builder.cpp @@ -5,7 +5,6 @@ namespace { - class ObjectInfo { public: @@ -18,10 +17,19 @@ class ObjectInfo { } - inline bool IsEdge() const { return m_type.IsEdge(); } + inline bool IsEdge() const + { + return m_type.IsEdge(); + } - inline ObjectInfo const * GetSource() const { return m_source; } - inline ObjectInfo const * GetTarget() const { return m_target; } + inline ObjectInfo const * GetSource() const + { + return m_source; + } + inline ObjectInfo const * GetTarget() const + { + return m_target; + } inline std::string GetIdtf() const { @@ -33,20 +41,34 @@ class ObjectInfo return {}; } - inline ScAddr const & GetAddr() const { return m_addr; } - inline ScType const & GetType() const { return m_type; } - inline ScAddr::HashType GetAddrHash() const { return m_addr.Hash(); } + inline ScAddr const & GetAddr() const + { + return m_addr; + } + inline ScType const & GetType() const + { + return m_type; + } + inline ScAddr::HashType GetAddrHash() const + { + return m_addr.Hash(); + } - inline void SetSource(ObjectInfo * src) { m_source = src; } - inline void SetTarget(ObjectInfo * trg) { m_target = trg; } + inline void SetSource(ObjectInfo * src) + { + m_source = src; + } + inline void SetTarget(ObjectInfo * trg) + { + m_target = trg; + } inline uint32_t CalculateEdgeRank() const { SC_ASSERT(IsEdge(), ()); SC_ASSERT(m_source, ()); SC_ASSERT(m_target, ()); - return (m_source->GetType().IsConst() ? 1 : 0) + - (m_target->GetType().IsConst() ? 1 : 0); + return (m_source->GetType().IsConst() ? 1 : 0) + (m_target->GetType().IsConst() ? 1 : 0); } private: @@ -85,7 +107,7 @@ class EdgeLessFunctor return false; } - bool operator() (size_t const indexA, size_t const indexB) const + bool operator()(size_t const indexA, size_t const indexB) const { ObjectInfo const & objA = m_objects[indexA]; ObjectInfo const & objB = m_objects[indexB]; @@ -116,8 +138,7 @@ class EdgeLessFunctor ObjectVector const & m_objects; }; -} // namespace - +} // namespace ScTemplateStructBuilder::ScTemplateStructBuilder(ScMemoryContext & ctx) : m_ctx(ctx) @@ -146,10 +167,7 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) objects.reserve(128); size_t index = 0; - ScIterator3Ptr iter = m_ctx.Iterator3( - structAddr, - ScType::EdgeAccessConstPosPerm, - ScType::Unknown); + ScIterator3Ptr iter = m_ctx.Iterator3(structAddr, ScType::EdgeAccessConstPosPerm, ScType::Unknown); while (iter->Next()) { @@ -158,7 +176,7 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) auto const it = addrToObjectIndex.find(objHash); if (it != addrToObjectIndex.end()) - continue; // object already exist + continue; // object already exist addrToObjectIndex[objHash] = objects.size(); @@ -195,9 +213,9 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) auto const itSrc = addrToObjectIndex.find(src.Hash()); if (itSrc == addrToObjectIndex.end()) { - m_errorMessage = "Source element " + std::to_string(src.Hash()) + - " of edge " + std::to_string(obj.GetAddrHash()) + - " is not a part of the same structure " + std::to_string(structAddr.Hash()); + m_errorMessage = "Source element " + std::to_string(src.Hash()) + " of edge " + + std::to_string(obj.GetAddrHash()) + " is not a part of the same structure " + + std::to_string(structAddr.Hash()); return {}; } @@ -205,9 +223,9 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) auto const itTrg = addrToObjectIndex.find(trg.Hash()); if (itTrg == addrToObjectIndex.end()) { - m_errorMessage = "Target element " + std::to_string(trg.Hash()) + - " of edge " + std::to_string(obj.GetAddrHash()) + - " is not a part of the same structure " + std::to_string(structAddr.Hash()); + m_errorMessage = "Target element " + std::to_string(trg.Hash()) + " of edge " + + std::to_string(obj.GetAddrHash()) + " is not a part of the same structure " + + std::to_string(structAddr.Hash()); return {}; } @@ -216,9 +234,9 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) ObjectInfo * trgObj = &(objects[itTrg->second]); if (srcObj->IsEdge()) - edgeDependMap.insert({ obj.GetAddr().Hash(), srcObj->GetAddr().Hash() }); + edgeDependMap.insert({obj.GetAddr().Hash(), srcObj->GetAddr().Hash()}); if (trgObj->IsEdge()) - edgeDependMap.insert({ obj.GetAddr().Hash(), srcObj->GetAddr().Hash() }); + edgeDependMap.insert({obj.GetAddr().Hash(), srcObj->GetAddr().Hash()}); obj.SetSource(srcObj); obj.SetTarget(trgObj); @@ -254,43 +272,31 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) if (trgType.IsConst()) // F_A_F { m_builder->Triple( - src->GetAddr() >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trg->GetAddr() >> WrapIdtf(*trg)); + src->GetAddr() >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trg->GetAddr() >> WrapIdtf(*trg)); } else { - if (m_builder->HasReplacement(trg->GetIdtf())) // F_A_F + if (m_builder->HasReplacement(trg->GetIdtf())) // F_A_F { - m_builder->Triple( - src->GetAddr() >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trg->GetIdtf()); + m_builder->Triple(src->GetAddr() >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trg->GetIdtf()); } - else // F_A_A + else // F_A_A { - m_builder->Triple( - src->GetAddr() >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trgType >> WrapIdtf(*trg)); + m_builder->Triple( + src->GetAddr() >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trgType >> WrapIdtf(*trg)); } } } else if (trgType.IsConst()) { - if (m_builder->HasReplacement(src->GetIdtf())) // F_A_F + if (m_builder->HasReplacement(src->GetIdtf())) // F_A_F { - m_builder->Triple( - src->GetIdtf(), - edge.GetType() >> WrapIdtf(edge), - trg->GetAddr() >> WrapIdtf(*trg)); + m_builder->Triple(src->GetIdtf(), edge.GetType() >> WrapIdtf(edge), trg->GetAddr() >> WrapIdtf(*trg)); } - else // A_A_F + else // A_A_F { m_builder->Triple( - srcType >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trg->GetAddr() >> WrapIdtf(*trg)); + srcType >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trg->GetAddr() >> WrapIdtf(*trg)); } } else @@ -298,39 +304,27 @@ ScTemplatePtr ScTemplateStructBuilder::Make(ScAddr const & structAddr) bool const srcRepl = m_builder->HasReplacement(src->GetIdtf()); bool const trgRepl = m_builder->HasReplacement(trg->GetIdtf()); - if (srcRepl && trgRepl) // F_A_F + if (srcRepl && trgRepl) // F_A_F { - m_builder->Triple( - src->GetIdtf(), - edge.GetType() >> WrapIdtf(edge), - trg->GetIdtf()); + m_builder->Triple(src->GetIdtf(), edge.GetType() >> WrapIdtf(edge), trg->GetIdtf()); } - else if (!srcRepl && trgRepl) // A_A_F + else if (!srcRepl && trgRepl) // A_A_F { - m_builder->Triple( - srcType >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trg->GetIdtf()); + m_builder->Triple(srcType >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trg->GetIdtf()); } - else if (srcRepl && !trgRepl) // F_A_A + else if (srcRepl && !trgRepl) // F_A_A { - m_builder->Triple( - src->GetIdtf(), - edge.GetType() >> WrapIdtf(edge), - trgType >> WrapIdtf(*trg)); + m_builder->Triple(src->GetIdtf(), edge.GetType() >> WrapIdtf(edge), trgType >> WrapIdtf(*trg)); } else { - m_builder->Triple( - srcType >> WrapIdtf(*src), - edge.GetType() >> WrapIdtf(edge), - trgType >> WrapIdtf(*trg)); + m_builder->Triple(srcType >> WrapIdtf(*src), edge.GetType() >> WrapIdtf(edge), trgType >> WrapIdtf(*trg)); } } // Add addr aliases /// TODO: Implement this in better way - std::array elements = { src, &edge, trg }; + std::array elements = {src, &edge, trg}; for (ObjectInfo const * e : elements) { SC_ASSERT(e->GetAddr(), ()); diff --git a/sc-memory/sc-memory/sc_timer.cpp b/sc-memory/sc-memory/sc_timer.cpp index fa8ed46bf..3b3dc7816 100644 --- a/sc-memory/sc-memory/sc_timer.cpp +++ b/sc-memory/sc-memory/sc_timer.cpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_timer.hpp" @@ -22,4 +22,3 @@ bool ScTimer::IsTimeOut() const { return ((m_timeOutSec > 0) && (Seconds() > m_timeOutSec)); } - diff --git a/sc-memory/sc-memory/sc_timer.hpp b/sc-memory/sc-memory/sc_timer.hpp index 90818f238..bdb30fd7e 100644 --- a/sc-memory/sc-memory/sc_timer.hpp +++ b/sc-memory/sc-memory/sc_timer.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once diff --git a/sc-memory/sc-memory/sc_type.cpp b/sc-memory/sc-memory/sc_type.cpp index f36938d28..4e1174936 100644 --- a/sc-memory/sc-memory/sc_type.cpp +++ b/sc-memory/sc-memory/sc_type.cpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_type.hpp" @@ -20,7 +20,6 @@ ScType const ScType::EdgeAccessConstPosTemp(sc_type_const | sc_type_arc_access | ScType const ScType::EdgeAccessConstNegTemp(sc_type_const | sc_type_arc_access | sc_type_arc_temp | sc_type_arc_neg); ScType const ScType::EdgeAccessConstFuzTemp(sc_type_const | sc_type_arc_access | sc_type_arc_temp | sc_type_arc_fuz); - ScType const ScType::EdgeUCommonVar(sc_type_edge_common | sc_type_var); ScType const ScType::EdgeDCommonVar(sc_type_arc_common | sc_type_var); ScType const ScType::EdgeAccessVarPosPerm(sc_type_var | sc_type_arc_access | sc_type_arc_perm | sc_type_arc_pos); diff --git a/sc-memory/sc-memory/sc_type.hpp b/sc-memory/sc-memory/sc_type.hpp index 4782981b5..fd2ae31c0 100644 --- a/sc-memory/sc-memory/sc_type.hpp +++ b/sc-memory/sc-memory/sc_type.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once @@ -11,25 +11,24 @@ extern "C" #include "sc-core/sc_memory.h" } -#include -#include -#include -#include -#include -#include +#include "sc_defines.hpp" + #include -#include -#include #include -#include #include - #include - -#include "sc_defines.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include #if SC_IS_PLATFORM_WIN32 -#define NOMINMAX +# define NOMINMAX #endif class ScMemoryContext; @@ -40,7 +39,8 @@ class _SC_EXTERN ScType public: using RealType = sc_type; - explicit ScType() : m_realType(0) + explicit ScType() + : m_realType(0) { } @@ -49,58 +49,106 @@ class _SC_EXTERN ScType { } - inline bool IsEdge() const { return (m_realType & sc_type_arc_mask) != 0; } - inline bool IsNode() const { return (m_realType & sc_type_node) != 0; } - inline bool IsLink() const { return (m_realType & sc_type_link) != 0; } - inline bool IsConst() const { return (m_realType & sc_type_const) != 0; } - inline bool IsVar() const { return (m_realType & sc_type_var) != 0; } + inline bool IsEdge() const + { + return (m_realType & sc_type_arc_mask) != 0; + } + inline bool IsNode() const + { + return (m_realType & sc_type_node) != 0; + } + inline bool IsLink() const + { + return (m_realType & sc_type_link) != 0; + } + inline bool IsConst() const + { + return (m_realType & sc_type_const) != 0; + } + inline bool IsVar() const + { + return (m_realType & sc_type_var) != 0; + } SC_DEPRECATED(0.4.0, "Use !IsUnknown() instead") - inline bool IsValid() const { return !IsUnknown(); } + inline bool IsValid() const + { + return !IsUnknown(); + } - inline bool IsUnknown() const { return (m_realType == 0); } + inline bool IsUnknown() const + { + return (m_realType == 0); + } - inline bool HasConstancyFlag() const { return (m_realType & sc_type_constancy_mask) != 0; } + inline bool HasConstancyFlag() const + { + return (m_realType & sc_type_constancy_mask) != 0; + } // Returns copy of this type, but with variable raplaced to const - inline ScType AsConst() const { return ScType((m_realType & ~sc_type_var) | sc_type_const); } + inline ScType AsConst() const + { + return ScType((m_realType & ~sc_type_var) | sc_type_const); + } // Returns copy of this type, but replace constancy type upward (metavar -> var -> const) inline ScType UpConstType() const { /// TODO: metavar - //if (isVar()) - return ScType((m_realType & ~sc_type_var) | sc_type_const); // copied from asConst for maximum perfomance + // if (isVar()) + return ScType((m_realType & ~sc_type_var) | sc_type_const); // copied from asConst for maximum perfomance } - inline sc_type operator * () const { return m_realType; } + inline sc_type operator*() const + { + return m_realType; + } - ScType & operator() (RealType bits) + ScType & operator()(RealType bits) { m_realType |= bits; return *this; } - inline bool operator == (ScType const & other) { return (m_realType == other.m_realType); } - inline bool operator != (ScType const & other) { return (m_realType != other.m_realType); } - inline RealType BitAnd(RealType const & inMask) const { return (m_realType & inMask); } + inline bool operator==(ScType const & other) + { + return (m_realType == other.m_realType); + } + inline bool operator!=(ScType const & other) + { + return (m_realType != other.m_realType); + } + inline RealType BitAnd(RealType const & inMask) const + { + return (m_realType & inMask); + } - inline ScType operator | (ScType const & other) { return ScType(m_realType | other.m_realType); } - inline ScType operator & (ScType const & other) { return ScType(m_realType & other.m_realType); } + inline ScType operator|(ScType const & other) + { + return ScType(m_realType | other.m_realType); + } + inline ScType operator&(ScType const & other) + { + return ScType(m_realType & other.m_realType); + } - inline ScType & operator |= (ScType const & other) + inline ScType & operator|=(ScType const & other) { m_realType |= other.m_realType; return *this; } - inline ScType & operator &= (ScType const & other) + inline ScType & operator&=(ScType const & other) { m_realType &= other.m_realType; return *this; } - operator RealType () const { return m_realType; } + operator RealType() const + { + return m_realType; + } /* Check if specified type can be extended by another one to be a valid type/ * For example this function returns false, if you try to extend node by @@ -173,19 +221,19 @@ class _SC_EXTERN ScType public: static ScType const EdgeUCommon; static ScType const EdgeDCommon; - + static ScType const EdgeUCommonConst; static ScType const EdgeDCommonConst; - + static ScType const EdgeAccess; - + static ScType const EdgeAccessConstPosPerm; static ScType const EdgeAccessConstNegPerm; static ScType const EdgeAccessConstFuzPerm; static ScType const EdgeAccessConstPosTemp; static ScType const EdgeAccessConstNegTemp; static ScType const EdgeAccessConstFuzTemp; - + static ScType const EdgeUCommonVar; static ScType const EdgeDCommonVar; static ScType const EdgeAccessVarPosPerm; @@ -194,14 +242,14 @@ class _SC_EXTERN ScType static ScType const EdgeAccessVarPosTemp; static ScType const EdgeAccessVarNegTemp; static ScType const EdgeAccessVarFuzTemp; - + static ScType const Const; static ScType const Var; - + static ScType const Node; static ScType const Link; static ScType const Unknown; - + static ScType const NodeConst; static ScType const NodeVar; @@ -215,7 +263,7 @@ class _SC_EXTERN ScType static ScType const NodeClass; static ScType const NodeAbstract; static ScType const NodeMaterial; - + static ScType const NodeConstStruct; static ScType const NodeConstTuple; static ScType const NodeConstRole; @@ -223,7 +271,7 @@ class _SC_EXTERN ScType static ScType const NodeConstClass; static ScType const NodeConstAbstract; static ScType const NodeConstMaterial; - + static ScType const NodeVarStruct; static ScType const NodeVarTuple; static ScType const NodeVarRole; diff --git a/sc-memory/sc-memory/sc_utils.cpp b/sc-memory/sc-memory/sc_utils.cpp index 40523b6f4..52569c35c 100644 --- a/sc-memory/sc-memory/sc_utils.cpp +++ b/sc-memory/sc-memory/sc_utils.cpp @@ -13,24 +13,15 @@ namespace utils { - void StringUtils::ToLowerCase(std::string & str) { - std::transform( - str.begin(), - str.end(), - str.begin(), - tolower); + std::transform(str.begin(), str.end(), str.begin(), tolower); } //----------------------------------------------------------------------- void StringUtils::ToUpperCase(std::string & str) { - std::transform( - str.begin(), - str.end(), - str.begin(), - toupper); + std::transform(str.begin(), str.end(), str.begin(), toupper); } bool StringUtils::StartsWith(std::string const & str, std::string const & pattern, bool lowerCase) @@ -89,7 +80,6 @@ void StringUtils::SplitFilename(std::string const & qualifiedName, std::string & outBasename = path.substr(i + 1, path.size() - i - 1); outPath = path.substr(0, i + 1); } - } void StringUtils::SplitString(std::string const & str, char delim, std::vector & outList) @@ -103,75 +93,80 @@ void StringUtils::SplitString(std::string const & str, char delim, std::vector 1023) { - //if source path is to long ensure we don't do a buffer overrun by allocating some - //new memory + // if source path is to long ensure we don't do a buffer overrun by allocating some + // new memory isDestAllocated = true; bufferDst = new char[pathLen + 1]; } - //The outer loop loops over directories + // The outer loop loops over directories while (indexSrc < pathLen) { if ((bufferSrc[indexSrc] == '\\') || (bufferSrc[indexSrc] == '/')) { - //check if we have a directory delimiter if so skip it (we should already - //have written such a delimiter by this point + // check if we have a directory delimiter if so skip it (we should already + // have written such a delimiter by this point ++indexSrc; continue; } else { - //check if there is a directory to skip of type ".\" - if ((bufferSrc[indexSrc] == '.') && - ((bufferSrc[indexSrc + 1] == '\\') || (bufferSrc[indexSrc + 1] == '/'))) + // check if there is a directory to skip of type ".\" + if ((bufferSrc[indexSrc] == '.') && ((bufferSrc[indexSrc + 1] == '\\') || (bufferSrc[indexSrc + 1] == '/'))) { indexSrc += 2; continue; } - //check if there is a directory to skip of type "..\" - else if ((bufferSrc[indexSrc] == '.') && (bufferSrc[indexSrc + 1] == '.') && - ((bufferSrc[indexSrc + 2] == '\\') || (bufferSrc[indexSrc + 2] == '/'))) + // check if there is a directory to skip of type "..\" + else if ( + (bufferSrc[indexSrc] == '.') && (bufferSrc[indexSrc + 1] == '.') && + ((bufferSrc[indexSrc + 2] == '\\') || (bufferSrc[indexSrc + 2] == '/'))) { if (indexDst > metaPathArea) { - //skip a directory backward in the destination path - do { + // skip a directory backward in the destination path + do + { --indexDst; - } while ((indexDst > metaPathArea) && (bufferDst[indexDst - 1] != '/')); + } + while ((indexDst > metaPathArea) && (bufferDst[indexDst - 1] != '/')); indexSrc += 3; continue; } else { - //we are about to write "..\" to the destination buffer - //ensure we will not remove this in future "skip directories" + // we are about to write "..\" to the destination buffer + // ensure we will not remove this in future "skip directories" metaPathArea += 3; } } } - //transfer the current directory name from the source to the destination + // transfer the current directory name from the source to the destination while (indexSrc < pathLen) { char curChar = bufferSrc[indexSrc]; - if (makeLowerCase) curChar = tolower(curChar); - if ((curChar == '\\') || (curChar == '/')) curChar = '/'; + if (makeLowerCase) + curChar = tolower(curChar); + if ((curChar == '\\') || (curChar == '/')) + curChar = '/'; bufferDst[indexDst] = curChar; ++indexDst; ++indexSrc; - if (curChar == '/') break; + if (curChar == '/') + break; } } bufferDst[indexDst] = 0; @@ -185,8 +180,10 @@ std::string StringUtils::NormalizeFilePath(std::string const & init, bool makeLo return normalized; } - -std::string StringUtils::ReplaceAll(std::string const & source, std::string const & replaceWhat, std::string const & replaceWithWhat) +std::string StringUtils::ReplaceAll( + std::string const & source, + std::string const & replaceWhat, + std::string const & replaceWithWhat) { std::string result = source; std::string::size_type pos = 0; @@ -242,4 +239,4 @@ int Random::Int() return std::rand(); } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/sc_utils.hpp b/sc-memory/sc-memory/sc_utils.hpp index 0b427ec7c..c775f5040 100644 --- a/sc-memory/sc-memory/sc_utils.hpp +++ b/sc-memory/sc-memory/sc_utils.hpp @@ -8,29 +8,26 @@ #include "sc_debug.hpp" +#include #include #include +#include #include #include -#include -#include - - // Got it there: https://github.com/mapsme/omim/blob/136f12af3adde05623008f71d07bb996fe5801a5/base/macros.hpp #define ARRAY_SIZE(X) sizeof(::my::impl::ArraySize(X)) -#define SC_DISALLOW_COPY(className) \ - className(className const &) = delete; \ +#define SC_DISALLOW_COPY(className) \ + className(className const &) = delete; \ className & operator=(className const &) = delete - -#define SC_DISALLOW_MOVE(className) \ - className(className &&) = delete; \ +#define SC_DISALLOW_MOVE(className) \ + className(className &&) = delete; \ className & operator=(className &&) = delete -#define SC_DISALLOW_COPY_AND_MOVE(className) \ - SC_DISALLOW_COPY(className); \ +#define SC_DISALLOW_COPY_AND_MOVE(className) \ + SC_DISALLOW_COPY(className); \ SC_DISALLOW_MOVE(className) // ---------------- Reference counter ----------- @@ -59,8 +56,7 @@ class RefCount uint32_t m_refCount; }; - -#define SHARED_PTR_TYPE(__type) using __type##Ptr = std::shared_ptr< __type >; +#define SHARED_PTR_TYPE(__type) using __type##Ptr = std::shared_ptr<__type>; class MemoryBuffer { @@ -71,11 +67,23 @@ class MemoryBuffer { } - inline bool IsValid() const { return m_data != nullptr; } + inline bool IsValid() const + { + return m_data != nullptr; + } - void * Data() { return static_cast(m_data); } - void const * CData() const { return static_cast(m_data); } - size_t Size() const { return m_size; } + void * Data() + { + return static_cast(m_data); + } + void const * CData() const + { + return static_cast(m_data); + } + size_t Size() const + { + return m_size; + } size_t Read(void * buff, size_t size) const { @@ -98,7 +106,8 @@ class MemoryBuffer class MemoryBufferSafe : public MemoryBuffer { public: - MemoryBufferSafe() : MemoryBuffer() + MemoryBufferSafe() + : MemoryBuffer() { } @@ -138,27 +147,65 @@ class MemoryBufferSafe : public MemoryBuffer SHARED_PTR_TYPE(MemoryBuffer) SHARED_PTR_TYPE(MemoryBufferSafe) - namespace utils { - namespace impl { -template inline T toNumber(std::string const & value); - -template <> inline int8_t toNumber(std::string const & value) { return int8_t(std::stol(value)); } -template <> inline int16_t toNumber(std::string const & value) { return int16_t(std::stol(value)); } -template <> inline int32_t toNumber(std::string const & value) { return int32_t(std::stol(value)); } -template <> inline int64_t toNumber(std::string const & value) { return int64_t(std::stoll(value)); } -template <> inline uint8_t toNumber(std::string const & value) { return uint8_t(std::stoul(value)); } -template <> inline uint16_t toNumber(std::string const & value) { return uint16_t(std::stoul(value)); } -template <> inline uint32_t toNumber(std::string const & value) { return uint32_t(std::stoul(value)); } -template <> inline uint64_t toNumber(std::string const & value) { return uint64_t(std::stoull(value)); } -template <> inline float toNumber(std::string const & value) { return std::stof(value); } -template <> inline double toNumber(std::string const & value) { return std::stod(value); } +template +inline T toNumber(std::string const & value); -} // namespace impl +template <> +inline int8_t toNumber(std::string const & value) +{ + return int8_t(std::stol(value)); +} +template <> +inline int16_t toNumber(std::string const & value) +{ + return int16_t(std::stol(value)); +} +template <> +inline int32_t toNumber(std::string const & value) +{ + return int32_t(std::stol(value)); +} +template <> +inline int64_t toNumber(std::string const & value) +{ + return int64_t(std::stoll(value)); +} +template <> +inline uint8_t toNumber(std::string const & value) +{ + return uint8_t(std::stoul(value)); +} +template <> +inline uint16_t toNumber(std::string const & value) +{ + return uint16_t(std::stoul(value)); +} +template <> +inline uint32_t toNumber(std::string const & value) +{ + return uint32_t(std::stoul(value)); +} +template <> +inline uint64_t toNumber(std::string const & value) +{ + return uint64_t(std::stoull(value)); +} +template <> +inline float toNumber(std::string const & value) +{ + return std::stof(value); +} +template <> +inline double toNumber(std::string const & value) +{ + return std::stod(value); +} +} // namespace impl class StringUtils { @@ -169,7 +216,10 @@ class StringUtils _SC_EXTERN static bool StartsWith(std::string const & str, std::string const & pattern, bool lowerCase = true); _SC_EXTERN static bool EndsWith(std::string const & str, std::string const & pattern, bool lowerCase = true); - _SC_EXTERN static void SplitFilename(std::string const & qualifiedName, std::string & outBasename, std::string & outPath); + _SC_EXTERN static void SplitFilename( + std::string const & qualifiedName, + std::string & outBasename, + std::string & outPath); _SC_EXTERN static void SplitString(std::string const & str, char delim, std::vector & outList); _SC_EXTERN static void TrimLeft(std::string & str); @@ -179,8 +229,12 @@ class StringUtils _SC_EXTERN static std::string GetFileExtension(std::string const & filename); _SC_EXTERN static std::string NormalizeFilePath(std::string const & init, bool makeLowerCase); - _SC_EXTERN static std::string ReplaceAll(std::string const & source, std::string const & replaceWhat, std::string const & replaceWithWhat); - template static bool ParseNumber(std::string const & value, T & outValue) + _SC_EXTERN static std::string ReplaceAll( + std::string const & source, + std::string const & replaceWhat, + std::string const & replaceWithWhat); + template + static bool ParseNumber(std::string const & value, T & outValue) { try { @@ -201,4 +255,4 @@ class Random _SC_EXTERN static int Int(); }; -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/sc_wait.cpp b/sc-memory/sc-memory/sc_wait.cpp index ca4d99474..f7c284dc2 100644 --- a/sc-memory/sc-memory/sc_wait.cpp +++ b/sc-memory/sc-memory/sc_wait.cpp @@ -5,8 +5,8 @@ */ #include "sc_wait.hpp" -#include "kpm/sc_agent.hpp" +#include "kpm/sc_agent.hpp" ScWaitActionFinished::ScWaitActionFinished(ScMemoryContext const & ctx, ScAddr const & actionAddr) : ScWaitEvent(ctx, actionAddr) diff --git a/sc-memory/sc-memory/sc_wait.hpp b/sc-memory/sc-memory/sc_wait.hpp index 35cf5dc17..677a424e6 100644 --- a/sc-memory/sc-memory/sc_wait.hpp +++ b/sc-memory/sc-memory/sc_wait.hpp @@ -9,8 +9,8 @@ #include "sc_event.hpp" #include "sc_timer.hpp" -#include #include +#include #include /* Class implements common wait logic. @@ -51,7 +51,9 @@ class ScWait public: using DelegateFunc = std::function; - virtual ~ScWait() {} + virtual ~ScWait() + { + } void Resolve() { @@ -79,23 +81,28 @@ class ScWait }; /* Class implements event wait logic. -* Should be alive, while Memory context is alive. -*/ + * Should be alive, while Memory context is alive. + */ template class ScWaitEvent : public ScWait { public: ScWaitEvent(const ScMemoryContext & ctx, const ScAddr & addr) - : m_event(ctx, addr, - std::bind(&ScWaitEvent::OnEvent, - this, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)) + : m_event( + ctx, + addr, + std::bind( + &ScWaitEvent::OnEvent, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3)) { } - virtual ~ScWaitEvent() {} + virtual ~ScWaitEvent() + { + } protected: bool OnEvent(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) @@ -108,18 +115,19 @@ class ScWaitEvent : public ScWait return false; } - virtual bool OnEventImpl(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) { return true; } + virtual bool OnEventImpl(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) + { + return true; + } private: EventClassT m_event; }; - -template -class ScWaitCondition final : public ScWaitEvent +template +class ScWaitCondition final : public ScWaitEvent { public: - using DelegateCheckFunc = std::function; ScWaitCondition(const ScMemoryContext & ctx, const ScAddr & addr, DelegateCheckFunc func) @@ -150,4 +158,5 @@ class ScWaitActionFinished final : public ScWaitEvent }; #define SC_WAIT_CHECK(_func) std::bind(_func, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) -#define SC_WAIT_CHECK_MEMBER(_class, _func) std::bind(_class, _func, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) +#define SC_WAIT_CHECK_MEMBER(_class, _func) \ + std::bind(_class, _func, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3) diff --git a/sc-memory/sc-memory/scs/scs_parser.cpp b/sc-memory/sc-memory/scs/scs_parser.cpp index 190069e8f..ef6dc5be0 100644 --- a/sc-memory/sc-memory/scs/scs_parser.cpp +++ b/sc-memory/sc-memory/scs/scs_parser.cpp @@ -6,8 +6,8 @@ #include "sc-memory/scs/scs_parser.hpp" -#include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_debug.hpp" +#include "sc-memory/sc_memory.hpp" #include @@ -16,13 +16,16 @@ #if SC_DEBUG_MODE /// TODO: @deniskoronchik: make as cmake parameter -# define SCS_DEBUG_TOKEN 1 +# define SCS_DEBUG_TOKEN 1 #endif #if SCS_DEBUG_TOKEN -# define DEBUG_TOKEN(__msg) { std::cout << __msg << std::endl; } +# define DEBUG_TOKEN(__msg) \ + { \ + std::cout << __msg << std::endl; \ + } #else -# define DEBUG_TOKEN(__msg) +# define DEBUG_TOKEN(__msg) #endif #include "scsLexer.h" @@ -32,7 +35,6 @@ namespace { - bool IsLevel1Idtf(std::string const & idtf) { return (idtf.find('#') != std::string::npos); @@ -53,57 +55,75 @@ std::string UnescapeContent(std::string const & content) { auto const nextSymbol = result[pos + 1]; if (nextSymbol == '\\' || nextSymbol == '[' || nextSymbol == ']') - result.replace(pos, 2, { nextSymbol }); + result.replace(pos, 2, {nextSymbol}); } ++pos; } - return result; } class ErrorListener : public antlr4::ANTLRErrorListener { protected: - void syntaxError(antlr4::Recognizer *, antlr4::Token *, size_t line, - size_t charPositionInLine, std::string const & msg, std::exception_ptr) override + void syntaxError( + antlr4::Recognizer *, + antlr4::Token *, + size_t line, + size_t charPositionInLine, + std::string const & msg, + std::exception_ptr) override { - SC_THROW_EXCEPTION(utils::ExceptionParseError, "Parse error at line " << line << "," << charPositionInLine << ": " << msg); + SC_THROW_EXCEPTION( + utils::ExceptionParseError, "Parse error at line " << line << "," << charPositionInLine << ": " << msg); } - void reportAmbiguity(antlr4::Parser *, antlr4::dfa::DFA const &, size_t, size_t, bool, - antlrcpp::BitSet const &, antlr4::atn::ATNConfigSet *) override + void reportAmbiguity( + antlr4::Parser *, + antlr4::dfa::DFA const &, + size_t, + size_t, + bool, + antlrcpp::BitSet const &, + antlr4::atn::ATNConfigSet *) override { SC_THROW_EXCEPTION(utils::ExceptionParseError, "reportAmbiguity"); } - - void reportAttemptingFullContext(antlr4::Parser *, antlr4::dfa::DFA const &, size_t, size_t, - antlrcpp::BitSet const &, antlr4::atn::ATNConfigSet *) override + void reportAttemptingFullContext( + antlr4::Parser *, + antlr4::dfa::DFA const &, + size_t, + size_t, + antlrcpp::BitSet const &, + antlr4::atn::ATNConfigSet *) override { SC_THROW_EXCEPTION(utils::ExceptionParseError, "reportAttemptingFullContext"); } - - void reportContextSensitivity(antlr4::Parser *, antlr4::dfa::DFA const &, size_t, size_t, - size_t, antlr4::atn::ATNConfigSet *) override + void reportContextSensitivity( + antlr4::Parser *, + antlr4::dfa::DFA const &, + size_t, + size_t, + size_t, + antlr4::atn::ATNConfigSet *) override { SC_THROW_EXCEPTION(utils::ExceptionParseError, "reportContextSensitivity"); } - }; -} +} // namespace namespace scs { - -ParsedElement::ParsedElement(std::string const & idtf, - ScType const & type, - bool isReversed, - std::string const & value /* = "" */, - bool isURL /* = false */) +ParsedElement::ParsedElement( + std::string const & idtf, + ScType const & type, + bool isReversed, + std::string const & value /* = "" */, + bool isURL /* = false */) : m_idtf(idtf) , m_type(type) , m_visibility(Visibility::System) @@ -202,7 +222,7 @@ ElementHandle::ElementHandle(ElementID id, bool isLocal) { } -ElementID ElementHandle::operator * () const +ElementID ElementHandle::operator*() const { SC_ASSERT(IsValid(), ()); return m_id; @@ -218,24 +238,24 @@ bool ElementHandle::IsValid() const return m_id != INVALID_ID; } -bool ElementHandle::operator == (ElementHandle const & other) const +bool ElementHandle::operator==(ElementHandle const & other) const { return (m_id == other.m_id) && (m_isLocal == other.m_isLocal); } -bool ElementHandle::operator != (ElementHandle const & other) const +bool ElementHandle::operator!=(ElementHandle const & other) const { return !(*this == other); } -ElementHandle & ElementHandle::operator = (ElementHandle const & other) +ElementHandle & ElementHandle::operator=(ElementHandle const & other) { m_id = other.m_id; m_isLocal = other.m_isLocal; return *this; } -bool ElementHandle::operator < (ElementHandle const & other) const +bool ElementHandle::operator<(ElementHandle const & other) const { if (m_id == other.m_id) return m_isLocal < other.m_isLocal; @@ -243,7 +263,6 @@ bool ElementHandle::operator < (ElementHandle const & other) const return m_id < other.m_id; } - // --------------------------------------- Parser::Parser() @@ -294,8 +313,9 @@ ParsedElement & Parser::GetParsedElementRef(ElementHandle const & elID) if (*elID >= container.size()) { - SC_THROW_EXCEPTION(utils::ExceptionItemNotFound, - std::string("ElementId{") + std::to_string(*elID) + ", " + std::to_string(elID.IsLocal()) + "}"); + SC_THROW_EXCEPTION( + utils::ExceptionItemNotFound, + std::string("ElementId{") + std::to_string(*elID) + ", " + std::to_string(elID.IsLocal()) + "}"); } return container[*elID]; @@ -307,8 +327,9 @@ ParsedElement const & Parser::GetParsedElement(ElementHandle const & elID) const if (*elID >= container.size()) { - SC_THROW_EXCEPTION(utils::ExceptionItemNotFound, - std::string("ElementId{") + std::to_string(*elID) + ", " + std::to_string(elID.IsLocal()) + "}"); + SC_THROW_EXCEPTION( + utils::ExceptionItemNotFound, + std::string("ElementId{") + std::to_string(*elID) + ", " + std::to_string(elID.IsLocal()) + "}"); } return container[*elID]; @@ -349,11 +370,12 @@ std::string Parser::GenerateContourIdtf() return std::string("..contour_") + std::to_string(m_idtfCounter++); } -ElementHandle Parser::AppendElement(std::string idtf, - ScType const & type, - bool isConnectorReversed, - std::string const & value /* = "" */, - bool isURL /* = false */) +ElementHandle Parser::AppendElement( + std::string idtf, + ScType const & type, + bool isConnectorReversed, + std::string const & value /* = "" */, + bool isURL /* = false */) { SC_CHECK_GREAT(idtf.size(), 0, ()); if (TypeResolver::IsUnnamed(idtf)) @@ -432,8 +454,7 @@ void Parser::ProcessTriple(ElementHandle const & source, ElementHandle const & e } else { - SC_THROW_EXCEPTION(utils::ExceptionParseError, - "Can't merge types for element " + targetEl.GetIdtf()); + SC_THROW_EXCEPTION(utils::ExceptionParseError, "Can't merge types for element " + targetEl.GetIdtf()); } if (!m_contourTriplesStack.empty()) @@ -542,4 +563,4 @@ void Parser::ProcessContourEnd(ElementHandle const & contourHandle) } } -} +} // namespace scs diff --git a/sc-memory/sc-memory/scs/scs_parser.hpp b/sc-memory/sc-memory/scs/scs_parser.hpp index 25d6c1b72..7ff1c558e 100644 --- a/sc-memory/sc-memory/scs/scs_parser.hpp +++ b/sc-memory/sc-memory/scs/scs_parser.hpp @@ -7,7 +7,6 @@ #pragma once #include "sc-memory/sc_type.hpp" - #include "sc-memory/scs/scs_types.hpp" #include @@ -15,14 +14,13 @@ namespace scs { - typedef uint32_t ElementID; enum class Visibility : uint8_t { - Local, // just in one file - Global, // in whole knowledge base, but without system idtf - System // system idtf + Local, // just in one file + Global, // in whole knowledge base, but without system idtf + System // system idtf }; class ParsedElement @@ -30,11 +28,12 @@ class ParsedElement friend class Parser; public: - explicit ParsedElement(std::string const & idtf, - ScType const & type = ScType(), - bool isReversed = false, - std::string const & value = "", - bool isURL = false); + explicit ParsedElement( + std::string const & idtf, + ScType const & type = ScType(), + bool isReversed = false, + std::string const & value = "", + bool isURL = false); _SC_EXTERN std::string const & GetIdtf() const; _SC_EXTERN ScType const & GetType() const; @@ -52,10 +51,10 @@ class ParsedElement protected: std::string m_idtf; ScType m_type; - Visibility m_visibility; // cached value, to prevent each time check - bool m_isReversed : 1; // flag used just for an edges - std::string m_value; // string representation of content/link value - bool m_isURL : 1; // flag used to determine if ScLink value is an URL + Visibility m_visibility; // cached value, to prevent each time check + bool m_isReversed : 1; // flag used just for an edges + std::string m_value; // string representation of content/link value + bool m_isURL : 1; // flag used to determine if ScLink value is an URL }; class ElementHandle @@ -66,13 +65,13 @@ class ElementHandle _SC_EXTERN ElementHandle(ElementID id, bool isLocal); _SC_EXTERN ElementHandle(ElementHandle const & other) = default; - _SC_EXTERN ElementID operator * () const; + _SC_EXTERN ElementID operator*() const; _SC_EXTERN bool IsLocal() const; _SC_EXTERN bool IsValid() const; - _SC_EXTERN bool operator == (ElementHandle const & other) const; - _SC_EXTERN bool operator != (ElementHandle const & other) const; - _SC_EXTERN ElementHandle & operator = (ElementHandle const & other); - _SC_EXTERN bool operator < (ElementHandle const & other) const; + _SC_EXTERN bool operator==(ElementHandle const & other) const; + _SC_EXTERN bool operator!=(ElementHandle const & other) const; + _SC_EXTERN ElementHandle & operator=(ElementHandle const & other); + _SC_EXTERN bool operator<(ElementHandle const & other) const; private: static const ElementID INVALID_ID = std::numeric_limits::max(); @@ -81,16 +80,13 @@ class ElementHandle bool m_isLocal; }; - struct ParsedTriple { ElementHandle const m_source; ElementHandle const m_edge; ElementHandle const m_target; - ParsedTriple(ElementHandle const & s, - ElementHandle const & e, - ElementHandle const & t) + ParsedTriple(ElementHandle const & s, ElementHandle const & e, ElementHandle const & t) : m_source(s) , m_edge(e) , m_target(t) @@ -98,7 +94,6 @@ struct ParsedTriple } }; - class Parser { friend class scsParser; @@ -130,7 +125,6 @@ class Parser } protected: - ParsedElement & GetParsedElementRef(ElementHandle const & elID); ElementHandle ResolveAlias(std::string const & name); @@ -149,11 +143,12 @@ class Parser void ProcessAssign(std::string const & alias, ElementHandle const & value); private: - ElementHandle AppendElement(std::string idtf, - ScType const & type = ScType(), - bool isConnectorReversed = false, - std::string const & value = "", - bool isURL = false); + ElementHandle AppendElement( + std::string idtf, + ScType const & type = ScType(), + bool isConnectorReversed = false, + std::string const & value = "", + bool isURL = false); std::string GenerateNodeIdtf(); std::string GenerateEdgeIdtf(); @@ -161,9 +156,8 @@ class Parser std::string GenerateContourIdtf(); private: - ParsedElementVector m_parsedElements; - ParsedElementVector m_parsedElementsLocal; // just elements that has a local visibility + ParsedElementVector m_parsedElementsLocal; // just elements that has a local visibility std::stack> m_contourElementsStack; std::stack m_contourTriplesStack; @@ -176,4 +170,4 @@ class Parser uint32_t m_idtfCounter; }; -} +} // namespace scs diff --git a/sc-memory/sc-memory/scs/scs_types.cpp b/sc-memory/sc-memory/scs/scs_types.cpp index 19ed8d66e..56b37c027 100644 --- a/sc-memory/sc-memory/scs/scs_types.cpp +++ b/sc-memory/sc-memory/scs/scs_types.cpp @@ -9,83 +9,69 @@ namespace scs { - -TypeResolver::MapType TypeResolver::ms_connectorToType = -{ - {">", ScType::EdgeDCommon}, - {"<", ScType::EdgeDCommon}, - {"<>", ScType::EdgeUCommon}, - {"..>", ScType::EdgeAccess}, - {"<..", ScType::EdgeAccess}, - {"<=>", ScType::EdgeUCommonConst}, - {"_<=>", ScType::EdgeUCommonVar}, - {"=>", ScType::EdgeDCommonConst}, - {"<=", ScType::EdgeDCommonConst}, - {"_=>", ScType::EdgeDCommonVar}, - {"_<=", ScType::EdgeDCommonVar}, - {"->", ScType::EdgeAccessConstPosPerm}, - {"<-", ScType::EdgeAccessConstPosPerm}, - {"_->", ScType::EdgeAccessVarPosPerm}, - {"_<-", ScType::EdgeAccessVarPosPerm}, - {"-|>", ScType::EdgeAccessConstNegPerm}, - {"<|-", ScType::EdgeAccessConstNegPerm}, - {"_-|>", ScType::EdgeAccessVarNegPerm}, - {"_<|-", ScType::EdgeAccessVarNegPerm}, - {"-/>", ScType::EdgeAccessConstFuzPerm}, - {"", ScType::EdgeAccessVarFuzPerm}, - {"_", ScType::EdgeAccessConstPosTemp}, - {"<~", ScType::EdgeAccessConstPosTemp}, - {"_~>", ScType::EdgeAccessVarPosTemp}, - {"_<~", ScType::EdgeAccessVarPosTemp}, - {"~|>", ScType::EdgeAccessConstNegTemp}, - {"<|~", ScType::EdgeAccessConstNegTemp}, - {"_~|>", ScType::EdgeAccessVarNegTemp}, - {"_<|~", ScType::EdgeAccessVarNegTemp}, - {"~/>", ScType::EdgeAccessConstFuzTemp}, - {"", ScType::EdgeAccessVarFuzTemp}, - {"_", ScType::EdgeDCommon}, + {"<", ScType::EdgeDCommon}, + {"<>", ScType::EdgeUCommon}, + {"..>", ScType::EdgeAccess}, + {"<..", ScType::EdgeAccess}, + {"<=>", ScType::EdgeUCommonConst}, + {"_<=>", ScType::EdgeUCommonVar}, + {"=>", ScType::EdgeDCommonConst}, + {"<=", ScType::EdgeDCommonConst}, + {"_=>", ScType::EdgeDCommonVar}, + {"_<=", ScType::EdgeDCommonVar}, + {"->", ScType::EdgeAccessConstPosPerm}, + {"<-", ScType::EdgeAccessConstPosPerm}, + {"_->", ScType::EdgeAccessVarPosPerm}, + {"_<-", ScType::EdgeAccessVarPosPerm}, + {"-|>", ScType::EdgeAccessConstNegPerm}, + {"<|-", ScType::EdgeAccessConstNegPerm}, + {"_-|>", ScType::EdgeAccessVarNegPerm}, + {"_<|-", ScType::EdgeAccessVarNegPerm}, + {"-/>", ScType::EdgeAccessConstFuzPerm}, + {"", ScType::EdgeAccessVarFuzPerm}, + {"_", ScType::EdgeAccessConstPosTemp}, + {"<~", ScType::EdgeAccessConstPosTemp}, + {"_~>", ScType::EdgeAccessVarPosTemp}, + {"_<~", ScType::EdgeAccessVarPosTemp}, + {"~|>", ScType::EdgeAccessConstNegTemp}, + {"<|~", ScType::EdgeAccessConstNegTemp}, + {"_~|>", ScType::EdgeAccessVarNegTemp}, + {"_<|~", ScType::EdgeAccessVarNegTemp}, + {"~/>", ScType::EdgeAccessConstFuzTemp}, + {"", ScType::EdgeAccessVarFuzTemp}, + {"_ #include @@ -33,4 +32,4 @@ class TypeResolver final static MapType ms_connectorToType; static IsType ms_reversedConnectors; }; -} +} // namespace scs diff --git a/sc-memory/sc-memory/utils/sc_base64.cpp b/sc-memory/sc-memory/utils/sc_base64.cpp index 51173a488..2036f95c1 100644 --- a/sc-memory/sc-memory/utils/sc_base64.cpp +++ b/sc-memory/sc-memory/utils/sc_base64.cpp @@ -26,29 +26,26 @@ */ #include "sc_base64.hpp" -#include +#include namespace { static const std::string base64_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } -} // namespace +} // namespace namespace ScBase64 { - - -std::string Encode(unsigned char const* bytes_to_encode, unsigned int in_len) +std::string Encode(unsigned char const * bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; @@ -87,11 +84,9 @@ std::string Encode(unsigned char const* bytes_to_encode, unsigned int in_len) while ((i++ < 3)) ret += '='; - } return ret; - } std::string Decode(std::string const & encoded_string) @@ -105,7 +100,8 @@ std::string Decode(std::string const & encoded_string) while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { - char_array_4[i++] = encoded_string[in_]; in_++; + char_array_4[i++] = encoded_string[in_]; + in_++; if (i == 4) { for (i = 0; i < 4; i++) @@ -133,10 +129,11 @@ std::string Decode(std::string const & encoded_string) char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + for (j = 0; (j < i - 1); j++) + ret += char_array_3[j]; } return ret; } -} // namespace ScBase64 \ No newline at end of file +} // namespace ScBase64 \ No newline at end of file diff --git a/sc-memory/sc-memory/utils/sc_base64.hpp b/sc-memory/sc-memory/utils/sc_base64.hpp index 356c3e921..89a7a07a8 100644 --- a/sc-memory/sc-memory/utils/sc_base64.hpp +++ b/sc-memory/sc-memory/utils/sc_base64.hpp @@ -32,8 +32,7 @@ namespace ScBase64 { +_SC_EXTERN std::string Encode(unsigned char const *, unsigned int len); +_SC_EXTERN std::string Decode(std::string const & s); -_SC_EXTERN std::string Encode(unsigned char const*, unsigned int len); -_SC_EXTERN std::string Decode(std::string const& s); - -} +} // namespace ScBase64 diff --git a/sc-memory/sc-memory/utils/sc_boost.hpp b/sc-memory/sc-memory/utils/sc_boost.hpp index b53c0a5d7..c4a667f1e 100644 --- a/sc-memory/sc-memory/utils/sc_boost.hpp +++ b/sc-memory/sc-memory/utils/sc_boost.hpp @@ -6,37 +6,36 @@ namespace boost { namespace filesystem { - static boost::filesystem::path relativePath(boost::filesystem::path parent, boost::filesystem::path to) { - // Start at the root path and while they are the same then do nothing then when they first - // diverge take the remainder of the two path and replace the entire parent path with ".." - // segments. - boost::filesystem::path::const_iterator fromIter = parent.begin(); - boost::filesystem::path::const_iterator toIter = to.begin(); - - // Loop through both - while (fromIter != parent.end() && toIter != to.end() && (*toIter) == (*fromIter)) - { - ++toIter; - ++fromIter; - } - - boost::filesystem::path finalPath; - while (fromIter != parent.end()) - { - finalPath /= ".."; - ++fromIter; - } - - while (toIter != to.end()) - { - finalPath /= *toIter; - ++toIter; - } - - return finalPath; + // Start at the root path and while they are the same then do nothing then when they first + // diverge take the remainder of the two path and replace the entire parent path with ".." + // segments. + boost::filesystem::path::const_iterator fromIter = parent.begin(); + boost::filesystem::path::const_iterator toIter = to.begin(); + + // Loop through both + while (fromIter != parent.end() && toIter != to.end() && (*toIter) == (*fromIter)) + { + ++toIter; + ++fromIter; + } + + boost::filesystem::path finalPath; + while (fromIter != parent.end()) + { + finalPath /= ".."; + ++fromIter; + } + + while (toIter != to.end()) + { + finalPath /= *toIter; + ++toIter; + } + + return finalPath; } -} // filesystem -} // namespace boost \ No newline at end of file +} // namespace filesystem +} // namespace boost \ No newline at end of file diff --git a/sc-memory/sc-memory/utils/sc_cache.hpp b/sc-memory/sc-memory/utils/sc_cache.hpp index 1d91fdd0a..b04e3e1ad 100644 --- a/sc-memory/sc-memory/utils/sc_cache.hpp +++ b/sc-memory/sc-memory/utils/sc_cache.hpp @@ -8,9 +8,9 @@ namespace utils { - // Simple cache that stores list of values. -template class Cache +template +class Cache { SC_DISALLOW_COPY(Cache); @@ -27,9 +27,10 @@ template class Cache void Init(uint32_t logCacheSize) { SC_ASSERT(logCacheSize > 0 && logCacheSize < 32, (logCacheSize)); - static_assert((std::is_same::value || - std::is_same::value || - std::is_same::value), ""); + static_assert( + (std::is_same::value || std::is_same::value || + std::is_same::value), + ""); m_cache.reset(new Data[uint64_t(1) << logCacheSize]); m_hashMask = uint32_t(1 << logCacheSize) - 1; @@ -63,17 +64,20 @@ template class Cache inline void ResetValue(uint32_t i, uint32_t & value) { - for (value = 0; Index(value) == i; ++value); + for (value = 0; Index(value) == i; ++value) + ; } inline void ResetValue(uint32_t i, uint64_t & value) { - for (value = 0; Index(value) == i; ++value); + for (value = 0; Index(value) == i; ++value) + ; } inline void ResetValue(uint32_t i, std::string & value) { - for (value = ""; Index(value) == i; value += " "); + for (value = ""; Index(value) == i; value += " ") + ; } template @@ -122,7 +126,11 @@ template class Cache // TODO: Consider using separate arrays for keys and values, to save on padding. struct Data { - Data() : m_Key(), m_Value() {} + Data() + : m_Key() + , m_Value() + { + } KeyT m_Key; ValueT m_Value; }; @@ -131,5 +139,4 @@ template class Cache uint32_t m_hashMask; }; - -} // namespace utils \ No newline at end of file +} // namespace utils \ No newline at end of file diff --git a/sc-memory/sc-memory/utils/sc_console.cpp b/sc-memory/sc-memory/utils/sc_console.cpp index 94e6655f7..6c2e66685 100644 --- a/sc-memory/sc-memory/utils/sc_console.cpp +++ b/sc-memory/sc-memory/utils/sc_console.cpp @@ -1,29 +1,28 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_console.hpp" /// Common C++ headers +#include // for getch() #include #include -#include // for getch() - #if SC_IS_PLATFORM_WIN32 -# include // for WinAPI and Sleep() -# define _NO_OLDNAMES // for MinGW compatibility -# include // for getch() and kbhit() -# define getch _getch -# define kbhit _kbhit +# include // for WinAPI and Sleep() +# define _NO_OLDNAMES // for MinGW compatibility +# include // for getch() and kbhit() +# define getch _getch +# define kbhit _kbhit #else -# include // for getch() and kbhit() -# include // for getch(), kbhit() and (u)sleep() -# include // for getkey() -# include // for kbhit() -# include // for kbhit() +# include // for getkey() +# include // for kbhit() +# include // for kbhit() +# include // for getch() and kbhit() +# include // for getch(), kbhit() and (u)sleep() /// Function: getch /// Get character without waiting for Return to be pressed. @@ -53,22 +52,25 @@ int kbhit(void) tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); - newt.c_iflag = 0; // input mode - newt.c_oflag = 0; // output mode - newt.c_cc[VMIN] = 1; // minimum time to wait - newt.c_cc[VTIME] = 1; // minimum characters to wait for + newt.c_iflag = 0; // input mode + newt.c_oflag = 0; // output mode + newt.c_cc[VMIN] = 1; // minimum time to wait + newt.c_cc[VTIME] = 1; // minimum characters to wait for tcsetattr(STDIN_FILENO, TCSANOW, &newt); - ioctl(0, FIONREAD, &cnt); // Read count + ioctl(0, FIONREAD, &cnt); // Read count struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100; - select(STDIN_FILENO + 1, NULL, NULL, NULL, &tv); // A small time delay + select(STDIN_FILENO + 1, NULL, NULL, NULL, &tv); // A small time delay tcsetattr(STDIN_FILENO, TCSANOW, &oldt); - return cnt; // Return number of characters + return cnt; // Return number of characters } -#endif // SC_PLATFORM_WIN32 +#endif // SC_PLATFORM_WIN32 -#define SC_CONSOLE_PRINT(st) { std::cout << st; } +#define SC_CONSOLE_PRINT(st) \ + { \ + std::cout << st; \ + } namespace impl { @@ -115,7 +117,7 @@ const std::string ANSI_EMPTY = ""; ScConsole::KeyCode GetKey(void) { #if !SC_IS_PLATFORM_WIN32 - int cnt = kbhit(); // for ANSI escapes processing + int cnt = kbhit(); // for ANSI escapes processing #endif int k = getch(); switch (k) @@ -125,17 +127,28 @@ ScConsole::KeyCode GetKey(void) int kk; switch (kk = getch()) { - case 71: return ScConsole::KeyCode::NumPad7; - case 72: return ScConsole::KeyCode::NumPad8; - case 73: return ScConsole::KeyCode::NumPad9; - case 75: return ScConsole::KeyCode::NumPad4; - case 77: return ScConsole::KeyCode::NumPad6; - case 79: return ScConsole::KeyCode::NumPad1; - case 80: return ScConsole::KeyCode::NumPad2; - case 81: return ScConsole::KeyCode::NumPad3; - case 82: return ScConsole::KeyCode::NumPad0; - case 83: return ScConsole::KeyCode::NumDel; - default: return static_cast(kk - 59 + static_cast(ScConsole::KeyCode::F1)); // Function keys + case 71: + return ScConsole::KeyCode::NumPad7; + case 72: + return ScConsole::KeyCode::NumPad8; + case 73: + return ScConsole::KeyCode::NumPad9; + case 75: + return ScConsole::KeyCode::NumPad4; + case 77: + return ScConsole::KeyCode::NumPad6; + case 79: + return ScConsole::KeyCode::NumPad1; + case 80: + return ScConsole::KeyCode::NumPad2; + case 81: + return ScConsole::KeyCode::NumPad3; + case 82: + return ScConsole::KeyCode::NumPad0; + case 83: + return ScConsole::KeyCode::NumDel; + default: + return static_cast(kk - 59 + static_cast(ScConsole::KeyCode::F1)); // Function keys } } case 224: @@ -143,24 +156,37 @@ ScConsole::KeyCode GetKey(void) int kk; switch (kk = getch()) { - case 71: return ScConsole::KeyCode::Home; - case 72: return ScConsole::KeyCode::Up; - case 73: return ScConsole::KeyCode::PageUp; - case 75: return ScConsole::KeyCode::Left; - case 77: return ScConsole::KeyCode::Right; - case 79: return ScConsole::KeyCode::End; - case 80: return ScConsole::KeyCode::Down; - case 81: return ScConsole::KeyCode::PageDown; - case 82: return ScConsole::KeyCode::Insert; - case 83: return ScConsole::KeyCode::Delete; - default: return static_cast(kk - 123 + static_cast(ScConsole::KeyCode::F1)); // Function keys + case 71: + return ScConsole::KeyCode::Home; + case 72: + return ScConsole::KeyCode::Up; + case 73: + return ScConsole::KeyCode::PageUp; + case 75: + return ScConsole::KeyCode::Left; + case 77: + return ScConsole::KeyCode::Right; + case 79: + return ScConsole::KeyCode::End; + case 80: + return ScConsole::KeyCode::Down; + case 81: + return ScConsole::KeyCode::PageDown; + case 82: + return ScConsole::KeyCode::Insert; + case 83: + return ScConsole::KeyCode::Delete; + default: + return static_cast(kk - 123 + static_cast(ScConsole::KeyCode::F1)); // Function keys } } - case 13: return ScConsole::KeyCode::Enter; + case 13: + return ScConsole::KeyCode::Enter; #if SC_IS_PLATFORM_WIN32 - case 27: return ScConsole::KeyCode::Escape; -#else // _WIN32 - case 155: // single-character CSI + case 27: + return ScConsole::KeyCode::Escape; +#else // _WIN32 + case 155: // single-character CSI case 27: { // Process ANSI escape sequences @@ -168,10 +194,14 @@ ScConsole::KeyCode GetKey(void) { switch (k = getch()) { - case 'A': return ScConsole::KeyCode::Up; - case 'B': return ScConsole::KeyCode::Down; - case 'C': return ScConsole::KeyCode::Right; - case 'D': return ScConsole::KeyCode::Left; + case 'A': + return ScConsole::KeyCode::Up; + case 'B': + return ScConsole::KeyCode::Down; + case 'C': + return ScConsole::KeyCode::Right; + case 'D': + return ScConsole::KeyCode::Left; } } else @@ -179,39 +209,58 @@ ScConsole::KeyCode GetKey(void) return ScConsole::KeyCode::Escape; } } -#endif // _WIN32 - default: return static_cast(k); +#endif // _WIN32 + default: + return static_cast(k); } } int nb_getch(void) { - if (kbhit()) return getch(); - else return 0; + if (kbhit()) + return getch(); + else + return 0; } std::string const & GetANSIColor(ScConsole::Color const c) { - switch (c) { - case ScConsole::Color::Reset: return ANSI_ATTRIBUTE_RESET; - case ScConsole::Color::Black: return ANSI_BLACK; - case ScConsole::Color::Blue: return ANSI_BLUE; // non-ANSI - case ScConsole::Color::Green: return ANSI_GREEN; - case ScConsole::Color::Cyan: return ANSI_CYAN; // non-ANSI - case ScConsole::Color::Red: return ANSI_RED; // non-ANSI - case ScConsole::Color::Magneta: return ANSI_MAGENTA; - case ScConsole::Color::Brown: return ANSI_BROWN; - case ScConsole::Color::Grey: return ANSI_GREY; - case ScConsole::Color::DarkGrey: return ANSI_DARKGREY; - case ScConsole::Color::LightBlue: return ANSI_LIGHTBLUE; // non-ANSI - case ScConsole::Color::LightGreen: return ANSI_LIGHTGREEN; - case ScConsole::Color::LightCyan: return ANSI_LIGHTCYAN; // non-ANSI; - case ScConsole::Color::LightRed: return ANSI_LIGHTRED; // non-ANSI; - case ScConsole::Color::LightMagneta: return ANSI_LIGHTMAGENTA; - case ScConsole::Color::Yellow: return ANSI_YELLOW; // non-ANSI - case ScConsole::Color::White: return ANSI_WHITE; + case ScConsole::Color::Reset: + return ANSI_ATTRIBUTE_RESET; + case ScConsole::Color::Black: + return ANSI_BLACK; + case ScConsole::Color::Blue: + return ANSI_BLUE; // non-ANSI + case ScConsole::Color::Green: + return ANSI_GREEN; + case ScConsole::Color::Cyan: + return ANSI_CYAN; // non-ANSI + case ScConsole::Color::Red: + return ANSI_RED; // non-ANSI + case ScConsole::Color::Magneta: + return ANSI_MAGENTA; + case ScConsole::Color::Brown: + return ANSI_BROWN; + case ScConsole::Color::Grey: + return ANSI_GREY; + case ScConsole::Color::DarkGrey: + return ANSI_DARKGREY; + case ScConsole::Color::LightBlue: + return ANSI_LIGHTBLUE; // non-ANSI + case ScConsole::Color::LightGreen: + return ANSI_LIGHTGREEN; + case ScConsole::Color::LightCyan: + return ANSI_LIGHTCYAN; // non-ANSI; + case ScConsole::Color::LightRed: + return ANSI_LIGHTRED; // non-ANSI; + case ScConsole::Color::LightMagneta: + return ANSI_LIGHTMAGENTA; + case ScConsole::Color::Yellow: + return ANSI_YELLOW; // non-ANSI + case ScConsole::Color::White: + return ANSI_WHITE; } return ANSI_EMPTY; } @@ -220,16 +269,26 @@ std::string const & GetANSIBackgroundColor(ScConsole::Color const c) { switch (c) { - case ScConsole::Color::Reset: return ANSI_ATTRIBUTE_RESET; - case ScConsole::Color::Black: return ANSI_BACKGROUND_BLACK; - case ScConsole::Color::Blue: return ANSI_BACKGROUND_BLUE; - case ScConsole::Color::Green: return ANSI_BACKGROUND_GREEN; - case ScConsole::Color::Cyan: return ANSI_BACKGROUND_CYAN; - case ScConsole::Color::Red: return ANSI_BACKGROUND_RED; - case ScConsole::Color::Magneta: return ANSI_BACKGROUND_MAGENTA; - case ScConsole::Color::Brown: return ANSI_BACKGROUND_YELLOW; - case ScConsole::Color::Grey: return ANSI_BACKGROUND_WHITE; - default: break; + case ScConsole::Color::Reset: + return ANSI_ATTRIBUTE_RESET; + case ScConsole::Color::Black: + return ANSI_BACKGROUND_BLACK; + case ScConsole::Color::Blue: + return ANSI_BACKGROUND_BLUE; + case ScConsole::Color::Green: + return ANSI_BACKGROUND_GREEN; + case ScConsole::Color::Cyan: + return ANSI_BACKGROUND_CYAN; + case ScConsole::Color::Red: + return ANSI_BACKGROUND_RED; + case ScConsole::Color::Magneta: + return ANSI_BACKGROUND_MAGENTA; + case ScConsole::Color::Brown: + return ANSI_BACKGROUND_YELLOW; + case ScConsole::Color::Grey: + return ANSI_BACKGROUND_WHITE; + default: + break; } return ANSI_EMPTY; } @@ -239,7 +298,7 @@ void SetCursorVisibility(bool isVisible) #if SC_IS_PLATFORM_WIN32 && !defined(SC_CONSOLE_USE_ANSI) HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO structCursorInfo; - GetConsoleCursorInfo(hConsoleOutput, &structCursorInfo); // Get current cursor size + GetConsoleCursorInfo(hConsoleOutput, &structCursorInfo); // Get current cursor size structCursorInfo.bVisible = (isVisible ? TRUE : FALSE); SetConsoleCursorInfo(hConsoleOutput, &structCursorInfo); #else @@ -247,7 +306,7 @@ void SetCursorVisibility(bool isVisible) #endif } -} // namespace +} // namespace impl #if SC_IS_PLATFORM_WIN32 WORD ColorToWin(ScConsole::Color c) @@ -289,7 +348,6 @@ WORD ColorToWin(ScConsole::Color c) } #endif - void ScConsole::SetColor(Color c) { #if SC_IS_PLATFORM_WIN32 && !defined(SC_CONSOLE_USE_ANSI) @@ -298,7 +356,8 @@ void ScConsole::SetColor(Color c) GetConsoleScreenBufferInfo(hConsole, &csbi); - SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFFF0) | ColorToWin(c)); // Foreground colors take up the least significant byte + SetConsoleTextAttribute( + hConsole, (csbi.wAttributes & 0xFFF0) | ColorToWin(c)); // Foreground colors take up the least significant byte #else SC_CONSOLE_PRINT(impl::GetANSIColor(c)); #endif @@ -312,7 +371,9 @@ void ScConsole::SetBackgroundColor(Color c) GetConsoleScreenBufferInfo(hConsole, &csbi); - SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFF0F) | (((WORD)c) << 4)); // Background colors take up the second-least significant byte + SetConsoleTextAttribute( + hConsole, + (csbi.wAttributes & 0xFF0F) | (((WORD)c) << 4)); // Background colors take up the second-least significant byte #else SC_CONSOLE_PRINT(impl::GetANSIBackgroundColor(c)); #endif @@ -321,10 +382,11 @@ void ScConsole::SetBackgroundColor(Color c) ScConsole::Color ScConsole::GetDefaultColor() { #if SC_IS_PLATFORM_WIN32 && !defined(SC_CONSOLE_USE_ANSI) - static char initialized = 0; // bool + static char initialized = 0; // bool static WORD attributes; - if (!initialized) { + if (!initialized) + { CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); attributes = csbi.wAttributes; @@ -351,7 +413,7 @@ void ScConsole::SetCursorPos(int x, int y) COORD coord; // TODO: clamping/assert for x/y <= 0? coord.X = (SHORT)(x - 1); - coord.Y = (SHORT)(y - 1); // Windows uses 0-based coordinates + coord.Y = (SHORT)(y - 1); // Windows uses 0-based coordinates SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); #else SC_CONSOLE_PRINT("\033[" << y << ";" << x << "H"); @@ -363,7 +425,7 @@ void ScConsole::Clear() #if SC_IS_PLATFORM_WIN32 && !defined(SC_CONSOLE_USE_ANSI) // Based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022%28v=vs.85%29.aspx const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - const COORD coordScreen = { 0, 0 }; + const COORD coordScreen = {0, 0}; DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; @@ -416,25 +478,25 @@ int ScConsole::GetRowsNum() CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { - return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height + return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height } else { return -1; } #else -# ifdef TIOCGSIZE +# ifdef TIOCGSIZE struct ttysize ts; ioctl(STDIN_FILENO, TIOCGSIZE, &ts); return ts.ts_lines; -# elif defined(TIOCGWINSZ) +# elif defined(TIOCGWINSZ) struct winsize ts; ioctl(STDIN_FILENO, TIOCGWINSZ, &ts); return ts.ws_row; -# else // TIOCGSIZE +# else // TIOCGSIZE return -1; -# endif // TIOCGSIZE -#endif // WIN32 +# endif // TIOCGSIZE +#endif // WIN32 } int ScConsole::GetColsNum() @@ -443,25 +505,25 @@ int ScConsole::GetColsNum() CONSOLE_SCREEN_BUFFER_INFO csbi; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) { - return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width + return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width } else { return -1; } #else -# ifdef TIOCGSIZE +# ifdef TIOCGSIZE struct ttysize ts; ioctl(STDIN_FILENO, TIOCGSIZE, &ts); return ts.ts_cols; -# elif defined(TIOCGWINSZ) +# elif defined(TIOCGWINSZ) struct winsize ts; ioctl(STDIN_FILENO, TIOCGWINSZ, &ts); return ts.ws_col; -# else // TIOCGSIZE +# else // TIOCGSIZE return -1; -# endif // TIOCGSIZE -#endif // _WIN32 +# endif // TIOCGSIZE +#endif // _WIN32 } void ScConsole::WaitAnyKey(std::string const & message) diff --git a/sc-memory/sc-memory/utils/sc_console.hpp b/sc-memory/sc-memory/utils/sc_console.hpp index 91680a2ce..34f14328e 100644 --- a/sc-memory/sc-memory/utils/sc_console.hpp +++ b/sc-memory/sc-memory/utils/sc_console.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once @@ -38,7 +38,6 @@ class ScConsole final White }; - class Output final { public: @@ -57,59 +56,60 @@ class ScConsole final std::cout << std::flush; } - template Output & operator << (T v) + template + Output & operator<<(T v) { std::cout << v; return *this; } + private: bool m_isNewLine = false; }; public: - enum class KeyCode : uint8_t { - Escape = 0, - Enter = 1, - Space = 32, - - Insert = 2, - Home = 3, - PageUp = 4, - Delete = 5, - End = 6, - PageDown = 7, - - Up = 14, - Down = 15, - Left = 16, - Right = 17, - - F1 = 18, - F2 = 19, - F3 = 20, - F4 = 21, - F5 = 22, - F6 = 23, - F7 = 24, - F8 = 25, - F9 = 26, - F10 = 27, - F11 = 28, - F12 = 29, - - NumDel = 30, - NumPad0 = 31, - NumPad1 = 127, - NumPad2 = 128, - NumPad3 = 129, - NumPad4 = 130, - NumPad5 = 131, - NumPad6 = 132, - NumPad7 = 133, - NumPad8 = 134, - NumPad9 = 135 + Escape = 0, + Enter = 1, + Space = 32, + + Insert = 2, + Home = 3, + PageUp = 4, + Delete = 5, + End = 6, + PageDown = 7, + + Up = 14, + Down = 15, + Left = 16, + Right = 17, + + F1 = 18, + F2 = 19, + F3 = 20, + F4 = 21, + F5 = 22, + F6 = 23, + F7 = 24, + F8 = 25, + F9 = 26, + F10 = 27, + F11 = 28, + F12 = 29, + + NumDel = 30, + NumPad0 = 31, + NumPad1 = 127, + NumPad2 = 128, + NumPad3 = 129, + NumPad4 = 130, + NumPad5 = 131, + NumPad6 = 132, + NumPad7 = 133, + NumPad8 = 134, + NumPad9 = 135 }; _SC_EXTERN static void SetColor(Color c); @@ -142,20 +142,26 @@ class ScConsole final struct CursorHideGuard final { - CursorHideGuard() { ScConsole::HideCursor(); } - ~CursorHideGuard() { ScConsole::ShowCursor(); } + CursorHideGuard() + { + ScConsole::HideCursor(); + } + ~CursorHideGuard() + { + ScConsole::ShowCursor(); + } }; }; namespace impl { - std::string const & GetANSIColor(ScConsole::Color const c); +std::string const & GetANSIColor(ScConsole::Color const c); } - -template <> inline ScConsole::Output & ScConsole::Output::operator << (ScConsole::Color v) +template <> +inline ScConsole::Output & ScConsole::Output::operator<<(ScConsole::Color v) { ScConsole::SetColor(v); - //std::cout << impl::GetANSIColor(v); + // std::cout << impl::GetANSIColor(v); return *this; } diff --git a/sc-memory/sc-memory/utils/sc_keynode_cache.cpp b/sc-memory/sc-memory/utils/sc_keynode_cache.cpp index 5d20a4816..7b3244064 100644 --- a/sc-memory/sc-memory/utils/sc_keynode_cache.cpp +++ b/sc-memory/sc-memory/utils/sc_keynode_cache.cpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_keynode_cache.hpp" @@ -10,7 +10,6 @@ namespace utils { - ScKeynodeCache::ScKeynodeCache(ScMemoryContext & ctx) : m_ctx(ctx) { @@ -18,7 +17,6 @@ ScKeynodeCache::ScKeynodeCache(ScMemoryContext & ctx) ScAddr const & ScKeynodeCache::GetKeynode(std::string const & idtf) { - auto const it = m_cache.find(idtf); if (it == m_cache.end()) { @@ -37,4 +35,4 @@ ScAddr const & ScKeynodeCache::GetKeynode(std::string const & idtf) return it->second; } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_keynode_cache.hpp b/sc-memory/sc-memory/utils/sc_keynode_cache.hpp index b5d0e9087..bcae124c4 100644 --- a/sc-memory/sc-memory/utils/sc_keynode_cache.hpp +++ b/sc-memory/sc-memory/utils/sc_keynode_cache.hpp @@ -1,28 +1,27 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once -#include "../sc_defines.hpp" #include "../sc_addr.hpp" +#include "../sc_defines.hpp" -#include #include +#include class ScMemoryContext; namespace utils { - // Simple lock without mutex class ScKeynodeCache { public: _SC_EXTERN explicit ScKeynodeCache(ScMemoryContext & ctx); - + _SC_EXTERN ScAddr const & GetKeynode(std::string const & idtf); private: @@ -31,4 +30,4 @@ class ScKeynodeCache std::unordered_map m_cache; }; -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_lock.cpp b/sc-memory/sc-memory/utils/sc_lock.cpp index c6b0925c4..af852581b 100644 --- a/sc-memory/sc-memory/utils/sc_lock.cpp +++ b/sc-memory/sc-memory/utils/sc_lock.cpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_lock.hpp" @@ -15,7 +15,6 @@ extern "C" namespace utils { - ScLock::ScLock() : m_locked(0) { @@ -40,4 +39,4 @@ bool ScLock::IsLocked() const return g_atomic_int_get(&m_locked) == 1; } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_lock.hpp b/sc-memory/sc-memory/utils/sc_lock.hpp index 4d3014047..72b098ec1 100644 --- a/sc-memory/sc-memory/utils/sc_lock.hpp +++ b/sc-memory/sc-memory/utils/sc_lock.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once @@ -10,7 +10,6 @@ namespace utils { - // Simple lock without mutex class ScLock { @@ -33,11 +32,18 @@ class ScLock struct ScLockScope { - ScLockScope(ScLock & lock) : m_lock(lock) { m_lock.Lock(); } - ~ScLockScope() { m_lock.Unlock(); } + ScLockScope(ScLock & lock) + : m_lock(lock) + { + m_lock.Lock(); + } + ~ScLockScope() + { + m_lock.Unlock(); + } private: ScLock & m_lock; }; -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_log.cpp b/sc-memory/sc-memory/utils/sc_log.cpp index bd0b29288..93e449550 100644 --- a/sc-memory/sc-memory/utils/sc_log.cpp +++ b/sc-memory/sc-memory/utils/sc_log.cpp @@ -1,30 +1,28 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_log.hpp" -#include "../sc_debug.hpp" + #include "sc_lock.hpp" +#include "../sc_debug.hpp" + #include #include #include namespace { - // should be synced with ScLog::Type -const char * kTypeToStr[] = { - "Debug", "Info", "Warning", "Error" -}; +const char * kTypeToStr[] = {"Debug", "Info", "Warning", "Error"}; -} // namespace +} // namespace namespace utils { - ScLock gLock; ScLog * ScLog::ms_instance = nullptr; @@ -65,7 +63,7 @@ void ScLog::Shutdown() void ScLog::Message(ScLog::Type type, std::string const & msg, ScConsole::Color color /*= ScConsole::Color::White*/) { if (m_isMuted && type != Type::Error) - return; // do nothing on mute + return; // do nothing on mute utils::ScLockScope lock(gLock); if (m_mode <= type) @@ -75,15 +73,14 @@ void ScLog::Message(ScLog::Type type, std::string const & msg, ScConsole::Color std::tm tm = *std::localtime(&t); std::stringstream ss; - ss << "[" << std::setw(2) << std::setfill('0') << tm.tm_hour - << ":" << std::setw(2) << std::setfill('0') << tm.tm_min - << ":" << std::setw(2) << std::setfill('0') << tm.tm_sec << "][" - << kTypeToStr[int(type)] << "]: "; + ss << "[" << std::setw(2) << std::setfill('0') << tm.tm_hour << ":" << std::setw(2) << std::setfill('0') + << tm.tm_min << ":" << std::setw(2) << std::setfill('0') << tm.tm_sec << "][" << kTypeToStr[int(type)] << "]: "; ScConsole::SetColor(ScConsole::Color::White); std::cout << ss.str(); ScConsole::SetColor(color); - std::cout << msg << std::endl;; + std::cout << msg << std::endl; + ; ScConsole::ResetColor(); m_fileStream << ss.str() << msg; @@ -96,4 +93,4 @@ void ScLog::SetMuted(bool value) m_isMuted = value; } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_log.hpp b/sc-memory/sc-memory/utils/sc_log.hpp index ea7712efa..38e61f2a5 100644 --- a/sc-memory/sc-memory/utils/sc_log.hpp +++ b/sc-memory/sc-memory/utils/sc_log.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once #include "sc_console.hpp" @@ -13,7 +13,6 @@ namespace utils { - class ScLog final { protected: @@ -21,7 +20,6 @@ class ScLog final _SC_EXTERN ~ScLog(); public: - // should be synced with kTypeToStr in cpp enum class Type : uint8_t { @@ -48,23 +46,51 @@ class ScLog final static ScLog * ms_instance; }; - #define SC_LOG_COLOR(__type, __msg, __color) \ -{ std::stringstream ss; ss << __msg; ::utils::ScLog::GetInstance()->Message(__type, ss.str(), __color); } + { \ + std::stringstream ss; \ + ss << __msg; \ + ::utils::ScLog::GetInstance()->Message(__type, ss.str(), __color); \ + } #define SC_LOG(__type, __msg) SC_LOG_COLOR(__type, __msg, ScConsole::Color::White) - -#define SC_LOG_DEBUG(__msg) { SC_LOG_COLOR(::utils::ScLog::Type::Debug, __msg, ScConsole::Color::LightBlue) } -#define SC_LOG_INFO(__msg) { SC_LOG_COLOR(::utils::ScLog::Type::Info, __msg, ScConsole::Color::Grey) } -#define SC_LOG_WARNING(__msg) { SC_LOG_COLOR(::utils::ScLog::Type::Warning, __msg, ScConsole::Color::Yellow) } -#define SC_LOG_ERROR(__msg) { SC_LOG_COLOR(::utils::ScLog::Type::Error, __msg, ScConsole::Color::Red) } -#define SC_LOG_INFO_COLOR(__msg, __color) { SC_LOG_COLOR(::utils::ScLog::Type::Info, __msg, __color) } - -#define SC_LOG_INIT(__msg) { SC_LOG_INFO("[init] " << __msg) } -#define SC_LOG_SHUTDOWN(__msg) { SC_LOG_INFO("[shutdown] " << __msg) } -#define SC_LOG_LOAD(__msg) { SC_LOG_INFO("[load] " << __msg) } -#define SC_LOG_UNLOAD(__msg) { SC_LOG_INFO("[unload] " << __msg) } - - -} // namesapce utils +#define SC_LOG_DEBUG(__msg) \ + { \ + SC_LOG_COLOR(::utils::ScLog::Type::Debug, __msg, ScConsole::Color::LightBlue) \ + } +#define SC_LOG_INFO(__msg) \ + { \ + SC_LOG_COLOR(::utils::ScLog::Type::Info, __msg, ScConsole::Color::Grey) \ + } +#define SC_LOG_WARNING(__msg) \ + { \ + SC_LOG_COLOR(::utils::ScLog::Type::Warning, __msg, ScConsole::Color::Yellow) \ + } +#define SC_LOG_ERROR(__msg) \ + { \ + SC_LOG_COLOR(::utils::ScLog::Type::Error, __msg, ScConsole::Color::Red) \ + } +#define SC_LOG_INFO_COLOR(__msg, __color) \ + { \ + SC_LOG_COLOR(::utils::ScLog::Type::Info, __msg, __color) \ + } + +#define SC_LOG_INIT(__msg) \ + { \ + SC_LOG_INFO("[init] " << __msg) \ + } +#define SC_LOG_SHUTDOWN(__msg) \ + { \ + SC_LOG_INFO("[shutdown] " << __msg) \ + } +#define SC_LOG_LOAD(__msg) \ + { \ + SC_LOG_INFO("[load] " << __msg) \ + } +#define SC_LOG_UNLOAD(__msg) \ + { \ + SC_LOG_INFO("[unload] " << __msg) \ + } + +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_message.cpp b/sc-memory/sc-memory/utils/sc_message.cpp index 20fe06f2e..d3009f876 100644 --- a/sc-memory/sc-memory/utils/sc_message.cpp +++ b/sc-memory/sc-memory/utils/sc_message.cpp @@ -1,4 +1,5 @@ #include "sc_message.hpp" + #include "../sc_platform.hpp" std::string DebugPrint(std::string const & t) diff --git a/sc-memory/sc-memory/utils/sc_message.hpp b/sc-memory/sc-memory/utils/sc_message.hpp index a73c76688..6e3aa52c0 100644 --- a/sc-memory/sc-memory/utils/sc_message.hpp +++ b/sc-memory/sc-memory/utils/sc_message.hpp @@ -13,26 +13,33 @@ #include #include -template inline std::string DebugPrint(T const & t); +template +inline std::string DebugPrint(T const & t); _SC_EXTERN std::string DebugPrint(std::string const & t); inline std::string DebugPrint(char const * t); inline std::string DebugPrint(char t); -template inline std::string DebugPrint(std::pair const & p); -template inline std::string DebugPrint(std::list const & v); -template inline std::string DebugPrint(std::vector const & v); -template > inline std::string DebugPrint(std::set const & v); -template > inline std::string DebugPrint(std::multiset const & v); -template > inline std::string DebugPrint(std::map const & v); -template inline std::string DebugPrint(std::initializer_list const & v); +template +inline std::string DebugPrint(std::pair const & p); +template +inline std::string DebugPrint(std::list const & v); +template +inline std::string DebugPrint(std::vector const & v); +template > +inline std::string DebugPrint(std::set const & v); +template > +inline std::string DebugPrint(std::multiset const & v); +template > +inline std::string DebugPrint(std::map const & v); +template +inline std::string DebugPrint(std::initializer_list const & v); template , class Pred = std::equal_to> inline std::string DebugPrint(std::unordered_set const & v); template , class Pred = std::equal_to> inline std::string DebugPrint(std::unordered_map const & v); - inline std::string DebugPrint(char const * t) { if (t) @@ -60,7 +67,8 @@ inline std::string DebugPrint(unsigned char t) return DebugPrint(static_cast(t)); } -template inline std::string DebugPrint(std::pair const & p) +template +inline std::string DebugPrint(std::pair const & p) { std::ostringstream out; out << "(" << DebugPrint(p.first) << ", " << DebugPrint(p.second) << ")"; @@ -71,8 +79,8 @@ namespace utils { namespace impl { - -template inline std::string DebugPrintSequence(IterT beg, IterT end) +template +inline std::string DebugPrintSequence(IterT beg, IterT end) { std::ostringstream out; out << "[" << std::distance(beg, end) << ":"; @@ -82,45 +90,53 @@ template inline std::string DebugPrintSequence(IterT beg, IterT return out.str(); } -} // namespace impl -} // namespace utils +} // namespace impl +} // namespace utils -template inline std::string DebugPrint(T (&arr) [N]) +template +inline std::string DebugPrint(T (&arr)[N]) { return ::utils::impl::DebugPrintSequence(arr, arr + N); } -template inline std::string DebugPrint(std::array const & v) +template +inline std::string DebugPrint(std::array const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::vector const & v) +template +inline std::string DebugPrint(std::vector const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::list const & v) +template +inline std::string DebugPrint(std::list const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::set const & v) +template +inline std::string DebugPrint(std::set const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::multiset const & v) +template +inline std::string DebugPrint(std::multiset const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::map const & v) +template +inline std::string DebugPrint(std::map const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(std::initializer_list const & v) +template +inline std::string DebugPrint(std::initializer_list const & v) { return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } @@ -137,7 +153,8 @@ inline std::string DebugPrint(std::unordered_map const & v) return ::utils::impl::DebugPrintSequence(v.begin(), v.end()); } -template inline std::string DebugPrint(T const & t) +template +inline std::string DebugPrint(T const & t) { std::ostringstream out; out << t; @@ -152,13 +169,15 @@ inline std::string Message() { return std::string(); } -template std::string Message(T const & t) +template +std::string Message(T const & t) { return DebugPrint(t); } -template std::string Message(T const & t, ARGS const & ... others) +template +std::string Message(T const & t, ARGS const &... others) { return DebugPrint(t) + " " + Message(others...); } -} -} +} // namespace impl +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_progress.cpp b/sc-memory/sc-memory/utils/sc_progress.cpp index 4bc3ff492..23f52b1d8 100644 --- a/sc-memory/sc-memory/utils/sc_progress.cpp +++ b/sc-memory/sc-memory/utils/sc_progress.cpp @@ -1,7 +1,7 @@ #include "sc_progress.hpp" -#include "sc_log.hpp" #include "sc_console.hpp" +#include "sc_log.hpp" #include #include @@ -23,7 +23,7 @@ ScProgress::ScProgress(std::string const & title, size_t stepsNum, size_t width) void ScProgress::PrintStatus(size_t passedStep) { - m_passedSteps = passedStep + 1; // to correctly work with for (0; N); + m_passedSteps = passedStep + 1; // to correctly work with for (0; N); // calculate status float progress = (float)(m_passedSteps + 1) / (float)m_stepsNum; m_isComplete = (progress >= 1.f); @@ -47,4 +47,4 @@ void ScProgress::PrintStatus(size_t passedStep) std::cout << std::endl; } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_progress.hpp b/sc-memory/sc-memory/utils/sc_progress.hpp index be42ef31c..33f78bb77 100644 --- a/sc-memory/sc-memory/utils/sc_progress.hpp +++ b/sc-memory/sc-memory/utils/sc_progress.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #pragma once @@ -12,7 +12,6 @@ namespace utils { - class ScProgress final { public: @@ -30,4 +29,4 @@ class ScProgress final size_t m_prevPercent; }; -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_signal_handler.cpp b/sc-memory/sc-memory/utils/sc_signal_handler.cpp index 363b76947..ecaf8a614 100644 --- a/sc-memory/sc-memory/utils/sc_signal_handler.cpp +++ b/sc-memory/sc-memory/utils/sc_signal_handler.cpp @@ -1,46 +1,46 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "sc_signal_handler.hpp" -#include "../sc_platform.hpp" #include "../sc_debug.hpp" +#include "../sc_platform.hpp" #if SC_IS_PLATFORM_WIN32 -#include +# include #elif SC_IS_PLATFORM_LINUX || SC_IS_PLATFORM_MAC -#include +# include #else -#error "Not supported platform" +# error "Not supported platform" #endif namespace handlers { #if SC_IS_PLATFORM_WIN32 -BOOL CtrlHandler( DWORD fdwCtrlType ) +BOOL CtrlHandler(DWORD fdwCtrlType) { - switch( fdwCtrlType ) + switch (fdwCtrlType) + { + // Handle the CTRL-C signal. + case CTRL_C_EVENT: + // CTRL-CLOSE: confirm that the user wants to exit. + case CTRL_CLOSE_EVENT: + case CTRL_BREAK_EVENT: { - // Handle the CTRL-C signal. - case CTRL_C_EVENT: - // CTRL-CLOSE: confirm that the user wants to exit. - case CTRL_CLOSE_EVENT: - case CTRL_BREAK_EVENT: - { - if (utils::ScSignalHandler::m_onTerminate) - utils::ScSignalHandler::m_onTerminate(); - return( TRUE ); - } + if (utils::ScSignalHandler::m_onTerminate) + utils::ScSignalHandler::m_onTerminate(); + return (TRUE); + } - case CTRL_LOGOFF_EVENT: - case CTRL_SHUTDOWN_EVENT: - return FALSE; + case CTRL_LOGOFF_EVENT: + case CTRL_SHUTDOWN_EVENT: + return FALSE; - default: - return FALSE; + default: + return FALSE; } } #elif SC_IS_PLATFORM_LINUX || SC_IS_PLATFORM_MAC @@ -50,20 +50,19 @@ void sc_signal_handler(int s) utils::ScSignalHandler::m_onTerminate(); } #else -#error "Not supported platform" +# error "Not supported platform" #endif -} // namespace handlers +} // namespace handlers namespace utils { - ScSignalHandler::HandlerDelegate ScSignalHandler::m_onTerminate; void ScSignalHandler::Initialize() { SC_LOG_INIT("Signal handler"); #if SC_IS_PLATFORM_WIN32 - if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) handlers::CtrlHandler, TRUE ) ) + if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlers::CtrlHandler, TRUE)) { SC_LOG_INFO("Signal handler initialized"); } @@ -80,8 +79,8 @@ void ScSignalHandler::Initialize() sigaction(SIGINT, &sigIntHandler, nullptr); #else -#error "Unsupported platform" +# error "Unsupported platform" #endif } -} // namespace utils +} // namespace utils diff --git a/sc-memory/sc-memory/utils/sc_signal_handler.hpp b/sc-memory/sc-memory/utils/sc_signal_handler.hpp index 47bd65564..dd6c0da57 100644 --- a/sc-memory/sc-memory/utils/sc_signal_handler.hpp +++ b/sc-memory/sc-memory/utils/sc_signal_handler.hpp @@ -1,8 +1,8 @@ /* -* This source file is part of an OSTIS project. For the latest info, see http://ostis.net -* Distributed under the MIT License -* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) -*/ + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ #include "../sc_defines.hpp" @@ -10,7 +10,6 @@ namespace utils { - /* This class used to handle system signals such as * Ctrl + C, Ctrl + Break and etc. */ @@ -25,4 +24,4 @@ class ScSignalHandler _SC_EXTERN static HandlerDelegate m_onTerminate; }; -} // namespace utils +} // namespace utils diff --git a/sc-memory/tests/sc-memory/_test/dummy_file_interface.hpp b/sc-memory/tests/sc-memory/_test/dummy_file_interface.hpp index 2ea527fff..6479fe8a8 100644 --- a/sc-memory/tests/sc-memory/_test/dummy_file_interface.hpp +++ b/sc-memory/tests/sc-memory/_test/dummy_file_interface.hpp @@ -5,7 +5,9 @@ class DummyFileInterface : public SCsFileInterface { public: - ~DummyFileInterface() override {} + ~DummyFileInterface() override + { + } ScStreamPtr GetFileContent(std::string const &) override { diff --git a/sc-memory/tests/sc-memory/agents/sc-agent-actions.cpp b/sc-memory/tests/sc-memory/agents/sc-agent-actions.cpp index df898df97..4ee62aae2 100644 --- a/sc-memory/tests/sc-memory/agents/sc-agent-actions.cpp +++ b/sc-memory/tests/sc-memory/agents/sc-agent-actions.cpp @@ -1,11 +1,9 @@ #include +#include "agents_test_utils.hpp" #include "sc-memory/sc_wait.hpp" - #include "test_action.hpp" -#include "agents_test_utils.hpp" - ScAddr ATestActionEmit::ms_keynodeParam1; ScAddr ATestActionEmit::ms_keynodeParam2; @@ -31,16 +29,18 @@ TEST_F(ScAgentTest, action_emit) testInitLock.Lock(); ScAddr const cmd = ScAgentAction::CreateCommand( - *m_ctx, - ATestActionEmit::GetCommandClassAddr(), - { ATestActionEmit::ms_keynodeParam1, ATestActionEmit::ms_keynodeParam2 }); + *m_ctx, + ATestActionEmit::GetCommandClassAddr(), + {ATestActionEmit::ms_keynodeParam1, ATestActionEmit::ms_keynodeParam2}); SC_CHECK(cmd.IsValid(), ()); ScWaitActionFinished waiter(*m_ctx, cmd); - waiter.SetOnWaitStartDelegate([&]() { - ScAgentAction::InitiateCommand(*m_ctx, cmd); - }); + waiter.SetOnWaitStartDelegate( + [&]() + { + ScAgentAction::InitiateCommand(*m_ctx, cmd); + }); waiter.Wait(); SC_CHECK_EQUAL(ScAgentAction::GetCommandResultCode(*m_ctx, cmd), SC_RESULT_OK, ()); diff --git a/sc-memory/tests/sc-memory/agents/sc-agent-result.cpp b/sc-memory/tests/sc-memory/agents/sc-agent-result.cpp index 38086f3d5..a2b2f42a5 100644 --- a/sc-memory/tests/sc-memory/agents/sc-agent-result.cpp +++ b/sc-memory/tests/sc-memory/agents/sc-agent-result.cpp @@ -1,13 +1,11 @@ #include -#include "sc-memory/sc_wait.hpp" - #include "agents_test_utils.hpp" +#include "sc-memory/sc_wait.hpp" +#include "test_sc_agent_result.hpp" #include -#include "test_sc_agent_result.hpp" - ScAddr ATestResultOk::ms_keynodeTestResultOk; // Implement just one test, because whole logic depends on ScAgentAction::GetResultCodeAddr funciton @@ -30,19 +28,17 @@ TEST_F(ScAgentTest, ATestResultOk) ScAddr const cmdAddr = ctx.CreateNode(ScType::NodeConst); EXPECT_TRUE(cmdAddr.IsValid()); - ScAddr const edge = ctx.CreateEdge( - ScType::EdgeAccessConstPosPerm, - ATestResultOk::ms_keynodeTestResultOk, - cmdAddr); + ScAddr const edge = ctx.CreateEdge(ScType::EdgeAccessConstPosPerm, ATestResultOk::ms_keynodeTestResultOk, cmdAddr); EXPECT_TRUE(edge.IsValid()); ScWaitActionFinished waiter(ctx, cmdAddr); - waiter.SetOnWaitStartDelegate([&cmdAddr]() - { - ScMemoryContext ctxLocal(sc_access_lvl_make_min, "ATestResultOk_init"); - ScAgentAction::InitiateCommand(ctxLocal, cmdAddr); - }); + waiter.SetOnWaitStartDelegate( + [&cmdAddr]() + { + ScMemoryContext ctxLocal(sc_access_lvl_make_min, "ATestResultOk_init"); + ScAgentAction::InitiateCommand(ctxLocal, cmdAddr); + }); EXPECT_TRUE(waiter.Wait()); // check result diff --git a/sc-memory/tests/sc-memory/agents/sc-agent.cpp b/sc-memory/tests/sc-memory/agents/sc-agent.cpp index 1f783f353..3aa3f3828 100644 --- a/sc-memory/tests/sc-memory/agents/sc-agent.cpp +++ b/sc-memory/tests/sc-memory/agents/sc-agent.cpp @@ -1,14 +1,11 @@ #include +#include "agents_test_utils.hpp" #include "sc-memory/kpm/sc_agent.hpp" - #include "test_sc_agent.hpp" -#include "agents_test_utils.hpp" - namespace { - ScAddr CreateKeynode(ScMemoryContext & ctx, std::string const & name) { ScAddr const node = ctx.CreateNode(ScType::NodeConst); @@ -18,8 +15,7 @@ ScAddr CreateKeynode(ScMemoryContext & ctx, std::string const & name) return node; } -} // namespace - +} // namespace TEST_F(ScAgentTest, ATestAction) { diff --git a/sc-memory/tests/sc-memory/agents/test_sc_agent.hpp b/sc-memory/tests/sc-memory/agents/test_sc_agent.hpp index 4802c64dc..77e568bb4 100644 --- a/sc-memory/tests/sc-memory/agents/test_sc_agent.hpp +++ b/sc-memory/tests/sc-memory/agents/test_sc_agent.hpp @@ -1,10 +1,10 @@ #pragma once +#include "sc-memory/kpm/sc_agent.hpp" #include "sc-memory/sc_addr.hpp" #include "sc-memory/sc_object.hpp" #include "sc-memory/sc_timer.hpp" #include "sc-memory/utils/sc_lock.hpp" -#include "sc-memory/kpm/sc_agent.hpp" #include @@ -36,7 +36,6 @@ class TestWaiter utils::ScLock m_lock; }; - class ATestAction : public ScAgentAction { SC_CLASS(Agent, CmdClass("command_1")) @@ -46,7 +45,6 @@ class ATestAction : public ScAgentAction static TestWaiter msWaiter; }; - class ATestAddInputEdge : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::AddInputEdge)) @@ -59,21 +57,18 @@ class ATestAddInputEdge : public ScAgent static TestWaiter msWaiter; }; - class ATestAddOutputEdge : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::AddOutputEdge)) SC_GENERATED_BODY() public: - SC_PROPERTY(Keynode("ATestAddOutputEdge"), ForceCreate) static ScAddr msAgentKeynode; static TestWaiter msWaiter; }; - class ATestRemoveInputEdge : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::RemoveInputEdge)) @@ -86,7 +81,6 @@ class ATestRemoveInputEdge : public ScAgent static TestWaiter msWaiter; }; - class ATestRemoveOutputEdge : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::RemoveOutputEdge)) @@ -99,7 +93,6 @@ class ATestRemoveOutputEdge : public ScAgent static TestWaiter msWaiter; }; - class ATestRemoveElement : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::EraseElement)) @@ -112,7 +105,6 @@ class ATestRemoveElement : public ScAgent static TestWaiter msWaiter; }; - class ATestContentChanged : public ScAgent { SC_CLASS(Agent, Event(msAgentKeynode, ScEvent::Type::ContentChanged)) diff --git a/sc-memory/tests/sc-memory/agents/test_sc_agent_result.hpp b/sc-memory/tests/sc-memory/agents/test_sc_agent_result.hpp index c2926bfc0..4c9f7484a 100644 --- a/sc-memory/tests/sc-memory/agents/test_sc_agent_result.hpp +++ b/sc-memory/tests/sc-memory/agents/test_sc_agent_result.hpp @@ -4,7 +4,7 @@ #include "test_sc_agent_result.generated.hpp" -class ATestResultOk: public ScAgentAction +class ATestResultOk : public ScAgentAction { SC_CLASS(Agent, CmdClass("test_result_ok")) SC_GENERATED_BODY() diff --git a/sc-memory/tests/sc-memory/codegen/codegen.cpp b/sc-memory/tests/sc-memory/codegen/codegen.cpp index 0717db2b7..d9f49ad1f 100644 --- a/sc-memory/tests/sc-memory/codegen/codegen.cpp +++ b/sc-memory/tests/sc-memory/codegen/codegen.cpp @@ -1,9 +1,8 @@ #include -#include "sc-memory/sc_object.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_object.hpp" #include "test_sc_object.hpp" using ScCodegenTest = ScMemoryTest; diff --git a/sc-memory/tests/sc-memory/codegen/test_sc_object.cpp b/sc-memory/tests/sc-memory/codegen/test_sc_object.cpp index 1eaf0428e..c94057349 100644 --- a/sc-memory/tests/sc-memory/codegen/test_sc_object.cpp +++ b/sc-memory/tests/sc-memory/codegen/test_sc_object.cpp @@ -10,9 +10,8 @@ namespace n1 { namespace n2 { - ScAddr TestObject::mTestKeynode3; ScTemplate TestObject::mTestTemplate2; -} // namespace n2 -} // namespace n1 +} // namespace n2 +} // namespace n1 diff --git a/sc-memory/tests/sc-memory/codegen/test_sc_object.hpp b/sc-memory/tests/sc-memory/codegen/test_sc_object.hpp index 1997008f0..46c7119a9 100644 --- a/sc-memory/tests/sc-memory/codegen/test_sc_object.hpp +++ b/sc-memory/tests/sc-memory/codegen/test_sc_object.hpp @@ -22,10 +22,12 @@ class TestObject : public ScObject public: /// TODO: autogenerate code to call _initInternal - TestObject() { Init(); } /// TEST + TestObject() + { + Init(); + } /// TEST public: - SC_PROPERTY(Keynode("test_keynode1")) ScAddr mTestKeynode1; @@ -45,5 +47,5 @@ class TestObject : public ScObject SC_PROPERTY(Template("test_template2")) static ScTemplate mTestTemplate2; }; -} -} +} // namespace n2 +} // namespace n1 diff --git a/sc-memory/tests/sc-memory/common/sc-common-templ.cpp b/sc-memory/tests/sc-memory/common/sc-common-templ.cpp index dc51c017f..5b5816832 100644 --- a/sc-memory/tests/sc-memory/common/sc-common-templ.cpp +++ b/sc-memory/tests/sc-memory/common/sc-common-templ.cpp @@ -1,10 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_common_templ.hpp" #include "sc-memory/sc_memory.hpp" -#include "sc_test.hpp" - using ScCommonTemplTest = ScMemoryTest; TEST_F(ScCommonTemplTest, ResolveRelationTuple) @@ -14,14 +14,11 @@ TEST_F(ScCommonTemplTest, ResolveRelationTuple) ScAddr const tuple = sc::ResolveRelationTuple(*m_ctx, el, relAddr); { - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::NodeVarTuple >> "_tuple", - ScType::EdgeDCommonVar, - el, - ScType::EdgeAccessVarPosPerm, - relAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + ScType::NodeVarTuple >> "_tuple", ScType::EdgeDCommonVar, el, ScType::EdgeAccessVarPosPerm, relAddr) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator result = search.begin(); @@ -42,14 +39,11 @@ TEST_F(ScCommonTemplTest, SetRelationValue) ScAddr const relAddr1 = m_ctx->CreateNode(ScType::NodeConstNoRole); ScAddr const linkAddr1 = sc::SetRelationValue(*m_ctx, el, relAddr1, value1); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - el, - ScType::EdgeDCommonVar, - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm, - relAddr1) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + el, ScType::EdgeDCommonVar, ScType::Link >> "_link", ScType::EdgeAccessVarPosPerm, relAddr1) + .Make(); ScLink link(*m_ctx, linkAddr1); diff --git a/sc-memory/tests/sc-memory/common/sc-elements.cpp b/sc-memory/tests/sc-memory/common/sc-elements.cpp index 45b175599..c1ff4df08 100644 --- a/sc-memory/tests/sc-memory/common/sc-elements.cpp +++ b/sc-memory/tests/sc-memory/common/sc-elements.cpp @@ -1,9 +1,8 @@ #include -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_memory.hpp" TEST_F(ScMemoryTest, elements) { diff --git a/sc-memory/tests/sc-memory/common/sc-iterator3.cpp b/sc-memory/tests/sc-memory/common/sc-iterator3.cpp index 2c4328d42..f10ec0c2e 100644 --- a/sc-memory/tests/sc-memory/common/sc-iterator3.cpp +++ b/sc-memory/tests/sc-memory/common/sc-iterator3.cpp @@ -1,9 +1,9 @@ #include -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_memory.hpp" + class ScIterator3Test : public ScMemoryTest { protected: @@ -52,7 +52,6 @@ TEST_F(ScIterator3Test, f_a_f) EXPECT_EQ(iter3->Get(2), m_target); } - TEST_F(ScIterator3Test, f_a_a) { ScIterator3Ptr const iter3 = m_ctx->Iterator3(m_source, ScType::EdgeAccessConstPosPerm, ScType::Node); diff --git a/sc-memory/tests/sc-memory/common/sc-iterator5.cpp b/sc-memory/tests/sc-memory/common/sc-iterator5.cpp index fb4b03fda..32352a1ed 100644 --- a/sc-memory/tests/sc-memory/common/sc-iterator5.cpp +++ b/sc-memory/tests/sc-memory/common/sc-iterator5.cpp @@ -1,9 +1,9 @@ #include -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_memory.hpp" + class ScIterator5Test : public ScMemoryTest { protected: @@ -56,11 +56,7 @@ TEST_F(ScIterator5Test, smoke) TEST_F(ScIterator5Test, a_a_f_a_a) { ScIterator5Ptr const iter5 = m_ctx->Iterator5( - ScType::Node, - ScType::EdgeAccessConstPosPerm, - m_target, - ScType::EdgeAccessConstPosPerm, - ScType::Node); + ScType::Node, ScType::EdgeAccessConstPosPerm, m_target, ScType::EdgeAccessConstPosPerm, ScType::Node); EXPECT_TRUE(iter5->Next()); @@ -73,12 +69,8 @@ TEST_F(ScIterator5Test, a_a_f_a_a) TEST_F(ScIterator5Test, a_a_f_a_f) { - ScIterator5Ptr const iter5 = m_ctx->Iterator5( - ScType::Node, - ScType::EdgeAccessConstPosPerm, - m_target, - ScType::EdgeAccessConstPosPerm, - m_attr); + ScIterator5Ptr const iter5 = + m_ctx->Iterator5(ScType::Node, ScType::EdgeAccessConstPosPerm, m_target, ScType::EdgeAccessConstPosPerm, m_attr); EXPECT_TRUE(iter5->Next()); @@ -92,11 +84,7 @@ TEST_F(ScIterator5Test, a_a_f_a_f) TEST_F(ScIterator5Test, f_a_a_a_a) { ScIterator5Ptr const iter5 = m_ctx->Iterator5( - m_source, - ScType::EdgeAccessConstPosPerm, - ScType::Node, - ScType::EdgeAccessConstPosPerm, - ScType::Node); + m_source, ScType::EdgeAccessConstPosPerm, ScType::Node, ScType::EdgeAccessConstPosPerm, ScType::Node); EXPECT_TRUE(iter5->Next()); @@ -109,12 +97,8 @@ TEST_F(ScIterator5Test, f_a_a_a_a) TEST_F(ScIterator5Test, f_a_a_a_f) { - ScIterator5Ptr const iter5 = m_ctx->Iterator5( - m_source, - ScType::EdgeAccessConstPosPerm, - ScType::Node, - ScType::EdgeAccessConstPosPerm, - m_attr); + ScIterator5Ptr const iter5 = + m_ctx->Iterator5(m_source, ScType::EdgeAccessConstPosPerm, ScType::Node, ScType::EdgeAccessConstPosPerm, m_attr); EXPECT_TRUE(iter5->Next()); @@ -128,11 +112,7 @@ TEST_F(ScIterator5Test, f_a_a_a_f) TEST_F(ScIterator5Test, f_a_f_a_a) { ScIterator5Ptr const iter5 = m_ctx->Iterator5( - m_source, - ScType::EdgeAccessConstPosPerm, - m_target, - ScType::EdgeAccessConstPosPerm, - ScType::Node); + m_source, ScType::EdgeAccessConstPosPerm, m_target, ScType::EdgeAccessConstPosPerm, ScType::Node); EXPECT_TRUE(iter5->Next()); @@ -145,12 +125,8 @@ TEST_F(ScIterator5Test, f_a_f_a_a) TEST_F(ScIterator5Test, f_a_f_a_f) { - ScIterator5Ptr const iter5 = m_ctx->Iterator5( - m_source, - ScType::EdgeAccessConstPosPerm, - m_target, - ScType::EdgeAccessConstPosPerm, - m_attr); + ScIterator5Ptr const iter5 = + m_ctx->Iterator5(m_source, ScType::EdgeAccessConstPosPerm, m_target, ScType::EdgeAccessConstPosPerm, m_attr); EXPECT_TRUE(iter5->Next()); diff --git a/sc-memory/tests/sc-memory/common/sc-keynodes.cpp b/sc-memory/tests/sc-memory/common/sc-keynodes.cpp index c1ebec515..718f2903c 100644 --- a/sc-memory/tests/sc-memory/common/sc-keynodes.cpp +++ b/sc-memory/tests/sc-memory/common/sc-keynodes.cpp @@ -1,28 +1,26 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_keynodes.hpp" #include "sc-memory/utils/sc_keynode_cache.hpp" -#include "sc_test.hpp" - using ScKeynodesTest = ScMemoryTest; TEST_F(ScKeynodesTest, binary_types) { - ScAddr keynodes[] = - { - ScKeynodes::kBinaryDouble, - ScKeynodes::kBinaryFloat, - ScKeynodes::kBinaryInt8, - ScKeynodes::kBinaryInt16, - ScKeynodes::kBinaryInt32, - ScKeynodes::kBinaryInt64, - ScKeynodes::kBinaryUInt8, - ScKeynodes::kBinaryUInt16, - ScKeynodes::kBinaryUInt32, - ScKeynodes::kBinaryUInt64, - ScKeynodes::kBinaryString - }; + ScAddr keynodes[] = { + ScKeynodes::kBinaryDouble, + ScKeynodes::kBinaryFloat, + ScKeynodes::kBinaryInt8, + ScKeynodes::kBinaryInt16, + ScKeynodes::kBinaryInt32, + ScKeynodes::kBinaryInt64, + ScKeynodes::kBinaryUInt8, + ScKeynodes::kBinaryUInt16, + ScKeynodes::kBinaryUInt32, + ScKeynodes::kBinaryUInt64, + ScKeynodes::kBinaryString}; for (ScAddr a : keynodes) EXPECT_TRUE(m_ctx->HelperCheckEdge(ScKeynodes::kBinaryType, a, ScType::EdgeAccessConstPosPerm)); diff --git a/sc-memory/tests/sc-memory/common/sc-link.cpp b/sc-memory/tests/sc-memory/common/sc-link.cpp index c52bc236e..b5ae2f3ad 100644 --- a/sc-memory/tests/sc-memory/common/sc-link.cpp +++ b/sc-memory/tests/sc-memory/common/sc-link.cpp @@ -1,11 +1,12 @@ #include -#include "sc-memory/sc_memory.hpp" -#include "sc-memory/sc_link.hpp" - #include "sc_test.hpp" -template void TestType(ScMemoryContext & ctx, Type const & value) +#include "sc-memory/sc_link.hpp" +#include "sc-memory/sc_memory.hpp" + +template +void TestType(ScMemoryContext & ctx, Type const & value) { ScAddr const linkAddr = ctx.CreateLink(); EXPECT_TRUE(linkAddr.IsValid()); diff --git a/sc-memory/tests/sc-memory/common/sc-memory.cpp b/sc-memory/tests/sc-memory/common/sc-memory.cpp index 97bb6c4a3..8775e2e59 100644 --- a/sc-memory/tests/sc-memory/common/sc-memory.cpp +++ b/sc-memory/tests/sc-memory/common/sc-memory.cpp @@ -1,10 +1,9 @@ #include -#include "sc-memory/sc_link.hpp" -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_link.hpp" +#include "sc-memory/sc_memory.hpp" TEST_F(ScMemoryTest, LinkContent) { diff --git a/sc-memory/tests/sc-memory/common/sc-stream.cpp b/sc-memory/tests/sc-memory/common/sc-stream.cpp index 6e4c3382e..c31c939f2 100644 --- a/sc-memory/tests/sc-memory/common/sc-stream.cpp +++ b/sc-memory/tests/sc-memory/common/sc-stream.cpp @@ -10,7 +10,7 @@ TEST(ScStreamTest, common) for (uint32_t i = 0; i < length; ++i) buff[i] = rand() % 256; - ScStream stream((sc_char*)buff, length, SC_STREAM_FLAG_READ); + ScStream stream((sc_char *)buff, length, SC_STREAM_FLAG_READ); EXPECT_TRUE(stream.IsValid()); EXPECT_TRUE(stream.HasFlag(SC_STREAM_FLAG_READ)); @@ -24,7 +24,7 @@ TEST(ScStreamTest, common) { unsigned char c; size_t readBytes; - EXPECT_TRUE(stream.Read((sc_char*)&c, sizeof(c), readBytes)); + EXPECT_TRUE(stream.Read((sc_char *)&c, sizeof(c), readBytes)); EXPECT_EQ(c, buff[i]); } @@ -38,10 +38,9 @@ TEST(ScStreamTest, common) sc_uint32 pos = rand() % length; EXPECT_TRUE(stream.Seek(SC_STREAM_SEEK_SET, pos)); - unsigned char c; size_t readBytes; - EXPECT_TRUE(stream.Read((sc_char*)&c, sizeof(c), readBytes)); + EXPECT_TRUE(stream.Read((sc_char *)&c, sizeof(c), readBytes)); EXPECT_EQ(c, buff[pos]); } } diff --git a/sc-memory/tests/sc-memory/common/sc-struct.cpp b/sc-memory/tests/sc-memory/common/sc-struct.cpp index afde64502..3193d5bc5 100644 --- a/sc-memory/tests/sc-memory/common/sc-struct.cpp +++ b/sc-memory/tests/sc-memory/common/sc-struct.cpp @@ -1,10 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_struct.hpp" -#include "sc_test.hpp" - using ScStructTest = ScMemoryTest; TEST_F(ScStructTest, common) @@ -41,16 +41,12 @@ TEST_F(ScStructTest, common) SC_CHECK(st.Append(addr1, attrAddr), ()); ScIterator5Ptr iter5 = m_ctx->Iterator5( - structAddr, - ScType::EdgeAccessConstPosPerm, - ScType::Unknown, - ScType::EdgeAccessConstPosPerm, - attrAddr); + structAddr, ScType::EdgeAccessConstPosPerm, ScType::Unknown, ScType::EdgeAccessConstPosPerm, attrAddr); bool found = false; while (iter5->Next()) { - EXPECT_FALSE(found); // one time + EXPECT_FALSE(found); // one time EXPECT_EQ(iter5->Get(0), structAddr); EXPECT_EQ(iter5->Get(2), addr1); EXPECT_EQ(iter5->Get(4), attrAddr); diff --git a/sc-memory/tests/sc-memory/common/sc-type.cpp b/sc-memory/tests/sc-memory/common/sc-type.cpp index bff5b2720..8f15ad5ed 100644 --- a/sc-memory/tests/sc-memory/common/sc-type.cpp +++ b/sc-memory/tests/sc-memory/common/sc-type.cpp @@ -1,9 +1,8 @@ #include -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_memory.hpp" TEST(ScTypeTest, nodes) { diff --git a/sc-memory/tests/sc-memory/common/sc-utils.cpp b/sc-memory/tests/sc-memory/common/sc-utils.cpp index 184f46ded..e8c1a5f20 100644 --- a/sc-memory/tests/sc-memory/common/sc-utils.cpp +++ b/sc-memory/tests/sc-memory/common/sc-utils.cpp @@ -70,7 +70,6 @@ TEST(StringUtils, ParseNumbers) EXPECT_EQ(resultInt32, 32); } - { int64_t resultInt64; EXPECT_TRUE(utils::StringUtils::ParseNumber("64", resultInt64)); diff --git a/sc-memory/tests/sc-memory/events/sc-event-threading.cpp b/sc-memory/tests/sc-memory/events/sc-event-threading.cpp index 49c476b57..c8519d3c8 100644 --- a/sc-memory/tests/sc-memory/events/sc-event-threading.cpp +++ b/sc-memory/tests/sc-memory/events/sc-event-threading.cpp @@ -1,10 +1,9 @@ #include +#include "event_test_utils.hpp" #include "sc-memory/sc_event.hpp" #include "sc-memory/sc_timer.hpp" -#include "event_test_utils.hpp" - #include #include #include @@ -30,42 +29,41 @@ TEST_F(ScEventTest, threading_smoke) } // create random events for each node - std::vector events; + std::vector events; events.resize(eventsNum); - std::vector eventTypes = - { - ScEvent::Type::AddOutputEdge, - ScEvent::Type::AddInputEdge, - ScEvent::Type::RemoveOutputEdge, - ScEvent::Type::RemoveInputEdge, - ScEvent::Type::EraseElement, - ScEvent::Type::ContentChanged - }; + std::vector eventTypes = { + ScEvent::Type::AddOutputEdge, + ScEvent::Type::AddInputEdge, + ScEvent::Type::RemoveOutputEdge, + ScEvent::Type::RemoveInputEdge, + ScEvent::Type::EraseElement, + ScEvent::Type::ContentChanged}; auto const randNode = [&nodes]() { return nodes[std::rand() % nodes.size()]; }; - std::atomic_int evtCount = { 0 }; + std::atomic_int evtCount = {0}; for (size_t i = 0; i < eventsNum; ++i) { - events[i] = new ScEvent(*m_ctx, - randNode(), - eventTypes[std::rand() % (eventTypes.size() - 1)], // ignore ContentChanged event + events[i] = new ScEvent( + *m_ctx, + randNode(), + eventTypes[std::rand() % (eventTypes.size() - 1)], // ignore ContentChanged event [&](ScAddr const &, ScAddr const &, ScAddr const &) - { - evtCount++; - return true; - }); + { + evtCount++; + return true; + }); } ScTimer timer; - std::atomic_int createEdgeCount = { 0 }; - std::atomic_int eraseNodeCount = { 0 }; + std::atomic_int createEdgeCount = {0}; + std::atomic_int eraseNodeCount = {0}; std::vector edges; edges.reserve(testCount); @@ -80,7 +78,7 @@ TEST_F(ScEventTest, threading_smoke) createEdgeCount++; } - else if (v == 1) // will also erase edges + else if (v == 1) // will also erase edges { if (nodes.size() > 2) { diff --git a/sc-memory/tests/sc-memory/events/sc-event.cpp b/sc-memory/tests/sc-memory/events/sc-event.cpp index 4fd123fcb..30a3d0de0 100644 --- a/sc-memory/tests/sc-memory/events/sc-event.cpp +++ b/sc-memory/tests/sc-memory/events/sc-event.cpp @@ -1,28 +1,26 @@ #include +#include "event_test_utils.hpp" #include "sc-memory/sc_event.hpp" #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_templates.hpp" #include "sc-memory/sc_timer.hpp" -#include "event_test_utils.hpp" - #include -#include #include +#include namespace { const double kTestTimeout = 5.0; -template +template void testEventsFuncT(ScMemoryContext & ctx, ScAddr const & addr, PrepareF prepare, EmitF emit) { prepare(); volatile bool isDone = false; - auto const callback = - [&isDone](ScAddr const &, ScAddr const &, ScAddr const &) + auto const callback = [&isDone](ScAddr const &, ScAddr const &, ScAddr const &) { isDone = true; return true; @@ -39,7 +37,7 @@ void testEventsFuncT(ScMemoryContext & ctx, ScAddr const & addr, PrepareF prepar EXPECT_TRUE(isDone); } -} // namespace +} // namespace TEST_F(ScEventTest, AddInputEdge) { @@ -158,11 +156,13 @@ TEST_F(ScEventTest, destroy_order) ScAddr const node = m_ctx->CreateNode(ScType::Unknown); EXPECT_TRUE(node.IsValid()); - ScEventAddOutputEdge * evt = new ScEventAddOutputEdge(*m_ctx, node, - [](ScAddr const &, ScAddr const &, ScAddr const &) - { - return true; - }); + ScEventAddOutputEdge * evt = new ScEventAddOutputEdge( + *m_ctx, + node, + [](ScAddr const &, ScAddr const &, ScAddr const &) + { + return true; + }); m_ctx.reset(); @@ -175,19 +175,21 @@ TEST_F(ScEventTest, events_lock) ScAddr const node = m_ctx->CreateNode(ScType::NodeConst); ScAddr const node2 = m_ctx->CreateNode(ScType::NodeConst); - ScEventAddOutputEdge evt(*m_ctx, node, - [](ScAddr const & addr, ScAddr const &, ScAddr const &) - { - bool result = false; - ScMemoryContext localCtx(sc_access_lvl_make_min); - ScIterator3Ptr it = localCtx.Iterator3(addr, ScType::EdgeAccessConstPosPerm, ScType::Unknown); - while (it->Next()) - result = true; + ScEventAddOutputEdge evt( + *m_ctx, + node, + [](ScAddr const & addr, ScAddr const &, ScAddr const &) + { + bool result = false; + ScMemoryContext localCtx(sc_access_lvl_make_min); + ScIterator3Ptr it = localCtx.Iterator3(addr, ScType::EdgeAccessConstPosPerm, ScType::Unknown); + while (it->Next()) + result = true; - EXPECT_TRUE(result); + EXPECT_TRUE(result); - return result; - }); + return result; + }); for (size_t i = 0; i < 10000; i++) m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, node, node2); @@ -214,12 +216,7 @@ TEST_F(ScEventTest, pend_events) ScTemplateBuilder builder; for (auto const & a : elements) { - builder.TripleWithRelation( - set1, - ScType::EdgeDCommonVar, - a, - ScType::EdgeAccessVarPosPerm, - rel); + builder.TripleWithRelation(set1, ScType::EdgeDCommonVar, a, ScType::EdgeAccessVarPosPerm, rel); } ScTemplatePtr templ = builder.Make(); @@ -227,37 +224,35 @@ TEST_F(ScEventTest, pend_events) std::atomic_uint eventsCount(0); std::atomic_uint passedCount(0); - ScEventAddOutputEdge evt(*m_ctx, set1, - [&passedCount, &eventsCount, &set1, &elements, &rel](ScAddr const &, ScAddr const &, ScAddr const &) - { - ScTemplateBuilder checkBuilder; - size_t step = 100; - size_t testNum = el_num / step - 1; - for (size_t i = 0; i < testNum; ++i) - { - checkBuilder.TripleWithRelation( - set1, - ScType::EdgeDCommonVar, - elements[i * step], - ScType::EdgeAccessVarPosPerm, - rel); - } + ScEventAddOutputEdge evt( + *m_ctx, + set1, + [&passedCount, &eventsCount, &set1, &elements, &rel](ScAddr const &, ScAddr const &, ScAddr const &) + { + ScTemplateBuilder checkBuilder; + size_t step = 100; + size_t testNum = el_num / step - 1; + for (size_t i = 0; i < testNum; ++i) + { + checkBuilder.TripleWithRelation( + set1, ScType::EdgeDCommonVar, elements[i * step], ScType::EdgeAccessVarPosPerm, rel); + } - ScTemplatePtr checkTempl = checkBuilder.Make(); + ScTemplatePtr checkTempl = checkBuilder.Make(); - ScMemoryContext localCtx(sc_access_lvl_make_min); + ScMemoryContext localCtx(sc_access_lvl_make_min); - ScTemplateSearch checkSearch(localCtx, *checkTempl); - ScTemplateSearch::Iterator found = checkSearch.begin(); - EXPECT_TRUE(found != checkSearch.end()); + ScTemplateSearch checkSearch(localCtx, *checkTempl); + ScTemplateSearch::Iterator found = checkSearch.begin(); + EXPECT_TRUE(found != checkSearch.end()); - if (++found == checkSearch.end()) - passedCount.fetch_add(1); + if (++found == checkSearch.end()) + passedCount.fetch_add(1); - eventsCount.fetch_add(1); + eventsCount.fetch_add(1); - return true; - }); + return true; + }); ScTemplateGenerate generator(*m_ctx, *templ); EXPECT_TRUE(generator.Do()); diff --git a/sc-memory/tests/sc-memory/events/sc-wait.cpp b/sc-memory/tests/sc-memory/events/sc-wait.cpp index be6346e87..67846a071 100644 --- a/sc-memory/tests/sc-memory/events/sc-wait.cpp +++ b/sc-memory/tests/sc-memory/events/sc-wait.cpp @@ -1,15 +1,13 @@ #include -#include "sc-memory/kpm/sc_agent.hpp" +#include "sc_test.hpp" +#include "sc-memory/kpm/sc_agent.hpp" #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_wait.hpp" -#include "sc_test.hpp" - namespace { - // waiters threads struct WaitTestData { @@ -38,7 +36,7 @@ void EmitEvent(WaitTestData & data) data.m_isDone = edge.IsValid(); } -} +} // namespace class ScWaitTest : public ScMemoryTest { @@ -70,9 +68,11 @@ TEST_F(ScWaitTest, valid) { WaitTestData data(m_addr); ScWaitEvent waiter(*m_ctx, m_addr); - waiter.SetOnWaitStartDelegate([&data]() { - EmitEvent(data); - }); + waiter.SetOnWaitStartDelegate( + [&data]() + { + EmitEvent(data); + }); EXPECT_TRUE(waiter.Wait()); EXPECT_TRUE(data.m_isDone); @@ -86,16 +86,19 @@ TEST_F(ScWaitTest, TimeOut) TEST_F(ScWaitTest, CondValid) { WaitTestData data(m_addr); - ScWaitCondition waiter(*m_ctx, m_addr, + ScWaitCondition waiter( + *m_ctx, + m_addr, [](ScAddr const &, ScAddr const &, ScAddr const &) - { - return true; - }); + { + return true; + }); - waiter.SetOnWaitStartDelegate([&data]() - { - EmitEvent(data); - }); + waiter.SetOnWaitStartDelegate( + [&data]() + { + EmitEvent(data); + }); EXPECT_TRUE(waiter.Wait()); EXPECT_TRUE(data.m_isDone); @@ -105,15 +108,19 @@ TEST_F(ScWaitTest, CondValidFalse) { WaitTestData data(m_addr); - ScWaitCondition waiter(*m_ctx, m_addr, - [](ScAddr const &, ScAddr const &, ScAddr const &) - { - return false; - }); + ScWaitCondition waiter( + *m_ctx, + m_addr, + [](ScAddr const &, ScAddr const &, ScAddr const &) + { + return false; + }); - waiter.SetOnWaitStartDelegate([&data]() { - EmitEvent(data); - }); + waiter.SetOnWaitStartDelegate( + [&data]() + { + EmitEvent(data); + }); EXPECT_FALSE(waiter.Wait(2000)); EXPECT_TRUE(data.m_isDone); @@ -124,9 +131,11 @@ TEST_F(ScWaitTest, ActionFinished) WaitTestData data(m_addr, ScAgentAction::GetCommandFinishedAddr()); ScWaitActionFinished waiter(*m_ctx, m_addr); - waiter.SetOnWaitStartDelegate([&data]() { - EmitEvent(data); - }); + waiter.SetOnWaitStartDelegate( + [&data]() + { + EmitEvent(data); + }); EXPECT_TRUE(waiter.Wait()); EXPECT_TRUE(data.m_isDone); diff --git a/sc-memory/tests/sc-memory/performance/main.cpp b/sc-memory/tests/sc-memory/performance/main.cpp index 6b1921e63..0c95b123e 100644 --- a/sc-memory/tests/sc-memory/performance/main.cpp +++ b/sc-memory/tests/sc-memory/performance/main.cpp @@ -1,21 +1,19 @@ -#include +#include "sc_code_base_vs_extend.hpp" #include "memory_create_edge.hpp" -#include "memory_create_node.hpp" #include "memory_create_link.hpp" +#include "memory_create_node.hpp" #include "memory_delete_elements.hpp" - -#include "sc_code_base_vs_extend.hpp" - #include "template_search_complex.hpp" #include "template_search_smoke.hpp" #include +#include template void BM_MemoryThreaded(benchmark::State & state) { - static std::atomic_int gCtxNum = { 0 }; + static std::atomic_int gCtxNum = {0}; BMType test; if (state.thread_index == 0) test.Initialize(); @@ -58,24 +56,24 @@ BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) - ->Threads(2) - ->Iterations(kNodeIters / 2) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(2) + ->Iterations(kNodeIters / 2) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) - ->Threads(4) - ->Iterations(kNodeIters / 4) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(4) + ->Iterations(kNodeIters / 4) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) - ->Threads(8) - ->Iterations(kNodeIters / 8) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(8) + ->Iterations(kNodeIters / 8) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateNode) - ->Threads(16) - ->Iterations(kNodeIters / 16) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(16) + ->Iterations(kNodeIters / 16) + ->Unit(benchmark::TimeUnit::kMicrosecond); int constexpr kLinkIters = 2500; @@ -85,24 +83,24 @@ BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) - ->Threads(2) - ->Iterations(kLinkIters / 2) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(2) + ->Iterations(kLinkIters / 2) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) - ->Threads(4) - ->Iterations(kLinkIters / 4) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(4) + ->Iterations(kLinkIters / 4) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) - ->Threads(8) - ->Iterations(kLinkIters / 8) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(8) + ->Iterations(kLinkIters / 8) + ->Unit(benchmark::TimeUnit::kMicrosecond); BENCHMARK_TEMPLATE(BM_MemoryThreaded, TestCreateLink) - ->Threads(16) - ->Iterations(kLinkIters / 64) - ->Unit(benchmark::TimeUnit::kMicrosecond); + ->Threads(16) + ->Iterations(kLinkIters / 64) + ->Unit(benchmark::TimeUnit::kMicrosecond); // ------------------------------------ template @@ -120,11 +118,9 @@ void BM_Memory(benchmark::State & state) test.Shutdown(); } -BENCHMARK_TEMPLATE(BM_Memory, TestCreateNode) - ->Unit(benchmark::TimeUnit::kMicrosecond); +BENCHMARK_TEMPLATE(BM_Memory, TestCreateNode)->Unit(benchmark::TimeUnit::kMicrosecond); -BENCHMARK_TEMPLATE(BM_Memory, TestCreateLink) - ->Unit(benchmark::TimeUnit::kMicrosecond); +BENCHMARK_TEMPLATE(BM_Memory, TestCreateLink)->Unit(benchmark::TimeUnit::kMicrosecond); template void BM_MemoryRanged(benchmark::State & state) @@ -142,14 +138,16 @@ void BM_MemoryRanged(benchmark::State & state) } BENCHMARK_TEMPLATE(BM_MemoryRanged, TestCreateEdge) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(1000) - ->Iterations(5000000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(1000) + ->Iterations(5000000); BENCHMARK_TEMPLATE(BM_MemoryRanged, TestDeleteElements) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(10)->Arg(100)->Arg(1000) - ->Iterations(5000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(10) + ->Arg(100) + ->Arg(1000) + ->Iterations(5000); // ------------------------------------ template @@ -163,7 +161,7 @@ void BM_Template(benchmark::State & state) if (!test.Run()) state.SkipWithError("Empty result"); - ++iterations; + ++iterations; } state.counters["rate"] = benchmark::Counter(iterations, benchmark::Counter::kIsRate); test.Shutdown(); @@ -171,55 +169,55 @@ void BM_Template(benchmark::State & state) // Template search BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchSmoke) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(5)->Iterations(500000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(5) + ->Iterations(500000); BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchSmoke) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(50)->Iterations(50000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(50) + ->Iterations(50000); BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchSmoke) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(500)->Iterations(5000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(500) + ->Iterations(5000); BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchComplex) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(5)->Iterations(1000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(5) + ->Iterations(1000); BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchComplex) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(50)->Iterations(100); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(50) + ->Iterations(100); BENCHMARK_TEMPLATE(BM_Template, TestTemplateSearchComplex) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(500) - ->Iterations(10); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(500) + ->Iterations(10); // SC-code base vs extended -BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(1000) - ->Iterations(500); +BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase)->Unit(benchmark::TimeUnit::kMicrosecond)->Arg(1000)->Iterations(500); -BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(10000)->Iterations(50); +BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase)->Unit(benchmark::TimeUnit::kMicrosecond)->Arg(10000)->Iterations(50); -BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(100000)->Iterations(5); +BENCHMARK_TEMPLATE(BM_Template, TestScCodeBase)->Unit(benchmark::TimeUnit::kMicrosecond)->Arg(100000)->Iterations(5); BENCHMARK_TEMPLATE(BM_Template, TestScCodeExtended) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(1000)->Iterations(1000); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(1000) + ->Iterations(1000); BENCHMARK_TEMPLATE(BM_Template, TestScCodeExtended) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(10000)->Iterations(100); + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(10000) + ->Iterations(100); BENCHMARK_TEMPLATE(BM_Template, TestScCodeExtended) - ->Unit(benchmark::TimeUnit::kMicrosecond) - ->Arg(100000)->Iterations(10); - + ->Unit(benchmark::TimeUnit::kMicrosecond) + ->Arg(100000) + ->Iterations(10); BENCHMARK_MAIN(); diff --git a/sc-memory/tests/sc-memory/performance/memory_create_edge.hpp b/sc-memory/tests/sc-memory/performance/memory_create_edge.hpp index 6a6dbdeef..4336529df 100644 --- a/sc-memory/tests/sc-memory/performance/memory_create_edge.hpp +++ b/sc-memory/tests/sc-memory/performance/memory_create_edge.hpp @@ -7,9 +7,8 @@ class TestCreateEdge : public TestMemory public: void Run() { - m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, - m_nodes[rand() % m_nodes.size()], - m_nodes[rand() % m_nodes.size()]); + m_ctx->CreateEdge( + ScType::EdgeAccessConstPosPerm, m_nodes[rand() % m_nodes.size()], m_nodes[rand() % m_nodes.size()]); } void Setup(size_t elementsNum) override diff --git a/sc-memory/tests/sc-memory/performance/memory_create_link.hpp b/sc-memory/tests/sc-memory/performance/memory_create_link.hpp index 9c11a6092..856ff9eba 100644 --- a/sc-memory/tests/sc-memory/performance/memory_create_link.hpp +++ b/sc-memory/tests/sc-memory/performance/memory_create_link.hpp @@ -1,7 +1,6 @@ #pragma once #include "memory_test.hpp" - #include "sc-memory/sc_link.hpp" class TestCreateLink : public TestMemory diff --git a/sc-memory/tests/sc-memory/performance/memory_test.hpp b/sc-memory/tests/sc-memory/performance/memory_test.hpp index b8b06995d..85603bb73 100644 --- a/sc-memory/tests/sc-memory/performance/memory_test.hpp +++ b/sc-memory/tests/sc-memory/performance/memory_test.hpp @@ -43,7 +43,9 @@ class TestMemory return static_cast(m_ctx); } - virtual void Setup(size_t objectsNum) {} + virtual void Setup(size_t objectsNum) + { + } protected: std::unique_ptr m_ctx; diff --git a/sc-memory/tests/sc-memory/performance/sc_code_base_vs_extend.hpp b/sc-memory/tests/sc-memory/performance/sc_code_base_vs_extend.hpp index 63190c1e6..b29123ff5 100644 --- a/sc-memory/tests/sc-memory/performance/sc_code_base_vs_extend.hpp +++ b/sc-memory/tests/sc-memory/performance/sc_code_base_vs_extend.hpp @@ -5,7 +5,6 @@ class TestScCodeExtended : public TestTemplate { public: - void Setup(size_t constrCount) override { ScAddr const node = m_ctx->CreateNode(ScType::NodeConstClass); @@ -18,20 +17,15 @@ class TestScCodeExtended : public TestTemplate } m_templ = ScTemplateBuilder() - .TripleWithRelation( - node, - ScType::EdgeDCommonVar, - ScType::NodeVarAbstract, - ScType::EdgeAccessVarPosPerm, - attr) - .Make(); + .TripleWithRelation( + node, ScType::EdgeDCommonVar, ScType::NodeVarAbstract, ScType::EdgeAccessVarPosPerm, attr) + .Make(); } }; class TestScCodeBase : public TestTemplate { public: - void Setup(size_t constrCount) override { ScAddr const kAbstract = m_ctx->CreateNode(ScType::NodeConst); @@ -60,40 +54,19 @@ class TestScCodeBase : public TestTemplate } m_templ = ScTemplateBuilder() - .TripleWithRelation( - node >> "_node", - ScType::EdgeDCommonVar >> "_edge", - ScType::NodeVarAbstract >> "_trg", - ScType::EdgeAccessVarPosPerm, - attr >> "_attr") - .Triple( - kConst, - ScType::EdgeAccessVarPosPerm, - "_node") - .Triple( - kClass, - ScType::EdgeAccessVarPosPerm, - "_node") - .Triple( - kConst, - ScType::EdgeAccessVarPosPerm, - "_attr") - .Triple( - kRole, - ScType::EdgeAccessVarPosPerm, - "_attr") - .Triple( - kAbstract, - ScType::EdgeAccessVarPosPerm, - "_trg") - .Triple( - kConst, - ScType::EdgeAccessVarPosPerm, - "_trg") - .Triple( - kConst, - ScType::EdgeAccessVarPosPerm, - "_edge") - .Make(); + .TripleWithRelation( + node >> "_node", + ScType::EdgeDCommonVar >> "_edge", + ScType::NodeVarAbstract >> "_trg", + ScType::EdgeAccessVarPosPerm, + attr >> "_attr") + .Triple(kConst, ScType::EdgeAccessVarPosPerm, "_node") + .Triple(kClass, ScType::EdgeAccessVarPosPerm, "_node") + .Triple(kConst, ScType::EdgeAccessVarPosPerm, "_attr") + .Triple(kRole, ScType::EdgeAccessVarPosPerm, "_attr") + .Triple(kAbstract, ScType::EdgeAccessVarPosPerm, "_trg") + .Triple(kConst, ScType::EdgeAccessVarPosPerm, "_trg") + .Triple(kConst, ScType::EdgeAccessVarPosPerm, "_edge") + .Make(); } }; diff --git a/sc-memory/tests/sc-memory/performance/template_search_complex.hpp b/sc-memory/tests/sc-memory/performance/template_search_complex.hpp index b50e8bc7b..ec37fd2bf 100644 --- a/sc-memory/tests/sc-memory/performance/template_search_complex.hpp +++ b/sc-memory/tests/sc-memory/performance/template_search_complex.hpp @@ -9,23 +9,20 @@ class TestTemplateSearchComplex : public TestTemplate { ScAddr const node = m_ctx->CreateNode(ScType::NodeConstStruct); m_templ = ScTemplateBuilder() - .TripleWithRelation( - node, - ScType::EdgeDCommonVar, - ScType::NodeVarTuple >> "_tuple", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarNoRole) - .TripleWithRelation( - ScType::NodeVarClass, - ScType::EdgeDCommonVar, - "_tuple", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarNoRole) - .Triple( - ScType::NodeVarClass, - ScType::EdgeAccessVarPosPerm, - node) - .Make(); + .TripleWithRelation( + node, + ScType::EdgeDCommonVar, + ScType::NodeVarTuple >> "_tuple", + ScType::EdgeAccessVarPosPerm, + ScType::NodeVarNoRole) + .TripleWithRelation( + ScType::NodeVarClass, + ScType::EdgeDCommonVar, + "_tuple", + ScType::EdgeAccessVarPosPerm, + ScType::NodeVarNoRole) + .Triple(ScType::NodeVarClass, ScType::EdgeAccessVarPosPerm, node) + .Make(); for (size_t i = 0; i < constrCount; ++i) { diff --git a/sc-memory/tests/sc-memory/performance/template_search_smoke.hpp b/sc-memory/tests/sc-memory/performance/template_search_smoke.hpp index ef516b45f..540832cb6 100644 --- a/sc-memory/tests/sc-memory/performance/template_search_smoke.hpp +++ b/sc-memory/tests/sc-memory/performance/template_search_smoke.hpp @@ -15,11 +15,6 @@ class TestTemplateSearchSmoke : public TestTemplate m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, node, trg); } - m_templ = ScTemplateBuilder() - .Triple( - node, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarStruct) - .Make(); + m_templ = ScTemplateBuilder().Triple(node, ScType::EdgeAccessVarPosPerm, ScType::NodeVarStruct).Make(); } }; diff --git a/sc-memory/tests/sc-memory/scs/scs-helper.cpp b/sc-memory/tests/sc-memory/scs/scs-helper.cpp index eacca6a46..787e4e7a5 100644 --- a/sc-memory/tests/sc-memory/scs/scs-helper.cpp +++ b/sc-memory/tests/sc-memory/scs/scs-helper.cpp @@ -1,24 +1,22 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_link.hpp" #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_scs_helper.hpp" #include "sc-memory/sc_templates.hpp" - #include "scs_test_utils.hpp" -#include "sc_test.hpp" - using SCsHelperTest = ScMemoryTest; TEST_F(SCsHelperTest, GenerateBySCs) { - std::vector> tests = - { - { "x -> y;;", "x _-> _y;;" }, - { "x1 => nrel_x1: [test_content*];;", "x1 _=> nrel_x1:: _[];;" }, - { "x2 ~> y2 (* <- z2;; *);;", "x2 _~> _y2 (* _<- _z2;; *);;" }, - { "x3 <- y3 (* <- sc_node_class;; *);;", "sc_node_class -> _y3;; _y3 _-> x3;;" }, + std::vector> tests = { + {"x -> y;;", "x _-> _y;;"}, + {"x1 => nrel_x1: [test_content*];;", "x1 _=> nrel_x1:: _[];;"}, + {"x2 ~> y2 (* <- z2;; *);;", "x2 _~> _y2 (* _<- _z2;; *);;"}, + {"x3 <- y3 (* <- sc_node_class;; *);;", "sc_node_class -> _y3;; _y3 _-> x3;;"}, }; for (auto const & t : tests) @@ -47,11 +45,8 @@ TEST_F(SCsHelperTest, GenerateBySCs_FileURL) ScAddr const xAddr = m_ctx->HelperResolveSystemIdtf("x"); EXPECT_TRUE(xAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(xAddr, - ScType::EdgeAccessVarPosPerm, - ScType::LinkVar >> "_link") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(xAddr, ScType::EdgeAccessVarPosPerm, ScType::LinkVar >> "_link").Make(); EXPECT_TRUE(templ); ScTemplateSearch search(*m_ctx, *templ); @@ -92,10 +87,10 @@ TEST_F(SCsHelperTest, GenerateBySCs_Aliases) TEST_F(SCsHelperTest, GenerateBySCs_NestedAliases) { std::string const data = - "a -> b;;" - "@link_a = a;;" - "@link_b = b;;" - "@edge_alias = (@link_a -> @link_b);;"; + "a -> b;;" + "@link_a = a;;" + "@link_b = b;;" + "@edge_alias = (@link_a -> @link_b);;"; SCsHelper helper(*m_ctx, std::make_shared()); EXPECT_TRUE(helper.GenerateBySCsText(data)); @@ -106,11 +101,7 @@ TEST_F(SCsHelperTest, GenerateBySCs_NestedAliases) ScAddr const bAddr = m_ctx->HelperResolveSystemIdtf("b"); EXPECT_TRUE(bAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(aAddr, - ScType::EdgeAccessVarPosPerm, - bAddr) - .Make(); + ScTemplatePtr templ = ScTemplateBuilder().Triple(aAddr, ScType::EdgeAccessVarPosPerm, bAddr).Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator result = search.begin(); @@ -121,8 +112,9 @@ TEST_F(SCsHelperTest, GenerateBySCs_NestedAliases) TEST_F(SCsHelperTest, GenerateBySCs_EdgeAlias) { - std::string const data = "@edge_alias = (c -> b);;" - "a -> @edge_alias;;"; + std::string const data = + "@edge_alias = (c -> b);;" + "a -> @edge_alias;;"; SCsHelper helper(*m_ctx, std::make_shared()); EXPECT_TRUE(helper.GenerateBySCsText(data)); @@ -135,14 +127,10 @@ TEST_F(SCsHelperTest, GenerateBySCs_EdgeAlias) ScAddr const cAddr = m_ctx->HelperResolveSystemIdtf("c"); EXPECT_TRUE(cAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - cAddr, - ScType::EdgeAccessVarPosPerm, - bAddr, - ScType::EdgeAccessVarPosPerm, - aAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation(cAddr, ScType::EdgeAccessVarPosPerm, bAddr, ScType::EdgeAccessVarPosPerm, aAddr) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator result = search.begin(); @@ -152,8 +140,9 @@ TEST_F(SCsHelperTest, GenerateBySCs_EdgeAlias) TEST_F(SCsHelperTest, GenerateBySCs_ContourAlias) { - std::string const data = "@alias = [* x -> y;; *];;" - "z -> @alias;;"; + std::string const data = + "@alias = [* x -> y;; *];;" + "z -> @alias;;"; SCsHelper helper(*m_ctx, std::make_shared()); EXPECT_TRUE(helper.GenerateBySCsText(data)); @@ -167,27 +156,12 @@ TEST_F(SCsHelperTest, GenerateBySCs_ContourAlias) EXPECT_TRUE(zAddr.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - zAddr, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarStruct >> "_contour") - .Triple( - "_contour", - ScType::EdgeAccessVarPosPerm, - xAddr) - .Triple( - "_contour", - ScType::EdgeAccessVarPosPerm, - yAddr) - .Triple( - xAddr, - ScType::EdgeAccessVarPosPerm >> "_edge", - yAddr) - .Triple( - "_contour", - ScType::EdgeAccessVarPosPerm, - "_edge") - .Make(); + .Triple(zAddr, ScType::EdgeAccessVarPosPerm, ScType::NodeVarStruct >> "_contour") + .Triple("_contour", ScType::EdgeAccessVarPosPerm, xAddr) + .Triple("_contour", ScType::EdgeAccessVarPosPerm, yAddr) + .Triple(xAddr, ScType::EdgeAccessVarPosPerm >> "_edge", yAddr) + .Triple("_contour", ScType::EdgeAccessVarPosPerm, "_edge") + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator result = search.begin(); @@ -198,13 +172,13 @@ TEST_F(SCsHelperTest, GenerateBySCs_ContourAlias) TEST_F(SCsHelperTest, GenerateBySCs_Contents) { std::string const dataString = "v_string -> [string];;"; - std::string const dataFloat = "v_float -> [^\"float:7\"];;"; + std::string const dataFloat = "v_float -> [^\"float:7\"];;"; std::string const dataDouble = "v_double -> [^\"double:8\"];;"; - std::string const dataInt8 = "v_int8 -> [^\"int8:9\"];;"; - std::string const dataInt16 = "v_int16 -> [^\"int16:10\"];;"; - std::string const dataInt32 = "v_int32 -> [^\"int32:11\"];;"; - std::string const dataInt64 = "v_int64 -> [^\"int64:12\"];;"; - std::string const dataUint8 = "v_uint8 -> [^\"uint8:13\"];;"; + std::string const dataInt8 = "v_int8 -> [^\"int8:9\"];;"; + std::string const dataInt16 = "v_int16 -> [^\"int16:10\"];;"; + std::string const dataInt32 = "v_int32 -> [^\"int32:11\"];;"; + std::string const dataInt64 = "v_int64 -> [^\"int64:12\"];;"; + std::string const dataUint8 = "v_uint8 -> [^\"uint8:13\"];;"; std::string const dataUint16 = "v_uint16 -> [^\"uint16:14\"];;"; std::string const dataUint32 = "v_uint32 -> [^\"uint32:15\"];;"; std::string const dataUint64 = "v_uint64 -> [^\"uint64:16\"];;"; @@ -215,12 +189,8 @@ TEST_F(SCsHelperTest, GenerateBySCs_Contents) EXPECT_TRUE(helper.GenerateBySCsText(data)); ScAddr const kAddr = m_ctx->HelperResolveSystemIdtf(keynode); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - kAddr, - ScType::EdgeAccessVarPosPerm, - ScType::LinkVar >> "_link") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(kAddr, ScType::EdgeAccessVarPosPerm, ScType::LinkVar >> "_link").Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator result = search.begin(); @@ -329,30 +299,20 @@ TEST_F(SCsHelperTest, GenerateBySCs_Visibility_System) EXPECT_TRUE(zAddr.IsValid()); { - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - xAddr, - ScType::EdgeAccessVarPosPerm, - yAddr) - .Make(); + ScTemplatePtr templ = ScTemplateBuilder().Triple(xAddr, ScType::EdgeAccessVarPosPerm, yAddr).Make(); ScTemplateSearch search(*m_ctx, *templ); EXPECT_NE(search.begin(), search.end()); } { - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(xAddr, - ScType::EdgeAccessVarPosTemp, - zAddr) - .Make(); + ScTemplatePtr templ = ScTemplateBuilder().Triple(xAddr, ScType::EdgeAccessVarPosTemp, zAddr).Make(); ScTemplateSearch search(*m_ctx, *templ); EXPECT_NE(search.begin(), search.end()); } } - TEST_F(SCsHelperTest, GenerateBySCs_Visibility_Global) { SCsHelper helper(*m_ctx, std::make_shared()); @@ -368,11 +328,8 @@ TEST_F(SCsHelperTest, GenerateBySCs_Visibility_Global) ScAddr const xAddr = m_ctx->HelperResolveSystemIdtf("x_global"); EXPECT_TRUE(xAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(xAddr, - ScType::EdgeAccessVarPosPerm >> "_edge", - ScType::Unknown >> "_trg") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(xAddr, ScType::EdgeAccessVarPosPerm >> "_edge", ScType::Unknown >> "_trg").Make(); ScTemplateSearch search(*m_ctx, *templ); std::vector> values; @@ -401,11 +358,8 @@ TEST_F(SCsHelperTest, GenerateBySCs_Visibility_Local) ScAddr const xAddr = m_ctx->HelperResolveSystemIdtf("x_local"); EXPECT_TRUE(xAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(xAddr, - ScType::EdgeAccessVarPosPerm, - ScType::Unknown >> "_trg") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(xAddr, ScType::EdgeAccessVarPosPerm, ScType::Unknown >> "_trg").Make(); ScTemplateSearch search(*m_ctx, *templ); std::vector values; diff --git a/sc-memory/tests/sc-memory/scs/scs-regression.cpp b/sc-memory/tests/sc-memory/scs/scs-regression.cpp index 6914b9a71..d9fe66dce 100644 --- a/sc-memory/tests/sc-memory/scs/scs-regression.cpp +++ b/sc-memory/tests/sc-memory/scs/scs-regression.cpp @@ -1,11 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_scs_helper.hpp" #include "sc-memory/sc_templates.hpp" - -#include "sc_test.hpp" - #include "scs_test_utils.hpp" using SCsHelperRegressionTest = ScMemoryTest; @@ -14,7 +13,7 @@ TEST_F(SCsHelperRegressionTest, issue_353) { std::string const data = "a -> [*" - "_x <- sc_node_class;;" + "_x <- sc_node_class;;" "*];;"; SCsHelper helper(*m_ctx, std::make_shared()); @@ -31,23 +30,12 @@ TEST_F(SCsHelperRegressionTest, issue_353) EXPECT_TRUE(_xAddr.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .Triple(aAddr, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarStruct >> "_struct") - .Triple(classAddr, - ScType::EdgeAccessVarPosPerm >> "_edge", - _xAddr) - .Triple("_struct", - ScType::EdgeAccessVarPosPerm, - classAddr) - .Triple("_struct", - ScType::EdgeAccessVarPosPerm, - "_edge") - .Triple("_struct", - ScType::EdgeAccessVarPosPerm, - _xAddr) - .Make(); - + .Triple(aAddr, ScType::EdgeAccessVarPosPerm, ScType::NodeVarStruct >> "_struct") + .Triple(classAddr, ScType::EdgeAccessVarPosPerm >> "_edge", _xAddr) + .Triple("_struct", ScType::EdgeAccessVarPosPerm, classAddr) + .Triple("_struct", ScType::EdgeAccessVarPosPerm, "_edge") + .Triple("_struct", ScType::EdgeAccessVarPosPerm, _xAddr) + .Make(); ScTemplateSearch result(*m_ctx, *templ); ScTemplateSearch::Iterator found = result.begin(); diff --git a/sc-memory/tests/sc-memory/scs/scs_test_utils.hpp b/sc-memory/tests/sc-memory/scs/scs_test_utils.hpp index 99ade7e0b..c34bcad05 100644 --- a/sc-memory/tests/sc-memory/scs/scs_test_utils.hpp +++ b/sc-memory/tests/sc-memory/scs/scs_test_utils.hpp @@ -5,7 +5,9 @@ class TestFileInterface : public SCsFileInterface { public: - ~TestFileInterface() override {} + ~TestFileInterface() override + { + } ScStreamPtr GetFileContent(std::string const & fileURL) override { diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-build.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-build.cpp index cf597c04b..58e8b6f3a 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-build.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-build.cpp @@ -1,10 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_struct.hpp" #include "sc-memory/sc_templates.hpp" - -#include "sc_test.hpp" #include "template_test_utils.hpp" using ScTemplateBuidlerTest = ScTemplateTest; @@ -15,11 +15,7 @@ TEST_F(ScTemplateBuidlerTest, addrs_in_repls) ScAddr const addr = m_ctx->CreateNode(ScType::NodeConst); EXPECT_TRUE(addr); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr >> "_x", - ScType::EdgeAccessVarNegPerm, - ScType::NodeVar) - .Make(); + ScTemplatePtr templ = ScTemplateBuilder().Triple(addr >> "_x", ScType::EdgeAccessVarNegPerm, ScType::NodeVar).Make(); EXPECT_TRUE(templ); EXPECT_TRUE(templ->HasReplacement("_x")); @@ -59,9 +55,9 @@ TEST_F(ScTemplateStructBuidlerTest, double_attrs) EXPECT_TRUE(templ); }; - testOrder({ addr1, addr2, addr3, addr4, edge1, edge2, edge3 }); - testOrder({ edge3, edge2, edge1, addr4, addr3, addr2, addr1 }); - testOrder({ addr1, addr2, addr3, addr4, edge2, edge1, edge3 }); + testOrder({addr1, addr2, addr3, addr4, edge1, edge2, edge3}); + testOrder({edge3, edge2, edge1, addr4, addr3, addr2, addr1}); + testOrder({addr1, addr2, addr3, addr4, edge2, edge1, edge3}); } TEST_F(ScTemplateStructBuidlerTest, addrs_in_repls) @@ -69,7 +65,8 @@ TEST_F(ScTemplateStructBuidlerTest, addrs_in_repls) // create template in sc-memory { SCsHelper helper(*m_ctx, std::make_shared()); - EXPECT_TRUE(helper.GenerateBySCsText("[* x _-> _y;; *] => nrel_system_identifier: [test_template_parameters_addrs];;")); + EXPECT_TRUE( + helper.GenerateBySCsText("[* x _-> _y;; *] => nrel_system_identifier: [test_template_parameters_addrs];;")); } ScAddr const templAddr = m_ctx->HelperFindBySystemIdtf("test_template_parameters_addrs"); @@ -115,7 +112,7 @@ TEST_F(ScTemplateStructBuidlerTest, edge_from_edge) EXPECT_TRUE(templ); }; - testOrder({ addr1, addr2, addr3, edge1, edge2 }); - testOrder({ edge2, edge1, addr3, addr2, addr1 }); - testOrder({ addr1, addr2, addr3, edge2, edge1 }); + testOrder({addr1, addr2, addr3, edge1, edge2}); + testOrder({edge2, edge1, addr3, addr2, addr1}); + testOrder({addr1, addr2, addr3, edge2, edge1}); } diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-common.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-common.cpp index 10236de44..ee04b97cb 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-common.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-common.cpp @@ -1,11 +1,11 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_struct.hpp" #include "sc-memory/sc_templates.hpp" #include "sc-memory/sc_type.hpp" - -#include "sc_test.hpp" #include "template_test_utils.hpp" using ScTemplateCommonTest = ScTemplateTest; @@ -27,30 +27,18 @@ TEST_F(ScTemplateCommonTest, smoke) ScAddr const edge2 = m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, addr3, edge1); EXPECT_TRUE(edge2.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - addr1 >> "addr1", - ScType::EdgeAccessVarPosPerm >> "edge1", - ScType::NodeVar >> "addr2") - .Triple( - ScType::NodeVar >> "_addr1T2", - ScType::EdgeAccessVarPosPerm >> "_addr2T2", - "edge1") - .Triple( - "addr2", - ScType::EdgeDCommonVar >> "_addr2T3", - "edge1") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple(addr1 >> "addr1", ScType::EdgeAccessVarPosPerm >> "edge1", ScType::NodeVar >> "addr2") + .Triple(ScType::NodeVar >> "_addr1T2", ScType::EdgeAccessVarPosPerm >> "_addr2T2", "edge1") + .Triple("addr2", ScType::EdgeDCommonVar >> "_addr2T3", "edge1") + .Make(); auto const genResult = ScTemplateGenerate(*m_ctx, *templ).Do(); EXPECT_TRUE(genResult); ScIterator5Ptr const it5 = m_ctx->Iterator5( - addr1, - ScType::EdgeAccessConstPosPerm, - ScType::Node, - ScType::EdgeAccessConstPosPerm, - ScType::Node); + addr1, ScType::EdgeAccessConstPosPerm, ScType::Node, ScType::EdgeAccessConstPosPerm, ScType::Node); EXPECT_TRUE(it5->Next()); EXPECT_EQ(it5->Get(0), (*genResult)["addr1"]); @@ -59,17 +47,14 @@ TEST_F(ScTemplateCommonTest, smoke) EXPECT_EQ(it5->Get(3), (*genResult)["_addr2T2"]); EXPECT_EQ(it5->Get(4), (*genResult)["_addr1T2"]); - ScIterator3Ptr const it3 = m_ctx->Iterator3( - (*genResult)["addr2"], - ScType::EdgeDCommon, - ScType::EdgeAccessConstPosPerm); + ScIterator3Ptr const it3 = + m_ctx->Iterator3((*genResult)["addr2"], ScType::EdgeDCommon, ScType::EdgeAccessConstPosPerm); EXPECT_TRUE(it3->Next()); EXPECT_EQ(it3->Get(0), (*genResult)["addr2"]); EXPECT_EQ(it3->Get(1), (*genResult)["_addr2T3"]); EXPECT_EQ(it3->Get(2), (*genResult)["edge1"]); - ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); EXPECT_NE(found, search.end()); @@ -106,11 +91,10 @@ TEST_F(ScTemplateCommonTest, search) edges.push_back(addrEdge); } - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addrSrc >> "addrSrc", - ScType::EdgeAccessVarPosPerm >> "edge", - ScType::NodeVar >> "addrTrg") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple(addrSrc >> "addrSrc", ScType::EdgeAccessVarPosPerm >> "edge", ScType::NodeVar >> "addrTrg") + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -145,14 +129,11 @@ TEST_F(ScTemplateCommonTest, searchTripleWithRelation) EXPECT_TRUE(edge2.IsValid()); { - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - addr1, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVar, - ScType::EdgeAccessVarPosPerm, - addr3) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + addr1, ScType::EdgeAccessVarPosPerm, ScType::NodeVar, ScType::EdgeAccessVarPosPerm, addr3) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -162,13 +143,13 @@ TEST_F(ScTemplateCommonTest, searchTripleWithRelation) { ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - addr1 >> "1", - ScType::EdgeAccessVarPosPerm >> "2", - ScType::NodeVar >> "3", - ScType::EdgeAccessVarPosPerm >> "4", - addr3 >> "5") - .Make(); + .TripleWithRelation( + addr1 >> "1", + ScType::EdgeAccessVarPosPerm >> "2", + ScType::NodeVar >> "3", + ScType::EdgeAccessVarPosPerm >> "4", + addr3 >> "5") + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -183,35 +164,23 @@ TEST_F(ScTemplateCommonTest, params_correct) ScAddr const addrTest3 = m_ctx->CreateNode(ScType::NodeConstTuple); ScAddr const addrTest6 = m_ctx->CreateNode(ScType::NodeConstClass); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - addrConst >> "1", - ScType::EdgeAccessVarPosPerm >> "_2", - ScType::NodeVarTuple >> "_3") - .Triple( - "_3", - ScType::EdgeAccessVarPosPerm >> "_5", - ScType::NodeVarClass >> "_6") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple(addrConst >> "1", ScType::EdgeAccessVarPosPerm >> "_2", ScType::NodeVarTuple >> "_3") + .Triple("_3", ScType::EdgeAccessVarPosPerm >> "_5", ScType::NodeVarClass >> "_6") + .Make(); ScTemplateParams params; - params - .Add("_3", addrTest3) - .Add("_6", addrTest6); + params.Add("_3", addrTest3).Add("_6", addrTest6); ScTemplateGenerate::Result const result = ScTemplateGenerate(*m_ctx, *templ).Do(params); EXPECT_TRUE(result); - ScTemplatePtr searchTempl = ScTemplateBuilder() - .Triple( - addrConst >> "1", - ScType::EdgeAccessVarPosPerm >> "_2", - ScType::NodeVarTuple >> "_3") - .Triple( - "_3", - ScType::EdgeAccessVarPosPerm >> "_5", - ScType::NodeVarClass >> "_6") - .Make(); + ScTemplatePtr searchTempl = + ScTemplateBuilder() + .Triple(addrConst >> "1", ScType::EdgeAccessVarPosPerm >> "_2", ScType::NodeVarTuple >> "_3") + .Triple("_3", ScType::EdgeAccessVarPosPerm >> "_5", ScType::NodeVarClass >> "_6") + .Make(); ScTemplateSearch search(*m_ctx, *searchTempl); ScTemplateSearch::Iterator found = search.begin(); @@ -227,12 +196,13 @@ TEST_F(ScTemplateCommonTest, params_invalid) ScAddr const addrTest3 = m_ctx->CreateNode(ScType::NodeConstTuple); ScAddr const addrEdge2 = m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, addrConst, addrTest3); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - addrConst >> "1", - ScType::EdgeAccessVarPosPerm >> "_2", // can't be replaced by param in template generation - ScType::NodeVar >> "_3") // can't be replaced by param in template generation - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .Triple( + addrConst >> "1", + ScType::EdgeAccessVarPosPerm >> "_2", // can't be replaced by param in template generation + ScType::NodeVar >> "_3") // can't be replaced by param in template generation + .Make(); ScTemplateGenerate::Result result = ScTemplateGenerate(*m_ctx, *templ).Do(); EXPECT_TRUE(result); @@ -250,26 +220,23 @@ TEST_F(ScTemplateCommonTest, params_invalid) { // target is const { - EXPECT_EQ(false, TestTemplParams(*m_ctx)( - addrConst >> "1", - ScType::EdgeAccessVarPosPerm >> "_2", - ScType::NodeConst >> "_3")); + EXPECT_EQ( + false, + TestTemplParams(*m_ctx)(addrConst >> "1", ScType::EdgeAccessVarPosPerm >> "_2", ScType::NodeConst >> "_3")); } // source is const { - EXPECT_EQ(false, TestTemplParams(*m_ctx)( - ScType::NodeConst >> "_1", - ScType::EdgeAccessVarPosPerm >> "_2", - addrConst >> "3")); + EXPECT_EQ( + false, + TestTemplParams(*m_ctx)(ScType::NodeConst >> "_1", ScType::EdgeAccessVarPosPerm >> "_2", addrConst >> "3")); } // edge is const { - EXPECT_EQ(false, TestTemplParams(*m_ctx)( - ScType::NodeVar >> "_1", - ScType::EdgeAccessConstPosPerm >> "_2", - addrConst >> "3")); + EXPECT_EQ( + false, + TestTemplParams(*m_ctx)(ScType::NodeVar >> "_1", ScType::EdgeAccessConstPosPerm >> "_2", addrConst >> "3")); } } } @@ -307,16 +274,19 @@ TEST_F(ScTemplateCommonTest, a_a_a) EXPECT_TRUE(nrel_translationAddr.IsValid()); EXPECT_TRUE(m_ctx->HelperSetSystemIdtf("nrel_translation", nrel_translationAddr)); - ScAddr const _struct_locationEdgeAddr = m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, _structAddr, _apiai_locationAddr); + ScAddr const _struct_locationEdgeAddr = + m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, _structAddr, _apiai_locationAddr); EXPECT_TRUE(_struct_locationEdgeAddr.IsValid()); - ScAddr const _rrel_locationEdgeAddr = m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, rrel_locationAddr, _struct_locationEdgeAddr); + ScAddr const _rrel_locationEdgeAddr = + m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, rrel_locationAddr, _struct_locationEdgeAddr); EXPECT_TRUE(_rrel_locationEdgeAddr.IsValid()); ScAddr const _struct_speechEdgeAddr = m_ctx->CreateEdge(ScType::EdgeDCommonVar, _structAddr, _apiai_speechAddr); EXPECT_TRUE(_struct_speechEdgeAddr.IsValid()); - ScAddr const _nrel_translationEdgeAddr = m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, nrel_translationAddr, _struct_speechEdgeAddr); + ScAddr const _nrel_translationEdgeAddr = + m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, nrel_translationAddr, _struct_speechEdgeAddr); EXPECT_TRUE(_nrel_translationEdgeAddr.IsValid()); ScAddr const _langEdgeAddr = m_ctx->CreateEdge(ScType::EdgeAccessVarPosPerm, _langAddr, _apiai_speechAddr); @@ -327,18 +297,9 @@ TEST_F(ScTemplateCommonTest, a_a_a) EXPECT_TRUE(templStructAddr.IsValid()); ScStruct templStruct(*m_ctx, templStructAddr); - templStruct - << _structAddr - << _apiai_locationAddr - << _apiai_speechAddr - << _langAddr - << rrel_locationAddr - << nrel_translationAddr - << _struct_locationEdgeAddr - << _rrel_locationEdgeAddr - << _struct_speechEdgeAddr - << _nrel_translationEdgeAddr - << _langEdgeAddr; + templStruct << _structAddr << _apiai_locationAddr << _apiai_speechAddr << _langAddr << rrel_locationAddr + << nrel_translationAddr << _struct_locationEdgeAddr << _rrel_locationEdgeAddr << _struct_speechEdgeAddr + << _nrel_translationEdgeAddr << _langEdgeAddr; ScTemplatePtr templ = ScTemplateStructBuilder(*m_ctx).Make(templStructAddr); EXPECT_TRUE(templ); @@ -368,14 +329,11 @@ TEST_F(ScTemplateCommonTest, a_a_a_a_f) ScAddr const xAddr = m_ctx->HelperResolveSystemIdtf("x"); EXPECT_TRUE(xAddr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::Unknown >> "_x", - ScType::EdgeDCommonVar, - ScType::Link, - ScType::EdgeAccessVarPosPerm, - nrelAddr) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + ScType::Unknown >> "_x", ScType::EdgeDCommonVar, ScType::Link, ScType::EdgeAccessVarPosPerm, nrelAddr) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -405,11 +363,7 @@ TEST_F(ScTemplateCommonTest, big_template_smoke) for (auto const & a : elements) { builder.TripleWithRelation( - set1, - ScType::EdgeDCommonVar, - a >> ("_el" + std::to_string(index++)), - ScType::EdgeAccessVarPosPerm, - rel); + set1, ScType::EdgeDCommonVar, a >> ("_el" + std::to_string(index++)), ScType::EdgeAccessVarPosPerm, rel); } ScTemplatePtr templ = builder.Make(); @@ -435,15 +389,9 @@ TEST_F(ScTemplateCommonTest, big_template_smoke) TEST_F(ScTemplateCommonTest, named_struct) { std::string const idtf = "test"; - ScTemplateNamedStruct::NamesMap names = { - { idtf, 1 } - }; + ScTemplateNamedStruct::NamesMap names = {{idtf, 1}}; - ScAddrVector elements = { - ScAddr(1), - ScAddr(2), - ScAddr(3) - }; + ScAddrVector elements = {ScAddr(1), ScAddr(2), ScAddr(3)}; ScAddrVector elementsCopy = elements; ScTemplateNamedStruct::NamesMap namesCopy = names; @@ -473,7 +421,7 @@ TEST_F(ScTemplateCommonTest, named_struct_builder) // test builder ScTemplateNamedStruct::Builder builder(namedStruct); - EXPECT_TRUE(namedStruct.IsEmpty()); // builder clears struct + EXPECT_TRUE(namedStruct.IsEmpty()); // builder clears struct ScAddr const addr1(1); ScAddr const addr2(2); diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-data.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-data.cpp index 27c096ed7..5fb7a734a 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-data.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-data.cpp @@ -1,8 +1,8 @@ #include -#include "sc-memory/sc_templates.hpp" - #include "sc_test.hpp" + +#include "sc-memory/sc_templates.hpp" #include "template_test_utils.hpp" using ScTemplateDataTest = ScTemplateTest; @@ -14,13 +14,9 @@ TEST_F(ScTemplateDataTest, smoke) ScTemplateData data; - data.AddTriple(addr1, - ScType::EdgeAccessVarFuzPerm >> "_edge", - addr2); + data.AddTriple(addr1, ScType::EdgeAccessVarFuzPerm >> "_edge", addr2); - data.AddTriple(ScType::NodeVarAbstract, - ScType::EdgeAccessVarPosPerm, - "_edge"); + data.AddTriple(ScType::NodeVarAbstract, ScType::EdgeAccessVarPosPerm, "_edge"); EXPECT_EQ(data.TriplesNum(), 2u); } @@ -31,9 +27,7 @@ TEST_F(ScTemplateDataTest, Replacements) ScAddr const sourceAddr(21); ScAddr const targetAddr(43); - data.AddTriple(sourceAddr, - ScType::EdgeAccessVarFuzPerm >> "_edge", - targetAddr >> "addr2"); + data.AddTriple(sourceAddr, ScType::EdgeAccessVarFuzPerm >> "_edge", targetAddr >> "addr2"); EXPECT_TRUE(data.HasReplacement("_edge")); EXPECT_TRUE(data.HasReplacement("addr2")); @@ -55,16 +49,10 @@ TEST_F(ScTemplateDataTest, Replacements) TEST_F(ScTemplateDataTest, build_error_double_replacements) { ScTemplateData data; - data.AddTriple(ScAddr(1), - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarClass >> "_test"); - - EXPECT_ANY_THROW( - data.AddTriple(ScType::NodeVarAbstract >> "_test", - ScType::EdgeAccessVarFuzPerm, - ScAddr(2))); -} + data.AddTriple(ScAddr(1), ScType::EdgeAccessVarPosPerm, ScType::NodeVarClass >> "_test"); + EXPECT_ANY_THROW(data.AddTriple(ScType::NodeVarAbstract >> "_test", ScType::EdgeAccessVarFuzPerm, ScAddr(2))); +} TEST_F(ScTemplateDataTest, SetupReplAlias) { @@ -75,9 +63,7 @@ TEST_F(ScTemplateDataTest, SetupReplAlias) std::string const repl = "_repl"; std::string const alias = "_alias"; - data.AddTriple(ScAddr(1), - ScType::EdgeAccessVarFuzTemp >> repl, - ScType::NodeVarAbstract); + data.AddTriple(ScAddr(1), ScType::EdgeAccessVarFuzTemp >> repl, ScType::NodeVarAbstract); EXPECT_FALSE(data.HasReplacement(alias)); EXPECT_TRUE(data.HasReplacement(repl)); diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-params.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-params.cpp index 0a35fd945..d1a739533 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-params.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-params.cpp @@ -1,9 +1,9 @@ #include -#include "sc-memory/sc_templates.hpp" - #include "sc_test.hpp" +#include "sc-memory/sc_templates.hpp" + using ScTemplateParamsTest = ScMemoryTest; TEST_F(ScTemplateParamsTest, Smoke) @@ -30,16 +30,14 @@ TEST_F(ScTemplateParamsTest, Iterator) ScAddr const test1(34234); ScAddr const test2(3422234); - params - .Add("test1", test1) - .Add("test2", test2); + params.Add("test1", test1).Add("test2", test2); size_t counter = 0; EXPECT_FALSE(params.IsEmpty()); for (auto const & it : params) { counter++; - EXPECT_TRUE( it.second == test1 || it.second == test2 ); + EXPECT_TRUE(it.second == test1 || it.second == test2); } EXPECT_EQ(counter, 2u); @@ -86,4 +84,3 @@ TEST_F(ScTemplateParamsTest, CanAssignParam) EXPECT_FALSE(ScTemplateParams::CanAssignParam(ScType::EdgeUCommonVar, ScType::EdgeDCommonConst)); EXPECT_FALSE(ScTemplateParams::CanAssignParam(ScType::EdgeUCommonVar, ScType::EdgeAccessConstPosPerm)); } - diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-regression.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-regression.cpp index abdfbc7e4..bac716cc1 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-regression.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-regression.cpp @@ -1,10 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_scs_helper.hpp" #include "sc-memory/sc_struct.hpp" - -#include "sc_test.hpp" #include "template_test_utils.hpp" #include @@ -42,9 +42,12 @@ TEST_F(ScTemplateRegressionTest, issue_224) return edge; }; - auto testCreateEdgeAttrs = [&testCreateEdge](ScType const & type, - ScAddr const & src, ScAddr const & trg, - ScType const & attrsEdgeType, std::vector const & attrNodes) + auto testCreateEdgeAttrs = [&testCreateEdge]( + ScType const & type, + ScAddr const & src, + ScAddr const & trg, + ScType const & attrsEdgeType, + std::vector const & attrNodes) { ScAddr const edge = testCreateEdge(type, src, trg); for (ScAddr const & addr : attrNodes) @@ -94,7 +97,8 @@ TEST_F(ScTemplateRegressionTest, issue_224) ScAddr const searchElStr3Addr = testCreateNodeIdtf(ScType::NodeConstClass, "searchElStr3"); ScAddr const genElStr3Addr = testCreateNodeIdtf(ScType::NodeConstClass, "geElStr3"); ScAddr const returnAddr = testCreateNodeIdtf(ScType::NodeConstClass, "return"); - ScAddr const nrel_decompoisition_of_actionAddr = testCreateNodeIdtf(ScType::NodeVarNoRole, "nrel_decomposition_of_action"); + ScAddr const nrel_decompoisition_of_actionAddr = + testCreateNodeIdtf(ScType::NodeVarNoRole, "nrel_decomposition_of_action"); ScAddr const nrel_thenAddr = testCreateNodeIdtf(ScType::NodeConstNoRole, "nrel_then"); ScAddr const nrel_elseAddr = testCreateNodeIdtf(ScType::NodeConstNoRole, "nrel_else"); ScAddr const nrel_gotoAddr = testCreateNodeIdtf(ScType::NodeConstNoRole, "nrel_goto"); @@ -102,153 +106,123 @@ TEST_F(ScTemplateRegressionTest, issue_224) { // scp_process _-> ..process_instance;; ScAddr const __procInstanceAddr = testCreateNode(ScType::NodeVar); - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - scpProcessAddr, - __procInstanceAddr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, scpProcessAddr, __procInstanceAddr); // ..process_instance _-> rrel_1:: rrel_in:: _set1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - __procInstanceAddr, - _set1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_1Addr, rrel_inAddr }); + ScType::EdgeAccessVarPosPerm, + __procInstanceAddr, + _set1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_1Addr, rrel_inAddr}); // ..process_instance _-> rrel_1:: rrel_in::_element1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - __procInstanceAddr, - _element1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_1Addr, rrel_inAddr }); + ScType::EdgeAccessVarPosPerm, + __procInstanceAddr, + _element1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_1Addr, rrel_inAddr}); // ..process_instance _<= nrel_decomposition_of_action:: ..proc_decomp_instance;; ScAddr const __procDecompInstanceAddr = testCreateNode(ScType::NodeVar); testCreateEdgeAttrs( - ScType::EdgeDCommonVar, - __procDecompInstanceAddr, - __procInstanceAddr, - ScType::EdgeAccessVarPosPerm, - { nrel_decompoisition_of_actionAddr }); + ScType::EdgeDCommonVar, + __procDecompInstanceAddr, + __procInstanceAddr, + ScType::EdgeAccessVarPosPerm, + {nrel_decompoisition_of_actionAddr}); // ..proc_decomp_instance _-> rrel_1:: _operator1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - __procDecompInstanceAddr, - _operator1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_1Addr }); + ScType::EdgeAccessVarPosPerm, + __procDecompInstanceAddr, + _operator1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_1Addr}); // ..proc_decomp_instance _->_operator2;; - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - __procDecompInstanceAddr, - _operator2Addr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, __procDecompInstanceAddr, _operator2Addr); // ..proc_decomp_instance _-> _operator3;; - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - __procDecompInstanceAddr, - _operator3Addr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, __procDecompInstanceAddr, _operator3Addr); // _operator1 _<- searchElStr3;; - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - searchElStr3Addr, - _operator1Addr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, searchElStr3Addr, _operator1Addr); // _operator1 _-> rrel_1:: rrel_fixed:: rrel_scp_var:: _set1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator1Addr, - _set1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_1Addr, rrel_fixedAddr, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator1Addr, + _set1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_1Addr, rrel_fixedAddr, rrel_scp_varAddr}); // _operator1 _-> rrel_2:: rrel_assign:: rrel_arc_const_pos_perm:: rrel_scp_var:: _arc1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator1Addr, - _arc1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_assignAddr, rrel_arc_const_pos_perm, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator1Addr, + _arc1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_assignAddr, rrel_arc_const_pos_perm, rrel_scp_varAddr}); // _operator1 _-> rrel_3:: rrel_fixed:: rrel_scp_var:: _element1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator1Addr, - _element1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator1Addr, + _element1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr}); // _operator1 _=> nrel_then:: _operator3;; testCreateEdgeAttrs( - ScType::EdgeDCommonVar, - _operator1Addr, - _operator3Addr, - ScType::EdgeAccessVarPosPerm, - { nrel_thenAddr }); + ScType::EdgeDCommonVar, _operator1Addr, _operator3Addr, ScType::EdgeAccessVarPosPerm, {nrel_thenAddr}); // _operator1 _=> nrel_else:: _operator2;; testCreateEdgeAttrs( - ScType::EdgeDCommonVar, - _operator1Addr, - _operator2Addr, - ScType::EdgeAccessVarPosPerm, - { nrel_elseAddr }); + ScType::EdgeDCommonVar, _operator1Addr, _operator2Addr, ScType::EdgeAccessVarPosPerm, {nrel_elseAddr}); // _operator2 _<- genElStr3;; - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - genElStr3Addr, - _operator2Addr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, genElStr3Addr, _operator2Addr); // _operator2 _-> rrel_1:: rrel_fixed:: rrel_scp_var:: _set1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator2Addr, - _set1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_1Addr, rrel_fixedAddr, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator2Addr, + _set1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_1Addr, rrel_fixedAddr, rrel_scp_varAddr}); // _operator2 _-> rrel_2:: rrel_assign:: rrel_arc_const_pos_perm:: rrel_scp_var:: _arc1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator2Addr, - _arc1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_2Addr, rrel_assignAddr, rrel_arc_const_pos_perm, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator2Addr, + _arc1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_2Addr, rrel_assignAddr, rrel_arc_const_pos_perm, rrel_scp_varAddr}); // _operator2 _-> rrel_3:: rrel_fixed:: rrel_scp_var:: _element1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator2Addr, - _element1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator2Addr, + _element1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr}); // _operator2 _-> rrel_3:: rrel_fixed:: rrel_scp_var:: _element1;; testCreateEdgeAttrs( - ScType::EdgeAccessVarPosPerm, - _operator2Addr, - _element1Addr, - ScType::EdgeAccessVarPosPerm, - { rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr }); + ScType::EdgeAccessVarPosPerm, + _operator2Addr, + _element1Addr, + ScType::EdgeAccessVarPosPerm, + {rrel_3Addr, rrel_fixedAddr, rrel_scp_varAddr}); // _operator2 _=> nrel_goto:: _operator3;; testCreateEdgeAttrs( - ScType::EdgeDCommonVar, - _operator2Addr, - _operator3Addr, - ScType::EdgeAccessVarPosPerm, - { nrel_gotoAddr }); + ScType::EdgeDCommonVar, _operator2Addr, _operator3Addr, ScType::EdgeAccessVarPosPerm, {nrel_gotoAddr}); // _operator3 _<- return;; - testCreateEdge( - ScType::EdgeAccessVarPosPerm, - returnAddr, - _operator3Addr); + testCreateEdge(ScType::EdgeAccessVarPosPerm, returnAddr, _operator3Addr); } } @@ -274,7 +248,8 @@ TEST_F(ScTemplateRegressionTest, issue_224) for (size_t i = 0; i < testNum; ++i) { shuffle(1); - ScAddr const structAddr = m_ctx->HelperResolveSystemIdtf("test_program" + std::to_string(i), ScType::NodeConstStruct); + ScAddr const structAddr = + m_ctx->HelperResolveSystemIdtf("test_program" + std::to_string(i), ScType::NodeConstStruct); EXPECT_TRUE(structAddr.IsValid()); ScStruct contour(*m_ctx, structAddr); @@ -312,18 +287,12 @@ TEST_F(ScTemplateRegressionTest, issue_251) EXPECT_TRUE(edgeRel_edge.IsValid()); // create template for a search - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - kAddr, - ScType::EdgeDCommonVar, - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm, - relAddr) - .Triple( - tAddr, - ScType::EdgeAccessVarPosPerm, - "_link") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + kAddr, ScType::EdgeDCommonVar, ScType::Link >> "_link", ScType::EdgeAccessVarPosPerm, relAddr) + .Triple(tAddr, ScType::EdgeAccessVarPosPerm, "_link") + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-scs.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-scs.cpp index 00a75d8e8..a3ce20a48 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-scs.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-scs.cpp @@ -1,8 +1,8 @@ #include -#include "sc-memory/sc_memory.hpp" - #include "sc_test.hpp" + +#include "sc-memory/sc_memory.hpp" #include "template_test_utils.hpp" using ScTemplateSCsTest = ScTemplateTest; @@ -25,12 +25,10 @@ TEST_F(ScTemplateSCsTest, build_fail) TEST_F(ScTemplateSCsTest, search) { - ScTemplatePtr genTempl = ScTemplateBuilder() - .Triple( - ScType::NodeVar >> "_a", - ScType::EdgeAccessVarPosPerm >> "_edge", - ScType::NodeVarTuple >> "b") - .Make(); + ScTemplatePtr genTempl = + ScTemplateBuilder() + .Triple(ScType::NodeVar >> "_a", ScType::EdgeAccessVarPosPerm >> "_edge", ScType::NodeVarTuple >> "b") + .Make(); ScTemplateGenerate::Result genResult = ScTemplateGenerate(*m_ctx, *genTempl).Do(); EXPECT_TRUE(genResult); @@ -67,12 +65,10 @@ TEST_F(ScTemplateSCsTest, generate) EXPECT_TRUE(genResult); // check - ScTemplatePtr searchTempl = ScTemplateBuilder() - .Triple( - cAddr >> "c1", - ScType::EdgeDCommonVar >> "_edge", - ScType::NodeVarAbstract >> "_b1") - .Make(); + ScTemplatePtr searchTempl = + ScTemplateBuilder() + .Triple(cAddr >> "c1", ScType::EdgeDCommonVar >> "_edge", ScType::NodeVarAbstract >> "_b1") + .Make(); ScTemplateSearch search(*m_ctx, *searchTempl); ScTemplateSearch::Iterator searchResult = search.begin(); diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-search.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-search.cpp index d9f2606c6..9e305dbbc 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-search.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-search.cpp @@ -1,10 +1,10 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_link.hpp" #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_struct.hpp" - -#include "sc_test.hpp" #include "template_test_utils.hpp" using ScTemplateSearchTest = ScTemplateTest; @@ -14,11 +14,7 @@ TEST_F(ScTemplateSearchTest, empty) ScAddr const addr = m_ctx->CreateNode(ScType::NodeClass); EXPECT_TRUE(addr.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr, - ScType::EdgeAccessVarNegPerm, - ScType::NodeVar) - .Make(); + ScTemplatePtr templ = ScTemplateBuilder().Triple(addr, ScType::EdgeAccessVarNegPerm, ScType::NodeVar).Make(); ScTemplateSearch search(*m_ctx, *templ); EXPECT_EQ(search.begin(), search.end()); @@ -35,11 +31,8 @@ TEST_F(ScTemplateSearchTest, empty_end) ScAddr const edge = m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, addr, addr2); EXPECT_TRUE(edge); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr, - ScType::EdgeAccessVarPosPerm >> "_edge", - ScType::NodeVar) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr, ScType::EdgeAccessVarPosPerm >> "_edge", ScType::NodeVar).Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator it = search.begin(); @@ -51,7 +44,6 @@ TEST_F(ScTemplateSearchTest, empty_end) EXPECT_FALSE(it["_edge"]); } - TEST_F(ScTemplateSearchTest, search_1) { /** _y @@ -158,17 +150,14 @@ TEST_F(ScTemplateSearchTest, search_2) // now check search ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - addr >> "_addr", - ScType::EdgeDCommonVar >> "_edgeCommon", - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm >> "_edgeAttr", - nrelMainIdtf >> "_nrelMainIdtf") - .Triple( - lang >> "_lang", - ScType::EdgeAccessVarPosPerm >> "_edgeLang", - "_link") - .Make(); + .TripleWithRelation( + addr >> "_addr", + ScType::EdgeDCommonVar >> "_edgeCommon", + ScType::Link >> "_link", + ScType::EdgeAccessVarPosPerm >> "_edgeAttr", + nrelMainIdtf >> "_nrelMainIdtf") + .Triple(lang >> "_lang", ScType::EdgeAccessVarPosPerm >> "_edgeLang", "_link") + .Make(); // search { @@ -198,12 +187,8 @@ TEST_F(ScTemplateSearchTest, unknown_type) ScAddr const edge = m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, addr1, addr2); EXPECT_TRUE(edge.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - addr1, - ScType::EdgeAccessVarPosPerm >> "edge", - ScType::Unknown >> "addr2") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr1, ScType::EdgeAccessVarPosPerm >> "edge", ScType::Unknown >> "addr2").Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -288,30 +273,20 @@ TEST_F(ScTemplateSearchTest, links_with_relation) ++i; } - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::NodeVarTuple >> "_tuple", - ScType::EdgeDCommonVar, - deviceAddr, - ScType::EdgeAccessVarPosPerm, - nrelInstalledApp) - .Triple( - "_tuple", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVar >> "_app") - .TripleWithRelation( - "_app", - ScType::EdgeDCommonVar, - ScType::Link >> "_idtf", - ScType::EdgeAccessVarPosPerm, - nrelIdtf) - .TripleWithRelation( - "_app", - ScType::EdgeDCommonVar, - ScType::Link >> "_image", - ScType::EdgeAccessVarPosPerm, - nrelImage) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + ScType::NodeVarTuple >> "_tuple", + ScType::EdgeDCommonVar, + deviceAddr, + ScType::EdgeAccessVarPosPerm, + nrelInstalledApp) + .Triple("_tuple", ScType::EdgeAccessVarPosPerm, ScType::NodeVar >> "_app") + .TripleWithRelation( + "_app", ScType::EdgeDCommonVar, ScType::Link >> "_idtf", ScType::EdgeAccessVarPosPerm, nrelIdtf) + .TripleWithRelation( + "_app", ScType::EdgeDCommonVar, ScType::Link >> "_image", ScType::EdgeAccessVarPosPerm, nrelImage) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -355,15 +330,9 @@ TEST_F(ScTemplateSearchTest, result_deduplication) EXPECT_TRUE(a.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - a >> "a", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarMaterial >> "b") - .Triple( - "a", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVar >> "c") - .Make(); + .Triple(a >> "a", ScType::EdgeAccessVarPosPerm, ScType::NodeVarMaterial >> "b") + .Triple("a", ScType::EdgeAccessVarPosPerm, ScType::NodeVar >> "c") + .Make(); ScTemplateGenerate::Result genResult = ScTemplateGenerate(*m_ctx, *templ).Do(); EXPECT_TRUE(genResult); @@ -398,21 +367,18 @@ TEST_F(ScTemplateSearchTest, parameters) ScAddr const rel2 = m_ctx->CreateNode(ScType::NodeConstNoRole); EXPECT_TRUE(rel2.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation(node, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarMaterial >> "_trg", - ScType::EdgeAccessVarPosPerm, - ScType::NodeVarNoRole >> "_rel") - .Make(); + .TripleWithRelation( + node, + ScType::EdgeAccessVarPosPerm, + ScType::NodeVarMaterial >> "_trg", + ScType::EdgeAccessVarPosPerm, + ScType::NodeVarNoRole >> "_rel") + .Make(); { ScTemplateParams params; - params - .Add("_trg", target1) - .Add("_rel", rel1); - + params.Add("_trg", target1).Add("_rel", rel1); ScTemplateGenerate::Result result = ScTemplateGenerate(*m_ctx, *templ).Do(params); EXPECT_TRUE(result); @@ -420,10 +386,7 @@ TEST_F(ScTemplateSearchTest, parameters) { ScTemplateParams params; - params - .Add("_trg", target2) - .Add("_rel", rel2); - + params.Add("_trg", target2).Add("_rel", rel2); ScTemplateGenerate::Result result = ScTemplateGenerate(*m_ctx, *templ).Do(params); EXPECT_TRUE(result); @@ -490,7 +453,8 @@ TEST_F(ScTemplateSearchTest, parameters_addrs) // create template in sc-memory { SCsHelper helper(*m_ctx, std::make_shared()); - EXPECT_TRUE(helper.GenerateBySCsText("[* x _-> _y;; *] => nrel_system_identifier: [test_template_parameters_addrs];;")); + EXPECT_TRUE( + helper.GenerateBySCsText("[* x _-> _y;; *] => nrel_system_identifier: [test_template_parameters_addrs];;")); } ScAddr const templAddr = m_ctx->HelperFindBySystemIdtf("test_template_parameters_addrs"); @@ -518,7 +482,6 @@ TEST_F(ScTemplateSearchTest, parameters_addrs) TEST_F(ScTemplateSearchTest, parameters_addrs_edge) { - } TEST_F(ScTemplateSearchTest, parameters_invalid_assign_to_non_type) @@ -529,19 +492,14 @@ TEST_F(ScTemplateSearchTest, parameters_invalid_assign_to_non_type) ScAddr const value = m_ctx->CreateNode(ScType::NodeConstAbstract); EXPECT_TRUE(value); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr >> "_addr", - ScType::EdgeAccessVarFuzPerm, - ScType::NodeVar) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr >> "_addr", ScType::EdgeAccessVarFuzPerm, ScType::NodeVar).Make(); ScTemplateParams params; params.Add("_addr", value); ScTemplateSearch search(*m_ctx, *templ, params); - EXPECT_THROW( - search.begin(), - utils::ExceptionInvalidParams); + EXPECT_THROW(search.begin(), utils::ExceptionInvalidParams); } TEST_F(ScTemplateSearchTest, parameters_invalid_assign_variable_value) @@ -552,19 +510,14 @@ TEST_F(ScTemplateSearchTest, parameters_invalid_assign_variable_value) ScAddr const value = m_ctx->CreateNode(ScType::NodeVarAbstract); EXPECT_TRUE(value); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr, - ScType::EdgeAccessVarFuzPerm, - ScType::NodeVar >> "_var") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr, ScType::EdgeAccessVarFuzPerm, ScType::NodeVar >> "_var").Make(); ScTemplateParams params; params.Add("_var", value); ScTemplateSearch search(*m_ctx, *templ, params); - EXPECT_THROW( - search.begin(), - utils::ExceptionInvalidParams); + EXPECT_THROW(search.begin(), utils::ExceptionInvalidParams); } TEST_F(ScTemplateSearchTest, parameters_invalid_assign_non_compatible_type) @@ -575,19 +528,14 @@ TEST_F(ScTemplateSearchTest, parameters_invalid_assign_non_compatible_type) ScAddr const value = m_ctx->CreateNode(ScType::NodeVarClass); EXPECT_TRUE(value); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr, - ScType::EdgeAccessVarFuzPerm, - ScType::NodeVar >> "_var") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr, ScType::EdgeAccessVarFuzPerm, ScType::NodeVar >> "_var").Make(); ScTemplateParams params; params.Add("_var", value); ScTemplateSearch search(*m_ctx, *templ, params); - EXPECT_THROW( - search.begin(), - utils::ExceptionInvalidParams); + EXPECT_THROW(search.begin(), utils::ExceptionInvalidParams); } TEST_F(ScTemplateSearchTest, parameters_invalid_assign_non_existing) @@ -598,17 +546,12 @@ TEST_F(ScTemplateSearchTest, parameters_invalid_assign_non_existing) ScAddr const value = m_ctx->CreateNode(ScType::NodeConstClass); EXPECT_TRUE(value); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple(addr, - ScType::EdgeAccessVarFuzPerm, - ScType::NodeVar >> "_var") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(addr, ScType::EdgeAccessVarFuzPerm, ScType::NodeVar >> "_var").Make(); ScTemplateParams params; params.Add("_non_exist", value); ScTemplateSearch search(*m_ctx, *templ, params); - EXPECT_THROW( - search.begin(), - utils::ExceptionItemNotFound); + EXPECT_THROW(search.begin(), utils::ExceptionItemNotFound); } diff --git a/sc-memory/tests/sc-memory/templates/sc-templates-struct.cpp b/sc-memory/tests/sc-memory/templates/sc-templates-struct.cpp index 69528859d..aba229134 100644 --- a/sc-memory/tests/sc-memory/templates/sc-templates-struct.cpp +++ b/sc-memory/tests/sc-memory/templates/sc-templates-struct.cpp @@ -1,9 +1,9 @@ #include +#include "sc_test.hpp" + #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_struct.hpp" - -#include "sc_test.hpp" #include "template_test_utils.hpp" using ScTemplateSearchInStructTest = ScTemplateTest; @@ -55,16 +55,16 @@ TEST_F(ScTemplateSearchInStructTest, search_in_struct) EXPECT_TRUE(testStructAddr.IsValid()); /* y ---> u - * ^ - * | <--- z - * x - * | <--- s - * v - * g - * scs: x -> z: y; s: g;; y -> u;; - */ - ScAddr tyAddr, txAddr, tgAddr, tuAddr, tzAddr, tsAddr, - tyuEdgeAddr, txyEdgeAddr, txgEdgeAddr, tzxyEdgeAddr, tsxgEdgeAddr; + * ^ + * | <--- z + * x + * | <--- s + * v + * g + * scs: x -> z: y; s: g;; y -> u;; + */ + ScAddr tyAddr, txAddr, tgAddr, tuAddr, tzAddr, tsAddr, tyuEdgeAddr, txyEdgeAddr, txgEdgeAddr, tzxyEdgeAddr, + tsxgEdgeAddr; ScStruct testStruct(*m_ctx, testStructAddr); { @@ -100,11 +100,8 @@ TEST_F(ScTemplateSearchInStructTest, search_in_struct) tsxgEdgeAddr = m_ctx->CreateEdge(ScType::EdgeAccessConstPosPerm, tsAddr, txgEdgeAddr); EXPECT_TRUE(tsxgEdgeAddr.IsValid()); - testStruct << tyAddr << txAddr << tgAddr - << tuAddr << tzAddr << tsAddr - << tyuEdgeAddr << txyEdgeAddr - << txgEdgeAddr << tzxyEdgeAddr - << tsxgEdgeAddr; + testStruct << tyAddr << txAddr << tgAddr << tuAddr << tzAddr << tsAddr << tyuEdgeAddr << txyEdgeAddr << txgEdgeAddr + << tzxyEdgeAddr << tsxgEdgeAddr; } // add extra edges that not included into struct @@ -131,4 +128,3 @@ TEST_F(ScTemplateSearchInStructTest, search_in_struct) EXPECT_EQ(count, 2u); } } - diff --git a/sc-memory/tests/sc-memory/templates/template_test_utils.hpp b/sc-memory/tests/sc-memory/templates/template_test_utils.hpp index 12138b494..382c224dd 100644 --- a/sc-memory/tests/sc-memory/templates/template_test_utils.hpp +++ b/sc-memory/tests/sc-memory/templates/template_test_utils.hpp @@ -1,12 +1,12 @@ #pragma once -#include "sc-memory/sc_memory.hpp" -#include "sc-memory/sc_scs_helper.hpp" -#include "sc-memory/sc_templates.hpp" +#include #include "sc_test.hpp" -#include +#include "sc-memory/sc_memory.hpp" +#include "sc-memory/sc_scs_helper.hpp" +#include "sc-memory/sc_templates.hpp" #include @@ -14,7 +14,6 @@ using ScTemplateTest = ScMemoryTest; namespace { - struct TestTemplParams { explicit TestTemplParams(ScMemoryContext & ctx) @@ -22,14 +21,12 @@ struct TestTemplParams { } - bool operator () (ScTemplateArg param1, ScTemplateArg param2, ScTemplateArg param3) + bool operator()(ScTemplateArg param1, ScTemplateArg param2, ScTemplateArg param3) { bool catched = false; try { - ScTemplatePtr testTempl = ScTemplateBuilder() - .Triple(param1, param2, param3) - .Make(); + ScTemplatePtr testTempl = ScTemplateBuilder().Triple(param1, param2, param3).Make(); ScTemplateGenerate generator(m_ctx, *testTempl); EXPECT_TRUE(generator.Do()); @@ -47,7 +44,6 @@ struct TestTemplParams ScMemoryContext & m_ctx; }; - inline bool HasAddr(ScAddrVector const & v, ScAddr const & addr) { return std::find(v.begin(), v.end(), addr) != v.end(); @@ -69,4 +65,4 @@ class DummyFileInterface : public SCsFileInterface } }; -} // namespace +} // namespace diff --git a/sc-memory/tests/scs/units/test_scs_common.cpp b/sc-memory/tests/scs/units/test_scs_common.cpp index f815884bd..41dac97c7 100644 --- a/sc-memory/tests/scs/units/test_scs_common.cpp +++ b/sc-memory/tests/scs/units/test_scs_common.cpp @@ -2,7 +2,6 @@ #include "test_scs_utils.hpp" - TEST(scs_common, ElementHandle) { scs::ElementHandle handle_err; @@ -154,17 +153,18 @@ TEST(scs_common, const_var) TEST(scs_common, nodes) { - char const * data = "a -> b;;" - "sc_node_tuple -> a;;" - "sc_node_struct -> b;;" - "sc_node_role_relation -> c;;" - "c -> _d;;" - "sc_node_norole_relation -> _d;;" - "sc_node_class -> e;;" - "e -> f;;" - "sc_node_abstract -> f;;" - "f -> g;;" - "sc_node_material -> g;;"; + char const * data = + "a -> b;;" + "sc_node_tuple -> a;;" + "sc_node_struct -> b;;" + "sc_node_role_relation -> c;;" + "c -> _d;;" + "sc_node_norole_relation -> _d;;" + "sc_node_class -> e;;" + "e -> f;;" + "sc_node_abstract -> f;;" + "f -> g;;" + "sc_node_material -> g;;"; scs::Parser parser; @@ -196,7 +196,6 @@ TEST(scs_common, nodes) } } - TEST(scs_common, links) { std::string const data = @@ -221,7 +220,6 @@ TEST(scs_common, links) EXPECT_FALSE(parser.GetParsedElement(triples[3].m_target).IsURL()); } - TEST(scs_common, backward_compatibility) { std::string const data = "a <- c;; a <- sc_node_not_relation;; b <- c;; b <- sc_node_not_binary_tuple;;"; @@ -238,11 +236,12 @@ TEST(scs_common, backward_compatibility) TEST(scs_common, edges) { - std::string const data = "x" - "> _y; <> y4; ..> y5;" - "<=> y7; _<=> y8; => y9; _=> y11;" - "-> y2; _-> y13; -|> y15; _-|> y17; -/> y19; _-/> y21;" - " ~> y23; _~> y25; ~|> y27; _~|> y29; ~/> y31; _~/> y33;;"; + std::string const data = + "x" + "> _y; <> y4; ..> y5;" + "<=> y7; _<=> y8; => y9; _=> y11;" + "-> y2; _-> y13; -|> y15; _-|> y17; -/> y19; _-/> y21;" + " ~> y23; _~> y25; ~|> y27; _~|> y29; ~/> y31; _~/> y33;;"; scs::Parser parser; @@ -282,7 +281,6 @@ TEST(scs_common, edges) } } - TEST(scs_common, type_error) { std::string const data = "a <- sc_node_abstract;; a <- sc_node_role_relation;;"; diff --git a/sc-memory/tests/scs/units/test_scs_level_1.cpp b/sc-memory/tests/scs/units/test_scs_level_1.cpp index 2a9877e5f..d80d674bd 100644 --- a/sc-memory/tests/scs/units/test_scs_level_1.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_1.cpp @@ -1,7 +1,6 @@ #include #include "sc-memory/scs/scs_parser.hpp" - #include "test_scs_utils.hpp" TEST(scs_level_1, dummy) diff --git a/sc-memory/tests/scs/units/test_scs_level_2.cpp b/sc-memory/tests/scs/units/test_scs_level_2.cpp index 0f1d6cfde..69bea3783 100644 --- a/sc-memory/tests/scs/units/test_scs_level_2.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_2.cpp @@ -10,18 +10,13 @@ TEST(scs_level_2, simple_1) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "c" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::NodeConst, "b" } - }, - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "c"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::NodeConst, "b"}}, + {{ScType::NodeConst, "a"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 2u); @@ -35,18 +30,13 @@ TEST(scs_level_2, simple_2) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::NodeConst, "b" } - }, - { - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::EdgeDCommonConst, "", scs::Visibility::Local }, - { ScType::NodeConst, "c" } - } - }); + tester( + {{{ScType::NodeConst, "a"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::NodeConst, "b"}}, + {{ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::EdgeDCommonConst, "", scs::Visibility::Local}, + {ScType::NodeConst, "c"}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 2u); @@ -63,33 +53,22 @@ TEST(scs_level_2, complex) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::NodeConst, "c" } - }, - { - { ScType::NodeConst, "a" }, - { ScType::EdgeUCommon, "", scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local } - }, - { - { ScType::NodeConst, "x" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::NodeConst, "c" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::NodeConst, "y" } - }, - { - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::NodeConst, "c"}}, + {{ScType::NodeConst, "a"}, + {ScType::EdgeUCommon, "", scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}}, + {{ScType::NodeConst, "x"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::NodeConst, "c"}}, + {{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::NodeConst, "y"}}, + {{ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, "", scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 5u); @@ -115,11 +94,7 @@ TEST(scs_level_2, unnamed) TEST(scs_level_2, not_allowed) { std::vector tests = { - "a -> (x -> (y -> z));;", - "a -> (x -> [content]);;", - "a -> (x -> [* y -> z ;; *]);;", - "a -> (x -> { y; z });;" - }; + "a -> (x -> (y -> z));;", "a -> (x -> [content]);;", "a -> (x -> [* y -> z ;; *]);;", "a -> (x -> { y; z });;"}; for (auto const & t : tests) { diff --git a/sc-memory/tests/scs/units/test_scs_level_3.cpp b/sc-memory/tests/scs/units/test_scs_level_3.cpp index 2ec19937a..df211d2b5 100644 --- a/sc-memory/tests/scs/units/test_scs_level_3.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_3.cpp @@ -9,23 +9,14 @@ TEST(scs_level_3, simple_1) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "d" } - }, - { - { ScType::NodeConst, "c" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeVar, "_b" }, - { ScType::EdgeAccessVarPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "a"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "d"}}, + {{ScType::NodeConst, "c"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeVar, "_b"}, + {ScType::EdgeAccessVarPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 3u); @@ -42,33 +33,18 @@ TEST(scs_level_3, complex_1) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "d" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "a" } - }, - { - { ScType::NodeConst, "f" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConst, "c" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "d" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "d"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "a"}}, + {{ScType::NodeConst, "f"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConst, "c"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "d"}}, + {{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 5u); @@ -87,28 +63,17 @@ TEST(scs_level_3, complex_2) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "d" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "h"} - }, - { - { ScType::NodeConst, "g" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConst, "c" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "d"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "h"}}, + {{ScType::NodeConst, "g"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConst, "a"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConst, "c"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 4u); diff --git a/sc-memory/tests/scs/units/test_scs_level_4.cpp b/sc-memory/tests/scs/units/test_scs_level_4.cpp index 83b8643a5..d4c09d074 100644 --- a/sc-memory/tests/scs/units/test_scs_level_4.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_4.cpp @@ -10,28 +10,15 @@ TEST(scs_level_4, simple_1) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "c" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "d" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "a"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "c"}}, + {{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConst, "a"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "d"}}, + {{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); @@ -49,33 +36,24 @@ TEST(scs_level_4, simple_2) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "a" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "c" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - }, - { - { ScType::NodeConst, "f" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "a" } - }, - { - { ScType::NodeConst, "d" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - }, - { - { ScType::NodeConst, "e" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - } - }); + tester( + {{{ScType::NodeConst, "a"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "c"}}, + { + {ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + }, + {{ScType::NodeConst, "f"}, {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, {ScType::NodeConst, "a"}}, + { + {ScType::NodeConst, "d"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + }, + { + {ScType::NodeConst, "e"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + }}); auto const & triples = parser.GetParsedTriples(); diff --git a/sc-memory/tests/scs/units/test_scs_level_5.cpp b/sc-memory/tests/scs/units/test_scs_level_5.cpp index 8d91f0c7e..69c106761 100644 --- a/sc-memory/tests/scs/units/test_scs_level_5.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_5.cpp @@ -11,28 +11,19 @@ TEST(scs_level_5, simple) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConst, "item" }, - { ScType::EdgeAccessConstFuzPerm, scs::Visibility::Local }, - { ScType::NodeConst, "subitem" } - }, - { - { ScType::NodeConst, "subitem2" }, - { ScType::EdgeDCommonConst, scs::Visibility::Local }, - { ScType::NodeConst, "item" } - }, - { - { ScType::NodeConst, "set" }, - { ScType::EdgeAccessConstPosTemp, scs::Visibility::Local }, - { ScType::NodeConst, "item" } - }, - { - { ScType::NodeConst, "attr" }, - { ScType::EdgeAccessVarPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosTemp, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConst, "item"}, + {ScType::EdgeAccessConstFuzPerm, scs::Visibility::Local}, + {ScType::NodeConst, "subitem"}}, + {{ScType::NodeConst, "subitem2"}, + {ScType::EdgeDCommonConst, scs::Visibility::Local}, + {ScType::NodeConst, "item"}}, + {{ScType::NodeConst, "set"}, + {ScType::EdgeAccessConstPosTemp, scs::Visibility::Local}, + {ScType::NodeConst, "item"}}, + {{ScType::NodeConst, "attr"}, + {ScType::EdgeAccessVarPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosTemp, scs::Visibility::Local}}}); auto const & triples = parser.GetParsedTriples(); EXPECT_EQ(triples.size(), 4u); diff --git a/sc-memory/tests/scs/units/test_scs_level_6.cpp b/sc-memory/tests/scs/units/test_scs_level_6.cpp index f83c32e6c..80f65f6c8 100644 --- a/sc-memory/tests/scs/units/test_scs_level_6.cpp +++ b/sc-memory/tests/scs/units/test_scs_level_6.cpp @@ -11,51 +11,37 @@ TEST(scs_level_6, set) EXPECT_TRUE(parser.Parse(data)); TripleTester tester(parser); - tester({ - { - { ScType::NodeConstTuple, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "a" } - }, - { - { ScType::NodeConstTuple, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "c" } - }, - { - { ScType::NodeConst, "b" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConstTuple, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::NodeConst, "f" } - }, - { - { ScType::NodeConst, "d" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - }, - { - { ScType::NodeConst, "e" }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local }, - { ScType::EdgeAccessConstPosPerm, scs::Visibility::Local } - } - }); + tester( + {{{ScType::NodeConstTuple, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::NodeConst, "a"}}, + {{ScType::NodeConstTuple, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::NodeConst, "c"}}, + {{ScType::NodeConst, "b"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConstTuple, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::NodeConst, "f"}}, + {{ScType::NodeConst, "d"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}, + {{ScType::NodeConst, "e"}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}, + {ScType::EdgeAccessConstPosPerm, scs::Visibility::Local}}}); } TEST(scs_level_6, smoke) { std::vector data = { - "z -> [**];;", - "x -> [test*];;", - "@a = [\\[* r-> b;; *\\]];;", - "@alias = u;; @alias -> [* x -> [* y -> z;; *];; *];;", - "y <= nrel_main_idtf: [y*];;", - "a -> [* z -> [begin*];; *];;", - "a -> [* b -> c;; *];;" - }; + "z -> [**];;", + "x -> [test*];;", + "@a = [\\[* r-> b;; *\\]];;", + "@alias = u;; @alias -> [* x -> [* y -> z;; *];; *];;", + "y <= nrel_main_idtf: [y*];;", + "a -> [* z -> [begin*];; *];;", + "a -> [* b -> c;; *];;"}; for (auto const & d : data) { @@ -181,7 +167,6 @@ TEST(scs_level_6, contour_empty) EXPECT_EQ(trg.GetType(), ScType::NodeConstStruct); } - TEST(scs_level_6, contour_parse_error) { { @@ -201,7 +186,6 @@ TEST(scs_level_6, contour_parse_error) } } - TEST(scs_level_6, contour_simple) { std::string const data = "x -|> [* y _=> z;; *];;"; @@ -290,7 +274,6 @@ TEST(scs_level_6, contour_recursive) } } - TEST(scs_level_6, contout_with_content) { std::string const data = "x -> [* y _=> [test*];; *];;"; diff --git a/sc-memory/tests/scs/units/test_scs_regression.cpp b/sc-memory/tests/scs/units/test_scs_regression.cpp index a13fc1d9d..10eb693b8 100644 --- a/sc-memory/tests/scs/units/test_scs_regression.cpp +++ b/sc-memory/tests/scs/units/test_scs_regression.cpp @@ -6,7 +6,7 @@ TEST(scs_regression, issue_353) { std::string const data = "a -> [*" - "_x <- sc_node_class;;" + "_x <- sc_node_class;;" "*];;"; scs::Parser parser; diff --git a/sc-memory/tests/scs/units/test_scs_utils.hpp b/sc-memory/tests/scs/units/test_scs_utils.hpp index 124b4bd4d..2b37a6b9b 100644 --- a/sc-memory/tests/scs/units/test_scs_utils.hpp +++ b/sc-memory/tests/scs/units/test_scs_utils.hpp @@ -4,16 +4,17 @@ #include #include "sc-memory/sc_addr.hpp" -#include "sc-memory/sc_type.hpp" - #include "sc-memory/sc_debug.hpp" - +#include "sc-memory/sc_type.hpp" #include "sc-memory/scs/scs_parser.hpp" #define SPLIT_TRIPLE(t) \ - auto const & src = parser.GetParsedElement(t.m_source); SC_UNUSED(src); \ - auto const & edge = parser.GetParsedElement(t.m_edge); SC_UNUSED(edge); \ - auto const & trg = parser.GetParsedElement(t.m_target); SC_UNUSED(trg); + auto const & src = parser.GetParsedElement(t.m_source); \ + SC_UNUSED(src); \ + auto const & edge = parser.GetParsedElement(t.m_edge); \ + SC_UNUSED(edge); \ + auto const & trg = parser.GetParsedElement(t.m_target); \ + SC_UNUSED(trg); struct TripleElement { @@ -59,13 +60,12 @@ struct TripleElement scs::Visibility m_visibility; }; -inline std::ostream & operator<< (std::ostream & out, TripleElement const & t) +inline std::ostream & operator<<(std::ostream & out, TripleElement const & t) { out << "{ m_type: " << *t.m_type << ", m_idtf: \"" << t.m_idtf << "\", m_visibility: " << int(t.m_visibility) << " }"; return out; } - struct TripleResult { void Test(scs::Parser const & parser, scs::ParsedTriple const & triple) const @@ -110,14 +110,16 @@ struct TripleResult TripleElement m_target; }; - using ResultTriples = std::vector; struct TripleTester { - explicit TripleTester(scs::Parser const & parser) : m_parser(parser) {} + explicit TripleTester(scs::Parser const & parser) + : m_parser(parser) + { + } - void operator() (ResultTriples const & resultTriples) + void operator()(ResultTriples const & resultTriples) { auto const & triples = m_parser.GetParsedTriples(); EXPECT_EQ(triples.size(), resultTriples.size()); diff --git a/sc-network/sctp_client/sctpClient.cpp b/sc-network/sctp_client/sctpClient.cpp index 0c82bcab7..bd730fb2a 100644 --- a/sc-network/sctp_client/sctpClient.cpp +++ b/sc-network/sctp_client/sctpClient.cpp @@ -5,11 +5,11 @@ */ #include "sctpClient.hpp" + #include "sctpTypes.hpp" namespace sctp { - sc_uint8 mIterRange; sc_uint32 mResultCount; sc_uint32 mCurrentResult; @@ -37,7 +37,7 @@ ScAddr Iterator::getValue(sc_uint8 idx) const { SC_ASSERT(mCurrentResult > 0, ()); sc_uint32 const offset = (mCurrentResult - 1) * sizeof(ScRealAddr) * mIterRange + sizeof(ScRealAddr) * idx; - return ScAddr(*((ScRealAddr*)(mBuffer.get() + offset))); + return ScAddr(*((ScRealAddr *)(mBuffer.get() + offset))); } // ----------------------------------------- @@ -82,7 +82,6 @@ _SC_EXTERN bool Client::IsElement(ScAddr const & addr) return (res.resultCode == SCTP_RESULT_OK); } - return false; } @@ -319,5 +318,4 @@ bool Client::ReadResultHeader(ResultHeader & outHeader) return false; } - -} +} // namespace sctp diff --git a/sc-network/sctp_client/sctpClient.hpp b/sc-network/sctp_client/sctpClient.hpp index 3c35762bc..9ce0a969e 100644 --- a/sc-network/sctp_client/sctpClient.hpp +++ b/sc-network/sctp_client/sctpClient.hpp @@ -9,16 +9,12 @@ #include "sc-memory/sc_addr.hpp" #include "sc-memory/sc_stream.hpp" #include "sc-memory/sc_utils.hpp" - -#include "sctpTypes.hpp" #include "sctpISocket.hpp" - - +#include "sctpTypes.hpp" namespace sctp { - -#define SCTP_ADDR_SIZE (sizeof(ScRealAddr)) +#define SCTP_ADDR_SIZE (sizeof(ScRealAddr)) struct RequestHeader { @@ -64,7 +60,6 @@ struct RequestSetLinkContent // data appends later (because it has dynamic size) }; - /// ------------ struct ResultHeader { @@ -74,7 +69,6 @@ struct ResultHeader uint32_t resultSize; }; - class Iterator { friend class Client; @@ -96,134 +90,179 @@ class Iterator SHARED_PTR_TYPE(Iterator) - - template -sc_uint32 Iterator3ParamsT(char * buffer, ParamType1 const & param1, ParamType2 const & param2, ParamType3 const & param3); - -template<> sc_uint32 Iterator3ParamsT(char * buffer, ScAddr const & param1, sc_type const & param2, sc_type const & param3) +sc_uint32 Iterator3ParamsT( + char * buffer, + ParamType1 const & param1, + ParamType2 const & param2, + ParamType3 const & param3); + +template <> +sc_uint32 Iterator3ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + sc_type const & param3) { buffer[0] = SCTP_ITERATOR_3F_A_A; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; *typeBuff = param3; - return 1 + sizeof(ScRealAddr) + sizeof(sc_type)* 2; + return 1 + sizeof(ScRealAddr) + sizeof(sc_type) * 2; } -template<> sc_uint32 Iterator3ParamsT(char * buffer, ScAddr const & param1, sc_type const & param2, ScAddr const & param3) +template <> +sc_uint32 Iterator3ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + ScAddr const & param3) { buffer[0] = SCTP_ITERATOR_3F_A_F; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; return 1 + sizeof(ScRealAddr) * 2 + sizeof(sc_type); } -template<> sc_uint32 Iterator3ParamsT(char * buffer, sc_type const & param1, sc_type const & param2, ScAddr const & param3) +template <> +sc_uint32 Iterator3ParamsT( + char * buffer, + sc_type const & param1, + sc_type const & param2, + ScAddr const & param3) { buffer[0] = SCTP_ITERATOR_3A_A_F; - sc_type * typeBuff = (sc_type*)(buffer + 1); + sc_type * typeBuff = (sc_type *)(buffer + 1); *typeBuff = param1; ++typeBuff; *typeBuff = param2; ++typeBuff; - ScRealAddr * addrBuff = (ScRealAddr*)typeBuff; + ScRealAddr * addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; return 1 + sizeof(ScRealAddr) + sizeof(sc_type) * 2; } - template -sc_uint32 Iterator5ParamsT(char * buffer, ParamType1 const & param1, ParamType2 const & param2, ParamType3 const & param3, ParamType4 const & param4, ParamType5 const & param5); - - -template <> sc_uint32 Iterator5ParamsT -(char * buffer, ScAddr const & param1, sc_type const & param2, sc_type const & param3, sc_type const & param4, ScAddr const & param5) +sc_uint32 Iterator5ParamsT( + char * buffer, + ParamType1 const & param1, + ParamType2 const & param2, + ParamType3 const & param3, + ParamType4 const & param4, + ParamType5 const & param5); + +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + sc_type const & param3, + sc_type const & param4, + ScAddr const & param5) { buffer[0] = SCTP_ITERATOR_5F_A_A_A_F; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; *typeBuff = param3; ++typeBuff; *typeBuff = param4; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param5; return 1 + sizeof(ScRealAddr) * 2 + sizeof(sc_type) * 3; } -template <> sc_uint32 Iterator5ParamsT -(char * buffer, sc_type const & param1, sc_type const & param2, ScAddr const & param3, sc_type const & param4, ScAddr const & param5) +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + sc_type const & param1, + sc_type const & param2, + ScAddr const & param3, + sc_type const & param4, + ScAddr const & param5) { buffer[0] = SCTP_ITERATOR_5A_A_F_A_F; - sc_type * typeBuff = (sc_type*)(buffer + 1); + sc_type * typeBuff = (sc_type *)(buffer + 1); *typeBuff = param1; ++typeBuff; *typeBuff = param2; ++typeBuff; - ScRealAddr * addrBuff = (ScRealAddr*)typeBuff; + ScRealAddr * addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; ++addrBuff; - typeBuff = (sc_type*)addrBuff; + typeBuff = (sc_type *)addrBuff; *typeBuff = param4; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param5; return 1 + sizeof(ScRealAddr) * 2 + sizeof(sc_type) * 3; } -template <> sc_uint32 Iterator5ParamsT -(char * buffer, ScAddr const & param1, sc_type const & param2, ScAddr const & param3, sc_type const & param4, ScAddr const & param5) +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + ScAddr const & param3, + sc_type const & param4, + ScAddr const & param5) { buffer[0] = SCTP_ITERATOR_5F_A_F_A_F; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; - typeBuff = (sc_type*)addrBuff; + typeBuff = (sc_type *)addrBuff; *typeBuff = param4; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param5; return 1 + sizeof(ScRealAddr) * 3 + sizeof(sc_type) * 2; } -template <> sc_uint32 Iterator5ParamsT -(char * buffer, sc_type const & param1, sc_type const & param2, ScAddr const & param3, sc_type const & param4, sc_type const & param5) +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + sc_type const & param1, + sc_type const & param2, + ScAddr const & param3, + sc_type const & param4, + sc_type const & param5) { buffer[0] = SCTP_ITERATOR_5A_A_F_A_A; - sc_type * typeBuff = (sc_type*)(buffer + 1); + sc_type * typeBuff = (sc_type *)(buffer + 1); *typeBuff = param1; ++typeBuff; *typeBuff = param2; ++typeBuff; - ScRealAddr * addrBuff = (ScRealAddr*)typeBuff; + ScRealAddr * addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; ++addrBuff; - typeBuff = (sc_type*)addrBuff; + typeBuff = (sc_type *)addrBuff; *typeBuff = param4; ++typeBuff; *typeBuff = param5; @@ -231,14 +270,20 @@ template <> sc_uint32 Iterator5ParamsT sc_uint32 Iterator5ParamsT -(char * buffer, ScAddr const & param1, sc_type const & param2, sc_type const & param3, sc_type const & param4, sc_type const & param5) +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + sc_type const & param3, + sc_type const & param4, + sc_type const & param5) { buffer[0] = SCTP_ITERATOR_5F_A_A_A_A; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; *typeBuff = param3; @@ -250,20 +295,26 @@ template <> sc_uint32 Iterator5ParamsT sc_uint32 Iterator5ParamsT -(char * buffer, ScAddr const & param1, sc_type const & param2, ScAddr const & param3, sc_type const & param4, sc_type const & param5) +template <> +sc_uint32 Iterator5ParamsT( + char * buffer, + ScAddr const & param1, + sc_type const & param2, + ScAddr const & param3, + sc_type const & param4, + sc_type const & param5) { buffer[0] = SCTP_ITERATOR_5F_A_F_A_A; - ScRealAddr * addrBuff = (ScRealAddr*)(buffer + 1); + ScRealAddr * addrBuff = (ScRealAddr *)(buffer + 1); *addrBuff = *param1; ++addrBuff; - sc_type * typeBuff = (sc_type*)addrBuff; + sc_type * typeBuff = (sc_type *)addrBuff; *typeBuff = param2; ++typeBuff; - addrBuff = (ScRealAddr*)typeBuff; + addrBuff = (ScRealAddr *)typeBuff; *addrBuff = *param3; ++addrBuff; - typeBuff = (sc_type*)addrBuff; + typeBuff = (sc_type *)addrBuff; *typeBuff = param4; ++typeBuff; *typeBuff = param5; @@ -294,8 +345,8 @@ class Client _SC_EXTERN sc_type GetElementType(ScAddr const & addr); /*! Change subtype of sc-element (subtype & sc_type_element_mask == 0). - * Return true, if there are no any errors; otherwise return false. - */ + * Return true, if there are no any errors; otherwise return false. + */ _SC_EXTERN bool SetElementSubtype(ScAddr const & addr, sc_type subtype); _SC_EXTERN bool GetArcInfo(ScAddr const & arcAddr, ScAddr & outBegin, ScAddr & outEnd) const; @@ -345,7 +396,8 @@ class Client /// TODO: possible merge 3 and 5 iterator in one template function template - _SC_EXTERN IteratorPtr Iterator5(ParamType1 param1, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5) + _SC_EXTERN IteratorPtr + Iterator5(ParamType1 param1, ParamType2 param2, ParamType3 param3, ParamType4 param4, ParamType5 param5) { char buffer[128]; sc_uint32 paramsSize = Iterator5ParamsT(buffer, param1, param2, param3, param4, param5); @@ -381,7 +433,6 @@ class Client return IteratorPtr(); } - private: bool WriteSctpHeader(RequestHeader const & header); /// Buffer must have a correct size @@ -389,9 +440,8 @@ class Client ///! TODO : Iterators private: - mutable sc_uint32 m_cmdIdCounter; ISocket * m_socketImpl; }; -} +} // namespace sctp diff --git a/sc-network/sctp_client/sctpISocket.hpp b/sc-network/sctp_client/sctpISocket.hpp index bd0f93f0b..69d26b0e9 100644 --- a/sc-network/sctp_client/sctpISocket.hpp +++ b/sc-network/sctp_client/sctpISocket.hpp @@ -11,11 +11,12 @@ namespace sctp { - class ISocket { public: - virtual ~ISocket() {} + virtual ~ISocket() + { + } virtual bool Connect(std::string const & host, std::string const & port) = 0; virtual void Disconnect() = 0; @@ -37,14 +38,14 @@ class ISocket template int WriteType(Type const & value) { - return Write((void*)&value, sizeof(Type)); + return Write((void *)&value, sizeof(Type)); } template int ReadType(Type const & value) { - return Read((void*)&value, sizeof(Type)); + return Read((void *)&value, sizeof(Type)); } }; -} +} // namespace sctp diff --git a/sc-network/sctp_client/sctpTypes.hpp b/sc-network/sctp_client/sctpTypes.hpp index bc16957bb..4fb881b48 100644 --- a/sc-network/sctp_client/sctpTypes.hpp +++ b/sc-network/sctp_client/sctpTypes.hpp @@ -13,34 +13,34 @@ extern "C" #include -#define POINTER_TO_UINT(p) ((sc_uint) (sc_ulong) (p)) -#define UINT_TO_POINTER(u) ((sc_pointer) (sc_ulong) (u)) +#define POINTER_TO_UINT(p) ((sc_uint)(sc_ulong)(p)) +#define UINT_TO_POINTER(u) ((sc_pointer)(sc_ulong)(u)) typedef enum { - SCTP_CMD_UNKNOWN = 0x00, // unkown command - SCTP_CMD_CHECK_ELEMENT = 0x01, // check if specified sc-element exist - SCTP_CMD_GET_ELEMENT_TYPE = 0x02, // return sc-element type - SCTP_CMD_ERASE_ELEMENT = 0x03, // erase specified sc-element - SCTP_CMD_CREATE_NODE = 0x04, // create new sc-node - SCTP_CMD_CREATE_LINK = 0x05, // create new sc-link - SCTP_CMD_CREATE_ARC = 0x06, // create new sc-arc - SCTP_CMD_GET_ARC = 0x07, // return begin element of sc-arc - - SCTP_CMD_GET_LINK_CONTENT = 0x09, // return content of sc-link - SCTP_CMD_FIND_LINKS = 0x0a, // return sc-links with specified content - SCTP_CMD_SET_LINK_CONTENT = 0x0b, // setup new content for the link - SCTP_CMD_ITERATE_ELEMENTS = 0x0c, // return base template iteration results - SCTP_CMD_ITERATE_CONSTRUCTION = 0x0d, // return advanced template iteration results - SCTP_CMD_EVENT_CREATE = 0x0e, // create subscription to specified event - SCTP_CMD_EVENT_DESTROY = 0x0f, // destroys specified event subscription - SCTP_CMD_EVENT_EMIT = 0x10, // emits events to client - SCTP_CMD_GENERATE_CONSTRUCTION = 0x11, // generate cunstrution by template - - SCTP_CMD_FIND_ELEMENT_BY_SYSITDF = 0xa0, // return sc-element by it system identifier - SCTP_CMD_SET_SYSIDTF = 0xa1, // setup new system identifier for sc-element - SCTP_CMD_STATISTICS = 0xa2, // return usage statistics from server - SCTP_CMD_VERSION = 0xa3 // return version of used sctp protocol + SCTP_CMD_UNKNOWN = 0x00, // unkown command + SCTP_CMD_CHECK_ELEMENT = 0x01, // check if specified sc-element exist + SCTP_CMD_GET_ELEMENT_TYPE = 0x02, // return sc-element type + SCTP_CMD_ERASE_ELEMENT = 0x03, // erase specified sc-element + SCTP_CMD_CREATE_NODE = 0x04, // create new sc-node + SCTP_CMD_CREATE_LINK = 0x05, // create new sc-link + SCTP_CMD_CREATE_ARC = 0x06, // create new sc-arc + SCTP_CMD_GET_ARC = 0x07, // return begin element of sc-arc + + SCTP_CMD_GET_LINK_CONTENT = 0x09, // return content of sc-link + SCTP_CMD_FIND_LINKS = 0x0a, // return sc-links with specified content + SCTP_CMD_SET_LINK_CONTENT = 0x0b, // setup new content for the link + SCTP_CMD_ITERATE_ELEMENTS = 0x0c, // return base template iteration results + SCTP_CMD_ITERATE_CONSTRUCTION = 0x0d, // return advanced template iteration results + SCTP_CMD_EVENT_CREATE = 0x0e, // create subscription to specified event + SCTP_CMD_EVENT_DESTROY = 0x0f, // destroys specified event subscription + SCTP_CMD_EVENT_EMIT = 0x10, // emits events to client + SCTP_CMD_GENERATE_CONSTRUCTION = 0x11, // generate cunstrution by template + + SCTP_CMD_FIND_ELEMENT_BY_SYSITDF = 0xa0, // return sc-element by it system identifier + SCTP_CMD_SET_SYSIDTF = 0xa1, // setup new system identifier for sc-element + SCTP_CMD_STATISTICS = 0xa2, // return usage statistics from server + SCTP_CMD_VERSION = 0xa3 // return version of used sctp protocol } eSctpCommandCode; @@ -63,25 +63,23 @@ typedef enum typedef enum { - SCTP_RESULT_OK = 0x00, // - SCTP_RESULT_FAIL = 0x01, // - SCTP_RESULT_ERROR_NO_ELEMENT= 0x02, // sc-element wasn't found - SCTP_RESULT_NORIGHTS = 0x03 + SCTP_RESULT_OK = 0x00, // + SCTP_RESULT_FAIL = 0x01, // + SCTP_RESULT_ERROR_NO_ELEMENT = 0x02, // sc-element wasn't found + SCTP_RESULT_NORIGHTS = 0x03 } eSctpResultCode; //! Command processing result codes typedef enum { - SCTP_NO_ERROR = 0, // No any errors, command processed - SCTP_ERROR, // There are any errors while processing command - SCTP_ERROR_UNKNOWN_CMD, // Unknown command code - SCTP_ERROR_CMD_READ_PARAMS, // Error while read command parameters - SCTP_ERROR_CMD_HEADER_READ_TIMEOUT, // Timeout while waiting command header - SCTP_ERROR_CMD_PARAM_READ_TIMEOUT // Timeout while waiting command params + SCTP_NO_ERROR = 0, // No any errors, command processed + SCTP_ERROR, // There are any errors while processing command + SCTP_ERROR_UNKNOWN_CMD, // Unknown command code + SCTP_ERROR_CMD_READ_PARAMS, // Error while read command parameters + SCTP_ERROR_CMD_HEADER_READ_TIMEOUT, // Timeout while waiting command header + SCTP_ERROR_CMD_PARAM_READ_TIMEOUT // Timeout while waiting command params } eSctpErrorCode; - typedef sc_uint32 tEventId; - diff --git a/sc-network/sctp_client/sockets/glibSocket.cpp b/sc-network/sctp_client/sockets/glibSocket.cpp index a36172c4f..cede35b53 100644 --- a/sc-network/sctp_client/sockets/glibSocket.cpp +++ b/sc-network/sctp_client/sockets/glibSocket.cpp @@ -5,16 +5,15 @@ */ #include "glibSocket.hpp" + #include namespace sctp { - glibSocket::glibSocket() : mConnection(NULL) , mClient(NULL) { - } bool glibSocket::connect(std::string const & host, std::string const & port) @@ -88,5 +87,4 @@ int glibSocket::write(void * buffer, unsigned int bytesCount) return (int)writtenBytes; } - -} +} // namespace sctp diff --git a/sc-network/sctp_client/sockets/glibSocket.hpp b/sc-network/sctp_client/sockets/glibSocket.hpp index 1e1f47bd2..35d54e60c 100644 --- a/sc-network/sctp_client/sockets/glibSocket.hpp +++ b/sc-network/sctp_client/sockets/glibSocket.hpp @@ -9,18 +9,16 @@ extern "C" { -#include #include +#include } #include "../sctpISocket.hpp" namespace sctp { - class glibSocket : public ISocket { - public: explicit glibSocket(); @@ -30,15 +28,15 @@ class glibSocket : public ISocket bool isConnected() const; /** Reads data from socket into buffer (buffer size must be equal to bytesCount). - * Returns number of bytes that was read. If returned value is -1, - * then there was error while read data. - */ + * Returns number of bytes that was read. If returned value is -1, + * then there was error while read data. + */ int read(void * buffer, unsigned int bytesCount); /** Writes data into socket from buffer (buffer size must be equal to bytesCount) - * Returns number of bytes that was written. If returned value is -1, - * then there was error while write data. - */ + * Returns number of bytes that was written. If returned value is -1, + * then there was error while write data. + */ int write(void * buffer, unsigned int bytesCount); private: @@ -49,4 +47,4 @@ class glibSocket : public ISocket GOutputStream * mOutputStream; }; -} +} // namespace sctp diff --git a/sc-network/sctp_client/sockets/winSocket.cpp b/sc-network/sctp_client/sockets/winSocket.cpp index a7ebd09c6..8e8afe61d 100644 --- a/sc-network/sctp_client/sockets/winSocket.cpp +++ b/sc-network/sctp_client/sockets/winSocket.cpp @@ -5,103 +5,102 @@ */ #include "winSocket.hpp" + #include #include namespace sctp { - winSocket::winSocket() - : m_socket(INVALID_SOCKET) + : m_socket(INVALID_SOCKET) { - } bool winSocket::Connect(std::string const & host, std::string const & port) { - int portValue = atoi(port.c_str()); - assert(portValue > 0); - - struct sockaddr_in address; - address.sin_family = AF_INET; - address.sin_port = htons(portValue); - address.sin_addr.s_addr = inet_addr(host.c_str());//InetPton(address.sin_family, host.c_str(), &address.sin_addr.s_addr); - - m_socket = socket(address.sin_family, SOCK_STREAM, 0); - if (m_socket == INVALID_SOCKET) - { - printf("Could not create socket: %d", WSAGetLastError()); - return false; - } - - if (::connect(m_socket, (struct sockaddr *)&address, sizeof(address)) < 0) - { - printf("Can't connect to server: %s:%s", host.c_str(), port.c_str()); - Disconnect(); - return false; - } - - - return true; + int portValue = atoi(port.c_str()); + assert(portValue > 0); + + struct sockaddr_in address; + address.sin_family = AF_INET; + address.sin_port = htons(portValue); + address.sin_addr.s_addr = + inet_addr(host.c_str()); // InetPton(address.sin_family, host.c_str(), &address.sin_addr.s_addr); + + m_socket = socket(address.sin_family, SOCK_STREAM, 0); + if (m_socket == INVALID_SOCKET) + { + printf("Could not create socket: %d", WSAGetLastError()); + return false; + } + + if (::connect(m_socket, (struct sockaddr *)&address, sizeof(address)) < 0) + { + printf("Can't connect to server: %s:%s", host.c_str(), port.c_str()); + Disconnect(); + return false; + } + + return true; } void winSocket::Disconnect() { - closesocket(m_socket); - m_socket = INVALID_SOCKET; + closesocket(m_socket); + m_socket = INVALID_SOCKET; } bool winSocket::IsConnected() const { - return (m_socket != INVALID_SOCKET); + return (m_socket != INVALID_SOCKET); } int winSocket::Read(void * buffer, size_t bytesCount) { - unsigned int bytesRead = 0; - char * buff = (char*)buffer; + unsigned int bytesRead = 0; + char * buff = (char *)buffer; - while (bytesRead < bytesCount) - { - int bytes = ::recv(m_socket, (&buff[bytesRead]), static_cast(bytesCount - bytesRead), 0); - if (bytes == SOCKET_ERROR) - return -1; + while (bytesRead < bytesCount) + { + int bytes = ::recv(m_socket, (&buff[bytesRead]), static_cast(bytesCount - bytesRead), 0); + if (bytes == SOCKET_ERROR) + return -1; - bytesRead += bytes; - } + bytesRead += bytes; + } - assert(bytesRead == bytesCount); - return bytesRead; + assert(bytesRead == bytesCount); + return bytesRead; } int winSocket::Write(void * buffer, size_t bytesCount) { - unsigned int bytesSent = 0; - char const * buff = (char*)buffer; + unsigned int bytesSent = 0; + char const * buff = (char *)buffer; - while (bytesSent < bytesCount) - { - int bytes = ::send(m_socket, (&(buff[bytesSent])), static_cast(bytesCount - bytesSent), 0); - if (bytes == SOCKET_ERROR) - return -1; + while (bytesSent < bytesCount) + { + int bytes = ::send(m_socket, (&(buff[bytesSent])), static_cast(bytesCount - bytesSent), 0); + if (bytes == SOCKET_ERROR) + return -1; - bytesSent += bytes; - } + bytesSent += bytes; + } - assert(bytesSent == bytesCount); + assert(bytesSent == bytesCount); - return bytesSent; + return bytesSent; } bool winSocket::Initialize() { - WSADATA wsaData; - return (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0); + WSADATA wsaData; + return (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0); } void winSocket::Shutdown() { - WSACleanup(); + WSACleanup(); } -} +} // namespace sctp diff --git a/sc-network/sctp_client/sockets/winSocket.hpp b/sc-network/sctp_client/sockets/winSocket.hpp index e1453f5fb..a6ad1a18b 100644 --- a/sc-network/sctp_client/sockets/winSocket.hpp +++ b/sc-network/sctp_client/sockets/winSocket.hpp @@ -7,6 +7,7 @@ #pragma once #include "../sctpISocket.hpp" + #include "sc-memory/sc-store/sc_defines.h" #define WIN32_LEAN_AND_MEAN @@ -16,41 +17,39 @@ #include // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib -#pragma comment (lib, "Ws2_32.lib") -#pragma comment (lib, "Mswsock.lib") -#pragma comment (lib, "AdvApi32.lib") +#pragma comment(lib, "Ws2_32.lib") +#pragma comment(lib, "Mswsock.lib") +#pragma comment(lib, "AdvApi32.lib") namespace sctp { - class winSocket : public ISocket { - public: - _SC_EXTERN explicit winSocket(); + _SC_EXTERN explicit winSocket(); - _SC_EXTERN bool Connect(std::string const & host, std::string const & port); - _SC_EXTERN void Disconnect(); + _SC_EXTERN bool Connect(std::string const & host, std::string const & port); + _SC_EXTERN void Disconnect(); - _SC_EXTERN bool IsConnected() const; + _SC_EXTERN bool IsConnected() const; - /** Reads data from socket into buffer (buffer size must be equal to bytesCount). - * Returns number of bytes that was read. If returned value is -1, - * then there was error while read data. - */ - _SC_EXTERN int Read(void * buffer, size_t bytesCount); + /** Reads data from socket into buffer (buffer size must be equal to bytesCount). + * Returns number of bytes that was read. If returned value is -1, + * then there was error while read data. + */ + _SC_EXTERN int Read(void * buffer, size_t bytesCount); - /** Writes data into socket from buffer (buffer size must be equal to bytesCount) - * Returns number of bytes that was written. If returned value is -1, - * then there was error while write data. - */ - _SC_EXTERN int Write(void * buffer, size_t bytesCount); + /** Writes data into socket from buffer (buffer size must be equal to bytesCount) + * Returns number of bytes that was written. If returned value is -1, + * then there was error while write data. + */ + _SC_EXTERN int Write(void * buffer, size_t bytesCount); - _SC_EXTERN static bool Initialize(); - _SC_EXTERN static void Shutdown(); + _SC_EXTERN static bool Initialize(); + _SC_EXTERN static void Shutdown(); private: - SOCKET m_socket; + SOCKET m_socket; }; -} +} // namespace sctp diff --git a/sc-network/sctp_client/test/test_client.cpp b/sc-network/sctp_client/test/test_client.cpp index 484c0c29a..07fb9f9ed 100644 --- a/sc-network/sctp_client/test/test_client.cpp +++ b/sc-network/sctp_client/test/test_client.cpp @@ -11,167 +11,168 @@ extern "C" #include "../sctpClient.hpp" -#if defined (SC_PLATFORM_WIN) - #include "../sockets/winSocket.hpp" - sctp::Client sctpClient(new sctp::winSocket()); +#if defined(SC_PLATFORM_WIN) +# include "../sockets/winSocket.hpp" +sctp::Client sctpClient(new sctp::winSocket()); #else - #include "../sockets/glibSocket.hpp" - sctp::Client sctpClient(new sctp::glibSocket()); +# include "../sockets/glibSocket.hpp" +sctp::Client sctpClient(new sctp::glibSocket()); #endif void test_connection() { - g_assert(sctpClient.Connect("127.0.0.1", "55770")); + g_assert(sctpClient.Connect("127.0.0.1", "55770")); } void test_base_commands() { + { + ScAddr addr = sctpClient.CreateNode(sc_type_node | sc_type_node_class); + + g_assert(addr.IsValid()); + g_assert(sctpClient.IsElement(addr)); + g_assert(sctpClient.GetElementType(addr) == (sc_type_node | sc_type_node_class)); + g_assert(sctpClient.EraseElement(addr)); + g_assert(!sctpClient.IsElement(addr)); + } + + { + ScAddr addr1 = sctpClient.CreateNode(sc_type_node); + ScAddr addr2 = sctpClient.CreateNode(sc_type_node); + + ScAddr arc = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr1, addr2); + + g_assert(arc.IsValid()); + g_assert(sctpClient.GetElementType(arc) == sc_type_arc_pos_const_perm); + + ScAddr a1, a2; + g_assert(sctpClient.GetArcInfo(arc, a1, a2)); + g_assert(a1 == addr1); + g_assert(a2 == addr2); + } + + { + ScAddr link = sctpClient.CreateLink(); + char * data = "Test data"; + IScStreamPtr stream(new ScStream(data, (sc_uint32)strlen(data), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); + + g_assert(link.IsValid()); + g_assert(sctpClient.SetLinkContent(link, stream)); + + g_assert(stream->Seek(SC_STREAM_SEEK_SET, 0)); + + IScStreamPtr stream2; + g_assert(sctpClient.GetLinkContent(link, stream2)); + g_assert(stream->Size() == stream2->Size()); + for (sc_uint32 i = 0; i < stream->Size(); ++i) { - ScAddr addr = sctpClient.CreateNode(sc_type_node | sc_type_node_class); - - g_assert(addr.IsValid()); - g_assert(sctpClient.IsElement(addr)); - g_assert(sctpClient.GetElementType(addr) == (sc_type_node | sc_type_node_class)); - g_assert(sctpClient.EraseElement(addr)); - g_assert(!sctpClient.IsElement(addr)); - } - - { - ScAddr addr1 = sctpClient.CreateNode(sc_type_node); - ScAddr addr2 = sctpClient.CreateNode(sc_type_node); - - ScAddr arc = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr1, addr2); - - g_assert(arc.IsValid()); - g_assert(sctpClient.GetElementType(arc) == sc_type_arc_pos_const_perm); - - ScAddr a1, a2; - g_assert(sctpClient.GetArcInfo(arc, a1, a2)); - g_assert(a1 == addr1); - g_assert(a2 == addr2); - } - - { - ScAddr link = sctpClient.CreateLink(); - char * data = "Test data"; - IScStreamPtr stream(new ScStream(data, (sc_uint32)strlen(data), SC_STREAM_FLAG_READ | SC_STREAM_FLAG_SEEK)); - - g_assert(link.IsValid()); - g_assert(sctpClient.SetLinkContent(link, stream)); - - g_assert(stream->Seek(SC_STREAM_SEEK_SET, 0)); - - IScStreamPtr stream2; - g_assert(sctpClient.GetLinkContent(link, stream2)); - g_assert(stream->Size() == stream2->Size()); - for (sc_uint32 i = 0; i < stream->Size(); ++i) - { - char v1, v2; - size_t r1, r2; - g_assert(stream->Read(&v1, sizeof(v1), r1)); - g_assert(stream2->Read(&v2, sizeof(v2), r2)); - - g_assert(r1 == r2); - g_assert(v1 == v2); - } - } + char v1, v2; + size_t r1, r2; + g_assert(stream->Read(&v1, sizeof(v1), r1)); + g_assert(stream2->Read(&v2, sizeof(v2), r2)); + + g_assert(r1 == r2); + g_assert(v1 == v2); + } + } } void test_iterators() { - { - ScAddr addr = sctpClient.CreateNode(0); - ScAddr addr1 = sctpClient.CreateNode(0); - ScAddr addr2 = sctpClient.CreateNode(0); - ScAddr addr3 = sctpClient.CreateNode(0); - - g_assert(addr.IsValid()); - g_assert(addr1.IsValid()); - g_assert(addr2.IsValid()); - g_assert(addr3.IsValid()); - - ScAddr arc1 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr1); - ScAddr arc2 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr2); - ScAddr arc3 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr3); - - g_assert(arc1.IsValid()); - g_assert(arc2.IsValid()); - g_assert(arc3.IsValid()); - - sctp::IteratorPtr iter = sctpClient.Iterator3(addr, sc_type_arc_pos_const_perm, sc_type_node); - g_assert(iter->next()); - g_assert(iter->getValue(0) == addr); - g_assert(iter->getValue(1) == arc3); - g_assert(iter->getValue(2) == addr3); - - g_assert(iter->next()); - g_assert(iter->getValue(0) == addr); - g_assert(iter->getValue(1) == arc2); - g_assert(iter->getValue(2) == addr2); - - g_assert(iter->next()); - g_assert(iter->getValue(0) == addr); - g_assert(iter->getValue(1) == arc1); - g_assert(iter->getValue(2) == addr1); - - g_assert(!iter->next()); - } - - { - ScAddr addr = sctpClient.CreateNode(0); - ScAddr addr1 = sctpClient.CreateNode(0); - ScAddr addr2 = sctpClient.CreateNode(0); - ScAddr addr3 = sctpClient.CreateNode(0); - - g_assert(addr.IsValid()); - g_assert(addr1.IsValid()); - g_assert(addr2.IsValid()); - g_assert(addr3.IsValid()); - - ScAddr arc1 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr1); - ScAddr arc2 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr2, arc1); - ScAddr arc3 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr3, arc1); - - g_assert(arc1.IsValid()); - g_assert(arc2.IsValid()); - g_assert(arc3.IsValid()); - - sctp::IteratorPtr iter = sctpClient.Iterator5(addr, sc_type_arc_pos_const_perm, addr1, sc_type_arc_pos_const_perm, sc_type_node); - - g_assert(iter->next()); - g_assert(iter->getValue(0) == addr); - g_assert(iter->getValue(1) == arc1); - g_assert(iter->getValue(2) == addr1); - g_assert(iter->getValue(3) == arc3); - g_assert(iter->getValue(4) == addr3); - - g_assert(iter->next()); - g_assert(iter->getValue(0) == addr); - g_assert(iter->getValue(1) == arc1); - g_assert(iter->getValue(2) == addr1); - g_assert(iter->getValue(3) == arc2); - g_assert(iter->getValue(4) == addr2); - - g_assert(!iter->next()); - } + { + ScAddr addr = sctpClient.CreateNode(0); + ScAddr addr1 = sctpClient.CreateNode(0); + ScAddr addr2 = sctpClient.CreateNode(0); + ScAddr addr3 = sctpClient.CreateNode(0); + + g_assert(addr.IsValid()); + g_assert(addr1.IsValid()); + g_assert(addr2.IsValid()); + g_assert(addr3.IsValid()); + + ScAddr arc1 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr1); + ScAddr arc2 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr2); + ScAddr arc3 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr3); + + g_assert(arc1.IsValid()); + g_assert(arc2.IsValid()); + g_assert(arc3.IsValid()); + + sctp::IteratorPtr iter = sctpClient.Iterator3(addr, sc_type_arc_pos_const_perm, sc_type_node); + g_assert(iter->next()); + g_assert(iter->getValue(0) == addr); + g_assert(iter->getValue(1) == arc3); + g_assert(iter->getValue(2) == addr3); + + g_assert(iter->next()); + g_assert(iter->getValue(0) == addr); + g_assert(iter->getValue(1) == arc2); + g_assert(iter->getValue(2) == addr2); + + g_assert(iter->next()); + g_assert(iter->getValue(0) == addr); + g_assert(iter->getValue(1) == arc1); + g_assert(iter->getValue(2) == addr1); + + g_assert(!iter->next()); + } + + { + ScAddr addr = sctpClient.CreateNode(0); + ScAddr addr1 = sctpClient.CreateNode(0); + ScAddr addr2 = sctpClient.CreateNode(0); + ScAddr addr3 = sctpClient.CreateNode(0); + + g_assert(addr.IsValid()); + g_assert(addr1.IsValid()); + g_assert(addr2.IsValid()); + g_assert(addr3.IsValid()); + + ScAddr arc1 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr, addr1); + ScAddr arc2 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr2, arc1); + ScAddr arc3 = sctpClient.CreateArc(sc_type_arc_pos_const_perm, addr3, arc1); + + g_assert(arc1.IsValid()); + g_assert(arc2.IsValid()); + g_assert(arc3.IsValid()); + + sctp::IteratorPtr iter = + sctpClient.Iterator5(addr, sc_type_arc_pos_const_perm, addr1, sc_type_arc_pos_const_perm, sc_type_node); + + g_assert(iter->next()); + g_assert(iter->getValue(0) == addr); + g_assert(iter->getValue(1) == arc1); + g_assert(iter->getValue(2) == addr1); + g_assert(iter->getValue(3) == arc3); + g_assert(iter->getValue(4) == addr3); + + g_assert(iter->next()); + g_assert(iter->getValue(0) == addr); + g_assert(iter->getValue(1) == arc1); + g_assert(iter->getValue(2) == addr1); + g_assert(iter->getValue(3) == arc2); + g_assert(iter->getValue(4) == addr2); + + g_assert(!iter->next()); + } } -int main(int argc, char *argv[]) +int main(int argc, char * argv[]) { -#if defined (SC_PLATFORM_WIN) - sctp::winSocket::Initialize(); +#if defined(SC_PLATFORM_WIN) + sctp::winSocket::Initialize(); #endif - g_test_init(&argc, &argv, NULL); + g_test_init(&argc, &argv, NULL); - g_test_add_func("/sctp/connection", test_connection); - g_test_add_func("/sctp/base_commands", test_base_commands); - g_test_add_func("/sctp/iterators", test_iterators); + g_test_add_func("/sctp/connection", test_connection); + g_test_add_func("/sctp/base_commands", test_base_commands); + g_test_add_func("/sctp/iterators", test_iterators); - g_test_run(); + g_test_run(); -#if defined (SC_PLATFORM_WIN) - sctp::winSocket::Shutdown(); +#if defined(SC_PLATFORM_WIN) + sctp::winSocket::Shutdown(); #endif - return 0; + return 0; } diff --git a/sc-network/sctp_server/main.cpp b/sc-network/sctp_server/main.cpp index d5a65bc23..b1b4f35fa 100644 --- a/sc-network/sctp_server/main.cpp +++ b/sc-network/sctp_server/main.cpp @@ -4,12 +4,14 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include +#include + #include "sctpServer.h" -#include +#include -int main(int argc, char *argv[]) try +int main(int argc, char * argv[]) +try { QCoreApplication a(argc, argv); @@ -27,7 +29,7 @@ int main(int argc, char *argv[]) try if (!server.start(config)) exit(1); - //QObject::connect(&a, SIGNAL(aboutToQuit()), &server, SLOT(stop())); + // QObject::connect(&a, SIGNAL(aboutToQuit()), &server, SLOT(stop())); return a.exec(); } diff --git a/sc-network/sctp_server/sctpClient.cpp b/sc-network/sctp_server/sctpClient.cpp index 36fbc767c..88c68a688 100644 --- a/sc-network/sctp_server/sctpClient.cpp +++ b/sc-network/sctp_server/sctpClient.cpp @@ -5,14 +5,15 @@ */ #include "sctpClient.h" + #include "sctpCommand.h" #include "sctpStatistic.h" -#include -#include #include +#include +#include -sctpClient::sctpClient(QObject *parent, int socketDescriptor) +sctpClient::sctpClient(QObject * parent, int socketDescriptor) : QThread(parent) , mSocket(0) , mCommand(0) @@ -61,7 +62,7 @@ void sctpClient::run() delete mCommand; mCommand = 0; - //deleteLater(); // shedule destroy in main thread + // deleteLater(); // shedule destroy in main thread } void sctpClient::processCommands() diff --git a/sc-network/sctp_server/sctpCommand.cpp b/sc-network/sctp_server/sctpCommand.cpp index 71a3acade..727480a69 100644 --- a/sc-network/sctp_server/sctpCommand.cpp +++ b/sc-network/sctp_server/sctpCommand.cpp @@ -5,30 +5,30 @@ */ #include "sctpCommand.h" -#include "sctpStatistic.h" + #include "sctpEventManager.h" +#include "sctpStatistic.h" -#include -#include -#include #include #include +#include +#include +#include extern "C" { -#include "sc-core/sc_memory_headers.h" #include "sc-core/sc_helper.h" +#include "sc-core/sc_memory_headers.h" } -#define SCTP_READ_TIMEOUT 3000 - -#define READ_PARAM(__val) if (params->readRawData((char*)&__val, sizeof(__val)) != sizeof(__val)) \ - return SCTP_ERROR_CMD_READ_PARAMS; +#define SCTP_READ_TIMEOUT 3000 +#define READ_PARAM(__val) \ + if (params->readRawData((char *)&__val, sizeof(__val)) != sizeof(__val)) \ + return SCTP_ERROR_CMD_READ_PARAMS; namespace { - class IterConstsr { public: @@ -60,8 +60,8 @@ class IterConstsr quint8 m_replCount; IterParam m_args[5]; - sc_iterator3 *m_it3; - sc_iterator5 *m_it5; + sc_iterator3 * m_it3; + sc_iterator5 * m_it5; IteratorData() : m_type(SCTP_ITERATOR_COUNT) @@ -69,7 +69,7 @@ class IterConstsr , m_it3(0) , m_it5(0) { - memset(&m_repl[0], 255, sizeof(uint8_t)* 5); + memset(&m_repl[0], 255, sizeof(uint8_t) * 5); } ~IteratorData() @@ -120,10 +120,10 @@ class IterConstsr return argsCount() != 0; } - bool buildRepl(QDataStream *params) + bool buildRepl(QDataStream * params) { quint8 count = fixedCount(); - params->readRawData((char*)&m_repl[0], count); + params->readRawData((char *)&m_repl[0], count); for (quint8 i = 0; i < count; ++i) { @@ -175,17 +175,19 @@ class IterConstsr case SCTP_ITERATOR_5F_A_A_A_A: m_args[0].m_param.is_type = false; - m_args[1].m_param.is_type = m_args[2].m_param.is_type = m_args[3].m_param.is_type = m_args[4].m_param.is_type = true; + m_args[1].m_param.is_type = m_args[2].m_param.is_type = m_args[3].m_param.is_type = m_args[4].m_param.is_type = + true; break; case SCTP_ITERATOR_5A_A_F_A_A: m_args[2].m_param.is_type = false; - m_args[0].m_param.is_type = m_args[1].m_param.is_type = m_args[3].m_param.is_type = m_args[4].m_param.is_type = true; + m_args[0].m_param.is_type = m_args[1].m_param.is_type = m_args[3].m_param.is_type = m_args[4].m_param.is_type = + true; break; } } - bool buildParams(QDataStream *params) + bool buildParams(QDataStream * params) { quint8 count = argsCount(); @@ -196,12 +198,12 @@ class IterConstsr { IterParam & p = m_args[i]; if (p.m_param.is_type) - params->readRawData((char*)&p.m_param.type, sizeof(p.m_param.type)); + params->readRawData((char *)&p.m_param.type, sizeof(p.m_param.type)); else { p.m_repl = m_repl[rCount]; if (!p.isRepl()) - params->readRawData((char*)&p.m_param.addr, sizeof(p.m_param.addr)); + params->readRawData((char *)&p.m_param.addr, sizeof(p.m_param.addr)); ++rCount; } } @@ -315,7 +317,7 @@ class IterConstsr return -1; } - } // switch + } // switch return -1; } @@ -364,7 +366,6 @@ class IterConstsr } else if (count == 5) { - } return false; @@ -378,7 +379,14 @@ class IterConstsr if (count == 3) m_it3 = sc_iterator3_new(ctx, scIterator3Type(m_type), m_args[0].m_param, m_args[1].m_param, m_args[2].m_param); else if (count == 5) - m_it5 = sc_iterator5_new(ctx, scIterator5Type(m_type), m_args[0].m_param, m_args[1].m_param, m_args[2].m_param, m_args[3].m_param, m_args[4].m_param); + m_it5 = sc_iterator5_new( + ctx, + scIterator5Type(m_type), + m_args[0].m_param, + m_args[1].m_param, + m_args[2].m_param, + m_args[3].m_param, + m_args[4].m_param); } void stopIterate() @@ -419,32 +427,30 @@ class IterConstsr for (quint8 i = 0; i < count; ++i) result[pos + i] = sc_iterator5_value(m_it5, i); } - } - }; // IteratorData + }; // IteratorData typedef std::vector IteratorDataVec; IteratorDataVec m_iterators; public: - - bool build(QDataStream *params) + bool build(QDataStream * params) { quint8 iterCount; - if (params->readRawData((char*)&iterCount, sizeof(iterCount)) != sizeof(iterCount)) + if (params->readRawData((char *)&iterCount, sizeof(iterCount)) != sizeof(iterCount)) return false; if (iterCount > 50) return false; m_iterators.resize(iterCount); - for (size_t i = 0; i readRawData((char*)&it.m_type, sizeof(it.m_type)) != sizeof(it.m_type)) + if (params->readRawData((char *)&it.m_type, sizeof(it.m_type)) != sizeof(it.m_type)) return false; if (i > 0) it.buildRepl(params); @@ -558,20 +564,17 @@ class IterConstsr return generateStep(ctx, m_results, 0, 0); } - ScAddrVec const & result() const { return m_results; } - }; -} // namespace - +} // namespace // ----------------------------- -sctpCommand::sctpCommand(QObject *parent) +sctpCommand::sctpCommand(QObject * parent) : QObject(parent) , mSendEventsCount(0) , mContext(0) @@ -598,7 +601,7 @@ void sctpCommand::shutdown() mContext = 0; } -eSctpErrorCode sctpCommand::processCommand(QIODevice *inDevice, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCommand(QIODevice * inDevice, QIODevice * outDevice) { quint8 cmdCode = SCTP_CMD_UNKNOWN; quint8 cmdFlags = 0; @@ -609,17 +612,17 @@ eSctpErrorCode sctpCommand::processCommand(QIODevice *inDevice, QIODevice *outDe if (!waitAvailableBytes(inDevice, cmdHeaderSize())) return SCTP_ERROR_CMD_HEADER_READ_TIMEOUT; - inDevice->read((char*)&cmdCode, sizeof(cmdCode)); - inDevice->read((char*)&cmdFlags, sizeof(cmdFlags)); - inDevice->read((char*)&cmdId, sizeof(cmdId)); - inDevice->read((char*)&cmdParamSize, sizeof(cmdParamSize)); + inDevice->read((char *)&cmdCode, sizeof(cmdCode)); + inDevice->read((char *)&cmdFlags, sizeof(cmdFlags)); + inDevice->read((char *)&cmdId, sizeof(cmdId)); + inDevice->read((char *)&cmdParamSize, sizeof(cmdParamSize)); // read params data QByteArray paramsData(cmdParamSize, 0); if (!waitAvailableBytes(inDevice, cmdParamSize)) return SCTP_ERROR_CMD_PARAM_READ_TIMEOUT; - inDevice->read((char*)paramsData.data(), paramsData.size()); + inDevice->read((char *)paramsData.data(), paramsData.size()); QDataStream paramsStream(paramsData); switch (cmdCode) @@ -688,7 +691,7 @@ eSctpErrorCode sctpCommand::processCommand(QIODevice *inDevice, QIODevice *outDe return SCTP_ERROR; } -bool sctpCommand::waitAvailableBytes(QIODevice *stream, quint32 bytesNum) +bool sctpCommand::waitAvailableBytes(QIODevice * stream, quint32 bytesNum) { while (stream->bytesAvailable() < bytesNum) { @@ -701,17 +704,22 @@ bool sctpCommand::waitAvailableBytes(QIODevice *stream, quint32 bytesNum) return true; } -void sctpCommand::writeResultHeader(eSctpCommandCode cmdCode, quint32 cmdId, eSctpResultCode resCode, quint32 resSize, QIODevice *outDevice) +void sctpCommand::writeResultHeader( + eSctpCommandCode cmdCode, + quint32 cmdId, + eSctpResultCode resCode, + quint32 resSize, + QIODevice * outDevice) { Q_ASSERT(outDevice != 0); quint8 code = cmdCode; - outDevice->write((const char*)&code, sizeof(code)); - outDevice->write((const char*)&cmdId, sizeof(cmdId)); + outDevice->write((const char *)&code, sizeof(code)); + outDevice->write((const char *)&cmdId, sizeof(cmdId)); code = resCode; - outDevice->write((const char*)&code, sizeof(code)); - outDevice->write((const char*)&resSize, sizeof(resSize)); + outDevice->write((const char *)&code, sizeof(code)); + outDevice->write((const char *)&resSize, sizeof(resSize)); } quint32 sctpCommand::cmdHeaderSize() @@ -719,9 +727,12 @@ quint32 sctpCommand::cmdHeaderSize() return 2 * sizeof(quint8) + 2 * sizeof(quint32); } - // ----------- process commands ------------- -eSctpErrorCode sctpCommand::processCheckElement(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCheckElement( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; Q_UNUSED(cmdFlags); @@ -739,7 +750,11 @@ eSctpErrorCode sctpCommand::processCheckElement(quint32 cmdFlags, quint32 cmdId, return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processGetElementType(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processGetElementType( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; Q_UNUSED(cmdFlags); @@ -750,18 +765,23 @@ eSctpErrorCode sctpCommand::processGetElementType(quint32 cmdFlags, quint32 cmdI READ_PARAM(addr); sc_type type = 0; - eSctpResultCode resCode = (sc_memory_get_element_type(mContext, addr, &type) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; + eSctpResultCode resCode = + (sc_memory_get_element_type(mContext, addr, &type) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; quint32 resSize = (resCode == SCTP_RESULT_OK) ? sizeof(type) : 0; // send result writeResultHeader(SCTP_CMD_GET_ELEMENT_TYPE, cmdId, resCode, resSize, outDevice); if (resCode == SCTP_RESULT_OK) - outDevice->write((const char*)&type, sizeof(type)); + outDevice->write((const char *)&type, sizeof(type)); return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processElementErase(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processElementErase( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; Q_UNUSED(cmdFlags); @@ -771,14 +791,19 @@ eSctpErrorCode sctpCommand::processElementErase(quint32 cmdFlags, quint32 cmdId, // read sc-addr of sc-element from parameters READ_PARAM(addr); - eSctpResultCode resCode = (sc_memory_element_free(mContext, addr) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; + eSctpResultCode resCode = + (sc_memory_element_free(mContext, addr) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; // send result writeResultHeader(SCTP_CMD_ERASE_ELEMENT, cmdId, resCode, 0, outDevice); return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processCreateNode(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCreateNode( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { Q_UNUSED(cmdFlags); @@ -795,10 +820,11 @@ eSctpErrorCode sctpCommand::processCreateNode(quint32 cmdFlags, quint32 cmdId, Q if (SC_ADDR_IS_NOT_EMPTY(addr)) { writeResultHeader(SCTP_CMD_CREATE_NODE, cmdId, SCTP_RESULT_OK, sizeof(addr), outDevice); - outDevice->write((const char*)&addr, sizeof(addr)); + outDevice->write((const char *)&addr, sizeof(addr)); result = SCTP_NO_ERROR; - }else + } + else { writeResultHeader(SCTP_CMD_CREATE_NODE, cmdId, SCTP_RESULT_FAIL, 0, outDevice); result = SCTP_ERROR; @@ -807,7 +833,11 @@ eSctpErrorCode sctpCommand::processCreateNode(quint32 cmdFlags, quint32 cmdId, Q return result; } -eSctpErrorCode sctpCommand::processCreateLink(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCreateLink( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { Q_UNUSED(cmdFlags); @@ -818,10 +848,11 @@ eSctpErrorCode sctpCommand::processCreateLink(quint32 cmdFlags, quint32 cmdId, Q if (SC_ADDR_IS_NOT_EMPTY(addr)) { writeResultHeader(SCTP_CMD_CREATE_LINK, cmdId, SCTP_RESULT_OK, sizeof(addr), outDevice); - outDevice->write((const char*)&addr, sizeof(addr)); + outDevice->write((const char *)&addr, sizeof(addr)); result = SCTP_NO_ERROR; - }else + } + else { writeResultHeader(SCTP_CMD_CREATE_LINK, cmdId, SCTP_RESULT_FAIL, 0, outDevice); result = SCTP_ERROR; @@ -830,7 +861,11 @@ eSctpErrorCode sctpCommand::processCreateLink(quint32 cmdFlags, quint32 cmdId, Q return result; } -eSctpErrorCode sctpCommand::processCreateArc(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCreateArc( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { Q_UNUSED(cmdFlags); @@ -851,10 +886,11 @@ eSctpErrorCode sctpCommand::processCreateArc(quint32 cmdFlags, quint32 cmdId, QD if (SC_ADDR_IS_NOT_EMPTY(addr)) { writeResultHeader(SCTP_CMD_CREATE_ARC, cmdId, SCTP_RESULT_OK, sizeof(addr), outDevice); - outDevice->write((const char*)&addr, sizeof(addr)); + outDevice->write((const char *)&addr, sizeof(addr)); result = SCTP_NO_ERROR; - }else + } + else { writeResultHeader(SCTP_CMD_CREATE_LINK, cmdId, SCTP_RESULT_FAIL, 0, outDevice); result = SCTP_ERROR; @@ -863,7 +899,7 @@ eSctpErrorCode sctpCommand::processCreateArc(quint32 cmdFlags, quint32 cmdId, QD return result; } -eSctpErrorCode sctpCommand::processGetArc(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processGetArc(quint32 cmdFlags, quint32 cmdId, QDataStream * params, QIODevice * outDevice) { Q_UNUSED(cmdFlags); @@ -881,15 +917,19 @@ eSctpErrorCode sctpCommand::processGetArc(quint32 cmdFlags, quint32 cmdId, QData } writeResultHeader(SCTP_CMD_GET_ARC, cmdId, SCTP_RESULT_OK, sizeof(sc_addr) * 2, outDevice); - outDevice->write((const char*)&begin, sizeof(begin)); - outDevice->write((const char*)&end, sizeof(end)); + outDevice->write((const char *)&begin, sizeof(begin)); + outDevice->write((const char *)&end, sizeof(end)); return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processGetLinkContent(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processGetLinkContent( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; - sc_stream *stream = (sc_stream*)null_ptr; + sc_stream * stream = (sc_stream *)null_ptr; sc_char data_buffer[512]; sc_uint32 data_len = 0; sc_uint32 data_written = 0; @@ -899,11 +939,11 @@ eSctpErrorCode sctpCommand::processGetLinkContent(quint32 cmdFlags, quint32 cmdI Q_ASSERT(params != 0); // read sc-addr of sc-element from parameters - if (params->readRawData((char*)&addr, sizeof(addr)) != sizeof(addr)) + if (params->readRawData((char *)&addr, sizeof(addr)) != sizeof(addr)) return SCTP_ERROR_CMD_READ_PARAMS; - eSctpResultCode resCode = (sc_memory_get_link_content(mContext, addr, &stream) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; - + eSctpResultCode resCode = + (sc_memory_get_link_content(mContext, addr, &stream) == SC_RESULT_OK) ? SCTP_RESULT_OK : SCTP_RESULT_FAIL; if (resCode == SCTP_RESULT_OK) { @@ -911,7 +951,7 @@ eSctpErrorCode sctpCommand::processGetLinkContent(quint32 cmdFlags, quint32 cmdI { resCode = SCTP_RESULT_FAIL; sc_stream_free(stream); - stream = (sc_stream*)null_ptr; + stream = (sc_stream *)null_ptr; } } // send result @@ -935,10 +975,10 @@ eSctpErrorCode sctpCommand::processGetLinkContent(quint32 cmdFlags, quint32 cmdI if (data_written < data_len) { quint32 len = data_len - data_written; - sc_char *data = new sc_char[len]; + sc_char * data = new sc_char[len]; memset(data, 0, len); outDevice->write(data, len); - delete []data; + delete[] data; sc_stream_free(stream); return SCTP_ERROR; @@ -954,14 +994,17 @@ eSctpErrorCode sctpCommand::processGetLinkContent(quint32 cmdFlags, quint32 cmdI if (resCode == SCTP_RESULT_OK) sc_stream_free(stream); - return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processFindLinks(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processFindLinks( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_int32 data_len = 0; - sc_char *data = 0; + sc_char * data = 0; Q_UNUSED(cmdFlags); @@ -978,17 +1021,18 @@ eSctpErrorCode sctpCommand::processFindLinks(quint32 cmdFlags, quint32 cmdId, QD return SCTP_ERROR_CMD_READ_PARAMS; } - sc_stream *stream = sc_stream_memory_new(data, data_len, SC_STREAM_FLAG_READ, SC_FALSE); + sc_stream * stream = sc_stream_memory_new(data, data_len, SC_STREAM_FLAG_READ, SC_FALSE); sc_uint32 result_count = 0; - sc_addr *result = 0; + sc_addr * result = 0; if (sc_memory_find_links_with_content(mContext, stream, &result, &result_count) != SC_RESULT_OK) writeResultHeader(SCTP_CMD_FIND_LINKS, cmdId, SCTP_RESULT_FAIL, 0, outDevice); else { - writeResultHeader(SCTP_CMD_FIND_LINKS, cmdId, SCTP_RESULT_OK, result_count * sizeof(sc_addr) + sizeof(result_count), outDevice); - outDevice->write((const char*)&result_count, sizeof(result_count)); - outDevice->write((const char*)result, sizeof(sc_addr) * result_count); + writeResultHeader( + SCTP_CMD_FIND_LINKS, cmdId, SCTP_RESULT_OK, result_count * sizeof(sc_addr) + sizeof(result_count), outDevice); + outDevice->write((const char *)&result_count, sizeof(result_count)); + outDevice->write((const char *)result, sizeof(sc_addr) * result_count); } delete[] data; sc_stream_free(stream); @@ -996,11 +1040,15 @@ eSctpErrorCode sctpCommand::processFindLinks(quint32 cmdFlags, quint32 cmdId, QD return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processSetLinkContent(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processSetLinkContent( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; sc_int32 data_len = 0; - sc_char *data = 0; + sc_char * data = 0; Q_UNUSED(cmdFlags); @@ -1018,17 +1066,22 @@ eSctpErrorCode sctpCommand::processSetLinkContent(quint32 cmdFlags, quint32 cmdI return SCTP_ERROR_CMD_READ_PARAMS; } - sc_stream *stream = sc_stream_memory_new(data, data_len, SC_STREAM_FLAG_READ, SC_FALSE); + sc_stream * stream = sc_stream_memory_new(data, data_len, SC_STREAM_FLAG_READ, SC_FALSE); sc_result result = sc_memory_set_link_content(mContext, addr, stream); - writeResultHeader(SCTP_CMD_SET_LINK_CONTENT, cmdId, result == SC_RESULT_OK ? SCTP_RESULT_OK : SCTP_RESULT_FAIL, 0, outDevice); + writeResultHeader( + SCTP_CMD_SET_LINK_CONTENT, cmdId, result == SC_RESULT_OK ? SCTP_RESULT_OK : SCTP_RESULT_FAIL, 0, outDevice); sc_stream_free(stream); delete[] data; return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processIterateElements(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processIterateElements( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_uchar iterator_type = 0; sc_type type1, type2, type3, type4; @@ -1046,7 +1099,7 @@ eSctpErrorCode sctpCommand::processIterateElements(quint32 cmdFlags, quint32 cmd // 3-elements iterators if (iterator_type <= SCTP_ITERATOR_3F_A_F) { - sc_iterator3 *it = (sc_iterator3*)null_ptr; + sc_iterator3 * it = (sc_iterator3 *)null_ptr; switch (iterator_type) { @@ -1091,23 +1144,24 @@ eSctpErrorCode sctpCommand::processIterateElements(quint32 cmdFlags, quint32 cmd for (sc_uint i = 0; i < 3; i++) { addr = sc_iterator3_value(it, i); - buffer.write((const char*)&addr, sizeof(addr)); + buffer.write((const char *)&addr, sizeof(addr)); } } buffer.close(); // write result - writeResultHeader(SCTP_CMD_ITERATE_ELEMENTS, cmdId, SCTP_RESULT_OK, results.size() + sizeof(results_count), outDevice); - outDevice->write((const char*)&results_count, sizeof(results_count)); + writeResultHeader( + SCTP_CMD_ITERATE_ELEMENTS, cmdId, SCTP_RESULT_OK, results.size() + sizeof(results_count), outDevice); + outDevice->write((const char *)&results_count, sizeof(results_count)); if (results_count > 0) - outDevice->write((const char*)results.constData(), results.size()); + outDevice->write((const char *)results.constData(), results.size()); sc_iterator3_free(it); - - }else + } + else { // 5-elements iterators - sc_iterator5 *it = (sc_iterator5*)null_ptr; + sc_iterator5 * it = (sc_iterator5 *)null_ptr; switch (iterator_type) { @@ -1185,16 +1239,17 @@ eSctpErrorCode sctpCommand::processIterateElements(quint32 cmdFlags, quint32 cmd for (sc_uint i = 0; i < 5; i++) { addr = sc_iterator5_value(it, i); - buffer.write((const char*)&addr, sizeof(addr)); + buffer.write((const char *)&addr, sizeof(addr)); } } buffer.close(); // write result - writeResultHeader(SCTP_CMD_ITERATE_ELEMENTS, cmdId, SCTP_RESULT_OK, results.size() + sizeof(results_count), outDevice); - outDevice->write((const char*)&results_count, sizeof(results_count)); + writeResultHeader( + SCTP_CMD_ITERATE_ELEMENTS, cmdId, SCTP_RESULT_OK, results.size() + sizeof(results_count), outDevice); + outDevice->write((const char *)&results_count, sizeof(results_count)); if (results_count > 0) - outDevice->write((const char*)results.constData(), results.size()); + outDevice->write((const char *)results.constData(), results.size()); sc_iterator5_free(it); } @@ -1202,7 +1257,11 @@ eSctpErrorCode sctpCommand::processIterateElements(quint32 cmdFlags, quint32 cmd return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processIterateConstruction(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processIterateConstruction( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { IterConstsr constr; if (constr.build(params)) @@ -1219,8 +1278,8 @@ eSctpErrorCode sctpCommand::processIterateConstruction(quint32 cmdFlags, quint32 if (result.size() > 0) { writeResultHeader(SCTP_CMD_ITERATE_CONSTRUCTION, cmdId, SCTP_RESULT_OK, s + sizeof(quint32), outDevice); - outDevice->write((const char*)&count, sizeof(count)); - outDevice->write((const char*)result.data(), s); + outDevice->write((const char *)&count, sizeof(count)); + outDevice->write((const char *)result.data(), s); } else writeResultHeader(SCTP_CMD_ITERATE_CONSTRUCTION, cmdId, SCTP_RESULT_FAIL, 0, outDevice); @@ -1231,7 +1290,11 @@ eSctpErrorCode sctpCommand::processIterateConstruction(quint32 cmdFlags, quint32 return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processGenerateConstruction(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processGenerateConstruction( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { IterConstsr constr; if (constr.build(params) && constr.generate(mContext)) @@ -1250,7 +1313,11 @@ eSctpErrorCode sctpCommand::processGenerateConstruction(quint32 cmdFlags, quint3 return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processCreateEvent(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processCreateEvent( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_uint8 event_type; sc_addr addr; @@ -1261,7 +1328,6 @@ eSctpErrorCode sctpCommand::processCreateEvent(quint32 cmdFlags, quint32 cmdId, READ_PARAM(event_type); READ_PARAM(addr); - tEventId event = 0; if (!sctpEventManager::getSingleton()->createEvent(mContext, (sc_event_type)event_type, addr, this, event)) { @@ -1275,12 +1341,16 @@ eSctpErrorCode sctpCommand::processCreateEvent(quint32 cmdFlags, quint32 cmdId, mEventsSet.insert(event); writeResultHeader(SCTP_CMD_EVENT_CREATE, cmdId, SCTP_RESULT_OK, sizeof(tEventId), outDevice); - outDevice->write((const char*)&event, sizeof(event)); + outDevice->write((const char *)&event, sizeof(event)); return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processDestroyEvent(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processDestroyEvent( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { tEventId eventId = 0; @@ -1292,7 +1362,7 @@ eSctpErrorCode sctpCommand::processDestroyEvent(quint32 cmdFlags, quint32 cmdId, if (sctpEventManager::getSingleton()->destroyEvent(eventId)) { writeResultHeader(SCTP_CMD_EVENT_DESTROY, cmdId, SCTP_RESULT_OK, sizeof(eventId), outDevice); - outDevice->write((const char*)&eventId, sizeof(eventId)); + outDevice->write((const char *)&eventId, sizeof(eventId)); return SCTP_NO_ERROR; } @@ -1300,13 +1370,17 @@ eSctpErrorCode sctpCommand::processDestroyEvent(quint32 cmdFlags, quint32 cmdId, return SCTP_ERROR; } -eSctpErrorCode sctpCommand::processEmitEvent(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processEmitEvent( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { QMutexLocker locker(&mSendMutex); quint32 resSize = sizeof(mSendEventsCount) + mSendData.size(); writeResultHeader(SCTP_CMD_EVENT_EMIT, cmdId, SCTP_RESULT_OK, resSize, outDevice); - outDevice->write((const char*)&mSendEventsCount, sizeof(mSendEventsCount)); + outDevice->write((const char *)&mSendEventsCount, sizeof(mSendEventsCount)); outDevice->write(mSendData); mSendData.clear(); @@ -1315,10 +1389,14 @@ eSctpErrorCode sctpCommand::processEmitEvent(quint32 cmdFlags, quint32 cmdId, QD return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processFindElementBySysIdtf(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processFindElementBySysIdtf( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_int32 data_len = 0; - sc_char *data = 0; + sc_char * data = 0; Q_UNUSED(cmdFlags); @@ -1326,7 +1404,7 @@ eSctpErrorCode sctpCommand::processFindElementBySysIdtf(quint32 cmdFlags, quint3 // read length of content data READ_PARAM(data_len); - Q_ASSERT(data_len > 0); // just for a test + Q_ASSERT(data_len > 0); // just for a test data = new sc_char[data_len]; if (params->readRawData(data, data_len) != data_len) @@ -1341,18 +1419,22 @@ eSctpErrorCode sctpCommand::processFindElementBySysIdtf(quint32 cmdFlags, quint3 else { writeResultHeader(SCTP_CMD_FIND_ELEMENT_BY_SYSITDF, cmdId, SCTP_RESULT_OK, sizeof(sc_addr), outDevice); - outDevice->write((const char*)&result, sizeof(sc_addr)); + outDevice->write((const char *)&result, sizeof(sc_addr)); } delete[] data; return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processSetSysIdtf(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processSetSysIdtf( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { sc_addr addr; sc_int32 data_len = 0; - sc_char *data = 0; + sc_char * data = 0; Q_UNUSED(cmdFlags); @@ -1370,14 +1452,24 @@ eSctpErrorCode sctpCommand::processSetSysIdtf(quint32 cmdFlags, quint32 cmdId, Q return SCTP_ERROR_CMD_READ_PARAMS; } - writeResultHeader(SCTP_CMD_SET_SYSIDTF, cmdId, sc_helper_set_system_identifier(mContext, addr, data, data_len) != SC_RESULT_OK ? SCTP_RESULT_FAIL : SCTP_RESULT_OK, 0, outDevice); + writeResultHeader( + SCTP_CMD_SET_SYSIDTF, + cmdId, + sc_helper_set_system_identifier(mContext, addr, data, data_len) != SC_RESULT_OK ? SCTP_RESULT_FAIL + : SCTP_RESULT_OK, + 0, + outDevice); delete[] data; return SCTP_NO_ERROR; } -eSctpErrorCode sctpCommand::processStatistics(quint32 cmdFlags, quint32 cmdId, QDataStream *params, QIODevice *outDevice) +eSctpErrorCode sctpCommand::processStatistics( + quint32 cmdFlags, + quint32 cmdId, + QDataStream * params, + QIODevice * outDevice) { quint64 begin_time; quint64 end_time; @@ -1391,23 +1483,24 @@ eSctpErrorCode sctpCommand::processStatistics(quint32 cmdFlags, quint32 cmdId, Q tStatItemVector stat; sctpStatistic::getInstance()->getStatisticsInTimeRange(begin_time, end_time, stat); - writeResultHeader(SCTP_CMD_STATISTICS, cmdId, SCTP_RESULT_OK, sizeof(quint32) + sStatItem::realSize() * stat.size(), outDevice); + writeResultHeader( + SCTP_CMD_STATISTICS, cmdId, SCTP_RESULT_OK, sizeof(quint32) + sStatItem::realSize() * stat.size(), outDevice); // write result quint32 res_count = stat.size(); - outDevice->write((const char*)&res_count, sizeof(res_count)); + outDevice->write((const char *)&res_count, sizeof(res_count)); for (quint32 idx = 0; idx < res_count; ++idx) - outDevice->write((const char*)&(stat[idx]), sStatItem::realSize()); + outDevice->write((const char *)&(stat[idx]), sStatItem::realSize()); return SCTP_NO_ERROR; } sc_result sctpCommand::processEventEmit(tEventId eventId, sc_addr el_addr, sc_addr arg_addr) -{ +{ QMutexLocker locker(&mSendMutex); - mSendData.append((char*)&eventId, sizeof(eventId)); - mSendData.append((char*)&el_addr, sizeof(el_addr)); - mSendData.append((char*)&arg_addr, sizeof(arg_addr)); + mSendData.append((char *)&eventId, sizeof(eventId)); + mSendData.append((char *)&el_addr, sizeof(el_addr)); + mSendData.append((char *)&arg_addr, sizeof(arg_addr)); ++mSendEventsCount; diff --git a/sc-network/sctp_server/sctpEventManager.cpp b/sc-network/sctp_server/sctpEventManager.cpp index 3889b40fe..a6b445f58 100644 --- a/sc-network/sctp_server/sctpEventManager.cpp +++ b/sc-network/sctp_server/sctpEventManager.cpp @@ -5,6 +5,7 @@ */ #include "sctpEventManager.h" + #include "sctpCommand.h" extern "C" @@ -12,7 +13,7 @@ extern "C" #include "sc-core/sc-store/sc_event.h" } -sctpEventManager* sctpEventManager::msInstance = 0; +sctpEventManager * sctpEventManager::msInstance = 0; sctpEventManager::sctpEventManager() : mLastEventId(1) @@ -26,7 +27,7 @@ sctpEventManager::~sctpEventManager() msInstance = 0; } -sctpEventManager* sctpEventManager::getSingleton() +sctpEventManager * sctpEventManager::getSingleton() { return msInstance; } @@ -45,7 +46,7 @@ void sctpEventManager::shutdown() tScEventsMap::iterator it, itEnd = mEvents.end(); for (it = mEvents.begin(); it != itEnd; ++it) { - sEventData *evt = it->second; + sEventData * evt = it->second; sc_event_destroy(evt->event); delete evt; } @@ -53,15 +54,19 @@ void sctpEventManager::shutdown() mEvents.clear(); } -bool sctpEventManager::createEvent(sc_memory_context *ctx, sc_event_type type, sc_addr addr, sctpCommand *cmd, tEventId &event) +bool sctpEventManager::createEvent( + sc_memory_context * ctx, + sc_event_type type, + sc_addr addr, + sctpCommand * cmd, + tEventId & event) { QMutexLocker locker(&mEventsMutex); - if (!_getAvailableEventId(event)) return false; - sEventData *evt = new sEventData(); + sEventData * evt = new sEventData(); evt->cmd = cmd; evt->id = event; @@ -93,7 +98,7 @@ bool sctpEventManager::destroyEvent(tEventId event) return true; } -bool sctpEventManager::_getAvailableEventId(tEventId &eventId) +bool sctpEventManager::_getAvailableEventId(tEventId & eventId) { tEventId start = mLastEventId; eventId = start + 1; @@ -110,8 +115,7 @@ bool sctpEventManager::_getAvailableEventId(tEventId &eventId) return false; } - -sc_result sctpEventManager::_eventsCallback(const sc_event *event, sc_addr arg) +sc_result sctpEventManager::_eventsCallback(const sc_event * event, sc_addr arg) { QMutexLocker locker(&sctpEventManager::msInstance->mEventsMutex); @@ -121,7 +125,7 @@ sc_result sctpEventManager::_eventsCallback(const sc_event *event, sc_addr arg) if (it == sctpEventManager::msInstance->mEvents.end()) return SC_RESULT_ERROR_INVALID_STATE; - sEventData *evt = it->second; + sEventData * evt = it->second; Q_ASSERT(evt && evt->cmd); Q_ASSERT(event == evt->event); diff --git a/sc-network/sctp_server/sctpServer.cpp b/sc-network/sctp_server/sctpServer.cpp index b62da9c8a..246276a96 100644 --- a/sc-network/sctp_server/sctpServer.cpp +++ b/sc-network/sctp_server/sctpServer.cpp @@ -5,15 +5,15 @@ */ #include "sctpServer.h" + #include "sctpClient.h" -#include "sctpStatistic.h" #include "sctpEventManager.h" +#include "sctpStatistic.h" -#include #include +#include #include #include - #include extern "C" @@ -23,7 +23,7 @@ extern "C" #include -sctpServer::sctpServer(QObject *parent) +sctpServer::sctpServer(QObject * parent) : QTcpServer(parent) , mPort(0) , mStatistic(0) @@ -36,10 +36,9 @@ sctpServer::~sctpServer() { if (mStatistic) delete mStatistic; - } -bool sctpServer::start(const QString &config) +bool sctpServer::start(const QString & config) { parseConfig(config); @@ -52,9 +51,10 @@ bool sctpServer::start(const QString &config) QString ipAddress; QList ipAddressesList = QNetworkInterface::allAddresses(); // use the first non-localhost IPv4 address - for (int i = 0; i < ipAddressesList.size(); ++i) { - if (ipAddressesList.at(i) != QHostAddress::LocalHost && - ipAddressesList.at(i).toIPv4Address()) { + for (int i = 0; i < ipAddressesList.size(); ++i) + { + if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) + { ipAddress = ipAddressesList.at(i).toString(); break; } @@ -63,8 +63,7 @@ bool sctpServer::start(const QString &config) // if we did not find one, use IPv4 localhost if (ipAddress.isEmpty()) ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); - QString message = QObject::tr("The server is running on\nIP: %1\tport: %2\n") - .arg(ipAddress).arg(serverPort()); + QString message = QObject::tr("The server is running on\nIP: %1\tport: %2\n").arg(ipAddress).arg(serverPort()); qDebug() << message.toUtf8().constData(); // initialize sc-memory @@ -101,7 +100,7 @@ bool sctpServer::start(const QString &config) return true; } -void sctpServer::parseConfig(const QString &config_path) +void sctpServer::parseConfig(const QString & config_path) { QSettings settings(config_path, QSettings::IniFormat); @@ -135,7 +134,8 @@ void sctpServer::parseConfig(const QString &config_path) if (!result) qWarning() << "Can't parse period statistic from configuration file\n"; if (mStatUpdatePeriod > 0 && mStatUpdatePeriod < 60) - qWarning() << "Statistics update period is very short, it would be take much processor time. Recomend to make it more long"; + qWarning() << "Statistics update period is very short, it would be take much processor time. Recomend to make it " + "more long"; mStatPath = settings.value("Stat/Path").toString(); if (mStatPath.isEmpty() && mStatUpdatePeriod > 0) @@ -147,9 +147,9 @@ void sctpServer::parseConfig(const QString &config_path) void sctpServer::incomingConnection(qintptr socketDescriptor) { - sctpClient *client = new sctpClient(this, socketDescriptor); + sctpClient * client = new sctpClient(this, socketDescriptor); connect(client, SIGNAL(finished()), client, SLOT(deleteLater())); - connect(client, SIGNAL(destroyed(QObject*)), this, SLOT(clientDestroyed(QObject*))); + connect(client, SIGNAL(destroyed(QObject *)), this, SLOT(clientDestroyed(QObject *))); mClients.insert(client); client->start(); } @@ -167,9 +167,9 @@ void sctpServer::stop() exit(0); } -void sctpServer::clientDestroyed(QObject *client) +void sctpServer::clientDestroyed(QObject * client) { - QSet::iterator it = mClients.find(static_cast(client)); + QSet::iterator it = mClients.find(static_cast(client)); if (it == mClients.end()) qWarning("Recieve event from non existing client"); diff --git a/sc-network/sctp_server/sctpStatistic.cpp b/sc-network/sctp_server/sctpStatistic.cpp index 1a7f4a662..be8893a9b 100644 --- a/sc-network/sctp_server/sctpStatistic.cpp +++ b/sc-network/sctp_server/sctpStatistic.cpp @@ -6,27 +6,26 @@ #include "sctpStatistic.h" -#include -#include #include #include +#include #include +#include extern "C" { #include "sc-core/sc_memory.h" } +sctpStatistic * sctpStatistic::mInstance = 0; -sctpStatistic* sctpStatistic::mInstance = 0; - -sctpStatistic* sctpStatistic::getInstance() +sctpStatistic * sctpStatistic::getInstance() { Q_ASSERT(mInstance != 0); return mInstance; } -sctpStatistic::sctpStatistic(QObject *parent) +sctpStatistic::sctpStatistic(QObject * parent) : QObject(parent) , mStatUpdatePeriod(0) , mStatUpdateTimer(0) @@ -42,7 +41,7 @@ sctpStatistic::~sctpStatistic() mInstance = 0; } -bool sctpStatistic::initialize(const QString &statDirPath, quint32 updatePeriod, sc_memory_context const * context) +bool sctpStatistic::initialize(const QString & statDirPath, quint32 updatePeriod, sc_memory_context const * context) { mStatPath = statDirPath; mStatUpdatePeriod = updatePeriod; @@ -91,7 +90,6 @@ void sctpStatistic::shutdown() mFsMutex = 0; } - void sctpStatistic::update() { QMutexLocker dataLocker(mDataMutex); @@ -105,7 +103,8 @@ void sctpStatistic::update() // determine date QDateTime dateTime(QDateTime::currentDateTime()); - QString statFileName = QString("%1_%2_%3").arg(dateTime.date().day()).arg(dateTime.date().month()).arg(dateTime.date().year()); + QString statFileName = + QString("%1_%2_%3").arg(dateTime.date().day()).arg(dateTime.date().month()).arg(dateTime.date().year()); QDir statDir(mStatPath); QString statFilePath = statDir.filePath(statFileName); @@ -119,20 +118,21 @@ void sctpStatistic::update() // read exist information in file if (file.open(QFile::ReadOnly)) { - if (file.read((char*)&stat.mCount, sizeof(stat.mCount)) != sizeof(stat.mCount)) + if (file.read((char *)&stat.mCount, sizeof(stat.mCount)) != sizeof(stat.mCount)) stat.mCount = 0; if (stat.mCount > 0) { int bytesToRead = sizeof(sStatItem) * stat.mCount; stat.mItems = new sStatItem[stat.mCount + 1]; - if (file.read((char*)&stat.mItems[0], bytesToRead) != bytesToRead) + if (file.read((char *)&stat.mItems[0], bytesToRead) != bytesToRead) stat.mCount = 0; } file.close(); - }else - qCritical() << "Can't open statistic file: " << statFilePath; + } + else + qCritical() << "Can't open statistic file: " << statFilePath; } // collect information @@ -158,11 +158,12 @@ void sctpStatistic::update() // save to file if (file.open(QFile::WriteOnly)) { - file.write((char*)&stat.mCount, sizeof(stat.mCount)); - file.write((char*)stat.mItems, sizeof(sStatItem) * stat.mCount); + file.write((char *)&stat.mCount, sizeof(stat.mCount)); + file.write((char *)stat.mItems, sizeof(sStatItem) * stat.mCount); file.close(); - }else + } + else qCritical() << "Can't write statistic file: " << statFilePath; memset(&mCurrentStat, 0, sizeof(mCurrentStat)); @@ -170,7 +171,7 @@ void sctpStatistic::update() mStatUpdateTimer->singleShot(mStatUpdatePeriod * 1000, this, SLOT(update())); } -void sctpStatistic::getStatisticsInTimeRange(quint64 beg_time, quint64 end_time, tStatItemVector &result) +void sctpStatistic::getStatisticsInTimeRange(quint64 beg_time, quint64 end_time, tStatItemVector & result) { QMutexLocker fsLocker(mFsMutex); @@ -188,7 +189,8 @@ void sctpStatistic::getStatisticsInTimeRange(quint64 beg_time, quint64 end_time, { // build date from file name QStringList values = fileName.split("_"); - if (values.size() != 3) continue; //! TODO: error reports + if (values.size() != 3) + continue; //! TODO: error reports fileDate.setDate(QDate(values[2].toInt(), values[1].toInt(), values[0].toInt())); @@ -202,14 +204,14 @@ void sctpStatistic::getStatisticsInTimeRange(quint64 beg_time, quint64 end_time, // read exist information in file if (file.open(QFile::ReadOnly)) { - if (file.read((char*)&stat.mCount, sizeof(stat.mCount)) != sizeof(stat.mCount)) + if (file.read((char *)&stat.mCount, sizeof(stat.mCount)) != sizeof(stat.mCount)) stat.mCount = 0; if (stat.mCount > 0) { int bytesToRead = sizeof(sStatItem) * stat.mCount; stat.mItems = new sStatItem[stat.mCount]; - if (file.read((char*)stat.mItems, bytesToRead) == bytesToRead) + if (file.read((char *)stat.mItems, bytesToRead) == bytesToRead) { // iterate internal data for (quint32 idx = 0; idx < stat.mCount; idx++) @@ -221,15 +223,16 @@ void sctpStatistic::getStatisticsInTimeRange(quint64 beg_time, quint64 end_time, else { if (stat.mItems[idx].mTime > end_time) - break; // do not process file, because we gone out of range + break; // do not process file, because we gone out of range } } - }//! TODO report error + } //! TODO report error } file.close(); - }else - qCritical() << "Can't open statistic file: " << statFilePath; + } + else + qCritical() << "Can't open statistic file: " << statFilePath; } } diff --git a/sc-server/src/main.cpp b/sc-server/src/main.cpp index 93c5338cb..d67da4d1a 100644 --- a/sc-server/src/main.cpp +++ b/sc-server/src/main.cpp @@ -4,30 +4,29 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include - -#include - #include #include #include +#include + #include +#include #include -int main(int argc, char *argv[]) try +int main(int argc, char * argv[]) +try { boost::program_options::options_description options_description("Builder usage"); - options_description.add_options() - ("help", "Display this message") - ("ext-path,e", boost::program_options::value(), "Path to directory with sc-memory extensions") - ("repo-path,r", boost::program_options::value(), "Path to repository") - ("verbose,v", "Flag to don't save sc-memory state on exit") - ("clear,c", "Flag to clear sc-memory on start") - ("config-file,i", boost::program_options::value(), "Path to configuration file"); + options_description.add_options()("help", "Display this message")( + "ext-path,e", boost::program_options::value(), "Path to directory with sc-memory extensions")( + "repo-path,r", boost::program_options::value(), "Path to repository")( + "verbose,v", "Flag to don't save sc-memory state on exit")("clear,c", "Flag to clear sc-memory on start")( + "config-file,i", boost::program_options::value(), "Path to configuration file"); boost::program_options::variables_map vm; - boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options_description).run(), vm); + boost::program_options::store( + boost::program_options::command_line_parser(argc, argv).options(options_description).run(), vm); boost::program_options::notify(vm); std::string configFile; @@ -56,7 +55,7 @@ int main(int argc, char *argv[]) try return 0; } - std::atomic_bool isRun = { true }; + std::atomic_bool isRun = {true}; utils::ScSignalHandler::Initialize(); utils::ScSignalHandler::m_onTerminate = [&isRun]() { @@ -81,7 +80,7 @@ int main(int argc, char *argv[]) try ScMemory::Shutdown(saveState); - return EXIT_SUCCESS; // : EXIT_FAILURE; + return EXIT_SUCCESS; // : EXIT_FAILURE; } catch (utils::ScException const & ex) { diff --git a/tools/builder/src/base64/base64.cpp b/tools/builder/src/base64/base64.cpp index 9b77e8d72..ea59da9fe 100644 --- a/tools/builder/src/base64/base64.cpp +++ b/tools/builder/src/base64/base64.cpp @@ -26,106 +26,106 @@ */ #include "base64.h" + #include static const std::string base64_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; static inline bool is_base64(unsigned char c) { - return (isalnum(c) || (c == '+') || (c == '/')); + return (isalnum(c) || (c == '+') || (c == '/')); } -std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) +std::string base64_encode(unsigned char const * bytes_to_encode, unsigned int in_len) { - std::string ret; - int i = 0; - int j = 0; - unsigned char char_array_3[3]; - unsigned char char_array_4[4]; - - while (in_len--) + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (in_len--) + { + char_array_3[i++] = *(bytes_to_encode++); + if (i == 3) { - char_array_3[i++] = *(bytes_to_encode++); - if (i == 3) - { - char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - char_array_4[3] = char_array_3[2] & 0x3f; - - for(i = 0; (i <4) ; i++) - ret += base64_chars[char_array_4[i]]; - i = 0; - } + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; (i < 4); i++) + ret += base64_chars[char_array_4[i]]; + i = 0; } + } - if (i) - { - for(j = i; j < 3; j++) - char_array_3[j] = '\0'; - - char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - char_array_4[3] = char_array_3[2] & 0x3f; + if (i) + { + for (j = i; j < 3; j++) + char_array_3[j] = '\0'; - for (j = 0; (j < i + 1); j++) - ret += base64_chars[char_array_4[j]]; + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; - while((i++ < 3)) - ret += '='; + for (j = 0; (j < i + 1); j++) + ret += base64_chars[char_array_4[j]]; - } - - return ret; + while ((i++ < 3)) + ret += '='; + } + return ret; } std::string base64_decode(std::string const & encoded_string) { - int in_len = (int)encoded_string.size(); - int i = 0; - int j = 0; - int in_ = 0; - unsigned char char_array_4[4], char_array_3[3]; - std::string ret; - - while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) + int in_len = (int)encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) + { + char_array_4[i++] = encoded_string[in_]; + in_++; + if (i == 4) { - char_array_4[i++] = encoded_string[in_]; in_++; - if (i == 4) - { - for (i = 0; i <4; i++) - char_array_4[i] = static_cast(base64_chars.find(char_array_4[i])); - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (i = 0; (i < 3); i++) - ret += char_array_3[i]; - i = 0; - } + for (i = 0; i < 4; i++) + char_array_4[i] = static_cast(base64_chars.find(char_array_4[i])); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; (i < 3); i++) + ret += char_array_3[i]; + i = 0; } + } - if (i) - { - for (j = i; j <4; j++) - char_array_4[j] = 0; + if (i) + { + for (j = i; j < 4; j++) + char_array_4[j] = 0; - for (j = 0; j <4; j++) - char_array_4[j] = static_cast(base64_chars.find(char_array_4[j])); + for (j = 0; j < 4; j++) + char_array_4[j] = static_cast(base64_chars.find(char_array_4[j])); - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; - } + for (j = 0; (j < i - 1); j++) + ret += char_array_3[j]; + } - return ret; + return ret; } diff --git a/tools/builder/src/builder.cpp b/tools/builder/src/builder.cpp index ce87cb573..1f013bef1 100644 --- a/tools/builder/src/builder.cpp +++ b/tools/builder/src/builder.cpp @@ -5,23 +5,20 @@ */ #include "builder.hpp" + #include "keynodes.hpp" #include "scs_translator.hpp" -#include #include +#include +#include #include #include -#include - namespace impl { - -std::unordered_set gSupportedFormats = { - "scs", "scsi" -}; +std::unordered_set gSupportedFormats = {"scs", "scsi"}; std::string NormalizeExt(std::string ext) { @@ -37,7 +34,7 @@ bool IsSupportedFormat(std::string const & fileExt) class ExtParser { public: - void operator() (std::string const & file_path) + void operator()(std::string const & file_path) { if (!file_path.empty()) { @@ -60,17 +57,17 @@ class ExtParser m_params.push_back(nullptr); } - std::vector & GetParams() + std::vector & GetParams() { return m_params; } private: - std::vector m_params; + std::vector m_params; std::vector m_names; }; -} // namespace impl +} // namespace impl Builder::Builder() { @@ -82,10 +79,8 @@ bool Builder::Run(BuilderParams const & params) if (!boost::filesystem::exists(m_params.m_inputPath)) { - ScConsole::PrintLine() << ScConsole::Color::White - << "File or directory " << ScConsole::Color::Red - << m_params.m_inputPath << ScConsole::Color::White - << " doesn't exist"; + ScConsole::PrintLine() << ScConsole::Color::White << "File or directory " << ScConsole::Color::Red + << m_params.m_inputPath << ScConsole::Color::White << " doesn't exist"; return false; } @@ -93,7 +88,7 @@ bool Builder::Run(BuilderParams const & params) CollectFiles(); // initialize sc-memory - bool noErrors = true; + bool noErrors = true; impl::ExtParser extParser; extParser(m_params.m_enabledExtPath); @@ -107,7 +102,7 @@ bool Builder::Run(BuilderParams const & params) ScMemory::Initialize(p); m_ctx.reset(new ScMemoryContext(sc_access_lvl_make_min, "Builder")); - + Keynodes::InitGlobal(); std::cout << "Build knowledge base from sources... " << std::endl; @@ -127,8 +122,8 @@ bool Builder::Run(BuilderParams const & params) ScConsole::SetColor(ScConsole::Color::Green); std::cout << "ok" << std::endl; - } - catch(utils::ScException const & e) + } + catch (utils::ScException const & e) { ScConsole::SetColor(ScConsole::Color::Red); std::cout << "failed" << std::endl; @@ -136,14 +131,14 @@ bool Builder::Run(BuilderParams const & params) std::cout << e.Message() << std::endl; noErrors = false; break; - } + } } ScConsole::PrintLine() << ScConsole::Color::Green << "Clean state..."; Translator::Clean(*m_ctx); if (noErrors) - { + { // print statistics ScMemoryContext::Stat const stats = m_ctx->CalculateStat(); @@ -151,7 +146,8 @@ bool Builder::Run(BuilderParams const & params) auto const printLine = [](std::string const & name, uint32_t num, float percent) { - ScConsole::PrintLine() << ScConsole::Color::LightBlue << name << ": " << ScConsole::Color::White << num << "(" << percent << "%)"; + ScConsole::PrintLine() << ScConsole::Color::LightBlue << name << ": " << ScConsole::Color::White << num << "(" + << percent << "%)"; }; ScConsole::PrintLine() << ScConsole::Color::White << "Statistics"; @@ -174,20 +170,15 @@ bool Builder::ProcessFile(std::string const & fileName) std::string const ext = utils::StringUtils::GetFileExtension(fileName); if (ext.empty()) { - SC_THROW_EXCEPTION( - utils::ExceptionInvalidState, - "Can't determine file extension " << fileName); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't determine file extension " << fileName); return false; } - std::shared_ptr translator = CreateTranslator(ext); if (!translator) { - SC_THROW_EXCEPTION( - utils::ExceptionInvalidState, - "Can't create translator for a file " << fileName); + SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't create translator for a file " << fileName); return false; } @@ -226,8 +217,8 @@ void Builder::CollectFiles(std::string const & path) try { ++it; - } - catch(...) + } + catch (...) { std::cout << ex.what() << std::endl; return; @@ -268,7 +259,8 @@ void Builder::CollectFiles() } } } - } else + } + else { SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Can't open file: " << m_params.m_inputPath); } @@ -278,12 +270,9 @@ void Builder::CollectFiles() std::shared_ptr Builder::CreateTranslator(std::string const & fileExt) { std::string const ext = impl::NormalizeExt(fileExt); - + if (ext == "scs" || ext == "scsi") return std::make_shared(*m_ctx); return {}; } - - - diff --git a/tools/builder/src/builder.hpp b/tools/builder/src/builder.hpp index 47736c771..84dda0443 100644 --- a/tools/builder/src/builder.hpp +++ b/tools/builder/src/builder.hpp @@ -22,9 +22,9 @@ struct BuilderParams //! Path to file with a list of enabled extensions std::string m_enabledExtPath; //! Flag to clear output - bool m_clearOutput:1; + bool m_clearOutput : 1; //! Flag to generate format information based on file extensions - bool m_autoFormatInfo:1; + bool m_autoFormatInfo : 1; //! Path to configuration file std::string m_configFile; }; @@ -35,7 +35,7 @@ class Builder Builder(); bool Run(BuilderParams const & options); - + protected: bool ProcessFile(std::string const & filename); @@ -43,7 +43,7 @@ class Builder void CollectFiles(); std::shared_ptr CreateTranslator(std::string const & fileExt); - + private: std::list m_files; diff --git a/tools/builder/src/exception.hpp b/tools/builder/src/exception.hpp index 557e3344c..2e970bca0 100644 --- a/tools/builder/src/exception.hpp +++ b/tools/builder/src/exception.hpp @@ -11,5 +11,8 @@ class ExceptionFileNotFound final : public utils::ScException { public: - ExceptionFileNotFound(std::string const & description, std::string const & msg) : utils::ScException("Assert: " + description, msg) {} + ExceptionFileNotFound(std::string const & description, std::string const & msg) + : utils::ScException("Assert: " + description, msg) + { + } }; \ No newline at end of file diff --git a/tools/builder/src/gwf_translator.cpp b/tools/builder/src/gwf_translator.cpp index 3a22b109b..3c337dd61 100644 --- a/tools/builder/src/gwf_translator.cpp +++ b/tools/builder/src/gwf_translator.cpp @@ -6,19 +6,16 @@ #include "gwf_translator.hpp" -#include "utils.hpp" - #include "base64/base64.h" -#include "tinyxml/tinyxml2.h" - #include "sc-memory/sc_memory.hpp" +#include "tinyxml/tinyxml2.h" +#include "utils.hpp" +#include #include #include #include -#include - std::string const sEdge = "arc"; std::string const sPair = "pair"; std::string const sBus = "bus"; @@ -41,7 +38,7 @@ bool GwfTranslator::TranslateImpl(Params const & params) if (error != tinyxml2::XML_SUCCESS) PARSE_ERROR(params.m_fileName, -1, doc.GetErrorStr2()); - tinyxml2::XMLElement *root = doc.FirstChildElement("GWF"); + tinyxml2::XMLElement * root = doc.FirstChildElement("GWF"); if (!root) PARSE_ERROR(params.m_fileName, -1, "Can't find root element"); @@ -50,12 +47,12 @@ bool GwfTranslator::TranslateImpl(Params const & params) PARSE_ERROR(params.m_fileName, -1, "Can't find static sector"); // collect elements - std::vector nodes; - std::vector edges; - std::vector buses; - std::vector all; + std::vector nodes; + std::vector edges; + std::vector buses; + std::vector all; - tinyxml2::XMLElement *el = root->FirstChildElement(); + tinyxml2::XMLElement * el = root->FirstChildElement(); while (el) { all.push_back(el); @@ -78,7 +75,7 @@ bool GwfTranslator::TranslateImpl(Params const & params) std::unordered_map idMap; // create all nodes - std::vector::iterator it, itEnd = nodes.end(); + std::vector::iterator it, itEnd = nodes.end(); for (it = nodes.begin(); it != itEnd; ++it) { el = *it; @@ -96,7 +93,7 @@ bool GwfTranslator::TranslateImpl(Params const & params) if (addr.IsValid()) { idMap[id] = addr; - continue; // skip elements that already exists + continue; // skip elements that already exists } } } @@ -106,7 +103,7 @@ bool GwfTranslator::TranslateImpl(Params const & params) // if (el->Name() == sContour) // { // AppendScAddr(m_ctx.CreateNode(ScType::NodeConstStruct, idtf); -// } +// } // else // { // tinyxml2::XMLElement *content = el->FirstChildElement("content"); @@ -118,12 +115,12 @@ bool GwfTranslator::TranslateImpl(Params const & params) // std::string const strType = el->Attribute("type"); // ScAddr const addr = m_ctx.CreateNode(ConvertType(strType)); // appendScAddr(addr, idtf); -// } +// } // else // { // // need to create link // ScAddr const addr = m_ctx.CreateLink(); -// +// // // setup content // std::string data = content->GetText(); // if (content->IntAttribute("type") == 4) @@ -226,7 +223,7 @@ ScAddr GwfTranslator::GetScAddr(std::string const & idtf) { return {}; } -//bool GwfTranslator::getScAddr(const String &idtf, sc_addr &addr) +// bool GwfTranslator::getScAddr(const String &idtf, sc_addr &addr) //{ // tStringAddrMap::iterator it = mLocalIdtfAddrs.find(idtf); // if (it != mLocalIdtfAddrs.end()) @@ -249,7 +246,8 @@ ScAddr GwfTranslator::GetScAddr(std::string const & idtf) // return true; // } // -// if (sc_helper_find_element_by_system_identifier(mContext, idtf.c_str(), (sc_uint32)idtf.size(), &addr) == SC_RESULT_OK) +// if (sc_helper_find_element_by_system_identifier(mContext, idtf.c_str(), (sc_uint32)idtf.size(), &addr) == +// SC_RESULT_OK) // return true; // // return false; @@ -359,6 +357,6 @@ ScType GwfTranslator::ConvertType(std::string const & type) if (type == "arc/var/pos/temp") return ScType::EdgeAccessVarPosTemp; - + return ScType(); } diff --git a/tools/builder/src/gwf_translator.hpp b/tools/builder/src/gwf_translator.hpp index a5e8eac75..3ef12e017 100644 --- a/tools/builder/src/gwf_translator.hpp +++ b/tools/builder/src/gwf_translator.hpp @@ -7,12 +7,10 @@ #pragma once #include "sc-memory/sc_type.hpp" - #include "translator.hpp" class GwfTranslator : public Translator { - protected: explicit GwfTranslator(class ScMemoryContext & context); virtual ~GwfTranslator() = default; diff --git a/tools/builder/src/main.cpp b/tools/builder/src/main.cpp index 3cf37a00c..fde3661f7 100644 --- a/tools/builder/src/main.cpp +++ b/tools/builder/src/main.cpp @@ -4,29 +4,28 @@ * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ -#include - #include "builder.hpp" +#include + #include -int main(int argc, char *argv[]) try +int main(int argc, char * argv[]) +try { - boost::program_options::options_description options_description("Builder usage"); - options_description.add_options() - ("help", "Display this message") - ("version", "Displays version number") - ("input-path,i", boost::program_options::value(), "Path to directory with sources") - ("output-path,o", boost::program_options::value(), "Path to output directory (repository)") - ("extension-path,e", boost::program_options::value(), "Path to extensions directory") - ("enabled-ext", boost::program_options::value(), "Path to file with enabled extensions") - ("clear-output,c", "Clear output directory (repository) before build") - ("settings,s", boost::program_options::value(), "Path to configuration file for sc-memory") - ("auto-formats,f", "Enable automatic formats info generation"); + options_description.add_options()("help", "Display this message")("version", "Displays version number")( + "input-path,i", boost::program_options::value(), "Path to directory with sources")( + "output-path,o", boost::program_options::value(), "Path to output directory (repository)")( + "extension-path,e", boost::program_options::value(), "Path to extensions directory")( + "enabled-ext", boost::program_options::value(), "Path to file with enabled extensions")( + "clear-output,c", "Clear output directory (repository) before build")( + "settings,s", boost::program_options::value(), "Path to configuration file for sc-memory")( + "auto-formats,f", "Enable automatic formats info generation"); boost::program_options::variables_map vm; - boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options_description).run(), vm); + boost::program_options::store( + boost::program_options::command_line_parser(argc, argv).options(options_description).run(), vm); boost::program_options::notify(vm); if (vm.count("help") || !vm.count("input-path") || !vm.count("output-path")) diff --git a/tools/builder/src/scs_translator.cpp b/tools/builder/src/scs_translator.cpp index 3b0e3275b..688aa3d2c 100644 --- a/tools/builder/src/scs_translator.cpp +++ b/tools/builder/src/scs_translator.cpp @@ -15,11 +15,10 @@ namespace impl { - class FileProvider : public SCsFileInterface { public: - explicit FileProvider(std::string const& parentPath) + explicit FileProvider(std::string const & parentPath) : m_parentPath(parentPath) { } @@ -52,8 +51,7 @@ class FileProvider : public SCsFileInterface } else { - SC_THROW_EXCEPTION(utils::ExceptionParseError, - "Can't process file content by url " << fileURL); + SC_THROW_EXCEPTION(utils::ExceptionParseError, "Can't process file content by url " << fileURL); } return {}; @@ -63,7 +61,7 @@ class FileProvider : public SCsFileInterface std::string m_parentPath; }; -} // namespace impl +} // namespace impl SCsTranslator::SCsTranslator(ScMemoryContext & context) : Translator(context) @@ -76,7 +74,7 @@ bool SCsTranslator::TranslateImpl(Params const & params) GetFileContent(params.m_fileName, data); SCsHelper scs(m_ctx, std::make_shared(params.m_fileName)); - + if (!scs.GenerateBySCsText(data)) { SC_THROW_EXCEPTION(utils::ExceptionParseError, scs.GetLastError()); diff --git a/tools/builder/src/scs_translator.hpp b/tools/builder/src/scs_translator.hpp index eedda6823..c6abd12e9 100644 --- a/tools/builder/src/scs_translator.hpp +++ b/tools/builder/src/scs_translator.hpp @@ -10,7 +10,6 @@ class SCsTranslator : public Translator { - public: explicit SCsTranslator(class ScMemoryContext & context); virtual ~SCsTranslator() = default; diff --git a/tools/builder/src/translator.cpp b/tools/builder/src/translator.cpp index 7119fdade..09001fb2f 100644 --- a/tools/builder/src/translator.cpp +++ b/tools/builder/src/translator.cpp @@ -5,10 +5,10 @@ */ #include "translator.hpp" -#include "keynodes.hpp" -#include "sc-memory/sc_memory.hpp" +#include "keynodes.hpp" #include "sc-memory/sc_link.hpp" +#include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_templates.hpp" Translator::Translator(ScMemoryContext & ctx) @@ -27,20 +27,18 @@ void Translator::GenerateFormatInfo(ScAddr const & addr, std::string const & ext ScAddr const formatAddr = m_ctx.HelperResolveSystemIdtf(fmtStr, ScType::NodeConstClass); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - addr, - ScType::EdgeDCommonVar, - formatAddr, - ScType::EdgeAccessVarPosPerm, - Keynodes::kNrelFormat()) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + addr, ScType::EdgeDCommonVar, formatAddr, ScType::EdgeAccessVarPosPerm, Keynodes::kNrelFormat()) + .Make(); ScTemplateGenerate generator(m_ctx, *templ); ScTemplateGenerate::Result result = generator.Do(); if (!result) { - SC_THROW_EXCEPTION(utils::ExceptionInvalidState, "Error to generate format for sc-link: " << generator.GetErrorMessage()); + SC_THROW_EXCEPTION( + utils::ExceptionInvalidState, "Error to generate format for sc-link: " << generator.GetErrorMessage()); } } @@ -67,18 +65,15 @@ void Translator::Clean(ScMemoryContext & ctx) } ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::Unknown, - ScType::EdgeDCommonVar, - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm, - nrelSCsGlobalIdtf) - .Make(); + .TripleWithRelation( + ScType::Unknown, + ScType::EdgeDCommonVar, + ScType::Link >> "_link", + ScType::EdgeAccessVarPosPerm, + nrelSCsGlobalIdtf) + .Make(); ScTemplateSearch search(ctx, *templ); for (ScTemplateNamedStruct const & res : search) ctx.EraseElement(res["_link"]); } - - - diff --git a/tools/builder/src/translator.hpp b/tools/builder/src/translator.hpp index 37a29ff27..436489b63 100644 --- a/tools/builder/src/translator.hpp +++ b/tools/builder/src/translator.hpp @@ -13,7 +13,6 @@ class Translator { public: - struct Params { //! Name of file to translate @@ -21,7 +20,7 @@ class Translator //! Flag to generate format information based on file extensions bool m_autoFormatInfo; }; - + explicit Translator(class ScMemoryContext & context); virtual ~Translator() = default; @@ -49,4 +48,3 @@ class Translator //! Pointer to memory context class ScMemoryContext & m_ctx; }; - diff --git a/tools/builder/src/utils.hpp b/tools/builder/src/utils.hpp index a3b6cfc5d..9717abc20 100644 --- a/tools/builder/src/utils.hpp +++ b/tools/builder/src/utils.hpp @@ -9,6 +9,7 @@ #include "sc-memory/sc_debug.hpp" #define PARSE_ERROR(source, line, description) \ -{ \ - SC_THROW_EXCEPTION(utils::ExceptionParseError, "Error: '" << description << "' in " << source << " at line " << line); \ -} + { \ + SC_THROW_EXCEPTION( \ + utils::ExceptionParseError, "Error: '" << description << "' in " << source << " at line " << line); \ + } diff --git a/tools/builder/tests/units/builder_test.hpp b/tools/builder/tests/units/builder_test.hpp index b30ee7338..2cb1b1da3 100644 --- a/tools/builder/tests/units/builder_test.hpp +++ b/tools/builder/tests/units/builder_test.hpp @@ -4,7 +4,6 @@ #include "sc-memory/sc_memory.hpp" #include "sc-memory/sc_templates.hpp" - #include "test_defines.hpp" #include diff --git a/tools/builder/tests/units/test_base.cpp b/tools/builder/tests/units/test_base.cpp index b9d4261d0..eff869cc8 100644 --- a/tools/builder/tests/units/test_base.cpp +++ b/tools/builder/tests/units/test_base.cpp @@ -1,7 +1,6 @@ #include #include "builder_test.hpp" - #include "sc-memory/sc_templates.hpp" TEST_F(ScBuilderTest, Smoke) @@ -9,11 +8,11 @@ TEST_F(ScBuilderTest, Smoke) ScMemoryContext ctx("Builder_Base"); std::string const scsData = - "base" - " _<- test_element;" - " _=> nrel_main_idtf::" - " _[]" - " (* _<- lang_en;; *);;"; + "base" + " _<- test_element;" + " _=> nrel_main_idtf::" + " _[]" + " (* _<- lang_en;; *);;"; ScTemplatePtr templ = ScTemplateSCsBuilder(ctx).Make(scsData); EXPECT_TRUE(templ); diff --git a/tools/builder/tests/units/test_clean.cpp b/tools/builder/tests/units/test_clean.cpp index 71474ca2f..dcc95589f 100644 --- a/tools/builder/tests/units/test_clean.cpp +++ b/tools/builder/tests/units/test_clean.cpp @@ -1,23 +1,22 @@ #include +#include "builder_test.hpp" #include "sc-memory/sc_link.hpp" #include "sc-memory/sc_templates.hpp" -#include "builder_test.hpp" - TEST_F(ScBuilderTest, clean_global_idtfs) { ScAddr const nrelSCsIdtf = m_ctx->HelperResolveSystemIdtf("nrel_scs_global_idtf"); EXPECT_TRUE(nrelSCsIdtf.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - ScType::Unknown, - ScType::EdgeDCommonVar, - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm, - nrelSCsIdtf) - .Make(); + .TripleWithRelation( + ScType::Unknown, + ScType::EdgeDCommonVar, + ScType::Link >> "_link", + ScType::EdgeAccessVarPosPerm, + nrelSCsIdtf) + .Make(); ScTemplateSearch search(*m_ctx, *templ); EXPECT_EQ(search.begin(), search.end()); diff --git a/tools/builder/tests/units/test_contents.cpp b/tools/builder/tests/units/test_contents.cpp index 966ebd5f7..9c9f0c806 100644 --- a/tools/builder/tests/units/test_contents.cpp +++ b/tools/builder/tests/units/test_contents.cpp @@ -1,8 +1,7 @@ #include -#include "sc-memory/sc_link.hpp" - #include "builder_test.hpp" +#include "sc-memory/sc_link.hpp" TEST_F(ScBuilderTest, file_relative) { diff --git a/tools/builder/tests/units/test_visibility.cpp b/tools/builder/tests/units/test_visibility.cpp index 3887381e6..8c5b8433d 100644 --- a/tools/builder/tests/units/test_visibility.cpp +++ b/tools/builder/tests/units/test_visibility.cpp @@ -1,25 +1,20 @@ #include -#include "sc-memory/sc_link.hpp" - #include "builder_test.hpp" +#include "sc-memory/sc_link.hpp" namespace { - -std::string GetIdtf(ScMemoryContext & ctx, ScAddr const& addr) +std::string GetIdtf(ScMemoryContext & ctx, ScAddr const & addr) { ScAddr const nrelIdtf = ctx.HelperResolveSystemIdtf("nrel_idtf", ScType::NodeConstNoRole); EXPECT_TRUE(nrelIdtf.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .TripleWithRelation( - addr, - ScType::EdgeDCommonVar, - ScType::Link >> "_link", - ScType::EdgeAccessVarPosPerm, - nrelIdtf) - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder() + .TripleWithRelation( + addr, ScType::EdgeDCommonVar, ScType::Link >> "_link", ScType::EdgeAccessVarPosPerm, nrelIdtf) + .Make(); ScTemplateSearch search(ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -35,7 +30,7 @@ std::string GetIdtf(ScMemoryContext & ctx, ScAddr const& addr) return link.Get(); }; -} // namespace +} // namespace TEST_F(ScBuilderTest, visibility_sys_idtf) { @@ -49,15 +44,9 @@ TEST_F(ScBuilderTest, visibility_sys_idtf) EXPECT_TRUE(element.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - visFirst, - ScType::EdgeAccessVarPosPerm, - element) - .Triple( - visSecond, - ScType::EdgeAccessVarPosPerm, - element) - .Make(); + .Triple(visFirst, ScType::EdgeAccessVarPosPerm, element) + .Triple(visSecond, ScType::EdgeAccessVarPosPerm, element) + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -73,15 +62,9 @@ TEST_F(ScBuilderTest, visibility_global) EXPECT_TRUE(visSecond.IsValid()); ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - visFirst, - ScType::EdgeAccessVarPosTemp, - ScType::Node >> ".visibility_global") - .Triple( - visSecond, - ScType::EdgeAccessVarPosTemp, - ".visibility_global") - .Make(); + .Triple(visFirst, ScType::EdgeAccessVarPosTemp, ScType::Node >> ".visibility_global") + .Triple(visSecond, ScType::EdgeAccessVarPosTemp, ".visibility_global") + .Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); @@ -106,12 +89,8 @@ TEST_F(ScBuilderTest, visibility_local) ScAddr const visLocal = m_ctx->HelperResolveSystemIdtf("visibility_local"); EXPECT_TRUE(visLocal.IsValid()); - ScTemplatePtr templ = ScTemplateBuilder() - .Triple( - visLocal, - ScType::EdgeAccessVarPosPerm, - ScType::NodeVar >> "_local") - .Make(); + ScTemplatePtr templ = + ScTemplateBuilder().Triple(visLocal, ScType::EdgeAccessVarPosPerm, ScType::NodeVar >> "_local").Make(); ScTemplateSearch search(*m_ctx, *templ); ScTemplateSearch::Iterator found = search.begin(); diff --git a/tools/codegen/Parser/Cache.cpp b/tools/codegen/Parser/Cache.cpp index 4ad50e5a7..63452d261 100644 --- a/tools/codegen/Parser/Cache.cpp +++ b/tools/codegen/Parser/Cache.cpp @@ -1,11 +1,12 @@ #include "Cache.hpp" + #include "Sha256.hpp" +#include + #include #include -#include - SourceCache::SourceCache(std::string const & path, std::string const & targetName) : m_cacheFileName(path + "/" + targetName + ".gen_cache") { @@ -57,7 +58,7 @@ void SourceCache::CheckGenerator(std::string const & fileName) if (it != m_cache.end()) { if (it->second == checksum) - return; // generator doesn't changed + return; // generator doesn't changed } // clear cache, because of new generator diff --git a/tools/codegen/Parser/Cache.hpp b/tools/codegen/Parser/Cache.hpp index 9018a4ba2..a8afc838a 100644 --- a/tools/codegen/Parser/Cache.hpp +++ b/tools/codegen/Parser/Cache.hpp @@ -19,6 +19,7 @@ class SourceCache static std::string FileChecksum(std::string const & fileName); void Reset(); + private: using CacheMap = std::unordered_map; CacheMap m_cache; diff --git a/tools/codegen/Parser/Cursor.cpp b/tools/codegen/Parser/Cursor.cpp index 012cb49b8..79e5c1a43 100644 --- a/tools/codegen/Parser/Cursor.cpp +++ b/tools/codegen/Parser/Cursor.cpp @@ -2,7 +2,7 @@ #include "MetaUtils.hpp" -Cursor::Cursor(const CXCursor &handle) +Cursor::Cursor(const CXCursor & handle) : m_handle(handle) { CXSourceLocation loc = clang_getCursorLocation(m_handle); @@ -69,7 +69,6 @@ CX_CXXAccessSpecifier Cursor::GetAccessModifier(void) const return clang_getCXXAccessSpecifier(m_handle); } - CursorType Cursor::GetType(void) const { return clang_getCursorType(m_handle); @@ -106,7 +105,7 @@ Cursor::List Cursor::GetChildren(void) const return children; } -void Cursor::VisitChildren(Visitor visitor, void *data) +void Cursor::VisitChildren(Visitor visitor, void * data) { clang_visitChildren(m_handle, visitor, data); } diff --git a/tools/codegen/Parser/Cursor.hpp b/tools/codegen/Parser/Cursor.hpp index bc2939871..ea46f67ce 100644 --- a/tools/codegen/Parser/Cursor.hpp +++ b/tools/codegen/Parser/Cursor.hpp @@ -10,7 +10,7 @@ class Cursor typedef std::vector List; typedef CXCursorVisitor Visitor; - Cursor(const CXCursor &handle); + Cursor(const CXCursor & handle); CXCursorKind GetKind(void) const; @@ -25,14 +25,14 @@ class Cursor bool IsStatic(void) const; CX_CXXAccessSpecifier GetAccessModifier(void) const; - //CX_StorageClass GetStorageClass(void) const; + // CX_StorageClass GetStorageClass(void) const; CursorType GetType(void) const; CursorType GetReturnType(void) const; CursorType GetTypedefType(void) const; List GetChildren(void) const; - void VisitChildren(Visitor visitor, void *data = nullptr); + void VisitChildren(Visitor visitor, void * data = nullptr); private: CXCursor m_handle; diff --git a/tools/codegen/Parser/CursorType.cpp b/tools/codegen/Parser/CursorType.cpp index 2a6ac507c..18b2204c6 100644 --- a/tools/codegen/Parser/CursorType.cpp +++ b/tools/codegen/Parser/CursorType.cpp @@ -1,12 +1,11 @@ #include "CursorType.hpp" -#include "Cursor.hpp" +#include "Cursor.hpp" #include "MetaUtils.hpp" -CursorType::CursorType(const CXType &handle) +CursorType::CursorType(const CXType & handle) : m_handle(handle) { - } std::string CursorType::GetDisplayName(void) const diff --git a/tools/codegen/Parser/CursorType.hpp b/tools/codegen/Parser/CursorType.hpp index 5a95f7291..bbe6c1af2 100644 --- a/tools/codegen/Parser/CursorType.hpp +++ b/tools/codegen/Parser/CursorType.hpp @@ -1,7 +1,6 @@ #pragma once #include - #include class Cursor; @@ -9,7 +8,7 @@ class Cursor; class CursorType { public: - CursorType(const CXType &handle); + CursorType(const CXType & handle); std::string GetDisplayName(void) const; diff --git a/tools/codegen/Parser/LanguageTypes/Class.cpp b/tools/codegen/Parser/LanguageTypes/Class.cpp index 9de1e90a8..2ecfe3e10 100644 --- a/tools/codegen/Parser/LanguageTypes/Class.cpp +++ b/tools/codegen/Parser/LanguageTypes/Class.cpp @@ -1,30 +1,27 @@ #include "Class.hpp" + +#include "../ReservedTypes.hpp" + #include "Constructor.hpp" #include "Cursor.hpp" #include "Field.hpp" +#include "Function.hpp" #include "Global.hpp" #include "Method.hpp" -#include "Function.hpp" - -#include "../ReservedTypes.hpp" #include -BaseClass::BaseClass(const Cursor &cursor) +BaseClass::BaseClass(const Cursor & cursor) : name(cursor.GetType().GetCanonicalType().GetDisplayName()) { - } bool BaseClass::IsNative() const { - return (name == Classes::Object || - name == Classes::Agent || - name == Classes::AgentAction || - name == Classes::Module); + return (name == Classes::Object || name == Classes::Agent || name == Classes::AgentAction || name == Classes::Module); } -Class::Class(const Cursor &cursor, const Namespace ¤tNamespace) +Class::Class(const Cursor & cursor, const Namespace & currentNamespace) : LanguageType(cursor, currentNamespace) , m_name(cursor.GetDisplayName()) , m_qualifiedName(cursor.GetType().GetDisplayName()) @@ -33,11 +30,10 @@ Class::Class(const Cursor &cursor, const Namespace ¤tNamespace) m_isScObject = false; m_displayName = cursor.GetSpelling(); - for (auto &child : cursor.GetChildren()) + for (auto & child : cursor.GetChildren()) { switch (child.GetKind()) { - case CXCursor_CXXBaseSpecifier: { auto baseClass = new BaseClass(child); @@ -55,7 +51,7 @@ Class::Class(const Cursor &cursor, const Namespace ¤tNamespace) m_metaData.SetProperty(ParserMeta::ParentClass, baseClass->name); } } - break; + break; // constructor case CXCursor_Constructor: @@ -96,7 +92,6 @@ Class::Class(const Cursor &cursor, const Namespace ¤tNamespace) default: break; } - } m_metaData.Check(); @@ -189,10 +184,11 @@ void Class::GenerateStaticFieldsInitCode(std::stringstream & outCode) const if (IsActionAgent()) { outCode << "\t"; - Field::GenerateResolveKeynodeCode(m_metaData.GetNativeString(Props::AgentCommandClass), - "ms_cmdClass_" + m_displayName, - "ScType::NodeConstClass", - outCode); + Field::GenerateResolveKeynodeCode( + m_metaData.GetNativeString(Props::AgentCommandClass), + "ms_cmdClass_" + m_displayName, + "ScType::NodeConstClass", + outCode); outCode << " \\\n"; } } @@ -226,7 +222,9 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const outCode << "\\\nprotected: "; outCode << "\\\n\t" << constrCode; - outCode << m_displayName << "(ScAddr const & cmdClassAddr, char const * name, sc_uint8 accessLvl) : Super(cmdClassAddr, name, accessLvl) {}"; + outCode << m_displayName + << "(ScAddr const & cmdClassAddr, char const * name, sc_uint8 accessLvl) : Super(cmdClassAddr, name, " + "accessLvl) {}"; } else { @@ -257,8 +255,8 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const outCode << "\\\nprotected: "; outCode << "\\\n " << constrCode; outCode << m_displayName << "(char const * name, sc_uint8 accessLvl) : Super(name, accessLvl) {}"; - outCode << "\\\n virtual sc_result Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & otherAddr) override; "; - + outCode << "\\\n virtual sc_result Run(ScAddr const & listenAddr, ScAddr const & edgeAddr, ScAddr const & " + "otherAddr) override; "; } outCode << "\\\nprivate:"; @@ -275,10 +273,13 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const { outCode << "\\\n static ScAddr const & GetCommandClassAddr() { return ms_cmdClass_" << m_displayName << "; }"; } - outCode << "\\\n static bool handler_emit" << "(ScAddr const & addr, ScAddr const & edgeAddr, ScAddr const & otherAddr)"; + outCode << "\\\n static bool handler_emit" + << "(ScAddr const & addr, ScAddr const & edgeAddr, ScAddr const & otherAddr)"; outCode << "\\\n {"; - outCode << "\\\n " << m_displayName << " Instance(" << instConstructParams << "\"" << m_displayName << "\", sc_access_lvl_make_min);"; - outCode << "\\\n " << "return Instance.Run(addr, edgeAddr, otherAddr) == SC_RESULT_OK;"; + outCode << "\\\n " << m_displayName << " Instance(" << instConstructParams << "\"" << m_displayName + << "\", sc_access_lvl_make_min);"; + outCode << "\\\n " + << "return Instance.Run(addr, edgeAddr, otherAddr) == SC_RESULT_OK;"; outCode << "\\\n }"; // register/unregister @@ -286,16 +287,19 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const outCode << "\\\n {"; outCode << "\\\n SC_ASSERT(!ms_event.get(), ());"; outCode << "\\\n SC_ASSERT(!ms_context.get(), ());"; - outCode << "\\\n ms_context.reset(new ScMemoryContext(sc_access_lvl_make_min, \"handler_" << m_displayName << "\"));"; - outCode << "\\\n ms_event.reset(new ScEvent(*ms_context, " << listenAddr << ", " - << eventType << ", &" << m_displayName << "::handler_emit" << "));"; + outCode << "\\\n ms_context.reset(new ScMemoryContext(sc_access_lvl_make_min, \"handler_" << m_displayName + << "\"));"; + outCode << "\\\n ms_event.reset(new ScEvent(*ms_context, " << listenAddr << ", " << eventType << ", &" + << m_displayName << "::handler_emit" + << "));"; outCode << "\\\n if (ms_event.get())"; outCode << "\\\n {"; /// TODO: Use common log system if (isActionAgent) { - outCode << "\\\n SC_LOG_INFO(\"Register agent " << m_displayName << " to action " << m_metaData.GetNativeString(Props::AgentCommandClass) << "\");"; + outCode << "\\\n SC_LOG_INFO(\"Register agent " << m_displayName << " to action " + << m_metaData.GetNativeString(Props::AgentCommandClass) << "\");"; } else { @@ -315,7 +319,7 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const outCode << "\\\n ms_context.reset();"; outCode << "\\\n }"; } - else if (IsModule()) // overrides for modules + else if (IsModule()) // overrides for modules { outCode << "\\\npublic:"; outCode << "\\\n sc_result InitializeGenerated()"; @@ -326,7 +330,6 @@ void Class::GenerateDeclarations(std::stringstream & outCode) const outCode << "\\\n if (!ScAgentInit(false))"; outCode << "\\\n return SC_RESULT_ERROR;"; - outCode << "\\\n return InitializeImpl();"; outCode << "\\\n }"; diff --git a/tools/codegen/Parser/LanguageTypes/Class.hpp b/tools/codegen/Parser/LanguageTypes/Class.hpp index d0e3bdf11..a1584ad55 100644 --- a/tools/codegen/Parser/LanguageTypes/Class.hpp +++ b/tools/codegen/Parser/LanguageTypes/Class.hpp @@ -1,11 +1,10 @@ #pragma once -#include "LanguageType.hpp" - #include "Constructor.hpp" #include "Field.hpp" #include "Function.hpp" #include "Global.hpp" +#include "LanguageType.hpp" #include "Method.hpp" #include @@ -13,7 +12,7 @@ struct BaseClass { - BaseClass(const Cursor &cursor); + BaseClass(const Cursor & cursor); bool IsNative() const; @@ -30,7 +29,7 @@ class Class : public LanguageType friend class Field; public: - Class(const Cursor &cursor, const Namespace ¤tNamespace); + Class(const Cursor & cursor, const Namespace & currentNamespace); bool ShouldGenerate(void) const; bool IsAgent() const; diff --git a/tools/codegen/Parser/LanguageTypes/Constructor.cpp b/tools/codegen/Parser/LanguageTypes/Constructor.cpp index f6e18554a..e842d90a6 100644 --- a/tools/codegen/Parser/LanguageTypes/Constructor.cpp +++ b/tools/codegen/Parser/LanguageTypes/Constructor.cpp @@ -1,5 +1,6 @@ -#include "Class.hpp" #include "Constructor.hpp" + +#include "Class.hpp" #include "MetaDataConfig.hpp" #include @@ -18,8 +19,7 @@ bool Constructor::ShouldCompile() const bool Constructor::isAccessible() const { - return m_accessModifier == CX_CXXPublic && - !m_metaData.GetFlag(kMetaDisable); + return m_accessModifier == CX_CXXPublic && !m_metaData.GetFlag(kMetaDisable); } std::string Constructor::getTemplateParameters() const diff --git a/tools/codegen/Parser/LanguageTypes/Constructor.hpp b/tools/codegen/Parser/LanguageTypes/Constructor.hpp index 8b26af45c..7467a0cb2 100644 --- a/tools/codegen/Parser/LanguageTypes/Constructor.hpp +++ b/tools/codegen/Parser/LanguageTypes/Constructor.hpp @@ -1,9 +1,11 @@ #pragma once -#include "LanguageType.hpp" #include "Invokable.hpp" +#include "LanguageType.hpp" -class Constructor final : public LanguageType, public Invokable +class Constructor final + : public LanguageType + , public Invokable { public: Constructor(Cursor const & cursor, Namespace const & currentNamespace, class Class * parent); diff --git a/tools/codegen/Parser/LanguageTypes/Field.cpp b/tools/codegen/Parser/LanguageTypes/Field.cpp index eccd5c9db..14efeb8c0 100644 --- a/tools/codegen/Parser/LanguageTypes/Field.cpp +++ b/tools/codegen/Parser/LanguageTypes/Field.cpp @@ -1,9 +1,8 @@ -#include "Cursor.hpp" - -#include "MetaDataConfig.hpp" +#include "LanguageTypes/Field.hpp" +#include "Cursor.hpp" #include "LanguageTypes/Class.hpp" -#include "LanguageTypes/Field.hpp" +#include "MetaDataConfig.hpp" Field::Field(Cursor const & cursor, Namespace const & currentNamespace) : LanguageType(cursor, currentNamespace) @@ -26,7 +25,6 @@ bool Field::isAccessible() const { bool const metaFlag = (m_accessModifier == CX_CXXPublic && !m_metaData.GetFlag(kMetaDisable)); return m_hasExplicitGetter || m_hasExplicitSetter || metaFlag; - } bool Field::isGetterAccessible() const @@ -54,10 +52,8 @@ void Field::GenarateInitCode(std::stringstream & outCode) const { if (m_metaData.HasProperty(Props::Keynode)) { - GenerateResolveKeynodeCode(m_metaData.GetNativeString(Props::Keynode), - m_displayName, - GetForceType(m_metaData), - outCode); + GenerateResolveKeynodeCode( + m_metaData.GetNativeString(Props::Keynode), m_displayName, GetForceType(m_metaData), outCode); } } diff --git a/tools/codegen/Parser/LanguageTypes/Field.hpp b/tools/codegen/Parser/LanguageTypes/Field.hpp index 0bce5232e..58e486990 100644 --- a/tools/codegen/Parser/LanguageTypes/Field.hpp +++ b/tools/codegen/Parser/LanguageTypes/Field.hpp @@ -15,8 +15,11 @@ class Field final : public LanguageType static std::string GetForceType(MetaDataManager const & metaData); - static void GenerateResolveKeynodeCode(std::string const & sysIdtf, std::string const & displayName, - std::string const & forceType, std::stringstream & outCode); + static void GenerateResolveKeynodeCode( + std::string const & sysIdtf, + std::string const & displayName, + std::string const & forceType, + std::stringstream & outCode); std::string const & GetDisplayName() const; diff --git a/tools/codegen/Parser/LanguageTypes/Function.cpp b/tools/codegen/Parser/LanguageTypes/Function.cpp index 9cc1da1de..2b92ff799 100644 --- a/tools/codegen/Parser/LanguageTypes/Function.cpp +++ b/tools/codegen/Parser/LanguageTypes/Function.cpp @@ -1,10 +1,10 @@ -#include "Cursor.hpp" - #include "LanguageTypes/Function.hpp" + +#include "Cursor.hpp" #include "LanguageTypes/Class.hpp" -#include #include +#include Function::Function(Cursor const & cursor, Namespace const & currentNamespace) : LanguageType(cursor, currentNamespace) diff --git a/tools/codegen/Parser/LanguageTypes/Function.hpp b/tools/codegen/Parser/LanguageTypes/Function.hpp index c29dff647..a3bf9417e 100644 --- a/tools/codegen/Parser/LanguageTypes/Function.hpp +++ b/tools/codegen/Parser/LanguageTypes/Function.hpp @@ -1,9 +1,11 @@ #pragma once -#include "LanguageType.hpp" #include "Invokable.hpp" +#include "LanguageType.hpp" -class Function final : public LanguageType, public Invokable +class Function final + : public LanguageType + , public Invokable { public: Function(Cursor const & cursor, Namespace const & currentNamespace); diff --git a/tools/codegen/Parser/LanguageTypes/Global.cpp b/tools/codegen/Parser/LanguageTypes/Global.cpp index e9ab13be0..f834b5cd0 100644 --- a/tools/codegen/Parser/LanguageTypes/Global.cpp +++ b/tools/codegen/Parser/LanguageTypes/Global.cpp @@ -1,11 +1,10 @@ -#include "Cursor.hpp" - -#include "MetaDataConfig.hpp" -#include "MetaUtils.hpp" - #include "LanguageTypes/Global.hpp" + +#include "Cursor.hpp" #include "LanguageTypes/Class.hpp" #include "LanguageTypes/Field.hpp" +#include "MetaDataConfig.hpp" +#include "MetaUtils.hpp" Global::Global(Cursor const & cursor, Namespace const & currentNamespace, Class * parent) : LanguageType(cursor, currentNamespace) @@ -30,14 +29,11 @@ bool Global::ShouldCompile() const void Global::GenerateInitCode(std::stringstream & outCode) const { - /// TODO: merge with field code generation if (m_metaData.HasProperty(Props::Keynode)) { - Field::GenerateResolveKeynodeCode(m_metaData.GetNativeString(Props::Keynode), - m_displayName, - Field::GetForceType(m_metaData), - outCode); + Field::GenerateResolveKeynodeCode( + m_metaData.GetNativeString(Props::Keynode), m_displayName, Field::GetForceType(m_metaData), outCode); } } diff --git a/tools/codegen/Parser/LanguageTypes/Global.hpp b/tools/codegen/Parser/LanguageTypes/Global.hpp index 8bacb008e..bf75ab96e 100644 --- a/tools/codegen/Parser/LanguageTypes/Global.hpp +++ b/tools/codegen/Parser/LanguageTypes/Global.hpp @@ -28,6 +28,4 @@ class Global final : public LanguageType std::string m_displayName; std::string m_qualifiedName; std::string m_type; - - }; diff --git a/tools/codegen/Parser/LanguageTypes/Invokable.cpp b/tools/codegen/Parser/LanguageTypes/Invokable.cpp index ecf0f16f1..320e6bb48 100644 --- a/tools/codegen/Parser/LanguageTypes/Invokable.cpp +++ b/tools/codegen/Parser/LanguageTypes/Invokable.cpp @@ -1,7 +1,7 @@ -#include "Cursor.hpp" - #include "LanguageTypes/Invokable.hpp" +#include "Cursor.hpp" + #include Invokable::Invokable(Cursor const & cursor) diff --git a/tools/codegen/Parser/LanguageTypes/LanguageType.cpp b/tools/codegen/Parser/LanguageTypes/LanguageType.cpp index 72237b3d5..78e0064dd 100644 --- a/tools/codegen/Parser/LanguageTypes/LanguageType.cpp +++ b/tools/codegen/Parser/LanguageTypes/LanguageType.cpp @@ -1,7 +1,7 @@ #include "LanguageType.hpp" -#include "MetaDataConfig.hpp" #include "Cursor.hpp" +#include "MetaDataConfig.hpp" LanguageType::LanguageType(Cursor const & cursor, Namespace const & currentNamespace) : m_metaData(cursor) diff --git a/tools/codegen/Parser/LanguageTypes/Method.cpp b/tools/codegen/Parser/LanguageTypes/Method.cpp index 09576b72e..108d95eb2 100644 --- a/tools/codegen/Parser/LanguageTypes/Method.cpp +++ b/tools/codegen/Parser/LanguageTypes/Method.cpp @@ -1,7 +1,7 @@ -#include "LanguageTypes/Class.hpp" #include "LanguageTypes/Method.hpp" #include "Cursor.hpp" +#include "LanguageTypes/Class.hpp" Method::Method(Cursor const & cursor, Namespace const & currentNamespace) : LanguageType(cursor, currentNamespace) diff --git a/tools/codegen/Parser/LanguageTypes/Method.hpp b/tools/codegen/Parser/LanguageTypes/Method.hpp index ec0f7c1ed..8e70e8bab 100644 --- a/tools/codegen/Parser/LanguageTypes/Method.hpp +++ b/tools/codegen/Parser/LanguageTypes/Method.hpp @@ -1,9 +1,11 @@ #pragma once -#include "LanguageType.hpp" #include "Invokable.hpp" +#include "LanguageType.hpp" -class Method final : public LanguageType, public Invokable +class Method final + : public LanguageType + , public Invokable { public: Method(Cursor const & cursor, Namespace const & currentNamespace); diff --git a/tools/codegen/Parser/MacrosManager.cpp b/tools/codegen/Parser/MacrosManager.cpp index 4433c88c1..1b6b905ab 100644 --- a/tools/codegen/Parser/MacrosManager.cpp +++ b/tools/codegen/Parser/MacrosManager.cpp @@ -4,12 +4,10 @@ MacrosManager::MacrosManager() { - } MacrosManager::~MacrosManager() { - } bool MacrosManager::AddMacros(MacrosInfo const & inMacros) @@ -40,7 +38,7 @@ bool MacrosManager::FindMacros(size_t line, std::string const & fileName, Macros count += classMacros.IsValid() ? 1 : 0; count += propertyMacros.IsValid() ? 1 : 0; - if (count > 1) // invalid state + if (count > 1) // invalid state { std::cout << "More that one SC_... macros used at line " << line << " in " << fileName << std::endl; } @@ -66,7 +64,11 @@ void MacrosManager::Clear() m_macrosStorage = MacrosTypedMap(); } -bool MacrosManager::FindMacrosInternal(MacrosInfo::Type type, size_t line, std::string const & fileName, MacrosInfo & outResult) const +bool MacrosManager::FindMacrosInternal( + MacrosInfo::Type type, + size_t line, + std::string const & fileName, + MacrosInfo & outResult) const { MacrosTypedMap::const_iterator itTyped = m_macrosStorage.find(type); if (itTyped != m_macrosStorage.end()) diff --git a/tools/codegen/Parser/MacrosManager.hpp b/tools/codegen/Parser/MacrosManager.hpp index 18959c52c..dd5d1f459 100644 --- a/tools/codegen/Parser/MacrosManager.hpp +++ b/tools/codegen/Parser/MacrosManager.hpp @@ -20,10 +20,14 @@ struct MacrosInfo , m_line(0) , m_column(0) { - } - MacrosInfo(std::string const & name, std::string const & code, size_t line, size_t column, std::string const & filename) + MacrosInfo( + std::string const & name, + std::string const & code, + size_t line, + size_t column, + std::string const & filename) : m_name(name) , m_code(code) , m_line(line) @@ -53,11 +57,10 @@ struct MacrosInfo return (m_type != MT_NONE); } - bool operator == (MacrosInfo const & other) const + bool operator==(MacrosInfo const & other) const { - return (m_name == other.m_name) && (m_fileName == other.m_fileName) - && (m_line == other.m_line) && (m_column == other.m_column) - && (m_type == other.m_type); + return (m_name == other.m_name) && (m_fileName == other.m_fileName) && (m_line == other.m_line) && + (m_column == other.m_column) && (m_type == other.m_type); } static bool RequestProcess(std::string const & name) @@ -65,7 +68,6 @@ struct MacrosInfo return (name == "SC_CLASS") || (name == "SC_PROPERTY") || (name == "SC_GENERATED_BODY"); } - std::string m_name; std::string m_code; Type m_type; @@ -88,11 +90,12 @@ class MacrosManager void Clear(); private: - bool FindMacrosInternal(MacrosInfo::Type type, size_t line, std::string const & fileName, MacrosInfo & outResult) const; + bool FindMacrosInternal(MacrosInfo::Type type, size_t line, std::string const & fileName, MacrosInfo & outResult) + const; private: - using MacrosLineMap = std::map< size_t, MacrosInfo>; - using MacrosTypedMap = std::map< MacrosInfo::Type, MacrosLineMap>; + using MacrosLineMap = std::map; + using MacrosTypedMap = std::map; MacrosTypedMap m_macrosStorage; }; diff --git a/tools/codegen/Parser/Main.cpp b/tools/codegen/Parser/Main.cpp index b3689dff3..8564860e1 100644 --- a/tools/codegen/Parser/Main.cpp +++ b/tools/codegen/Parser/Main.cpp @@ -1,14 +1,13 @@ +#include "MetaUtils.hpp" #include "ReflectionOptions.hpp" #include "ReflectionParser.hpp" -#include "MetaUtils.hpp" +#include #include #include #include -#include - void parse(std::string const & appName, boost::program_options::variables_map const & cmdLine) { ReflectionOptions options; @@ -23,15 +22,12 @@ void parse(std::string const & appName, boost::program_options::variables_map co // default arguments options.arguments = { - { - "-x", - "c++", - "-D__SC_REFLECTION_PARSER__", - "-std=c++17", - "-Wno-pragma-once-outside-header", - "-Wno-nullability-completeness" - } - }; + {"-x", + "c++", + "-D__SC_REFLECTION_PARSER__", + "-std=c++17", + "-Wno-pragma-once-outside-header", + "-Wno-nullability-completeness"}}; if (cmdLine.count("flags")) { @@ -71,7 +67,7 @@ void parse(std::string const & appName, boost::program_options::variables_map co } } -int main(int argc, char *argv[]) +int main(int argc, char * argv[]) { auto start = std::chrono::system_clock::now(); @@ -80,46 +76,18 @@ int main(int argc, char *argv[]) { boost::program_options::options_description program("SC Reflection Parser"); - program.add_options() - ( - "help,h", - "Displays help information." - ) - ( - "target,t", - boost::program_options::value()->required(), - "Input target project name." - ) - ( - "source,i", - boost::program_options::value()->required(), - "Source path to parse headers in." - ) - ( - "output,o", - boost::program_options::value()->required(), - "Output path for generated headers." - ) - ( - "build_dir,b", - boost::program_options::value()->default_value("./build"), - "Directory that contains the build intermediate files." - ) - ( - "flags,f", - boost::program_options::value>()->multitoken()->required(), - "Optional list of flags to pass to the compiler." - ) - ( - "debug,d", - boost::program_options::value()->implicit_value(false), - "Display compiler errors" - ) - ( - "cache,c", - boost::program_options::value()->implicit_value(false), - "Force cache usage" - ); + program.add_options()("help,h", "Displays help information.")( + "target,t", boost::program_options::value()->required(), "Input target project name.")( + "source,i", boost::program_options::value()->required(), "Source path to parse headers in.")( + "output,o", boost::program_options::value()->required(), "Output path for generated headers.")( + "build_dir,b", + boost::program_options::value()->default_value("./build"), + "Directory that contains the build intermediate files.")( + "flags,f", + boost::program_options::value>()->multitoken()->required(), + "Optional list of flags to pass to the compiler.")( + "debug,d", boost::program_options::value()->implicit_value(false), "Display compiler errors")( + "cache,c", boost::program_options::value()->implicit_value(false), "Force cache usage"); boost::program_options::variables_map cmdLine; @@ -137,7 +105,7 @@ int main(int argc, char *argv[]) std::string const appName = argv[0]; parse(appName, cmdLine); } - catch (std::exception &e) + catch (std::exception & e) { utils::FatalError(e.what()); } @@ -148,10 +116,8 @@ int main(int argc, char *argv[]) auto duration = std::chrono::system_clock::now() - start; - std::cout << "Completed in " - << std::chrono::duration_cast(duration).count() - << "ms" << std::endl; + std::cout << "Completed in " << std::chrono::duration_cast(duration).count() << "ms" + << std::endl; return EXIT_SUCCESS; } - diff --git a/tools/codegen/Parser/MetaDataManager.cpp b/tools/codegen/Parser/MetaDataManager.cpp index b675e3357..e241b8ae6 100644 --- a/tools/codegen/Parser/MetaDataManager.cpp +++ b/tools/codegen/Parser/MetaDataManager.cpp @@ -1,4 +1,5 @@ #include "MetaDataManager.hpp" + #include "ReflectionParser.hpp" #include @@ -7,13 +8,13 @@ MetaDataManager::MetaDataManager(Cursor const & cursor) { m_lineNumber = cursor.GetLineNumber() - 1; - for (auto &child : cursor.GetChildren()) + for (auto & child : cursor.GetChildren()) { if (child.GetKind() != CXCursor_AnnotateAttr) continue; auto const props = ExtractProperties(child); - for (auto &prop : props) + for (auto & prop : props) m_properties[prop.first] = prop.second; } } @@ -75,14 +76,14 @@ std::string MetaDataManager::GetNativeString(std::string const & key) const return ""; static const std::regex quotedString( - // opening quote - "(?:\\s*\")" - // actual string contents - "([^\"]*)" - // closing quote - "\""); + // opening quote + "(?:\\s*\")" + // actual string contents + "([^\"]*)" + // closing quote + "\""); - std::smatch match; + std::smatch match; if (std::regex_match(search->second, match, quotedString)) { @@ -99,23 +100,22 @@ std::vector MetaDataManager::ExtractProperties(Cursor std::vector properties; static const std::regex propertyList( - // property name - "([a-zA-Z\\:]+)" - // optional whitespace before - "(?:\\s*)" - // constructor - "(" - // opening paren - "\\(" - // arguments - "([^\\)]*)" - // closing paren - "\\)" - // end constructor - ")?" - // optional comma/whitespace - "(?:(\\s|,)*)" - ); + // property name + "([a-zA-Z\\:]+)" + // optional whitespace before + "(?:\\s*)" + // constructor + "(" + // opening paren + "\\(" + // arguments + "([^\\)]*)" + // closing paren + "\\)" + // end constructor + ")?" + // optional comma/whitespace + "(?:(\\s|,)*)"); auto const meta = cursor.GetDisplayName(); auto start = meta.cbegin(); @@ -178,7 +178,5 @@ void MetaDataManager::Check() const { EMIT_ERROR_LINE("Don't use empty " << Props::AgentCommandClass); } - } - } diff --git a/tools/codegen/Parser/MetaDataManager.hpp b/tools/codegen/Parser/MetaDataManager.hpp index 78dfdf4e4..0f04eba76 100644 --- a/tools/codegen/Parser/MetaDataManager.hpp +++ b/tools/codegen/Parser/MetaDataManager.hpp @@ -35,5 +35,4 @@ class MetaDataManager private: std::unordered_map m_properties; size_t m_lineNumber; - }; diff --git a/tools/codegen/Parser/MetaUtils.cpp b/tools/codegen/Parser/MetaUtils.cpp index 889195f14..ba9b3f945 100644 --- a/tools/codegen/Parser/MetaUtils.cpp +++ b/tools/codegen/Parser/MetaUtils.cpp @@ -4,14 +4,13 @@ #include "CursorType.hpp" #include "Types.hpp" -#include - #include +#include + namespace utils { - -void ToString(const CXString &str, std::string &output) +void ToString(const CXString & str, std::string & output) { auto cstr = clang_getCString(str); @@ -32,16 +31,16 @@ std::string GetQualifiedName(const std::string & displayName, const Namespace & return name; } -std::string GetQualifiedName(const Cursor &cursor, const Namespace ¤tNamespace) +std::string GetQualifiedName(const Cursor & cursor, const Namespace & currentNamespace) { return GetQualifiedName(cursor.GetSpelling(), currentNamespace); } -void FatalError(const std::string &error) +void FatalError(const std::string & error) { std::cerr << "Error: " << error << std::endl; exit(EXIT_FAILURE); } -} // namespace utils +} // namespace utils diff --git a/tools/codegen/Parser/MetaUtils.hpp b/tools/codegen/Parser/MetaUtils.hpp index 260122f5d..091641338 100644 --- a/tools/codegen/Parser/MetaUtils.hpp +++ b/tools/codegen/Parser/MetaUtils.hpp @@ -7,11 +7,11 @@ class Cursor; namespace utils { -void ToString(const CXString &str, std::string &output); +void ToString(const CXString & str, std::string & output); std::string GetQualifiedName(std::string const & displayName, Namespace const & currentNamespace); std::string GetQualifiedName(Cursor const & cursor, Namespace const & currentNamespace); -void FatalError(const std::string &error); -} +void FatalError(const std::string & error); +} // namespace utils diff --git a/tools/codegen/Parser/ReflectionParser.cpp b/tools/codegen/Parser/ReflectionParser.cpp index fa2c8e1c1..dfdf3dbd6 100644 --- a/tools/codegen/Parser/ReflectionParser.cpp +++ b/tools/codegen/Parser/ReflectionParser.cpp @@ -1,11 +1,11 @@ #include "ReflectionParser.hpp" -#include -#include - #include #include +#include +#include + #define RECURSE_NAMESPACES(kind, cursor, method, ns) \ if (kind == CXCursor_Namespace) \ { \ @@ -20,8 +20,7 @@ namespace impl { - -void displayDiagnostics (CXTranslationUnit tu) +void displayDiagnostics(CXTranslationUnit tu) { if (tu == 0) { @@ -32,18 +31,18 @@ void displayDiagnostics (CXTranslationUnit tu) int const numDiagnostics = clang_getNumDiagnostics(tu); for (int i = 0; i < numDiagnostics; ++i) { - auto const diagnostic = clang_getDiagnostic (tu, i); - auto const string = clang_formatDiagnostic (diagnostic, clang_defaultDiagnosticDisplayOptions()); + auto const diagnostic = clang_getDiagnostic(tu, i); + auto const string = clang_formatDiagnostic(diagnostic, clang_defaultDiagnosticDisplayOptions()); - std::cerr << clang_getCString (string) << std::endl; - clang_disposeString (string); - clang_disposeDiagnostic (diagnostic); + std::cerr << clang_getCString(string) << std::endl; + clang_disposeString(string); + clang_disposeDiagnostic(diagnostic); } } -} // namespace impl +} // namespace impl -ReflectionParser::ReflectionParser(const ReflectionOptions &options) +ReflectionParser::ReflectionParser(const ReflectionOptions & options) : m_options(options) , m_index(nullptr) , m_translationUnit(nullptr) @@ -148,7 +147,6 @@ void ReflectionParser::Parse() m_sourceCache->Save(); } - void ReflectionParser::Clear() { m_currentFile = ""; @@ -173,7 +171,7 @@ bool ReflectionParser::ProcessFile(std::string const & fileName, bool inProcessM std::vector arguments; - for (auto &argument : m_options.arguments) + for (auto & argument : m_options.arguments) { // unescape flags boost::algorithm::replace_all(argument, "\\-", "-"); @@ -181,13 +179,7 @@ bool ReflectionParser::ProcessFile(std::string const & fileName, bool inProcessM } m_translationUnit = clang_createTranslationUnitFromSourceFile( - m_index, - fileName.c_str(), - static_cast(arguments.size()), - arguments.data(), - 0, - nullptr - ); + m_index, fileName.c_str(), static_cast(arguments.size()), arguments.data(), 0, nullptr); if (m_options.displayDiagnostic) impl::displayDiagnostics(m_translationUnit); @@ -240,7 +232,6 @@ bool ReflectionParser::ProcessFile(std::string const & fileName, bool inProcessM clang_disposeIndex(m_index); clang_disposeTranslationUnit(m_translationUnit); - } catch (Exception e) { @@ -250,7 +241,6 @@ bool ReflectionParser::ProcessFile(std::string const & fileName, bool inProcessM EMIT_ERROR(e.GetDescription()); } - return true; } @@ -287,9 +277,9 @@ bool ReflectionParser::ContainsModule() const return false; } -void ReflectionParser::buildClasses(const Cursor &cursor, Namespace ¤tNamespace) +void ReflectionParser::buildClasses(const Cursor & cursor, Namespace & currentNamespace) { - for (auto &child : cursor.GetChildren()) + for (auto & child : cursor.GetChildren()) { // skip classes from other files if (!IsInCurrentFile(child)) @@ -305,7 +295,6 @@ void ReflectionParser::buildClasses(const Cursor &cursor, Namespace ¤tName } } - void ReflectionParser::DumpTree(Cursor const & cursor, size_t level, std::stringstream & outData) { outData << "\n"; @@ -314,13 +303,13 @@ void ReflectionParser::DumpTree(Cursor const & cursor, size_t level, std::string outData << cursor.GetDisplayName() << ", " << cursor.GetKind(); - for (auto &child : cursor.GetChildren()) + for (auto & child : cursor.GetChildren()) { DumpTree(child, level + 1, outData); } } -//void ReflectionParser::buildGlobals(const Cursor &cursor, Namespace ¤tNamespace) +// void ReflectionParser::buildGlobals(const Cursor &cursor, Namespace ¤tNamespace) //{ // for (auto &child : cursor.GetChildren()) // { @@ -342,7 +331,7 @@ void ReflectionParser::DumpTree(Cursor const & cursor, size_t level, std::string // } //} // -//void ReflectionParser::buildGlobalFunctions(const Cursor &cursor, Namespace ¤tNamespace) +// void ReflectionParser::buildGlobalFunctions(const Cursor &cursor, Namespace ¤tNamespace) //{ // for (auto &child : cursor.GetChildren()) // { @@ -367,7 +356,7 @@ void ReflectionParser::DumpTree(Cursor const & cursor, size_t level, std::string // } //} // -//void ReflectionParser::buildEnums(const Cursor &cursor, Namespace ¤tNamespace) +// void ReflectionParser::buildEnums(const Cursor &cursor, Namespace ¤tNamespace) //{ // for (auto &child : cursor.GetChildren()) // { @@ -428,4 +417,3 @@ std::string ReflectionParser::GetFileID(std::string const & fileName) return res; } - diff --git a/tools/codegen/Parser/ReflectionParser.hpp b/tools/codegen/Parser/ReflectionParser.hpp index e306b25a9..0d03213d4 100644 --- a/tools/codegen/Parser/ReflectionParser.hpp +++ b/tools/codegen/Parser/ReflectionParser.hpp @@ -1,20 +1,16 @@ #pragma once -#include "ReflectionOptions.hpp" - -#include "Cursor.hpp" - -#include "MacrosManager.hpp" #include "Cache.hpp" - +#include "Cursor.hpp" #include "LanguageTypes/Class.hpp" -#include "LanguageTypes/Global.hpp" #include "LanguageTypes/Function.hpp" +#include "LanguageTypes/Global.hpp" +#include "MacrosManager.hpp" +#include "ReflectionOptions.hpp" class ReflectionParser final { public: - explicit ReflectionParser(ReflectionOptions const & options); void Parse(); diff --git a/tools/codegen/Parser/ReservedTypes.hpp b/tools/codegen/Parser/ReservedTypes.hpp index b55689a7b..efe03e92e 100644 --- a/tools/codegen/Parser/ReservedTypes.hpp +++ b/tools/codegen/Parser/ReservedTypes.hpp @@ -4,7 +4,6 @@ namespace Props { - const std::string Body = "GenBody"; const std::string Keynode = "Keynode"; const std::string ForceCreate = "ForceCreate"; @@ -13,21 +12,19 @@ const std::string AgentCommandClass = "CmdClass"; const std::string Event = "Event"; const std::string LoadOrder = "LoadOrder"; -} // namespace Props +} // namespace Props namespace Classes { - const std::string Object = "ScObject"; const std::string Agent = "ScAgent"; const std::string AgentAction = "ScAgentAction"; const std::string Module = "ScModule"; -} // namespace Classes +} // namespace Classes namespace ParserMeta { - const std::string ParentClass = "ParentClass"; -} // namespace ParserMeta +} // namespace ParserMeta diff --git a/tools/codegen/Parser/Sha256.cpp b/tools/codegen/Parser/Sha256.cpp index 4711136ff..fb672a083 100644 --- a/tools/codegen/Parser/Sha256.cpp +++ b/tools/codegen/Parser/Sha256.cpp @@ -3,46 +3,42 @@ #include #include -const unsigned int SHA256::sha256_k[64] = //UL = uint32 -{ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, -0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, -0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, -0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, -0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, -0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, -0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, -0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, -0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, -0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, -0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, -0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, -0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, -0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, -0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, -0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; +const unsigned int SHA256::sha256_k[64] = // UL = uint32 + {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; -void SHA256::transform(const unsigned char *message, unsigned int block_nb) +void SHA256::transform(const unsigned char * message, unsigned int block_nb) { uint32 w[64]; uint32 wv[8]; uint32 t1, t2; - const unsigned char *sub_block; + const unsigned char * sub_block; int i; int j; - for (i = 0; i < (int)block_nb; i++) { + for (i = 0; i < (int)block_nb; i++) + { sub_block = message + (i << 6); - for (j = 0; j < 16; j++) { + for (j = 0; j < 16; j++) + { SHA2_PACK32(&sub_block[j << 2], &w[j]); } - for (j = 16; j < 64; j++) { + for (j = 16; j < 64; j++) + { w[j] = SHA256_F4(w[j - 2]) + w[j - 7] + SHA256_F3(w[j - 15]) + w[j - 16]; } - for (j = 0; j < 8; j++) { + for (j = 0; j < 8; j++) + { wv[j] = m_h[j]; } - for (j = 0; j < 64; j++) { - t1 = wv[7] + SHA256_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha256_k[j] + w[j]; + for (j = 0; j < 64; j++) + { + t1 = wv[7] + SHA256_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) + sha256_k[j] + w[j]; t2 = SHA256_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); wv[7] = wv[6]; wv[6] = wv[5]; @@ -53,7 +49,8 @@ void SHA256::transform(const unsigned char *message, unsigned int block_nb) wv[1] = wv[0]; wv[0] = t1 + t2; } - for (j = 0; j < 8; j++) { + for (j = 0; j < 8; j++) + { m_h[j] += wv[j]; } } @@ -73,15 +70,16 @@ void SHA256::init() m_tot_len = 0; } -void SHA256::update(const unsigned char *message, unsigned int len) +void SHA256::update(const unsigned char * message, unsigned int len) { unsigned int block_nb; unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; + const unsigned char * shifted_message; tmp_len = SHA224_256_BLOCK_SIZE - m_len; rem_len = len < tmp_len ? len : tmp_len; memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA224_256_BLOCK_SIZE) { + if (m_len + len < SHA224_256_BLOCK_SIZE) + { m_len += len; return; } @@ -96,21 +94,21 @@ void SHA256::update(const unsigned char *message, unsigned int len) m_tot_len += (block_nb + 1) << 6; } -void SHA256::final(unsigned char *digest) +void SHA256::final(unsigned char * digest) { unsigned int block_nb; unsigned int pm_len; unsigned int len_b; int i; - block_nb = (1 + ((SHA224_256_BLOCK_SIZE - 9) - < (m_len % SHA224_256_BLOCK_SIZE))); + block_nb = (1 + ((SHA224_256_BLOCK_SIZE - 9) < (m_len % SHA224_256_BLOCK_SIZE))); len_b = (m_tot_len + m_len) << 3; pm_len = block_nb << 6; memset(m_block + m_len, 0, pm_len - m_len); m_block[m_len] = 0x80; SHA2_UNPACK32(len_b, m_block + pm_len - 4); transform(m_block, block_nb); - for (i = 0; i < 8; i++) { + for (i = 0; i < 8; i++) + { SHA2_UNPACK32(m_h[i], &digest[i << 2]); } } @@ -122,12 +120,12 @@ std::string sha256(std::string input) SHA256 ctx = SHA256(); ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); + ctx.update((unsigned char *)input.c_str(), input.length()); ctx.final(digest); char buf[2 * SHA256::DIGEST_SIZE + 1]; buf[2 * SHA256::DIGEST_SIZE] = 0; - for (size_t i = 0; i < SHA256::DIGEST_SIZE; i++) + for (size_t i = 0; i < SHA256::DIGEST_SIZE; i++) sprintf(buf + i * 2, "%02x", digest[i]); return std::string(buf); } diff --git a/tools/codegen/Parser/Sha256.hpp b/tools/codegen/Parser/Sha256.hpp index d4a0e40a7..0fe2c3f56 100644 --- a/tools/codegen/Parser/Sha256.hpp +++ b/tools/codegen/Parser/Sha256.hpp @@ -1,89 +1,88 @@ #pragma once /* -* Updated to C++, zedwood.com 2012 -* Based on Olivier Gay's version -* See Modified BSD License below: -* -* FIPS 180-2 SHA-224/256/384/512 implementation -* Issue date: 04/30/2005 -* http://www.ouah.org/ogay/sha2/ -* -* Copyright (C) 2005, 2007 Olivier Gay -* 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 project 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 PROJECT 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 PROJECT 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. -*/ + * Updated to C++, zedwood.com 2012 + * Based on Olivier Gay's version + * See Modified BSD License below: + * + * FIPS 180-2 SHA-224/256/384/512 implementation + * Issue date: 04/30/2005 + * http://www.ouah.org/ogay/sha2/ + * + * Copyright (C) 2005, 2007 Olivier Gay + * 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 project 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 PROJECT 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 PROJECT 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 class SHA256 { protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; + typedef unsigned char uint8; + typedef unsigned int uint32; + typedef unsigned long long uint64; + + const static uint32 sha256_k[]; + static const unsigned int SHA224_256_BLOCK_SIZE = (512 / 8); - const static uint32 sha256_k[]; - static const unsigned int SHA224_256_BLOCK_SIZE = (512 / 8); public: - void init(); - void update(const unsigned char *message, unsigned int len); - void final(unsigned char *digest); - static const unsigned int DIGEST_SIZE = (256 / 8); + void init(); + void update(const unsigned char * message, unsigned int len); + void final(unsigned char * digest); + static const unsigned int DIGEST_SIZE = (256 / 8); protected: - void transform(const unsigned char *message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA224_256_BLOCK_SIZE]; - uint32 m_h[8]; + void transform(const unsigned char * message, unsigned int block_nb); + unsigned int m_tot_len; + unsigned int m_len; + unsigned char m_block[2 * SHA224_256_BLOCK_SIZE]; + uint32 m_h[8]; }; std::string sha256(std::string input); -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) +#define SHA2_SHFR(x, n) (x >> n) +#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) +#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) +#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) #define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA256_F1(x) (SHA2_ROTR(x, 2) ^ SHA2_ROTR(x, 13) ^ SHA2_ROTR(x, 22)) -#define SHA256_F2(x) (SHA2_ROTR(x, 6) ^ SHA2_ROTR(x, 11) ^ SHA2_ROTR(x, 25)) -#define SHA256_F3(x) (SHA2_ROTR(x, 7) ^ SHA2_ROTR(x, 18) ^ SHA2_SHFR(x, 3)) +#define SHA256_F1(x) (SHA2_ROTR(x, 2) ^ SHA2_ROTR(x, 13) ^ SHA2_ROTR(x, 22)) +#define SHA256_F2(x) (SHA2_ROTR(x, 6) ^ SHA2_ROTR(x, 11) ^ SHA2_ROTR(x, 25)) +#define SHA256_F3(x) (SHA2_ROTR(x, 7) ^ SHA2_ROTR(x, 18) ^ SHA2_SHFR(x, 3)) #define SHA256_F4(x) (SHA2_ROTR(x, 17) ^ SHA2_ROTR(x, 19) ^ SHA2_SHFR(x, 10)) -#define SHA2_UNPACK32(x, str) \ -{ \ - *((str) + 3) = (uint8) ((x) ); \ - *((str) + 2) = (uint8) ((x) >> 8); \ - *((str) + 1) = (uint8) ((x) >> 16); \ - *((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_PACK32(str, x) \ -{ \ - *(x) = ((uint32) *((str) + 3) ) \ - | ((uint32) *((str) + 2) << 8) \ - | ((uint32) *((str) + 1) << 16) \ - | ((uint32) *((str) + 0) << 24); \ -} +#define SHA2_UNPACK32(x, str) \ + { \ + *((str) + 3) = (uint8)((x)); \ + *((str) + 2) = (uint8)((x) >> 8); \ + *((str) + 1) = (uint8)((x) >> 16); \ + *((str) + 0) = (uint8)((x) >> 24); \ + } +#define SHA2_PACK32(str, x) \ + { \ + *(x) = ((uint32) * ((str) + 3)) | ((uint32) * ((str) + 2) << 8) | ((uint32) * ((str) + 1) << 16) | \ + ((uint32) * ((str) + 0) << 24); \ + } diff --git a/tools/codegen/Parser/Types.hpp b/tools/codegen/Parser/Types.hpp index d6e4755cb..ebc66c332 100644 --- a/tools/codegen/Parser/Types.hpp +++ b/tools/codegen/Parser/Types.hpp @@ -1,16 +1,16 @@ #pragma once +#include "ReservedTypes.hpp" + #include -#include #include #include #include - -#include "ReservedTypes.hpp" +#include using Namespace = std::vector; -class Exception final: public std::exception +class Exception final : public std::exception { public: Exception(std::string const & descr) @@ -22,13 +22,18 @@ class Exception final: public std::exception { return m_description; } + private: std::string m_description; }; #ifndef EMIT_ERROR -#define EMIT_ERROR(__desc) \ -{ std::stringstream ss; ss << __desc; throw Exception(ss.str()); } +# define EMIT_ERROR(__desc) \ + { \ + std::stringstream ss; \ + ss << __desc; \ + throw Exception(ss.str()); \ + } #endif typedef std::list tStringList;